mirror of
https://github.com/PurpleI2P/i2pd.git
synced 2025-04-27 11:17:49 +02:00
restructure build to separate the 3 main components into 3 subdirectories
libi2pd for core libs libi2pd_client for i2pd client libs daemon for i2pd daemon libs
This commit is contained in:
parent
b3161dde93
commit
4cc3b7f9fb
140 changed files with 209 additions and 206 deletions
871
libi2pd_client/AddressBook.cpp
Normal file
871
libi2pd_client/AddressBook.cpp
Normal file
|
@ -0,0 +1,871 @@
|
|||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <fstream>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <openssl/rand.h>
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include "Base.h"
|
||||
#include "util.h"
|
||||
#include "Identity.h"
|
||||
#include "FS.h"
|
||||
#include "Log.h"
|
||||
#include "HTTP.h"
|
||||
#include "NetDb.h"
|
||||
#include "ClientContext.h"
|
||||
#include "AddressBook.h"
|
||||
#include "Config.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
// TODO: this is actually proxy class
|
||||
class AddressBookFilesystemStorage: public AddressBookStorage
|
||||
{
|
||||
private:
|
||||
i2p::fs::HashedStorage storage;
|
||||
std::string etagsPath, indexPath, localPath;
|
||||
|
||||
public:
|
||||
AddressBookFilesystemStorage (): storage("addressbook", "b", "", "b32") {};
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) const;
|
||||
void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address);
|
||||
void RemoveAddress (const i2p::data::IdentHash& ident);
|
||||
|
||||
bool Init ();
|
||||
int Load (std::map<std::string, i2p::data::IdentHash>& addresses);
|
||||
int LoadLocal (std::map<std::string, i2p::data::IdentHash>& addresses);
|
||||
int Save (const std::map<std::string, i2p::data::IdentHash>& addresses);
|
||||
|
||||
void SaveEtag (const i2p::data::IdentHash& subsciption, const std::string& etag, const std::string& lastModified);
|
||||
bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified);
|
||||
|
||||
private:
|
||||
|
||||
int LoadFromFile (const std::string& filename, std::map<std::string, i2p::data::IdentHash>& addresses); // returns -1 if can't open file, otherwise number of records
|
||||
|
||||
};
|
||||
|
||||
bool AddressBookFilesystemStorage::Init()
|
||||
{
|
||||
storage.SetPlace(i2p::fs::GetDataDir());
|
||||
// init storage
|
||||
if (storage.Init(i2p::data::GetBase32SubstitutionTable(), 32))
|
||||
{
|
||||
// init ETags
|
||||
etagsPath = i2p::fs::StorageRootPath (storage, "etags");
|
||||
if (!i2p::fs::Exists (etagsPath))
|
||||
i2p::fs::CreateDirectory (etagsPath);
|
||||
// init address files
|
||||
indexPath = i2p::fs::StorageRootPath (storage, "addresses.csv");
|
||||
localPath = i2p::fs::StorageRootPath (storage, "local.csv");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::shared_ptr<const i2p::data::IdentityEx> AddressBookFilesystemStorage::GetAddress (const i2p::data::IdentHash& ident) const
|
||||
{
|
||||
std::string filename = storage.Path(ident.ToBase32());
|
||||
std::ifstream f(filename, std::ifstream::binary);
|
||||
if (!f.is_open ()) {
|
||||
LogPrint(eLogDebug, "Addressbook: Requested, but not found: ", filename);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
f.seekg (0,std::ios::end);
|
||||
size_t len = f.tellg ();
|
||||
if (len < i2p::data::DEFAULT_IDENTITY_SIZE) {
|
||||
LogPrint (eLogError, "Addressbook: File ", filename, " is too short: ", len);
|
||||
return nullptr;
|
||||
}
|
||||
f.seekg(0, std::ios::beg);
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
f.read((char *)buf, len);
|
||||
auto address = std::make_shared<i2p::data::IdentityEx>(buf, len);
|
||||
delete[] buf;
|
||||
return address;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address)
|
||||
{
|
||||
std::string path = storage.Path( address->GetIdentHash().ToBase32() );
|
||||
std::ofstream f (path, std::ofstream::binary | std::ofstream::out);
|
||||
if (!f.is_open ()) {
|
||||
LogPrint (eLogError, "Addressbook: can't open file ", path);
|
||||
return;
|
||||
}
|
||||
size_t len = address->GetFullLen ();
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
address->ToBuffer (buf, len);
|
||||
f.write ((char *)buf, len);
|
||||
delete[] buf;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::RemoveAddress (const i2p::data::IdentHash& ident)
|
||||
{
|
||||
storage.Remove( ident.ToBase32() );
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::LoadFromFile (const std::string& filename, std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
int num = 0;
|
||||
std::ifstream f (filename, std::ifstream::in); // in text mode
|
||||
if (!f) return -1;
|
||||
|
||||
addresses.clear ();
|
||||
while (!f.eof ())
|
||||
{
|
||||
std::string s;
|
||||
getline(f, s);
|
||||
if (!s.length()) continue; // skip empty line
|
||||
|
||||
std::size_t pos = s.find(',');
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
std::string name = s.substr(0, pos++);
|
||||
std::string addr = s.substr(pos);
|
||||
|
||||
i2p::data::IdentHash ident;
|
||||
ident.FromBase32 (addr);
|
||||
addresses[name] = ident;
|
||||
num++;
|
||||
}
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Load (std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
int num = LoadFromFile (indexPath, addresses);
|
||||
if (num < 0)
|
||||
{
|
||||
LogPrint(eLogWarning, "Addressbook: Can't open ", indexPath);
|
||||
return 0;
|
||||
}
|
||||
LogPrint(eLogInfo, "Addressbook: using index file ", indexPath);
|
||||
LogPrint (eLogInfo, "Addressbook: ", num, " addresses loaded from storage");
|
||||
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::LoadLocal (std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
int num = LoadFromFile (localPath, addresses);
|
||||
if (num < 0) return 0;
|
||||
LogPrint (eLogInfo, "Addressbook: ", num, " local addresses loaded");
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Save (const std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
if (addresses.empty()) {
|
||||
LogPrint(eLogWarning, "Addressbook: not saving empty addressbook");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int num = 0;
|
||||
std::ofstream f (indexPath, std::ofstream::out); // in text mode
|
||||
|
||||
if (!f.is_open ()) {
|
||||
LogPrint (eLogWarning, "Addressbook: Can't open ", indexPath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const auto& it: addresses) {
|
||||
f << it.first << "," << it.second.ToBase32 () << std::endl;
|
||||
num++;
|
||||
}
|
||||
LogPrint (eLogInfo, "Addressbook: ", num, " addresses saved");
|
||||
return num;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::SaveEtag (const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified)
|
||||
{
|
||||
std::string fname = etagsPath + i2p::fs::dirSep + subscription.ToBase32 () + ".txt";
|
||||
std::ofstream f (fname, std::ofstream::out | std::ofstream::trunc);
|
||||
if (f)
|
||||
{
|
||||
f << etag << std::endl;
|
||||
f<< lastModified << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
bool AddressBookFilesystemStorage::GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified)
|
||||
{
|
||||
std::string fname = etagsPath + i2p::fs::dirSep + subscription.ToBase32 () + ".txt";
|
||||
std::ifstream f (fname, std::ofstream::in);
|
||||
if (!f || f.eof ()) return false;
|
||||
std::getline (f, etag);
|
||||
if (f.eof ()) return false;
|
||||
std::getline (f, lastModified);
|
||||
return true;
|
||||
}
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
AddressBook::AddressBook (): m_Storage(nullptr), m_IsLoaded (false), m_IsDownloading (false),
|
||||
m_DefaultSubscription (nullptr), m_SubscriptionsUpdateTimer (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
AddressBook::~AddressBook ()
|
||||
{
|
||||
Stop ();
|
||||
}
|
||||
|
||||
void AddressBook::Start ()
|
||||
{
|
||||
if (!m_Storage)
|
||||
m_Storage = new AddressBookFilesystemStorage;
|
||||
m_Storage->Init();
|
||||
LoadHosts (); /* try storage, then hosts.txt, then download */
|
||||
StartSubscriptions ();
|
||||
StartLookups ();
|
||||
}
|
||||
|
||||
void AddressBook::StartResolvers ()
|
||||
{
|
||||
LoadLocal ();
|
||||
}
|
||||
|
||||
void AddressBook::Stop ()
|
||||
{
|
||||
StopLookups ();
|
||||
StopSubscriptions ();
|
||||
if (m_SubscriptionsUpdateTimer)
|
||||
{
|
||||
delete m_SubscriptionsUpdateTimer;
|
||||
m_SubscriptionsUpdateTimer = nullptr;
|
||||
}
|
||||
if (m_IsDownloading)
|
||||
{
|
||||
LogPrint (eLogInfo, "Addressbook: subscriptions is downloading, abort");
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
if (!m_IsDownloading)
|
||||
{
|
||||
LogPrint (eLogInfo, "Addressbook: subscriptions download complete");
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for (std::chrono::seconds (1)); // wait for 1 seconds
|
||||
}
|
||||
LogPrint (eLogError, "Addressbook: subscription download timeout");
|
||||
m_IsDownloading = false;
|
||||
}
|
||||
if (m_Storage)
|
||||
{
|
||||
m_Storage->Save (m_Addresses);
|
||||
delete m_Storage;
|
||||
m_Storage = nullptr;
|
||||
}
|
||||
m_DefaultSubscription = nullptr;
|
||||
m_Subscriptions.clear ();
|
||||
}
|
||||
|
||||
bool AddressBook::GetIdentHash (const std::string& address, i2p::data::IdentHash& ident)
|
||||
{
|
||||
auto pos = address.find(".b32.i2p");
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
Base32ToByteStream (address.c_str(), pos, ident, 32);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
pos = address.find (".i2p");
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
auto identHash = FindAddress (address);
|
||||
if (identHash)
|
||||
{
|
||||
ident = *identHash;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LookupAddress (address); // TODO:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// if not .b32 we assume full base64 address
|
||||
i2p::data::IdentityEx dest;
|
||||
if (!dest.FromBase64 (address))
|
||||
return false;
|
||||
ident = dest.GetIdentHash ();
|
||||
return true;
|
||||
}
|
||||
|
||||
const i2p::data::IdentHash * AddressBook::FindAddress (const std::string& address)
|
||||
{
|
||||
auto it = m_Addresses.find (address);
|
||||
if (it != m_Addresses.end ())
|
||||
return &it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void AddressBook::InsertAddress (const std::string& address, const std::string& base64)
|
||||
{
|
||||
auto ident = std::make_shared<i2p::data::IdentityEx>();
|
||||
ident->FromBase64 (base64);
|
||||
m_Storage->AddAddress (ident);
|
||||
m_Addresses[address] = ident->GetIdentHash ();
|
||||
LogPrint (eLogInfo, "Addressbook: added ", address," -> ", ToAddress(ident->GetIdentHash ()));
|
||||
}
|
||||
|
||||
void AddressBook::InsertAddress (std::shared_ptr<const i2p::data::IdentityEx> address)
|
||||
{
|
||||
m_Storage->AddAddress (address);
|
||||
}
|
||||
|
||||
std::shared_ptr<const i2p::data::IdentityEx> AddressBook::GetAddress (const std::string& address)
|
||||
{
|
||||
i2p::data::IdentHash ident;
|
||||
if (!GetIdentHash (address, ident)) return nullptr;
|
||||
return m_Storage->GetAddress (ident);
|
||||
}
|
||||
|
||||
void AddressBook::LoadHosts ()
|
||||
{
|
||||
if (m_Storage->Load (m_Addresses) > 0)
|
||||
{
|
||||
m_IsLoaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// then try hosts.txt
|
||||
std::ifstream f (i2p::fs::DataDirPath("hosts.txt"), std::ifstream::in); // in text mode
|
||||
if (f.is_open ())
|
||||
{
|
||||
LoadHostsFromStream (f, false);
|
||||
m_IsLoaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool AddressBook::LoadHostsFromStream (std::istream& f, bool is_update)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_AddressBookMutex);
|
||||
int numAddresses = 0;
|
||||
bool incomplete = false;
|
||||
std::string s;
|
||||
while (!f.eof ())
|
||||
{
|
||||
getline(f, s);
|
||||
|
||||
if (!s.length())
|
||||
continue; // skip empty line
|
||||
|
||||
size_t pos = s.find('=');
|
||||
|
||||
if (pos != std::string::npos)
|
||||
{
|
||||
std::string name = s.substr(0, pos++);
|
||||
std::string addr = s.substr(pos);
|
||||
|
||||
auto ident = std::make_shared<i2p::data::IdentityEx> ();
|
||||
if (!ident->FromBase64(addr)) {
|
||||
LogPrint (eLogError, "Addressbook: malformed address ", addr, " for ", name);
|
||||
incomplete = f.eof ();
|
||||
continue;
|
||||
}
|
||||
numAddresses++;
|
||||
if (m_Addresses.count(name) > 0)
|
||||
continue; /* already exists */
|
||||
m_Addresses[name] = ident->GetIdentHash ();
|
||||
m_Storage->AddAddress (ident);
|
||||
if (is_update)
|
||||
LogPrint(eLogInfo, "Addressbook: added new host: ", name);
|
||||
}
|
||||
else
|
||||
incomplete = f.eof ();
|
||||
}
|
||||
LogPrint (eLogInfo, "Addressbook: ", numAddresses, " addresses processed");
|
||||
if (numAddresses > 0)
|
||||
{
|
||||
if (!incomplete) m_IsLoaded = true;
|
||||
m_Storage->Save (m_Addresses);
|
||||
}
|
||||
return !incomplete;
|
||||
}
|
||||
|
||||
void AddressBook::LoadSubscriptions ()
|
||||
{
|
||||
if (!m_Subscriptions.size ())
|
||||
{
|
||||
std::ifstream f (i2p::fs::DataDirPath ("subscriptions.txt"), std::ifstream::in); // in text mode
|
||||
if (f.is_open ())
|
||||
{
|
||||
std::string s;
|
||||
while (!f.eof ())
|
||||
{
|
||||
getline(f, s);
|
||||
if (!s.length()) continue; // skip empty line
|
||||
m_Subscriptions.push_back (std::make_shared<AddressBookSubscription> (*this, s));
|
||||
}
|
||||
LogPrint (eLogInfo, "Addressbook: ", m_Subscriptions.size (), " subscriptions urls loaded");
|
||||
LogPrint (eLogWarning, "Addressbook: subscriptions.txt usage is deprecated, use config file instead");
|
||||
}
|
||||
else if (!i2p::config::IsDefault("addressbook.subscriptions"))
|
||||
{
|
||||
// using config file items
|
||||
std::string subscriptionURLs; i2p::config::GetOption("addressbook.subscriptions", subscriptionURLs);
|
||||
std::vector<std::string> subsList;
|
||||
boost::split(subsList, subscriptionURLs, boost::is_any_of(","), boost::token_compress_on);
|
||||
|
||||
for (size_t i = 0; i < subsList.size (); i++)
|
||||
{
|
||||
m_Subscriptions.push_back (std::make_shared<AddressBookSubscription> (*this, subsList[i]));
|
||||
}
|
||||
LogPrint (eLogInfo, "Addressbook: ", m_Subscriptions.size (), " subscriptions urls loaded");
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Addressbook: subscriptions already loaded");
|
||||
}
|
||||
|
||||
void AddressBook::LoadLocal ()
|
||||
{
|
||||
std::map<std::string, i2p::data::IdentHash> localAddresses;
|
||||
m_Storage->LoadLocal (localAddresses);
|
||||
for (const auto& it: localAddresses)
|
||||
{
|
||||
auto dot = it.first.find ('.');
|
||||
if (dot != std::string::npos)
|
||||
{
|
||||
auto domain = it.first.substr (dot + 1);
|
||||
auto it1 = m_Addresses.find (domain); // find domain in our addressbook
|
||||
if (it1 != m_Addresses.end ())
|
||||
{
|
||||
auto dest = context.FindLocalDestination (it1->second);
|
||||
if (dest)
|
||||
{
|
||||
// address is ours
|
||||
std::shared_ptr<AddressResolver> resolver;
|
||||
auto it2 = m_Resolvers.find (it1->second);
|
||||
if (it2 != m_Resolvers.end ())
|
||||
resolver = it2->second; // resolver exists
|
||||
else
|
||||
{
|
||||
// create new resolver
|
||||
resolver = std::make_shared<AddressResolver>(dest);
|
||||
m_Resolvers.insert (std::make_pair(it1->second, resolver));
|
||||
}
|
||||
resolver->AddAddress (it.first, it.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool AddressBook::GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified)
|
||||
{
|
||||
if (m_Storage)
|
||||
return m_Storage->GetEtag (subscription, etag, lastModified);
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void AddressBook::DownloadComplete (bool success, const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified)
|
||||
{
|
||||
m_IsDownloading = false;
|
||||
int nextUpdateTimeout = CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT;
|
||||
if (success)
|
||||
{
|
||||
if (m_DefaultSubscription) m_DefaultSubscription = nullptr;
|
||||
if (m_IsLoaded)
|
||||
nextUpdateTimeout = CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT;
|
||||
else
|
||||
m_IsLoaded = true;
|
||||
if (m_Storage) m_Storage->SaveEtag (subscription, etag, lastModified);
|
||||
}
|
||||
if (m_SubscriptionsUpdateTimer)
|
||||
{
|
||||
m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(nextUpdateTimeout));
|
||||
m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::StartSubscriptions ()
|
||||
{
|
||||
LoadSubscriptions ();
|
||||
if (m_IsLoaded && m_Subscriptions.empty ()) return;
|
||||
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (dest)
|
||||
{
|
||||
m_SubscriptionsUpdateTimer = new boost::asio::deadline_timer (dest->GetService ());
|
||||
m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT));
|
||||
m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Addressbook: can't start subscriptions: missing shared local destination");
|
||||
}
|
||||
|
||||
void AddressBook::StopSubscriptions ()
|
||||
{
|
||||
if (m_SubscriptionsUpdateTimer)
|
||||
m_SubscriptionsUpdateTimer->cancel ();
|
||||
}
|
||||
|
||||
void AddressBook::HandleSubscriptionsUpdateTimer (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (!dest) {
|
||||
LogPrint(eLogWarning, "Addressbook: missing local destination, skip subscription update");
|
||||
return;
|
||||
}
|
||||
if (!m_IsDownloading && dest->IsReady ())
|
||||
{
|
||||
if (!m_IsLoaded)
|
||||
{
|
||||
// download it from default subscription
|
||||
LogPrint (eLogInfo, "Addressbook: trying to download it from default subscription.");
|
||||
std::string defaultSubURL; i2p::config::GetOption("addressbook.defaulturl", defaultSubURL);
|
||||
if (!m_DefaultSubscription)
|
||||
m_DefaultSubscription = std::make_shared<AddressBookSubscription>(*this, defaultSubURL);
|
||||
m_IsDownloading = true;
|
||||
std::thread load_hosts(std::bind (&AddressBookSubscription::CheckUpdates, m_DefaultSubscription));
|
||||
load_hosts.detach(); // TODO: use join
|
||||
}
|
||||
else if (!m_Subscriptions.empty ())
|
||||
{
|
||||
// pick random subscription
|
||||
auto ind = rand () % m_Subscriptions.size();
|
||||
m_IsDownloading = true;
|
||||
std::thread load_hosts(std::bind (&AddressBookSubscription::CheckUpdates, m_Subscriptions[ind]));
|
||||
load_hosts.detach(); // TODO: use join
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// try it again later
|
||||
m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(INITIAL_SUBSCRIPTION_RETRY_TIMEOUT));
|
||||
m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::StartLookups ()
|
||||
{
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (dest)
|
||||
{
|
||||
auto datagram = dest->GetDatagramDestination ();
|
||||
if (!datagram)
|
||||
datagram = dest->CreateDatagramDestination ();
|
||||
datagram->SetReceiver (std::bind (&AddressBook::HandleLookupResponse, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5),
|
||||
ADDRESS_RESPONSE_DATAGRAM_PORT);
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::StopLookups ()
|
||||
{
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (dest)
|
||||
{
|
||||
auto datagram = dest->GetDatagramDestination ();
|
||||
if (datagram) datagram->ResetReceiver (ADDRESS_RESPONSE_DATAGRAM_PORT);
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::LookupAddress (const std::string& address)
|
||||
{
|
||||
const i2p::data::IdentHash * ident = nullptr;
|
||||
auto dot = address.find ('.');
|
||||
if (dot != std::string::npos)
|
||||
ident = FindAddress (address.substr (dot + 1));
|
||||
if (!ident)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Can't find domain for ", address);
|
||||
return;
|
||||
}
|
||||
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (dest)
|
||||
{
|
||||
auto datagram = dest->GetDatagramDestination ();
|
||||
if (datagram)
|
||||
{
|
||||
uint32_t nonce;
|
||||
RAND_bytes ((uint8_t *)&nonce, 4);
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_LookupsMutex);
|
||||
m_Lookups[nonce] = address;
|
||||
}
|
||||
LogPrint (eLogDebug, "Addressbook: Lookup of ", address, " to ", ident->ToBase32 (), " nonce=", nonce);
|
||||
size_t len = address.length () + 9;
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
memset (buf, 0, 4);
|
||||
htobe32buf (buf + 4, nonce);
|
||||
buf[8] = address.length ();
|
||||
memcpy (buf + 9, address.c_str (), address.length ());
|
||||
datagram->SendDatagramTo (buf, len, *ident, ADDRESS_RESPONSE_DATAGRAM_PORT, ADDRESS_RESOLVER_DATAGRAM_PORT);
|
||||
delete[] buf;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::HandleLookupResponse (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (len < 44)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Lookup response is too short ", len);
|
||||
return;
|
||||
}
|
||||
uint32_t nonce = bufbe32toh (buf + 4);
|
||||
LogPrint (eLogDebug, "Addressbook: Lookup response received from ", from.GetIdentHash ().ToBase32 (), " nonce=", nonce);
|
||||
std::string address;
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_LookupsMutex);
|
||||
auto it = m_Lookups.find (nonce);
|
||||
if (it != m_Lookups.end ())
|
||||
{
|
||||
address = it->second;
|
||||
m_Lookups.erase (it);
|
||||
}
|
||||
}
|
||||
if (address.length () > 0)
|
||||
{
|
||||
// TODO: verify from
|
||||
i2p::data::IdentHash hash(buf + 8);
|
||||
if (!hash.IsZero ())
|
||||
m_Addresses[address] = hash;
|
||||
else
|
||||
LogPrint (eLogInfo, "AddressBook: Lookup response: ", address, " not found");
|
||||
}
|
||||
}
|
||||
|
||||
AddressBookSubscription::AddressBookSubscription (AddressBook& book, const std::string& link):
|
||||
m_Book (book), m_Link (link)
|
||||
{
|
||||
}
|
||||
|
||||
void AddressBookSubscription::CheckUpdates ()
|
||||
{
|
||||
bool result = MakeRequest ();
|
||||
m_Book.DownloadComplete (result, m_Ident, m_Etag, m_LastModified);
|
||||
}
|
||||
|
||||
bool AddressBookSubscription::MakeRequest ()
|
||||
{
|
||||
i2p::http::URL url;
|
||||
// must be run in separate thread
|
||||
LogPrint (eLogInfo, "Addressbook: Downloading hosts database from ", m_Link);
|
||||
if (!url.parse(m_Link)) {
|
||||
LogPrint(eLogError, "Addressbook: failed to parse url: ", m_Link);
|
||||
return false;
|
||||
}
|
||||
if (!m_Book.GetIdentHash (url.host, m_Ident)) {
|
||||
LogPrint (eLogError, "Addressbook: Can't resolve ", url.host);
|
||||
return false;
|
||||
}
|
||||
/* this code block still needs some love */
|
||||
std::condition_variable newDataReceived;
|
||||
std::mutex newDataReceivedMutex;
|
||||
auto leaseSet = i2p::client::context.GetSharedLocalDestination ()->FindLeaseSet (m_Ident);
|
||||
if (!leaseSet)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(newDataReceivedMutex);
|
||||
i2p::client::context.GetSharedLocalDestination ()->RequestDestination (m_Ident,
|
||||
[&newDataReceived, &leaseSet, &newDataReceivedMutex](std::shared_ptr<i2p::data::LeaseSet> ls)
|
||||
{
|
||||
leaseSet = ls;
|
||||
std::unique_lock<std::mutex> l1(newDataReceivedMutex);
|
||||
newDataReceived.notify_all ();
|
||||
});
|
||||
if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Subscription LeaseSet request timeout expired");
|
||||
i2p::client::context.GetSharedLocalDestination ()->CancelDestinationRequest (m_Ident, false); // don't notify, because we know it already
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!leaseSet) {
|
||||
/* still no leaseset found */
|
||||
LogPrint (eLogError, "Addressbook: LeaseSet for address ", url.host, " not found");
|
||||
return false;
|
||||
}
|
||||
if (m_Etag.empty() && m_LastModified.empty()) {
|
||||
m_Book.GetEtag (m_Ident, m_Etag, m_LastModified);
|
||||
LogPrint (eLogDebug, "Addressbook: loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified);
|
||||
}
|
||||
/* save url parts for later use */
|
||||
std::string dest_host = url.host;
|
||||
int dest_port = url.port ? url.port : 80;
|
||||
/* create http request & send it */
|
||||
i2p::http::HTTPReq req;
|
||||
req.AddHeader("Host", dest_host);
|
||||
req.AddHeader("User-Agent", "Wget/1.11.4");
|
||||
req.AddHeader("X-Accept-Encoding", "x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n");
|
||||
req.AddHeader("Connection", "close");
|
||||
if (!m_Etag.empty())
|
||||
req.AddHeader("If-None-Match", m_Etag);
|
||||
if (!m_LastModified.empty())
|
||||
req.AddHeader("If-Modified-Since", m_LastModified);
|
||||
/* convert url to relative */
|
||||
url.schema = "";
|
||||
url.host = "";
|
||||
req.uri = url.to_string();
|
||||
auto stream = i2p::client::context.GetSharedLocalDestination ()->CreateStream (leaseSet, dest_port);
|
||||
std::string request = req.to_string();
|
||||
stream->Send ((const uint8_t *) request.data(), request.length());
|
||||
/* read response */
|
||||
std::string response;
|
||||
uint8_t recv_buf[4096];
|
||||
bool end = false;
|
||||
int numAttempts = 5;
|
||||
while (!end)
|
||||
{
|
||||
stream->AsyncReceive (boost::asio::buffer (recv_buf, 4096),
|
||||
[&](const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (bytes_transferred)
|
||||
response.append ((char *)recv_buf, bytes_transferred);
|
||||
if (ecode == boost::asio::error::timed_out || !stream->IsOpen ())
|
||||
end = true;
|
||||
newDataReceived.notify_all ();
|
||||
},
|
||||
30); // wait for 30 seconds
|
||||
std::unique_lock<std::mutex> l(newDataReceivedMutex);
|
||||
if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: subscriptions request timeout expired");
|
||||
numAttempts++;
|
||||
if (numAttempts > 5) end = true;
|
||||
}
|
||||
}
|
||||
// process remaining buffer
|
||||
while (size_t len = stream->ReadSome (recv_buf, sizeof(recv_buf)))
|
||||
response.append ((char *)recv_buf, len);
|
||||
/* parse response */
|
||||
i2p::http::HTTPRes res;
|
||||
int res_head_len = res.parse(response);
|
||||
if (res_head_len < 0)
|
||||
{
|
||||
LogPrint(eLogError, "Addressbook: can't parse http response from ", dest_host);
|
||||
return false;
|
||||
}
|
||||
if (res_head_len == 0)
|
||||
{
|
||||
LogPrint(eLogError, "Addressbook: incomplete http response from ", dest_host, ", interrupted by timeout");
|
||||
return false;
|
||||
}
|
||||
/* assert: res_head_len > 0 */
|
||||
response.erase(0, res_head_len);
|
||||
if (res.code == 304)
|
||||
{
|
||||
LogPrint (eLogInfo, "Addressbook: no updates from ", dest_host, ", code 304");
|
||||
return false;
|
||||
}
|
||||
if (res.code != 200)
|
||||
{
|
||||
LogPrint (eLogWarning, "Adressbook: can't get updates from ", dest_host, ", response code ", res.code);
|
||||
return false;
|
||||
}
|
||||
int len = res.content_length();
|
||||
if (response.empty())
|
||||
{
|
||||
LogPrint(eLogError, "Addressbook: empty response from ", dest_host, ", expected ", len, " bytes");
|
||||
return false;
|
||||
}
|
||||
if (!res.is_gzipped () && len > 0 && len != (int) response.length())
|
||||
{
|
||||
LogPrint(eLogError, "Addressbook: response size mismatch, expected: ", len, ", got: ", response.length(), "bytes");
|
||||
return false;
|
||||
}
|
||||
/* assert: res.code == 200 */
|
||||
auto it = res.headers.find("ETag");
|
||||
if (it != res.headers.end()) m_Etag = it->second;
|
||||
it = res.headers.find("If-Modified-Since");
|
||||
if (it != res.headers.end()) m_LastModified = it->second;
|
||||
if (res.is_chunked())
|
||||
{
|
||||
std::stringstream in(response), out;
|
||||
i2p::http::MergeChunkedResponse (in, out);
|
||||
response = out.str();
|
||||
}
|
||||
else if (res.is_gzipped())
|
||||
{
|
||||
std::stringstream out;
|
||||
i2p::data::GzipInflator inflator;
|
||||
inflator.Inflate ((const uint8_t *) response.data(), response.length(), out);
|
||||
if (out.fail())
|
||||
{
|
||||
LogPrint(eLogError, "Addressbook: can't gunzip http response");
|
||||
return false;
|
||||
}
|
||||
response = out.str();
|
||||
}
|
||||
std::stringstream ss(response);
|
||||
LogPrint (eLogInfo, "Addressbook: got update from ", dest_host);
|
||||
m_Book.LoadHostsFromStream (ss, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
AddressResolver::AddressResolver (std::shared_ptr<ClientDestination> destination):
|
||||
m_LocalDestination (destination)
|
||||
{
|
||||
if (m_LocalDestination)
|
||||
{
|
||||
auto datagram = m_LocalDestination->GetDatagramDestination ();
|
||||
if (!datagram)
|
||||
datagram = m_LocalDestination->CreateDatagramDestination ();
|
||||
datagram->SetReceiver (std::bind (&AddressResolver::HandleRequest, this,
|
||||
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5),
|
||||
ADDRESS_RESOLVER_DATAGRAM_PORT);
|
||||
}
|
||||
}
|
||||
|
||||
AddressResolver::~AddressResolver ()
|
||||
{
|
||||
if (m_LocalDestination)
|
||||
{
|
||||
auto datagram = m_LocalDestination->GetDatagramDestination ();
|
||||
if (datagram)
|
||||
datagram->ResetReceiver (ADDRESS_RESOLVER_DATAGRAM_PORT);
|
||||
}
|
||||
}
|
||||
|
||||
void AddressResolver::HandleRequest (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (len < 9 || len < buf[8] + 9U)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Address request is too short ", len);
|
||||
return;
|
||||
}
|
||||
// read requested address
|
||||
uint8_t l = buf[8];
|
||||
char address[255];
|
||||
memcpy (address, buf + 9, l);
|
||||
address[l] = 0;
|
||||
LogPrint (eLogDebug, "Addressbook: Address request ", address);
|
||||
// send response
|
||||
uint8_t response[44];
|
||||
memset (response, 0, 4); // reserved
|
||||
memcpy (response + 4, buf + 4, 4); // nonce
|
||||
auto it = m_LocalAddresses.find (address); // address lookup
|
||||
if (it != m_LocalAddresses.end ())
|
||||
memcpy (response + 8, it->second, 32); // ident
|
||||
else
|
||||
memset (response + 8, 0, 32); // not found
|
||||
memset (response + 40, 0, 4); // set expiration time to zero
|
||||
m_LocalDestination->GetDatagramDestination ()->SendDatagramTo (response, 44, from.GetIdentHash(), toPort, fromPort);
|
||||
}
|
||||
|
||||
void AddressResolver::AddAddress (const std::string& name, const i2p::data::IdentHash& ident)
|
||||
{
|
||||
m_LocalAddresses[name] = ident;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
146
libi2pd_client/AddressBook.h
Normal file
146
libi2pd_client/AddressBook.h
Normal file
|
@ -0,0 +1,146 @@
|
|||
#ifndef ADDRESS_BOOK_H__
|
||||
#define ADDRESS_BOOK_H__
|
||||
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Base.h"
|
||||
#include "Identity.h"
|
||||
#include "Log.h"
|
||||
#include "Destination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const int INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT = 3; // in minutes
|
||||
const int INITIAL_SUBSCRIPTION_RETRY_TIMEOUT = 1; // in minutes
|
||||
const int CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT = 720; // in minutes (12 hours)
|
||||
const int CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT = 5; // in minutes
|
||||
const int SUBSCRIPTION_REQUEST_TIMEOUT = 60; //in second
|
||||
|
||||
const uint16_t ADDRESS_RESOLVER_DATAGRAM_PORT = 53;
|
||||
const uint16_t ADDRESS_RESPONSE_DATAGRAM_PORT = 54;
|
||||
|
||||
inline std::string GetB32Address(const i2p::data::IdentHash& ident) { return ident.ToBase32().append(".b32.i2p"); }
|
||||
|
||||
class AddressBookStorage // interface for storage
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AddressBookStorage () {};
|
||||
virtual std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) const = 0;
|
||||
virtual void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address) = 0;
|
||||
virtual void RemoveAddress (const i2p::data::IdentHash& ident) = 0;
|
||||
|
||||
virtual bool Init () = 0;
|
||||
virtual int Load (std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
|
||||
virtual int LoadLocal (std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
|
||||
virtual int Save (const std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
|
||||
|
||||
virtual void SaveEtag (const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified) = 0;
|
||||
virtual bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified) = 0;
|
||||
};
|
||||
|
||||
class AddressBookSubscription;
|
||||
class AddressResolver;
|
||||
class AddressBook
|
||||
{
|
||||
public:
|
||||
|
||||
AddressBook ();
|
||||
~AddressBook ();
|
||||
void Start ();
|
||||
void StartResolvers ();
|
||||
void Stop ();
|
||||
bool GetIdentHash (const std::string& address, i2p::data::IdentHash& ident);
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const std::string& address);
|
||||
const i2p::data::IdentHash * FindAddress (const std::string& address);
|
||||
void LookupAddress (const std::string& address);
|
||||
void InsertAddress (const std::string& address, const std::string& base64); // for jump service
|
||||
void InsertAddress (std::shared_ptr<const i2p::data::IdentityEx> address);
|
||||
|
||||
bool LoadHostsFromStream (std::istream& f, bool is_update);
|
||||
void DownloadComplete (bool success, const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified);
|
||||
//This method returns the ".b32.i2p" address
|
||||
std::string ToAddress(const i2p::data::IdentHash& ident) { return GetB32Address(ident); }
|
||||
std::string ToAddress(std::shared_ptr<const i2p::data::IdentityEx> ident) { return ToAddress(ident->GetIdentHash ()); }
|
||||
|
||||
bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified);
|
||||
|
||||
private:
|
||||
|
||||
void StartSubscriptions ();
|
||||
void StopSubscriptions ();
|
||||
|
||||
void LoadHosts ();
|
||||
void LoadSubscriptions ();
|
||||
void LoadLocal ();
|
||||
|
||||
void HandleSubscriptionsUpdateTimer (const boost::system::error_code& ecode);
|
||||
|
||||
void StartLookups ();
|
||||
void StopLookups ();
|
||||
void HandleLookupResponse (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_AddressBookMutex;
|
||||
std::map<std::string, i2p::data::IdentHash> m_Addresses;
|
||||
std::map<i2p::data::IdentHash, std::shared_ptr<AddressResolver> > m_Resolvers; // local destination->resolver
|
||||
std::mutex m_LookupsMutex;
|
||||
std::map<uint32_t, std::string> m_Lookups; // nonce -> address
|
||||
AddressBookStorage * m_Storage;
|
||||
volatile bool m_IsLoaded, m_IsDownloading;
|
||||
std::vector<std::shared_ptr<AddressBookSubscription> > m_Subscriptions;
|
||||
std::shared_ptr<AddressBookSubscription> m_DefaultSubscription; // in case if we don't know any addresses yet
|
||||
boost::asio::deadline_timer * m_SubscriptionsUpdateTimer;
|
||||
};
|
||||
|
||||
class AddressBookSubscription
|
||||
{
|
||||
public:
|
||||
|
||||
AddressBookSubscription (AddressBook& book, const std::string& link);
|
||||
void CheckUpdates ();
|
||||
|
||||
private:
|
||||
|
||||
bool MakeRequest ();
|
||||
|
||||
private:
|
||||
|
||||
AddressBook& m_Book;
|
||||
std::string m_Link, m_Etag, m_LastModified;
|
||||
i2p::data::IdentHash m_Ident;
|
||||
// m_Etag must be surrounded by ""
|
||||
};
|
||||
|
||||
class AddressResolver
|
||||
{
|
||||
public:
|
||||
|
||||
AddressResolver (std::shared_ptr<ClientDestination> destination);
|
||||
~AddressResolver ();
|
||||
void AddAddress (const std::string& name, const i2p::data::IdentHash& ident);
|
||||
|
||||
private:
|
||||
|
||||
void HandleRequest (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<ClientDestination> m_LocalDestination;
|
||||
std::map<std::string, i2p::data::IdentHash> m_LocalAddresses;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
719
libi2pd_client/BOB.cpp
Normal file
719
libi2pd_client/BOB.cpp
Normal file
|
@ -0,0 +1,719 @@
|
|||
#include <string.h>
|
||||
#include "Log.h"
|
||||
#include "ClientContext.h"
|
||||
#include "util.h"
|
||||
#include "BOB.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
BOBI2PInboundTunnel::BOBI2PInboundTunnel (int port, std::shared_ptr<ClientDestination> localDestination):
|
||||
BOBI2PTunnel (localDestination),
|
||||
m_Acceptor (localDestination->GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port))
|
||||
{
|
||||
}
|
||||
|
||||
BOBI2PInboundTunnel::~BOBI2PInboundTunnel ()
|
||||
{
|
||||
Stop ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Start ()
|
||||
{
|
||||
m_Acceptor.listen ();
|
||||
Accept ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Stop ()
|
||||
{
|
||||
m_Acceptor.close();
|
||||
ClearHandlers ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Accept ()
|
||||
{
|
||||
auto receiver = std::make_shared<AddressReceiver> ();
|
||||
receiver->socket = std::make_shared<boost::asio::ip::tcp::socket> (GetService ());
|
||||
m_Acceptor.async_accept (*receiver->socket, std::bind (&BOBI2PInboundTunnel::HandleAccept, this,
|
||||
std::placeholders::_1, receiver));
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<AddressReceiver> receiver)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
Accept ();
|
||||
ReceiveAddress (receiver);
|
||||
}
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::ReceiveAddress (std::shared_ptr<AddressReceiver> receiver)
|
||||
{
|
||||
receiver->socket->async_read_some (boost::asio::buffer(
|
||||
receiver->buffer + receiver->bufferOffset,
|
||||
BOB_COMMAND_BUFFER_SIZE - receiver->bufferOffset),
|
||||
std::bind(&BOBI2PInboundTunnel::HandleReceivedAddress, this,
|
||||
std::placeholders::_1, std::placeholders::_2, receiver));
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::HandleReceivedAddress (const boost::system::error_code& ecode, std::size_t bytes_transferred,
|
||||
std::shared_ptr<AddressReceiver> receiver)
|
||||
{
|
||||
if (ecode)
|
||||
LogPrint (eLogError, "BOB: inbound tunnel read error: ", ecode.message ());
|
||||
else
|
||||
{
|
||||
receiver->bufferOffset += bytes_transferred;
|
||||
receiver->buffer[receiver->bufferOffset] = 0;
|
||||
char * eol = strchr (receiver->buffer, '\n');
|
||||
if (eol)
|
||||
{
|
||||
*eol = 0;
|
||||
if (eol != receiver->buffer && eol[-1] == '\r') eol[-1] = 0; // workaround for Transmission, it sends '\r\n' terminated address
|
||||
receiver->data = (uint8_t *)eol + 1;
|
||||
receiver->dataLen = receiver->bufferOffset - (eol - receiver->buffer + 1);
|
||||
i2p::data::IdentHash ident;
|
||||
if (!context.GetAddressBook ().GetIdentHash (receiver->buffer, ident))
|
||||
{
|
||||
LogPrint (eLogError, "BOB: address ", receiver->buffer, " not found");
|
||||
return;
|
||||
}
|
||||
auto leaseSet = GetLocalDestination ()->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
CreateConnection (receiver, leaseSet);
|
||||
else
|
||||
GetLocalDestination ()->RequestDestination (ident,
|
||||
std::bind (&BOBI2PInboundTunnel::HandleDestinationRequestComplete,
|
||||
this, std::placeholders::_1, receiver));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (receiver->bufferOffset < BOB_COMMAND_BUFFER_SIZE)
|
||||
ReceiveAddress (receiver);
|
||||
else
|
||||
LogPrint (eLogError, "BOB: missing inbound address");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::HandleDestinationRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet, std::shared_ptr<AddressReceiver> receiver)
|
||||
{
|
||||
if (leaseSet)
|
||||
CreateConnection (receiver, leaseSet);
|
||||
else
|
||||
LogPrint (eLogError, "BOB: LeaseSet for inbound destination not found");
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::CreateConnection (std::shared_ptr<AddressReceiver> receiver, std::shared_ptr<const i2p::data::LeaseSet> leaseSet)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: New inbound connection");
|
||||
auto connection = std::make_shared<I2PTunnelConnection>(this, receiver->socket, leaseSet);
|
||||
AddHandler (connection);
|
||||
connection->I2PConnect (receiver->data, receiver->dataLen);
|
||||
}
|
||||
|
||||
BOBI2POutboundTunnel::BOBI2POutboundTunnel (const std::string& address, int port,
|
||||
std::shared_ptr<ClientDestination> localDestination, bool quiet): BOBI2PTunnel (localDestination),
|
||||
m_Endpoint (boost::asio::ip::address::from_string (address), port), m_IsQuiet (quiet)
|
||||
{
|
||||
}
|
||||
|
||||
void BOBI2POutboundTunnel::Start ()
|
||||
{
|
||||
Accept ();
|
||||
}
|
||||
|
||||
void BOBI2POutboundTunnel::Stop ()
|
||||
{
|
||||
ClearHandlers ();
|
||||
}
|
||||
|
||||
void BOBI2POutboundTunnel::Accept ()
|
||||
{
|
||||
auto localDestination = GetLocalDestination ();
|
||||
if (localDestination)
|
||||
localDestination->AcceptStreams (std::bind (&BOBI2POutboundTunnel::HandleAccept, this, std::placeholders::_1));
|
||||
else
|
||||
LogPrint (eLogError, "BOB: Local destination not set for server tunnel");
|
||||
}
|
||||
|
||||
void BOBI2POutboundTunnel::HandleAccept (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
auto conn = std::make_shared<I2PTunnelConnection> (this, stream, std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), m_Endpoint, m_IsQuiet);
|
||||
AddHandler (conn);
|
||||
conn->Connect ();
|
||||
}
|
||||
}
|
||||
|
||||
BOBDestination::BOBDestination (std::shared_ptr<ClientDestination> localDestination):
|
||||
m_LocalDestination (localDestination),
|
||||
m_OutboundTunnel (nullptr), m_InboundTunnel (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
BOBDestination::~BOBDestination ()
|
||||
{
|
||||
delete m_OutboundTunnel;
|
||||
delete m_InboundTunnel;
|
||||
i2p::client::context.DeleteLocalDestination (m_LocalDestination);
|
||||
}
|
||||
|
||||
void BOBDestination::Start ()
|
||||
{
|
||||
if (m_OutboundTunnel) m_OutboundTunnel->Start ();
|
||||
if (m_InboundTunnel) m_InboundTunnel->Start ();
|
||||
}
|
||||
|
||||
void BOBDestination::Stop ()
|
||||
{
|
||||
StopTunnels ();
|
||||
m_LocalDestination->Stop ();
|
||||
}
|
||||
|
||||
void BOBDestination::StopTunnels ()
|
||||
{
|
||||
if (m_OutboundTunnel)
|
||||
{
|
||||
m_OutboundTunnel->Stop ();
|
||||
delete m_OutboundTunnel;
|
||||
m_OutboundTunnel = nullptr;
|
||||
}
|
||||
if (m_InboundTunnel)
|
||||
{
|
||||
m_InboundTunnel->Stop ();
|
||||
delete m_InboundTunnel;
|
||||
m_InboundTunnel = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void BOBDestination::CreateInboundTunnel (int port)
|
||||
{
|
||||
if (!m_InboundTunnel)
|
||||
m_InboundTunnel = new BOBI2PInboundTunnel (port, m_LocalDestination);
|
||||
}
|
||||
|
||||
void BOBDestination::CreateOutboundTunnel (const std::string& address, int port, bool quiet)
|
||||
{
|
||||
if (!m_OutboundTunnel)
|
||||
m_OutboundTunnel = new BOBI2POutboundTunnel (address, port, m_LocalDestination, quiet);
|
||||
}
|
||||
|
||||
BOBCommandSession::BOBCommandSession (BOBCommandChannel& owner):
|
||||
m_Owner (owner), m_Socket (m_Owner.GetService ()),
|
||||
m_ReceiveBufferOffset (0), m_IsOpen (true), m_IsQuiet (false), m_IsActive (false),
|
||||
m_InPort (0), m_OutPort (0), m_CurrentDestination (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
BOBCommandSession::~BOBCommandSession ()
|
||||
{
|
||||
}
|
||||
|
||||
void BOBCommandSession::Terminate ()
|
||||
{
|
||||
m_Socket.close ();
|
||||
m_IsOpen = false;
|
||||
}
|
||||
|
||||
void BOBCommandSession::Receive ()
|
||||
{
|
||||
m_Socket.async_read_some (boost::asio::buffer(m_ReceiveBuffer + m_ReceiveBufferOffset, BOB_COMMAND_BUFFER_SIZE - m_ReceiveBufferOffset),
|
||||
std::bind(&BOBCommandSession::HandleReceived, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void BOBCommandSession::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "BOB: command channel read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t size = m_ReceiveBufferOffset + bytes_transferred;
|
||||
m_ReceiveBuffer[size] = 0;
|
||||
char * eol = strchr (m_ReceiveBuffer, '\n');
|
||||
if (eol)
|
||||
{
|
||||
*eol = 0;
|
||||
char * operand = strchr (m_ReceiveBuffer, ' ');
|
||||
if (operand)
|
||||
{
|
||||
*operand = 0;
|
||||
operand++;
|
||||
}
|
||||
else
|
||||
operand = eol;
|
||||
// process command
|
||||
auto& handlers = m_Owner.GetCommandHandlers ();
|
||||
auto it = handlers.find (m_ReceiveBuffer);
|
||||
if (it != handlers.end ())
|
||||
(this->*(it->second))(operand, eol - operand);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "BOB: unknown command ", m_ReceiveBuffer);
|
||||
SendReplyError ("unknown command");
|
||||
}
|
||||
|
||||
m_ReceiveBufferOffset = size - (eol - m_ReceiveBuffer) - 1;
|
||||
memmove (m_ReceiveBuffer, eol + 1, m_ReceiveBufferOffset);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (size < BOB_COMMAND_BUFFER_SIZE)
|
||||
m_ReceiveBufferOffset = size;
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "BOB: Malformed input of the command channel");
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BOBCommandSession::Send (size_t len)
|
||||
{
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_SendBuffer, len),
|
||||
boost::asio::transfer_all (),
|
||||
std::bind(&BOBCommandSession::HandleSent, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void BOBCommandSession::HandleSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "BOB: command channel send error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_IsOpen)
|
||||
Receive ();
|
||||
else
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
|
||||
void BOBCommandSession::SendReplyOK (const char * msg)
|
||||
{
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_REPLY_OK, msg);
|
||||
#else
|
||||
size_t len = snprintf (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_REPLY_OK, msg);
|
||||
#endif
|
||||
Send (len);
|
||||
}
|
||||
|
||||
void BOBCommandSession::SendReplyError (const char * msg)
|
||||
{
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_REPLY_ERROR, msg);
|
||||
#else
|
||||
size_t len = snprintf (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_REPLY_ERROR, msg);
|
||||
#endif
|
||||
Send (len);
|
||||
}
|
||||
|
||||
void BOBCommandSession::SendVersion ()
|
||||
{
|
||||
size_t len = strlen (BOB_VERSION);
|
||||
memcpy (m_SendBuffer, BOB_VERSION, len);
|
||||
Send (len);
|
||||
}
|
||||
|
||||
void BOBCommandSession::SendData (const char * nickname)
|
||||
{
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_DATA, nickname);
|
||||
#else
|
||||
size_t len = snprintf (m_SendBuffer, BOB_COMMAND_BUFFER_SIZE, BOB_DATA, nickname);
|
||||
#endif
|
||||
Send (len);
|
||||
}
|
||||
|
||||
void BOBCommandSession::ZapCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: zap");
|
||||
Terminate ();
|
||||
}
|
||||
|
||||
void BOBCommandSession::QuitCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: quit");
|
||||
m_IsOpen = false;
|
||||
SendReplyOK ("Bye!");
|
||||
}
|
||||
|
||||
void BOBCommandSession::StartCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: start ", m_Nickname);
|
||||
if (m_IsActive)
|
||||
{
|
||||
SendReplyError ("tunnel is active");
|
||||
return;
|
||||
}
|
||||
if (!m_CurrentDestination)
|
||||
{
|
||||
m_CurrentDestination = new BOBDestination (i2p::client::context.CreateNewLocalDestination (m_Keys, true, &m_Options));
|
||||
m_Owner.AddDestination (m_Nickname, m_CurrentDestination);
|
||||
}
|
||||
if (m_InPort)
|
||||
m_CurrentDestination->CreateInboundTunnel (m_InPort);
|
||||
if (m_OutPort && !m_Address.empty ())
|
||||
m_CurrentDestination->CreateOutboundTunnel (m_Address, m_OutPort, m_IsQuiet);
|
||||
m_CurrentDestination->Start ();
|
||||
SendReplyOK ("Tunnel starting");
|
||||
m_IsActive = true;
|
||||
}
|
||||
|
||||
void BOBCommandSession::StopCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: stop ", m_Nickname);
|
||||
if (!m_IsActive)
|
||||
{
|
||||
SendReplyError ("tunnel is inactive");
|
||||
return;
|
||||
}
|
||||
auto dest = m_Owner.FindDestination (m_Nickname);
|
||||
if (dest)
|
||||
{
|
||||
dest->StopTunnels ();
|
||||
SendReplyOK ("Tunnel stopping");
|
||||
}
|
||||
else
|
||||
SendReplyError ("tunnel not found");
|
||||
m_IsActive = false;
|
||||
}
|
||||
|
||||
void BOBCommandSession::SetNickCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: setnick ", operand);
|
||||
m_Nickname = operand;
|
||||
std::string msg ("Nickname set to ");
|
||||
msg += m_Nickname;
|
||||
SendReplyOK (msg.c_str ());
|
||||
}
|
||||
|
||||
void BOBCommandSession::GetNickCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: getnick ", operand);
|
||||
m_CurrentDestination = m_Owner.FindDestination (operand);
|
||||
if (m_CurrentDestination)
|
||||
{
|
||||
m_Keys = m_CurrentDestination->GetKeys ();
|
||||
m_Nickname = operand;
|
||||
}
|
||||
if (m_Nickname == operand)
|
||||
{
|
||||
std::string msg ("Nickname set to ");
|
||||
msg += m_Nickname;
|
||||
SendReplyOK (msg.c_str ());
|
||||
}
|
||||
else
|
||||
SendReplyError ("no nickname has been set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::NewkeysCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: newkeys");
|
||||
m_Keys = i2p::data::PrivateKeys::CreateRandomKeys ();
|
||||
SendReplyOK (m_Keys.GetPublic ()->ToBase64 ().c_str ());
|
||||
}
|
||||
|
||||
void BOBCommandSession::SetkeysCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: setkeys ", operand);
|
||||
if (m_Keys.FromBase64 (operand))
|
||||
SendReplyOK (m_Keys.GetPublic ()->ToBase64 ().c_str ());
|
||||
else
|
||||
SendReplyError ("invalid keys");
|
||||
}
|
||||
|
||||
void BOBCommandSession::GetkeysCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: getkeys");
|
||||
if (m_Keys.GetPublic ()) // keys are set ?
|
||||
SendReplyOK (m_Keys.ToBase64 ().c_str ());
|
||||
else
|
||||
SendReplyError ("keys are not set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::GetdestCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: getdest");
|
||||
SendReplyOK (m_Keys.GetPublic ()->ToBase64 ().c_str ());
|
||||
}
|
||||
|
||||
void BOBCommandSession::OuthostCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: outhost ", operand);
|
||||
m_Address = operand;
|
||||
SendReplyOK ("outhost set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::OutportCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: outport ", operand);
|
||||
m_OutPort = std::stoi(operand);
|
||||
if (m_OutPort >= 0)
|
||||
SendReplyOK ("outbound port set");
|
||||
else
|
||||
SendReplyError ("port out of range");
|
||||
}
|
||||
|
||||
void BOBCommandSession::InhostCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: inhost ", operand);
|
||||
m_Address = operand;
|
||||
SendReplyOK ("inhost set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::InportCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: inport ", operand);
|
||||
m_InPort = std::stoi(operand);
|
||||
if (m_InPort >= 0)
|
||||
SendReplyOK ("inbound port set");
|
||||
else
|
||||
SendReplyError ("port out of range");
|
||||
}
|
||||
|
||||
void BOBCommandSession::QuietCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: quiet");
|
||||
if (m_Nickname.length () > 0)
|
||||
{
|
||||
if (!m_IsActive)
|
||||
{
|
||||
m_IsQuiet = true;
|
||||
SendReplyOK ("Quiet set");
|
||||
}
|
||||
else
|
||||
SendReplyError ("tunnel is active");
|
||||
}
|
||||
else
|
||||
SendReplyError ("no nickname has been set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::LookupCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: lookup ", operand);
|
||||
i2p::data::IdentHash ident;
|
||||
if (!context.GetAddressBook ().GetIdentHash (operand, ident))
|
||||
{
|
||||
SendReplyError ("Address Not found");
|
||||
return;
|
||||
}
|
||||
auto localDestination = m_CurrentDestination ? m_CurrentDestination->GetLocalDestination () : i2p::client::context.GetSharedLocalDestination ();
|
||||
auto leaseSet = localDestination->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
SendReplyOK (leaseSet->GetIdentity ()->ToBase64 ().c_str ());
|
||||
else
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
localDestination->RequestDestination (ident,
|
||||
[s](std::shared_ptr<i2p::data::LeaseSet> ls)
|
||||
{
|
||||
if (ls)
|
||||
s->SendReplyOK (ls->GetIdentity ()->ToBase64 ().c_str ());
|
||||
else
|
||||
s->SendReplyError ("LeaseSet Not found");
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void BOBCommandSession::ClearCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: clear");
|
||||
m_Owner.DeleteDestination (m_Nickname);
|
||||
m_Nickname = "";
|
||||
SendReplyOK ("cleared");
|
||||
}
|
||||
|
||||
void BOBCommandSession::ListCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: list");
|
||||
const auto& destinations = m_Owner.GetDestinations ();
|
||||
for (const auto& it: destinations)
|
||||
SendData (it.first.c_str ());
|
||||
SendReplyOK ("Listing done");
|
||||
}
|
||||
|
||||
void BOBCommandSession::OptionCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: option ", operand);
|
||||
const char * value = strchr (operand, '=');
|
||||
if (value)
|
||||
{
|
||||
std::string msg ("option ");
|
||||
*(const_cast<char *>(value)) = 0;
|
||||
m_Options[operand] = value + 1;
|
||||
msg += operand;
|
||||
*(const_cast<char *>(value)) = '=';
|
||||
msg += " set to ";
|
||||
msg += value;
|
||||
SendReplyOK (msg.c_str ());
|
||||
}
|
||||
else
|
||||
SendReplyError ("malformed");
|
||||
}
|
||||
|
||||
void BOBCommandSession::StatusCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: status ", operand);
|
||||
if (m_Nickname == operand)
|
||||
{
|
||||
std::stringstream s;
|
||||
s << "DATA"; s << " NICKNAME: "; s << m_Nickname;
|
||||
if (m_CurrentDestination)
|
||||
{
|
||||
if (m_CurrentDestination->GetLocalDestination ()->IsReady ())
|
||||
s << " STARTING: false RUNNING: true STOPPING: false";
|
||||
else
|
||||
s << " STARTING: true RUNNING: false STOPPING: false";
|
||||
}
|
||||
else
|
||||
s << " STARTING: false RUNNING: false STOPPING: false";
|
||||
s << " KEYS: true"; s << " QUIET: "; s << (m_IsQuiet ? "true":"false");
|
||||
if (m_InPort)
|
||||
{
|
||||
s << " INPORT: " << m_InPort;
|
||||
s << " INHOST: " << (m_Address.length () > 0 ? m_Address : "127.0.0.1");
|
||||
}
|
||||
if (m_OutPort)
|
||||
{
|
||||
s << " OUTPORT: " << m_OutPort;
|
||||
s << " OUTHOST: " << (m_Address.length () > 0 ? m_Address : "127.0.0.1");
|
||||
}
|
||||
SendReplyOK (s.str().c_str());
|
||||
}
|
||||
else
|
||||
SendReplyError ("no nickname has been set");
|
||||
}
|
||||
|
||||
BOBCommandChannel::BOBCommandChannel (const std::string& address, int port):
|
||||
m_IsRunning (false), m_Thread (nullptr),
|
||||
m_Acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(address), port))
|
||||
{
|
||||
// command -> handler
|
||||
m_CommandHandlers[BOB_COMMAND_ZAP] = &BOBCommandSession::ZapCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_QUIT] = &BOBCommandSession::QuitCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_START] = &BOBCommandSession::StartCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_STOP] = &BOBCommandSession::StopCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_SETNICK] = &BOBCommandSession::SetNickCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_GETNICK] = &BOBCommandSession::GetNickCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_NEWKEYS] = &BOBCommandSession::NewkeysCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_GETKEYS] = &BOBCommandSession::GetkeysCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_SETKEYS] = &BOBCommandSession::SetkeysCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_GETDEST] = &BOBCommandSession::GetdestCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_OUTHOST] = &BOBCommandSession::OuthostCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_OUTPORT] = &BOBCommandSession::OutportCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_INHOST] = &BOBCommandSession::InhostCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_INPORT] = &BOBCommandSession::InportCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_QUIET] = &BOBCommandSession::QuietCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_LOOKUP] = &BOBCommandSession::LookupCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_CLEAR] = &BOBCommandSession::ClearCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_LIST] = &BOBCommandSession::ListCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_OPTION] = &BOBCommandSession::OptionCommandHandler;
|
||||
m_CommandHandlers[BOB_COMMAND_STATUS] = &BOBCommandSession::StatusCommandHandler;
|
||||
}
|
||||
|
||||
BOBCommandChannel::~BOBCommandChannel ()
|
||||
{
|
||||
Stop ();
|
||||
for (const auto& it: m_Destinations)
|
||||
delete it.second;
|
||||
}
|
||||
|
||||
void BOBCommandChannel::Start ()
|
||||
{
|
||||
Accept ();
|
||||
m_IsRunning = true;
|
||||
m_Thread = new std::thread (std::bind (&BOBCommandChannel::Run, this));
|
||||
}
|
||||
|
||||
void BOBCommandChannel::Stop ()
|
||||
{
|
||||
m_IsRunning = false;
|
||||
for (auto& it: m_Destinations)
|
||||
it.second->Stop ();
|
||||
m_Acceptor.cancel ();
|
||||
m_Service.stop ();
|
||||
if (m_Thread)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void BOBCommandChannel::Run ()
|
||||
{
|
||||
while (m_IsRunning)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Service.run ();
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint (eLogError, "BOB: runtime exception: ", ex.what ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BOBCommandChannel::AddDestination (const std::string& name, BOBDestination * dest)
|
||||
{
|
||||
m_Destinations[name] = dest;
|
||||
}
|
||||
|
||||
void BOBCommandChannel::DeleteDestination (const std::string& name)
|
||||
{
|
||||
auto it = m_Destinations.find (name);
|
||||
if (it != m_Destinations.end ())
|
||||
{
|
||||
it->second->Stop ();
|
||||
delete it->second;
|
||||
m_Destinations.erase (it);
|
||||
}
|
||||
}
|
||||
|
||||
BOBDestination * BOBCommandChannel::FindDestination (const std::string& name)
|
||||
{
|
||||
auto it = m_Destinations.find (name);
|
||||
if (it != m_Destinations.end ())
|
||||
return it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void BOBCommandChannel::Accept ()
|
||||
{
|
||||
auto newSession = std::make_shared<BOBCommandSession> (*this);
|
||||
m_Acceptor.async_accept (newSession->GetSocket (), std::bind (&BOBCommandChannel::HandleAccept, this,
|
||||
std::placeholders::_1, newSession));
|
||||
}
|
||||
|
||||
void BOBCommandChannel::HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<BOBCommandSession> session)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Accept ();
|
||||
|
||||
if (!ecode)
|
||||
{
|
||||
LogPrint (eLogInfo, "BOB: New command connection from ", session->GetSocket ().remote_endpoint ());
|
||||
session->SendVersion ();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "BOB: accept error: ", ecode.message ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
239
libi2pd_client/BOB.h
Normal file
239
libi2pd_client/BOB.h
Normal file
|
@ -0,0 +1,239 @@
|
|||
#ifndef BOB_H__
|
||||
#define BOB_H__
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <thread>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <boost/asio.hpp>
|
||||
#include "I2PTunnel.h"
|
||||
#include "I2PService.h"
|
||||
#include "Identity.h"
|
||||
#include "LeaseSet.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const size_t BOB_COMMAND_BUFFER_SIZE = 1024;
|
||||
const char BOB_COMMAND_ZAP[] = "zap";
|
||||
const char BOB_COMMAND_QUIT[] = "quit";
|
||||
const char BOB_COMMAND_START[] = "start";
|
||||
const char BOB_COMMAND_STOP[] = "stop";
|
||||
const char BOB_COMMAND_SETNICK[] = "setnick";
|
||||
const char BOB_COMMAND_GETNICK[] = "getnick";
|
||||
const char BOB_COMMAND_NEWKEYS[] = "newkeys";
|
||||
const char BOB_COMMAND_GETKEYS[] = "getkeys";
|
||||
const char BOB_COMMAND_SETKEYS[] = "setkeys";
|
||||
const char BOB_COMMAND_GETDEST[] = "getdest";
|
||||
const char BOB_COMMAND_OUTHOST[] = "outhost";
|
||||
const char BOB_COMMAND_OUTPORT[] = "outport";
|
||||
const char BOB_COMMAND_INHOST[] = "inhost";
|
||||
const char BOB_COMMAND_INPORT[] = "inport";
|
||||
const char BOB_COMMAND_QUIET[] = "quiet";
|
||||
const char BOB_COMMAND_LOOKUP[] = "lookup";
|
||||
const char BOB_COMMAND_CLEAR[] = "clear";
|
||||
const char BOB_COMMAND_LIST[] = "list";
|
||||
const char BOB_COMMAND_OPTION[] = "option";
|
||||
const char BOB_COMMAND_STATUS[] = "status";
|
||||
|
||||
const char BOB_VERSION[] = "BOB 00.00.10\nOK\n";
|
||||
const char BOB_REPLY_OK[] = "OK %s\n";
|
||||
const char BOB_REPLY_ERROR[] = "ERROR %s\n";
|
||||
const char BOB_DATA[] = "NICKNAME %s\n";
|
||||
|
||||
class BOBI2PTunnel: public I2PService
|
||||
{
|
||||
public:
|
||||
|
||||
BOBI2PTunnel (std::shared_ptr<ClientDestination> localDestination):
|
||||
I2PService (localDestination) {};
|
||||
|
||||
virtual void Start () {};
|
||||
virtual void Stop () {};
|
||||
};
|
||||
|
||||
class BOBI2PInboundTunnel: public BOBI2PTunnel
|
||||
{
|
||||
struct AddressReceiver
|
||||
{
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket;
|
||||
char buffer[BOB_COMMAND_BUFFER_SIZE + 1]; // for destination base64 address
|
||||
uint8_t * data; // pointer to buffer
|
||||
size_t dataLen, bufferOffset;
|
||||
|
||||
AddressReceiver (): data (nullptr), dataLen (0), bufferOffset (0) {};
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
BOBI2PInboundTunnel (int port, std::shared_ptr<ClientDestination> localDestination);
|
||||
~BOBI2PInboundTunnel ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
private:
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<AddressReceiver> receiver);
|
||||
|
||||
void ReceiveAddress (std::shared_ptr<AddressReceiver> receiver);
|
||||
void HandleReceivedAddress (const boost::system::error_code& ecode, std::size_t bytes_transferred,
|
||||
std::shared_ptr<AddressReceiver> receiver);
|
||||
|
||||
void HandleDestinationRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet, std::shared_ptr<AddressReceiver> receiver);
|
||||
|
||||
void CreateConnection (std::shared_ptr<AddressReceiver> receiver, std::shared_ptr<const i2p::data::LeaseSet> leaseSet);
|
||||
|
||||
private:
|
||||
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
};
|
||||
|
||||
class BOBI2POutboundTunnel: public BOBI2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
BOBI2POutboundTunnel (const std::string& address, int port, std::shared_ptr<ClientDestination> localDestination, bool quiet);
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
void SetQuiet () { m_IsQuiet = true; };
|
||||
|
||||
private:
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
private:
|
||||
|
||||
boost::asio::ip::tcp::endpoint m_Endpoint;
|
||||
bool m_IsQuiet;
|
||||
};
|
||||
|
||||
|
||||
class BOBDestination
|
||||
{
|
||||
public:
|
||||
|
||||
BOBDestination (std::shared_ptr<ClientDestination> localDestination);
|
||||
~BOBDestination ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
void StopTunnels ();
|
||||
void CreateInboundTunnel (int port);
|
||||
void CreateOutboundTunnel (const std::string& address, int port, bool quiet);
|
||||
const i2p::data::PrivateKeys& GetKeys () const { return m_LocalDestination->GetPrivateKeys (); };
|
||||
std::shared_ptr<ClientDestination> GetLocalDestination () const { return m_LocalDestination; };
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<ClientDestination> m_LocalDestination;
|
||||
BOBI2POutboundTunnel * m_OutboundTunnel;
|
||||
BOBI2PInboundTunnel * m_InboundTunnel;
|
||||
};
|
||||
|
||||
class BOBCommandChannel;
|
||||
class BOBCommandSession: public std::enable_shared_from_this<BOBCommandSession>
|
||||
{
|
||||
public:
|
||||
|
||||
BOBCommandSession (BOBCommandChannel& owner);
|
||||
~BOBCommandSession ();
|
||||
void Terminate ();
|
||||
|
||||
boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
|
||||
void SendVersion ();
|
||||
|
||||
// command handlers
|
||||
void ZapCommandHandler (const char * operand, size_t len);
|
||||
void QuitCommandHandler (const char * operand, size_t len);
|
||||
void StartCommandHandler (const char * operand, size_t len);
|
||||
void StopCommandHandler (const char * operand, size_t len);
|
||||
void SetNickCommandHandler (const char * operand, size_t len);
|
||||
void GetNickCommandHandler (const char * operand, size_t len);
|
||||
void NewkeysCommandHandler (const char * operand, size_t len);
|
||||
void SetkeysCommandHandler (const char * operand, size_t len);
|
||||
void GetkeysCommandHandler (const char * operand, size_t len);
|
||||
void GetdestCommandHandler (const char * operand, size_t len);
|
||||
void OuthostCommandHandler (const char * operand, size_t len);
|
||||
void OutportCommandHandler (const char * operand, size_t len);
|
||||
void InhostCommandHandler (const char * operand, size_t len);
|
||||
void InportCommandHandler (const char * operand, size_t len);
|
||||
void QuietCommandHandler (const char * operand, size_t len);
|
||||
void LookupCommandHandler (const char * operand, size_t len);
|
||||
void ClearCommandHandler (const char * operand, size_t len);
|
||||
void ListCommandHandler (const char * operand, size_t len);
|
||||
void OptionCommandHandler (const char * operand, size_t len);
|
||||
void StatusCommandHandler (const char * operand, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
void Receive ();
|
||||
void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
|
||||
void Send (size_t len);
|
||||
void HandleSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void SendReplyOK (const char * msg);
|
||||
void SendReplyError (const char * msg);
|
||||
void SendData (const char * nickname);
|
||||
|
||||
private:
|
||||
|
||||
BOBCommandChannel& m_Owner;
|
||||
boost::asio::ip::tcp::socket m_Socket;
|
||||
char m_ReceiveBuffer[BOB_COMMAND_BUFFER_SIZE + 1], m_SendBuffer[BOB_COMMAND_BUFFER_SIZE + 1];
|
||||
size_t m_ReceiveBufferOffset;
|
||||
bool m_IsOpen, m_IsQuiet, m_IsActive;
|
||||
std::string m_Nickname, m_Address;
|
||||
int m_InPort, m_OutPort;
|
||||
i2p::data::PrivateKeys m_Keys;
|
||||
std::map<std::string, std::string> m_Options;
|
||||
BOBDestination * m_CurrentDestination;
|
||||
};
|
||||
typedef void (BOBCommandSession::*BOBCommandHandler)(const char * operand, size_t len);
|
||||
|
||||
class BOBCommandChannel
|
||||
{
|
||||
public:
|
||||
|
||||
BOBCommandChannel (const std::string& address, int port);
|
||||
~BOBCommandChannel ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
void AddDestination (const std::string& name, BOBDestination * dest);
|
||||
void DeleteDestination (const std::string& name);
|
||||
BOBDestination * FindDestination (const std::string& name);
|
||||
|
||||
private:
|
||||
|
||||
void Run ();
|
||||
void Accept ();
|
||||
void HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<BOBCommandSession> session);
|
||||
|
||||
private:
|
||||
|
||||
bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
std::map<std::string, BOBDestination *> m_Destinations;
|
||||
std::map<std::string, BOBCommandHandler> m_CommandHandlers;
|
||||
|
||||
public:
|
||||
|
||||
const decltype(m_CommandHandlers)& GetCommandHandlers () const { return m_CommandHandlers; };
|
||||
const decltype(m_Destinations)& GetDestinations () const { return m_Destinations; };
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
666
libi2pd_client/ClientContext.cpp
Normal file
666
libi2pd_client/ClientContext.cpp
Normal file
|
@ -0,0 +1,666 @@
|
|||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <boost/property_tree/ptree.hpp>
|
||||
#include <boost/property_tree/ini_parser.hpp>
|
||||
#include "Config.h"
|
||||
#include "FS.h"
|
||||
#include "Log.h"
|
||||
#include "Identity.h"
|
||||
#include "util.h"
|
||||
#include "ClientContext.h"
|
||||
#include "SOCKS.h"
|
||||
#include "WebSocks.h"
|
||||
#include "MatchedDestination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
ClientContext context;
|
||||
|
||||
ClientContext::ClientContext (): m_SharedLocalDestination (nullptr),
|
||||
m_HttpProxy (nullptr), m_SocksProxy (nullptr), m_SamBridge (nullptr),
|
||||
m_BOBCommandChannel (nullptr), m_I2CPServer (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
ClientContext::~ClientContext ()
|
||||
{
|
||||
delete m_HttpProxy;
|
||||
delete m_SocksProxy;
|
||||
delete m_SamBridge;
|
||||
delete m_BOBCommandChannel;
|
||||
delete m_I2CPServer;
|
||||
}
|
||||
|
||||
void ClientContext::Start ()
|
||||
{
|
||||
if (!m_SharedLocalDestination)
|
||||
{
|
||||
m_SharedLocalDestination = CreateNewLocalDestination (); // non-public, DSA
|
||||
m_Destinations[m_SharedLocalDestination->GetIdentity ()->GetIdentHash ()] = m_SharedLocalDestination;
|
||||
m_SharedLocalDestination->Start ();
|
||||
}
|
||||
|
||||
|
||||
m_AddressBook.Start ();
|
||||
|
||||
std::shared_ptr<ClientDestination> localDestination;
|
||||
bool httproxy; i2p::config::GetOption("httpproxy.enabled", httproxy);
|
||||
if (httproxy) {
|
||||
std::string httpProxyKeys; i2p::config::GetOption("httpproxy.keys", httpProxyKeys);
|
||||
std::string httpProxyAddr; i2p::config::GetOption("httpproxy.address", httpProxyAddr);
|
||||
uint16_t httpProxyPort; i2p::config::GetOption("httpproxy.port", httpProxyPort);
|
||||
i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType);
|
||||
LogPrint(eLogInfo, "Clients: starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort);
|
||||
if (httpProxyKeys.length () > 0)
|
||||
{
|
||||
i2p::data::PrivateKeys keys;
|
||||
if(LoadPrivateKeys (keys, httpProxyKeys, sigType))
|
||||
{
|
||||
std::map<std::string, std::string> params;
|
||||
ReadI2CPOptionsFromConfig ("httpproxy.", params);
|
||||
localDestination = CreateNewLocalDestination (keys, false, ¶ms);
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "Clients: failed to load HTTP Proxy key");
|
||||
}
|
||||
try {
|
||||
m_HttpProxy = new i2p::proxy::HTTPProxy(httpProxyAddr, httpProxyPort, localDestination);
|
||||
m_HttpProxy->Start();
|
||||
} catch (std::exception& e) {
|
||||
LogPrint(eLogError, "Clients: Exception in HTTP Proxy: ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
localDestination = nullptr;
|
||||
bool socksproxy; i2p::config::GetOption("socksproxy.enabled", socksproxy);
|
||||
if (socksproxy)
|
||||
{
|
||||
std::string socksProxyKeys; i2p::config::GetOption("socksproxy.keys", socksProxyKeys);
|
||||
std::string socksProxyAddr; i2p::config::GetOption("socksproxy.address", socksProxyAddr);
|
||||
uint16_t socksProxyPort; i2p::config::GetOption("socksproxy.port", socksProxyPort);
|
||||
std::string socksOutProxyAddr; i2p::config::GetOption("socksproxy.outproxy", socksOutProxyAddr);
|
||||
uint16_t socksOutProxyPort; i2p::config::GetOption("socksproxy.outproxyport", socksOutProxyPort);
|
||||
i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype", sigType);
|
||||
LogPrint(eLogInfo, "Clients: starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort);
|
||||
if (socksProxyKeys.length () > 0)
|
||||
{
|
||||
i2p::data::PrivateKeys keys;
|
||||
if (LoadPrivateKeys (keys, socksProxyKeys, sigType))
|
||||
{
|
||||
std::map<std::string, std::string> params;
|
||||
ReadI2CPOptionsFromConfig ("socksproxy.", params);
|
||||
localDestination = CreateNewLocalDestination (keys, false, ¶ms);
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "Clients: failed to load SOCKS Proxy key");
|
||||
}
|
||||
try {
|
||||
m_SocksProxy = new i2p::proxy::SOCKSProxy(socksProxyAddr, socksProxyPort, socksOutProxyAddr, socksOutProxyPort, localDestination);
|
||||
m_SocksProxy->Start();
|
||||
} catch (std::exception& e) {
|
||||
LogPrint(eLogError, "Clients: Exception in SOCKS Proxy: ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// I2P tunnels
|
||||
ReadTunnels ();
|
||||
|
||||
// SAM
|
||||
bool sam; i2p::config::GetOption("sam.enabled", sam);
|
||||
if (sam) {
|
||||
std::string samAddr; i2p::config::GetOption("sam.address", samAddr);
|
||||
uint16_t samPort; i2p::config::GetOption("sam.port", samPort);
|
||||
LogPrint(eLogInfo, "Clients: starting SAM bridge at ", samAddr, ":", samPort);
|
||||
try {
|
||||
m_SamBridge = new SAMBridge (samAddr, samPort);
|
||||
m_SamBridge->Start ();
|
||||
} catch (std::exception& e) {
|
||||
LogPrint(eLogError, "Clients: Exception in SAM bridge: ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// BOB
|
||||
bool bob; i2p::config::GetOption("bob.enabled", bob);
|
||||
if (bob) {
|
||||
std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr);
|
||||
uint16_t bobPort; i2p::config::GetOption("bob.port", bobPort);
|
||||
LogPrint(eLogInfo, "Clients: starting BOB command channel at ", bobAddr, ":", bobPort);
|
||||
try {
|
||||
m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort);
|
||||
m_BOBCommandChannel->Start ();
|
||||
} catch (std::exception& e) {
|
||||
LogPrint(eLogError, "Clients: Exception in BOB bridge: ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// I2CP
|
||||
bool i2cp; i2p::config::GetOption("i2cp.enabled", i2cp);
|
||||
if (i2cp)
|
||||
{
|
||||
std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr);
|
||||
uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort);
|
||||
LogPrint(eLogInfo, "Clients: starting I2CP at ", i2cpAddr, ":", i2cpPort);
|
||||
try
|
||||
{
|
||||
m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort);
|
||||
m_I2CPServer->Start ();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
LogPrint(eLogError, "Clients: Exception in I2CP: ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
m_AddressBook.StartResolvers ();
|
||||
|
||||
// start UDP cleanup
|
||||
if (!m_ServerForwards.empty ())
|
||||
{
|
||||
m_CleanupUDPTimer.reset (new boost::asio::deadline_timer(m_SharedLocalDestination->GetService ()));
|
||||
ScheduleCleanupUDP();
|
||||
}
|
||||
}
|
||||
|
||||
void ClientContext::Stop ()
|
||||
{
|
||||
if (m_HttpProxy)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping HTTP Proxy");
|
||||
m_HttpProxy->Stop();
|
||||
delete m_HttpProxy;
|
||||
m_HttpProxy = nullptr;
|
||||
}
|
||||
|
||||
if (m_SocksProxy)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping SOCKS Proxy");
|
||||
m_SocksProxy->Stop();
|
||||
delete m_SocksProxy;
|
||||
m_SocksProxy = nullptr;
|
||||
}
|
||||
|
||||
for (auto& it: m_ClientTunnels)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping I2P client tunnel on port ", it.first);
|
||||
it.second->Stop ();
|
||||
}
|
||||
m_ClientTunnels.clear ();
|
||||
|
||||
for (auto& it: m_ServerTunnels)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping I2P server tunnel");
|
||||
it.second->Stop ();
|
||||
}
|
||||
m_ServerTunnels.clear ();
|
||||
|
||||
if (m_SamBridge)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping SAM bridge");
|
||||
m_SamBridge->Stop ();
|
||||
delete m_SamBridge;
|
||||
m_SamBridge = nullptr;
|
||||
}
|
||||
|
||||
if (m_BOBCommandChannel)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping BOB command channel");
|
||||
m_BOBCommandChannel->Stop ();
|
||||
delete m_BOBCommandChannel;
|
||||
m_BOBCommandChannel = nullptr;
|
||||
}
|
||||
|
||||
if (m_I2CPServer)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: stopping I2CP");
|
||||
m_I2CPServer->Stop ();
|
||||
delete m_I2CPServer;
|
||||
m_I2CPServer = nullptr;
|
||||
}
|
||||
|
||||
LogPrint(eLogInfo, "Clients: stopping AddressBook");
|
||||
m_AddressBook.Stop ();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
|
||||
m_ServerForwards.clear();
|
||||
m_ClientForwards.clear();
|
||||
}
|
||||
|
||||
if (m_CleanupUDPTimer)
|
||||
{
|
||||
m_CleanupUDPTimer->cancel ();
|
||||
m_CleanupUDPTimer = nullptr;
|
||||
}
|
||||
|
||||
for (auto& it: m_Destinations)
|
||||
it.second->Stop ();
|
||||
m_Destinations.clear ();
|
||||
m_SharedLocalDestination = nullptr;
|
||||
}
|
||||
|
||||
void ClientContext::ReloadConfig ()
|
||||
{
|
||||
std::string config; i2p::config::GetOption("conf", config);
|
||||
i2p::config::ParseConfig(config);
|
||||
Stop();
|
||||
Start();
|
||||
}
|
||||
|
||||
bool ClientContext::LoadPrivateKeys (i2p::data::PrivateKeys& keys, const std::string& filename, i2p::data::SigningKeyType sigType)
|
||||
{
|
||||
bool success = true;
|
||||
std::string fullPath = i2p::fs::DataDirPath (filename);
|
||||
std::ifstream s(fullPath, std::ifstream::binary);
|
||||
if (s.is_open ())
|
||||
{
|
||||
s.seekg (0, std::ios::end);
|
||||
size_t len = s.tellg();
|
||||
s.seekg (0, std::ios::beg);
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
s.read ((char *)buf, len);
|
||||
if(!keys.FromBuffer (buf, len))
|
||||
{
|
||||
LogPrint (eLogError, "Clients: failed to load keyfile ", filename);
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogInfo, "Clients: Local address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " loaded");
|
||||
delete[] buf;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "Clients: can't open file ", fullPath, " Creating new one with signature type ", sigType);
|
||||
keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
|
||||
std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
|
||||
size_t len = keys.GetFullLen ();
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
len = keys.ToBuffer (buf, len);
|
||||
f.write ((char *)buf, len);
|
||||
delete[] buf;
|
||||
|
||||
LogPrint (eLogInfo, "Clients: New private keys file ", fullPath, " for ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > ClientContext::GetForwardInfosFor(const i2p::data::IdentHash & destination)
|
||||
{
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
|
||||
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
|
||||
for(const auto & c : m_ClientForwards)
|
||||
{
|
||||
if (c.second->IsLocalDestination(destination))
|
||||
{
|
||||
for (auto & i : c.second->GetSessions()) infos.push_back(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for(const auto & s : m_ServerForwards)
|
||||
{
|
||||
if(std::get<0>(s.first) == destination)
|
||||
{
|
||||
for( auto & i : s.second->GetSessions()) infos.push_back(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return infos;
|
||||
}
|
||||
|
||||
std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
|
||||
auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
|
||||
std::shared_ptr<ClientDestination> ClientContext::CreateNewMatchedTunnelDestination(const i2p::data::PrivateKeys &keys, const std::string & name, const std::map<std::string, std::string> * params)
|
||||
{
|
||||
MatchedTunnelDestination * cl = new MatchedTunnelDestination(keys, name, params);
|
||||
auto localDestination = std::shared_ptr<ClientDestination>(cl);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
|
||||
void ClientContext::DeleteLocalDestination (std::shared_ptr<ClientDestination> destination)
|
||||
{
|
||||
if (!destination) return;
|
||||
auto it = m_Destinations.find (destination->GetIdentHash ());
|
||||
if (it != m_Destinations.end ())
|
||||
{
|
||||
auto d = it->second;
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations.erase (it);
|
||||
}
|
||||
d->Stop ();
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
auto it = m_Destinations.find (keys.GetPublic ()->GetIdentHash ());
|
||||
if (it != m_Destinations.end ())
|
||||
{
|
||||
LogPrint (eLogWarning, "Clients: Local destination ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " exists");
|
||||
if (!it->second->IsRunning ())
|
||||
{
|
||||
it->second->Start ();
|
||||
return it->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[keys.GetPublic ()->GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
|
||||
std::shared_ptr<ClientDestination> ClientContext::FindLocalDestination (const i2p::data::IdentHash& destination) const
|
||||
{
|
||||
auto it = m_Destinations.find (destination);
|
||||
if (it != m_Destinations.end ())
|
||||
return it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename Section, typename Type>
|
||||
std::string ClientContext::GetI2CPOption (const Section& section, const std::string& name, const Type& value) const
|
||||
{
|
||||
return section.second.get (boost::property_tree::ptree::path_type (name, '/'), std::to_string (value));
|
||||
}
|
||||
|
||||
template<typename Section>
|
||||
void ClientContext::ReadI2CPOptions (const Section& section, std::map<std::string, std::string>& options) const
|
||||
{
|
||||
options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNEL_LENGTH, DEFAULT_INBOUND_TUNNEL_LENGTH);
|
||||
options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, DEFAULT_OUTBOUND_TUNNEL_LENGTH);
|
||||
options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, DEFAULT_INBOUND_TUNNELS_QUANTITY);
|
||||
options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, DEFAULT_OUTBOUND_TUNNELS_QUANTITY);
|
||||
options[I2CP_PARAM_TAGS_TO_SEND] = GetI2CPOption (section, I2CP_PARAM_TAGS_TO_SEND, DEFAULT_TAGS_TO_SEND);
|
||||
options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MIN_TUNNEL_LATENCY, DEFAULT_MIN_TUNNEL_LATENCY);
|
||||
options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MAX_TUNNEL_LATENCY, DEFAULT_MAX_TUNNEL_LATENCY);
|
||||
}
|
||||
|
||||
void ClientContext::ReadI2CPOptionsFromConfig (const std::string& prefix, std::map<std::string, std::string>& options) const
|
||||
{
|
||||
std::string value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNEL_LENGTH, value))
|
||||
options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, value))
|
||||
options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, value))
|
||||
options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, value))
|
||||
options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_MIN_TUNNEL_LATENCY, value))
|
||||
options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = value;
|
||||
if (i2p::config::GetOption(prefix + I2CP_PARAM_MAX_TUNNEL_LATENCY, value))
|
||||
options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = value;
|
||||
}
|
||||
|
||||
void ClientContext::ReadTunnels ()
|
||||
{
|
||||
boost::property_tree::ptree pt;
|
||||
std::string tunConf; i2p::config::GetOption("tunconf", tunConf);
|
||||
if (tunConf == "") {
|
||||
// TODO: cleanup this in 2.8.0
|
||||
tunConf = i2p::fs::DataDirPath ("tunnels.cfg");
|
||||
if (i2p::fs::Exists(tunConf)) {
|
||||
LogPrint(eLogWarning, "FS: please rename tunnels.cfg -> tunnels.conf here: ", tunConf);
|
||||
} else {
|
||||
tunConf = i2p::fs::DataDirPath ("tunnels.conf");
|
||||
}
|
||||
}
|
||||
LogPrint(eLogDebug, "FS: tunnels config file: ", tunConf);
|
||||
try
|
||||
{
|
||||
boost::property_tree::read_ini (tunConf, pt);
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint (eLogWarning, "Clients: Can't read ", tunConf, ": ", ex.what ());
|
||||
return;
|
||||
}
|
||||
|
||||
int numClientTunnels = 0, numServerTunnels = 0;
|
||||
for (auto& section: pt)
|
||||
{
|
||||
std::string name = section.first;
|
||||
try
|
||||
{
|
||||
std::string type = section.second.get<std::string> (I2P_TUNNELS_SECTION_TYPE);
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_SOCKS
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
|
||||
{
|
||||
// mandatory params
|
||||
std::string dest;
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT || type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
|
||||
dest = section.second.get<std::string> (I2P_CLIENT_TUNNEL_DESTINATION);
|
||||
int port = section.second.get<int> (I2P_CLIENT_TUNNEL_PORT);
|
||||
// optional params
|
||||
bool matchTunnels = section.second.get(I2P_CLIENT_TUNNEL_MATCH_TUNNELS, false);
|
||||
std::string keys = section.second.get (I2P_CLIENT_TUNNEL_KEYS, "");
|
||||
std::string address = section.second.get (I2P_CLIENT_TUNNEL_ADDRESS, "127.0.0.1");
|
||||
int destinationPort = section.second.get (I2P_CLIENT_TUNNEL_DESTINATION_PORT, 0);
|
||||
i2p::data::SigningKeyType sigType = section.second.get (I2P_CLIENT_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
|
||||
// I2CP
|
||||
std::map<std::string, std::string> options;
|
||||
ReadI2CPOptions (section, options);
|
||||
|
||||
std::shared_ptr<ClientDestination> localDestination = nullptr;
|
||||
if (keys.length () > 0)
|
||||
{
|
||||
i2p::data::PrivateKeys k;
|
||||
if(LoadPrivateKeys (k, keys, sigType))
|
||||
{
|
||||
localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
|
||||
if (!localDestination)
|
||||
{
|
||||
if(matchTunnels)
|
||||
localDestination = CreateNewMatchedTunnelDestination(k, dest, &options);
|
||||
else
|
||||
localDestination = CreateNewLocalDestination (k, type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT, &options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT) {
|
||||
// udp client
|
||||
// TODO: hostnames
|
||||
boost::asio::ip::udp::endpoint end(boost::asio::ip::address::from_string(address), port);
|
||||
if (!localDestination)
|
||||
{
|
||||
localDestination = m_SharedLocalDestination;
|
||||
}
|
||||
auto clientTunnel = new I2PUDPClientTunnel(name, dest, end, localDestination, destinationPort);
|
||||
if(m_ClientForwards.insert(std::make_pair(end, std::unique_ptr<I2PUDPClientTunnel>(clientTunnel))).second)
|
||||
{
|
||||
clientTunnel->Start();
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "Clients: I2P Client forward for endpoint ", end, " already exists");
|
||||
|
||||
} else {
|
||||
boost::asio::ip::tcp::endpoint clientEndpoint;
|
||||
I2PService * clientTunnel = nullptr;
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_SOCKS)
|
||||
{
|
||||
// socks proxy
|
||||
clientTunnel = new i2p::proxy::SOCKSProxy(address, port, "", destinationPort, localDestination);
|
||||
clientEndpoint = ((i2p::proxy::SOCKSProxy*)clientTunnel)->GetAcceptor().local_endpoint();
|
||||
}
|
||||
else if (type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY)
|
||||
{
|
||||
// http proxy
|
||||
clientTunnel = new i2p::proxy::HTTPProxy(address, port, localDestination);
|
||||
clientEndpoint = ((i2p::proxy::HTTPProxy*)clientTunnel)->GetAcceptor().local_endpoint();
|
||||
}
|
||||
else if (type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS)
|
||||
{
|
||||
// websocks proxy
|
||||
clientTunnel = new WebSocks(address, port, localDestination);;
|
||||
clientEndpoint = ((WebSocks*)clientTunnel)->GetLocalEndpoint();
|
||||
}
|
||||
else
|
||||
{
|
||||
// tcp client
|
||||
clientTunnel = new I2PClientTunnel (name, dest, address, port, localDestination, destinationPort);
|
||||
clientEndpoint = ((I2PClientTunnel*)clientTunnel)->GetAcceptor().local_endpoint();
|
||||
}
|
||||
if (m_ClientTunnels.insert (std::make_pair (clientEndpoint, std::unique_ptr<I2PService>(clientTunnel))).second)
|
||||
{
|
||||
clientTunnel->Start ();
|
||||
numClientTunnels++;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Clients: I2P client tunnel for endpoint ", clientEndpoint, "already exists");
|
||||
}
|
||||
}
|
||||
else if (type == I2P_TUNNELS_SECTION_TYPE_SERVER
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_HTTP
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_IRC
|
||||
|| type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
|
||||
{
|
||||
// mandatory params
|
||||
std::string host = section.second.get<std::string> (I2P_SERVER_TUNNEL_HOST);
|
||||
int port = section.second.get<int> (I2P_SERVER_TUNNEL_PORT);
|
||||
std::string keys = section.second.get<std::string> (I2P_SERVER_TUNNEL_KEYS);
|
||||
// optional params
|
||||
int inPort = section.second.get (I2P_SERVER_TUNNEL_INPORT, 0);
|
||||
std::string accessList = section.second.get (I2P_SERVER_TUNNEL_ACCESS_LIST, "");
|
||||
std::string hostOverride = section.second.get (I2P_SERVER_TUNNEL_HOST_OVERRIDE, "");
|
||||
std::string webircpass = section.second.get<std::string> (I2P_SERVER_TUNNEL_WEBIRC_PASSWORD, "");
|
||||
bool gzip = section.second.get (I2P_SERVER_TUNNEL_GZIP, true);
|
||||
i2p::data::SigningKeyType sigType = section.second.get (I2P_SERVER_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
|
||||
uint32_t maxConns = section.second.get(i2p::stream::I2CP_PARAM_STREAMING_MAX_CONNS_PER_MIN, i2p::stream::DEFAULT_MAX_CONNS_PER_MIN);
|
||||
std::string address = section.second.get<std::string> (I2P_SERVER_TUNNEL_ADDRESS, "127.0.0.1");
|
||||
bool isUniqueLocal = section.second.get(I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL, true);
|
||||
|
||||
// I2CP
|
||||
std::map<std::string, std::string> options;
|
||||
ReadI2CPOptions (section, options);
|
||||
|
||||
std::shared_ptr<ClientDestination> localDestination = nullptr;
|
||||
i2p::data::PrivateKeys k;
|
||||
if(!LoadPrivateKeys (k, keys, sigType))
|
||||
continue;
|
||||
localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
|
||||
if (!localDestination)
|
||||
localDestination = CreateNewLocalDestination (k, true, &options);
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
|
||||
{
|
||||
// udp server tunnel
|
||||
// TODO: hostnames
|
||||
auto localAddress = boost::asio::ip::address::from_string(address);
|
||||
boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
|
||||
I2PUDPServerTunnel * serverTunnel = new I2PUDPServerTunnel(name, localDestination, localAddress, endpoint, port);
|
||||
if(!isUniqueLocal)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
|
||||
serverTunnel->SetUniqueLocal(isUniqueLocal);
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
|
||||
if(m_ServerForwards.insert(
|
||||
std::make_pair(
|
||||
std::make_pair(
|
||||
localDestination->GetIdentHash(), port),
|
||||
std::unique_ptr<I2PUDPServerTunnel>(serverTunnel))).second)
|
||||
{
|
||||
serverTunnel->Start();
|
||||
LogPrint(eLogInfo, "Clients: I2P Server Forward created for UDP Endpoint ", host, ":", port, " bound on ", address, " for ",localDestination->GetIdentHash().ToBase32());
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "Clients: I2P Server Forward for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash()), "/", port, "already exists");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
I2PServerTunnel * serverTunnel;
|
||||
if (type == I2P_TUNNELS_SECTION_TYPE_HTTP)
|
||||
serverTunnel = new I2PServerTunnelHTTP (name, host, port, localDestination, hostOverride, inPort, gzip);
|
||||
else if (type == I2P_TUNNELS_SECTION_TYPE_IRC)
|
||||
serverTunnel = new I2PServerTunnelIRC (name, host, port, localDestination, webircpass, inPort, gzip);
|
||||
else // regular server tunnel by default
|
||||
serverTunnel = new I2PServerTunnel (name, host, port, localDestination, inPort, gzip);
|
||||
|
||||
LogPrint(eLogInfo, "Clients: Set Max Conns To ", maxConns);
|
||||
serverTunnel->SetMaxConnsPerMinute(maxConns);
|
||||
if(!isUniqueLocal)
|
||||
{
|
||||
LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
|
||||
serverTunnel->SetUniqueLocal(isUniqueLocal);
|
||||
}
|
||||
|
||||
if (accessList.length () > 0)
|
||||
{
|
||||
std::set<i2p::data::IdentHash> idents;
|
||||
size_t pos = 0, comma;
|
||||
do
|
||||
{
|
||||
comma = accessList.find (',', pos);
|
||||
i2p::data::IdentHash ident;
|
||||
ident.FromBase32 (accessList.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
|
||||
idents.insert (ident);
|
||||
pos = comma + 1;
|
||||
}
|
||||
while (comma != std::string::npos);
|
||||
serverTunnel->SetAccessList (idents);
|
||||
}
|
||||
if (m_ServerTunnels.insert (std::make_pair (
|
||||
std::make_pair (localDestination->GetIdentHash (), inPort),
|
||||
std::unique_ptr<I2PServerTunnel>(serverTunnel))).second)
|
||||
{
|
||||
serverTunnel->Start ();
|
||||
numServerTunnels++;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Clients: I2P server tunnel for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash ()), "/", inPort, " already exists");
|
||||
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Clients: Unknown section type=", type, " of ", name, " in ", tunConf);
|
||||
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint (eLogError, "Clients: Can't read tunnel ", name, " params: ", ex.what ());
|
||||
}
|
||||
}
|
||||
LogPrint (eLogInfo, "Clients: ", numClientTunnels, " I2P client tunnels created");
|
||||
LogPrint (eLogInfo, "Clients: ", numServerTunnels, " I2P server tunnels created");
|
||||
}
|
||||
|
||||
void ClientContext::ScheduleCleanupUDP()
|
||||
{
|
||||
if (m_CleanupUDPTimer)
|
||||
{
|
||||
// schedule cleanup in 17 seconds
|
||||
m_CleanupUDPTimer->expires_from_now (boost::posix_time::seconds (17));
|
||||
m_CleanupUDPTimer->async_wait(std::bind(&ClientContext::CleanupUDP, this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
void ClientContext::CleanupUDP(const boost::system::error_code & ecode)
|
||||
{
|
||||
if(!ecode)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ForwardsMutex);
|
||||
for (auto & s : m_ServerForwards ) s.second->ExpireStale();
|
||||
ScheduleCleanupUDP();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
130
libi2pd_client/ClientContext.h
Normal file
130
libi2pd_client/ClientContext.h
Normal file
|
@ -0,0 +1,130 @@
|
|||
#ifndef CLIENT_CONTEXT_H__
|
||||
#define CLIENT_CONTEXT_H__
|
||||
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Destination.h"
|
||||
#include "I2PService.h"
|
||||
#include "HTTPProxy.h"
|
||||
#include "SOCKS.h"
|
||||
#include "I2PTunnel.h"
|
||||
#include "SAM.h"
|
||||
#include "BOB.h"
|
||||
#include "I2CP.h"
|
||||
#include "AddressBook.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const char I2P_TUNNELS_SECTION_TYPE[] = "type";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_CLIENT[] = "client";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_SERVER[] = "server";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_HTTP[] = "http";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_IRC[] = "irc";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_UDPCLIENT[] = "udpclient";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_UDPSERVER[] = "udpserver";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_SOCKS[] = "socks";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_WEBSOCKS[] = "websocks";
|
||||
const char I2P_TUNNELS_SECTION_TYPE_HTTPPROXY[] = "httpproxy";
|
||||
const char I2P_CLIENT_TUNNEL_PORT[] = "port";
|
||||
const char I2P_CLIENT_TUNNEL_ADDRESS[] = "address";
|
||||
const char I2P_CLIENT_TUNNEL_DESTINATION[] = "destination";
|
||||
const char I2P_CLIENT_TUNNEL_KEYS[] = "keys";
|
||||
const char I2P_CLIENT_TUNNEL_SIGNATURE_TYPE[] = "signaturetype";
|
||||
const char I2P_CLIENT_TUNNEL_DESTINATION_PORT[] = "destinationport";
|
||||
const char I2P_CLIENT_TUNNEL_MATCH_TUNNELS[] = "matchtunnels";
|
||||
const char I2P_SERVER_TUNNEL_HOST[] = "host";
|
||||
const char I2P_SERVER_TUNNEL_HOST_OVERRIDE[] = "hostoverride";
|
||||
const char I2P_SERVER_TUNNEL_PORT[] = "port";
|
||||
const char I2P_SERVER_TUNNEL_KEYS[] = "keys";
|
||||
const char I2P_SERVER_TUNNEL_SIGNATURE_TYPE[] = "signaturetype";
|
||||
const char I2P_SERVER_TUNNEL_INPORT[] = "inport";
|
||||
const char I2P_SERVER_TUNNEL_ACCESS_LIST[] = "accesslist";
|
||||
const char I2P_SERVER_TUNNEL_GZIP[] = "gzip";
|
||||
const char I2P_SERVER_TUNNEL_WEBIRC_PASSWORD[] = "webircpassword";
|
||||
const char I2P_SERVER_TUNNEL_ADDRESS[] = "address";
|
||||
const char I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL[] = "enableuniquelocal";
|
||||
|
||||
|
||||
class ClientContext
|
||||
{
|
||||
public:
|
||||
|
||||
ClientContext ();
|
||||
~ClientContext ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
void ReloadConfig ();
|
||||
|
||||
std::shared_ptr<ClientDestination> GetSharedLocalDestination () const { return m_SharedLocalDestination; };
|
||||
std::shared_ptr<ClientDestination> CreateNewLocalDestination (bool isPublic = false, i2p::data::SigningKeyType sigType = i2p::data::SIGNING_KEY_TYPE_DSA_SHA1,
|
||||
const std::map<std::string, std::string> * params = nullptr); // transient
|
||||
std::shared_ptr<ClientDestination> CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic = true,
|
||||
const std::map<std::string, std::string> * params = nullptr);
|
||||
std::shared_ptr<ClientDestination> CreateNewMatchedTunnelDestination(const i2p::data::PrivateKeys &keys, const std::string & name, const std::map<std::string, std::string> * params = nullptr);
|
||||
void DeleteLocalDestination (std::shared_ptr<ClientDestination> destination);
|
||||
std::shared_ptr<ClientDestination> FindLocalDestination (const i2p::data::IdentHash& destination) const;
|
||||
bool LoadPrivateKeys (i2p::data::PrivateKeys& keys, const std::string& filename, i2p::data::SigningKeyType sigType = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
|
||||
|
||||
AddressBook& GetAddressBook () { return m_AddressBook; };
|
||||
const SAMBridge * GetSAMBridge () const { return m_SamBridge; };
|
||||
const I2CPServer * GetI2CPServer () const { return m_I2CPServer; };
|
||||
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > GetForwardInfosFor(const i2p::data::IdentHash & destination);
|
||||
|
||||
private:
|
||||
|
||||
void ReadTunnels ();
|
||||
template<typename Section, typename Type>
|
||||
std::string GetI2CPOption (const Section& section, const std::string& name, const Type& value) const;
|
||||
template<typename Section>
|
||||
void ReadI2CPOptions (const Section& section, std::map<std::string, std::string>& options) const;
|
||||
void ReadI2CPOptionsFromConfig (const std::string& prefix, std::map<std::string, std::string>& options) const;
|
||||
|
||||
void CleanupUDP(const boost::system::error_code & ecode);
|
||||
void ScheduleCleanupUDP();
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_DestinationsMutex;
|
||||
std::map<i2p::data::IdentHash, std::shared_ptr<ClientDestination> > m_Destinations;
|
||||
std::shared_ptr<ClientDestination> m_SharedLocalDestination;
|
||||
|
||||
AddressBook m_AddressBook;
|
||||
|
||||
i2p::proxy::HTTPProxy * m_HttpProxy;
|
||||
i2p::proxy::SOCKSProxy * m_SocksProxy;
|
||||
std::map<boost::asio::ip::tcp::endpoint, std::unique_ptr<I2PService> > m_ClientTunnels; // local endpoint->tunnel
|
||||
std::map<std::pair<i2p::data::IdentHash, int>, std::unique_ptr<I2PServerTunnel> > m_ServerTunnels; // <destination,port>->tunnel
|
||||
|
||||
std::mutex m_ForwardsMutex;
|
||||
std::map<boost::asio::ip::udp::endpoint, std::unique_ptr<I2PUDPClientTunnel> > m_ClientForwards; // local endpoint -> udp tunnel
|
||||
std::map<std::pair<i2p::data::IdentHash, int>, std::unique_ptr<I2PUDPServerTunnel> > m_ServerForwards; // <destination,port> -> udp tunnel
|
||||
|
||||
SAMBridge * m_SamBridge;
|
||||
BOBCommandChannel * m_BOBCommandChannel;
|
||||
I2CPServer * m_I2CPServer;
|
||||
|
||||
std::unique_ptr<boost::asio::deadline_timer> m_CleanupUDPTimer;
|
||||
|
||||
public:
|
||||
// for HTTP
|
||||
const decltype(m_Destinations)& GetDestinations () const { return m_Destinations; };
|
||||
const decltype(m_ClientTunnels)& GetClientTunnels () const { return m_ClientTunnels; };
|
||||
const decltype(m_ServerTunnels)& GetServerTunnels () const { return m_ServerTunnels; };
|
||||
const decltype(m_ClientForwards)& GetClientForwards () const { return m_ClientForwards; }
|
||||
const decltype(m_ServerForwards)& GetServerForwards () const { return m_ServerForwards; }
|
||||
const i2p::proxy::HTTPProxy * GetHttpProxy () const { return m_HttpProxy; }
|
||||
const i2p::proxy::SOCKSProxy * GetSocksProxy () const { return m_SocksProxy; }
|
||||
};
|
||||
|
||||
extern ClientContext context;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
525
libi2pd_client/HTTPProxy.cpp
Normal file
525
libi2pd_client/HTTPProxy.cpp
Normal file
|
@ -0,0 +1,525 @@
|
|||
#include <cstring>
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <boost/asio.hpp>
|
||||
#include <mutex>
|
||||
|
||||
#include "I2PService.h"
|
||||
#include "Destination.h"
|
||||
#include "HTTPProxy.h"
|
||||
#include "util.h"
|
||||
#include "Identity.h"
|
||||
#include "Streaming.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PEndian.h"
|
||||
#include "I2PTunnel.h"
|
||||
#include "Config.h"
|
||||
#include "HTTP.h"
|
||||
|
||||
namespace i2p {
|
||||
namespace proxy {
|
||||
std::map<std::string, std::string> jumpservices = {
|
||||
{ "inr.i2p", "http://joajgazyztfssty4w2on5oaqksz6tqoxbduy553y34mf4byv6gpq.b32.i2p/search/?q=" },
|
||||
{ "stats.i2p", "http://7tbay5p4kzeekxvyvbf6v7eauazemsnnl2aoyqhg5jzpr5eke7tq.b32.i2p/cgi-bin/jump.cgi?a=" },
|
||||
};
|
||||
|
||||
static const char *pageHead =
|
||||
"<head>\r\n"
|
||||
" <title>I2Pd HTTP proxy</title>\r\n"
|
||||
" <style type=\"text/css\">\r\n"
|
||||
" body { font: 100%/1.5em sans-serif; margin: 0; padding: 1.5em; background: #FAFAFA; color: #103456; }\r\n"
|
||||
" .header { font-size: 2.5em; text-align: center; margin: 1.5em 0; color: #894C84; }\r\n"
|
||||
" </style>\r\n"
|
||||
"</head>\r\n"
|
||||
;
|
||||
|
||||
bool str_rmatch(std::string & str, const char *suffix) {
|
||||
auto pos = str.rfind (suffix);
|
||||
if (pos == std::string::npos)
|
||||
return false; /* not found */
|
||||
if (str.length() == (pos + std::strlen(suffix)))
|
||||
return true; /* match */
|
||||
return false;
|
||||
}
|
||||
|
||||
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
|
||||
{
|
||||
private:
|
||||
|
||||
bool HandleRequest();
|
||||
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void Terminate();
|
||||
void AsyncSockRead();
|
||||
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
|
||||
void SanitizeHTTPRequest(i2p::http::HTTPReq & req);
|
||||
void SentHTTPFailed(const boost::system::error_code & ecode);
|
||||
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
/* error helpers */
|
||||
void GenericProxyError(const char *title, const char *description);
|
||||
void GenericProxyInfo(const char *title, const char *description);
|
||||
void HostNotFound(std::string & host);
|
||||
void SendProxyError(std::string & content);
|
||||
|
||||
void ForwardToUpstreamProxy();
|
||||
void HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec);
|
||||
void HandleUpstreamSocksProxyConnect(const boost::system::error_code & ec);
|
||||
|
||||
void HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transfered);
|
||||
void HandleSocksProxyReply(const boost::system::error_code & ec, std::size_t bytes_transfered);
|
||||
|
||||
typedef std::function<void(boost::asio::ip::tcp::endpoint)> ProxyResolvedHandler;
|
||||
|
||||
void HandleUpstreamProxyResolved(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr, ProxyResolvedHandler handler);
|
||||
|
||||
void SocksProxySuccess();
|
||||
void HandoverToUpstreamProxy();
|
||||
|
||||
uint8_t m_recv_chunk[8192];
|
||||
std::string m_recv_buf; // from client
|
||||
std::string m_send_buf; // to upstream
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_proxysock;
|
||||
boost::asio::ip::tcp::resolver m_proxy_resolver;
|
||||
i2p::http::URL m_ProxyURL;
|
||||
i2p::http::URL m_RequestURL;
|
||||
uint8_t m_socks_buf[255+8]; // for socks request/response
|
||||
ssize_t m_req_len;
|
||||
i2p::http::URL m_ClientRequestURL;
|
||||
i2p::http::HTTPReq m_ClientRequest;
|
||||
i2p::http::HTTPRes m_ClientResponse;
|
||||
std::stringstream m_ClientRequestBuffer;
|
||||
public:
|
||||
|
||||
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
|
||||
I2PServiceHandler(parent), m_sock(sock),
|
||||
m_proxysock(std::make_shared<boost::asio::ip::tcp::socket>(parent->GetService())),
|
||||
m_proxy_resolver(parent->GetService()) {}
|
||||
~HTTPReqHandler() { Terminate(); }
|
||||
void Handle () { AsyncSockRead(); } /* overload */
|
||||
};
|
||||
|
||||
void HTTPReqHandler::AsyncSockRead()
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: async sock read");
|
||||
if (!m_sock) {
|
||||
LogPrint(eLogError, "HTTPProxy: no socket for read");
|
||||
return;
|
||||
}
|
||||
m_sock->async_read_some(boost::asio::buffer(m_recv_chunk, sizeof(m_recv_chunk)),
|
||||
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void HTTPReqHandler::Terminate() {
|
||||
if (Kill()) return;
|
||||
if (m_sock)
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: close sock");
|
||||
m_sock->close();
|
||||
m_sock = nullptr;
|
||||
}
|
||||
if(m_proxysock)
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: close proxysock");
|
||||
if(m_proxysock->is_open())
|
||||
m_proxysock->close();
|
||||
m_proxysock = nullptr;
|
||||
}
|
||||
Done(shared_from_this());
|
||||
}
|
||||
|
||||
void HTTPReqHandler::GenericProxyError(const char *title, const char *description) {
|
||||
std::stringstream ss;
|
||||
ss << "<h1>Proxy error: " << title << "</h1>\r\n";
|
||||
ss << "<p>" << description << "</p>\r\n";
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::GenericProxyInfo(const char *title, const char *description) {
|
||||
std::stringstream ss;
|
||||
ss << "<h1>Proxy info: " << title << "</h1>\r\n";
|
||||
ss << "<p>" << description << "</p>\r\n";
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HostNotFound(std::string & host) {
|
||||
std::stringstream ss;
|
||||
ss << "<h1>Proxy error: Host not found</h1>\r\n"
|
||||
<< "<p>Remote host not found in router's addressbook</p>\r\n"
|
||||
<< "<p>You may try to find this host on jumpservices below:</p>\r\n"
|
||||
<< "<ul>\r\n";
|
||||
for (const auto& js : jumpservices) {
|
||||
ss << " <li><a href=\"" << js.second << host << "\">" << js.first << "</a></li>\r\n";
|
||||
}
|
||||
ss << "</ul>\r\n";
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::SendProxyError(std::string & content)
|
||||
{
|
||||
i2p::http::HTTPRes res;
|
||||
res.code = 500;
|
||||
res.add_header("Content-Type", "text/html; charset=UTF-8");
|
||||
res.add_header("Connection", "close");
|
||||
std::stringstream ss;
|
||||
ss << "<html>\r\n" << pageHead
|
||||
<< "<body>" << content << "</body>\r\n"
|
||||
<< "</html>\r\n";
|
||||
res.body = ss.str();
|
||||
std::string response = res.to_string();
|
||||
boost::asio::async_write(*m_sock, boost::asio::buffer(response), boost::asio::transfer_all(),
|
||||
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
|
||||
}
|
||||
|
||||
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
|
||||
{
|
||||
const char *param = "i2paddresshelper=";
|
||||
std::size_t pos = url.query.find(param);
|
||||
std::size_t len = std::strlen(param);
|
||||
std::map<std::string, std::string> params;
|
||||
|
||||
if (pos == std::string::npos)
|
||||
return false; /* not found */
|
||||
if (!url.parse_query(params))
|
||||
return false;
|
||||
|
||||
std::string value = params["i2paddresshelper"];
|
||||
len += value.length();
|
||||
b64 = i2p::http::UrlDecode(value);
|
||||
url.query.replace(pos, len, "");
|
||||
return true;
|
||||
}
|
||||
|
||||
void HTTPReqHandler::SanitizeHTTPRequest(i2p::http::HTTPReq & req)
|
||||
{
|
||||
/* drop common headers */
|
||||
req.RemoveHeader ("Referer");
|
||||
req.RemoveHeader("Via");
|
||||
req.RemoveHeader("Forwarded");
|
||||
/* drop proxy-disclosing headers */
|
||||
req.RemoveHeader("X-Forwarded");
|
||||
req.RemoveHeader("Proxy-");
|
||||
/* replace headers */
|
||||
req.UpdateHeader("User-Agent", "MYOB/6.66 (AN/ON)");
|
||||
/* add headers */
|
||||
req.AddHeader("Connection", "close"); /* keep-alive conns not supported yet */
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Try to parse request from @a m_recv_buf
|
||||
* If parsing success, rebuild request and store to @a m_send_buf
|
||||
* with remaining data tail
|
||||
* @return true on processed request or false if more data needed
|
||||
*/
|
||||
bool HTTPReqHandler::HandleRequest()
|
||||
{
|
||||
std::string b64;
|
||||
|
||||
m_req_len = m_ClientRequest.parse(m_recv_buf);
|
||||
|
||||
if (m_req_len == 0)
|
||||
return false; /* need more data */
|
||||
|
||||
if (m_req_len < 0) {
|
||||
LogPrint(eLogError, "HTTPProxy: unable to parse request");
|
||||
GenericProxyError("Invalid request", "Proxy unable to parse your request");
|
||||
return true; /* parse error */
|
||||
}
|
||||
|
||||
/* parsing success, now let's look inside request */
|
||||
LogPrint(eLogDebug, "HTTPProxy: requested: ", m_ClientRequest.uri);
|
||||
m_RequestURL.parse(m_ClientRequest.uri);
|
||||
|
||||
if (ExtractAddressHelper(m_RequestURL, b64))
|
||||
{
|
||||
bool addresshelper; i2p::config::GetOption("httpproxy.addresshelper", addresshelper);
|
||||
if (!addresshelper)
|
||||
{
|
||||
LogPrint(eLogWarning, "HTTPProxy: addresshelper disabled");
|
||||
GenericProxyError("Invalid request", "adddresshelper is not supported");
|
||||
return true;
|
||||
}
|
||||
i2p::client::context.GetAddressBook ().InsertAddress (m_RequestURL.host, b64);
|
||||
LogPrint (eLogInfo, "HTTPProxy: added b64 from addresshelper for ", m_RequestURL.host);
|
||||
std::string full_url = m_RequestURL.to_string();
|
||||
std::stringstream ss;
|
||||
ss << "Host " << m_RequestURL.host << " added to router's addressbook from helper. "
|
||||
<< "Click <a href=\"" << full_url << "\">here</a> to proceed.";
|
||||
GenericProxyInfo("Addresshelper found", ss.str().c_str());
|
||||
return true; /* request processed */
|
||||
}
|
||||
|
||||
SanitizeHTTPRequest(m_ClientRequest);
|
||||
|
||||
std::string dest_host = m_RequestURL.host;
|
||||
uint16_t dest_port = m_RequestURL.port;
|
||||
/* always set port, even if missing in request */
|
||||
if (!dest_port)
|
||||
dest_port = (m_RequestURL.schema == "https") ? 443 : 80;
|
||||
/* detect dest_host, set proper 'Host' header in upstream request */
|
||||
if (dest_host != "")
|
||||
{
|
||||
/* absolute url, replace 'Host' header */
|
||||
std::string h = dest_host;
|
||||
if (dest_port != 0 && dest_port != 80)
|
||||
h += ":" + std::to_string(dest_port);
|
||||
m_ClientRequest.UpdateHeader("Host", h);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto h = m_ClientRequest.GetHeader ("Host");
|
||||
if (h.length () > 0)
|
||||
{
|
||||
/* relative url and 'Host' header provided. transparent proxy mode? */
|
||||
i2p::http::URL u;
|
||||
std::string t = "http://" + h;
|
||||
u.parse(t);
|
||||
dest_host = u.host;
|
||||
dest_port = u.port;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* relative url and missing 'Host' header */
|
||||
GenericProxyError("Invalid request", "Can't detect destination host from request");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/* check dest_host really exists and inside I2P network */
|
||||
i2p::data::IdentHash identHash;
|
||||
if (str_rmatch(dest_host, ".i2p")) {
|
||||
if (!i2p::client::context.GetAddressBook ().GetIdentHash (dest_host, identHash)) {
|
||||
HostNotFound(dest_host);
|
||||
return true; /* request processed */
|
||||
}
|
||||
} else {
|
||||
std::string outproxyUrl; i2p::config::GetOption("httpproxy.outproxy", outproxyUrl);
|
||||
if(outproxyUrl.size()) {
|
||||
LogPrint (eLogDebug, "HTTPProxy: use outproxy ", outproxyUrl);
|
||||
if(m_ProxyURL.parse(outproxyUrl))
|
||||
ForwardToUpstreamProxy();
|
||||
else
|
||||
GenericProxyError("Outproxy failure", "bad outproxy settings");
|
||||
} else {
|
||||
LogPrint (eLogWarning, "HTTPProxy: outproxy failure for ", dest_host, ": no outprxy enabled");
|
||||
std::string message = "Host" + dest_host + "not inside I2P network, but outproxy is not enabled";
|
||||
GenericProxyError("Outproxy failure", message.c_str());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* make relative url */
|
||||
m_RequestURL.schema = "";
|
||||
m_RequestURL.host = "";
|
||||
m_ClientRequest.uri = m_RequestURL.to_string();
|
||||
|
||||
/* drop original request from recv buffer */
|
||||
m_recv_buf.erase(0, m_req_len);
|
||||
/* build new buffer from modified request and data from original request */
|
||||
m_send_buf = m_ClientRequest.to_string();
|
||||
m_send_buf.append(m_recv_buf);
|
||||
/* connect to destination */
|
||||
LogPrint(eLogDebug, "HTTPProxy: connecting to host ", dest_host, ":", dest_port);
|
||||
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
|
||||
shared_from_this(), std::placeholders::_1), dest_host, dest_port);
|
||||
return true;
|
||||
}
|
||||
|
||||
void HTTPReqHandler::ForwardToUpstreamProxy()
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: forward to upstream");
|
||||
// build http requset
|
||||
|
||||
m_ClientRequestURL = m_RequestURL;
|
||||
LogPrint(eLogDebug, "HTTPProxy: ", m_ClientRequestURL.host);
|
||||
m_ClientRequestURL.schema = "";
|
||||
m_ClientRequestURL.host = "";
|
||||
m_ClientRequest.uri = m_ClientRequestURL.to_string();
|
||||
|
||||
m_ClientRequest.write(m_ClientRequestBuffer);
|
||||
m_ClientRequestBuffer << m_recv_buf.substr(m_req_len);
|
||||
|
||||
// assume http if empty schema
|
||||
if (m_ProxyURL.schema == "" || m_ProxyURL.schema == "http") {
|
||||
// handle upstream http proxy
|
||||
if (!m_ProxyURL.port) m_ProxyURL.port = 80;
|
||||
boost::asio::ip::tcp::resolver::query q(m_ProxyURL.host, std::to_string(m_ProxyURL.port));
|
||||
m_proxy_resolver.async_resolve(q, std::bind(&HTTPReqHandler::HandleUpstreamProxyResolved, this, std::placeholders::_1, std::placeholders::_2, [&](boost::asio::ip::tcp::endpoint ep) {
|
||||
m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamHTTPProxyConnect, this, std::placeholders::_1));
|
||||
}));
|
||||
} else if (m_ProxyURL.schema == "socks") {
|
||||
// handle upstream socks proxy
|
||||
if (!m_ProxyURL.port) m_ProxyURL.port = 9050; // default to tor default if not specified
|
||||
boost::asio::ip::tcp::resolver::query q(m_ProxyURL.host, std::to_string(m_ProxyURL.port));
|
||||
m_proxy_resolver.async_resolve(q, std::bind(&HTTPReqHandler::HandleUpstreamProxyResolved, this, std::placeholders::_1, std::placeholders::_2, [&](boost::asio::ip::tcp::endpoint ep) {
|
||||
m_proxysock->async_connect(ep, std::bind(&HTTPReqHandler::HandleUpstreamSocksProxyConnect, this, std::placeholders::_1));
|
||||
}));
|
||||
} else {
|
||||
// unknown type, complain
|
||||
GenericProxyError("unknown outproxy url", m_ProxyURL.to_string().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleUpstreamProxyResolved(const boost::system::error_code & ec, boost::asio::ip::tcp::resolver::iterator it, ProxyResolvedHandler handler)
|
||||
{
|
||||
if(ec) GenericProxyError("cannot resolve upstream proxy", ec.message().c_str());
|
||||
else handler(*it);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleUpstreamSocksProxyConnect(const boost::system::error_code & ec)
|
||||
{
|
||||
if(!ec) {
|
||||
if(m_RequestURL.host.size() > 255) {
|
||||
GenericProxyError("hostname too long", m_RequestURL.host.c_str());
|
||||
return;
|
||||
}
|
||||
uint16_t port = m_RequestURL.port;
|
||||
if(!port) port = 80;
|
||||
LogPrint(eLogDebug, "HTTPProxy: connected to socks upstream");
|
||||
|
||||
std::string host = m_RequestURL.host;
|
||||
std::size_t reqsize = 0;
|
||||
m_socks_buf[0] = '\x04';
|
||||
m_socks_buf[1] = 1;
|
||||
htobe16buf(m_socks_buf+2, port);
|
||||
m_socks_buf[4] = 0;
|
||||
m_socks_buf[5] = 0;
|
||||
m_socks_buf[6] = 0;
|
||||
m_socks_buf[7] = 1;
|
||||
// user id
|
||||
m_socks_buf[8] = 'i';
|
||||
m_socks_buf[9] = '2';
|
||||
m_socks_buf[10] = 'p';
|
||||
m_socks_buf[11] = 'd';
|
||||
m_socks_buf[12] = 0;
|
||||
reqsize += 13;
|
||||
memcpy(m_socks_buf+ reqsize, host.c_str(), host.size());
|
||||
reqsize += host.size();
|
||||
m_socks_buf[++reqsize] = 0;
|
||||
boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_socks_buf, reqsize), boost::asio::transfer_all(), std::bind(&HTTPReqHandler::HandleSocksProxySendHandshake, this, std::placeholders::_1, std::placeholders::_2));
|
||||
} else GenericProxyError("cannot connect to upstream socks proxy", ec.message().c_str());
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleSocksProxySendHandshake(const boost::system::error_code & ec, std::size_t bytes_transferred)
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: upstream socks handshake sent");
|
||||
if(ec) GenericProxyError("Cannot negotiate with socks proxy", ec.message().c_str());
|
||||
else m_proxysock->async_read_some(boost::asio::buffer(m_socks_buf, 8), std::bind(&HTTPReqHandler::HandleSocksProxyReply, this, std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandoverToUpstreamProxy()
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: handover to socks proxy");
|
||||
auto connection = std::make_shared<i2p::client::TCPIPPipe>(GetOwner(), m_proxysock, m_sock);
|
||||
m_sock = nullptr;
|
||||
m_proxysock = nullptr;
|
||||
GetOwner()->AddHandler(connection);
|
||||
connection->Start();
|
||||
Terminate();
|
||||
}
|
||||
|
||||
void HTTPReqHandler::SocksProxySuccess()
|
||||
{
|
||||
if(m_ClientRequest.method == "CONNECT") {
|
||||
m_ClientResponse.code = 200;
|
||||
m_send_buf = m_ClientResponse.to_string();
|
||||
boost::asio::async_write(*m_sock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&] (const boost::system::error_code & ec, std::size_t transferred) {
|
||||
if(ec) GenericProxyError("socks proxy error", ec.message().c_str());
|
||||
else HandoverToUpstreamProxy();
|
||||
});
|
||||
} else {
|
||||
m_send_buf = m_ClientRequestBuffer.str();
|
||||
LogPrint(eLogDebug, "HTTPProxy: send ", m_send_buf.size(), " bytes");
|
||||
boost::asio::async_write(*m_proxysock, boost::asio::buffer(m_send_buf), boost::asio::transfer_all(), [&](const boost::system::error_code & ec, std::size_t transferred) {
|
||||
if(ec) GenericProxyError("failed to send request to upstream", ec.message().c_str());
|
||||
else HandoverToUpstreamProxy();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleSocksProxyReply(const boost::system::error_code & ec, std::size_t bytes_transferred)
|
||||
{
|
||||
if(!ec)
|
||||
{
|
||||
if(m_socks_buf[1] == 90) {
|
||||
// success
|
||||
SocksProxySuccess();
|
||||
} else {
|
||||
std::stringstream ss;
|
||||
ss << "error code: ";
|
||||
ss << (int) m_socks_buf[1];
|
||||
std::string msg = ss.str();
|
||||
GenericProxyError("Socks Proxy error", msg.c_str());
|
||||
}
|
||||
}
|
||||
else GenericProxyError("No Reply From socks proxy", ec.message().c_str());
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec)
|
||||
{
|
||||
if(!ec) {
|
||||
LogPrint(eLogDebug, "HTTPProxy: connected to http upstream");
|
||||
GenericProxyError("cannot connect", "http out proxy not implemented");
|
||||
} else GenericProxyError("cannot connect to upstream http proxy", ec.message().c_str());
|
||||
}
|
||||
|
||||
/* will be called after some data received from client */
|
||||
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes, recv buf: ", m_recv_buf.length(), ", send buf: ", m_send_buf.length());
|
||||
if(ecode)
|
||||
{
|
||||
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
|
||||
Terminate();
|
||||
return;
|
||||
}
|
||||
|
||||
m_recv_buf.append(reinterpret_cast<const char *>(m_recv_chunk), len);
|
||||
if (HandleRequest()) {
|
||||
m_recv_buf.clear();
|
||||
return;
|
||||
}
|
||||
AsyncSockRead();
|
||||
}
|
||||
|
||||
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (ecode)
|
||||
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
|
||||
Terminate();
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (!stream) {
|
||||
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
|
||||
GenericProxyError("Host is down", "Can't create connection to requested host, it may be down");
|
||||
return;
|
||||
}
|
||||
if (Kill())
|
||||
return;
|
||||
LogPrint (eLogDebug, "HTTPProxy: Created new I2PTunnel stream, sSID=", stream->GetSendStreamID(), ", rSID=", stream->GetRecvStreamID());
|
||||
auto connection = std::make_shared<i2p::client::I2PClientTunnelConnectionHTTP>(GetOwner(), m_sock, stream);
|
||||
GetOwner()->AddHandler (connection);
|
||||
connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_send_buf.data()), m_send_buf.length());
|
||||
Done (shared_from_this());
|
||||
}
|
||||
|
||||
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
|
||||
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
|
||||
{
|
||||
return std::make_shared<HTTPReqHandler> (this, socket);
|
||||
}
|
||||
} // http
|
||||
} // i2p
|
21
libi2pd_client/HTTPProxy.h
Normal file
21
libi2pd_client/HTTPProxy.h
Normal file
|
@ -0,0 +1,21 @@
|
|||
#ifndef HTTP_PROXY_H__
|
||||
#define HTTP_PROXY_H__
|
||||
|
||||
namespace i2p {
|
||||
namespace proxy {
|
||||
class HTTPProxy: public i2p::client::TCPIPAcceptor
|
||||
{
|
||||
public:
|
||||
|
||||
HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination = nullptr);
|
||||
~HTTPProxy() {};
|
||||
|
||||
protected:
|
||||
// Implements TCPIPAcceptor
|
||||
std::shared_ptr<i2p::client::I2PServiceHandler> CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket);
|
||||
const char* GetName() { return "HTTP Proxy"; }
|
||||
};
|
||||
} // http
|
||||
} // i2p
|
||||
|
||||
#endif
|
744
libi2pd_client/I2CP.cpp
Normal file
744
libi2pd_client/I2CP.cpp
Normal file
|
@ -0,0 +1,744 @@
|
|||
/*
|
||||
* Copyright (c) 2013-2016, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
* See full license text in LICENSE file at top of project tree
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <openssl/rand.h>
|
||||
#include "I2PEndian.h"
|
||||
#include "Log.h"
|
||||
#include "Timestamp.h"
|
||||
#include "LeaseSet.h"
|
||||
#include "ClientContext.h"
|
||||
#include "Transports.h"
|
||||
#include "Signature.h"
|
||||
#include "I2CP.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
|
||||
I2CPDestination::I2CPDestination (std::shared_ptr<I2CPSession> owner, std::shared_ptr<const i2p::data::IdentityEx> identity, bool isPublic, const std::map<std::string, std::string>& params):
|
||||
LeaseSetDestination (isPublic, ¶ms), m_Owner (owner), m_Identity (identity)
|
||||
{
|
||||
}
|
||||
|
||||
void I2CPDestination::SetEncryptionPrivateKey (const uint8_t * key)
|
||||
{
|
||||
memcpy (m_EncryptionPrivateKey, key, 256);
|
||||
}
|
||||
|
||||
void I2CPDestination::HandleDataMessage (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint32_t length = bufbe32toh (buf);
|
||||
if (length > len - 4) length = len - 4;
|
||||
m_Owner->SendMessagePayloadMessage (buf + 4, length);
|
||||
}
|
||||
|
||||
void I2CPDestination::CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels)
|
||||
{
|
||||
i2p::data::LocalLeaseSet ls (m_Identity, m_EncryptionPrivateKey, tunnels); // we don't care about encryption key
|
||||
m_LeaseSetExpirationTime = ls.GetExpirationTime ();
|
||||
uint8_t * leases = ls.GetLeases ();
|
||||
leases[-1] = tunnels.size ();
|
||||
htobe16buf (leases - 3, m_Owner->GetSessionID ());
|
||||
size_t l = 2/*sessionID*/ + 1/*num leases*/ + i2p::data::LEASE_SIZE*tunnels.size ();
|
||||
m_Owner->SendI2CPMessage (I2CP_REQUEST_VARIABLE_LEASESET_MESSAGE, leases - 3, l);
|
||||
}
|
||||
|
||||
void I2CPDestination::LeaseSetCreated (const uint8_t * buf, size_t len)
|
||||
{
|
||||
auto ls = new i2p::data::LocalLeaseSet (m_Identity, buf, len);
|
||||
ls->SetExpirationTime (m_LeaseSetExpirationTime);
|
||||
SetLeaseSet (ls);
|
||||
}
|
||||
|
||||
void I2CPDestination::SendMsgTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash& ident, uint32_t nonce)
|
||||
{
|
||||
auto msg = NewI2NPMessage ();
|
||||
uint8_t * buf = msg->GetPayload ();
|
||||
htobe32buf (buf, len);
|
||||
memcpy (buf + 4, payload, len);
|
||||
msg->len += len + 4;
|
||||
msg->FillI2NPMessageHeader (eI2NPData);
|
||||
auto s = GetSharedFromThis ();
|
||||
auto remote = FindLeaseSet (ident);
|
||||
if (remote)
|
||||
{
|
||||
GetService ().post (
|
||||
[s, msg, remote, nonce]()
|
||||
{
|
||||
bool sent = s->SendMsg (msg, remote);
|
||||
s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
RequestDestination (ident,
|
||||
[s, msg, nonce](std::shared_ptr<i2p::data::LeaseSet> ls)
|
||||
{
|
||||
if (ls)
|
||||
{
|
||||
bool sent = s->SendMsg (msg, ls);
|
||||
s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
|
||||
}
|
||||
else
|
||||
s->m_Owner->SendMessageStatusMessage (nonce, eI2CPMessageStatusNoLeaseSet);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
bool I2CPDestination::SendMsg (std::shared_ptr<I2NPMessage> msg, std::shared_ptr<const i2p::data::LeaseSet> remote)
|
||||
{
|
||||
auto remoteSession = GetRoutingSession (remote, true);
|
||||
if (!remoteSession)
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: Failed to create remote session");
|
||||
return false;
|
||||
}
|
||||
auto path = remoteSession->GetSharedRoutingPath ();
|
||||
std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
|
||||
std::shared_ptr<const i2p::data::Lease> remoteLease;
|
||||
if (path)
|
||||
{
|
||||
if (!remoteSession->CleanupUnconfirmedTags ()) // no stuck tags
|
||||
{
|
||||
outboundTunnel = path->outboundTunnel;
|
||||
remoteLease = path->remoteLease;
|
||||
}
|
||||
else
|
||||
remoteSession->SetSharedRoutingPath (nullptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
outboundTunnel = GetTunnelPool ()->GetNextOutboundTunnel ();
|
||||
auto leases = remote->GetNonExpiredLeases ();
|
||||
if (!leases.empty ())
|
||||
remoteLease = leases[rand () % leases.size ()];
|
||||
if (remoteLease && outboundTunnel)
|
||||
remoteSession->SetSharedRoutingPath (std::make_shared<i2p::garlic::GarlicRoutingPath> (
|
||||
i2p::garlic::GarlicRoutingPath{outboundTunnel, remoteLease, 10000, 0, 0})); // 10 secs RTT
|
||||
else
|
||||
remoteSession->SetSharedRoutingPath (nullptr);
|
||||
}
|
||||
if (remoteLease && outboundTunnel)
|
||||
{
|
||||
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
|
||||
auto garlic = remoteSession->WrapSingleMessage (msg);
|
||||
msgs.push_back (i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
i2p::tunnel::eDeliveryTypeTunnel,
|
||||
remoteLease->tunnelGateway, remoteLease->tunnelID,
|
||||
garlic
|
||||
});
|
||||
outboundTunnel->SendTunnelDataMsg (msgs);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (outboundTunnel)
|
||||
LogPrint (eLogWarning, "I2CP: Failed to send message. All leases expired");
|
||||
else
|
||||
LogPrint (eLogWarning, "I2CP: Failed to send message. No outbound tunnels");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
I2CPSession::I2CPSession (I2CPServer& owner, std::shared_ptr<proto::socket> socket):
|
||||
m_Owner (owner), m_Socket (socket), m_Payload (nullptr),
|
||||
m_SessionID (0xFFFF), m_MessageID (0), m_IsSendAccepted (true)
|
||||
{
|
||||
}
|
||||
|
||||
I2CPSession::~I2CPSession ()
|
||||
{
|
||||
delete[] m_Payload;
|
||||
}
|
||||
|
||||
void I2CPSession::Start ()
|
||||
{
|
||||
ReadProtocolByte ();
|
||||
}
|
||||
|
||||
void I2CPSession::Stop ()
|
||||
{
|
||||
Terminate ();
|
||||
}
|
||||
|
||||
void I2CPSession::ReadProtocolByte ()
|
||||
{
|
||||
if (m_Socket)
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
m_Socket->async_read_some (boost::asio::buffer (m_Header, 1),
|
||||
[s](const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (!ecode && bytes_transferred > 0 && s->m_Header[0] == I2CP_PROTOCOL_BYTE)
|
||||
s->ReceiveHeader ();
|
||||
else
|
||||
s->Terminate ();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::ReceiveHeader ()
|
||||
{
|
||||
boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Header, I2CP_HEADER_SIZE),
|
||||
boost::asio::transfer_all (),
|
||||
std::bind (&I2CPSession::HandleReceivedHeader, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void I2CPSession::HandleReceivedHeader (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
Terminate ();
|
||||
else
|
||||
{
|
||||
m_PayloadLen = bufbe32toh (m_Header + I2CP_HEADER_LENGTH_OFFSET);
|
||||
if (m_PayloadLen > 0)
|
||||
{
|
||||
m_Payload = new uint8_t[m_PayloadLen];
|
||||
ReceivePayload ();
|
||||
}
|
||||
else // no following payload
|
||||
{
|
||||
HandleMessage ();
|
||||
ReceiveHeader (); // next message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::ReceivePayload ()
|
||||
{
|
||||
boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Payload, m_PayloadLen),
|
||||
boost::asio::transfer_all (),
|
||||
std::bind (&I2CPSession::HandleReceivedPayload, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void I2CPSession::HandleReceivedPayload (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
Terminate ();
|
||||
else
|
||||
{
|
||||
HandleMessage ();
|
||||
delete[] m_Payload;
|
||||
m_Payload = nullptr;
|
||||
m_PayloadLen = 0;
|
||||
ReceiveHeader (); // next message
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::HandleMessage ()
|
||||
{
|
||||
auto handler = m_Owner.GetMessagesHandlers ()[m_Header[I2CP_HEADER_TYPE_OFFSET]];
|
||||
if (handler)
|
||||
(this->*handler)(m_Payload, m_PayloadLen);
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: Unknown I2CP messsage ", (int)m_Header[I2CP_HEADER_TYPE_OFFSET]);
|
||||
}
|
||||
|
||||
void I2CPSession::Terminate ()
|
||||
{
|
||||
if (m_Destination)
|
||||
{
|
||||
m_Destination->Stop ();
|
||||
m_Destination = nullptr;
|
||||
}
|
||||
if (m_Socket)
|
||||
{
|
||||
m_Socket->close ();
|
||||
m_Socket = nullptr;
|
||||
}
|
||||
m_Owner.RemoveSession (GetSessionID ());
|
||||
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " terminated");
|
||||
}
|
||||
|
||||
void I2CPSession::SendI2CPMessage (uint8_t type, const uint8_t * payload, size_t len)
|
||||
{
|
||||
auto socket = m_Socket;
|
||||
if (socket)
|
||||
{
|
||||
auto l = len + I2CP_HEADER_SIZE;
|
||||
uint8_t * buf = new uint8_t[l];
|
||||
htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len);
|
||||
buf[I2CP_HEADER_TYPE_OFFSET] = type;
|
||||
memcpy (buf + I2CP_HEADER_SIZE, payload, len);
|
||||
boost::asio::async_write (*socket, boost::asio::buffer (buf, l), boost::asio::transfer_all (),
|
||||
std::bind(&I2CPSession::HandleI2CPMessageSent, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, buf));
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: Can't write to the socket");
|
||||
}
|
||||
|
||||
void I2CPSession::HandleI2CPMessageSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, const uint8_t * buf)
|
||||
{
|
||||
delete[] buf;
|
||||
if (ecode && ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
|
||||
std::string I2CPSession::ExtractString (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint8_t l = buf[0];
|
||||
if (l > len) l = len;
|
||||
return std::string ((const char *)(buf + 1), l);
|
||||
}
|
||||
|
||||
size_t I2CPSession::PutString (uint8_t * buf, size_t len, const std::string& str)
|
||||
{
|
||||
auto l = str.length ();
|
||||
if (l + 1 >= len) l = len - 1;
|
||||
if (l > 255) l = 255; // 1 byte max
|
||||
buf[0] = l;
|
||||
memcpy (buf + 1, str.c_str (), l);
|
||||
return l + 1;
|
||||
}
|
||||
|
||||
void I2CPSession::ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping)
|
||||
// TODO: move to Base.cpp
|
||||
{
|
||||
size_t offset = 0;
|
||||
while (offset < len)
|
||||
{
|
||||
std::string param = ExtractString (buf + offset, len - offset);
|
||||
offset += param.length () + 1;
|
||||
if (buf[offset] != '=')
|
||||
{
|
||||
LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead '=' after ", param);
|
||||
break;
|
||||
}
|
||||
offset++;
|
||||
|
||||
std::string value = ExtractString (buf + offset, len - offset);
|
||||
offset += value.length () + 1;
|
||||
if (buf[offset] != ';')
|
||||
{
|
||||
LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead ';' after ", value);
|
||||
break;
|
||||
}
|
||||
offset++;
|
||||
mapping.insert (std::make_pair (param, value));
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::GetDateMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
// get version
|
||||
auto version = ExtractString (buf, len);
|
||||
auto l = version.length () + 1 + 8;
|
||||
uint8_t * payload = new uint8_t[l];
|
||||
// set date
|
||||
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
htobe64buf (payload, ts);
|
||||
// echo vesrion back
|
||||
PutString (payload + 8, l - 8, version);
|
||||
SendI2CPMessage (I2CP_SET_DATE_MESSAGE, payload, l);
|
||||
delete[] payload;
|
||||
}
|
||||
|
||||
void I2CPSession::CreateSessionMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
RAND_bytes ((uint8_t *)&m_SessionID, 2);
|
||||
m_Owner.InsertSession (shared_from_this ());
|
||||
auto identity = std::make_shared<i2p::data::IdentityEx>();
|
||||
size_t offset = identity->FromBuffer (buf, len);
|
||||
if (!offset)
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: create session maformed identity");
|
||||
SendSessionStatusMessage (3); // invalid
|
||||
return;
|
||||
}
|
||||
uint16_t optionsSize = bufbe16toh (buf + offset);
|
||||
offset += 2;
|
||||
if (optionsSize > len - offset)
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: options size ", optionsSize, "exceeds message size");
|
||||
SendSessionStatusMessage (3); // invalid
|
||||
return;
|
||||
}
|
||||
std::map<std::string, std::string> params;
|
||||
ExtractMapping (buf + offset, optionsSize, params);
|
||||
offset += optionsSize; // options
|
||||
if (params[I2CP_PARAM_MESSAGE_RELIABILITY] == "none") m_IsSendAccepted = false;
|
||||
|
||||
offset += 8; // date
|
||||
if (identity->Verify (buf, offset, buf + offset)) // signature
|
||||
{
|
||||
bool isPublic = true;
|
||||
if (params[I2CP_PARAM_DONT_PUBLISH_LEASESET] == "true") isPublic = false;
|
||||
if (!m_Destination)
|
||||
{
|
||||
m_Destination = std::make_shared<I2CPDestination>(shared_from_this (), identity, isPublic, params);
|
||||
SendSessionStatusMessage (1); // created
|
||||
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " created");
|
||||
m_Destination->Start ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: session already exists");
|
||||
SendSessionStatusMessage (4); // refused
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: create session signature verification falied");
|
||||
SendSessionStatusMessage (3); // invalid
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::DestroySessionMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
SendSessionStatusMessage (0); // destroy
|
||||
LogPrint (eLogDebug, "I2CP: session ", m_SessionID, " destroyed");
|
||||
if (m_Destination)
|
||||
{
|
||||
m_Destination->Stop ();
|
||||
m_Destination = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::ReconfigureSessionMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
// TODO: implement actual reconfiguration
|
||||
SendSessionStatusMessage (2); // updated
|
||||
}
|
||||
|
||||
void I2CPSession::SendSessionStatusMessage (uint8_t status)
|
||||
{
|
||||
uint8_t buf[3];
|
||||
htobe16buf (buf, m_SessionID);
|
||||
buf[2] = status;
|
||||
SendI2CPMessage (I2CP_SESSION_STATUS_MESSAGE, buf, 3);
|
||||
}
|
||||
|
||||
void I2CPSession::SendMessageStatusMessage (uint32_t nonce, I2CPMessageStatus status)
|
||||
{
|
||||
if (!nonce) return; // don't send status with zero nonce
|
||||
uint8_t buf[15];
|
||||
htobe16buf (buf, m_SessionID);
|
||||
htobe32buf (buf + 2, m_MessageID++);
|
||||
buf[6] = (uint8_t)status;
|
||||
memset (buf + 7, 0, 4); // size
|
||||
htobe32buf (buf + 11, nonce);
|
||||
SendI2CPMessage (I2CP_MESSAGE_STATUS_MESSAGE, buf, 15);
|
||||
}
|
||||
|
||||
void I2CPSession::CreateLeaseSetMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint16_t sessionID = bufbe16toh (buf);
|
||||
if (sessionID == m_SessionID)
|
||||
{
|
||||
size_t offset = 2;
|
||||
if (m_Destination)
|
||||
{
|
||||
offset += i2p::crypto::DSA_PRIVATE_KEY_LENGTH; // skip signing private key
|
||||
// we always assume this field as 20 bytes (DSA) regardless actual size
|
||||
// instead of
|
||||
//offset += m_Destination->GetIdentity ()->GetSigningPrivateKeyLen ();
|
||||
m_Destination->SetEncryptionPrivateKey (buf + offset);
|
||||
offset += 256;
|
||||
m_Destination->LeaseSetCreated (buf + offset, len - offset);
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
|
||||
}
|
||||
|
||||
void I2CPSession::SendMessageMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint16_t sessionID = bufbe16toh (buf);
|
||||
if (sessionID == m_SessionID)
|
||||
{
|
||||
size_t offset = 2;
|
||||
if (m_Destination)
|
||||
{
|
||||
i2p::data::IdentityEx identity;
|
||||
size_t identsize = identity.FromBuffer (buf + offset, len - offset);
|
||||
if (identsize)
|
||||
{
|
||||
offset += identsize;
|
||||
uint32_t payloadLen = bufbe32toh (buf + offset);
|
||||
if (payloadLen + offset <= len)
|
||||
{
|
||||
offset += 4;
|
||||
uint32_t nonce = bufbe32toh (buf + offset + payloadLen);
|
||||
if (m_IsSendAccepted)
|
||||
SendMessageStatusMessage (nonce, eI2CPMessageStatusAccepted); // accepted
|
||||
m_Destination->SendMsgTo (buf + offset, payloadLen, identity.GetIdentHash (), nonce);
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "I2CP: cannot send message, too big");
|
||||
}
|
||||
else
|
||||
LogPrint(eLogError, "I2CP: invalid identity");
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
|
||||
}
|
||||
|
||||
void I2CPSession::SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
SendMessageMessageHandler (buf, len - 8); // ignore flags(2) and expiration(6)
|
||||
}
|
||||
|
||||
void I2CPSession::HostLookupMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint16_t sessionID = bufbe16toh (buf);
|
||||
if (sessionID == m_SessionID || sessionID == 0xFFFF) // -1 means without session
|
||||
{
|
||||
uint32_t requestID = bufbe32toh (buf + 2);
|
||||
//uint32_t timeout = bufbe32toh (buf + 6);
|
||||
i2p::data::IdentHash ident;
|
||||
switch (buf[10])
|
||||
{
|
||||
case 0: // hash
|
||||
ident = i2p::data::IdentHash (buf + 11);
|
||||
break;
|
||||
case 1: // address
|
||||
{
|
||||
auto name = ExtractString (buf + 11, len - 11);
|
||||
if (!i2p::client::context.GetAddressBook ().GetIdentHash (name, ident))
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: address ", name, " not found");
|
||||
SendHostReplyMessage (requestID, nullptr);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LogPrint (eLogError, "I2CP: request type ", (int)buf[10], " is not supported");
|
||||
SendHostReplyMessage (requestID, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
std::shared_ptr<LeaseSetDestination> destination = m_Destination;
|
||||
if(!destination) destination = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (destination)
|
||||
{
|
||||
auto ls = destination->FindLeaseSet (ident);
|
||||
if (ls)
|
||||
SendHostReplyMessage (requestID, ls->GetIdentity ());
|
||||
else
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
destination->RequestDestination (ident,
|
||||
[s, requestID](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
|
||||
{
|
||||
s->SendHostReplyMessage (requestID, leaseSet ? leaseSet->GetIdentity () : nullptr);
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
SendHostReplyMessage (requestID, nullptr);
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: unexpected sessionID ", sessionID);
|
||||
}
|
||||
|
||||
void I2CPSession::SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity)
|
||||
{
|
||||
if (identity)
|
||||
{
|
||||
size_t l = identity->GetFullLen () + 7;
|
||||
uint8_t * buf = new uint8_t[l];
|
||||
htobe16buf (buf, m_SessionID);
|
||||
htobe32buf (buf + 2, requestID);
|
||||
buf[6] = 0; // result code
|
||||
identity->ToBuffer (buf + 7, l - 7);
|
||||
SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, l);
|
||||
delete[] buf;
|
||||
}
|
||||
else
|
||||
{
|
||||
uint8_t buf[7];
|
||||
htobe16buf (buf, m_SessionID);
|
||||
htobe32buf (buf + 2, requestID);
|
||||
buf[6] = 1; // result code
|
||||
SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, 7);
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPSession::DestLookupMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (m_Destination)
|
||||
{
|
||||
auto ls = m_Destination->FindLeaseSet (buf);
|
||||
if (ls)
|
||||
{
|
||||
auto l = ls->GetIdentity ()->GetFullLen ();
|
||||
uint8_t * identBuf = new uint8_t[l];
|
||||
ls->GetIdentity ()->ToBuffer (identBuf, l);
|
||||
SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
|
||||
delete[] identBuf;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
i2p::data::IdentHash ident (buf);
|
||||
m_Destination->RequestDestination (ident,
|
||||
[s, ident](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
|
||||
{
|
||||
if (leaseSet) // found
|
||||
{
|
||||
auto l = leaseSet->GetIdentity ()->GetFullLen ();
|
||||
uint8_t * identBuf = new uint8_t[l];
|
||||
leaseSet->GetIdentity ()->ToBuffer (identBuf, l);
|
||||
s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
|
||||
delete[] identBuf;
|
||||
}
|
||||
else
|
||||
s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, ident, 32); // not found
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, buf, 32);
|
||||
}
|
||||
|
||||
void I2CPSession::GetBandwidthLimitsMessageHandler (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint8_t limits[64];
|
||||
memset (limits, 0, 64);
|
||||
htobe32buf (limits, i2p::transport::transports.GetInBandwidth ()); // inbound
|
||||
htobe32buf (limits + 4, i2p::transport::transports.GetOutBandwidth ()); // outbound
|
||||
SendI2CPMessage (I2CP_BANDWIDTH_LIMITS_MESSAGE, limits, 64);
|
||||
}
|
||||
|
||||
void I2CPSession::SendMessagePayloadMessage (const uint8_t * payload, size_t len)
|
||||
{
|
||||
// we don't use SendI2CPMessage to eliminate additional copy
|
||||
auto l = len + 10 + I2CP_HEADER_SIZE;
|
||||
uint8_t * buf = new uint8_t[l];
|
||||
htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len + 10);
|
||||
buf[I2CP_HEADER_TYPE_OFFSET] = I2CP_MESSAGE_PAYLOAD_MESSAGE;
|
||||
htobe16buf (buf + I2CP_HEADER_SIZE, m_SessionID);
|
||||
htobe32buf (buf + I2CP_HEADER_SIZE + 2, m_MessageID++);
|
||||
htobe32buf (buf + I2CP_HEADER_SIZE + 6, len);
|
||||
memcpy (buf + I2CP_HEADER_SIZE + 10, payload, len);
|
||||
boost::asio::async_write (*m_Socket, boost::asio::buffer (buf, l), boost::asio::transfer_all (),
|
||||
std::bind(&I2CPSession::HandleI2CPMessageSent, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, buf));
|
||||
}
|
||||
|
||||
I2CPServer::I2CPServer (const std::string& interface, int port):
|
||||
m_IsRunning (false), m_Thread (nullptr),
|
||||
m_Acceptor (m_Service,
|
||||
#ifdef ANDROID
|
||||
I2CPSession::proto::endpoint(std::string (1, '\0') + interface)) // leading 0 for abstract address
|
||||
#else
|
||||
I2CPSession::proto::endpoint(boost::asio::ip::address::from_string(interface), port))
|
||||
#endif
|
||||
{
|
||||
memset (m_MessagesHandlers, 0, sizeof (m_MessagesHandlers));
|
||||
m_MessagesHandlers[I2CP_GET_DATE_MESSAGE] = &I2CPSession::GetDateMessageHandler;
|
||||
m_MessagesHandlers[I2CP_CREATE_SESSION_MESSAGE] = &I2CPSession::CreateSessionMessageHandler;
|
||||
m_MessagesHandlers[I2CP_DESTROY_SESSION_MESSAGE] = &I2CPSession::DestroySessionMessageHandler;
|
||||
m_MessagesHandlers[I2CP_RECONFIGURE_SESSION_MESSAGE] = &I2CPSession::ReconfigureSessionMessageHandler;
|
||||
m_MessagesHandlers[I2CP_CREATE_LEASESET_MESSAGE] = &I2CPSession::CreateLeaseSetMessageHandler;
|
||||
m_MessagesHandlers[I2CP_SEND_MESSAGE_MESSAGE] = &I2CPSession::SendMessageMessageHandler;
|
||||
m_MessagesHandlers[I2CP_SEND_MESSAGE_EXPIRES_MESSAGE] = &I2CPSession::SendMessageExpiresMessageHandler;
|
||||
m_MessagesHandlers[I2CP_HOST_LOOKUP_MESSAGE] = &I2CPSession::HostLookupMessageHandler;
|
||||
m_MessagesHandlers[I2CP_DEST_LOOKUP_MESSAGE] = &I2CPSession::DestLookupMessageHandler;
|
||||
m_MessagesHandlers[I2CP_GET_BANDWIDTH_LIMITS_MESSAGE] = &I2CPSession::GetBandwidthLimitsMessageHandler;
|
||||
}
|
||||
|
||||
I2CPServer::~I2CPServer ()
|
||||
{
|
||||
if (m_IsRunning)
|
||||
Stop ();
|
||||
}
|
||||
|
||||
void I2CPServer::Start ()
|
||||
{
|
||||
Accept ();
|
||||
m_IsRunning = true;
|
||||
m_Thread = new std::thread (std::bind (&I2CPServer::Run, this));
|
||||
}
|
||||
|
||||
void I2CPServer::Stop ()
|
||||
{
|
||||
m_IsRunning = false;
|
||||
m_Acceptor.cancel ();
|
||||
for (auto& it: m_Sessions)
|
||||
it.second->Stop ();
|
||||
m_Sessions.clear ();
|
||||
m_Service.stop ();
|
||||
if (m_Thread)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPServer::Run ()
|
||||
{
|
||||
while (m_IsRunning)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Service.run ();
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: runtime exception: ", ex.what ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void I2CPServer::Accept ()
|
||||
{
|
||||
auto newSocket = std::make_shared<I2CPSession::proto::socket> (m_Service);
|
||||
m_Acceptor.async_accept (*newSocket, std::bind (&I2CPServer::HandleAccept, this,
|
||||
std::placeholders::_1, newSocket));
|
||||
}
|
||||
|
||||
void I2CPServer::HandleAccept(const boost::system::error_code& ecode,
|
||||
std::shared_ptr<I2CPSession::proto::socket> socket)
|
||||
{
|
||||
if (!ecode && socket)
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
auto ep = socket->remote_endpoint (ec);
|
||||
if (!ec)
|
||||
{
|
||||
LogPrint (eLogDebug, "I2CP: new connection from ", ep);
|
||||
auto session = std::make_shared<I2CPSession>(*this, socket);
|
||||
session->Start ();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: incoming connection error ", ec.message ());
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2CP: accept error: ", ecode.message ());
|
||||
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Accept ();
|
||||
}
|
||||
|
||||
bool I2CPServer::InsertSession (std::shared_ptr<I2CPSession> session)
|
||||
{
|
||||
if (!session) return false;
|
||||
if (!m_Sessions.insert({session->GetSessionID (), session}).second)
|
||||
{
|
||||
LogPrint (eLogError, "I2CP: duplicate session id ", session->GetSessionID ());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void I2CPServer::RemoveSession (uint16_t sessionID)
|
||||
{
|
||||
m_Sessions.erase (sessionID);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
209
libi2pd_client/I2CP.h
Normal file
209
libi2pd_client/I2CP.h
Normal file
|
@ -0,0 +1,209 @@
|
|||
/*
|
||||
* Copyright (c) 2013-2016, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
* See full license text in LICENSE file at top of project tree
|
||||
*/
|
||||
|
||||
#ifndef I2CP_H__
|
||||
#define I2CP_H__
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <map>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Destination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const uint8_t I2CP_PROTOCOL_BYTE = 0x2A;
|
||||
const size_t I2CP_SESSION_BUFFER_SIZE = 4096;
|
||||
|
||||
const size_t I2CP_HEADER_LENGTH_OFFSET = 0;
|
||||
const size_t I2CP_HEADER_TYPE_OFFSET = I2CP_HEADER_LENGTH_OFFSET + 4;
|
||||
const size_t I2CP_HEADER_SIZE = I2CP_HEADER_TYPE_OFFSET + 1;
|
||||
|
||||
const uint8_t I2CP_GET_DATE_MESSAGE = 32;
|
||||
const uint8_t I2CP_SET_DATE_MESSAGE = 33;
|
||||
const uint8_t I2CP_CREATE_SESSION_MESSAGE = 1;
|
||||
const uint8_t I2CP_RECONFIGURE_SESSION_MESSAGE = 2;
|
||||
const uint8_t I2CP_SESSION_STATUS_MESSAGE = 20;
|
||||
const uint8_t I2CP_DESTROY_SESSION_MESSAGE = 3;
|
||||
const uint8_t I2CP_REQUEST_VARIABLE_LEASESET_MESSAGE = 37;
|
||||
const uint8_t I2CP_CREATE_LEASESET_MESSAGE = 4;
|
||||
const uint8_t I2CP_SEND_MESSAGE_MESSAGE = 5;
|
||||
const uint8_t I2CP_SEND_MESSAGE_EXPIRES_MESSAGE = 36;
|
||||
const uint8_t I2CP_MESSAGE_PAYLOAD_MESSAGE = 31;
|
||||
const uint8_t I2CP_MESSAGE_STATUS_MESSAGE = 22;
|
||||
const uint8_t I2CP_HOST_LOOKUP_MESSAGE = 38;
|
||||
const uint8_t I2CP_HOST_REPLY_MESSAGE = 39;
|
||||
const uint8_t I2CP_DEST_LOOKUP_MESSAGE = 34;
|
||||
const uint8_t I2CP_DEST_REPLY_MESSAGE = 35;
|
||||
const uint8_t I2CP_GET_BANDWIDTH_LIMITS_MESSAGE = 8;
|
||||
const uint8_t I2CP_BANDWIDTH_LIMITS_MESSAGE = 23;
|
||||
|
||||
enum I2CPMessageStatus
|
||||
{
|
||||
eI2CPMessageStatusAccepted = 1,
|
||||
eI2CPMessageStatusGuaranteedSuccess = 4,
|
||||
eI2CPMessageStatusGuaranteedFailure = 5,
|
||||
eI2CPMessageStatusNoLeaseSet = 21
|
||||
};
|
||||
|
||||
// params
|
||||
const char I2CP_PARAM_DONT_PUBLISH_LEASESET[] = "i2cp.dontPublishLeaseSet";
|
||||
const char I2CP_PARAM_MESSAGE_RELIABILITY[] = "i2cp.messageReliability";
|
||||
|
||||
class I2CPSession;
|
||||
class I2CPDestination: public LeaseSetDestination
|
||||
{
|
||||
public:
|
||||
|
||||
I2CPDestination (std::shared_ptr<I2CPSession> owner, std::shared_ptr<const i2p::data::IdentityEx> identity, bool isPublic, const std::map<std::string, std::string>& params);
|
||||
|
||||
void SetEncryptionPrivateKey (const uint8_t * key);
|
||||
void LeaseSetCreated (const uint8_t * buf, size_t len); // called from I2CPSession
|
||||
void SendMsgTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash& ident, uint32_t nonce); // called from I2CPSession
|
||||
|
||||
// implements LocalDestination
|
||||
const uint8_t * GetEncryptionPrivateKey () const { return m_EncryptionPrivateKey; };
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetIdentity () const { return m_Identity; };
|
||||
|
||||
protected:
|
||||
|
||||
// I2CP
|
||||
void HandleDataMessage (const uint8_t * buf, size_t len);
|
||||
void CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<I2CPDestination> GetSharedFromThis ()
|
||||
{ return std::static_pointer_cast<I2CPDestination>(shared_from_this ()); }
|
||||
bool SendMsg (std::shared_ptr<I2NPMessage> msg, std::shared_ptr<const i2p::data::LeaseSet> remote);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<I2CPSession> m_Owner;
|
||||
std::shared_ptr<const i2p::data::IdentityEx> m_Identity;
|
||||
uint8_t m_EncryptionPrivateKey[256];
|
||||
uint64_t m_LeaseSetExpirationTime;
|
||||
};
|
||||
|
||||
class I2CPServer;
|
||||
class I2CPSession: public std::enable_shared_from_this<I2CPSession>
|
||||
{
|
||||
public:
|
||||
|
||||
#ifdef ANDROID
|
||||
typedef boost::asio::local::stream_protocol proto;
|
||||
#else
|
||||
typedef boost::asio::ip::tcp proto;
|
||||
#endif
|
||||
|
||||
I2CPSession (I2CPServer& owner, std::shared_ptr<proto::socket> socket);
|
||||
|
||||
~I2CPSession ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
uint16_t GetSessionID () const { return m_SessionID; };
|
||||
std::shared_ptr<const I2CPDestination> GetDestination () const { return m_Destination; };
|
||||
|
||||
// called from I2CPDestination
|
||||
void SendI2CPMessage (uint8_t type, const uint8_t * payload, size_t len);
|
||||
void SendMessagePayloadMessage (const uint8_t * payload, size_t len);
|
||||
void SendMessageStatusMessage (uint32_t nonce, I2CPMessageStatus status);
|
||||
|
||||
// message handlers
|
||||
void GetDateMessageHandler (const uint8_t * buf, size_t len);
|
||||
void CreateSessionMessageHandler (const uint8_t * buf, size_t len);
|
||||
void DestroySessionMessageHandler (const uint8_t * buf, size_t len);
|
||||
void ReconfigureSessionMessageHandler (const uint8_t * buf, size_t len);
|
||||
void CreateLeaseSetMessageHandler (const uint8_t * buf, size_t len);
|
||||
void SendMessageMessageHandler (const uint8_t * buf, size_t len);
|
||||
void SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len);
|
||||
void HostLookupMessageHandler (const uint8_t * buf, size_t len);
|
||||
void DestLookupMessageHandler (const uint8_t * buf, size_t len);
|
||||
void GetBandwidthLimitsMessageHandler (const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
void ReadProtocolByte ();
|
||||
void ReceiveHeader ();
|
||||
void HandleReceivedHeader (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void ReceivePayload ();
|
||||
void HandleReceivedPayload (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleMessage ();
|
||||
void Terminate ();
|
||||
|
||||
void HandleI2CPMessageSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, const uint8_t * buf);
|
||||
std::string ExtractString (const uint8_t * buf, size_t len);
|
||||
size_t PutString (uint8_t * buf, size_t len, const std::string& str);
|
||||
void ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping);
|
||||
|
||||
void SendSessionStatusMessage (uint8_t status);
|
||||
void SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity);
|
||||
|
||||
private:
|
||||
|
||||
I2CPServer& m_Owner;
|
||||
std::shared_ptr<proto::socket> m_Socket;
|
||||
uint8_t m_Header[I2CP_HEADER_SIZE], * m_Payload;
|
||||
size_t m_PayloadLen;
|
||||
|
||||
std::shared_ptr<I2CPDestination> m_Destination;
|
||||
uint16_t m_SessionID;
|
||||
uint32_t m_MessageID;
|
||||
bool m_IsSendAccepted;
|
||||
};
|
||||
typedef void (I2CPSession::*I2CPMessageHandler)(const uint8_t * buf, size_t len);
|
||||
|
||||
class I2CPServer
|
||||
{
|
||||
public:
|
||||
|
||||
I2CPServer (const std::string& interface, int port);
|
||||
~I2CPServer ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
|
||||
bool InsertSession (std::shared_ptr<I2CPSession> session);
|
||||
void RemoveSession (uint16_t sessionID);
|
||||
|
||||
private:
|
||||
|
||||
void Run ();
|
||||
|
||||
void Accept ();
|
||||
|
||||
void HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<I2CPSession::proto::socket> socket);
|
||||
|
||||
private:
|
||||
|
||||
I2CPMessageHandler m_MessagesHandlers[256];
|
||||
std::map<uint16_t, std::shared_ptr<I2CPSession> > m_Sessions;
|
||||
|
||||
bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
boost::asio::io_service m_Service;
|
||||
I2CPSession::proto::acceptor m_Acceptor;
|
||||
|
||||
public:
|
||||
|
||||
const decltype(m_MessagesHandlers)& GetMessagesHandlers () const { return m_MessagesHandlers; };
|
||||
|
||||
// for HTTP
|
||||
const decltype(m_Sessions)& GetSessions () const { return m_Sessions; };
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
216
libi2pd_client/I2PService.cpp
Normal file
216
libi2pd_client/I2PService.cpp
Normal file
|
@ -0,0 +1,216 @@
|
|||
#include "Destination.h"
|
||||
#include "Identity.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PService.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
static const i2p::data::SigningKeyType I2P_SERVICE_DEFAULT_KEY_TYPE = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256;
|
||||
|
||||
I2PService::I2PService (std::shared_ptr<ClientDestination> localDestination):
|
||||
m_LocalDestination (localDestination ? localDestination :
|
||||
i2p::client::context.CreateNewLocalDestination (false, I2P_SERVICE_DEFAULT_KEY_TYPE))
|
||||
{
|
||||
}
|
||||
|
||||
I2PService::I2PService (i2p::data::SigningKeyType kt):
|
||||
m_LocalDestination (i2p::client::context.CreateNewLocalDestination (false, kt))
|
||||
{
|
||||
}
|
||||
|
||||
void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port) {
|
||||
assert(streamRequestComplete);
|
||||
i2p::data::IdentHash identHash;
|
||||
if (i2p::client::context.GetAddressBook ().GetIdentHash (dest, identHash))
|
||||
m_LocalDestination->CreateStream (streamRequestComplete, identHash, port);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "I2PService: Remote destination not found: ", dest);
|
||||
streamRequestComplete (nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
TCPIPPipe::TCPIPPipe(I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> upstream, std::shared_ptr<boost::asio::ip::tcp::socket> downstream) : I2PServiceHandler(owner), m_up(upstream), m_down(downstream)
|
||||
{
|
||||
boost::asio::socket_base::receive_buffer_size option(TCP_IP_PIPE_BUFFER_SIZE);
|
||||
upstream->set_option(option);
|
||||
downstream->set_option(option);
|
||||
}
|
||||
|
||||
TCPIPPipe::~TCPIPPipe()
|
||||
{
|
||||
Terminate();
|
||||
}
|
||||
|
||||
void TCPIPPipe::Start()
|
||||
{
|
||||
AsyncReceiveUpstream();
|
||||
AsyncReceiveDownstream();
|
||||
}
|
||||
|
||||
void TCPIPPipe::Terminate()
|
||||
{
|
||||
if(Kill()) return;
|
||||
if (m_up) {
|
||||
if (m_up->is_open()) {
|
||||
m_up->close();
|
||||
}
|
||||
m_up = nullptr;
|
||||
}
|
||||
if (m_down) {
|
||||
if (m_down->is_open()) {
|
||||
m_down->close();
|
||||
}
|
||||
m_down = nullptr;
|
||||
}
|
||||
Done(shared_from_this());
|
||||
}
|
||||
|
||||
void TCPIPPipe::AsyncReceiveUpstream()
|
||||
{
|
||||
if (m_up) {
|
||||
m_up->async_read_some(boost::asio::buffer(m_upstream_to_down_buf, TCP_IP_PIPE_BUFFER_SIZE),
|
||||
std::bind(&TCPIPPipe::HandleUpstreamReceived, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
} else {
|
||||
LogPrint(eLogError, "TCPIPPipe: upstream receive: no socket");
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::AsyncReceiveDownstream()
|
||||
{
|
||||
if (m_down) {
|
||||
m_down->async_read_some(boost::asio::buffer(m_downstream_to_up_buf, TCP_IP_PIPE_BUFFER_SIZE),
|
||||
std::bind(&TCPIPPipe::HandleDownstreamReceived, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
} else {
|
||||
LogPrint(eLogError, "TCPIPPipe: downstream receive: no socket");
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::UpstreamWrite(size_t len)
|
||||
{
|
||||
if (m_up) {
|
||||
LogPrint(eLogDebug, "TCPIPPipe: upstream: ", (int) len, " bytes written");
|
||||
boost::asio::async_write(*m_up, boost::asio::buffer(m_upstream_buf, len),
|
||||
boost::asio::transfer_all(),
|
||||
std::bind(&TCPIPPipe::HandleUpstreamWrite,
|
||||
shared_from_this(),
|
||||
std::placeholders::_1)
|
||||
);
|
||||
} else {
|
||||
LogPrint(eLogError, "TCPIPPipe: upstream write: no socket");
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::DownstreamWrite(size_t len)
|
||||
{
|
||||
if (m_down) {
|
||||
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) len, " bytes written");
|
||||
boost::asio::async_write(*m_down, boost::asio::buffer(m_downstream_buf, len),
|
||||
boost::asio::transfer_all(),
|
||||
std::bind(&TCPIPPipe::HandleDownstreamWrite,
|
||||
shared_from_this(),
|
||||
std::placeholders::_1)
|
||||
);
|
||||
} else {
|
||||
LogPrint(eLogError, "TCPIPPipe: downstream write: no socket");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
|
||||
{
|
||||
LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) bytes_transfered, " bytes received");
|
||||
if (ecode) {
|
||||
LogPrint(eLogError, "TCPIPPipe: downstream read error:" , ecode.message());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate();
|
||||
} else {
|
||||
if (bytes_transfered > 0 ) {
|
||||
memcpy(m_upstream_buf, m_downstream_to_up_buf, bytes_transfered);
|
||||
}
|
||||
UpstreamWrite(bytes_transfered);
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) {
|
||||
if (ecode) {
|
||||
LogPrint(eLogError, "TCPIPPipe: downstream write error:" , ecode.message());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate();
|
||||
} else {
|
||||
AsyncReceiveUpstream();
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) {
|
||||
if (ecode) {
|
||||
LogPrint(eLogError, "TCPIPPipe: upstream write error:" , ecode.message());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate();
|
||||
} else {
|
||||
AsyncReceiveDownstream();
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered)
|
||||
{
|
||||
LogPrint(eLogDebug, "TCPIPPipe: upstream ", (int)bytes_transfered, " bytes received");
|
||||
if (ecode) {
|
||||
LogPrint(eLogError, "TCPIPPipe: upstream read error:" , ecode.message());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate();
|
||||
} else {
|
||||
if (bytes_transfered > 0 ) {
|
||||
memcpy(m_downstream_buf, m_upstream_to_down_buf, bytes_transfered);
|
||||
}
|
||||
DownstreamWrite(bytes_transfered);
|
||||
}
|
||||
}
|
||||
|
||||
void TCPIPAcceptor::Start ()
|
||||
{
|
||||
m_Acceptor.listen ();
|
||||
Accept ();
|
||||
}
|
||||
|
||||
void TCPIPAcceptor::Stop ()
|
||||
{
|
||||
m_Acceptor.close();
|
||||
m_Timer.cancel ();
|
||||
ClearHandlers();
|
||||
}
|
||||
|
||||
void TCPIPAcceptor::Accept ()
|
||||
{
|
||||
auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (GetService ());
|
||||
m_Acceptor.async_accept (*newSocket, std::bind (&TCPIPAcceptor::HandleAccept, this,
|
||||
std::placeholders::_1, newSocket));
|
||||
}
|
||||
|
||||
void TCPIPAcceptor::HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<boost::asio::ip::tcp::socket> socket)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
LogPrint(eLogDebug, "I2PService: ", GetName(), " accepted");
|
||||
auto handler = CreateHandler(socket);
|
||||
if (handler)
|
||||
{
|
||||
AddHandler(handler);
|
||||
handler->Handle();
|
||||
}
|
||||
else
|
||||
socket->close();
|
||||
Accept();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
LogPrint (eLogError, "I2PService: ", GetName(), " closing socket on accept because: ", ecode.message ());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
138
libi2pd_client/I2PService.h
Normal file
138
libi2pd_client/I2PService.h
Normal file
|
@ -0,0 +1,138 @@
|
|||
#ifndef I2PSERVICE_H__
|
||||
#define I2PSERVICE_H__
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Destination.h"
|
||||
#include "Identity.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
class I2PServiceHandler;
|
||||
class I2PService
|
||||
{
|
||||
public:
|
||||
I2PService (std::shared_ptr<ClientDestination> localDestination = nullptr);
|
||||
I2PService (i2p::data::SigningKeyType kt);
|
||||
virtual ~I2PService () { ClearHandlers (); }
|
||||
|
||||
inline void AddHandler (std::shared_ptr<I2PServiceHandler> conn)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.insert(conn);
|
||||
}
|
||||
inline void RemoveHandler (std::shared_ptr<I2PServiceHandler> conn)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.erase(conn);
|
||||
}
|
||||
inline void ClearHandlers ()
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.clear();
|
||||
}
|
||||
|
||||
inline std::shared_ptr<ClientDestination> GetLocalDestination () { return m_LocalDestination; }
|
||||
inline std::shared_ptr<const ClientDestination> GetLocalDestination () const { return m_LocalDestination; }
|
||||
inline void SetLocalDestination (std::shared_ptr<ClientDestination> dest) { m_LocalDestination = dest; }
|
||||
void CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port = 0);
|
||||
|
||||
inline boost::asio::io_service& GetService () { return m_LocalDestination->GetService (); }
|
||||
|
||||
virtual void Start () = 0;
|
||||
virtual void Stop () = 0;
|
||||
|
||||
virtual const char* GetName() { return "Generic I2P Service"; }
|
||||
private:
|
||||
|
||||
std::shared_ptr<ClientDestination> m_LocalDestination;
|
||||
std::unordered_set<std::shared_ptr<I2PServiceHandler> > m_Handlers;
|
||||
std::mutex m_HandlersMutex;
|
||||
};
|
||||
|
||||
/*Simple interface for I2PHandlers, allows detection of finalization amongst other things */
|
||||
class I2PServiceHandler
|
||||
{
|
||||
public:
|
||||
I2PServiceHandler(I2PService * parent) : m_Service(parent), m_Dead(false) { }
|
||||
virtual ~I2PServiceHandler() { }
|
||||
//If you override this make sure you call it from the children
|
||||
virtual void Handle() {}; //Start handling the socket
|
||||
protected:
|
||||
// Call when terminating or handing over to avoid race conditions
|
||||
inline bool Kill () { return m_Dead.exchange(true); }
|
||||
// Call to know if the handler is dead
|
||||
inline bool Dead () { return m_Dead; }
|
||||
// Call when done to clean up (make sure Kill is called first)
|
||||
inline void Done (std::shared_ptr<I2PServiceHandler> me) { if(m_Service) m_Service->RemoveHandler(me); }
|
||||
// Call to talk with the owner
|
||||
inline I2PService * GetOwner() { return m_Service; }
|
||||
private:
|
||||
I2PService *m_Service;
|
||||
std::atomic<bool> m_Dead; //To avoid cleaning up multiple times
|
||||
};
|
||||
|
||||
const size_t TCP_IP_PIPE_BUFFER_SIZE = 8192 * 8;
|
||||
|
||||
// bidirectional pipe for 2 tcp/ip sockets
|
||||
class TCPIPPipe: public I2PServiceHandler, public std::enable_shared_from_this<TCPIPPipe> {
|
||||
public:
|
||||
TCPIPPipe(I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> upstream, std::shared_ptr<boost::asio::ip::tcp::socket> downstream);
|
||||
~TCPIPPipe();
|
||||
void Start();
|
||||
protected:
|
||||
void Terminate();
|
||||
void AsyncReceiveUpstream();
|
||||
void AsyncReceiveDownstream();
|
||||
void HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transferred);
|
||||
void HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transferred);
|
||||
void HandleUpstreamWrite(const boost::system::error_code & ecode);
|
||||
void HandleDownstreamWrite(const boost::system::error_code & ecode);
|
||||
void UpstreamWrite(size_t len);
|
||||
void DownstreamWrite(size_t len);
|
||||
private:
|
||||
uint8_t m_upstream_to_down_buf[TCP_IP_PIPE_BUFFER_SIZE], m_downstream_to_up_buf[TCP_IP_PIPE_BUFFER_SIZE];
|
||||
uint8_t m_upstream_buf[TCP_IP_PIPE_BUFFER_SIZE], m_downstream_buf[TCP_IP_PIPE_BUFFER_SIZE];
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_up, m_down;
|
||||
};
|
||||
|
||||
/* TODO: support IPv6 too */
|
||||
//This is a service that listens for connections on the IP network and interacts with I2P
|
||||
class TCPIPAcceptor: public I2PService
|
||||
{
|
||||
public:
|
||||
TCPIPAcceptor (const std::string& address, int port, std::shared_ptr<ClientDestination> localDestination = nullptr) :
|
||||
I2PService(localDestination),
|
||||
m_Acceptor (GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::address::from_string(address), port)),
|
||||
m_Timer (GetService ()) {}
|
||||
TCPIPAcceptor (const std::string& address, int port, i2p::data::SigningKeyType kt) :
|
||||
I2PService(kt),
|
||||
m_Acceptor (GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::address::from_string(address), port)),
|
||||
m_Timer (GetService ()) {}
|
||||
virtual ~TCPIPAcceptor () { TCPIPAcceptor::Stop(); }
|
||||
//If you override this make sure you call it from the children
|
||||
void Start ();
|
||||
//If you override this make sure you call it from the children
|
||||
void Stop ();
|
||||
|
||||
const boost::asio::ip::tcp::acceptor& GetAcceptor () const { return m_Acceptor; };
|
||||
|
||||
virtual const char* GetName() { return "Generic TCP/IP accepting daemon"; }
|
||||
|
||||
protected:
|
||||
virtual std::shared_ptr<I2PServiceHandler> CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket) = 0;
|
||||
private:
|
||||
void Accept();
|
||||
void HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<boost::asio::ip::tcp::socket> socket);
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
876
libi2pd_client/I2PTunnel.cpp
Normal file
876
libi2pd_client/I2PTunnel.cpp
Normal file
|
@ -0,0 +1,876 @@
|
|||
#include <cassert>
|
||||
#include "Base.h"
|
||||
#include "Log.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PTunnel.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
|
||||
/** set standard socket options */
|
||||
static void I2PTunnelSetSocketOptions(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
|
||||
{
|
||||
if (socket && socket->is_open())
|
||||
{
|
||||
boost::asio::socket_base::receive_buffer_size option(I2P_TUNNEL_CONNECTION_BUFFER_SIZE);
|
||||
socket->set_option(option);
|
||||
}
|
||||
}
|
||||
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
std::shared_ptr<const i2p::data::LeaseSet> leaseSet, int port):
|
||||
I2PServiceHandler(owner), m_Socket (socket), m_RemoteEndpoint (socket->remote_endpoint ()),
|
||||
m_IsQuiet (true)
|
||||
{
|
||||
m_Stream = GetOwner()->GetLocalDestination ()->CreateStream (leaseSet, port);
|
||||
}
|
||||
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket, std::shared_ptr<i2p::stream::Stream> stream):
|
||||
I2PServiceHandler(owner), m_Socket (socket), m_Stream (stream),
|
||||
m_RemoteEndpoint (socket->remote_endpoint ()), m_IsQuiet (true)
|
||||
{
|
||||
}
|
||||
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::asio::ip::tcp::endpoint& target, bool quiet):
|
||||
I2PServiceHandler(owner), m_Socket (socket), m_Stream (stream),
|
||||
m_RemoteEndpoint (target), m_IsQuiet (quiet)
|
||||
{
|
||||
}
|
||||
|
||||
I2PTunnelConnection::~I2PTunnelConnection ()
|
||||
{
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::I2PConnect (const uint8_t * msg, size_t len)
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
if (msg)
|
||||
m_Stream->Send (msg, len); // connect and send
|
||||
else
|
||||
m_Stream->Send (m_Buffer, 0); // connect
|
||||
}
|
||||
StreamReceive ();
|
||||
Receive ();
|
||||
}
|
||||
|
||||
static boost::asio::ip::address GetLoopbackAddressFor(const i2p::data::IdentHash & addr)
|
||||
{
|
||||
boost::asio::ip::address_v4::bytes_type bytes;
|
||||
const uint8_t * ident = addr;
|
||||
bytes[0] = 127;
|
||||
memcpy (bytes.data ()+1, ident, 3);
|
||||
boost::asio::ip::address ourIP = boost::asio::ip::address_v4 (bytes);
|
||||
return ourIP;
|
||||
}
|
||||
|
||||
static void MapToLoopback(const std::shared_ptr<boost::asio::ip::tcp::socket> & sock, const i2p::data::IdentHash & addr)
|
||||
{
|
||||
|
||||
// bind to 127.x.x.x address
|
||||
// where x.x.x are first three bytes from ident
|
||||
auto ourIP = GetLoopbackAddressFor(addr);
|
||||
sock->bind (boost::asio::ip::tcp::endpoint (ourIP, 0));
|
||||
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Connect (bool isUniqueLocal)
|
||||
{
|
||||
I2PTunnelSetSocketOptions(m_Socket);
|
||||
if (m_Socket)
|
||||
{
|
||||
#ifdef __linux__
|
||||
if (isUniqueLocal && m_RemoteEndpoint.address ().is_v4 () &&
|
||||
m_RemoteEndpoint.address ().to_v4 ().to_bytes ()[0] == 127)
|
||||
{
|
||||
m_Socket->open (boost::asio::ip::tcp::v4 ());
|
||||
auto ident = m_Stream->GetRemoteIdentity()->GetIdentHash();
|
||||
MapToLoopback(m_Socket, ident);
|
||||
}
|
||||
#endif
|
||||
m_Socket->async_connect (m_RemoteEndpoint, std::bind (&I2PTunnelConnection::HandleConnect,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Terminate ()
|
||||
{
|
||||
if (Kill()) return;
|
||||
if (m_Stream)
|
||||
{
|
||||
m_Stream->Close ();
|
||||
m_Stream.reset ();
|
||||
}
|
||||
boost::system::error_code ec;
|
||||
m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); // avoid RST
|
||||
m_Socket->close ();
|
||||
|
||||
Done(shared_from_this ());
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Receive ()
|
||||
{
|
||||
m_Socket->async_read_some (boost::asio::buffer(m_Buffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
|
||||
std::bind(&I2PTunnelConnection::HandleReceived, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
LogPrint (eLogError, "I2PTunnel: read error: ", ecode.message ());
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
m_Stream->AsyncSend (m_Buffer, bytes_transferred,
|
||||
[s](const boost::system::error_code& ecode)
|
||||
{
|
||||
if (!ecode)
|
||||
s->Receive ();
|
||||
else
|
||||
s->Terminate ();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::HandleWrite (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "I2PTunnel: write error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
StreamReceive ();
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::StreamReceive ()
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
if (m_Stream->GetStatus () == i2p::stream::eStreamStatusNew ||
|
||||
m_Stream->GetStatus () == i2p::stream::eStreamStatusOpen) // regular
|
||||
{
|
||||
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
|
||||
std::bind (&I2PTunnelConnection::HandleStreamReceive, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2),
|
||||
I2P_TUNNEL_CONNECTION_MAX_IDLE);
|
||||
}
|
||||
else // closed by peer
|
||||
{
|
||||
// get remaning data
|
||||
auto len = m_Stream->ReadSome (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE);
|
||||
if (len > 0) // still some data
|
||||
Write (m_StreamBuffer, len);
|
||||
else // no more data
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::HandleStreamReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
LogPrint (eLogError, "I2PTunnel: stream read error: ", ecode.message ());
|
||||
if (bytes_transferred > 0)
|
||||
Write (m_StreamBuffer, bytes_transferred); // postpone termination
|
||||
else if (ecode == boost::asio::error::timed_out && m_Stream && m_Stream->IsOpen ())
|
||||
StreamReceive ();
|
||||
else
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
Write (m_StreamBuffer, bytes_transferred);
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Write (const uint8_t * buf, size_t len)
|
||||
{
|
||||
boost::asio::async_write (*m_Socket, boost::asio::buffer (buf, len), boost::asio::transfer_all (),
|
||||
std::bind (&I2PTunnelConnection::HandleWrite, shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::HandleConnect (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "I2PTunnel: connect error: ", ecode.message ());
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogDebug, "I2PTunnel: connected");
|
||||
if (m_IsQuiet)
|
||||
StreamReceive ();
|
||||
else
|
||||
{
|
||||
// send destination first like received from I2P
|
||||
std::string dest = m_Stream->GetRemoteIdentity ()->ToBase64 ();
|
||||
dest += "\n";
|
||||
if(sizeof(m_StreamBuffer) >= dest.size()) {
|
||||
memcpy (m_StreamBuffer, dest.c_str (), dest.size ());
|
||||
}
|
||||
HandleStreamReceive (boost::system::error_code (), dest.size ());
|
||||
}
|
||||
Receive ();
|
||||
}
|
||||
}
|
||||
|
||||
void I2PClientTunnelConnectionHTTP::Write (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (m_HeaderSent)
|
||||
I2PTunnelConnection::Write (buf, len);
|
||||
else
|
||||
{
|
||||
m_InHeader.clear ();
|
||||
m_InHeader.write ((const char *)buf, len);
|
||||
std::string line;
|
||||
bool endOfHeader = false;
|
||||
while (!endOfHeader)
|
||||
{
|
||||
std::getline(m_InHeader, line);
|
||||
if (!m_InHeader.fail ())
|
||||
{
|
||||
if (line == "\r") endOfHeader = true;
|
||||
else
|
||||
{
|
||||
if (!m_ConnectionSent && !line.compare(0, 10, "Connection"))
|
||||
{
|
||||
m_OutHeader << "Connection: close\r\n";
|
||||
m_ConnectionSent = true;
|
||||
}
|
||||
else if (!m_ProxyConnectionSent && !line.compare(0, 16, "Proxy-Connection"))
|
||||
{
|
||||
m_OutHeader << "Proxy-Connection: close\r\n";
|
||||
m_ProxyConnectionSent = true;
|
||||
}
|
||||
else
|
||||
m_OutHeader << line << "\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
if (endOfHeader)
|
||||
{
|
||||
if (!m_ConnectionSent) m_OutHeader << "Connection: close\r\n";
|
||||
if (!m_ProxyConnectionSent) m_OutHeader << "Proxy-Connection: close\r\n";
|
||||
m_OutHeader << "\r\n"; // end of header
|
||||
m_OutHeader << m_InHeader.str ().substr (m_InHeader.tellg ()); // data right after header
|
||||
m_InHeader.str ("");
|
||||
m_HeaderSent = true;
|
||||
I2PTunnelConnection::Write ((uint8_t *)m_OutHeader.str ().c_str (), m_OutHeader.str ().length ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
I2PServerTunnelConnectionHTTP::I2PServerTunnelConnectionHTTP (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
const boost::asio::ip::tcp::endpoint& target, const std::string& host):
|
||||
I2PTunnelConnection (owner, stream, socket, target), m_Host (host), m_HeaderSent (false), m_From (stream->GetRemoteIdentity ())
|
||||
{
|
||||
}
|
||||
|
||||
void I2PServerTunnelConnectionHTTP::Write (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (m_HeaderSent)
|
||||
I2PTunnelConnection::Write (buf, len);
|
||||
else
|
||||
{
|
||||
m_InHeader.clear ();
|
||||
m_InHeader.write ((const char *)buf, len);
|
||||
std::string line;
|
||||
bool endOfHeader = false;
|
||||
while (!endOfHeader)
|
||||
{
|
||||
std::getline(m_InHeader, line);
|
||||
if (!m_InHeader.fail ())
|
||||
{
|
||||
if (line == "\r") endOfHeader = true;
|
||||
else
|
||||
{
|
||||
if (m_Host.length () > 0 && line.find ("Host:") != std::string::npos)
|
||||
m_OutHeader << "Host: " << m_Host << "\r\n"; // override host
|
||||
else
|
||||
m_OutHeader << line << "\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
// add X-I2P fields
|
||||
if (m_From)
|
||||
{
|
||||
m_OutHeader << X_I2P_DEST_B32 << ": " << context.GetAddressBook ().ToAddress(m_From->GetIdentHash ()) << "\r\n";
|
||||
m_OutHeader << X_I2P_DEST_HASH << ": " << m_From->GetIdentHash ().ToBase64 () << "\r\n";
|
||||
m_OutHeader << X_I2P_DEST_B64 << ": " << m_From->ToBase64 () << "\r\n";
|
||||
}
|
||||
|
||||
if (endOfHeader)
|
||||
{
|
||||
m_OutHeader << "\r\n"; // end of header
|
||||
m_OutHeader << m_InHeader.str ().substr (m_InHeader.tellg ()); // data right after header
|
||||
m_InHeader.str ("");
|
||||
m_HeaderSent = true;
|
||||
I2PTunnelConnection::Write ((uint8_t *)m_OutHeader.str ().c_str (), m_OutHeader.str ().length ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
I2PTunnelConnectionIRC::I2PTunnelConnectionIRC (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
const boost::asio::ip::tcp::endpoint& target, const std::string& webircpass):
|
||||
I2PTunnelConnection (owner, stream, socket, target), m_From (stream->GetRemoteIdentity ()),
|
||||
m_NeedsWebIrc (webircpass.length() ? true : false), m_WebircPass (webircpass)
|
||||
{
|
||||
}
|
||||
|
||||
void I2PTunnelConnectionIRC::Write (const uint8_t * buf, size_t len)
|
||||
{
|
||||
m_OutPacket.str ("");
|
||||
if (m_NeedsWebIrc)
|
||||
{
|
||||
m_NeedsWebIrc = false;
|
||||
m_OutPacket << "WEBIRC " << m_WebircPass << " cgiirc " << context.GetAddressBook ().ToAddress (m_From->GetIdentHash ()) << " " << GetSocket ()->local_endpoint ().address () << std::endl;
|
||||
}
|
||||
|
||||
m_InPacket.clear ();
|
||||
m_InPacket.write ((const char *)buf, len);
|
||||
|
||||
while (!m_InPacket.eof () && !m_InPacket.fail ())
|
||||
{
|
||||
std::string line;
|
||||
std::getline (m_InPacket, line);
|
||||
if (line.length () == 0 && m_InPacket.eof ())
|
||||
m_InPacket.str ("");
|
||||
auto pos = line.find ("USER");
|
||||
if (!pos) // start of line
|
||||
{
|
||||
pos = line.find (" ");
|
||||
pos++;
|
||||
pos = line.find (" ", pos);
|
||||
pos++;
|
||||
auto nextpos = line.find (" ", pos);
|
||||
m_OutPacket << line.substr (0, pos);
|
||||
m_OutPacket << context.GetAddressBook ().ToAddress (m_From->GetIdentHash ());
|
||||
m_OutPacket << line.substr (nextpos) << '\n';
|
||||
}
|
||||
else
|
||||
m_OutPacket << line << '\n';
|
||||
}
|
||||
I2PTunnelConnection::Write ((uint8_t *)m_OutPacket.str ().c_str (), m_OutPacket.str ().length ());
|
||||
}
|
||||
|
||||
|
||||
/* This handler tries to stablish a connection with the desired server and dies if it fails to do so */
|
||||
class I2PClientTunnelHandler: public I2PServiceHandler, public std::enable_shared_from_this<I2PClientTunnelHandler>
|
||||
{
|
||||
public:
|
||||
I2PClientTunnelHandler (I2PClientTunnel * parent, i2p::data::IdentHash destination,
|
||||
int destinationPort, std::shared_ptr<boost::asio::ip::tcp::socket> socket):
|
||||
I2PServiceHandler(parent), m_DestinationIdentHash(destination),
|
||||
m_DestinationPort (destinationPort), m_Socket(socket) {};
|
||||
void Handle();
|
||||
void Terminate();
|
||||
private:
|
||||
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
i2p::data::IdentHash m_DestinationIdentHash;
|
||||
int m_DestinationPort;
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_Socket;
|
||||
};
|
||||
|
||||
void I2PClientTunnelHandler::Handle()
|
||||
{
|
||||
GetOwner()->GetLocalDestination ()->CreateStream (
|
||||
std::bind (&I2PClientTunnelHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1),
|
||||
m_DestinationIdentHash, m_DestinationPort);
|
||||
}
|
||||
|
||||
void I2PClientTunnelHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
if (Kill()) return;
|
||||
LogPrint (eLogDebug, "I2PTunnel: new connection");
|
||||
auto connection = std::make_shared<I2PTunnelConnection>(GetOwner(), m_Socket, stream);
|
||||
GetOwner()->AddHandler (connection);
|
||||
connection->I2PConnect ();
|
||||
Done(shared_from_this());
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "I2PTunnel: Client Tunnel Issue when creating the stream, check the previous warnings for more info.");
|
||||
Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void I2PClientTunnelHandler::Terminate()
|
||||
{
|
||||
if (Kill()) return;
|
||||
if (m_Socket)
|
||||
{
|
||||
m_Socket->close();
|
||||
m_Socket = nullptr;
|
||||
}
|
||||
Done(shared_from_this());
|
||||
}
|
||||
|
||||
I2PClientTunnel::I2PClientTunnel (const std::string& name, const std::string& destination,
|
||||
const std::string& address, int port, std::shared_ptr<ClientDestination> localDestination, int destinationPort):
|
||||
TCPIPAcceptor (address, port, localDestination), m_Name (name), m_Destination (destination),
|
||||
m_DestinationIdentHash (nullptr), m_DestinationPort (destinationPort)
|
||||
{
|
||||
}
|
||||
|
||||
void I2PClientTunnel::Start ()
|
||||
{
|
||||
TCPIPAcceptor::Start ();
|
||||
GetIdentHash();
|
||||
}
|
||||
|
||||
void I2PClientTunnel::Stop ()
|
||||
{
|
||||
TCPIPAcceptor::Stop();
|
||||
auto *originalIdentHash = m_DestinationIdentHash;
|
||||
m_DestinationIdentHash = nullptr;
|
||||
delete originalIdentHash;
|
||||
}
|
||||
|
||||
/* HACK: maybe we should create a caching IdentHash provider in AddressBook */
|
||||
const i2p::data::IdentHash * I2PClientTunnel::GetIdentHash ()
|
||||
{
|
||||
if (!m_DestinationIdentHash)
|
||||
{
|
||||
i2p::data::IdentHash identHash;
|
||||
if (i2p::client::context.GetAddressBook ().GetIdentHash (m_Destination, identHash))
|
||||
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
|
||||
else
|
||||
LogPrint (eLogWarning, "I2PTunnel: Remote destination ", m_Destination, " not found");
|
||||
}
|
||||
return m_DestinationIdentHash;
|
||||
}
|
||||
|
||||
std::shared_ptr<I2PServiceHandler> I2PClientTunnel::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
|
||||
{
|
||||
const i2p::data::IdentHash *identHash = GetIdentHash();
|
||||
if (identHash)
|
||||
return std::make_shared<I2PClientTunnelHandler>(this, *identHash, m_DestinationPort, socket);
|
||||
else
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
I2PServerTunnel::I2PServerTunnel (const std::string& name, const std::string& address,
|
||||
int port, std::shared_ptr<ClientDestination> localDestination, int inport, bool gzip):
|
||||
I2PService (localDestination), m_IsUniqueLocal(true), m_Name (name), m_Address (address), m_Port (port), m_IsAccessList (false)
|
||||
{
|
||||
m_PortDestination = localDestination->CreateStreamingDestination (inport > 0 ? inport : port, gzip);
|
||||
}
|
||||
|
||||
void I2PServerTunnel::Start ()
|
||||
{
|
||||
m_Endpoint.port (m_Port);
|
||||
boost::system::error_code ec;
|
||||
auto addr = boost::asio::ip::address::from_string (m_Address, ec);
|
||||
if (!ec)
|
||||
{
|
||||
m_Endpoint.address (addr);
|
||||
Accept ();
|
||||
}
|
||||
else
|
||||
{
|
||||
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(GetService ());
|
||||
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (m_Address, ""),
|
||||
std::bind (&I2PServerTunnel::HandleResolve, this,
|
||||
std::placeholders::_1, std::placeholders::_2, resolver));
|
||||
}
|
||||
}
|
||||
|
||||
void I2PServerTunnel::Stop ()
|
||||
{
|
||||
ClearHandlers ();
|
||||
}
|
||||
|
||||
void I2PServerTunnel::HandleResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
|
||||
std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
auto addr = (*it).endpoint ().address ();
|
||||
LogPrint (eLogInfo, "I2PTunnel: server tunnel ", (*it).host_name (), " has been resolved to ", addr);
|
||||
m_Endpoint.address (addr);
|
||||
Accept ();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2PTunnel: Unable to resolve server tunnel address: ", ecode.message ());
|
||||
}
|
||||
|
||||
void I2PServerTunnel::SetAccessList (const std::set<i2p::data::IdentHash>& accessList)
|
||||
{
|
||||
m_AccessList = accessList;
|
||||
m_IsAccessList = true;
|
||||
}
|
||||
|
||||
void I2PServerTunnel::Accept ()
|
||||
{
|
||||
if (m_PortDestination)
|
||||
m_PortDestination->SetAcceptor (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
|
||||
|
||||
auto localDestination = GetLocalDestination ();
|
||||
if (localDestination)
|
||||
{
|
||||
if (!localDestination->IsAcceptingStreams ()) // set it as default if not set yet
|
||||
localDestination->AcceptStreams (std::bind (&I2PServerTunnel::HandleAccept, this, std::placeholders::_1));
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "I2PTunnel: Local destination not set for server tunnel");
|
||||
}
|
||||
|
||||
void I2PServerTunnel::HandleAccept (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
if (m_IsAccessList)
|
||||
{
|
||||
if (!m_AccessList.count (stream->GetRemoteIdentity ()->GetIdentHash ()))
|
||||
{
|
||||
LogPrint (eLogWarning, "I2PTunnel: Address ", stream->GetRemoteIdentity ()->GetIdentHash ().ToBase32 (), " is not in white list. Incoming connection dropped");
|
||||
stream->Close ();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// new connection
|
||||
auto conn = CreateI2PConnection (stream);
|
||||
AddHandler (conn);
|
||||
conn->Connect (m_IsUniqueLocal);
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<I2PTunnelConnection> I2PServerTunnel::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
return std::make_shared<I2PTunnelConnection> (this, stream, std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint ());
|
||||
|
||||
}
|
||||
|
||||
I2PServerTunnelHTTP::I2PServerTunnelHTTP (const std::string& name, const std::string& address,
|
||||
int port, std::shared_ptr<ClientDestination> localDestination,
|
||||
const std::string& host, int inport, bool gzip):
|
||||
I2PServerTunnel (name, address, port, localDestination, inport, gzip),
|
||||
m_Host (host)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<I2PTunnelConnection> I2PServerTunnelHTTP::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
return std::make_shared<I2PServerTunnelConnectionHTTP> (this, stream,
|
||||
std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint (), m_Host);
|
||||
}
|
||||
|
||||
I2PServerTunnelIRC::I2PServerTunnelIRC (const std::string& name, const std::string& address,
|
||||
int port, std::shared_ptr<ClientDestination> localDestination,
|
||||
const std::string& webircpass, int inport, bool gzip):
|
||||
I2PServerTunnel (name, address, port, localDestination, inport, gzip),
|
||||
m_WebircPass (webircpass)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<I2PTunnelConnection> I2PServerTunnelIRC::CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
return std::make_shared<I2PTunnelConnectionIRC> (this, stream, std::make_shared<boost::asio::ip::tcp::socket> (GetService ()), GetEndpoint (), this->m_WebircPass);
|
||||
}
|
||||
|
||||
void I2PUDPServerTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_SessionsMutex);
|
||||
auto session = ObtainUDPSession(from, toPort, fromPort);
|
||||
session->IPSocket.send_to(boost::asio::buffer(buf, len), m_RemoteEndpoint);
|
||||
session->LastActivity = i2p::util::GetMillisecondsSinceEpoch();
|
||||
}
|
||||
|
||||
void I2PUDPServerTunnel::ExpireStale(const uint64_t delta) {
|
||||
std::lock_guard<std::mutex> lock(m_SessionsMutex);
|
||||
uint64_t now = i2p::util::GetMillisecondsSinceEpoch();
|
||||
auto itr = m_Sessions.begin();
|
||||
while(itr != m_Sessions.end()) {
|
||||
if(now - (*itr)->LastActivity >= delta )
|
||||
itr = m_Sessions.erase(itr);
|
||||
else
|
||||
++itr;
|
||||
}
|
||||
}
|
||||
|
||||
void I2PUDPClientTunnel::ExpireStale(const uint64_t delta) {
|
||||
std::lock_guard<std::mutex> lock(m_SessionsMutex);
|
||||
uint64_t now = i2p::util::GetMillisecondsSinceEpoch();
|
||||
std::vector<uint16_t> removePorts;
|
||||
for (const auto & s : m_Sessions) {
|
||||
if (now - s.second.second >= delta)
|
||||
removePorts.push_back(s.first);
|
||||
}
|
||||
for(auto port : removePorts) {
|
||||
m_Sessions.erase(port);
|
||||
}
|
||||
}
|
||||
|
||||
UDPSessionPtr I2PUDPServerTunnel::ObtainUDPSession(const i2p::data::IdentityEx& from, uint16_t localPort, uint16_t remotePort)
|
||||
{
|
||||
auto ih = from.GetIdentHash();
|
||||
for (auto & s : m_Sessions )
|
||||
{
|
||||
if ( s->Identity == ih)
|
||||
{
|
||||
/** found existing session */
|
||||
LogPrint(eLogDebug, "UDPServer: found session ", s->IPSocket.local_endpoint(), " ", ih.ToBase32());
|
||||
return s;
|
||||
}
|
||||
}
|
||||
boost::asio::ip::address addr;
|
||||
/** create new udp session */
|
||||
if(m_IsUniqueLocal && m_LocalAddress.is_loopback())
|
||||
{
|
||||
auto ident = from.GetIdentHash();
|
||||
addr = GetLoopbackAddressFor(ident);
|
||||
}
|
||||
else
|
||||
addr = m_LocalAddress;
|
||||
boost::asio::ip::udp::endpoint ep(addr, 0);
|
||||
m_Sessions.push_back(std::make_shared<UDPSession>(ep, m_LocalDest, m_RemoteEndpoint, &ih, localPort, remotePort));
|
||||
auto & back = m_Sessions.back();
|
||||
return back;
|
||||
}
|
||||
|
||||
UDPSession::UDPSession(boost::asio::ip::udp::endpoint localEndpoint,
|
||||
const std::shared_ptr<i2p::client::ClientDestination> & localDestination,
|
||||
boost::asio::ip::udp::endpoint endpoint, const i2p::data::IdentHash * to,
|
||||
uint16_t ourPort, uint16_t theirPort) :
|
||||
m_Destination(localDestination->GetDatagramDestination()),
|
||||
IPSocket(localDestination->GetService(), localEndpoint),
|
||||
SendEndpoint(endpoint),
|
||||
LastActivity(i2p::util::GetMillisecondsSinceEpoch()),
|
||||
LocalPort(ourPort),
|
||||
RemotePort(theirPort)
|
||||
{
|
||||
memcpy(Identity, to->data(), 32);
|
||||
Receive();
|
||||
}
|
||||
|
||||
|
||||
void UDPSession::Receive() {
|
||||
LogPrint(eLogDebug, "UDPSession: Receive");
|
||||
IPSocket.async_receive_from(boost::asio::buffer(m_Buffer, I2P_UDP_MAX_MTU),
|
||||
FromEndpoint, std::bind(&UDPSession::HandleReceived, this, std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void UDPSession::HandleReceived(const boost::system::error_code & ecode, std::size_t len)
|
||||
{
|
||||
if(!ecode)
|
||||
{
|
||||
LogPrint(eLogDebug, "UDPSession: forward ", len, "B from ", FromEndpoint);
|
||||
LastActivity = i2p::util::GetMillisecondsSinceEpoch();
|
||||
m_Destination->SendDatagramTo(m_Buffer, len, Identity, LocalPort, RemotePort);
|
||||
Receive();
|
||||
} else {
|
||||
LogPrint(eLogError, "UDPSession: ", ecode.message());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
I2PUDPServerTunnel::I2PUDPServerTunnel(const std::string & name, std::shared_ptr<i2p::client::ClientDestination> localDestination,
|
||||
boost::asio::ip::address localAddress, boost::asio::ip::udp::endpoint forwardTo, uint16_t port) :
|
||||
m_IsUniqueLocal(true),
|
||||
m_Name(name),
|
||||
m_LocalAddress(localAddress),
|
||||
m_RemoteEndpoint(forwardTo)
|
||||
{
|
||||
m_LocalDest = localDestination;
|
||||
m_LocalDest->Start();
|
||||
auto dgram = m_LocalDest->CreateDatagramDestination();
|
||||
dgram->SetReceiver(std::bind(&I2PUDPServerTunnel::HandleRecvFromI2P, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5));
|
||||
}
|
||||
|
||||
I2PUDPServerTunnel::~I2PUDPServerTunnel()
|
||||
{
|
||||
auto dgram = m_LocalDest->GetDatagramDestination();
|
||||
if (dgram) dgram->ResetReceiver();
|
||||
|
||||
LogPrint(eLogInfo, "UDPServer: done");
|
||||
}
|
||||
|
||||
void I2PUDPServerTunnel::Start() {
|
||||
m_LocalDest->Start();
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > I2PUDPServerTunnel::GetSessions()
|
||||
{
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > sessions;
|
||||
std::lock_guard<std::mutex> lock(m_SessionsMutex);
|
||||
|
||||
for ( UDPSessionPtr s : m_Sessions )
|
||||
{
|
||||
if (!s->m_Destination) continue;
|
||||
auto info = s->m_Destination->GetInfoForRemote(s->Identity);
|
||||
if(!info) continue;
|
||||
|
||||
auto sinfo = std::make_shared<DatagramSessionInfo>();
|
||||
sinfo->Name = m_Name;
|
||||
sinfo->LocalIdent = std::make_shared<i2p::data::IdentHash>(m_LocalDest->GetIdentHash().data());
|
||||
sinfo->RemoteIdent = std::make_shared<i2p::data::IdentHash>(s->Identity.data());
|
||||
sinfo->CurrentIBGW = info->IBGW;
|
||||
sinfo->CurrentOBEP = info->OBEP;
|
||||
sessions.push_back(sinfo);
|
||||
}
|
||||
return sessions;
|
||||
}
|
||||
|
||||
I2PUDPClientTunnel::I2PUDPClientTunnel(const std::string & name, const std::string &remoteDest,
|
||||
boost::asio::ip::udp::endpoint localEndpoint,
|
||||
std::shared_ptr<i2p::client::ClientDestination> localDestination,
|
||||
uint16_t remotePort) :
|
||||
m_Name(name),
|
||||
m_RemoteDest(remoteDest),
|
||||
m_LocalDest(localDestination),
|
||||
m_LocalEndpoint(localEndpoint),
|
||||
m_RemoteIdent(nullptr),
|
||||
m_ResolveThread(nullptr),
|
||||
m_LocalSocket(localDestination->GetService(), localEndpoint),
|
||||
RemotePort(remotePort),
|
||||
m_cancel_resolve(false)
|
||||
{
|
||||
auto dgram = m_LocalDest->CreateDatagramDestination();
|
||||
dgram->SetReceiver(std::bind(&I2PUDPClientTunnel::HandleRecvFromI2P, this,
|
||||
std::placeholders::_1, std::placeholders::_2,
|
||||
std::placeholders::_3, std::placeholders::_4,
|
||||
std::placeholders::_5));
|
||||
}
|
||||
|
||||
|
||||
|
||||
void I2PUDPClientTunnel::Start() {
|
||||
m_LocalDest->Start();
|
||||
if (m_ResolveThread == nullptr)
|
||||
m_ResolveThread = new std::thread(std::bind(&I2PUDPClientTunnel::TryResolving, this));
|
||||
RecvFromLocal();
|
||||
}
|
||||
|
||||
void I2PUDPClientTunnel::RecvFromLocal()
|
||||
{
|
||||
m_LocalSocket.async_receive_from(boost::asio::buffer(m_RecvBuff, I2P_UDP_MAX_MTU),
|
||||
m_RecvEndpoint, std::bind(&I2PUDPClientTunnel::HandleRecvFromLocal, this, std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void I2PUDPClientTunnel::HandleRecvFromLocal(const boost::system::error_code & ec, std::size_t transferred)
|
||||
{
|
||||
if(ec) {
|
||||
LogPrint(eLogError, "UDP Client: ", ec.message());
|
||||
return;
|
||||
}
|
||||
if(!m_RemoteIdent) {
|
||||
LogPrint(eLogWarning, "UDP Client: remote endpoint not resolved yet");
|
||||
RecvFromLocal();
|
||||
return; // drop, remote not resolved
|
||||
}
|
||||
auto remotePort = m_RecvEndpoint.port();
|
||||
auto itr = m_Sessions.find(remotePort);
|
||||
if (itr == m_Sessions.end()) {
|
||||
// track new udp convo
|
||||
m_Sessions[remotePort] = {boost::asio::ip::udp::endpoint(m_RecvEndpoint), 0};
|
||||
}
|
||||
// send off to remote i2p destination
|
||||
LogPrint(eLogDebug, "UDP Client: send ", transferred, " to ", m_RemoteIdent->ToBase32(), ":", RemotePort);
|
||||
m_LocalDest->GetDatagramDestination()->SendDatagramTo(m_RecvBuff, transferred, *m_RemoteIdent, remotePort, RemotePort);
|
||||
// mark convo as active
|
||||
m_Sessions[remotePort].second = i2p::util::GetMillisecondsSinceEpoch();
|
||||
RecvFromLocal();
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > I2PUDPClientTunnel::GetSessions()
|
||||
{
|
||||
// TODO: implement
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
|
||||
return infos;
|
||||
}
|
||||
|
||||
void I2PUDPClientTunnel::TryResolving() {
|
||||
LogPrint(eLogInfo, "UDP Tunnel: Trying to resolve ", m_RemoteDest);
|
||||
i2p::data::IdentHash * h = new i2p::data::IdentHash;
|
||||
|
||||
while(!context.GetAddressBook().GetIdentHash(m_RemoteDest, *h) && !m_cancel_resolve)
|
||||
{
|
||||
LogPrint(eLogWarning, "UDP Tunnel: failed to lookup ", m_RemoteDest);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
if(m_cancel_resolve)
|
||||
{
|
||||
LogPrint(eLogError, "UDP Tunnel: lookup of ", m_RemoteDest, " was cancelled");
|
||||
return;
|
||||
}
|
||||
m_RemoteIdent = h;
|
||||
LogPrint(eLogInfo, "UDP Tunnel: resolved ", m_RemoteDest, " to ", m_RemoteIdent->ToBase32());
|
||||
}
|
||||
|
||||
void I2PUDPClientTunnel::HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
|
||||
{
|
||||
if(m_RemoteIdent && from.GetIdentHash() == *m_RemoteIdent)
|
||||
{
|
||||
auto itr = m_Sessions.find(toPort);
|
||||
// found convo ?
|
||||
if(itr != m_Sessions.end())
|
||||
{
|
||||
// found convo
|
||||
if (len > 0) {
|
||||
LogPrint(eLogDebug, "UDP Client: got ", len, "B from ", from.GetIdentHash().ToBase32());
|
||||
m_LocalSocket.send_to(boost::asio::buffer(buf, len), itr->second.first);
|
||||
// mark convo as active
|
||||
itr->second.second = i2p::util::GetMillisecondsSinceEpoch();
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint(eLogWarning, "UDP Client: not tracking udp session using port ", (int) toPort);
|
||||
}
|
||||
else
|
||||
LogPrint(eLogWarning, "UDP Client: unwarrented traffic from ", from.GetIdentHash().ToBase32());
|
||||
|
||||
}
|
||||
|
||||
I2PUDPClientTunnel::~I2PUDPClientTunnel() {
|
||||
auto dgram = m_LocalDest->GetDatagramDestination();
|
||||
if (dgram) dgram->ResetReceiver();
|
||||
|
||||
m_Sessions.clear();
|
||||
|
||||
if(m_LocalSocket.is_open())
|
||||
m_LocalSocket.close();
|
||||
|
||||
m_cancel_resolve = true;
|
||||
|
||||
if(m_ResolveThread)
|
||||
{
|
||||
m_ResolveThread->join();
|
||||
delete m_ResolveThread;
|
||||
m_ResolveThread = nullptr;
|
||||
}
|
||||
if (m_RemoteIdent) delete m_RemoteIdent;
|
||||
}
|
||||
}
|
||||
}
|
360
libi2pd_client/I2PTunnel.h
Normal file
360
libi2pd_client/I2PTunnel.h
Normal file
|
@ -0,0 +1,360 @@
|
|||
#ifndef I2PTUNNEL_H__
|
||||
#define I2PTUNNEL_H__
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <tuple>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
#include "Destination.h"
|
||||
#include "Datagram.h"
|
||||
#include "Streaming.h"
|
||||
#include "I2PService.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const size_t I2P_TUNNEL_CONNECTION_BUFFER_SIZE = 65536;
|
||||
const int I2P_TUNNEL_CONNECTION_MAX_IDLE = 3600; // in seconds
|
||||
const int I2P_TUNNEL_DESTINATION_REQUEST_TIMEOUT = 10; // in seconds
|
||||
// for HTTP tunnels
|
||||
const char X_I2P_DEST_HASH[] = "X-I2P-DestHash"; // hash in base64
|
||||
const char X_I2P_DEST_B64[] = "X-I2P-DestB64"; // full address in base64
|
||||
const char X_I2P_DEST_B32[] = "X-I2P-DestB32"; // .b32.i2p address
|
||||
|
||||
class I2PTunnelConnection: public I2PServiceHandler, public std::enable_shared_from_this<I2PTunnelConnection>
|
||||
{
|
||||
public:
|
||||
|
||||
I2PTunnelConnection (I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
std::shared_ptr<const i2p::data::LeaseSet> leaseSet, int port = 0); // to I2P
|
||||
I2PTunnelConnection (I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
std::shared_ptr<i2p::stream::Stream> stream); // to I2P using simplified API
|
||||
I2PTunnelConnection (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
const boost::asio::ip::tcp::endpoint& target, bool quiet = true); // from I2P
|
||||
~I2PTunnelConnection ();
|
||||
void I2PConnect (const uint8_t * msg = nullptr, size_t len = 0);
|
||||
void Connect (bool isUniqueLocal = true);
|
||||
|
||||
protected:
|
||||
|
||||
void Terminate ();
|
||||
|
||||
void Receive ();
|
||||
void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
virtual void Write (const uint8_t * buf, size_t len); // can be overloaded
|
||||
void HandleWrite (const boost::system::error_code& ecode);
|
||||
|
||||
void StreamReceive ();
|
||||
void HandleStreamReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleConnect (const boost::system::error_code& ecode);
|
||||
|
||||
std::shared_ptr<const boost::asio::ip::tcp::socket> GetSocket () const { return m_Socket; };
|
||||
|
||||
private:
|
||||
|
||||
uint8_t m_Buffer[I2P_TUNNEL_CONNECTION_BUFFER_SIZE], m_StreamBuffer[I2P_TUNNEL_CONNECTION_BUFFER_SIZE];
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_Socket;
|
||||
std::shared_ptr<i2p::stream::Stream> m_Stream;
|
||||
boost::asio::ip::tcp::endpoint m_RemoteEndpoint;
|
||||
bool m_IsQuiet; // don't send destination
|
||||
};
|
||||
|
||||
class I2PClientTunnelConnectionHTTP: public I2PTunnelConnection
|
||||
{
|
||||
public:
|
||||
|
||||
I2PClientTunnelConnectionHTTP (I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
std::shared_ptr<i2p::stream::Stream> stream):
|
||||
I2PTunnelConnection (owner, socket, stream), m_HeaderSent (false),
|
||||
m_ConnectionSent (false), m_ProxyConnectionSent (false) {};
|
||||
|
||||
protected:
|
||||
|
||||
void Write (const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
std::stringstream m_InHeader, m_OutHeader;
|
||||
bool m_HeaderSent, m_ConnectionSent, m_ProxyConnectionSent;
|
||||
};
|
||||
|
||||
class I2PServerTunnelConnectionHTTP: public I2PTunnelConnection
|
||||
{
|
||||
public:
|
||||
|
||||
I2PServerTunnelConnectionHTTP (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
const boost::asio::ip::tcp::endpoint& target, const std::string& host);
|
||||
|
||||
protected:
|
||||
|
||||
void Write (const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
std::string m_Host;
|
||||
std::stringstream m_InHeader, m_OutHeader;
|
||||
bool m_HeaderSent;
|
||||
std::shared_ptr<const i2p::data::IdentityEx> m_From;
|
||||
};
|
||||
|
||||
class I2PTunnelConnectionIRC: public I2PTunnelConnection
|
||||
{
|
||||
public:
|
||||
|
||||
I2PTunnelConnectionIRC (I2PService * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> socket,
|
||||
const boost::asio::ip::tcp::endpoint& target, const std::string& m_WebircPass);
|
||||
|
||||
protected:
|
||||
|
||||
void Write (const uint8_t * buf, size_t len);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<const i2p::data::IdentityEx> m_From;
|
||||
std::stringstream m_OutPacket, m_InPacket;
|
||||
bool m_NeedsWebIrc;
|
||||
std::string m_WebircPass;
|
||||
};
|
||||
|
||||
|
||||
class I2PClientTunnel: public TCPIPAcceptor
|
||||
{
|
||||
protected:
|
||||
|
||||
// Implements TCPIPAcceptor
|
||||
std::shared_ptr<I2PServiceHandler> CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket);
|
||||
|
||||
public:
|
||||
|
||||
I2PClientTunnel (const std::string& name, const std::string& destination,
|
||||
const std::string& address, int port, std::shared_ptr<ClientDestination> localDestination, int destinationPort = 0);
|
||||
~I2PClientTunnel () {}
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
const char* GetName() { return m_Name.c_str (); }
|
||||
|
||||
private:
|
||||
|
||||
const i2p::data::IdentHash * GetIdentHash ();
|
||||
|
||||
private:
|
||||
|
||||
std::string m_Name, m_Destination;
|
||||
const i2p::data::IdentHash * m_DestinationIdentHash;
|
||||
int m_DestinationPort;
|
||||
};
|
||||
|
||||
|
||||
/** 2 minute timeout for udp sessions */
|
||||
const uint64_t I2P_UDP_SESSION_TIMEOUT = 1000 * 60 * 2;
|
||||
|
||||
/** max size for i2p udp */
|
||||
const size_t I2P_UDP_MAX_MTU = i2p::datagram::MAX_DATAGRAM_SIZE;
|
||||
|
||||
struct UDPSession
|
||||
{
|
||||
i2p::datagram::DatagramDestination * m_Destination;
|
||||
boost::asio::ip::udp::socket IPSocket;
|
||||
i2p::data::IdentHash Identity;
|
||||
boost::asio::ip::udp::endpoint FromEndpoint;
|
||||
boost::asio::ip::udp::endpoint SendEndpoint;
|
||||
uint64_t LastActivity;
|
||||
|
||||
uint16_t LocalPort;
|
||||
uint16_t RemotePort;
|
||||
|
||||
uint8_t m_Buffer[I2P_UDP_MAX_MTU];
|
||||
|
||||
UDPSession(boost::asio::ip::udp::endpoint localEndpoint,
|
||||
const std::shared_ptr<i2p::client::ClientDestination> & localDestination,
|
||||
boost::asio::ip::udp::endpoint remote, const i2p::data::IdentHash * ident,
|
||||
uint16_t ourPort, uint16_t theirPort);
|
||||
void HandleReceived(const boost::system::error_code & ecode, std::size_t len);
|
||||
void Receive();
|
||||
};
|
||||
|
||||
|
||||
/** read only info about a datagram session */
|
||||
struct DatagramSessionInfo
|
||||
{
|
||||
/** the name of this forward */
|
||||
std::string Name;
|
||||
/** ident hash of local destination */
|
||||
std::shared_ptr<const i2p::data::IdentHash> LocalIdent;
|
||||
/** ident hash of remote destination */
|
||||
std::shared_ptr<const i2p::data::IdentHash> RemoteIdent;
|
||||
/** ident hash of IBGW in use currently in this session or nullptr if none is set */
|
||||
std::shared_ptr<const i2p::data::IdentHash> CurrentIBGW;
|
||||
/** ident hash of OBEP in use for this session or nullptr if none is set */
|
||||
std::shared_ptr<const i2p::data::IdentHash> CurrentOBEP;
|
||||
/** i2p router's udp endpoint */
|
||||
boost::asio::ip::udp::endpoint LocalEndpoint;
|
||||
/** client's udp endpoint */
|
||||
boost::asio::ip::udp::endpoint RemoteEndpoint;
|
||||
/** how long has this converstation been idle in ms */
|
||||
uint64_t idle;
|
||||
};
|
||||
|
||||
typedef std::shared_ptr<UDPSession> UDPSessionPtr;
|
||||
|
||||
/** server side udp tunnel, many i2p inbound to 1 ip outbound */
|
||||
class I2PUDPServerTunnel
|
||||
{
|
||||
public:
|
||||
I2PUDPServerTunnel(const std::string & name,
|
||||
std::shared_ptr<i2p::client::ClientDestination> localDestination,
|
||||
boost::asio::ip::address localAddress,
|
||||
boost::asio::ip::udp::endpoint forwardTo, uint16_t port);
|
||||
~I2PUDPServerTunnel();
|
||||
/** expire stale udp conversations */
|
||||
void ExpireStale(const uint64_t delta=I2P_UDP_SESSION_TIMEOUT);
|
||||
void Start();
|
||||
const char * GetName() const { return m_Name.c_str(); }
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > GetSessions();
|
||||
std::shared_ptr<ClientDestination> GetLocalDestination () const { return m_LocalDest; }
|
||||
|
||||
void SetUniqueLocal(bool isUniqueLocal = true) { m_IsUniqueLocal = isUniqueLocal; }
|
||||
|
||||
private:
|
||||
|
||||
void HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
UDPSessionPtr ObtainUDPSession(const i2p::data::IdentityEx& from, uint16_t localPort, uint16_t remotePort);
|
||||
|
||||
private:
|
||||
bool m_IsUniqueLocal;
|
||||
const std::string m_Name;
|
||||
boost::asio::ip::address m_LocalAddress;
|
||||
boost::asio::ip::udp::endpoint m_RemoteEndpoint;
|
||||
std::mutex m_SessionsMutex;
|
||||
std::vector<UDPSessionPtr> m_Sessions;
|
||||
std::shared_ptr<i2p::client::ClientDestination> m_LocalDest;
|
||||
};
|
||||
|
||||
class I2PUDPClientTunnel
|
||||
{
|
||||
public:
|
||||
I2PUDPClientTunnel(const std::string & name, const std::string &remoteDest,
|
||||
boost::asio::ip::udp::endpoint localEndpoint, std::shared_ptr<i2p::client::ClientDestination> localDestination,
|
||||
uint16_t remotePort);
|
||||
~I2PUDPClientTunnel();
|
||||
void Start();
|
||||
const char * GetName() const { return m_Name.c_str(); }
|
||||
std::vector<std::shared_ptr<DatagramSessionInfo> > GetSessions();
|
||||
|
||||
bool IsLocalDestination(const i2p::data::IdentHash & destination) const { return destination == m_LocalDest->GetIdentHash(); }
|
||||
|
||||
std::shared_ptr<ClientDestination> GetLocalDestination () const { return m_LocalDest; }
|
||||
void ExpireStale(const uint64_t delta=I2P_UDP_SESSION_TIMEOUT);
|
||||
|
||||
private:
|
||||
typedef std::pair<boost::asio::ip::udp::endpoint, uint64_t> UDPConvo;
|
||||
void RecvFromLocal();
|
||||
void HandleRecvFromLocal(const boost::system::error_code & e, std::size_t transferred);
|
||||
void HandleRecvFromI2P(const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
void TryResolving();
|
||||
const std::string m_Name;
|
||||
std::mutex m_SessionsMutex;
|
||||
std::map<uint16_t, UDPConvo > m_Sessions; // maps i2p port -> local udp convo
|
||||
const std::string m_RemoteDest;
|
||||
std::shared_ptr<i2p::client::ClientDestination> m_LocalDest;
|
||||
const boost::asio::ip::udp::endpoint m_LocalEndpoint;
|
||||
i2p::data::IdentHash * m_RemoteIdent;
|
||||
std::thread * m_ResolveThread;
|
||||
boost::asio::ip::udp::socket m_LocalSocket;
|
||||
boost::asio::ip::udp::endpoint m_RecvEndpoint;
|
||||
uint8_t m_RecvBuff[I2P_UDP_MAX_MTU];
|
||||
uint16_t RemotePort;
|
||||
bool m_cancel_resolve;
|
||||
};
|
||||
|
||||
class I2PServerTunnel: public I2PService
|
||||
{
|
||||
public:
|
||||
|
||||
I2PServerTunnel (const std::string& name, const std::string& address, int port,
|
||||
std::shared_ptr<ClientDestination> localDestination, int inport = 0, bool gzip = true);
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
void SetAccessList (const std::set<i2p::data::IdentHash>& accessList);
|
||||
|
||||
void SetUniqueLocal (bool isUniqueLocal) { m_IsUniqueLocal = isUniqueLocal; }
|
||||
bool IsUniqueLocal () const { return m_IsUniqueLocal; }
|
||||
|
||||
const std::string& GetAddress() const { return m_Address; }
|
||||
int GetPort () const { return m_Port; };
|
||||
uint16_t GetLocalPort () const { return m_PortDestination->GetLocalPort (); };
|
||||
const boost::asio::ip::tcp::endpoint& GetEndpoint () const { return m_Endpoint; }
|
||||
|
||||
const char* GetName() { return m_Name.c_str (); }
|
||||
|
||||
void SetMaxConnsPerMinute(const uint32_t conns) { m_PortDestination->SetMaxConnsPerMinute(conns); }
|
||||
|
||||
private:
|
||||
|
||||
void HandleResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
|
||||
std::shared_ptr<boost::asio::ip::tcp::resolver> resolver);
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
virtual std::shared_ptr<I2PTunnelConnection> CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
private:
|
||||
|
||||
bool m_IsUniqueLocal;
|
||||
std::string m_Name, m_Address;
|
||||
int m_Port;
|
||||
boost::asio::ip::tcp::endpoint m_Endpoint;
|
||||
std::shared_ptr<i2p::stream::StreamingDestination> m_PortDestination;
|
||||
std::set<i2p::data::IdentHash> m_AccessList;
|
||||
bool m_IsAccessList;
|
||||
};
|
||||
|
||||
class I2PServerTunnelHTTP: public I2PServerTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
I2PServerTunnelHTTP (const std::string& name, const std::string& address, int port,
|
||||
std::shared_ptr<ClientDestination> localDestination, const std::string& host,
|
||||
int inport = 0, bool gzip = true);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<I2PTunnelConnection> CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
private:
|
||||
|
||||
std::string m_Host;
|
||||
};
|
||||
|
||||
class I2PServerTunnelIRC: public I2PServerTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
I2PServerTunnelIRC (const std::string& name, const std::string& address, int port,
|
||||
std::shared_ptr<ClientDestination> localDestination, const std::string& webircpass,
|
||||
int inport = 0, bool gzip = true);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<I2PTunnelConnection> CreateI2PConnection (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
private:
|
||||
|
||||
std::string m_WebircPass;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
113
libi2pd_client/MatchedDestination.cpp
Normal file
113
libi2pd_client/MatchedDestination.cpp
Normal file
|
@ -0,0 +1,113 @@
|
|||
#include "MatchedDestination.h"
|
||||
#include "Log.h"
|
||||
#include "ClientContext.h"
|
||||
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
MatchedTunnelDestination::MatchedTunnelDestination(const i2p::data::PrivateKeys & keys, const std::string & remoteName, const std::map<std::string, std::string> * params)
|
||||
: ClientDestination(keys, false, params),
|
||||
m_RemoteName(remoteName) {}
|
||||
|
||||
|
||||
void MatchedTunnelDestination::ResolveCurrentLeaseSet()
|
||||
{
|
||||
if(i2p::client::context.GetAddressBook().GetIdentHash(m_RemoteName, m_RemoteIdent))
|
||||
{
|
||||
auto ls = FindLeaseSet(m_RemoteIdent);
|
||||
if(ls)
|
||||
{
|
||||
HandleFoundCurrentLeaseSet(ls);
|
||||
}
|
||||
else
|
||||
RequestDestination(m_RemoteIdent, std::bind(&MatchedTunnelDestination::HandleFoundCurrentLeaseSet, this, std::placeholders::_1));
|
||||
}
|
||||
else
|
||||
LogPrint(eLogWarning, "Destination: failed to resolve ", m_RemoteName);
|
||||
}
|
||||
|
||||
void MatchedTunnelDestination::HandleFoundCurrentLeaseSet(std::shared_ptr<const i2p::data::LeaseSet> ls)
|
||||
{
|
||||
if(ls)
|
||||
{
|
||||
LogPrint(eLogDebug, "Destination: resolved remote lease set for ", m_RemoteName);
|
||||
m_RemoteLeaseSet = ls;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_ResolveTimer->expires_from_now(boost::posix_time::seconds(1));
|
||||
m_ResolveTimer->async_wait([&](const boost::system::error_code & ec) {
|
||||
if(!ec) ResolveCurrentLeaseSet();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool MatchedTunnelDestination::Start()
|
||||
{
|
||||
if(ClientDestination::Start())
|
||||
{
|
||||
m_ResolveTimer = std::make_shared<boost::asio::deadline_timer>(GetService());
|
||||
GetTunnelPool()->SetCustomPeerSelector(this);
|
||||
ResolveCurrentLeaseSet();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MatchedTunnelDestination::Stop()
|
||||
{
|
||||
if(ClientDestination::Stop())
|
||||
{
|
||||
if(m_ResolveTimer)
|
||||
m_ResolveTimer->cancel();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
bool MatchedTunnelDestination::SelectPeers(i2p::tunnel::Path & path, int hops, bool inbound)
|
||||
{
|
||||
auto pool = GetTunnelPool();
|
||||
if(!i2p::tunnel::StandardSelectPeers(path, hops, inbound, std::bind(&i2p::tunnel::TunnelPool::SelectNextHop, pool, std::placeholders::_1)))
|
||||
return false;
|
||||
// more here for outbound tunnels
|
||||
if(!inbound && m_RemoteLeaseSet)
|
||||
{
|
||||
if(m_RemoteLeaseSet->IsExpired())
|
||||
{
|
||||
ResolveCurrentLeaseSet();
|
||||
}
|
||||
if(m_RemoteLeaseSet && !m_RemoteLeaseSet->IsExpired())
|
||||
{
|
||||
// remote lease set is good
|
||||
auto leases = m_RemoteLeaseSet->GetNonExpiredLeases();
|
||||
// pick lease
|
||||
std::shared_ptr<i2p::data::RouterInfo> obep;
|
||||
while(!obep && leases.size() > 0) {
|
||||
auto idx = rand() % leases.size();
|
||||
auto lease = leases[idx];
|
||||
obep = i2p::data::netdb.FindRouter(lease->tunnelGateway);
|
||||
leases.erase(leases.begin()+idx);
|
||||
}
|
||||
if(obep) {
|
||||
path.push_back(obep->GetRouterIdentity());
|
||||
LogPrint(eLogDebug, "Destination: found OBEP matching IBGW");
|
||||
} else
|
||||
LogPrint(eLogWarning, "Destination: could not find proper IBGW for matched outbound tunnel");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MatchedTunnelDestination::OnBuildResult(const i2p::tunnel::Path & path, bool inbound, i2p::tunnel::TunnelBuildResult result)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
36
libi2pd_client/MatchedDestination.h
Normal file
36
libi2pd_client/MatchedDestination.h
Normal file
|
@ -0,0 +1,36 @@
|
|||
#ifndef MATCHED_DESTINATION_H_
|
||||
#define MATCHED_DESTINATION_H_
|
||||
#include "Destination.h"
|
||||
#include <string>
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
/**
|
||||
client tunnel that uses same OBEP as IBGW of each remote lease for a remote destination
|
||||
*/
|
||||
class MatchedTunnelDestination : public ClientDestination, public i2p::tunnel::ITunnelPeerSelector
|
||||
{
|
||||
public:
|
||||
MatchedTunnelDestination(const i2p::data::PrivateKeys& keys, const std::string & remoteName, const std::map<std::string, std::string> * params = nullptr);
|
||||
bool Start();
|
||||
bool Stop();
|
||||
|
||||
bool SelectPeers(i2p::tunnel::Path & peers, int hops, bool inbound);
|
||||
bool OnBuildResult(const i2p::tunnel::Path & peers, bool inbound, i2p::tunnel::TunnelBuildResult result);
|
||||
|
||||
private:
|
||||
void ResolveCurrentLeaseSet();
|
||||
void HandleFoundCurrentLeaseSet(std::shared_ptr<const i2p::data::LeaseSet> ls);
|
||||
|
||||
private:
|
||||
std::string m_RemoteName;
|
||||
i2p::data::IdentHash m_RemoteIdent;
|
||||
std::shared_ptr<const i2p::data::LeaseSet> m_RemoteLeaseSet;
|
||||
std::shared_ptr<boost::asio::deadline_timer> m_ResolveTimer;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
1014
libi2pd_client/SAM.cpp
Normal file
1014
libi2pd_client/SAM.cpp
Normal file
File diff suppressed because it is too large
Load diff
223
libi2pd_client/SAM.h
Normal file
223
libi2pd_client/SAM.h
Normal file
|
@ -0,0 +1,223 @@
|
|||
#ifndef SAM_H__
|
||||
#define SAM_H__
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <list>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
#include "LeaseSet.h"
|
||||
#include "Streaming.h"
|
||||
#include "Destination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const size_t SAM_SOCKET_BUFFER_SIZE = 8192;
|
||||
const int SAM_SOCKET_CONNECTION_MAX_IDLE = 3600; // in seconds
|
||||
const int SAM_SESSION_READINESS_CHECK_INTERVAL = 20; // in seconds
|
||||
const char SAM_HANDSHAKE[] = "HELLO VERSION";
|
||||
const char SAM_HANDSHAKE_REPLY[] = "HELLO REPLY RESULT=OK VERSION=%s\n";
|
||||
const char SAM_HANDSHAKE_I2P_ERROR[] = "HELLO REPLY RESULT=I2P_ERROR\n";
|
||||
const char SAM_SESSION_CREATE[] = "SESSION CREATE";
|
||||
const char SAM_SESSION_CREATE_REPLY_OK[] = "SESSION STATUS RESULT=OK DESTINATION=%s\n";
|
||||
const char SAM_SESSION_CREATE_DUPLICATED_ID[] = "SESSION STATUS RESULT=DUPLICATED_ID\n";
|
||||
const char SAM_SESSION_CREATE_DUPLICATED_DEST[] = "SESSION STATUS RESULT=DUPLICATED_DEST\n";
|
||||
const char SAM_SESSION_STATUS_INVALID_KEY[] = "SESSION STATUS RESULT=INVALID_KEY\n";
|
||||
const char SAM_SESSION_STATUS_I2P_ERROR[] = "SESSION STATUS RESULT=I2P_ERROR MESSAGE=%s\n";
|
||||
const char SAM_STREAM_CONNECT[] = "STREAM CONNECT";
|
||||
const char SAM_STREAM_STATUS_OK[] = "STREAM STATUS RESULT=OK\n";
|
||||
const char SAM_STREAM_STATUS_INVALID_ID[] = "STREAM STATUS RESULT=INVALID_ID\n";
|
||||
const char SAM_STREAM_STATUS_CANT_REACH_PEER[] = "STREAM STATUS RESULT=CANT_REACH_PEER\n";
|
||||
const char SAM_STREAM_STATUS_I2P_ERROR[] = "STREAM STATUS RESULT=I2P_ERROR\n";
|
||||
const char SAM_STREAM_ACCEPT[] = "STREAM ACCEPT";
|
||||
const char SAM_DATAGRAM_SEND[] = "DATAGRAM SEND";
|
||||
const char SAM_DEST_GENERATE[] = "DEST GENERATE";
|
||||
const char SAM_DEST_REPLY[] = "DEST REPLY PUB=%s PRIV=%s\n";
|
||||
const char SAM_DEST_REPLY_I2P_ERROR[] = "DEST REPLY RESULT=I2P_ERROR\n";
|
||||
const char SAM_NAMING_LOOKUP[] = "NAMING LOOKUP";
|
||||
const char SAM_NAMING_REPLY[] = "NAMING REPLY RESULT=OK NAME=ME VALUE=%s\n";
|
||||
const char SAM_DATAGRAM_RECEIVED[] = "DATAGRAM RECEIVED DESTINATION=%s SIZE=%lu\n";
|
||||
const char SAM_NAMING_REPLY_INVALID_KEY[] = "NAMING REPLY RESULT=INVALID_KEY NAME=%s\n";
|
||||
const char SAM_NAMING_REPLY_KEY_NOT_FOUND[] = "NAMING REPLY RESULT=INVALID_KEY_NOT_FOUND NAME=%s\n";
|
||||
const char SAM_PARAM_MIN[] = "MIN";
|
||||
const char SAM_PARAM_MAX[] = "MAX";
|
||||
const char SAM_PARAM_STYLE[] = "STYLE";
|
||||
const char SAM_PARAM_ID[] = "ID";
|
||||
const char SAM_PARAM_SILENT[] = "SILENT";
|
||||
const char SAM_PARAM_DESTINATION[] = "DESTINATION";
|
||||
const char SAM_PARAM_NAME[] = "NAME";
|
||||
const char SAM_PARAM_SIGNATURE_TYPE[] = "SIGNATURE_TYPE";
|
||||
const char SAM_PARAM_SIZE[] = "SIZE";
|
||||
const char SAM_VALUE_TRANSIENT[] = "TRANSIENT";
|
||||
const char SAM_VALUE_STREAM[] = "STREAM";
|
||||
const char SAM_VALUE_DATAGRAM[] = "DATAGRAM";
|
||||
const char SAM_VALUE_RAW[] = "RAW";
|
||||
const char SAM_VALUE_TRUE[] = "true";
|
||||
const char SAM_VALUE_FALSE[] = "false";
|
||||
const char SAM_VALUE_HOST[] = "HOST";
|
||||
const char SAM_VALUE_PORT[] = "PORT";
|
||||
|
||||
enum SAMSocketType
|
||||
{
|
||||
eSAMSocketTypeUnknown,
|
||||
eSAMSocketTypeSession,
|
||||
eSAMSocketTypeStream,
|
||||
eSAMSocketTypeAcceptor,
|
||||
eSAMSocketTypeTerminated
|
||||
};
|
||||
|
||||
class SAMBridge;
|
||||
struct SAMSession;
|
||||
class SAMSocket: public std::enable_shared_from_this<SAMSocket>
|
||||
{
|
||||
public:
|
||||
|
||||
SAMSocket (SAMBridge& owner);
|
||||
~SAMSocket ();
|
||||
void CloseStream (); // TODO: implement it better
|
||||
|
||||
boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
|
||||
void ReceiveHandshake ();
|
||||
void SetSocketType (SAMSocketType socketType) { m_SocketType = socketType; };
|
||||
SAMSocketType GetSocketType () const { return m_SocketType; };
|
||||
|
||||
void Terminate ();
|
||||
private:
|
||||
|
||||
void HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleHandshakeReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleMessage (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void SendMessageReply (const char * msg, size_t len, bool close);
|
||||
void HandleMessageReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred, bool close);
|
||||
void Receive ();
|
||||
void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
|
||||
void I2PReceive ();
|
||||
void HandleI2PReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleI2PAccept (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
void HandleWriteI2PData (const boost::system::error_code& ecode);
|
||||
void HandleI2PDatagramReceive (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
|
||||
void ProcessSessionCreate (char * buf, size_t len);
|
||||
void ProcessStreamConnect (char * buf, size_t len, size_t rem);
|
||||
void ProcessStreamAccept (char * buf, size_t len);
|
||||
void ProcessDestGenerate (char * buf, size_t len);
|
||||
void ProcessNamingLookup (char * buf, size_t len);
|
||||
void SendI2PError(const std::string & msg);
|
||||
size_t ProcessDatagramSend (char * buf, size_t len, const char * data); // from SAM 1.0
|
||||
void ExtractParams (char * buf, std::map<std::string, std::string>& params);
|
||||
|
||||
void Connect (std::shared_ptr<const i2p::data::LeaseSet> remote);
|
||||
void HandleConnectLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet);
|
||||
void SendNamingLookupReply (std::shared_ptr<const i2p::data::IdentityEx> identity);
|
||||
void HandleNamingLookupLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet, i2p::data::IdentHash ident);
|
||||
void HandleSessionReadinessCheckTimer (const boost::system::error_code& ecode);
|
||||
void SendSessionCreateReplyOk ();
|
||||
|
||||
private:
|
||||
|
||||
SAMBridge& m_Owner;
|
||||
boost::asio::ip::tcp::socket m_Socket;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
char m_Buffer[SAM_SOCKET_BUFFER_SIZE + 1];
|
||||
size_t m_BufferOffset;
|
||||
uint8_t m_StreamBuffer[SAM_SOCKET_BUFFER_SIZE];
|
||||
SAMSocketType m_SocketType;
|
||||
std::string m_ID; // nickname
|
||||
bool m_IsSilent;
|
||||
bool m_IsAccepting; // for eSAMSocketTypeAcceptor only
|
||||
std::shared_ptr<i2p::stream::Stream> m_Stream;
|
||||
std::shared_ptr<SAMSession> m_Session;
|
||||
};
|
||||
|
||||
struct SAMSession
|
||||
{
|
||||
std::shared_ptr<ClientDestination> localDestination;
|
||||
std::list<std::shared_ptr<SAMSocket> > m_Sockets;
|
||||
std::shared_ptr<boost::asio::ip::udp::endpoint> UDPEndpoint;
|
||||
std::mutex m_SocketsMutex;
|
||||
|
||||
/** safely add a socket to this session */
|
||||
void AddSocket(const std::shared_ptr<SAMSocket> & sock) {
|
||||
std::lock_guard<std::mutex> lock(m_SocketsMutex);
|
||||
m_Sockets.push_back(sock);
|
||||
}
|
||||
|
||||
/** safely remove a socket from this session */
|
||||
void DelSocket(const std::shared_ptr<SAMSocket> & sock) {
|
||||
std::lock_guard<std::mutex> lock(m_SocketsMutex);
|
||||
m_Sockets.remove(sock);
|
||||
}
|
||||
|
||||
/** get a list holding a copy of all sam sockets from this session */
|
||||
std::list<std::shared_ptr<SAMSocket> > ListSockets() {
|
||||
std::list<std::shared_ptr<SAMSocket> > l;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_SocketsMutex);
|
||||
for(const auto& sock : m_Sockets ) l.push_back(sock);
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
SAMSession (std::shared_ptr<ClientDestination> dest);
|
||||
~SAMSession ();
|
||||
|
||||
void CloseStreams ();
|
||||
};
|
||||
|
||||
class SAMBridge
|
||||
{
|
||||
public:
|
||||
|
||||
SAMBridge (const std::string& address, int port);
|
||||
~SAMBridge ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
std::shared_ptr<SAMSession> CreateSession (const std::string& id, const std::string& destination, // empty string means transient
|
||||
const std::map<std::string, std::string> * params);
|
||||
void CloseSession (const std::string& id);
|
||||
std::shared_ptr<SAMSession> FindSession (const std::string& id) const;
|
||||
|
||||
/** send raw data to remote endpoint from our UDP Socket */
|
||||
void SendTo(const uint8_t * buf, size_t len, std::shared_ptr<boost::asio::ip::udp::endpoint> remote);
|
||||
|
||||
private:
|
||||
|
||||
void Run ();
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<SAMSocket> socket);
|
||||
|
||||
void ReceiveDatagram ();
|
||||
void HandleReceivedDatagram (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
|
||||
private:
|
||||
|
||||
bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
boost::asio::ip::udp::endpoint m_DatagramEndpoint, m_SenderEndpoint;
|
||||
boost::asio::ip::udp::socket m_DatagramSocket;
|
||||
mutable std::mutex m_SessionsMutex;
|
||||
std::map<std::string, std::shared_ptr<SAMSession> > m_Sessions;
|
||||
uint8_t m_DatagramReceiveBuffer[i2p::datagram::MAX_DATAGRAM_SIZE+1];
|
||||
|
||||
public:
|
||||
|
||||
// for HTTP
|
||||
const decltype(m_Sessions)& GetSessions () const { return m_Sessions; };
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
792
libi2pd_client/SOCKS.cpp
Normal file
792
libi2pd_client/SOCKS.cpp
Normal file
|
@ -0,0 +1,792 @@
|
|||
#include <cstring>
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
#include "SOCKS.h"
|
||||
#include "Identity.h"
|
||||
#include "Streaming.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PEndian.h"
|
||||
#include "I2PTunnel.h"
|
||||
#include "I2PService.h"
|
||||
#include "util.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace proxy
|
||||
{
|
||||
static const size_t socks_buffer_size = 8192;
|
||||
static const size_t max_socks_hostname_size = 255; // Limit for socks5 and bad idea to traverse
|
||||
|
||||
static const size_t SOCKS_FORWARDER_BUFFER_SIZE = 8192;
|
||||
|
||||
static const size_t SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE = 8;
|
||||
|
||||
struct SOCKSDnsAddress
|
||||
{
|
||||
uint8_t size;
|
||||
char value[max_socks_hostname_size];
|
||||
void FromString (const std::string& str)
|
||||
{
|
||||
size = str.length();
|
||||
if (str.length() > max_socks_hostname_size) size = max_socks_hostname_size;
|
||||
memcpy(value,str.c_str(),size);
|
||||
}
|
||||
std::string ToString() { return std::string(value, size); }
|
||||
void push_back (char c) { value[size++] = c; }
|
||||
};
|
||||
|
||||
class SOCKSServer;
|
||||
class SOCKSHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<SOCKSHandler>
|
||||
{
|
||||
private:
|
||||
enum state
|
||||
{
|
||||
GET_SOCKSV,
|
||||
GET_COMMAND,
|
||||
GET_PORT,
|
||||
GET_IPV4,
|
||||
GET4_IDENT,
|
||||
GET4A_HOST,
|
||||
GET5_AUTHNUM,
|
||||
GET5_AUTH,
|
||||
GET5_REQUESTV,
|
||||
GET5_GETRSV,
|
||||
GET5_GETADDRTYPE,
|
||||
GET5_IPV6,
|
||||
GET5_HOST_SIZE,
|
||||
GET5_HOST,
|
||||
READY,
|
||||
UPSTREAM_RESOLVE,
|
||||
UPSTREAM_CONNECT,
|
||||
UPSTREAM_HANDSHAKE
|
||||
};
|
||||
enum authMethods
|
||||
{
|
||||
AUTH_NONE = 0, //No authentication, skip to next step
|
||||
AUTH_GSSAPI = 1, //GSSAPI authentication
|
||||
AUTH_USERPASSWD = 2, //Username and password
|
||||
AUTH_UNACCEPTABLE = 0xff //No acceptable method found
|
||||
};
|
||||
enum addrTypes
|
||||
{
|
||||
ADDR_IPV4 = 1, //IPv4 address (4 octets)
|
||||
ADDR_DNS = 3, // DNS name (up to 255 octets)
|
||||
ADDR_IPV6 = 4 //IPV6 address (16 octets)
|
||||
};
|
||||
enum errTypes
|
||||
{
|
||||
SOCKS5_OK = 0, // No error for SOCKS5
|
||||
SOCKS5_GEN_FAIL = 1, // General server failure
|
||||
SOCKS5_RULE_DENIED = 2, // Connection disallowed by ruleset
|
||||
SOCKS5_NET_UNREACH = 3, // Network unreachable
|
||||
SOCKS5_HOST_UNREACH = 4, // Host unreachable
|
||||
SOCKS5_CONN_REFUSED = 5, // Connection refused by the peer
|
||||
SOCKS5_TTL_EXPIRED = 6, // TTL Expired
|
||||
SOCKS5_CMD_UNSUP = 7, // Command unsuported
|
||||
SOCKS5_ADDR_UNSUP = 8, // Address type unsuported
|
||||
SOCKS4_OK = 90, // No error for SOCKS4
|
||||
SOCKS4_FAIL = 91, // Failed establishing connecting or not allowed
|
||||
SOCKS4_IDENTD_MISSING = 92, // Couldn't connect to the identd server
|
||||
SOCKS4_IDENTD_DIFFER = 93 // The ID reported by the application and by identd differ
|
||||
};
|
||||
enum cmdTypes
|
||||
{
|
||||
CMD_CONNECT = 1, // TCP Connect
|
||||
CMD_BIND = 2, // TCP Bind
|
||||
CMD_UDP = 3 // UDP associate
|
||||
};
|
||||
enum socksVersions
|
||||
{
|
||||
SOCKS4 = 4, // SOCKS4
|
||||
SOCKS5 = 5 // SOCKS5
|
||||
};
|
||||
union address
|
||||
{
|
||||
uint32_t ip;
|
||||
SOCKSDnsAddress dns;
|
||||
uint8_t ipv6[16];
|
||||
};
|
||||
|
||||
void EnterState(state nstate, uint8_t parseleft = 1);
|
||||
bool HandleData(uint8_t *sock_buff, std::size_t len);
|
||||
bool ValidateSOCKSRequest();
|
||||
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void Terminate();
|
||||
void AsyncSockRead();
|
||||
boost::asio::const_buffers_1 GenerateSOCKS5SelectAuth(authMethods method);
|
||||
boost::asio::const_buffers_1 GenerateSOCKS4Response(errTypes error, uint32_t ip, uint16_t port);
|
||||
boost::asio::const_buffers_1 GenerateSOCKS5Response(errTypes error, addrTypes type, const address &addr, uint16_t port);
|
||||
boost::asio::const_buffers_1 GenerateUpstreamRequest();
|
||||
bool Socks5ChooseAuth();
|
||||
void SocksRequestFailed(errTypes error);
|
||||
void SocksRequestSuccess();
|
||||
void SentSocksFailed(const boost::system::error_code & ecode);
|
||||
void SentSocksDone(const boost::system::error_code & ecode);
|
||||
void SentSocksResponse(const boost::system::error_code & ecode);
|
||||
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
void ForwardSOCKS();
|
||||
|
||||
void SocksUpstreamSuccess();
|
||||
void AsyncUpstreamSockRead();
|
||||
void SendUpstreamRequest();
|
||||
void HandleUpstreamData(uint8_t * buff, std::size_t len);
|
||||
void HandleUpstreamSockSend(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void HandleUpstreamSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void HandleUpstreamConnected(const boost::system::error_code & ecode,
|
||||
boost::asio::ip::tcp::resolver::iterator itr);
|
||||
void HandleUpstreamResolved(const boost::system::error_code & ecode,
|
||||
boost::asio::ip::tcp::resolver::iterator itr);
|
||||
|
||||
boost::asio::ip::tcp::resolver m_proxy_resolver;
|
||||
uint8_t m_sock_buff[socks_buffer_size];
|
||||
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock, m_upstreamSock;
|
||||
std::shared_ptr<i2p::stream::Stream> m_stream;
|
||||
uint8_t *m_remaining_data; //Data left to be sent
|
||||
uint8_t *m_remaining_upstream_data; //upstream data left to be forwarded
|
||||
uint8_t m_response[7+max_socks_hostname_size];
|
||||
uint8_t m_upstream_response[SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE];
|
||||
uint8_t m_upstream_request[14+max_socks_hostname_size];
|
||||
std::size_t m_upstream_response_len;
|
||||
address m_address; //Address
|
||||
std::size_t m_remaining_data_len; //Size of the data left to be sent
|
||||
uint32_t m_4aip; //Used in 4a requests
|
||||
uint16_t m_port;
|
||||
uint8_t m_command;
|
||||
uint8_t m_parseleft; //Octets left to parse
|
||||
authMethods m_authchosen; //Authentication chosen
|
||||
addrTypes m_addrtype; //Address type chosen
|
||||
socksVersions m_socksv; //Socks version
|
||||
cmdTypes m_cmd; // Command requested
|
||||
state m_state;
|
||||
const bool m_UseUpstreamProxy; // do we want to use the upstream proxy for non i2p addresses?
|
||||
const std::string m_UpstreamProxyAddress;
|
||||
const uint16_t m_UpstreamProxyPort;
|
||||
|
||||
public:
|
||||
SOCKSHandler(SOCKSServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock, const std::string & upstreamAddr, const uint16_t upstreamPort, const bool useUpstream) :
|
||||
I2PServiceHandler(parent),
|
||||
m_proxy_resolver(parent->GetService()),
|
||||
m_sock(sock), m_stream(nullptr),
|
||||
m_authchosen(AUTH_UNACCEPTABLE), m_addrtype(ADDR_IPV4),
|
||||
m_UseUpstreamProxy(useUpstream),
|
||||
m_UpstreamProxyAddress(upstreamAddr),
|
||||
m_UpstreamProxyPort(upstreamPort)
|
||||
{ m_address.ip = 0; EnterState(GET_SOCKSV); }
|
||||
|
||||
~SOCKSHandler() { Terminate(); }
|
||||
void Handle() { 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(&SOCKSHandler::HandleSockRecv, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
} else {
|
||||
LogPrint(eLogError,"SOCKS: no socket for read");
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::Terminate()
|
||||
{
|
||||
if (Kill()) return;
|
||||
if (m_sock)
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: closing socket");
|
||||
m_sock->close();
|
||||
m_sock = nullptr;
|
||||
}
|
||||
if (m_upstreamSock)
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: closing upstream socket");
|
||||
m_upstreamSock->close();
|
||||
m_upstreamSock = nullptr;
|
||||
}
|
||||
if (m_stream)
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: closing stream");
|
||||
m_stream.reset ();
|
||||
}
|
||||
Done(shared_from_this());
|
||||
}
|
||||
|
||||
boost::asio::const_buffers_1 SOCKSHandler::GenerateSOCKS4Response(SOCKSHandler::errTypes error, uint32_t ip, uint16_t port)
|
||||
{
|
||||
assert(error >= SOCKS4_OK);
|
||||
m_response[0] = '\x00'; //Version
|
||||
m_response[1] = error; //Response code
|
||||
htobe16buf(m_response+2,port); //Port
|
||||
htobe32buf(m_response+4,ip); //IP
|
||||
return boost::asio::const_buffers_1(m_response,8);
|
||||
}
|
||||
|
||||
boost::asio::const_buffers_1 SOCKSHandler::GenerateSOCKS5Response(SOCKSHandler::errTypes error, SOCKSHandler::addrTypes type, const SOCKSHandler::address &addr, uint16_t port)
|
||||
{
|
||||
size_t size = 6;
|
||||
assert(error <= SOCKS5_ADDR_UNSUP);
|
||||
m_response[0] = '\x05'; //Version
|
||||
m_response[1] = error; //Response code
|
||||
m_response[2] = '\x00'; //RSV
|
||||
m_response[3] = type; //Address type
|
||||
switch (type)
|
||||
{
|
||||
case ADDR_IPV4:
|
||||
size = 10;
|
||||
htobe32buf(m_response+4,addr.ip);
|
||||
break;
|
||||
case ADDR_IPV6:
|
||||
size = 22;
|
||||
memcpy(m_response+4,addr.ipv6, 16);
|
||||
break;
|
||||
case ADDR_DNS:
|
||||
size = 7+addr.dns.size;
|
||||
m_response[4] = addr.dns.size;
|
||||
memcpy(m_response+5,addr.dns.value, addr.dns.size);
|
||||
break;
|
||||
}
|
||||
htobe16buf(m_response+size-2,port); //Port
|
||||
return boost::asio::const_buffers_1(m_response,size);
|
||||
}
|
||||
|
||||
boost::asio::const_buffers_1 SOCKSHandler::GenerateUpstreamRequest()
|
||||
{
|
||||
size_t upstreamRequestSize = 0;
|
||||
// TODO: negotiate with upstream
|
||||
// SOCKS 4a
|
||||
m_upstream_request[0] = '\x04'; //version
|
||||
m_upstream_request[1] = m_cmd;
|
||||
htobe16buf(m_upstream_request+2, m_port);
|
||||
m_upstream_request[4] = 0;
|
||||
m_upstream_request[5] = 0;
|
||||
m_upstream_request[6] = 0;
|
||||
m_upstream_request[7] = 1;
|
||||
// user id
|
||||
m_upstream_request[8] = 'i';
|
||||
m_upstream_request[9] = '2';
|
||||
m_upstream_request[10] = 'p';
|
||||
m_upstream_request[11] = 'd';
|
||||
m_upstream_request[12] = 0;
|
||||
upstreamRequestSize += 13;
|
||||
if (m_address.dns.size <= max_socks_hostname_size - ( upstreamRequestSize + 1) ) {
|
||||
// bounds check okay
|
||||
memcpy(m_upstream_request + upstreamRequestSize, m_address.dns.value, m_address.dns.size);
|
||||
upstreamRequestSize += m_address.dns.size;
|
||||
// null terminate
|
||||
m_upstream_request[++upstreamRequestSize] = 0;
|
||||
} else {
|
||||
LogPrint(eLogError, "SOCKS: BUG!!! m_addr.dns.sizs > max_socks_hostname - ( upstreamRequestSize + 1 ) )");
|
||||
}
|
||||
return boost::asio::const_buffers_1(m_upstream_request, upstreamRequestSize);
|
||||
}
|
||||
|
||||
bool SOCKSHandler::Socks5ChooseAuth()
|
||||
{
|
||||
m_response[0] = '\x05'; //Version
|
||||
m_response[1] = m_authchosen; //Response code
|
||||
boost::asio::const_buffers_1 response(m_response,2);
|
||||
if (m_authchosen == AUTH_UNACCEPTABLE)
|
||||
{
|
||||
LogPrint(eLogWarning, "SOCKS: v5 authentication negotiation failed");
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksFailed,
|
||||
shared_from_this(), std::placeholders::_1));
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: v5 choosing authentication method: ", m_authchosen);
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksResponse,
|
||||
shared_from_this(), std::placeholders::_1));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/* All hope is lost beyond this point */
|
||||
void SOCKSHandler::SocksRequestFailed(SOCKSHandler::errTypes error)
|
||||
{
|
||||
boost::asio::const_buffers_1 response(nullptr,0);
|
||||
assert(error != SOCKS4_OK && error != SOCKS5_OK);
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS4:
|
||||
LogPrint(eLogWarning, "SOCKS: v4 request failed: ", error);
|
||||
if (error < SOCKS4_OK) error = SOCKS4_FAIL; //Transparently map SOCKS5 errors
|
||||
response = GenerateSOCKS4Response(error, m_4aip, m_port);
|
||||
break;
|
||||
case SOCKS5:
|
||||
LogPrint(eLogWarning, "SOCKS: v5 request failed: ", error);
|
||||
response = GenerateSOCKS5Response(error, m_addrtype, m_address, m_port);
|
||||
break;
|
||||
}
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksFailed,
|
||||
shared_from_this(), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SOCKSHandler::SocksRequestSuccess()
|
||||
{
|
||||
boost::asio::const_buffers_1 response(nullptr,0);
|
||||
//TODO: this should depend on things like the command type and callbacks may change
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS4:
|
||||
LogPrint(eLogInfo, "SOCKS: v4 connection success");
|
||||
response = GenerateSOCKS4Response(SOCKS4_OK, m_4aip, m_port);
|
||||
break;
|
||||
case SOCKS5:
|
||||
LogPrint(eLogInfo, "SOCKS: v5 connection success");
|
||||
auto s = i2p::client::context.GetAddressBook().ToAddress(GetOwner()->GetLocalDestination()->GetIdentHash());
|
||||
address ad; ad.dns.FromString(s);
|
||||
//HACK only 16 bits passed in port as SOCKS5 doesn't allow for more
|
||||
response = GenerateSOCKS5Response(SOCKS5_OK, ADDR_DNS, ad, m_stream->GetRecvStreamID());
|
||||
break;
|
||||
}
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksDone,
|
||||
shared_from_this(), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SOCKSHandler::EnterState(SOCKSHandler::state nstate, uint8_t parseleft) {
|
||||
switch (nstate)
|
||||
{
|
||||
case GET_PORT: parseleft = 2; break;
|
||||
case GET_IPV4: m_addrtype = ADDR_IPV4; m_address.ip = 0; parseleft = 4; break;
|
||||
case GET4_IDENT: m_4aip = m_address.ip; break;
|
||||
case GET4A_HOST:
|
||||
case GET5_HOST: m_addrtype = ADDR_DNS; m_address.dns.size = 0; break;
|
||||
case GET5_IPV6: m_addrtype = ADDR_IPV6; parseleft = 16; break;
|
||||
default:;
|
||||
}
|
||||
m_parseleft = parseleft;
|
||||
m_state = nstate;
|
||||
}
|
||||
|
||||
bool SOCKSHandler::ValidateSOCKSRequest()
|
||||
{
|
||||
if ( m_cmd != CMD_CONNECT )
|
||||
{
|
||||
//TODO: we need to support binds and other shit!
|
||||
LogPrint(eLogError, "SOCKS: unsupported command: ", m_cmd);
|
||||
SocksRequestFailed(SOCKS5_CMD_UNSUP);
|
||||
return false;
|
||||
}
|
||||
//TODO: we may want to support other address types!
|
||||
if ( m_addrtype != ADDR_DNS )
|
||||
{
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS5:
|
||||
LogPrint(eLogError, "SOCKS: v5 unsupported address type: ", m_addrtype);
|
||||
break;
|
||||
case SOCKS4:
|
||||
LogPrint(eLogError, "SOCKS: request with v4a rejected because it's actually SOCKS4");
|
||||
break;
|
||||
}
|
||||
SocksRequestFailed(SOCKS5_ADDR_UNSUP);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool 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
|
||||
while (len > 0)
|
||||
{
|
||||
switch (m_state)
|
||||
{
|
||||
case GET_SOCKSV:
|
||||
m_socksv = (SOCKSHandler::socksVersions) *sock_buff;
|
||||
switch (*sock_buff)
|
||||
{
|
||||
case SOCKS4:
|
||||
EnterState(GET_COMMAND); //Initialize the parser at the right position
|
||||
break;
|
||||
case SOCKS5:
|
||||
EnterState(GET5_AUTHNUM); //Initialize the parser at the right position
|
||||
break;
|
||||
default:
|
||||
LogPrint(eLogError, "SOCKS: rejected invalid version: ", ((int)*sock_buff));
|
||||
Terminate();
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case GET5_AUTHNUM:
|
||||
EnterState(GET5_AUTH, *sock_buff);
|
||||
break;
|
||||
case GET5_AUTH:
|
||||
m_parseleft --;
|
||||
if (*sock_buff == AUTH_NONE)
|
||||
m_authchosen = AUTH_NONE;
|
||||
if ( m_parseleft == 0 )
|
||||
{
|
||||
if (!Socks5ChooseAuth()) return false;
|
||||
EnterState(GET5_REQUESTV);
|
||||
}
|
||||
break;
|
||||
case GET_COMMAND:
|
||||
switch (*sock_buff)
|
||||
{
|
||||
case CMD_CONNECT:
|
||||
case CMD_BIND:
|
||||
break;
|
||||
case CMD_UDP:
|
||||
if (m_socksv == SOCKS5) break;
|
||||
default:
|
||||
LogPrint(eLogError, "SOCKS: invalid command: ", ((int)*sock_buff));
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
return false;
|
||||
}
|
||||
m_cmd = (SOCKSHandler::cmdTypes)*sock_buff;
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS5: EnterState(GET5_GETRSV); break;
|
||||
case SOCKS4: EnterState(GET_PORT); break;
|
||||
}
|
||||
break;
|
||||
case GET_PORT:
|
||||
m_port = (m_port << 8)|((uint16_t)*sock_buff);
|
||||
m_parseleft--;
|
||||
if (m_parseleft == 0)
|
||||
{
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS5: EnterState(READY); break;
|
||||
case SOCKS4: EnterState(GET_IPV4); break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case GET_IPV4:
|
||||
m_address.ip = (m_address.ip << 8)|((uint32_t)*sock_buff);
|
||||
m_parseleft--;
|
||||
if (m_parseleft == 0)
|
||||
{
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS5: EnterState(GET_PORT); break;
|
||||
case SOCKS4: EnterState(GET4_IDENT); m_4aip = m_address.ip; break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case GET4_IDENT:
|
||||
if (!*sock_buff)
|
||||
{
|
||||
if( m_4aip == 0 || m_4aip > 255 )
|
||||
EnterState(READY);
|
||||
else
|
||||
EnterState(GET4A_HOST);
|
||||
}
|
||||
break;
|
||||
case GET4A_HOST:
|
||||
if (!*sock_buff)
|
||||
{
|
||||
EnterState(READY);
|
||||
break;
|
||||
}
|
||||
if (m_address.dns.size >= max_socks_hostname_size)
|
||||
{
|
||||
LogPrint(eLogError, "SOCKS: v4a req failed: destination is too large");
|
||||
SocksRequestFailed(SOCKS4_FAIL);
|
||||
return false;
|
||||
}
|
||||
m_address.dns.push_back(*sock_buff);
|
||||
break;
|
||||
case GET5_REQUESTV:
|
||||
if (*sock_buff != SOCKS5)
|
||||
{
|
||||
LogPrint(eLogError,"SOCKS: v5 rejected unknown request version: ", ((int)*sock_buff));
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
return false;
|
||||
}
|
||||
EnterState(GET_COMMAND);
|
||||
break;
|
||||
case GET5_GETRSV:
|
||||
if ( *sock_buff != 0 )
|
||||
{
|
||||
LogPrint(eLogError, "SOCKS: v5 unknown reserved field: ", ((int)*sock_buff));
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
return false;
|
||||
}
|
||||
EnterState(GET5_GETADDRTYPE);
|
||||
break;
|
||||
case GET5_GETADDRTYPE:
|
||||
switch (*sock_buff)
|
||||
{
|
||||
case ADDR_IPV4: EnterState(GET_IPV4); break;
|
||||
case ADDR_IPV6: EnterState(GET5_IPV6); break;
|
||||
case ADDR_DNS : EnterState(GET5_HOST_SIZE); break;
|
||||
default:
|
||||
LogPrint(eLogError, "SOCKS: v5 unknown address type: ", ((int)*sock_buff));
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case GET5_IPV6:
|
||||
m_address.ipv6[16-m_parseleft] = *sock_buff;
|
||||
m_parseleft--;
|
||||
if (m_parseleft == 0) EnterState(GET_PORT);
|
||||
break;
|
||||
case GET5_HOST_SIZE:
|
||||
EnterState(GET5_HOST, *sock_buff);
|
||||
break;
|
||||
case GET5_HOST:
|
||||
m_address.dns.push_back(*sock_buff);
|
||||
m_parseleft--;
|
||||
if (m_parseleft == 0) EnterState(GET_PORT);
|
||||
break;
|
||||
default:
|
||||
LogPrint(eLogError, "SOCKS: parse state?? ", m_state);
|
||||
Terminate();
|
||||
return false;
|
||||
}
|
||||
sock_buff++;
|
||||
len--;
|
||||
if (m_state == READY)
|
||||
{
|
||||
m_remaining_data_len = len;
|
||||
m_remaining_data = sock_buff;
|
||||
return ValidateSOCKSRequest();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: recieved ", len, " bytes");
|
||||
if(ecode)
|
||||
{
|
||||
LogPrint(eLogWarning, "SOCKS: recv got error: ", ecode);
|
||||
Terminate();
|
||||
return;
|
||||
}
|
||||
|
||||
if (HandleData(m_sock_buff, len))
|
||||
{
|
||||
if (m_state == READY)
|
||||
{
|
||||
const std::string addr = m_address.dns.ToString();
|
||||
LogPrint(eLogInfo, "SOCKS: requested ", addr, ":" , m_port);
|
||||
const size_t addrlen = addr.size();
|
||||
// does it end with .i2p?
|
||||
if ( addr.rfind(".i2p") == addrlen - 4) {
|
||||
// yes it does, make an i2p session
|
||||
GetOwner()->CreateStream ( std::bind (&SOCKSHandler::HandleStreamRequestComplete,
|
||||
shared_from_this(), std::placeholders::_1), m_address.dns.ToString(), m_port);
|
||||
} else if (m_UseUpstreamProxy) {
|
||||
// forward it to upstream proxy
|
||||
ForwardSOCKS();
|
||||
} else {
|
||||
// no upstream proxy
|
||||
SocksRequestFailed(SOCKS5_ADDR_UNSUP);
|
||||
}
|
||||
}
|
||||
else
|
||||
AsyncSockRead();
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::SentSocksFailed(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (ecode)
|
||||
LogPrint (eLogError, "SOCKS: closing socket after sending failure because: ", ecode.message ());
|
||||
Terminate();
|
||||
}
|
||||
|
||||
void SOCKSHandler::SentSocksDone(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
if (Kill()) return;
|
||||
LogPrint (eLogInfo, "SOCKS: new I2PTunnel connection");
|
||||
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, m_stream);
|
||||
GetOwner()->AddHandler (connection);
|
||||
connection->I2PConnect (m_remaining_data,m_remaining_data_len);
|
||||
Done(shared_from_this());
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "SOCKS: closing socket after completion reply because: ", ecode.message ());
|
||||
Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::SentSocksResponse(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "SOCKS: closing socket after sending reply because: ", ecode.message ());
|
||||
Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
m_stream = stream;
|
||||
SocksRequestSuccess();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "SOCKS: error when creating the stream, check the previous warnings for more info");
|
||||
SocksRequestFailed(SOCKS5_HOST_UNREACH);
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::ForwardSOCKS()
|
||||
{
|
||||
LogPrint(eLogInfo, "SOCKS: forwarding to upstream");
|
||||
EnterState(UPSTREAM_RESOLVE);
|
||||
boost::asio::ip::tcp::resolver::query q(m_UpstreamProxyAddress, std::to_string(m_UpstreamProxyPort));
|
||||
m_proxy_resolver.async_resolve(q, std::bind(&SOCKSHandler::HandleUpstreamResolved, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void SOCKSHandler::AsyncUpstreamSockRead()
|
||||
{
|
||||
LogPrint(eLogDebug, "SOCKS: async upstream sock read");
|
||||
if (m_upstreamSock) {
|
||||
m_upstreamSock->async_read_some(boost::asio::buffer(m_upstream_response, SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE),
|
||||
std::bind(&SOCKSHandler::HandleUpstreamSockRecv, shared_from_this(),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
} else {
|
||||
LogPrint(eLogError, "SOCKS: no upstream socket for read");
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleUpstreamSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered)
|
||||
{
|
||||
if (ecode) {
|
||||
if (m_state == UPSTREAM_HANDSHAKE ) {
|
||||
// we are trying to handshake but it failed
|
||||
SocksRequestFailed(SOCKS5_NET_UNREACH);
|
||||
} else {
|
||||
LogPrint(eLogError, "SOCKS: bad state when reading from upstream: ", (int) m_state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
HandleUpstreamData(m_upstream_response, bytes_transfered);
|
||||
}
|
||||
|
||||
void SOCKSHandler::SocksUpstreamSuccess()
|
||||
{
|
||||
LogPrint(eLogInfo, "SOCKS: upstream success");
|
||||
boost::asio::const_buffers_1 response(nullptr, 0);
|
||||
switch (m_socksv)
|
||||
{
|
||||
case SOCKS4:
|
||||
LogPrint(eLogInfo, "SOCKS: v4 connection success");
|
||||
response = GenerateSOCKS4Response(SOCKS4_OK, m_4aip, m_port);
|
||||
break;
|
||||
case SOCKS5:
|
||||
LogPrint(eLogInfo, "SOCKS: v5 connection success");
|
||||
//HACK only 16 bits passed in port as SOCKS5 doesn't allow for more
|
||||
response = GenerateSOCKS5Response(SOCKS5_OK, ADDR_DNS, m_address, m_port);
|
||||
break;
|
||||
}
|
||||
m_sock->send(response);
|
||||
auto forwarder = std::make_shared<i2p::client::TCPIPPipe>(GetOwner(), m_sock, m_upstreamSock);
|
||||
m_upstreamSock = nullptr;
|
||||
m_sock = nullptr;
|
||||
GetOwner()->AddHandler(forwarder);
|
||||
forwarder->Start();
|
||||
Terminate();
|
||||
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleUpstreamData(uint8_t * dataptr, std::size_t len)
|
||||
{
|
||||
if (m_state == UPSTREAM_HANDSHAKE) {
|
||||
m_upstream_response_len += len;
|
||||
// handle handshake data
|
||||
if (m_upstream_response_len < SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE) {
|
||||
// too small, continue reading
|
||||
AsyncUpstreamSockRead();
|
||||
} else if (len == SOCKS_UPSTREAM_SOCKS4A_REPLY_SIZE) {
|
||||
// just right
|
||||
uint8_t resp = m_upstream_response[1];
|
||||
if (resp == SOCKS4_OK) {
|
||||
// we have connected !
|
||||
SocksUpstreamSuccess();
|
||||
} else {
|
||||
// upstream failure
|
||||
LogPrint(eLogError, "SOCKS: upstream proxy failure: ", (int) resp);
|
||||
// TODO: runtime error?
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
}
|
||||
} else {
|
||||
// too big
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
}
|
||||
} else {
|
||||
// invalid state
|
||||
LogPrint(eLogError, "SOCKS: invalid state reading from upstream: ", (int) m_state);
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::SendUpstreamRequest()
|
||||
{
|
||||
LogPrint(eLogInfo, "SOCKS: negotiating with upstream proxy");
|
||||
EnterState(UPSTREAM_HANDSHAKE);
|
||||
if (m_upstreamSock) {
|
||||
boost::asio::write(*m_upstreamSock,
|
||||
GenerateUpstreamRequest());
|
||||
AsyncUpstreamSockRead();
|
||||
} else {
|
||||
LogPrint(eLogError, "SOCKS: no upstream socket to send handshake to");
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleUpstreamConnected(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr)
|
||||
{
|
||||
if (ecode) {
|
||||
LogPrint(eLogWarning, "SOCKS: could not connect to upstream proxy: ", ecode.message());
|
||||
SocksRequestFailed(SOCKS5_NET_UNREACH);
|
||||
return;
|
||||
}
|
||||
LogPrint(eLogInfo, "SOCKS: connected to upstream proxy");
|
||||
SendUpstreamRequest();
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleUpstreamResolved(const boost::system::error_code & ecode, boost::asio::ip::tcp::resolver::iterator itr)
|
||||
{
|
||||
if (ecode) {
|
||||
// error resolving
|
||||
LogPrint(eLogWarning, "SOCKS: upstream proxy", m_UpstreamProxyAddress, " not resolved: ", ecode.message());
|
||||
SocksRequestFailed(SOCKS5_NET_UNREACH);
|
||||
return;
|
||||
}
|
||||
LogPrint(eLogInfo, "SOCKS: upstream proxy resolved");
|
||||
EnterState(UPSTREAM_CONNECT);
|
||||
auto & service = GetOwner()->GetService();
|
||||
m_upstreamSock = std::make_shared<boost::asio::ip::tcp::socket>(service);
|
||||
boost::asio::async_connect(*m_upstreamSock, itr,
|
||||
std::bind(&SOCKSHandler::HandleUpstreamConnected,
|
||||
shared_from_this(), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
SOCKSServer::SOCKSServer(const std::string& address, int port, const std::string& outAddress, uint16_t outPort,
|
||||
std::shared_ptr<i2p::client::ClientDestination> localDestination) :
|
||||
TCPIPAcceptor (address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
|
||||
{
|
||||
m_UseUpstreamProxy = false;
|
||||
if (outAddress.length() > 0)
|
||||
SetUpstreamProxy(outAddress, outPort);
|
||||
}
|
||||
|
||||
std::shared_ptr<i2p::client::I2PServiceHandler> SOCKSServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
|
||||
{
|
||||
return std::make_shared<SOCKSHandler> (this, socket, m_UpstreamProxyAddress, m_UpstreamProxyPort, m_UseUpstreamProxy);
|
||||
}
|
||||
|
||||
void SOCKSServer::SetUpstreamProxy(const std::string & addr, const uint16_t port)
|
||||
{
|
||||
m_UpstreamProxyAddress = addr;
|
||||
m_UpstreamProxyPort = port;
|
||||
m_UseUpstreamProxy = true;
|
||||
}
|
||||
}
|
||||
}
|
40
libi2pd_client/SOCKS.h
Normal file
40
libi2pd_client/SOCKS.h
Normal file
|
@ -0,0 +1,40 @@
|
|||
#ifndef SOCKS_H__
|
||||
#define SOCKS_H__
|
||||
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <boost/asio.hpp>
|
||||
#include <mutex>
|
||||
#include "I2PService.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace proxy
|
||||
{
|
||||
class SOCKSServer: public i2p::client::TCPIPAcceptor
|
||||
{
|
||||
public:
|
||||
|
||||
SOCKSServer(const std::string& address, int port, const std::string& outAddress, uint16_t outPort,
|
||||
std::shared_ptr<i2p::client::ClientDestination> localDestination = nullptr);
|
||||
~SOCKSServer() {};
|
||||
|
||||
void SetUpstreamProxy(const std::string & addr, const uint16_t port);
|
||||
|
||||
protected:
|
||||
// Implements TCPIPAcceptor
|
||||
std::shared_ptr<i2p::client::I2PServiceHandler> CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket);
|
||||
const char* GetName() { return "SOCKS"; }
|
||||
|
||||
private:
|
||||
std::string m_UpstreamProxyAddress;
|
||||
uint16_t m_UpstreamProxyPort;
|
||||
bool m_UseUpstreamProxy;
|
||||
};
|
||||
|
||||
typedef SOCKSServer SOCKSProxy;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
467
libi2pd_client/WebSocks.cpp
Normal file
467
libi2pd_client/WebSocks.cpp
Normal file
|
@ -0,0 +1,467 @@
|
|||
#include "WebSocks.h"
|
||||
#include "Log.h"
|
||||
#include <string>
|
||||
|
||||
#ifdef WITH_EVENTS
|
||||
#include "ClientContext.h"
|
||||
#include "Identity.h"
|
||||
#include "Destination.h"
|
||||
#include "Streaming.h"
|
||||
#include <functional>
|
||||
|
||||
#include <websocketpp/config/asio_no_tls.hpp>
|
||||
#include <websocketpp/server.hpp>
|
||||
|
||||
#include <boost/property_tree/ini_parser.hpp>
|
||||
#define GCC47_BOOST149 ((BOOST_VERSION == 104900) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))
|
||||
#if !GCC47_BOOST149
|
||||
#include <boost/property_tree/json_parser.hpp>
|
||||
#endif
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
typedef websocketpp::server<websocketpp::config::asio> WebSocksServerImpl;
|
||||
|
||||
typedef std::function<void(std::shared_ptr<i2p::stream::Stream>)> StreamConnectFunc;
|
||||
|
||||
|
||||
struct IWebSocksConn : public I2PServiceHandler
|
||||
{
|
||||
IWebSocksConn(I2PService * parent) : I2PServiceHandler(parent) {}
|
||||
virtual void Close() = 0;
|
||||
virtual void GotMessage(const websocketpp::connection_hdl & conn, WebSocksServerImpl::message_ptr msg) = 0;
|
||||
};
|
||||
|
||||
typedef std::shared_ptr<IWebSocksConn> WebSocksConn_ptr;
|
||||
|
||||
WebSocksConn_ptr CreateWebSocksConn(const websocketpp::connection_hdl & conn, WebSocksImpl * parent);
|
||||
|
||||
class WebSocksImpl
|
||||
{
|
||||
|
||||
typedef std::mutex mutex_t;
|
||||
typedef std::unique_lock<mutex_t> lock_t;
|
||||
|
||||
typedef std::shared_ptr<ClientDestination> Destination_t;
|
||||
public:
|
||||
|
||||
typedef WebSocksServerImpl ServerImpl;
|
||||
typedef ServerImpl::message_ptr MessagePtr;
|
||||
|
||||
WebSocksImpl(const std::string & addr, int port) :
|
||||
Parent(nullptr),
|
||||
m_Run(false),
|
||||
m_Addr(addr),
|
||||
m_Port(port),
|
||||
m_Thread(nullptr)
|
||||
{
|
||||
m_Server.init_asio();
|
||||
m_Server.set_open_handler(std::bind(&WebSocksImpl::ConnOpened, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void InitializeDestination(WebSocks * parent)
|
||||
{
|
||||
Parent = parent;
|
||||
m_Dest = Parent->GetLocalDestination();
|
||||
}
|
||||
|
||||
ServerImpl::connection_ptr GetConn(const websocketpp::connection_hdl & conn)
|
||||
{
|
||||
return m_Server.get_con_from_hdl(conn);
|
||||
}
|
||||
|
||||
void CloseConn(const websocketpp::connection_hdl & conn)
|
||||
{
|
||||
auto c = GetConn(conn);
|
||||
if(c) c->close(websocketpp::close::status::normal, "closed");
|
||||
}
|
||||
|
||||
void CreateStreamTo(const std::string & addr, int port, StreamConnectFunc complete)
|
||||
{
|
||||
auto & addressbook = i2p::client::context.GetAddressBook();
|
||||
i2p::data::IdentHash ident;
|
||||
if(addressbook.GetIdentHash(addr, ident)) {
|
||||
// address found
|
||||
m_Dest->CreateStream(complete, ident, port);
|
||||
} else {
|
||||
// not found
|
||||
complete(nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
void ConnOpened(websocketpp::connection_hdl conn)
|
||||
{
|
||||
auto ptr = CreateWebSocksConn(conn, this);
|
||||
Parent->AddHandler(ptr);
|
||||
m_Conns.push_back(ptr);
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if(m_Run) return; // already started
|
||||
m_Server.listen(boost::asio::ip::address::from_string(m_Addr), m_Port);
|
||||
m_Server.start_accept();
|
||||
m_Run = true;
|
||||
m_Thread = new std::thread([&] (){
|
||||
while(m_Run) {
|
||||
try {
|
||||
m_Server.run();
|
||||
} catch( std::exception & ex) {
|
||||
LogPrint(eLogError, "Websocks runtime exception: ", ex.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
m_Dest->Start();
|
||||
}
|
||||
|
||||
void Stop()
|
||||
{
|
||||
for(const auto & conn : m_Conns)
|
||||
conn->Close();
|
||||
|
||||
m_Dest->Stop();
|
||||
m_Run = false;
|
||||
m_Server.stop();
|
||||
if(m_Thread) {
|
||||
m_Thread->join();
|
||||
delete m_Thread;
|
||||
}
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::endpoint GetLocalEndpoint()
|
||||
{
|
||||
return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(m_Addr), m_Port);
|
||||
}
|
||||
|
||||
WebSocks * Parent;
|
||||
|
||||
private:
|
||||
std::vector<WebSocksConn_ptr> m_Conns;
|
||||
bool m_Run;
|
||||
ServerImpl m_Server;
|
||||
std::string m_Addr;
|
||||
int m_Port;
|
||||
std::thread * m_Thread;
|
||||
Destination_t m_Dest;
|
||||
};
|
||||
|
||||
struct WebSocksConn : public IWebSocksConn , public std::enable_shared_from_this<WebSocksConn>
|
||||
{
|
||||
enum ConnState
|
||||
{
|
||||
eWSCInitial,
|
||||
eWSCTryConnect,
|
||||
eWSCFailConnect,
|
||||
eWSCOkayConnect,
|
||||
eWSCClose,
|
||||
eWSCEnd
|
||||
};
|
||||
|
||||
typedef WebSocksServerImpl ServerImpl;
|
||||
typedef ServerImpl::message_ptr Message_t;
|
||||
typedef websocketpp::connection_hdl ServerConn;
|
||||
typedef std::shared_ptr<ClientDestination> Destination_t;
|
||||
typedef std::shared_ptr<i2p::stream::StreamingDestination> StreamDest_t;
|
||||
typedef std::shared_ptr<i2p::stream::Stream> Stream_t;
|
||||
|
||||
ServerConn m_Conn;
|
||||
Stream_t m_Stream;
|
||||
ConnState m_State;
|
||||
WebSocksImpl * m_Parent;
|
||||
std::string m_RemoteAddr;
|
||||
int m_RemotePort;
|
||||
uint8_t m_RecvBuf[2048];
|
||||
|
||||
WebSocksConn(const ServerConn & conn, WebSocksImpl * parent) :
|
||||
IWebSocksConn(parent->Parent),
|
||||
m_Conn(conn),
|
||||
m_Stream(nullptr),
|
||||
m_State(eWSCInitial),
|
||||
m_Parent(parent)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
~WebSocksConn()
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
void EnterState(ConnState state)
|
||||
{
|
||||
LogPrint(eLogDebug, "websocks: state ", m_State, " -> ", state);
|
||||
switch(m_State)
|
||||
{
|
||||
case eWSCInitial:
|
||||
if (state == eWSCClose) {
|
||||
m_State = eWSCClose;
|
||||
// connection was opened but never used
|
||||
LogPrint(eLogInfo, "websocks: connection closed but never used");
|
||||
Close();
|
||||
return;
|
||||
} else if (state == eWSCTryConnect) {
|
||||
// we will try to connect
|
||||
m_State = eWSCTryConnect;
|
||||
m_Parent->CreateStreamTo(m_RemoteAddr, m_RemotePort, std::bind(&WebSocksConn::ConnectResult, this, std::placeholders::_1));
|
||||
} else {
|
||||
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
|
||||
}
|
||||
return;
|
||||
case eWSCTryConnect:
|
||||
if(state == eWSCOkayConnect) {
|
||||
// we connected okay
|
||||
LogPrint(eLogDebug, "websocks: connected to ", m_RemoteAddr, ":", m_RemotePort);
|
||||
SendResponse("");
|
||||
m_State = eWSCOkayConnect;
|
||||
} else if(state == eWSCFailConnect) {
|
||||
// we did not connect okay
|
||||
LogPrint(eLogDebug, "websocks: failed to connect to ", m_RemoteAddr, ":", m_RemotePort);
|
||||
SendResponse("failed to connect");
|
||||
m_State = eWSCFailConnect;
|
||||
EnterState(eWSCInitial);
|
||||
} else if(state == eWSCClose) {
|
||||
// premature close
|
||||
LogPrint(eLogWarning, "websocks: websocket connection closed prematurely");
|
||||
m_State = eWSCClose;
|
||||
} else {
|
||||
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
|
||||
}
|
||||
return;
|
||||
case eWSCFailConnect:
|
||||
if (state == eWSCInitial) {
|
||||
// reset to initial state so we can try connecting again
|
||||
m_RemoteAddr = "";
|
||||
m_RemotePort = 0;
|
||||
LogPrint(eLogDebug, "websocks: reset websocket conn to initial state");
|
||||
m_State = eWSCInitial;
|
||||
} else if (state == eWSCClose) {
|
||||
// we are going to close the connection
|
||||
m_State = eWSCClose;
|
||||
Close();
|
||||
} else {
|
||||
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
|
||||
}
|
||||
return;
|
||||
case eWSCOkayConnect:
|
||||
if(state == eWSCClose) {
|
||||
// graceful close
|
||||
m_State = eWSCClose;
|
||||
Close();
|
||||
} else {
|
||||
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
|
||||
}
|
||||
case eWSCClose:
|
||||
if(state == eWSCEnd) {
|
||||
LogPrint(eLogDebug, "websocks: socket ended");
|
||||
Kill();
|
||||
auto me = shared_from_this();
|
||||
Done(me);
|
||||
} else {
|
||||
LogPrint(eLogWarning, "websocks: invalid state change ", m_State, " -> ", state);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
LogPrint(eLogError, "websocks: bad state ", m_State);
|
||||
}
|
||||
}
|
||||
|
||||
void StartForwarding()
|
||||
{
|
||||
LogPrint(eLogDebug, "websocks: begin forwarding data");
|
||||
uint8_t b[1];
|
||||
m_Stream->Send(b, 0);
|
||||
AsyncRecv();
|
||||
}
|
||||
|
||||
void HandleAsyncRecv(const boost::system::error_code &ec, std::size_t n)
|
||||
{
|
||||
if(ec) {
|
||||
// error
|
||||
LogPrint(eLogWarning, "websocks: connection error ", ec.message());
|
||||
EnterState(eWSCClose);
|
||||
} else {
|
||||
// forward data
|
||||
LogPrint(eLogDebug, "websocks recv ", n);
|
||||
|
||||
std::string str((char*)m_RecvBuf, n);
|
||||
auto conn = m_Parent->GetConn(m_Conn);
|
||||
if(!conn) {
|
||||
LogPrint(eLogWarning, "websocks: connection is gone");
|
||||
EnterState(eWSCClose);
|
||||
return;
|
||||
}
|
||||
conn->send(str);
|
||||
AsyncRecv();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncRecv()
|
||||
{
|
||||
m_Stream->AsyncReceive(
|
||||
boost::asio::buffer(m_RecvBuf, sizeof(m_RecvBuf)),
|
||||
std::bind(&WebSocksConn::HandleAsyncRecv, this, std::placeholders::_1, std::placeholders::_2), 60);
|
||||
}
|
||||
|
||||
/** @brief send error message or empty string for success */
|
||||
void SendResponse(const std::string & errormsg)
|
||||
{
|
||||
boost::property_tree::ptree resp;
|
||||
if(errormsg.size()) {
|
||||
resp.put("error", errormsg);
|
||||
resp.put("success", 0);
|
||||
} else {
|
||||
resp.put("success", 1);
|
||||
}
|
||||
std::ostringstream ss;
|
||||
write_json(ss, resp);
|
||||
auto conn = m_Parent->GetConn(m_Conn);
|
||||
if(conn) conn->send(ss.str());
|
||||
}
|
||||
|
||||
void ConnectResult(Stream_t stream)
|
||||
{
|
||||
m_Stream = stream;
|
||||
if(m_State == eWSCClose) {
|
||||
// premature close of websocket
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
if(m_Stream) {
|
||||
// connect good
|
||||
EnterState(eWSCOkayConnect);
|
||||
StartForwarding();
|
||||
} else {
|
||||
// connect failed
|
||||
EnterState(eWSCFailConnect);
|
||||
}
|
||||
}
|
||||
|
||||
virtual void GotMessage(const websocketpp::connection_hdl & conn, WebSocksServerImpl::message_ptr msg)
|
||||
{
|
||||
(void) conn;
|
||||
std::string payload = msg->get_payload();
|
||||
if(m_State == eWSCOkayConnect)
|
||||
{
|
||||
// forward to server
|
||||
LogPrint(eLogDebug, "websocks: forward ", payload.size());
|
||||
m_Stream->Send((uint8_t*)payload.c_str(), payload.size());
|
||||
} else if (m_State == eWSCInitial) {
|
||||
// recv connect request
|
||||
auto itr = payload.find(":");
|
||||
if(itr == std::string::npos) {
|
||||
// no port
|
||||
m_RemotePort = 0;
|
||||
m_RemoteAddr = payload;
|
||||
} else {
|
||||
// includes port
|
||||
m_RemotePort = std::stoi(payload.substr(itr+1));
|
||||
m_RemoteAddr = payload.substr(0, itr);
|
||||
}
|
||||
EnterState(eWSCTryConnect);
|
||||
} else {
|
||||
// wtf?
|
||||
LogPrint(eLogWarning, "websocks: got message in invalid state ", m_State);
|
||||
}
|
||||
}
|
||||
|
||||
virtual void Close()
|
||||
{
|
||||
if(m_State == eWSCClose) {
|
||||
LogPrint(eLogDebug, "websocks: closing connection");
|
||||
if(m_Stream) m_Stream->Close();
|
||||
m_Parent->CloseConn(m_Conn);
|
||||
EnterState(eWSCEnd);
|
||||
} else {
|
||||
EnterState(eWSCClose);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
WebSocksConn_ptr CreateWebSocksConn(const websocketpp::connection_hdl & conn, WebSocksImpl * parent)
|
||||
{
|
||||
auto ptr = std::make_shared<WebSocksConn>(conn, parent);
|
||||
auto c = parent->GetConn(conn);
|
||||
c->set_message_handler(std::bind(&WebSocksConn::GotMessage, ptr.get(), std::placeholders::_1, std::placeholders::_2));
|
||||
return ptr;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
#else
|
||||
|
||||
// no websocket support
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
class WebSocksImpl
|
||||
{
|
||||
public:
|
||||
WebSocksImpl(const std::string & addr, int port) : m_Addr(addr), m_Port(port)
|
||||
{
|
||||
}
|
||||
|
||||
~WebSocksImpl()
|
||||
{
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
LogPrint(eLogInfo, "WebSockets not enabled on compile time");
|
||||
}
|
||||
|
||||
void Stop()
|
||||
{
|
||||
}
|
||||
|
||||
void InitializeDestination(WebSocks * parent)
|
||||
{
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::endpoint GetLocalEndpoint()
|
||||
{
|
||||
return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(m_Addr), m_Port);
|
||||
}
|
||||
|
||||
std::string m_Addr;
|
||||
int m_Port;
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
WebSocks::WebSocks(const std::string & addr, int port, std::shared_ptr<ClientDestination> localDestination) : m_Impl(new WebSocksImpl(addr, port))
|
||||
{
|
||||
m_Impl->InitializeDestination(this);
|
||||
}
|
||||
WebSocks::~WebSocks() { delete m_Impl; }
|
||||
|
||||
void WebSocks::Start()
|
||||
{
|
||||
m_Impl->Start();
|
||||
GetLocalDestination()->Start();
|
||||
}
|
||||
|
||||
boost::asio::ip::tcp::endpoint WebSocks::GetLocalEndpoint() const
|
||||
{
|
||||
return m_Impl->GetLocalEndpoint();
|
||||
}
|
||||
|
||||
void WebSocks::Stop()
|
||||
{
|
||||
m_Impl->Stop();
|
||||
GetLocalDestination()->Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
34
libi2pd_client/WebSocks.h
Normal file
34
libi2pd_client/WebSocks.h
Normal file
|
@ -0,0 +1,34 @@
|
|||
#ifndef WEBSOCKS_H_
|
||||
#define WEBSOCKS_H_
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include "I2PService.h"
|
||||
#include "Destination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
|
||||
class WebSocksImpl;
|
||||
|
||||
/** @brief websocket socks proxy server */
|
||||
class WebSocks : public i2p::client::I2PService
|
||||
{
|
||||
public:
|
||||
WebSocks(const std::string & addr, int port, std::shared_ptr<ClientDestination> localDestination);
|
||||
~WebSocks();
|
||||
|
||||
void Start();
|
||||
void Stop();
|
||||
|
||||
boost::asio::ip::tcp::endpoint GetLocalEndpoint() const;
|
||||
|
||||
const char * GetName() { return "WebSOCKS Proxy"; }
|
||||
|
||||
private:
|
||||
WebSocksImpl * m_Impl;
|
||||
};
|
||||
}
|
||||
}
|
||||
#endif
|
195
libi2pd_client/Websocket.cpp
Normal file
195
libi2pd_client/Websocket.cpp
Normal file
|
@ -0,0 +1,195 @@
|
|||
#ifdef USE_EVENTS
|
||||
#include "Websocket.h"
|
||||
#include "Log.h"
|
||||
|
||||
#include <set>
|
||||
#include <functional>
|
||||
|
||||
#include <websocketpp/config/asio_no_tls.hpp>
|
||||
#include <websocketpp/server.hpp>
|
||||
#include <boost/property_tree/ini_parser.hpp>
|
||||
#define GCC47_BOOST149 ((BOOST_VERSION == 104900) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))
|
||||
#if !GCC47_BOOST149
|
||||
#include <boost/property_tree/json_parser.hpp>
|
||||
#endif
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace event
|
||||
{
|
||||
|
||||
typedef websocketpp::server<websocketpp::config::asio> ServerImpl;
|
||||
typedef websocketpp::connection_hdl ServerConn;
|
||||
|
||||
class WebsocketServerImpl : public EventListener
|
||||
{
|
||||
private:
|
||||
typedef ServerImpl::message_ptr MessagePtr;
|
||||
public:
|
||||
|
||||
WebsocketServerImpl(const std::string & addr, int port) :
|
||||
m_run(false),
|
||||
m_ws_thread(nullptr),
|
||||
m_ev_thread(nullptr),
|
||||
m_WebsocketTicker(m_Service)
|
||||
{
|
||||
m_server.init_asio();
|
||||
m_server.set_open_handler(std::bind(&WebsocketServerImpl::ConnOpened, this, std::placeholders::_1));
|
||||
m_server.set_close_handler(std::bind(&WebsocketServerImpl::ConnClosed, this, std::placeholders::_1));
|
||||
m_server.set_message_handler(std::bind(&WebsocketServerImpl::OnConnMessage, this, std::placeholders::_1, std::placeholders::_2));
|
||||
|
||||
m_server.listen(boost::asio::ip::address::from_string(addr), port);
|
||||
}
|
||||
|
||||
~WebsocketServerImpl()
|
||||
{
|
||||
}
|
||||
|
||||
void Start() {
|
||||
m_run = true;
|
||||
m_server.start_accept();
|
||||
m_ws_thread = new std::thread([&] () {
|
||||
while(m_run) {
|
||||
try {
|
||||
m_server.run();
|
||||
} catch (std::exception & e ) {
|
||||
LogPrint(eLogError, "Websocket server: ", e.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
m_ev_thread = new std::thread([&] () {
|
||||
while(m_run) {
|
||||
try {
|
||||
m_Service.run();
|
||||
break;
|
||||
} catch (std::exception & e ) {
|
||||
LogPrint(eLogError, "Websocket service: ", e.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
ScheduleTick();
|
||||
}
|
||||
|
||||
void Stop() {
|
||||
m_run = false;
|
||||
m_Service.stop();
|
||||
m_server.stop();
|
||||
|
||||
if(m_ev_thread) {
|
||||
m_ev_thread->join();
|
||||
delete m_ev_thread;
|
||||
}
|
||||
m_ev_thread = nullptr;
|
||||
|
||||
if(m_ws_thread) {
|
||||
m_ws_thread->join();
|
||||
delete m_ws_thread;
|
||||
}
|
||||
m_ws_thread = nullptr;
|
||||
}
|
||||
|
||||
void ConnOpened(ServerConn c)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connsMutex);
|
||||
m_conns.insert(c);
|
||||
}
|
||||
|
||||
void ConnClosed(ServerConn c)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connsMutex);
|
||||
m_conns.erase(c);
|
||||
}
|
||||
|
||||
void OnConnMessage(ServerConn conn, ServerImpl::message_ptr msg)
|
||||
{
|
||||
(void) conn;
|
||||
(void) msg;
|
||||
}
|
||||
|
||||
void HandleTick(const boost::system::error_code & ec)
|
||||
{
|
||||
|
||||
if(ec != boost::asio::error::operation_aborted)
|
||||
LogPrint(eLogError, "Websocket ticker: ", ec.message());
|
||||
// pump collected events to us
|
||||
i2p::event::core.PumpCollected(this);
|
||||
ScheduleTick();
|
||||
}
|
||||
|
||||
void ScheduleTick()
|
||||
{
|
||||
LogPrint(eLogDebug, "Websocket schedule tick");
|
||||
boost::posix_time::seconds dlt(1);
|
||||
m_WebsocketTicker.expires_from_now(dlt);
|
||||
m_WebsocketTicker.async_wait(std::bind(&WebsocketServerImpl::HandleTick, this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
/** @brief called from m_ev_thread */
|
||||
void HandlePumpEvent(const EventType & ev, const uint64_t & val)
|
||||
{
|
||||
EventType e;
|
||||
for (const auto & i : ev)
|
||||
e[i.first] = i.second;
|
||||
|
||||
e["number"] = std::to_string(val);
|
||||
HandleEvent(e);
|
||||
}
|
||||
|
||||
/** @brief called from m_ws_thread */
|
||||
void HandleEvent(const EventType & ev)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connsMutex);
|
||||
boost::property_tree::ptree event;
|
||||
for (const auto & item : ev) {
|
||||
event.put(item.first, item.second);
|
||||
}
|
||||
std::ostringstream ss;
|
||||
write_json(ss, event);
|
||||
std::string s = ss.str();
|
||||
|
||||
ConnList::iterator it;
|
||||
for (it = m_conns.begin(); it != m_conns.end(); ++it) {
|
||||
ServerImpl::connection_ptr con = m_server.get_con_from_hdl(*it);
|
||||
con->send(s);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
typedef std::set<ServerConn, std::owner_less<ServerConn> > ConnList;
|
||||
bool m_run;
|
||||
std::thread * m_ws_thread;
|
||||
std::thread * m_ev_thread;
|
||||
std::mutex m_connsMutex;
|
||||
ConnList m_conns;
|
||||
ServerImpl m_server;
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::deadline_timer m_WebsocketTicker;
|
||||
};
|
||||
|
||||
|
||||
WebsocketServer::WebsocketServer(const std::string & addr, int port) : m_impl(new WebsocketServerImpl(addr, port)) {}
|
||||
WebsocketServer::~WebsocketServer()
|
||||
{
|
||||
delete m_impl;
|
||||
}
|
||||
|
||||
|
||||
void WebsocketServer::Start()
|
||||
{
|
||||
m_impl->Start();
|
||||
}
|
||||
|
||||
void WebsocketServer::Stop()
|
||||
{
|
||||
m_impl->Stop();
|
||||
}
|
||||
|
||||
EventListener * WebsocketServer::ToListener()
|
||||
{
|
||||
return m_impl;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
28
libi2pd_client/Websocket.h
Normal file
28
libi2pd_client/Websocket.h
Normal file
|
@ -0,0 +1,28 @@
|
|||
#ifndef WEBSOCKET_H__
|
||||
#define WEBSOCKET_H__
|
||||
#include "Event.h"
|
||||
namespace i2p
|
||||
{
|
||||
namespace event
|
||||
{
|
||||
|
||||
class WebsocketServerImpl;
|
||||
|
||||
class WebsocketServer
|
||||
{
|
||||
public:
|
||||
WebsocketServer(const std::string & addr, int port);
|
||||
~WebsocketServer();
|
||||
|
||||
void Start();
|
||||
void Stop();
|
||||
|
||||
EventListener * ToListener();
|
||||
|
||||
private:
|
||||
WebsocketServerImpl * m_impl;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
Loading…
Add table
Add a link
Reference in a new issue