mirror of
https://github.com/PurpleI2P/i2pd.git
synced 2025-03-07 06:09:42 +00:00
Compare commits
281 Commits
0.3.0-home
...
0.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5444889715 | ||
|
|
3e13a1feed | ||
|
|
7e4c416bc1 | ||
|
|
882b559d3a | ||
|
|
610fd2ac67 | ||
|
|
f383ebb718 | ||
|
|
cb94d43092 | ||
|
|
8812a45607 | ||
|
|
37a374000c | ||
|
|
ac17f116be | ||
|
|
ecf709cbba | ||
|
|
225aa7fa6a | ||
|
|
46b16237b6 | ||
|
|
7a387b9a9f | ||
|
|
3c5e9ddd4e | ||
|
|
02851d7587 | ||
|
|
1b3652e135 | ||
|
|
17ccaab792 | ||
|
|
c9576dcdbe | ||
|
|
7acdc0a606 | ||
|
|
f552f24e6e | ||
|
|
79d13eb6cb | ||
|
|
41974b8c75 | ||
|
|
729cc4330e | ||
|
|
27d510d1b7 | ||
|
|
8a293f45fa | ||
|
|
44bc09b007 | ||
|
|
b58d58ef29 | ||
|
|
ba12331a11 | ||
|
|
b88b04515e | ||
|
|
ba9a0c0b2e | ||
|
|
9237174026 | ||
|
|
fd9a8fd2b1 | ||
|
|
7b59ce61bb | ||
|
|
1ae55e5872 | ||
|
|
6489230e68 | ||
|
|
c05f411ba0 | ||
|
|
b30de01b12 | ||
|
|
79e1096eca | ||
|
|
f1ae5817eb | ||
|
|
a906d7f02f | ||
|
|
50fb373655 | ||
|
|
29d1aa0146 | ||
|
|
fa4009821e | ||
|
|
e5503c51b4 | ||
|
|
ccb68088a8 | ||
|
|
0f07b04627 | ||
|
|
bfc6274cd8 | ||
|
|
c5c0d2060c | ||
|
|
dde2b4a879 | ||
|
|
df21a067ff | ||
|
|
8c49f76534 | ||
|
|
96a9575049 | ||
|
|
0a9368fc70 | ||
|
|
84f7966a0b | ||
|
|
8f7dea698e | ||
|
|
9e7e0a456d | ||
|
|
64b47a29cf | ||
|
|
cbfe8b8232 | ||
|
|
583838e2c2 | ||
|
|
7bfb73dacf | ||
|
|
350e942b6a | ||
|
|
ed82f388e6 | ||
|
|
b5f624a10f | ||
|
|
700c53e60a | ||
|
|
2ed99ba245 | ||
|
|
472c5f542f | ||
|
|
1636187e26 | ||
|
|
4d640dac2a | ||
|
|
7bf11df3b8 | ||
|
|
ddf2aa38cc | ||
|
|
e8c544c774 | ||
|
|
82af922b40 | ||
|
|
446e5fd665 | ||
|
|
7847982a57 | ||
|
|
86a7f96a46 | ||
|
|
da01ea997d | ||
|
|
59aa40e2b0 | ||
|
|
6fb5fa1c52 | ||
|
|
64df22def8 | ||
|
|
bbe403fb40 | ||
|
|
3547a4042c | ||
|
|
46ea2291fe | ||
|
|
66c2c7f789 | ||
|
|
78c06bdd22 | ||
|
|
afd69e4afd | ||
|
|
ff7ff3b55b | ||
|
|
14e2c76799 | ||
|
|
677e3585c9 | ||
|
|
e349facd65 | ||
|
|
7b5e8a9661 | ||
|
|
3f314d8355 | ||
|
|
325117114a | ||
|
|
e1d445ab50 | ||
|
|
b1b72d2d33 | ||
|
|
bb5e520a79 | ||
|
|
fd0069cb0e | ||
|
|
52ee861d3a | ||
|
|
42075e74ad | ||
|
|
1e87aedbb8 | ||
|
|
5221e09b67 | ||
|
|
0972782553 | ||
|
|
425c746b87 | ||
|
|
db2d0df2c4 | ||
|
|
da1397ff76 | ||
|
|
c009fc5d72 | ||
|
|
993b4c92b0 | ||
|
|
b26bc5c7f4 | ||
|
|
e4cc15d19e | ||
|
|
e5c2022f71 | ||
|
|
b343c24a9f | ||
|
|
21e3778e69 | ||
|
|
f4f6e74ea2 | ||
|
|
c887f54740 | ||
|
|
1179731959 | ||
|
|
91e833cdaf | ||
|
|
84e5f30c70 | ||
|
|
b007b66b15 | ||
|
|
8b05455545 | ||
|
|
a44ca91409 | ||
|
|
84235fe479 | ||
|
|
25ccfef4b0 | ||
|
|
ec8e3574f9 | ||
|
|
7da694825d | ||
|
|
9606883b78 | ||
|
|
54cffb583f | ||
|
|
fe4d640504 | ||
|
|
1a69770e15 | ||
|
|
75b67b7ea7 | ||
|
|
e3f077ee9a | ||
|
|
f357a5864c | ||
|
|
6e32c389b1 | ||
|
|
219abaa7e1 | ||
|
|
82d5bf2f8a | ||
|
|
1ffe7955a3 | ||
|
|
ef73353a0a | ||
|
|
52a0b9ca03 | ||
|
|
0a9eca9f94 | ||
|
|
b399d45d66 | ||
|
|
d6fe4556fb | ||
|
|
6ad0313dbe | ||
|
|
ca2566e778 | ||
|
|
2b093a0e3f | ||
|
|
0e212f29d0 | ||
|
|
cd3a7040b0 | ||
|
|
cf8e229098 | ||
|
|
05a62af99b | ||
|
|
56c404e6c1 | ||
|
|
5ee4969322 | ||
|
|
8a43e070d8 | ||
|
|
aa0cb6b2c4 | ||
|
|
d6ec412422 | ||
|
|
4e94bc9efc | ||
|
|
bc0f0e96a3 | ||
|
|
9552edf82d | ||
|
|
8c218bd5df | ||
|
|
01bb492faf | ||
|
|
afd0a43725 | ||
|
|
366b160727 | ||
|
|
8b61aedc3f | ||
|
|
23e49e730f | ||
|
|
0e935a3511 | ||
|
|
56a95fa9b5 | ||
|
|
6ac846f95d | ||
|
|
9ce56eb95f | ||
|
|
3643d2f1da | ||
|
|
96851ab2fd | ||
|
|
7e52f8af5e | ||
|
|
ca3817abe3 | ||
|
|
aaf9a70153 | ||
|
|
0ee7f02f51 | ||
|
|
18d9325800 | ||
|
|
bec638914a | ||
|
|
67c4c237a9 | ||
|
|
6c98c80268 | ||
|
|
342c87e15b | ||
|
|
5966113268 | ||
|
|
a6ff3df591 | ||
|
|
9438f388ad | ||
|
|
0b3ee77717 | ||
|
|
7ccb7f05bf | ||
|
|
5b53665f4f | ||
|
|
b66aa7408e | ||
|
|
5dbee6b300 | ||
|
|
a0893eabfa | ||
|
|
c8e34052a7 | ||
|
|
a2d69a8b66 | ||
|
|
fd7fca1d54 | ||
|
|
47589125e0 | ||
|
|
02256be720 | ||
|
|
b9b224fdc3 | ||
|
|
cb06f8e0bb | ||
|
|
bb05bcf39f | ||
|
|
b7d1b74ffa | ||
|
|
d1cca92459 | ||
|
|
1d497cf8d6 | ||
|
|
efa771310d | ||
|
|
8f12881162 | ||
|
|
85624e4f4b | ||
|
|
5bbe661392 | ||
|
|
5e31d6b2bd | ||
|
|
06621a2198 | ||
|
|
4d77dad9cc | ||
|
|
e89938e9df | ||
|
|
1568128356 | ||
|
|
d13329471e | ||
|
|
9dbd5a583a | ||
|
|
07ad7fea9e | ||
|
|
fbff749838 | ||
|
|
797c8750d8 | ||
|
|
9164ac8a3e | ||
|
|
8788e1b2fd | ||
|
|
9a9d6e8e00 | ||
|
|
047a371050 | ||
|
|
392075bf60 | ||
|
|
07d5e8c756 | ||
|
|
e84d4e5f42 | ||
|
|
4c8d85870b | ||
|
|
519330015f | ||
|
|
08762870b4 | ||
|
|
517a7ba3ab | ||
|
|
3d0349191d | ||
|
|
76478ceaa2 | ||
|
|
9328bd1caf | ||
|
|
b2a6b6657f | ||
|
|
0214ad69a6 | ||
|
|
1c0c530769 | ||
|
|
75666e3e39 | ||
|
|
60e4e52373 | ||
|
|
30a1f9d447 | ||
|
|
cb293b93d2 | ||
|
|
3ab65bbe0d | ||
|
|
e7f05cc462 | ||
|
|
cfcec8229c | ||
|
|
4e54fbec08 | ||
|
|
38ee813e41 | ||
|
|
9acf80e563 | ||
|
|
9539fb8cb0 | ||
|
|
bd13406f42 | ||
|
|
fbec753dcd | ||
|
|
e6c92a535d | ||
|
|
32a767dc91 | ||
|
|
3ca560b895 | ||
|
|
5e83d950f5 | ||
|
|
95027930f2 | ||
|
|
3ff1158384 | ||
|
|
404f21ea76 | ||
|
|
49173da84d | ||
|
|
d794dfb7e5 | ||
|
|
8350f16b20 | ||
|
|
e1c25fedb0 | ||
|
|
3e3cfa3d68 | ||
|
|
092b445e36 | ||
|
|
b9806ac86b | ||
|
|
a8c08563f1 | ||
|
|
eb6b04d6c2 | ||
|
|
68c321609d | ||
|
|
fae01f61d2 | ||
|
|
aca87b5fd1 | ||
|
|
77687a70a2 | ||
|
|
357a9a6a56 | ||
|
|
f7d90648e3 | ||
|
|
6153d799bc | ||
|
|
f15508aff5 | ||
|
|
0ccb66476e | ||
|
|
6c13ad78a5 | ||
|
|
8fde36a4b0 | ||
|
|
de14f8dcd7 | ||
|
|
1e81652a62 | ||
|
|
f7ce86e0c4 | ||
|
|
9eb5982ea3 | ||
|
|
4778c8bdfb | ||
|
|
9574163aeb | ||
|
|
199ff0c210 | ||
|
|
e0635548e9 | ||
|
|
95524c8db3 | ||
|
|
1a0957b571 | ||
|
|
97656e7349 | ||
|
|
0262a8b057 | ||
|
|
4bd8b44ab2 | ||
|
|
4dc33a6f45 |
496
AddressBook.cpp
496
AddressBook.cpp
@@ -1,23 +1,193 @@
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <fstream>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include <cryptopp/osrng.h>
|
||||
#include "base64.h"
|
||||
#include "util.h"
|
||||
#include "Identity.h"
|
||||
#include "Log.h"
|
||||
#include "NetDb.h"
|
||||
#include "ClientContext.h"
|
||||
#include "AddressBook.h"
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
|
||||
AddressBook::AddressBook (): m_IsLoaded (false), m_IsDowloading (false)
|
||||
class AddressBookFilesystemStorage: public AddressBookStorage
|
||||
{
|
||||
public:
|
||||
|
||||
AddressBookFilesystemStorage ();
|
||||
bool GetAddress (const i2p::data::IdentHash& ident, i2p::data::IdentityEx& address) const;
|
||||
void AddAddress (const i2p::data::IdentityEx& address);
|
||||
void RemoveAddress (const i2p::data::IdentHash& ident);
|
||||
|
||||
int Load (std::map<std::string, i2p::data::IdentHash>& addresses);
|
||||
int Save (const std::map<std::string, i2p::data::IdentHash>& addresses);
|
||||
|
||||
private:
|
||||
|
||||
boost::filesystem::path GetPath () const { return i2p::util::filesystem::GetDefaultDataDir() / "addressbook"; };
|
||||
|
||||
};
|
||||
|
||||
AddressBookFilesystemStorage::AddressBookFilesystemStorage ()
|
||||
{
|
||||
auto path = GetPath ();
|
||||
if (!boost::filesystem::exists (path))
|
||||
{
|
||||
// Create directory is necessary
|
||||
if (!boost::filesystem::create_directory (path))
|
||||
LogPrint (eLogError, "Failed to create addressbook directory");
|
||||
}
|
||||
}
|
||||
|
||||
bool AddressBookFilesystemStorage::GetAddress (const i2p::data::IdentHash& ident, i2p::data::IdentityEx& address) const
|
||||
{
|
||||
auto filename = GetPath () / (ident.ToBase32() + ".b32");
|
||||
std::ifstream f(filename.c_str (), std::ifstream::binary);
|
||||
if (f.is_open ())
|
||||
{
|
||||
f.seekg (0,std::ios::end);
|
||||
size_t len = f.tellg ();
|
||||
if (len < i2p::data::DEFAULT_IDENTITY_SIZE)
|
||||
{
|
||||
LogPrint (eLogError, "File ", filename, " is too short. ", len);
|
||||
return false;
|
||||
}
|
||||
f.seekg(0, std::ios::beg);
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
f.read((char *)buf, len);
|
||||
address.FromBuffer (buf, len);
|
||||
delete[] buf;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::AddAddress (const i2p::data::IdentityEx& address)
|
||||
{
|
||||
auto filename = GetPath () / (address.GetIdentHash ().ToBase32() + ".b32");
|
||||
std::ofstream f (filename.c_str (), std::ofstream::binary | std::ofstream::out);
|
||||
if (f.is_open ())
|
||||
{
|
||||
size_t len = address.GetFullLen ();
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
address.ToBuffer (buf, len);
|
||||
f.write ((char *)buf, len);
|
||||
delete[] buf;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Can't open file ", filename);
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::RemoveAddress (const i2p::data::IdentHash& ident)
|
||||
{
|
||||
auto filename = GetPath () / (ident.ToBase32() + ".b32");
|
||||
if (boost::filesystem::exists (filename))
|
||||
boost::filesystem::remove (filename);
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Load (std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
int num = 0;
|
||||
auto filename = GetPath () / "addresses.csv";
|
||||
std::ifstream f (filename.c_str (), std::ofstream::in); // in text mode
|
||||
if (f.is_open ())
|
||||
{
|
||||
addresses.clear ();
|
||||
while (!f.eof ())
|
||||
{
|
||||
std::string s;
|
||||
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);
|
||||
|
||||
i2p::data::IdentHash ident;
|
||||
ident.FromBase32 (addr);
|
||||
addresses[name] = ident;
|
||||
num++;
|
||||
}
|
||||
}
|
||||
LogPrint (eLogInfo, num, " addresses loaded");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, filename, " not found");
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Save (const std::map<std::string, i2p::data::IdentHash>& addresses)
|
||||
{
|
||||
int num = 0;
|
||||
auto filename = GetPath () / "addresses.csv";
|
||||
std::ofstream f (filename.c_str (), std::ofstream::out); // in text mode
|
||||
if (f.is_open ())
|
||||
{
|
||||
for (auto it: addresses)
|
||||
{
|
||||
f << it.first << "," << it.second.ToBase32 () << std::endl;
|
||||
num++;
|
||||
}
|
||||
LogPrint (eLogInfo, num, " addresses saved");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Can't open file ", filename);
|
||||
return num;
|
||||
}
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
AddressBook::AddressBook (): m_IsLoaded (false), m_IsDownloading (false),
|
||||
m_DefaultSubscription (nullptr), m_SubscriptionsUpdateTimer (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
AddressBook::~AddressBook ()
|
||||
{
|
||||
if (m_IsDownloading)
|
||||
{
|
||||
LogPrint (eLogInfo, "Subscription is downloading. Waiting for temination...");
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
if (!m_IsDownloading)
|
||||
{
|
||||
LogPrint (eLogInfo, "Subscription download complete");
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for (std::chrono::seconds (1)); // wait for 1 seconds
|
||||
}
|
||||
LogPrint (eLogError, "Subscription download hangs");
|
||||
}
|
||||
if (m_Storage)
|
||||
{
|
||||
m_Storage->Save (m_Addresses);
|
||||
delete m_Storage;
|
||||
}
|
||||
delete m_DefaultSubscription;
|
||||
for (auto it: m_Subscriptions)
|
||||
delete it;
|
||||
delete m_SubscriptionsUpdateTimer;
|
||||
}
|
||||
|
||||
AddressBookStorage * AddressBook::CreateStorage ()
|
||||
{
|
||||
return new AddressBookFilesystemStorage ();
|
||||
}
|
||||
|
||||
bool AddressBook::GetIdentHash (const std::string& address, i2p::data::IdentHash& ident)
|
||||
{
|
||||
auto pos = address.find(".b32.i2p");
|
||||
@@ -37,9 +207,16 @@ namespace client
|
||||
ident = *identHash;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
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)
|
||||
@@ -59,51 +236,66 @@ namespace client
|
||||
{
|
||||
i2p::data::IdentityEx ident;
|
||||
ident.FromBase64 (base64);
|
||||
if (!m_Storage)
|
||||
m_Storage = CreateStorage ();
|
||||
m_Storage->AddAddress (ident);
|
||||
m_Addresses[address] = ident.GetIdentHash ();
|
||||
LogPrint (address,"->",ident.GetIdentHash ().ToBase32 (), ".b32.i2p added");
|
||||
LogPrint (address,"->", ToAddress(ident.GetIdentHash ()), " added");
|
||||
}
|
||||
|
||||
void AddressBook::LoadHostsFromI2P ()
|
||||
void AddressBook::InsertAddress (const i2p::data::IdentityEx& address)
|
||||
{
|
||||
std::string content;
|
||||
int http_code = i2p::util::http::httpRequestViaI2pProxy("http://udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p/hosts.txt", content);
|
||||
if (http_code == 200)
|
||||
{
|
||||
std::ofstream f_save(i2p::util::filesystem::GetFullPath("hosts.txt").c_str(), std::ofstream::out);
|
||||
if (f_save.is_open())
|
||||
{
|
||||
f_save << content;
|
||||
f_save.close();
|
||||
}
|
||||
else
|
||||
LogPrint("Can't write hosts.txt");
|
||||
m_IsLoaded = false;
|
||||
}
|
||||
else
|
||||
LogPrint ("Failed to download hosts.txt");
|
||||
m_IsDowloading = false;
|
||||
|
||||
return;
|
||||
if (!m_Storage)
|
||||
m_Storage = CreateStorage ();
|
||||
m_Storage->AddAddress (address);
|
||||
}
|
||||
|
||||
bool AddressBook::GetAddress (const std::string& address, i2p::data::IdentityEx& identity)
|
||||
{
|
||||
if (!m_Storage)
|
||||
m_Storage = CreateStorage ();
|
||||
i2p::data::IdentHash ident;
|
||||
if (!GetIdentHash (address, ident)) return false;
|
||||
return m_Storage->GetAddress (ident, identity);
|
||||
}
|
||||
|
||||
void AddressBook::LoadHosts ()
|
||||
{
|
||||
std::ifstream f (i2p::util::filesystem::GetFullPath ("hosts.txt").c_str (), std::ofstream::in); // in text mode
|
||||
if (!f.is_open ())
|
||||
if (!m_Storage)
|
||||
m_Storage = CreateStorage ();
|
||||
if (m_Storage->Load (m_Addresses) > 0)
|
||||
{
|
||||
LogPrint ("hosts.txt not found. Try to load...");
|
||||
if (!m_IsDowloading)
|
||||
{
|
||||
m_IsDowloading = true;
|
||||
std::thread load_hosts(&AddressBook::LoadHostsFromI2P, this);
|
||||
load_hosts.detach();
|
||||
}
|
||||
m_IsLoaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// try hosts.txt first
|
||||
std::ifstream f (i2p::util::filesystem::GetFullPath ("hosts.txt").c_str (), std::ofstream::in); // in text mode
|
||||
if (f.is_open ())
|
||||
{
|
||||
LoadHostsFromStream (f);
|
||||
m_IsLoaded = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// if not found download it from http://i2p-projekt.i2p/hosts.txt
|
||||
LogPrint (eLogInfo, "hosts.txt not found. Try to download it from default subscription...");
|
||||
if (!m_IsDownloading)
|
||||
{
|
||||
m_IsDownloading = true;
|
||||
if (!m_DefaultSubscription)
|
||||
m_DefaultSubscription = new AddressBookSubscription (*this, DEFAULT_SUBSCRIPTION_ADDRESS);
|
||||
m_DefaultSubscription->CheckSubscription ();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void AddressBook::LoadHostsFromStream (std::istream& f)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_AddressBookMutex);
|
||||
int numAddresses = 0;
|
||||
|
||||
std::string s;
|
||||
|
||||
while (!f.eof ())
|
||||
{
|
||||
getline(f, s);
|
||||
@@ -119,15 +311,237 @@ namespace client
|
||||
std::string addr = s.substr(pos);
|
||||
|
||||
i2p::data::IdentityEx ident;
|
||||
ident.FromBase64(addr);
|
||||
m_Addresses[name] = ident.GetIdentHash ();
|
||||
numAddresses++;
|
||||
if (ident.FromBase64(addr))
|
||||
{
|
||||
m_Addresses[name] = ident.GetIdentHash ();
|
||||
m_Storage->AddAddress (ident);
|
||||
numAddresses++;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Malformed address ", addr, " for ", name);
|
||||
}
|
||||
}
|
||||
LogPrint (numAddresses, " addresses loaded");
|
||||
m_IsLoaded = true;
|
||||
LogPrint (eLogInfo, numAddresses, " addresses processed");
|
||||
if (numAddresses > 0)
|
||||
{
|
||||
m_IsLoaded = true;
|
||||
m_Storage->Save (m_Addresses);
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::LoadSubscriptions ()
|
||||
{
|
||||
if (!m_Subscriptions.size ())
|
||||
{
|
||||
std::ifstream f (i2p::util::filesystem::GetFullPath ("subscriptions.txt").c_str (), std::ofstream::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 (new AddressBookSubscription (*this, s));
|
||||
}
|
||||
LogPrint (eLogInfo, m_Subscriptions.size (), " subscriptions loaded");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "subscriptions.txt not found");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Subscriptions already loaded");
|
||||
}
|
||||
|
||||
void AddressBook::DownloadComplete (bool success)
|
||||
{
|
||||
m_IsDownloading = false;
|
||||
m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(
|
||||
success ? CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT : CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT));
|
||||
m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void AddressBook::StartSubscriptions ()
|
||||
{
|
||||
LoadSubscriptions ();
|
||||
if (!m_Subscriptions.size ()) 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, "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) return;
|
||||
if (m_IsLoaded && !m_IsDownloading && dest->IsReady ())
|
||||
{
|
||||
// pick random subscription
|
||||
CryptoPP::AutoSeededRandomPool rnd;
|
||||
auto ind = rnd.GenerateWord32 (0, m_Subscriptions.size() - 1);
|
||||
m_IsDownloading = true;
|
||||
m_Subscriptions[ind]->CheckSubscription ();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!m_IsLoaded)
|
||||
LoadHosts ();
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AddressBookSubscription::AddressBookSubscription (AddressBook& book, const std::string& link):
|
||||
m_Book (book), m_Link (link)
|
||||
{
|
||||
}
|
||||
|
||||
void AddressBookSubscription::CheckSubscription ()
|
||||
{
|
||||
std::thread load_hosts(&AddressBookSubscription::Request, this);
|
||||
load_hosts.detach(); // TODO: use join
|
||||
}
|
||||
|
||||
void AddressBookSubscription::Request ()
|
||||
{
|
||||
// must be run in separate thread
|
||||
LogPrint (eLogInfo, "Downloading hosts from ", m_Link, " ETag: ", m_Etag, " Last-Modified: ", m_LastModified);
|
||||
bool success = false;
|
||||
i2p::util::http::url u (m_Link);
|
||||
i2p::data::IdentHash ident;
|
||||
if (m_Book.GetIdentHash (u.host_, ident))
|
||||
{
|
||||
std::condition_variable newDataReceived;
|
||||
std::mutex newDataReceivedMutex;
|
||||
const i2p::data::LeaseSet * leaseSet = i2p::data::netdb.FindLeaseSet (ident);
|
||||
if (!leaseSet)
|
||||
{
|
||||
bool found = false;
|
||||
std::unique_lock<std::mutex> l(newDataReceivedMutex);
|
||||
i2p::client::context.GetSharedLocalDestination ()->RequestDestination (ident,
|
||||
[&newDataReceived, &found](bool success)
|
||||
{
|
||||
found = success;
|
||||
newDataReceived.notify_all ();
|
||||
});
|
||||
if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
|
||||
LogPrint (eLogError, "Subscription LeseseSet request timeout expired");
|
||||
if (found)
|
||||
leaseSet = i2p::client::context.GetSharedLocalDestination ()->FindLeaseSet (ident);
|
||||
}
|
||||
if (leaseSet)
|
||||
{
|
||||
std::stringstream request, response;
|
||||
// standard header
|
||||
request << "GET " << u.path_ << " HTTP/1.1\r\nHost: " << u.host_
|
||||
<< "\r\nAccept: */*\r\n" << "User-Agent: Wget/1.11.4\r\n" << "Connection: close\r\n";
|
||||
if (m_Etag.length () > 0) // etag
|
||||
request << i2p::util::http::IF_NONE_MATCH << ": \"" << m_Etag << "\"\r\n";
|
||||
if (m_LastModified.length () > 0) // if-modfief-since
|
||||
request << i2p::util::http::IF_MODIFIED_SINCE << ": " << m_LastModified << "\r\n";
|
||||
request << "\r\n"; // end of header
|
||||
auto stream = i2p::client::context.GetSharedLocalDestination ()->CreateStream (*leaseSet, u.port_);
|
||||
stream->Send ((uint8_t *)request.str ().c_str (), request.str ().length ());
|
||||
|
||||
uint8_t buf[4095];
|
||||
bool end = false;
|
||||
while (!end)
|
||||
{
|
||||
stream->AsyncReceive (boost::asio::buffer (buf, 4096),
|
||||
[&](const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (bytes_transferred)
|
||||
response.write ((char *)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, "Subscription timeout expired");
|
||||
}
|
||||
// process remaining buffer
|
||||
while (size_t len = stream->ReadSome (buf, 4096))
|
||||
response.write ((char *)buf, len);
|
||||
|
||||
// parse response
|
||||
std::string version;
|
||||
response >> version; // HTTP version
|
||||
int status = 0;
|
||||
response >> status; // status
|
||||
if (status == 200) // OK
|
||||
{
|
||||
bool isChunked = false;
|
||||
std::string header, statusMessage;
|
||||
std::getline (response, statusMessage);
|
||||
// read until new line meaning end of header
|
||||
while (!response.eof () && header != "\r")
|
||||
{
|
||||
std::getline (response, header);
|
||||
auto colon = header.find (':');
|
||||
if (colon != std::string::npos)
|
||||
{
|
||||
std::string field = header.substr (0, colon);
|
||||
header.resize (header.length () - 1); // delete \r
|
||||
if (field == i2p::util::http::ETAG)
|
||||
m_Etag = header.substr (colon + 1);
|
||||
else if (field == i2p::util::http::LAST_MODIFIED)
|
||||
m_LastModified = header.substr (colon + 1);
|
||||
else if (field == i2p::util::http::TRANSFER_ENCODING)
|
||||
isChunked = !header.compare (colon + 1, std::string::npos, "chunked");
|
||||
}
|
||||
}
|
||||
LogPrint (eLogInfo, m_Link, " ETag: ", m_Etag, " Last-Modified: ", m_LastModified);
|
||||
if (!response.eof ())
|
||||
{
|
||||
success = true;
|
||||
if (!isChunked)
|
||||
m_Book.LoadHostsFromStream (response);
|
||||
else
|
||||
{
|
||||
// merge chunks
|
||||
std::stringstream merged;
|
||||
i2p::util::http::MergeChunkedResponse (response, merged);
|
||||
m_Book.LoadHostsFromStream (merged);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (status == 304)
|
||||
{
|
||||
success = true;
|
||||
LogPrint (eLogInfo, "No updates from ", m_Link);
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Adressbook HTTP response ", status);
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Address ", u.host_, " not found");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Can't resolve ", u.host_);
|
||||
LogPrint (eLogInfo, "Download complete ", success ? "Success" : "Failed");
|
||||
m_Book.DownloadComplete (success);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <boost/asio.hpp>
|
||||
#include "base64.h"
|
||||
#include "util.h"
|
||||
#include "Identity.h"
|
||||
@@ -13,22 +17,80 @@ namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
const char DEFAULT_SUBSCRIPTION_ADDRESS[] = "http://udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p/hosts.txt";
|
||||
const int INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT = 3; // in minutes
|
||||
const int INITIAL_SUBSCRIPTION_RETRY_TIMEOUT = 1; // in minutes
|
||||
const int CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT = 240; // in minutes
|
||||
const int CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT = 5; // in minutes
|
||||
const int SUBSCRIPTION_REQUEST_TIMEOUT = 60; //in second
|
||||
|
||||
class AddressBookStorage // interface for storage
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AddressBookStorage () {};
|
||||
virtual bool GetAddress (const i2p::data::IdentHash& ident, i2p::data::IdentityEx& address) const = 0;
|
||||
virtual void AddAddress (const i2p::data::IdentityEx& address) = 0;
|
||||
virtual void RemoveAddress (const i2p::data::IdentHash& ident) = 0;
|
||||
|
||||
virtual int Load (std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
|
||||
virtual int Save (const std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
|
||||
};
|
||||
|
||||
class AddressBookSubscription;
|
||||
class AddressBook
|
||||
{
|
||||
public:
|
||||
|
||||
AddressBook ();
|
||||
~AddressBook ();
|
||||
bool GetIdentHash (const std::string& address, i2p::data::IdentHash& ident);
|
||||
bool GetAddress (const std::string& address, i2p::data::IdentityEx& identity);
|
||||
const i2p::data::IdentHash * FindAddress (const std::string& address);
|
||||
void InsertAddress (const std::string& address, const std::string& base64); // for jump service
|
||||
void InsertAddress (const i2p::data::IdentityEx& address);
|
||||
|
||||
void StartSubscriptions ();
|
||||
void StopSubscriptions ();
|
||||
void LoadHostsFromStream (std::istream& f);
|
||||
void DownloadComplete (bool success);
|
||||
//This method returns the ".b32.i2p" address
|
||||
std::string ToAddress(const i2p::data::IdentHash& ident) { return ident.ToBase32().append(".b32.i2p"); }
|
||||
std::string ToAddress(const i2p::data::IdentityEx& ident) { return ToAddress(ident.GetIdentHash ()); }
|
||||
private:
|
||||
|
||||
AddressBookStorage * CreateStorage ();
|
||||
void LoadHosts ();
|
||||
void LoadSubscriptions ();
|
||||
|
||||
void HandleSubscriptionsUpdateTimer (const boost::system::error_code& ecode);
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_AddressBookMutex;
|
||||
std::map<std::string, i2p::data::IdentHash> m_Addresses;
|
||||
AddressBookStorage * m_Storage;
|
||||
volatile bool m_IsLoaded, m_IsDownloading;
|
||||
std::vector<AddressBookSubscription *> m_Subscriptions;
|
||||
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 CheckSubscription ();
|
||||
|
||||
private:
|
||||
|
||||
void Request ();
|
||||
|
||||
private:
|
||||
|
||||
void LoadHosts ();
|
||||
void LoadHostsFromI2P ();
|
||||
|
||||
std::map<std::string, i2p::data::IdentHash> m_Addresses;
|
||||
bool m_IsLoaded, m_IsDowloading;
|
||||
AddressBook& m_Book;
|
||||
std::string m_Link, m_Etag, m_LastModified;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
655
BOB.cpp
Normal file
655
BOB.cpp
Normal file
@@ -0,0 +1,655 @@
|
||||
#include <string.h>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "Log.h"
|
||||
#include "ClientContext.h"
|
||||
#include "BOB.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
BOBI2PInboundTunnel::BOBI2PInboundTunnel (int port, ClientDestination * localDestination):
|
||||
BOBI2PTunnel (localDestination),
|
||||
m_Acceptor (localDestination->GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)), m_Timer (localDestination->GetService ())
|
||||
{
|
||||
}
|
||||
|
||||
BOBI2PInboundTunnel::~BOBI2PInboundTunnel ()
|
||||
{
|
||||
Stop ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Start ()
|
||||
{
|
||||
m_Acceptor.listen ();
|
||||
Accept ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Stop ()
|
||||
{
|
||||
m_Acceptor.close();
|
||||
ClearConnections ();
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::Accept ()
|
||||
{
|
||||
auto receiver = new AddressReceiver ();
|
||||
receiver->socket = new 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, AddressReceiver * receiver)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
Accept ();
|
||||
ReceiveAddress (receiver);
|
||||
}
|
||||
else
|
||||
{
|
||||
delete receiver->socket;
|
||||
delete receiver;
|
||||
}
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::ReceiveAddress (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,
|
||||
AddressReceiver * receiver)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("BOB inbound tunnel read error: ", ecode.message ());
|
||||
delete receiver->socket;
|
||||
delete receiver;
|
||||
}
|
||||
else
|
||||
{
|
||||
receiver->bufferOffset += bytes_transferred;
|
||||
receiver->buffer[receiver->bufferOffset] = 0;
|
||||
char * eol = strchr (receiver->buffer, '\n');
|
||||
if (eol)
|
||||
{
|
||||
*eol = 0;
|
||||
|
||||
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");
|
||||
delete receiver->socket;
|
||||
delete receiver;
|
||||
return;
|
||||
}
|
||||
auto leaseSet = GetLocalDestination ()->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
CreateConnection (receiver, leaseSet);
|
||||
else
|
||||
{
|
||||
GetLocalDestination ()->RequestDestination (ident);
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds (I2P_TUNNEL_DESTINATION_REQUEST_TIMEOUT));
|
||||
m_Timer.async_wait (std::bind (&BOBI2PInboundTunnel::HandleDestinationRequestTimer,
|
||||
this, std::placeholders::_1, receiver, ident));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (receiver->bufferOffset < BOB_COMMAND_BUFFER_SIZE)
|
||||
ReceiveAddress (receiver);
|
||||
else
|
||||
{
|
||||
LogPrint ("BOB missing inbound address ");
|
||||
delete receiver->socket;
|
||||
delete receiver;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::HandleDestinationRequestTimer (const boost::system::error_code& ecode, AddressReceiver * receiver, i2p::data::IdentHash ident)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
auto leaseSet = GetLocalDestination ()->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
{
|
||||
CreateConnection (receiver, leaseSet);
|
||||
return;
|
||||
}
|
||||
else
|
||||
LogPrint ("LeaseSet for BOB inbound destination not found");
|
||||
}
|
||||
delete receiver->socket;
|
||||
delete receiver;
|
||||
}
|
||||
|
||||
void BOBI2PInboundTunnel::CreateConnection (AddressReceiver * receiver, const i2p::data::LeaseSet * leaseSet)
|
||||
{
|
||||
LogPrint ("New BOB inbound connection");
|
||||
auto connection = std::make_shared<I2PTunnelConnection>(this, receiver->socket, leaseSet);
|
||||
AddConnection (connection);
|
||||
connection->I2PConnect (receiver->data, receiver->dataLen);
|
||||
delete receiver;
|
||||
}
|
||||
|
||||
BOBI2POutboundTunnel::BOBI2POutboundTunnel (const std::string& address, int port,
|
||||
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 ()
|
||||
{
|
||||
ClearConnections ();
|
||||
}
|
||||
|
||||
void BOBI2POutboundTunnel::Accept ()
|
||||
{
|
||||
auto localDestination = GetLocalDestination ();
|
||||
if (localDestination)
|
||||
localDestination->AcceptStreams (std::bind (&BOBI2POutboundTunnel::HandleAccept, this, std::placeholders::_1));
|
||||
else
|
||||
LogPrint ("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, new boost::asio::ip::tcp::socket (GetService ()), m_Endpoint, m_IsQuiet);
|
||||
AddConnection (conn);
|
||||
conn->Connect ();
|
||||
}
|
||||
}
|
||||
|
||||
BOBDestination::BOBDestination (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_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 ("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, "Malformed input of the BOB 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 ("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_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");
|
||||
}
|
||||
|
||||
void BOBCommandSession::StopCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
auto dest = m_Owner.FindDestination (m_Nickname);
|
||||
if (dest)
|
||||
{
|
||||
dest->StopTunnels ();
|
||||
SendReplyOK ("tunnel stopping");
|
||||
}
|
||||
else
|
||||
SendReplyError ("tunnel not found");
|
||||
}
|
||||
|
||||
void BOBCommandSession::SetNickCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: setnick ", operand);
|
||||
m_Nickname = operand;
|
||||
std::string msg ("Nickname set to ");
|
||||
msg += operand;
|
||||
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;
|
||||
std::string msg ("Nickname set to ");
|
||||
msg += operand;
|
||||
SendReplyOK (msg.c_str ());
|
||||
}
|
||||
else
|
||||
SendReplyError ("tunnel not found");
|
||||
}
|
||||
|
||||
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);
|
||||
m_Keys.FromBase64 (operand);
|
||||
SendReplyOK (m_Keys.GetPublic ().ToBase64 ().c_str ());
|
||||
}
|
||||
|
||||
void BOBCommandSession::GetkeysCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: getkeys");
|
||||
SendReplyOK (m_Keys.ToBase64 ().c_str ());
|
||||
}
|
||||
|
||||
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 = boost::lexical_cast<int>(operand);
|
||||
SendReplyOK ("outbound port set");
|
||||
}
|
||||
|
||||
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 = boost::lexical_cast<int>(operand);
|
||||
SendReplyOK ("inbound port set");
|
||||
}
|
||||
|
||||
void BOBCommandSession::QuietCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: quiet");
|
||||
m_IsQuiet = true;
|
||||
SendReplyOK ("quiet");
|
||||
}
|
||||
|
||||
void BOBCommandSession::LookupCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: lookup ", operand);
|
||||
i2p::data::IdentityEx addr;
|
||||
if (!context.GetAddressBook ().GetAddress (operand, addr))
|
||||
{
|
||||
SendReplyError ("Address Not found");
|
||||
return;
|
||||
}
|
||||
SendReplyOK (addr.ToBase64 ().c_str ());
|
||||
}
|
||||
|
||||
void BOBCommandSession::ClearCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: clear");
|
||||
m_Owner.DeleteDestination (m_Nickname);
|
||||
SendReplyOK ("cleared");
|
||||
}
|
||||
|
||||
void BOBCommandSession::ListCommandHandler (const char * operand, size_t len)
|
||||
{
|
||||
LogPrint (eLogDebug, "BOB: list");
|
||||
auto& destinations = m_Owner.GetDestinations ();
|
||||
for (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)
|
||||
{
|
||||
*(const_cast<char *>(value)) = 0;
|
||||
m_Options[operand] = value + 1;
|
||||
*(const_cast<char *>(value)) = '=';
|
||||
SendReplyOK ("option");
|
||||
}
|
||||
else
|
||||
SendReplyError ("malformed");
|
||||
}
|
||||
|
||||
BOBCommandChannel::BOBCommandChannel (int port):
|
||||
m_IsRunning (false), m_Thread (nullptr),
|
||||
m_Acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 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;
|
||||
}
|
||||
|
||||
BOBCommandChannel::~BOBCommandChannel ()
|
||||
{
|
||||
Stop ();
|
||||
for (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: ", 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, "New BOB command connection from ", session->GetSocket ().remote_endpoint ());
|
||||
session->SendVersion ();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "BOB accept error: ", ecode.message ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
236
BOB.h
Normal file
236
BOB.h
Normal file
@@ -0,0 +1,236 @@
|
||||
#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 "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_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 I2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
BOBI2PTunnel (ClientDestination * localDestination):
|
||||
I2PTunnel (localDestination) {};
|
||||
|
||||
virtual void Start () {};
|
||||
virtual void Stop () {};
|
||||
};
|
||||
|
||||
class BOBI2PInboundTunnel: public BOBI2PTunnel
|
||||
{
|
||||
struct AddressReceiver
|
||||
{
|
||||
boost::asio::ip::tcp::socket * socket;
|
||||
char buffer[BOB_COMMAND_BUFFER_SIZE + 1]; // for destination base64 address
|
||||
uint8_t * data;
|
||||
size_t dataLen, bufferOffset;
|
||||
|
||||
AddressReceiver (): data (nullptr), dataLen (0), bufferOffset (0) {};
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
BOBI2PInboundTunnel (int port, ClientDestination * localDestination);
|
||||
~BOBI2PInboundTunnel ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
private:
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept (const boost::system::error_code& ecode, AddressReceiver * receiver);
|
||||
|
||||
void ReceiveAddress (AddressReceiver * receiver);
|
||||
void HandleReceivedAddress (const boost::system::error_code& ecode, std::size_t bytes_transferred,
|
||||
AddressReceiver * receiver);
|
||||
|
||||
void HandleDestinationRequestTimer (const boost::system::error_code& ecode, AddressReceiver * receiver, i2p::data::IdentHash ident);
|
||||
|
||||
void CreateConnection (AddressReceiver * receiver, const i2p::data::LeaseSet * leaseSet);
|
||||
|
||||
private:
|
||||
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
};
|
||||
|
||||
class BOBI2POutboundTunnel: public BOBI2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
BOBI2POutboundTunnel (const std::string& address, int port, 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 (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 (); };
|
||||
|
||||
private:
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
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 (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
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include <fstream>
|
||||
#include "util.h"
|
||||
#include "Log.h"
|
||||
#include "Identity.h"
|
||||
#include "ClientContext.h"
|
||||
|
||||
namespace i2p
|
||||
@@ -10,7 +12,7 @@ namespace client
|
||||
|
||||
ClientContext::ClientContext (): m_SharedLocalDestination (nullptr),
|
||||
m_HttpProxy (nullptr), m_SocksProxy (nullptr), m_IrcTunnel (nullptr),
|
||||
m_ServerTunnel (nullptr), m_SamBridge (nullptr)
|
||||
m_ServerTunnel (nullptr), m_SamBridge (nullptr), m_BOBCommandChannel (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -21,13 +23,14 @@ namespace client
|
||||
delete m_IrcTunnel;
|
||||
delete m_ServerTunnel;
|
||||
delete m_SamBridge;
|
||||
delete m_BOBCommandChannel;
|
||||
}
|
||||
|
||||
void ClientContext::Start ()
|
||||
{
|
||||
if (!m_SharedLocalDestination)
|
||||
{
|
||||
m_SharedLocalDestination = new ClientDestination (false, i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); // non-public, DSA
|
||||
m_SharedLocalDestination = CreateNewLocalDestination (); // non-public, DSA
|
||||
m_Destinations[m_SharedLocalDestination->GetIdentity ().GetIdentHash ()] = m_SharedLocalDestination;
|
||||
m_SharedLocalDestination->Start ();
|
||||
}
|
||||
@@ -44,19 +47,17 @@ namespace client
|
||||
ClientDestination * localDestination = nullptr;
|
||||
std::string ircKeys = i2p::util::config::GetArg("-irckeys", "");
|
||||
if (ircKeys.length () > 0)
|
||||
localDestination = i2p::client::context.LoadLocalDestination (ircKeys, false);
|
||||
m_IrcTunnel = new I2PClientTunnel (m_SocksProxy->GetService (), ircDestination,
|
||||
i2p::util::config::GetArg("-ircport", 6668), localDestination);
|
||||
localDestination = LoadLocalDestination (ircKeys, false);
|
||||
m_IrcTunnel = new I2PClientTunnel (ircDestination, i2p::util::config::GetArg("-ircport", 6668), localDestination);
|
||||
m_IrcTunnel->Start ();
|
||||
LogPrint("IRC tunnel started");
|
||||
}
|
||||
std::string eepKeys = i2p::util::config::GetArg("-eepkeys", "");
|
||||
if (eepKeys.length () > 0) // eepkeys file is presented
|
||||
{
|
||||
auto localDestination = i2p::client::context.LoadLocalDestination (eepKeys, true);
|
||||
m_ServerTunnel = new I2PServerTunnel (m_SocksProxy->GetService (),
|
||||
i2p::util::config::GetArg("-eephost", "127.0.0.1"), i2p::util::config::GetArg("-eepport", 80),
|
||||
localDestination);
|
||||
auto localDestination = LoadLocalDestination (eepKeys, true);
|
||||
m_ServerTunnel = new I2PServerTunnel (i2p::util::config::GetArg("-eephost", "127.0.0.1"),
|
||||
i2p::util::config::GetArg("-eepport", 80), localDestination);
|
||||
m_ServerTunnel->Start ();
|
||||
LogPrint("Server tunnel started");
|
||||
}
|
||||
@@ -67,10 +68,19 @@ namespace client
|
||||
m_SamBridge->Start ();
|
||||
LogPrint("SAM bridge started");
|
||||
}
|
||||
int bobPort = i2p::util::config::GetArg("-bobport", 0);
|
||||
if (bobPort)
|
||||
{
|
||||
m_BOBCommandChannel = new BOBCommandChannel (bobPort);
|
||||
m_BOBCommandChannel->Start ();
|
||||
LogPrint("BOB command channel started");
|
||||
}
|
||||
m_AddressBook.StartSubscriptions ();
|
||||
}
|
||||
|
||||
void ClientContext::Stop ()
|
||||
{
|
||||
m_AddressBook.StopSubscriptions ();
|
||||
m_HttpProxy->Stop();
|
||||
delete m_HttpProxy;
|
||||
m_HttpProxy = nullptr;
|
||||
@@ -100,7 +110,14 @@ namespace client
|
||||
m_SamBridge = nullptr;
|
||||
LogPrint("SAM brdige stoped");
|
||||
}
|
||||
|
||||
if (m_BOBCommandChannel)
|
||||
{
|
||||
m_BOBCommandChannel->Stop ();
|
||||
delete m_BOBCommandChannel;
|
||||
m_BOBCommandChannel = nullptr;
|
||||
LogPrint("BOB command channel stoped");
|
||||
}
|
||||
|
||||
for (auto it: m_Destinations)
|
||||
{
|
||||
it.second->Stop ();
|
||||
@@ -109,43 +126,49 @@ namespace client
|
||||
m_Destinations.clear ();
|
||||
m_SharedLocalDestination = 0; // deleted through m_Destination
|
||||
}
|
||||
|
||||
void ClientContext::LoadLocalDestinations ()
|
||||
{
|
||||
int numDestinations = 0;
|
||||
boost::filesystem::path p (i2p::util::filesystem::GetDataDir());
|
||||
boost::filesystem::directory_iterator end;
|
||||
for (boost::filesystem::directory_iterator it (p); it != end; ++it)
|
||||
{
|
||||
if (boost::filesystem::is_regular_file (*it) && it->path ().extension () == ".dat")
|
||||
{
|
||||
auto fullPath =
|
||||
#if BOOST_VERSION > 10500
|
||||
it->path().string();
|
||||
#else
|
||||
it->path();
|
||||
#endif
|
||||
auto localDestination = new ClientDestination (fullPath, true);
|
||||
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
|
||||
numDestinations++;
|
||||
}
|
||||
}
|
||||
if (numDestinations > 0)
|
||||
LogPrint (numDestinations, " local destinations loaded");
|
||||
}
|
||||
|
||||
ClientDestination * ClientContext::LoadLocalDestination (const std::string& filename, bool isPublic)
|
||||
{
|
||||
auto localDestination = new ClientDestination (i2p::util::filesystem::GetFullPath (filename), isPublic);
|
||||
i2p::data::PrivateKeys keys;
|
||||
std::string fullPath = i2p::util::filesystem::GetFullPath (filename);
|
||||
std::ifstream s(fullPath.c_str (), 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);
|
||||
keys.FromBuffer (buf, len);
|
||||
delete[] buf;
|
||||
LogPrint ("Local address ", m_AddressBook.ToAddress(keys.GetPublic ().GetIdentHash ()), " loaded");
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Can't open file ", fullPath, " Creating new one");
|
||||
keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1);
|
||||
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 ("New private keys file ", fullPath, " for ", m_AddressBook.ToAddress(keys.GetPublic ().GetIdentHash ()), " created");
|
||||
}
|
||||
|
||||
auto localDestination = new ClientDestination (keys, isPublic);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
|
||||
ClientDestination * ClientContext::CreateNewLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType)
|
||||
ClientDestination * ClientContext::CreateNewLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
auto localDestination = new ClientDestination (isPublic, sigType);
|
||||
i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
|
||||
auto localDestination = new ClientDestination (keys, isPublic, params);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[localDestination->GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
@@ -168,12 +191,13 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
ClientDestination * ClientContext::CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic)
|
||||
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 ("Local destination ", keys.GetPublic ().GetIdentHash ().ToBase32 (), ".b32.i2p exists");
|
||||
LogPrint ("Local destination ", m_AddressBook.ToAddress(keys.GetPublic ().GetIdentHash ()), " exists");
|
||||
if (!it->second->IsRunning ())
|
||||
{
|
||||
it->second->Start ();
|
||||
@@ -181,7 +205,7 @@ namespace client
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
auto localDestination = new ClientDestination (keys, isPublic);
|
||||
auto localDestination = new ClientDestination (keys, isPublic, params);
|
||||
std::unique_lock<std::mutex> l(m_DestinationsMutex);
|
||||
m_Destinations[keys.GetPublic ().GetIdentHash ()] = localDestination;
|
||||
localDestination->Start ();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "SOCKS.h"
|
||||
#include "I2PTunnel.h"
|
||||
#include "SAM.h"
|
||||
#include "BOB.h"
|
||||
#include "AddressBook.h"
|
||||
|
||||
namespace i2p
|
||||
@@ -24,17 +25,15 @@ namespace client
|
||||
void Stop ();
|
||||
|
||||
ClientDestination * GetSharedLocalDestination () const { return m_SharedLocalDestination; };
|
||||
ClientDestination * CreateNewLocalDestination (bool isPublic = true, i2p::data::SigningKeyType sigType = i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); // transient
|
||||
ClientDestination * CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic = true);
|
||||
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
|
||||
ClientDestination * CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic = true,
|
||||
const std::map<std::string, std::string> * params = nullptr);
|
||||
void DeleteLocalDestination (ClientDestination * destination);
|
||||
ClientDestination * FindLocalDestination (const i2p::data::IdentHash& destination) const;
|
||||
ClientDestination * LoadLocalDestination (const std::string& filename, bool isPublic);
|
||||
|
||||
AddressBook& GetAddressBook () { return m_AddressBook; };
|
||||
|
||||
private:
|
||||
|
||||
void LoadLocalDestinations ();
|
||||
|
||||
private:
|
||||
|
||||
@@ -49,6 +48,7 @@ namespace client
|
||||
I2PClientTunnel * m_IrcTunnel;
|
||||
I2PServerTunnel * m_ServerTunnel;
|
||||
SAMBridge * m_SamBridge;
|
||||
BOBCommandChannel * m_BOBCommandChannel;
|
||||
|
||||
public:
|
||||
// for HTTP
|
||||
|
||||
@@ -28,7 +28,10 @@ namespace crypto
|
||||
// DSA
|
||||
#define dsap GetCryptoConstants ().dsap
|
||||
#define dsaq GetCryptoConstants ().dsaq
|
||||
#define dsag GetCryptoConstants ().dsag
|
||||
#define dsag GetCryptoConstants ().dsag
|
||||
|
||||
// RSA
|
||||
const int rsae = 65537;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
19
Daemon.cpp
19
Daemon.cpp
@@ -18,6 +18,11 @@
|
||||
#include "HTTPServer.h"
|
||||
#include "ClientContext.h"
|
||||
|
||||
#ifdef USE_UPNP
|
||||
#include "UPnP.h"
|
||||
#endif
|
||||
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace util
|
||||
@@ -89,11 +94,11 @@ namespace i2p
|
||||
if (isDaemon)
|
||||
{
|
||||
std::string logfile_path = IsService () ? "/var/log" : i2p::util::filesystem::GetDataDir().string();
|
||||
#ifndef _WIN32
|
||||
#ifndef _WIN32
|
||||
logfile_path.append("/i2pd.log");
|
||||
#else
|
||||
#else
|
||||
logfile_path.append("\\i2pd.log");
|
||||
#endif
|
||||
#endif
|
||||
StartLog (logfile_path);
|
||||
}
|
||||
else
|
||||
@@ -111,7 +116,10 @@ namespace i2p
|
||||
LogPrint("Tunnels started");
|
||||
i2p::client::context.Start ();
|
||||
LogPrint("Client started");
|
||||
|
||||
#ifdef USE_UPNP
|
||||
i2p::UPnP::upnpc.Start();
|
||||
LogPrint("UPnP module loaded");
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -128,6 +136,9 @@ namespace i2p
|
||||
LogPrint("NetDB stoped");
|
||||
d.httpServer->Stop();
|
||||
LogPrint("HTTP Server stoped");
|
||||
#ifdef USE_UPNP
|
||||
i2p::UPnP::upnpc.Stop();
|
||||
#endif
|
||||
StopLog ();
|
||||
|
||||
delete d.httpServer; d.httpServer = nullptr;
|
||||
|
||||
26
Datagram.cpp
26
Datagram.cpp
@@ -36,18 +36,15 @@ namespace datagram
|
||||
else
|
||||
m_Owner.Sign (buf1, len, signature);
|
||||
|
||||
auto service = m_Owner.GetService ();
|
||||
if (service)
|
||||
service->post (boost::bind (&DatagramDestination::SendMsg, this,
|
||||
CreateDataMessage (buf, len + headerLen), remote));
|
||||
else
|
||||
LogPrint (eLogWarning, "Failed to send datagram. Destination is not running");
|
||||
m_Owner.GetService ().post (std::bind (&DatagramDestination::SendMsg, this,
|
||||
CreateDataMessage (buf, len + headerLen), remote));
|
||||
}
|
||||
|
||||
void DatagramDestination::SendMsg (I2NPMessage * msg, const i2p::data::LeaseSet& remote)
|
||||
{
|
||||
auto outboundTunnel = m_Owner.GetTunnelPool ()->GetNextOutboundTunnel ();
|
||||
auto leases = remote.GetNonExpiredLeases ();
|
||||
if (!leases.empty ())
|
||||
if (!leases.empty () && outboundTunnel)
|
||||
{
|
||||
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
|
||||
uint32_t i = i2p::context.GetRandomNumberGenerator ().GenerateWord32 (0, leases.size () - 1);
|
||||
@@ -58,11 +55,14 @@ namespace datagram
|
||||
leases[i].tunnelGateway, leases[i].tunnelID,
|
||||
garlic
|
||||
});
|
||||
m_Owner.SendTunnelDataMsgs (msgs);
|
||||
outboundTunnel->SendTunnelDataMsg (msgs);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "Failed to send datagram. All leases expired");
|
||||
if (outboundTunnel)
|
||||
LogPrint (eLogWarning, "Failed to send datagram. All leases expired");
|
||||
else
|
||||
LogPrint (eLogWarning, "Failed to send datagram. No outbound tunnels");
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
}
|
||||
@@ -76,11 +76,7 @@ namespace datagram
|
||||
|
||||
bool verified = false;
|
||||
if (identity.GetSigningKeyType () == i2p::data::SIGNING_KEY_TYPE_DSA_SHA1)
|
||||
{
|
||||
uint8_t hash[32];
|
||||
CryptoPP::SHA256().CalculateDigest (hash, buf + headerLen, len - headerLen);
|
||||
verified = identity.Verify (hash, 32, signature);
|
||||
}
|
||||
verified = CryptoPP::SHA256().VerifyDigest (signature, buf + headerLen, len - headerLen);
|
||||
else
|
||||
verified = identity.Verify (buf + headerLen, len - headerLen, signature);
|
||||
|
||||
@@ -121,7 +117,7 @@ namespace datagram
|
||||
compressor.MessageEnd();
|
||||
int size = compressor.MaxRetrievable ();
|
||||
uint8_t * buf = msg->GetPayload ();
|
||||
*(uint32_t *)buf = htobe32 (size); // length
|
||||
htobe32buf (buf, size); // length
|
||||
buf += 4;
|
||||
compressor.Get (buf, size);
|
||||
memset (buf + 4, 0, 4); // source and destination are zeroes
|
||||
|
||||
502
Destination.cpp
502
Destination.cpp
@@ -1,131 +1,124 @@
|
||||
#include <fstream>
|
||||
#include <algorithm>
|
||||
#include <cryptopp/dh.h>
|
||||
#include <cassert>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "Log.h"
|
||||
#include "util.h"
|
||||
#include "ElGamal.h"
|
||||
#include "Timestamp.h"
|
||||
#include "NetDb.h"
|
||||
#include "ClientContext.h"
|
||||
#include "Destination.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace client
|
||||
{
|
||||
ClientDestination::ClientDestination (bool isPublic, i2p::data::SigningKeyType sigType):
|
||||
m_IsRunning (false), m_Thread (nullptr), m_Service (nullptr), m_Work (nullptr),
|
||||
m_CurrentOutboundTunnel (nullptr), m_LeaseSet (nullptr), m_IsPublic (isPublic),
|
||||
m_DatagramDestination (nullptr)
|
||||
{
|
||||
m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
|
||||
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
|
||||
dh.GenerateKeyPair(i2p::context.GetRandomNumberGenerator (), m_EncryptionPrivateKey, m_EncryptionPublicKey);
|
||||
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (*this, 3); // 3-hops tunnel
|
||||
if (m_IsPublic)
|
||||
LogPrint ("Local address ", GetIdentHash ().ToBase32 (), ".b32.i2p created");
|
||||
m_StreamingDestination = new i2p::stream::StreamingDestination (*this); // TODO:
|
||||
}
|
||||
|
||||
ClientDestination::ClientDestination (const std::string& fullPath, bool isPublic):
|
||||
m_IsRunning (false), m_Thread (nullptr), m_Service (nullptr), m_Work (nullptr),
|
||||
m_CurrentOutboundTunnel (nullptr), m_LeaseSet (nullptr), m_IsPublic (isPublic),
|
||||
m_DatagramDestination (nullptr)
|
||||
ClientDestination::ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
|
||||
const std::map<std::string, std::string> * params):
|
||||
m_IsRunning (false), m_Thread (nullptr), m_Work (m_Service),
|
||||
m_Keys (keys), m_LeaseSet (nullptr), m_IsPublic (isPublic), m_PublishReplyToken (0),
|
||||
m_DatagramDestination (nullptr), m_PublishConfirmationTimer (m_Service)
|
||||
{
|
||||
std::ifstream s(fullPath.c_str (), 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);
|
||||
m_Keys.FromBuffer (buf, len);
|
||||
delete[] buf;
|
||||
LogPrint ("Local address ", GetIdentHash ().ToBase32 (), ".b32.i2p loaded");
|
||||
}
|
||||
else
|
||||
i2p::crypto::GenerateElGamalKeyPair(i2p::context.GetRandomNumberGenerator (), m_EncryptionPrivateKey, m_EncryptionPublicKey);
|
||||
int inboundTunnelLen = DEFAULT_INBOUND_TUNNEL_LENGTH;
|
||||
int outboundTunnelLen = DEFAULT_OUTBOUND_TUNNEL_LENGTH;
|
||||
if (params)
|
||||
{
|
||||
LogPrint ("Can't open file ", fullPath, " Creating new one");
|
||||
m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1);
|
||||
std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
|
||||
size_t len = m_Keys.GetFullLen ();
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
len = m_Keys.ToBuffer (buf, len);
|
||||
f.write ((char *)buf, len);
|
||||
delete[] buf;
|
||||
|
||||
LogPrint ("New private keys file ", fullPath, " for ", m_Keys.GetPublic ().GetIdentHash ().ToBase32 (), ".b32.i2p created");
|
||||
auto it = params->find (I2CP_PARAM_INBOUND_TUNNEL_LENGTH);
|
||||
if (it != params->end ())
|
||||
{
|
||||
int len = boost::lexical_cast<int>(it->second);
|
||||
if (len > 0)
|
||||
{
|
||||
inboundTunnelLen = len;
|
||||
LogPrint (eLogInfo, "Inbound tunnel length set to ", len);
|
||||
}
|
||||
}
|
||||
it = params->find (I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH);
|
||||
if (it != params->end ())
|
||||
{
|
||||
int len = boost::lexical_cast<int>(it->second);
|
||||
if (len > 0)
|
||||
{
|
||||
outboundTunnelLen = len;
|
||||
LogPrint (eLogInfo, "Outbound tunnel length set to ", len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
|
||||
dh.GenerateKeyPair(i2p::context.GetRandomNumberGenerator (), m_EncryptionPrivateKey, m_EncryptionPublicKey);
|
||||
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (*this, 3); // 3-hops tunnel
|
||||
m_StreamingDestination = new i2p::stream::StreamingDestination (*this); // TODO:
|
||||
}
|
||||
|
||||
ClientDestination::ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic):
|
||||
m_IsRunning (false), m_Thread (nullptr), m_Service (nullptr), m_Work (nullptr),
|
||||
m_Keys (keys), m_CurrentOutboundTunnel (nullptr), m_LeaseSet (nullptr), m_IsPublic (isPublic),
|
||||
m_DatagramDestination (nullptr)
|
||||
{
|
||||
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
|
||||
dh.GenerateKeyPair(i2p::context.GetRandomNumberGenerator (), m_EncryptionPrivateKey, m_EncryptionPublicKey);
|
||||
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (*this, 3); // 3-hops tunnel
|
||||
m_Pool = i2p::tunnel::tunnels.CreateTunnelPool (this, inboundTunnelLen, outboundTunnelLen);
|
||||
if (m_IsPublic)
|
||||
LogPrint ("Local address ", GetIdentHash ().ToBase32 (), ".b32.i2p created");
|
||||
LogPrint (eLogInfo, "Local address ", i2p::client::context.GetAddressBook ().ToAddress(GetIdentHash()), " created");
|
||||
m_StreamingDestination = new i2p::stream::StreamingDestination (*this); // TODO:
|
||||
}
|
||||
|
||||
ClientDestination::~ClientDestination ()
|
||||
{
|
||||
Stop ();
|
||||
if (m_IsRunning)
|
||||
Stop ();
|
||||
for (auto it: m_LeaseSetRequests)
|
||||
delete it.second;
|
||||
for (auto it: m_RemoteLeaseSets)
|
||||
delete it.second;
|
||||
if (m_Pool)
|
||||
i2p::tunnel::tunnels.DeleteTunnelPool (m_Pool);
|
||||
delete m_LeaseSet;
|
||||
delete m_Work;
|
||||
delete m_Service;
|
||||
delete m_StreamingDestination;
|
||||
delete m_DatagramDestination;
|
||||
if (m_StreamingDestination)
|
||||
delete m_StreamingDestination;
|
||||
if (m_DatagramDestination)
|
||||
delete m_DatagramDestination;
|
||||
}
|
||||
|
||||
void ClientDestination::Run ()
|
||||
{
|
||||
if (m_Service)
|
||||
m_Service->run ();
|
||||
while (m_IsRunning)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Service.run ();
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint ("Destination: ", ex.what ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::Start ()
|
||||
{
|
||||
m_Service = new boost::asio::io_service;
|
||||
m_Work = new boost::asio::io_service::work (*m_Service);
|
||||
m_Pool->SetActive (true);
|
||||
m_IsRunning = true;
|
||||
m_Thread = new std::thread (std::bind (&ClientDestination::Run, this));
|
||||
m_StreamingDestination->Start ();
|
||||
if (!m_IsRunning)
|
||||
{
|
||||
m_IsRunning = true;
|
||||
m_Pool->SetLocalDestination (this);
|
||||
m_Pool->SetActive (true);
|
||||
m_Thread = new std::thread (std::bind (&ClientDestination::Run, this));
|
||||
m_StreamingDestination->Start ();
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::Stop ()
|
||||
{
|
||||
m_StreamingDestination->Stop ();
|
||||
if (m_DatagramDestination)
|
||||
{
|
||||
auto d = m_DatagramDestination;
|
||||
m_DatagramDestination = nullptr;
|
||||
delete d;
|
||||
}
|
||||
if (m_Pool)
|
||||
i2p::tunnel::tunnels.StopTunnelPool (m_Pool);
|
||||
m_IsRunning = false;
|
||||
if (m_Service)
|
||||
m_Service->stop ();
|
||||
if (m_Thread)
|
||||
if (m_IsRunning)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = 0;
|
||||
m_IsRunning = false;
|
||||
m_StreamingDestination->Stop ();
|
||||
if (m_DatagramDestination)
|
||||
{
|
||||
auto d = m_DatagramDestination;
|
||||
m_DatagramDestination = nullptr;
|
||||
delete d;
|
||||
}
|
||||
if (m_Pool)
|
||||
{
|
||||
m_Pool->SetLocalDestination (nullptr);
|
||||
i2p::tunnel::tunnels.StopTunnelPool (m_Pool);
|
||||
}
|
||||
m_Service.stop ();
|
||||
if (m_Thread)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = 0;
|
||||
}
|
||||
}
|
||||
delete m_Work; m_Work = nullptr;
|
||||
delete m_Service; m_Service = nullptr;
|
||||
}
|
||||
|
||||
const i2p::data::LeaseSet * ClientDestination::FindLeaseSet (const i2p::data::IdentHash& ident)
|
||||
@@ -138,7 +131,7 @@ namespace client
|
||||
else
|
||||
{
|
||||
LogPrint ("All leases of remote LeaseSet expired. Request it");
|
||||
i2p::data::netdb.RequestDestination (ident, true, m_Pool);
|
||||
RequestDestination (ident);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -175,40 +168,44 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::SendTunnelDataMsgs (const std::vector<i2p::tunnel::TunnelMessageBlock>& msgs)
|
||||
bool ClientDestination::SubmitSessionKey (const uint8_t * key, const uint8_t * tag)
|
||||
{
|
||||
m_CurrentOutboundTunnel = m_Pool->GetNextOutboundTunnel (m_CurrentOutboundTunnel);
|
||||
if (m_CurrentOutboundTunnel)
|
||||
m_CurrentOutboundTunnel->SendTunnelDataMsg (msgs);
|
||||
else
|
||||
struct
|
||||
{
|
||||
LogPrint ("No outbound tunnels in the pool");
|
||||
for (auto it: msgs)
|
||||
DeleteI2NPMessage (it.data);
|
||||
}
|
||||
uint8_t k[32], t[32];
|
||||
} data;
|
||||
memcpy (data.k, key, 32);
|
||||
memcpy (data.t, tag, 32);
|
||||
m_Service.post ([this,data](void)
|
||||
{
|
||||
this->AddSessionKey (data.k, data.t);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClientDestination::ProcessGarlicMessage (I2NPMessage * msg)
|
||||
{
|
||||
m_Service->post (boost::bind (&ClientDestination::HandleGarlicMessage, this, msg));
|
||||
m_Service.post (std::bind (&ClientDestination::HandleGarlicMessage, this, msg));
|
||||
}
|
||||
|
||||
void ClientDestination::ProcessDeliveryStatusMessage (I2NPMessage * msg)
|
||||
{
|
||||
m_Service->post (boost::bind (&ClientDestination::HandleDeliveryStatusMessage, this, msg));
|
||||
m_Service.post (std::bind (&ClientDestination::HandleDeliveryStatusMessage, this, msg));
|
||||
}
|
||||
|
||||
void ClientDestination::HandleI2NPMessage (const uint8_t * buf, size_t len, i2p::tunnel::InboundTunnel * from)
|
||||
{
|
||||
I2NPHeader * header = (I2NPHeader *)buf;
|
||||
switch (header->typeID)
|
||||
uint8_t typeID = buf[I2NP_HEADER_TYPEID_OFFSET];
|
||||
switch (typeID)
|
||||
{
|
||||
case eI2NPData:
|
||||
HandleDataMessage (buf + sizeof (I2NPHeader), be16toh (header->size));
|
||||
HandleDataMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
|
||||
break;
|
||||
case eI2NPDatabaseStore:
|
||||
HandleDatabaseStoreMessage (buf + sizeof (I2NPHeader), be16toh (header->size));
|
||||
i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from)); // TODO: remove
|
||||
HandleDatabaseStoreMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
|
||||
break;
|
||||
case eI2NPDatabaseSearchReply:
|
||||
HandleDatabaseSearchReplyMessage (buf + I2NP_HEADER_SIZE, bufbe16toh (buf + I2NP_HEADER_SIZE_OFFSET));
|
||||
break;
|
||||
default:
|
||||
i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from));
|
||||
@@ -217,27 +214,94 @@ namespace client
|
||||
|
||||
void ClientDestination::HandleDatabaseStoreMessage (const uint8_t * buf, size_t len)
|
||||
{
|
||||
I2NPDatabaseStoreMsg * msg = (I2NPDatabaseStoreMsg *)buf;
|
||||
size_t offset = sizeof (I2NPDatabaseStoreMsg);
|
||||
if (msg->replyToken) // TODO:
|
||||
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
|
||||
size_t offset = DATABASE_STORE_HEADER_SIZE;
|
||||
if (replyToken) // TODO:
|
||||
offset += 36;
|
||||
if (msg->type == 1) // LeaseSet
|
||||
if (buf[DATABASE_STORE_TYPE_OFFSET] == 1) // LeaseSet
|
||||
{
|
||||
LogPrint ("Remote LeaseSet");
|
||||
auto it = m_RemoteLeaseSets.find (msg->key);
|
||||
LogPrint (eLogDebug, "Remote LeaseSet");
|
||||
auto it = m_RemoteLeaseSets.find (buf + DATABASE_STORE_KEY_OFFSET);
|
||||
if (it != m_RemoteLeaseSets.end ())
|
||||
{
|
||||
it->second->Update (buf + offset, len - offset);
|
||||
LogPrint ("Remote LeaseSet updated");
|
||||
LogPrint (eLogDebug, "Remote LeaseSet updated");
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("New remote LeaseSet added");
|
||||
m_RemoteLeaseSets[msg->key] = new i2p::data::LeaseSet (buf + offset, len - offset);
|
||||
LogPrint (eLogDebug, "New remote LeaseSet added");
|
||||
m_RemoteLeaseSets[buf + DATABASE_STORE_KEY_OFFSET] = new i2p::data::LeaseSet (buf + offset, len - offset);
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint ("Unexpected client's DatabaseStore type ", msg->type, ". Dropped");
|
||||
LogPrint (eLogError, "Unexpected client's DatabaseStore type ", buf[DATABASE_STORE_TYPE_OFFSET], ". Dropped");
|
||||
|
||||
auto it1 = m_LeaseSetRequests.find (buf + DATABASE_STORE_KEY_OFFSET);
|
||||
if (it1 != m_LeaseSetRequests.end ())
|
||||
{
|
||||
it1->second->requestTimeoutTimer.cancel ();
|
||||
if (it1->second->requestComplete) it1->second->requestComplete (true);
|
||||
delete it1->second;
|
||||
m_LeaseSetRequests.erase (it1);
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len)
|
||||
{
|
||||
i2p::data::IdentHash key (buf);
|
||||
int num = buf[32]; // num
|
||||
LogPrint ("DatabaseSearchReply for ", key.ToBase64 (), " num=", num);
|
||||
auto it = m_LeaseSetRequests.find (key);
|
||||
if (it != m_LeaseSetRequests.end ())
|
||||
{
|
||||
LeaseSetRequest * request = it->second;
|
||||
bool found = false;
|
||||
if (request->excluded.size () < MAX_NUM_FLOODFILLS_PER_REQUEST)
|
||||
{
|
||||
for (int i = 0; i < num; i++)
|
||||
{
|
||||
i2p::data::IdentHash peerHash (buf + 33 + i*32);
|
||||
auto floodfill = i2p::data::netdb.FindRouter (peerHash);
|
||||
if (floodfill)
|
||||
{
|
||||
LogPrint (eLogInfo, "Requesting ", key.ToBase64 (), " at ", peerHash.ToBase64 ());
|
||||
if (SendLeaseSetRequest (key, floodfill, request))
|
||||
found = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogInfo, "Found new floodfill. Request it");
|
||||
i2p::data::netdb.RequestDestination (peerHash);
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
LogPrint (eLogError, "Suggested floodfills are not presented in netDb");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogInfo, key.ToBase64 (), " was not found on ", MAX_NUM_FLOODFILLS_PER_REQUEST," floodfills");
|
||||
if (!found)
|
||||
{
|
||||
if (request->requestComplete) request->requestComplete (false);
|
||||
delete request;
|
||||
m_LeaseSetRequests.erase (key);
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint ("Request for ", key.ToBase64 (), " not found");
|
||||
}
|
||||
|
||||
void ClientDestination::HandleDeliveryStatusMessage (I2NPMessage * msg)
|
||||
{
|
||||
uint32_t msgID = bufbe32toh (msg->GetPayload () + DELIVERY_STATUS_MSGID_OFFSET);
|
||||
if (msgID == m_PublishReplyToken)
|
||||
{
|
||||
LogPrint (eLogDebug, "Publishing confirmed");
|
||||
m_ExcludedFloodfills.clear ();
|
||||
m_PublishReplyToken = 0;
|
||||
i2p::DeleteI2NPMessage (msg);
|
||||
}
|
||||
else
|
||||
i2p::garlic::GarlicDestination::HandleDeliveryStatusMessage (msg);
|
||||
}
|
||||
|
||||
void ClientDestination::SetLeaseSetUpdated ()
|
||||
@@ -245,12 +309,61 @@ namespace client
|
||||
i2p::garlic::GarlicDestination::SetLeaseSetUpdated ();
|
||||
UpdateLeaseSet ();
|
||||
if (m_IsPublic)
|
||||
i2p::data::netdb.PublishLeaseSet (m_LeaseSet, m_Pool);
|
||||
Publish ();
|
||||
}
|
||||
|
||||
void ClientDestination::Publish ()
|
||||
{
|
||||
if (!m_LeaseSet || !m_Pool)
|
||||
{
|
||||
LogPrint (eLogError, "Can't publish non-existing LeaseSet");
|
||||
return;
|
||||
}
|
||||
if (m_PublishReplyToken)
|
||||
{
|
||||
LogPrint (eLogInfo, "Publishing is pending");
|
||||
return;
|
||||
}
|
||||
auto outbound = m_Pool->GetNextOutboundTunnel ();
|
||||
if (!outbound)
|
||||
{
|
||||
LogPrint ("Can't publish LeaseSet. No outbound tunnels");
|
||||
return;
|
||||
}
|
||||
std::set<i2p::data::IdentHash> excluded;
|
||||
auto floodfill = i2p::data::netdb.GetClosestFloodfill (m_LeaseSet->GetIdentHash (), m_ExcludedFloodfills);
|
||||
if (!floodfill)
|
||||
{
|
||||
LogPrint ("Can't publish LeaseSet. No more floodfills found");
|
||||
m_ExcludedFloodfills.clear ();
|
||||
return;
|
||||
}
|
||||
m_ExcludedFloodfills.insert (floodfill->GetIdentHash ());
|
||||
LogPrint (eLogDebug, "Publish LeaseSet of ", GetIdentHash ().ToBase32 ());
|
||||
m_PublishReplyToken = i2p::context.GetRandomNumberGenerator ().GenerateWord32 ();
|
||||
auto msg = WrapMessage (*floodfill, i2p::CreateDatabaseStoreMsg (m_LeaseSet, m_PublishReplyToken));
|
||||
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_CONFIRMATION_TIMEOUT));
|
||||
m_PublishConfirmationTimer.async_wait (std::bind (&ClientDestination::HandlePublishConfirmationTimer,
|
||||
this, std::placeholders::_1));
|
||||
outbound->SendTunnelDataMsg (floodfill->GetIdentHash (), 0, msg);
|
||||
}
|
||||
|
||||
void ClientDestination::HandlePublishConfirmationTimer (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
if (m_PublishReplyToken)
|
||||
{
|
||||
LogPrint (eLogWarning, "Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, "seconds. Try again");
|
||||
m_PublishReplyToken = 0;
|
||||
Publish ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::HandleDataMessage (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint32_t length = be32toh (*(uint32_t *)buf);
|
||||
uint32_t length = bufbe32toh (buf);
|
||||
buf += 4;
|
||||
// we assume I2CP payload
|
||||
switch (buf[9])
|
||||
@@ -274,12 +387,49 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
i2p::stream::Stream * ClientDestination::CreateStream (const i2p::data::LeaseSet& remote, int port)
|
||||
void ClientDestination::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port) {
|
||||
assert(streamRequestComplete);
|
||||
i2p::data::IdentHash identHash;
|
||||
if (i2p::client::context.GetAddressBook ().GetIdentHash (dest, identHash))
|
||||
CreateStream (streamRequestComplete, identHash, port);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "Remote destination ", dest, " not found");
|
||||
streamRequestComplete (nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
void ClientDestination::CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port) {
|
||||
assert(streamRequestComplete);
|
||||
const i2p::data::LeaseSet * leaseSet = FindLeaseSet (dest);
|
||||
if (leaseSet)
|
||||
streamRequestComplete(CreateStream (*leaseSet, port));
|
||||
else
|
||||
{
|
||||
RequestDestination (dest,
|
||||
[this, streamRequestComplete, dest, port](bool success)
|
||||
{
|
||||
if (!success)
|
||||
streamRequestComplete (nullptr);
|
||||
else
|
||||
{
|
||||
const i2p::data::LeaseSet * leaseSet = FindLeaseSet (dest);
|
||||
if (leaseSet)
|
||||
streamRequestComplete(CreateStream (*leaseSet, port));
|
||||
else
|
||||
streamRequestComplete (nullptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (const i2p::data::LeaseSet& remote, int port)
|
||||
{
|
||||
if (m_StreamingDestination)
|
||||
return m_StreamingDestination->CreateNewOutgoingStream (remote, port);
|
||||
return nullptr;
|
||||
}
|
||||
else
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void ClientDestination::AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor)
|
||||
{
|
||||
@@ -306,5 +456,111 @@ namespace client
|
||||
m_DatagramDestination = new i2p::datagram::DatagramDestination (*this);
|
||||
return m_DatagramDestination;
|
||||
}
|
||||
|
||||
bool ClientDestination::RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete)
|
||||
{
|
||||
if (!m_Pool || !IsReady ())
|
||||
{
|
||||
if (requestComplete) requestComplete (false);
|
||||
return false;
|
||||
}
|
||||
m_Service.post (std::bind (&ClientDestination::RequestLeaseSet, this, dest, requestComplete));
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClientDestination::RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete)
|
||||
{
|
||||
std::set<i2p::data::IdentHash> excluded;
|
||||
auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, excluded);
|
||||
if (floodfill)
|
||||
{
|
||||
LeaseSetRequest * request = new LeaseSetRequest (m_Service);
|
||||
request->requestComplete = requestComplete;
|
||||
m_LeaseSetRequests[dest] = request;
|
||||
if (!SendLeaseSetRequest (dest, floodfill, request))
|
||||
{
|
||||
// request failed
|
||||
if (request->requestComplete) request->requestComplete (false);
|
||||
delete request;
|
||||
m_LeaseSetRequests.erase (dest);
|
||||
}
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "No floodfills found");
|
||||
}
|
||||
|
||||
bool ClientDestination::SendLeaseSetRequest (const i2p::data::IdentHash& dest,
|
||||
std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, LeaseSetRequest * request)
|
||||
{
|
||||
auto replyTunnel = m_Pool->GetNextInboundTunnel ();
|
||||
if (!replyTunnel) LogPrint (eLogError, "No inbound tunnels found");
|
||||
|
||||
auto outboundTunnel = m_Pool->GetNextOutboundTunnel ();
|
||||
if (!outboundTunnel) LogPrint (eLogError, "No outbound tunnels found");
|
||||
|
||||
if (replyTunnel && outboundTunnel)
|
||||
{
|
||||
request->excluded.insert (nextFloodfill->GetIdentHash ());
|
||||
request->requestTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
request->requestTimeoutTimer.cancel ();
|
||||
|
||||
CryptoPP::AutoSeededRandomPool rnd;
|
||||
uint8_t replyKey[32], replyTag[32];
|
||||
rnd.GenerateBlock (replyKey, 32); // random session key
|
||||
rnd.GenerateBlock (replyTag, 32); // random session tag
|
||||
AddSessionKey (replyKey, replyTag);
|
||||
|
||||
I2NPMessage * msg = WrapMessage (*nextFloodfill,
|
||||
CreateLeaseSetDatabaseLookupMsg (dest, request->excluded,
|
||||
replyTunnel, replyKey, replyTag));
|
||||
outboundTunnel->SendTunnelDataMsg (
|
||||
{
|
||||
i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
i2p::tunnel::eDeliveryTypeRouter,
|
||||
nextFloodfill->GetIdentHash (), 0, msg
|
||||
}
|
||||
});
|
||||
request->requestTimeoutTimer.expires_from_now (boost::posix_time::seconds(LEASESET_REQUEST_TIMEOUT));
|
||||
request->requestTimeoutTimer.async_wait (std::bind (&ClientDestination::HandleRequestTimoutTimer,
|
||||
this, std::placeholders::_1, dest));
|
||||
}
|
||||
else
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClientDestination::HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
auto it = m_LeaseSetRequests.find (dest);
|
||||
if (it != m_LeaseSetRequests.end ())
|
||||
{
|
||||
bool done = false;
|
||||
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
if (ts < it->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
|
||||
{
|
||||
auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, it->second->excluded);
|
||||
if (floodfill)
|
||||
SendLeaseSetRequest (dest, floodfill, it->second);
|
||||
else
|
||||
done = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogInfo, dest.ToBase64 (), " was not found within ", MAX_LEASESET_REQUEST_TIMEOUT, " seconds");
|
||||
done = true;
|
||||
}
|
||||
|
||||
if (done)
|
||||
{
|
||||
if (it->second->requestComplete) it->second->requestComplete (false);
|
||||
delete it->second;
|
||||
m_LeaseSetRequests.erase (it);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,18 @@
|
||||
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
#include "TunnelPool.h"
|
||||
#include "CryptoConst.h"
|
||||
#include "LeaseSet.h"
|
||||
#include "Garlic.h"
|
||||
#include "NetDb.h"
|
||||
#include "Streaming.h"
|
||||
#include "Datagram.h"
|
||||
|
||||
@@ -18,30 +25,51 @@ namespace client
|
||||
const uint8_t PROTOCOL_TYPE_STREAMING = 6;
|
||||
const uint8_t PROTOCOL_TYPE_DATAGRAM = 17;
|
||||
const uint8_t PROTOCOL_TYPE_RAW = 18;
|
||||
|
||||
const int PUBLISH_CONFIRMATION_TIMEOUT = 5; // in seconds
|
||||
const int LEASESET_REQUEST_TIMEOUT = 5; // in seconds
|
||||
const int MAX_LEASESET_REQUEST_TIMEOUT = 40; // in seconds
|
||||
const int MAX_NUM_FLOODFILLS_PER_REQUEST = 7;
|
||||
|
||||
// I2CP
|
||||
const char I2CP_PARAM_INBOUND_TUNNEL_LENGTH[] = "inbound.length";
|
||||
const int DEFAULT_INBOUND_TUNNEL_LENGTH = 3;
|
||||
const char I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH[] = "outbound.length";
|
||||
const int DEFAULT_OUTBOUND_TUNNEL_LENGTH = 3;
|
||||
const int STREAM_REQUEST_TIMEOUT = 60; //in seconds
|
||||
|
||||
class ClientDestination: public i2p::garlic::GarlicDestination
|
||||
{
|
||||
typedef std::function<void (bool success)> RequestComplete;
|
||||
struct LeaseSetRequest
|
||||
{
|
||||
LeaseSetRequest (boost::asio::io_service& service): requestTime (0), requestTimeoutTimer (service) {};
|
||||
std::set<i2p::data::IdentHash> excluded;
|
||||
uint64_t requestTime;
|
||||
boost::asio::deadline_timer requestTimeoutTimer;
|
||||
RequestComplete requestComplete;
|
||||
};
|
||||
|
||||
typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete;
|
||||
|
||||
public:
|
||||
|
||||
ClientDestination (bool isPublic, i2p::data::SigningKeyType sigType);
|
||||
ClientDestination (const std::string& fullPath, bool isPublic);
|
||||
ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic);
|
||||
ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params = nullptr);
|
||||
~ClientDestination ();
|
||||
|
||||
virtual void Start ();
|
||||
virtual void Stop ();
|
||||
bool IsRunning () const { return m_IsRunning; };
|
||||
boost::asio::io_service * GetService () { return m_Service; };
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
i2p::tunnel::TunnelPool * GetTunnelPool () { return m_Pool; };
|
||||
bool IsReady () const { return m_LeaseSet && m_LeaseSet->HasNonExpiredLeases (); };
|
||||
|
||||
void ResetCurrentOutboundTunnel () { m_CurrentOutboundTunnel = nullptr; };
|
||||
const i2p::data::LeaseSet * FindLeaseSet (const i2p::data::IdentHash& ident);
|
||||
void SendTunnelDataMsgs (const std::vector<i2p::tunnel::TunnelMessageBlock>& msgs);
|
||||
|
||||
bool RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete = nullptr);
|
||||
|
||||
// streaming
|
||||
i2p::stream::StreamingDestination * GetStreamingDestination () const { return m_StreamingDestination; };
|
||||
i2p::stream::Stream * CreateStream (const i2p::data::LeaseSet& remote, int port = 0);
|
||||
void CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port = 0);
|
||||
void CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port = 0);
|
||||
std::shared_ptr<i2p::stream::Stream> CreateStream (const i2p::data::LeaseSet& remote, int port = 0);
|
||||
void AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor);
|
||||
void StopAcceptingStreams ();
|
||||
bool IsAcceptingStreams () const;
|
||||
@@ -60,6 +88,7 @@ namespace client
|
||||
void HandleI2NPMessage (const uint8_t * buf, size_t len, i2p::tunnel::InboundTunnel * from);
|
||||
|
||||
// override GarlicDestination
|
||||
bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag);
|
||||
void ProcessGarlicMessage (I2NPMessage * msg);
|
||||
void ProcessDeliveryStatusMessage (I2NPMessage * msg);
|
||||
void SetLeaseSetUpdated ();
|
||||
@@ -71,26 +100,38 @@ namespace client
|
||||
|
||||
void Run ();
|
||||
void UpdateLeaseSet ();
|
||||
void HandleDatabaseStoreMessage (const uint8_t * buf, size_t len);
|
||||
void Publish ();
|
||||
void HandlePublishConfirmationTimer (const boost::system::error_code& ecode);
|
||||
void HandleDatabaseStoreMessage (const uint8_t * buf, size_t len);
|
||||
void HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len);
|
||||
void HandleDeliveryStatusMessage (I2NPMessage * msg);
|
||||
|
||||
void RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete);
|
||||
bool SendLeaseSetRequest (const i2p::data::IdentHash& dest, std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, LeaseSetRequest * request);
|
||||
void HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest);
|
||||
|
||||
private:
|
||||
|
||||
bool m_IsRunning;
|
||||
volatile bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
boost::asio::io_service * m_Service;
|
||||
boost::asio::io_service::work * m_Work;
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::io_service::work m_Work;
|
||||
i2p::data::PrivateKeys m_Keys;
|
||||
uint8_t m_EncryptionPublicKey[256], m_EncryptionPrivateKey[256];
|
||||
std::map<i2p::data::IdentHash, i2p::data::LeaseSet *> m_RemoteLeaseSets;
|
||||
std::map<i2p::data::IdentHash, LeaseSetRequest *> m_LeaseSetRequests;
|
||||
|
||||
i2p::tunnel::TunnelPool * m_Pool;
|
||||
i2p::tunnel::OutboundTunnel * m_CurrentOutboundTunnel;
|
||||
i2p::data::LeaseSet * m_LeaseSet;
|
||||
bool m_IsPublic;
|
||||
|
||||
uint32_t m_PublishReplyToken;
|
||||
std::set<i2p::data::IdentHash> m_ExcludedFloodfills; // for publishing
|
||||
|
||||
i2p::stream::StreamingDestination * m_StreamingDestination;
|
||||
i2p::datagram::DatagramDestination * m_DatagramDestination;
|
||||
|
||||
boost::asio::deadline_timer m_PublishConfirmationTimer;
|
||||
|
||||
public:
|
||||
|
||||
// for HTTP only
|
||||
|
||||
13
ElGamal.h
13
ElGamal.h
@@ -4,6 +4,7 @@
|
||||
#include <inttypes.h>
|
||||
#include <cryptopp/integer.h>
|
||||
#include <cryptopp/osrng.h>
|
||||
#include <cryptopp/dh.h>
|
||||
#include <cryptopp/sha.h>
|
||||
#include "CryptoConst.h"
|
||||
#include "Log.h"
|
||||
@@ -51,7 +52,6 @@ namespace crypto
|
||||
|
||||
CryptoPP::AutoSeededRandomPool rnd;
|
||||
CryptoPP::Integer y, k, a, b1;
|
||||
bool m_ZeroPadding;
|
||||
};
|
||||
|
||||
inline bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted,
|
||||
@@ -71,6 +71,17 @@ namespace crypto
|
||||
memcpy (data, m + 33, 222);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void GenerateElGamalKeyPair (CryptoPP::RandomNumberGenerator& rnd, uint8_t * priv, uint8_t * pub)
|
||||
{
|
||||
#if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER)
|
||||
rnd.GenerateBlock (priv, 256);
|
||||
a_exp_b_mod_c (elgg, CryptoPP::Integer (priv, 256), elgp).Encode (pub, 256);
|
||||
#else
|
||||
CryptoPP::DH dh (elgp, elgg);
|
||||
dh.GenerateKeyPair(rnd, priv, pub);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
54
Garlic.cpp
54
Garlic.cpp
@@ -83,6 +83,7 @@ namespace garlic
|
||||
I2NPMessage * GarlicRoutingSession::WrapSingleMessage (I2NPMessage * msg)
|
||||
{
|
||||
I2NPMessage * m = NewI2NPMessage ();
|
||||
m->Align (12); // in order to get buf aligned to 16 (12 + 4)
|
||||
size_t len = 0;
|
||||
uint8_t * buf = m->GetPayload () + 4; // 4 bytes for length
|
||||
|
||||
@@ -137,7 +138,7 @@ namespace garlic
|
||||
}
|
||||
// AES block
|
||||
len += CreateAESBlock (buf, msg);
|
||||
*(uint32_t *)(m->GetPayload ()) = htobe32 (len);
|
||||
htobe32buf (m->GetPayload (), len);
|
||||
m->len += len + 4;
|
||||
FillI2NPMessageHeader (m, eI2NPGarlic);
|
||||
if (msg)
|
||||
@@ -150,7 +151,7 @@ namespace garlic
|
||||
size_t blockSize = 0;
|
||||
bool createNewTags = m_Owner && m_NumTags && ((int)m_SessionTags.size () <= m_NumTags/2);
|
||||
UnconfirmedTags * newTags = createNewTags ? GenerateSessionTags () : nullptr;
|
||||
*(uint16_t *)buf = newTags ? htobe16 (newTags->numTags) : 0; // tag count
|
||||
htobuf16 (buf, newTags ? htobe16 (newTags->numTags) : 0); // tag count
|
||||
blockSize += 2;
|
||||
if (newTags) // session tags recreated
|
||||
{
|
||||
@@ -167,7 +168,7 @@ namespace garlic
|
||||
buf[blockSize] = 0; // flag
|
||||
blockSize++;
|
||||
size_t len = CreateGarlicPayload (buf + blockSize, msg, newTags);
|
||||
*payloadSize = htobe32 (len);
|
||||
htobe32buf (payloadSize, len);
|
||||
CryptoPP::SHA256().CalculateDigest(payloadHash, buf + blockSize, len);
|
||||
blockSize += len;
|
||||
size_t rem = blockSize % 16;
|
||||
@@ -219,9 +220,9 @@ namespace garlic
|
||||
|
||||
memset (payload + size, 0, 3); // certificate of message
|
||||
size += 3;
|
||||
*(uint32_t *)(payload + size) = htobe32 (msgID); // MessageID
|
||||
htobe32buf (payload + size, msgID); // MessageID
|
||||
size += 4;
|
||||
*(uint64_t *)(payload + size) = htobe64 (ts); // Expiration of message
|
||||
htobe64buf (payload + size, ts); // Expiration of message
|
||||
size += 8;
|
||||
return size;
|
||||
}
|
||||
@@ -245,9 +246,9 @@ namespace garlic
|
||||
|
||||
memcpy (buf + size, msg->GetBuffer (), msg->GetLength ());
|
||||
size += msg->GetLength ();
|
||||
*(uint32_t *)(buf + size) = htobe32 (m_Rnd.GenerateWord32 ()); // CloveID
|
||||
htobe32buf (buf + size, m_Rnd.GenerateWord32 ()); // CloveID
|
||||
size += 4;
|
||||
*(uint64_t *)(buf + size) = htobe64 (ts); // Expiration of clove
|
||||
htobe64buf (buf + size, ts); // Expiration of clove
|
||||
size += 8;
|
||||
memset (buf + size, 0, 3); // certificate of clove
|
||||
size += 3;
|
||||
@@ -268,7 +269,7 @@ namespace garlic
|
||||
// hash and tunnelID sequence is reversed for Garlic
|
||||
memcpy (buf + size, leases[i].tunnelGateway, 32); // To Hash
|
||||
size += 32;
|
||||
*(uint32_t *)(buf + size) = htobe32 (leases[i].tunnelID); // tunnelID
|
||||
htobe32buf (buf + size, leases[i].tunnelID); // tunnelID
|
||||
size += 4;
|
||||
// create msg
|
||||
I2NPMessage * msg = CreateDeliveryStatusMsg (msgID);
|
||||
@@ -278,7 +279,7 @@ namespace garlic
|
||||
uint8_t key[32], tag[32];
|
||||
m_Rnd.GenerateBlock (key, 32); // random session key
|
||||
m_Rnd.GenerateBlock (tag, 32); // random session tag
|
||||
m_Owner->AddSessionKey (key, tag);
|
||||
m_Owner->SubmitSessionKey (key, tag);
|
||||
GarlicRoutingSession garlic (key, tag);
|
||||
msg = garlic.WrapSingleMessage (msg);
|
||||
}
|
||||
@@ -287,9 +288,9 @@ namespace garlic
|
||||
DeleteI2NPMessage (msg);
|
||||
// fill clove
|
||||
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch () + 5000; // 5 sec
|
||||
*(uint32_t *)(buf + size) = htobe32 (m_Rnd.GenerateWord32 ()); // CloveID
|
||||
htobe32buf (buf + size, m_Rnd.GenerateWord32 ()); // CloveID
|
||||
size += 4;
|
||||
*(uint64_t *)(buf + size) = htobe64 (ts); // Expiration of clove
|
||||
htobe64buf (buf + size, ts); // Expiration of clove
|
||||
size += 8;
|
||||
memset (buf + size, 0, 3); // certificate of clove
|
||||
size += 3;
|
||||
@@ -321,10 +322,16 @@ namespace garlic
|
||||
}
|
||||
}
|
||||
|
||||
bool GarlicDestination::SubmitSessionKey (const uint8_t * key, const uint8_t * tag)
|
||||
{
|
||||
AddSessionKey (key, tag);
|
||||
return true;
|
||||
}
|
||||
|
||||
void GarlicDestination::HandleGarlicMessage (I2NPMessage * msg)
|
||||
{
|
||||
uint8_t * buf = msg->GetPayload ();
|
||||
uint32_t length = be32toh (*(uint32_t *)buf);
|
||||
uint32_t length = bufbe32toh (buf);
|
||||
buf += 4; // length
|
||||
auto it = m_Tags.find (SessionTag(buf));
|
||||
if (it != m_Tags.end ())
|
||||
@@ -382,19 +389,25 @@ namespace garlic
|
||||
void GarlicDestination::HandleAESBlock (uint8_t * buf, size_t len, std::shared_ptr<i2p::crypto::CBCDecryption> decryption,
|
||||
i2p::tunnel::InboundTunnel * from)
|
||||
{
|
||||
uint16_t tagCount = be16toh (*(uint16_t *)buf);
|
||||
buf += 2;
|
||||
uint16_t tagCount = bufbe16toh (buf);
|
||||
buf += 2; len -= 2;
|
||||
if (tagCount > 0)
|
||||
{
|
||||
if (tagCount*32 > len)
|
||||
{
|
||||
LogPrint (eLogError, "Tag count ", tagCount, " exceeds length ", len);
|
||||
return ;
|
||||
}
|
||||
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
for (int i = 0; i < tagCount; i++)
|
||||
m_Tags[SessionTag(buf + i*32, ts)] = decryption;
|
||||
}
|
||||
buf += tagCount*32;
|
||||
uint32_t payloadSize = be32toh (*(uint32_t *)buf);
|
||||
len -= tagCount*32;
|
||||
uint32_t payloadSize = bufbe32toh (buf);
|
||||
if (payloadSize > len)
|
||||
{
|
||||
LogPrint ("Unexpected payload size ", payloadSize);
|
||||
LogPrint (eLogError, "Unexpected payload size ", payloadSize);
|
||||
return;
|
||||
}
|
||||
buf += 4;
|
||||
@@ -405,9 +418,7 @@ namespace garlic
|
||||
buf++; // flag
|
||||
|
||||
// payload
|
||||
uint8_t hash[32];
|
||||
CryptoPP::SHA256().CalculateDigest(hash, buf, payloadSize);
|
||||
if (memcmp (hash, payloadHash, 32)) // payload hash doesn't match
|
||||
if (!CryptoPP::SHA256().VerifyDigest (payloadHash, buf, payloadSize)) // payload hash doesn't match
|
||||
{
|
||||
LogPrint ("Wrong payload hash");
|
||||
return;
|
||||
@@ -449,7 +460,7 @@ namespace garlic
|
||||
// gwHash and gwTunnel sequence is reverted
|
||||
uint8_t * gwHash = buf;
|
||||
buf += 32;
|
||||
uint32_t gwTunnel = be32toh (*(uint32_t *)buf);
|
||||
uint32_t gwTunnel = bufbe32toh (buf);
|
||||
buf += 4;
|
||||
i2p::tunnel::OutboundTunnel * tunnel = nullptr;
|
||||
if (from && from->GetTunnelPool ())
|
||||
@@ -515,8 +526,7 @@ namespace garlic
|
||||
|
||||
void GarlicDestination::HandleDeliveryStatusMessage (I2NPMessage * msg)
|
||||
{
|
||||
I2NPDeliveryStatusMsg * deliveryStatus = (I2NPDeliveryStatusMsg *)msg->GetPayload ();
|
||||
uint32_t msgID = be32toh (deliveryStatus->msgID);
|
||||
uint32_t msgID = bufbe32toh (msg->GetPayload ());
|
||||
{
|
||||
auto it = m_CreatedSessions.find (msgID);
|
||||
if (it != m_CreatedSessions.end ())
|
||||
|
||||
1
Garlic.h
1
Garlic.h
@@ -110,6 +110,7 @@ namespace garlic
|
||||
I2NPMessage * msg, bool attachLeaseSet = false);
|
||||
|
||||
void AddSessionKey (const uint8_t * key, const uint8_t * tag); // one tag
|
||||
virtual bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag); // from different thread
|
||||
void DeliveryStatusSent (GarlicRoutingSession * session, uint32_t msgID);
|
||||
|
||||
virtual void ProcessGarlicMessage (I2NPMessage * msg);
|
||||
|
||||
@@ -485,17 +485,17 @@ namespace util
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case 105: buffers.push_back(boost::asio::buffer("HTTP/1.0 105 Name Not Resolved\r\n")); break;
|
||||
case 200: buffers.push_back(boost::asio::buffer("HTTP/1.0 200 OK\r\n")); break;
|
||||
case 400: buffers.push_back(boost::asio::buffer("HTTP/1.0 400 Bad Request\r\n")); break;
|
||||
case 404: buffers.push_back(boost::asio::buffer("HTTP/1.0 404 Not Found\r\n")); break;
|
||||
case 408: buffers.push_back(boost::asio::buffer("HTTP/1.0 408 Request Timeout\r\n")); break;
|
||||
case 500: buffers.push_back(boost::asio::buffer("HTTP/1.0 500 Internal Server Error\r\n")); break;
|
||||
case 502: buffers.push_back(boost::asio::buffer("HTTP/1.0 502 Bad Gateway\r\n")); break;
|
||||
case 503: buffers.push_back(boost::asio::buffer("HTTP/1.0 503 Not Implemented\r\n")); break;
|
||||
case 504: buffers.push_back(boost::asio::buffer("HTTP/1.0 504 Gateway Timeout\r\n")); break;
|
||||
case 105: buffers.push_back(boost::asio::buffer("HTTP/1.1 105 Name Not Resolved\r\n")); break;
|
||||
case 200: buffers.push_back(boost::asio::buffer("HTTP/1.1 200 OK\r\n")); break;
|
||||
case 400: buffers.push_back(boost::asio::buffer("HTTP/1.1 400 Bad Request\r\n")); break;
|
||||
case 404: buffers.push_back(boost::asio::buffer("HTTP/1.1 404 Not Found\r\n")); break;
|
||||
case 408: buffers.push_back(boost::asio::buffer("HTTP/1.1 408 Request Timeout\r\n")); break;
|
||||
case 500: buffers.push_back(boost::asio::buffer("HTTP/1.1 500 Internal Server Error\r\n")); break;
|
||||
case 502: buffers.push_back(boost::asio::buffer("HTTP/1.1 502 Bad Gateway\r\n")); break;
|
||||
case 503: buffers.push_back(boost::asio::buffer("HTTP/1.1 503 Not Implemented\r\n")); break;
|
||||
case 504: buffers.push_back(boost::asio::buffer("HTTP/1.1 504 Gateway Timeout\r\n")); break;
|
||||
default:
|
||||
buffers.push_back(boost::asio::buffer("HTTP/1.0 200 OK\r\n"));
|
||||
buffers.push_back(boost::asio::buffer("HTTP/1.1 200 OK\r\n"));
|
||||
}
|
||||
|
||||
for (std::size_t i = 0; i < headers.size(); ++i)
|
||||
@@ -514,14 +514,16 @@ namespace util
|
||||
|
||||
void HTTPConnection::Terminate ()
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
m_Stream->Close ();
|
||||
i2p::stream::DeleteStream (m_Stream);
|
||||
m_Stream = nullptr;
|
||||
}
|
||||
if (!m_Stream) return;
|
||||
m_Socket->close ();
|
||||
//delete this;
|
||||
m_Stream->Close ();
|
||||
|
||||
m_Socket->get_io_service ().post ([=](void)
|
||||
{
|
||||
m_Stream.reset ();
|
||||
m_Stream = nullptr;
|
||||
// delete this
|
||||
});
|
||||
}
|
||||
|
||||
void HTTPConnection::Receive ()
|
||||
@@ -602,7 +604,10 @@ namespace util
|
||||
void HTTPConnection::HandleWriteReply (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
m_Socket->close ();
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPConnection::HandleWrite (const boost::system::error_code& ecode)
|
||||
@@ -744,8 +749,6 @@ namespace util
|
||||
for (auto it: i2p::tunnel::tunnels.GetOutboundTunnels ())
|
||||
{
|
||||
it->GetTunnelConfig ()->Print (s);
|
||||
if (it->GetTunnelPool () && !it->GetTunnelPool ()->IsExploratory ())
|
||||
s << " " << "Pool";
|
||||
auto state = it->GetState ();
|
||||
if (state == i2p::tunnel::eTunnelStateFailed)
|
||||
s << " " << "Failed";
|
||||
@@ -758,8 +761,6 @@ namespace util
|
||||
for (auto it: i2p::tunnel::tunnels.GetInboundTunnels ())
|
||||
{
|
||||
it.second->GetTunnelConfig ()->Print (s);
|
||||
if (it.second->GetTunnelPool () && !it.second->GetTunnelPool ()->IsExploratory ())
|
||||
s << " " << "Pool";
|
||||
auto state = it.second->GetState ();
|
||||
if (state == i2p::tunnel::eTunnelStateFailed)
|
||||
s << " " << "Failed";
|
||||
@@ -791,7 +792,7 @@ namespace util
|
||||
std::string b32 = it.first.ToBase32 ();
|
||||
s << "<a href=/?" << HTTP_COMMAND_LOCAL_DESTINATION;
|
||||
s << "&" << HTTP_PARAM_BASE32_ADDRESS << "=" << b32 << ">";
|
||||
s << b32 << ".b32.i2p</a><br>" << std::endl;
|
||||
s << i2p::client::context.GetAddressBook ().ToAddress(it.second->GetIdentHash()) << "</a><br>" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -810,18 +811,28 @@ namespace util
|
||||
for (auto it: pool->GetOutboundTunnels ())
|
||||
{
|
||||
it->GetTunnelConfig ()->Print (s);
|
||||
auto state = it->GetState ();
|
||||
if (state == i2p::tunnel::eTunnelStateFailed)
|
||||
s << " " << "Failed";
|
||||
else if (state == i2p::tunnel::eTunnelStateExpiring)
|
||||
s << " " << "Exp";
|
||||
s << "<br>" << std::endl;
|
||||
}
|
||||
for (auto it: pool->GetInboundTunnels ())
|
||||
{
|
||||
it->GetTunnelConfig ()->Print (s);
|
||||
auto state = it->GetState ();
|
||||
if (state == i2p::tunnel::eTunnelStateFailed)
|
||||
s << " " << "Failed";
|
||||
else if (state == i2p::tunnel::eTunnelStateExpiring)
|
||||
s << " " << "Exp";
|
||||
s << "<br>" << std::endl;
|
||||
}
|
||||
}
|
||||
s << "<br><b>Streams:</b><br>";
|
||||
for (auto it: dest->GetStreamingDestination ()->GetStreams ())
|
||||
{
|
||||
s << it.first << "->" << it.second->GetRemoteIdentity ().GetIdentHash ().ToBase32 () << ".b32.i2p ";
|
||||
s << it.first << "->" << i2p::client::context.GetAddressBook ().ToAddress(it.second->GetRemoteIdentity ()) << " ";
|
||||
s << " [" << it.second->GetNumSentBytes () << ":" << it.second->GetNumReceivedBytes () << "]";
|
||||
s << " [out:" << it.second->GetSendQueueSize () << "][in:" << it.second->GetReceiveQueueSize () << "]";
|
||||
s << "<br>"<< std::endl;
|
||||
@@ -863,10 +874,12 @@ namespace util
|
||||
SendToDestination (leaseSet, port, buf, len);
|
||||
else
|
||||
{
|
||||
i2p::data::netdb.RequestDestination (destination, true, i2p::client::context.GetSharedLocalDestination ()->GetTunnelPool ());
|
||||
memcpy (m_Buffer, buf, len);
|
||||
m_BufferLen = len;
|
||||
i2p::client::context.GetSharedLocalDestination ()->RequestDestination (destination);
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(HTTP_DESTINATION_REQUEST_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&HTTPConnection::HandleDestinationRequestTimeout,
|
||||
this, boost::asio::placeholders::error, destination, port, buf, len));
|
||||
this, boost::asio::placeholders::error, destination, port, m_Buffer, m_BufferLen));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include "LeaseSet.h"
|
||||
@@ -79,7 +80,7 @@ namespace util
|
||||
|
||||
boost::asio::ip::tcp::socket * m_Socket;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
i2p::stream::Stream * m_Stream;
|
||||
std::shared_ptr<i2p::stream::Stream> m_Stream;
|
||||
char m_Buffer[HTTP_CONNECTION_BUFFER_SIZE + 1], m_StreamBuffer[HTTP_CONNECTION_BUFFER_SIZE + 1];
|
||||
size_t m_BufferLen;
|
||||
request m_Request;
|
||||
|
||||
355
I2NPProtocol.cpp
355
I2NPProtocol.cpp
@@ -1,7 +1,6 @@
|
||||
#include <string.h>
|
||||
#include <atomic>
|
||||
#include "I2PEndian.h"
|
||||
#include <cryptopp/sha.h>
|
||||
#include <cryptopp/gzip.h>
|
||||
#include "ElGamal.h"
|
||||
#include "Timestamp.h"
|
||||
@@ -40,31 +39,26 @@ namespace i2p
|
||||
static std::atomic<uint32_t> I2NPmsgID(0); // TODO: create class
|
||||
void FillI2NPMessageHeader (I2NPMessage * msg, I2NPMessageType msgType, uint32_t replyMsgID)
|
||||
{
|
||||
I2NPHeader * header = msg->GetHeader ();
|
||||
header->typeID = msgType;
|
||||
msg->SetTypeID (msgType);
|
||||
if (replyMsgID) // for tunnel creation
|
||||
header->msgID = htobe32 (replyMsgID);
|
||||
msg->SetMsgID (replyMsgID);
|
||||
else
|
||||
{
|
||||
header->msgID = htobe32 (I2NPmsgID);
|
||||
msg->SetMsgID (I2NPmsgID);
|
||||
I2NPmsgID++;
|
||||
}
|
||||
header->expiration = htobe64 (i2p::util::GetMillisecondsSinceEpoch () + 5000); // TODO: 5 secs is a magic number
|
||||
int len = msg->GetLength () - sizeof (I2NPHeader);
|
||||
header->size = htobe16 (len);
|
||||
uint8_t hash[32];
|
||||
CryptoPP::SHA256().CalculateDigest(hash, msg->GetPayload (), len);
|
||||
header->chks = hash[0];
|
||||
}
|
||||
|
||||
msg->SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + 5000); // TODO: 5 secs is a magic number
|
||||
msg->UpdateSize ();
|
||||
msg->UpdateChks ();
|
||||
}
|
||||
|
||||
void RenewI2NPMessageHeader (I2NPMessage * msg)
|
||||
{
|
||||
if (msg)
|
||||
{
|
||||
I2NPHeader * header = msg->GetHeader ();
|
||||
header->msgID = htobe32 (I2NPmsgID);
|
||||
msg->SetMsgID (I2NPmsgID);
|
||||
I2NPmsgID++;
|
||||
header->expiration = htobe64 (i2p::util::GetMillisecondsSinceEpoch () + 5000);
|
||||
msg->SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + 5000);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,23 +82,25 @@ namespace i2p
|
||||
|
||||
I2NPMessage * CreateDeliveryStatusMsg (uint32_t msgID)
|
||||
{
|
||||
I2NPDeliveryStatusMsg msg;
|
||||
I2NPMessage * m = NewI2NPMessage ();
|
||||
uint8_t * buf = m->GetPayload ();
|
||||
if (msgID)
|
||||
{
|
||||
msg.msgID = htobe32 (msgID);
|
||||
msg.timestamp = htobe64 (i2p::util::GetMillisecondsSinceEpoch ());
|
||||
htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, msgID);
|
||||
htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, i2p::util::GetMillisecondsSinceEpoch ());
|
||||
}
|
||||
else // for SSU establishment
|
||||
{
|
||||
msg.msgID = htobe32 (i2p::context.GetRandomNumberGenerator ().GenerateWord32 ());
|
||||
msg.timestamp = htobe64 (2); // netID = 2
|
||||
}
|
||||
return CreateI2NPMessage (eI2NPDeliveryStatus, (uint8_t *)&msg, sizeof (msg));
|
||||
htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, i2p::context.GetRandomNumberGenerator ().GenerateWord32 ());
|
||||
htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, 2); // netID = 2
|
||||
}
|
||||
m->len += DELIVERY_STATUS_SIZE;
|
||||
FillI2NPMessageHeader (m, eI2NPDeliveryStatus);
|
||||
return m;
|
||||
}
|
||||
|
||||
I2NPMessage * CreateDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
|
||||
uint32_t replyTunnelID, bool exploratory, std::set<i2p::data::IdentHash> * excludedPeers,
|
||||
bool encryption, i2p::tunnel::TunnelPool * pool)
|
||||
I2NPMessage * CreateRouterInfoDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
|
||||
uint32_t replyTunnelID, bool exploratory, std::set<i2p::data::IdentHash> * excludedPeers)
|
||||
{
|
||||
I2NPMessage * m = NewI2NPMessage ();
|
||||
uint8_t * buf = m->GetPayload ();
|
||||
@@ -112,65 +108,81 @@ namespace i2p
|
||||
buf += 32;
|
||||
memcpy (buf, from, 32); // from
|
||||
buf += 32;
|
||||
uint8_t flag = exploratory ? 0x0C : 0x08; // 1000 - RI, 1100 -exporatory
|
||||
if (replyTunnelID)
|
||||
{
|
||||
*buf = encryption ? 0x03: 0x01; // set delivery flag
|
||||
*(uint32_t *)(buf+1) = htobe32 (replyTunnelID);
|
||||
*buf = flag | 0x01; // set delivery flag
|
||||
htobe32buf (buf+1, replyTunnelID);
|
||||
buf += 5;
|
||||
}
|
||||
else
|
||||
{
|
||||
encryption = false; // encryption can we set for tunnels only
|
||||
*buf = 0; // flag
|
||||
*buf = flag; // flag
|
||||
buf++;
|
||||
}
|
||||
|
||||
if (exploratory)
|
||||
|
||||
if (excludedPeers)
|
||||
{
|
||||
*(uint16_t *)buf = htobe16 (1); // one exlude record
|
||||
int cnt = excludedPeers->size ();
|
||||
htobe16buf (buf, cnt);
|
||||
buf += 2;
|
||||
// reply with non-floodfill routers only
|
||||
memset (buf, 0, 32);
|
||||
buf += 32;
|
||||
for (auto& it: *excludedPeers)
|
||||
{
|
||||
memcpy (buf, it, 32);
|
||||
buf += 32;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (excludedPeers)
|
||||
{
|
||||
int cnt = excludedPeers->size ();
|
||||
*(uint16_t *)buf = htobe16 (cnt);
|
||||
buf += 2;
|
||||
for (auto& it: *excludedPeers)
|
||||
{
|
||||
memcpy (buf, it, 32);
|
||||
buf += 32;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// nothing to exclude
|
||||
*(uint16_t *)buf = htobe16 (0);
|
||||
buf += 2;
|
||||
}
|
||||
}
|
||||
if (encryption)
|
||||
{
|
||||
// session key and tag for reply
|
||||
auto& rnd = i2p::context.GetRandomNumberGenerator ();
|
||||
rnd.GenerateBlock (buf, 32); // key
|
||||
buf[32] = 1; // 1 tag
|
||||
rnd.GenerateBlock (buf + 33, 32); // tag
|
||||
if (pool)
|
||||
pool->GetGarlicDestination ().AddSessionKey (buf, buf + 33); // introduce new key-tag to garlic engine
|
||||
else
|
||||
LogPrint ("Destination for encrypteed reply not specified");
|
||||
buf += 65;
|
||||
}
|
||||
{
|
||||
// nothing to exclude
|
||||
htobuf16 (buf, 0);
|
||||
buf += 2;
|
||||
}
|
||||
|
||||
m->len += (buf - m->GetPayload ());
|
||||
FillI2NPMessageHeader (m, eI2NPDatabaseLookup);
|
||||
return m;
|
||||
}
|
||||
|
||||
I2NPMessage * CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest,
|
||||
const std::set<i2p::data::IdentHash>& excludedFloodfills,
|
||||
const i2p::tunnel::InboundTunnel * replyTunnel, const uint8_t * replyKey, const uint8_t * replyTag)
|
||||
{
|
||||
I2NPMessage * m = NewI2NPMessage ();
|
||||
uint8_t * buf = m->GetPayload ();
|
||||
memcpy (buf, dest, 32); // key
|
||||
buf += 32;
|
||||
memcpy (buf, replyTunnel->GetNextIdentHash (), 32); // reply tunnel GW
|
||||
buf += 32;
|
||||
*buf = 7; // flags (01 - tunnel, 10 - encrypted, 0100 - LS lookup
|
||||
htobe32buf (buf + 1, replyTunnel->GetNextTunnelID ()); // reply tunnel ID
|
||||
buf += 5;
|
||||
|
||||
// excluded
|
||||
int cnt = excludedFloodfills.size ();
|
||||
htobe16buf (buf, cnt);
|
||||
buf += 2;
|
||||
if (cnt > 0)
|
||||
{
|
||||
for (auto& it: excludedFloodfills)
|
||||
{
|
||||
memcpy (buf, it, 32);
|
||||
buf += 32;
|
||||
}
|
||||
}
|
||||
// encryption
|
||||
memcpy (buf, replyKey, 32);
|
||||
buf[32] = 1; // 1 tag
|
||||
memcpy (buf + 33, replyTag, 32);
|
||||
buf += 65;
|
||||
|
||||
m->len += (buf - m->GetPayload ());
|
||||
FillI2NPMessageHeader (m, eI2NPDatabaseLookup);
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
|
||||
I2NPMessage * CreateDatabaseSearchReply (const i2p::data::IdentHash& ident,
|
||||
const i2p::data::RouterInfo * floodfill)
|
||||
{
|
||||
@@ -199,22 +211,22 @@ namespace i2p
|
||||
router = &context.GetRouterInfo ();
|
||||
|
||||
I2NPMessage * m = NewI2NPShortMessage ();
|
||||
I2NPDatabaseStoreMsg * msg = (I2NPDatabaseStoreMsg *)m->GetPayload ();
|
||||
uint8_t * payload = m->GetPayload ();
|
||||
|
||||
memcpy (msg->key, router->GetIdentHash (), 32);
|
||||
msg->type = 0;
|
||||
msg->replyToken = 0;
|
||||
memcpy (payload + DATABASE_STORE_KEY_OFFSET, router->GetIdentHash (), 32);
|
||||
payload[DATABASE_STORE_TYPE_OFFSET] = 0;
|
||||
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
|
||||
|
||||
CryptoPP::Gzip compressor;
|
||||
compressor.Put (router->GetBuffer (), router->GetBufferLen ());
|
||||
compressor.MessageEnd();
|
||||
auto size = compressor.MaxRetrievable ();
|
||||
uint8_t * buf = m->GetPayload () + sizeof (I2NPDatabaseStoreMsg);
|
||||
*(uint16_t *)buf = htobe16 (size); // size
|
||||
uint8_t * buf = payload + DATABASE_STORE_HEADER_SIZE;
|
||||
htobe16buf (buf, size); // size
|
||||
buf += 2;
|
||||
// TODO: check if size doesn't exceed buffer
|
||||
compressor.Get (buf, size);
|
||||
m->len += sizeof (I2NPDatabaseStoreMsg) + 2 + size; // payload size
|
||||
m->len += DATABASE_STORE_HEADER_SIZE + 2 + size; // payload size
|
||||
FillI2NPMessageHeader (m, eI2NPDatabaseStore);
|
||||
|
||||
return m;
|
||||
@@ -225,23 +237,22 @@ namespace i2p
|
||||
if (!leaseSet) return nullptr;
|
||||
I2NPMessage * m = NewI2NPShortMessage ();
|
||||
uint8_t * payload = m->GetPayload ();
|
||||
I2NPDatabaseStoreMsg * msg = (I2NPDatabaseStoreMsg *)payload;
|
||||
memcpy (msg->key, leaseSet->GetIdentHash (), 32);
|
||||
msg->type = 1; // LeaseSet
|
||||
msg->replyToken = htobe32 (replyToken);
|
||||
size_t size = sizeof (I2NPDatabaseStoreMsg);
|
||||
memcpy (payload + DATABASE_STORE_KEY_OFFSET, leaseSet->GetIdentHash (), 32);
|
||||
payload[DATABASE_STORE_TYPE_OFFSET] = 1; // LeaseSet
|
||||
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, replyToken);
|
||||
size_t size = DATABASE_STORE_HEADER_SIZE;
|
||||
if (replyToken)
|
||||
{
|
||||
auto leases = leaseSet->GetNonExpiredLeases ();
|
||||
if (leases.size () > 0)
|
||||
{
|
||||
*(uint32_t *)(payload + size) = htobe32 (leases[0].tunnelID);
|
||||
htobe32buf (payload + size, leases[0].tunnelID);
|
||||
size += 4; // reply tunnelID
|
||||
memcpy (payload + size, leases[0].tunnelGateway, 32);
|
||||
size += 32; // reply tunnel gateway
|
||||
}
|
||||
else
|
||||
msg->replyToken = 0;
|
||||
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
|
||||
}
|
||||
memcpy (payload + size, leaseSet->GetBuffer (), leaseSet->GetBufferLen ());
|
||||
size += leaseSet->GetBufferLen ();
|
||||
@@ -249,73 +260,46 @@ namespace i2p
|
||||
FillI2NPMessageHeader (m, eI2NPDatabaseStore);
|
||||
return m;
|
||||
}
|
||||
|
||||
I2NPBuildRequestRecordClearText CreateBuildRequestRecord (
|
||||
const uint8_t * ourIdent, uint32_t receiveTunnelID,
|
||||
const uint8_t * nextIdent, uint32_t nextTunnelID,
|
||||
const uint8_t * layerKey,const uint8_t * ivKey,
|
||||
const uint8_t * replyKey, const uint8_t * replyIV, uint32_t nextMessageID,
|
||||
bool isGateway, bool isEndpoint)
|
||||
{
|
||||
I2NPBuildRequestRecordClearText clearText;
|
||||
clearText.receiveTunnel = htobe32 (receiveTunnelID);
|
||||
clearText.nextTunnel = htobe32(nextTunnelID);
|
||||
memcpy (clearText.layerKey, layerKey, 32);
|
||||
memcpy (clearText.ivKey, ivKey, 32);
|
||||
memcpy (clearText.replyKey, replyKey, 32);
|
||||
memcpy (clearText.replyIV, replyIV, 16);
|
||||
clearText.flag = 0;
|
||||
if (isGateway) clearText.flag |= 0x80;
|
||||
if (isEndpoint) clearText.flag |= 0x40;
|
||||
memcpy (clearText.ourIdent, ourIdent, 32);
|
||||
memcpy (clearText.nextIdent, nextIdent, 32);
|
||||
clearText.requestTime = htobe32 (i2p::util::GetHoursSinceEpoch ());
|
||||
clearText.nextMessageID = htobe32(nextMessageID);
|
||||
return clearText;
|
||||
}
|
||||
|
||||
void EncryptBuildRequestRecord (const i2p::data::RouterInfo& router,
|
||||
const I2NPBuildRequestRecordClearText& clearText,
|
||||
I2NPBuildRequestRecordElGamalEncrypted& record)
|
||||
{
|
||||
router.GetElGamalEncryption ()->Encrypt ((uint8_t *)&clearText, sizeof(clearText), record.encrypted);
|
||||
memcpy (record.toPeer, (const uint8_t *)router.GetIdentHash (), 16);
|
||||
}
|
||||
|
||||
bool HandleBuildRequestRecords (int num, I2NPBuildRequestRecordElGamalEncrypted * records, I2NPBuildRequestRecordClearText& clearText)
|
||||
bool HandleBuildRequestRecords (int num, uint8_t * records, uint8_t * clearText)
|
||||
{
|
||||
for (int i = 0; i < num; i++)
|
||||
{
|
||||
if (!memcmp (records[i].toPeer, (const uint8_t *)i2p::context.GetRouterInfo ().GetIdentHash (), 16))
|
||||
uint8_t * record = records + i*TUNNEL_BUILD_RECORD_SIZE;
|
||||
if (!memcmp (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)i2p::context.GetRouterInfo ().GetIdentHash (), 16))
|
||||
{
|
||||
LogPrint ("Record ",i," is ours");
|
||||
|
||||
i2p::crypto::ElGamalDecrypt (i2p::context.GetEncryptionPrivateKey (), records[i].encrypted, (uint8_t *)&clearText);
|
||||
// replace record to reply
|
||||
I2NPBuildResponseRecord * reply = (I2NPBuildResponseRecord *)(records + i);
|
||||
i2p::crypto::ElGamalDecrypt (i2p::context.GetEncryptionPrivateKey (), record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, clearText);
|
||||
// replace record to reply
|
||||
if (i2p::context.AcceptsTunnels ())
|
||||
{
|
||||
i2p::tunnel::TransitTunnel * transitTunnel =
|
||||
i2p::tunnel::CreateTransitTunnel (
|
||||
be32toh (clearText.receiveTunnel),
|
||||
clearText.nextIdent, be32toh (clearText.nextTunnel),
|
||||
clearText.layerKey, clearText.ivKey,
|
||||
clearText.flag & 0x80, clearText.flag & 0x40);
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
|
||||
clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
clearText + BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET,
|
||||
clearText + BUILD_REQUEST_RECORD_IV_KEY_OFFSET,
|
||||
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x80,
|
||||
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET ] & 0x40);
|
||||
i2p::tunnel::tunnels.AddTransitTunnel (transitTunnel);
|
||||
reply->ret = 0;
|
||||
record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 0;
|
||||
}
|
||||
else
|
||||
reply->ret = 30; // always reject with bandwidth reason (30)
|
||||
record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 30; // always reject with bandwidth reason (30)
|
||||
|
||||
//TODO: fill filler
|
||||
CryptoPP::SHA256().CalculateDigest(reply->hash, reply->padding, sizeof (reply->padding) + 1); // + 1 byte of ret
|
||||
CryptoPP::SHA256().CalculateDigest(record + BUILD_RESPONSE_RECORD_HASH_OFFSET,
|
||||
record + BUILD_RESPONSE_RECORD_PADDING_OFFSET, BUILD_RESPONSE_RECORD_PADDING_SIZE + 1); // + 1 byte of ret
|
||||
// encrypt reply
|
||||
i2p::crypto::CBCEncryption encryption;
|
||||
for (int j = 0; j < num; j++)
|
||||
{
|
||||
encryption.SetKey (clearText.replyKey);
|
||||
encryption.SetIV (clearText.replyIV);
|
||||
encryption.Encrypt((uint8_t *)(records + j), sizeof (records[j]), (uint8_t *)(records + j));
|
||||
encryption.SetKey (clearText + BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET);
|
||||
encryption.SetIV (clearText + BUILD_REQUEST_RECORD_REPLY_IV_OFFSET);
|
||||
uint8_t * reply = records + j*TUNNEL_BUILD_RECORD_SIZE;
|
||||
encryption.Encrypt(reply, TUNNEL_BUILD_RECORD_SIZE, reply);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -347,41 +331,42 @@ namespace i2p
|
||||
}
|
||||
else
|
||||
{
|
||||
I2NPBuildRequestRecordElGamalEncrypted * records = (I2NPBuildRequestRecordElGamalEncrypted *)(buf+1);
|
||||
I2NPBuildRequestRecordClearText clearText;
|
||||
if (HandleBuildRequestRecords (num, records, clearText))
|
||||
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
|
||||
if (HandleBuildRequestRecords (num, buf + 1, clearText))
|
||||
{
|
||||
if (clearText.flag & 0x40) // we are endpoint of outboud tunnel
|
||||
if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outboud tunnel
|
||||
{
|
||||
// so we send it to reply tunnel
|
||||
transports.SendMessage (clearText.nextIdent,
|
||||
CreateTunnelGatewayMsg (be32toh (clearText.nextTunnel),
|
||||
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
eI2NPVariableTunnelBuildReply, buf, len,
|
||||
be32toh (clearText.nextMessageID)));
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
|
||||
}
|
||||
else
|
||||
transports.SendMessage (clearText.nextIdent,
|
||||
CreateI2NPMessage (eI2NPVariableTunnelBuild, buf, len, be32toh (clearText.nextMessageID)));
|
||||
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
CreateI2NPMessage (eI2NPVariableTunnelBuild, buf, len,
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HandleTunnelBuildMsg (uint8_t * buf, size_t len)
|
||||
{
|
||||
I2NPBuildRequestRecordClearText clearText;
|
||||
if (HandleBuildRequestRecords (NUM_TUNNEL_BUILD_RECORDS, (I2NPBuildRequestRecordElGamalEncrypted *)buf, clearText))
|
||||
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
|
||||
if (HandleBuildRequestRecords (NUM_TUNNEL_BUILD_RECORDS, buf, clearText))
|
||||
{
|
||||
if (clearText.flag & 0x40) // we are endpoint of outbound tunnel
|
||||
if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outbound tunnel
|
||||
{
|
||||
// so we send it to reply tunnel
|
||||
transports.SendMessage (clearText.nextIdent,
|
||||
CreateTunnelGatewayMsg (be32toh (clearText.nextTunnel),
|
||||
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
eI2NPTunnelBuildReply, buf, len,
|
||||
be32toh (clearText.nextMessageID)));
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
|
||||
}
|
||||
else
|
||||
transports.SendMessage (clearText.nextIdent,
|
||||
CreateI2NPMessage (eI2NPTunnelBuild, buf, len, be32toh (clearText.nextMessageID)));
|
||||
transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
CreateI2NPMessage (eI2NPTunnelBuild, buf, len,
|
||||
bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,7 +407,7 @@ namespace i2p
|
||||
{
|
||||
I2NPMessage * msg = NewI2NPMessage ();
|
||||
memcpy (msg->GetPayload () + 4, payload, i2p::tunnel::TUNNEL_DATA_MSG_SIZE - 4);
|
||||
*(uint32_t *)(msg->GetPayload ()) = htobe32 (tunnelID);
|
||||
htobe32buf (msg->GetPayload (), tunnelID);
|
||||
msg->len += i2p::tunnel::TUNNEL_DATA_MSG_SIZE;
|
||||
FillI2NPMessageHeader (msg, eI2NPTunnelData);
|
||||
return msg;
|
||||
@@ -431,26 +416,26 @@ namespace i2p
|
||||
I2NPMessage * CreateTunnelGatewayMsg (uint32_t tunnelID, const uint8_t * buf, size_t len)
|
||||
{
|
||||
I2NPMessage * msg = NewI2NPMessage (len);
|
||||
TunnelGatewayHeader * header = (TunnelGatewayHeader *)msg->GetPayload ();
|
||||
header->tunnelID = htobe32 (tunnelID);
|
||||
header->length = htobe16 (len);
|
||||
memcpy (msg->GetPayload () + sizeof (TunnelGatewayHeader), buf, len);
|
||||
msg->len += sizeof (TunnelGatewayHeader) + len;
|
||||
uint8_t * payload = msg->GetPayload ();
|
||||
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
|
||||
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
|
||||
memcpy (payload + TUNNEL_GATEWAY_HEADER_SIZE, buf, len);
|
||||
msg->len += TUNNEL_GATEWAY_HEADER_SIZE + len;
|
||||
FillI2NPMessageHeader (msg, eI2NPTunnelGateway);
|
||||
return msg;
|
||||
}
|
||||
|
||||
I2NPMessage * CreateTunnelGatewayMsg (uint32_t tunnelID, I2NPMessage * msg)
|
||||
{
|
||||
if (msg->offset >= sizeof (I2NPHeader) + sizeof (TunnelGatewayHeader))
|
||||
if (msg->offset >= I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE)
|
||||
{
|
||||
// message is capable to be used without copying
|
||||
TunnelGatewayHeader * header = (TunnelGatewayHeader *)(msg->GetBuffer () - sizeof (TunnelGatewayHeader));
|
||||
header->tunnelID = htobe32 (tunnelID);
|
||||
uint8_t * payload = msg->GetBuffer () - TUNNEL_GATEWAY_HEADER_SIZE;
|
||||
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
|
||||
int len = msg->GetLength ();
|
||||
header->length = htobe16 (len);
|
||||
msg->offset -= (sizeof (I2NPHeader) + sizeof (TunnelGatewayHeader));
|
||||
msg->len = msg->offset + sizeof (I2NPHeader) + sizeof (TunnelGatewayHeader) +len;
|
||||
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
|
||||
msg->offset -= (I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE);
|
||||
msg->len = msg->offset + I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE +len;
|
||||
FillI2NPMessageHeader (msg, eI2NPTunnelGateway);
|
||||
return msg;
|
||||
}
|
||||
@@ -466,7 +451,7 @@ namespace i2p
|
||||
const uint8_t * buf, size_t len, uint32_t replyMsgID)
|
||||
{
|
||||
I2NPMessage * msg = NewI2NPMessage (len);
|
||||
size_t gatewayMsgOffset = sizeof (I2NPHeader) + sizeof (TunnelGatewayHeader);
|
||||
size_t gatewayMsgOffset = I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE;
|
||||
msg->offset += gatewayMsgOffset;
|
||||
msg->len += gatewayMsgOffset;
|
||||
memcpy (msg->GetPayload (), buf, len);
|
||||
@@ -474,24 +459,25 @@ namespace i2p
|
||||
FillI2NPMessageHeader (msg, msgType, replyMsgID); // create content message
|
||||
len = msg->GetLength ();
|
||||
msg->offset -= gatewayMsgOffset;
|
||||
TunnelGatewayHeader * header = (TunnelGatewayHeader *)msg->GetPayload ();
|
||||
header->tunnelID = htobe32 (tunnelID);
|
||||
header->length = htobe16 (len);
|
||||
uint8_t * payload = msg->GetPayload ();
|
||||
htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
|
||||
htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
|
||||
FillI2NPMessageHeader (msg, eI2NPTunnelGateway); // gateway message
|
||||
return msg;
|
||||
}
|
||||
|
||||
void HandleTunnelGatewayMsg (I2NPMessage * msg)
|
||||
{
|
||||
TunnelGatewayHeader * header = (TunnelGatewayHeader *)msg->GetPayload ();
|
||||
uint32_t tunnelID = be32toh(header->tunnelID);
|
||||
uint16_t len = be16toh(header->length);
|
||||
const uint8_t * payload = msg->GetPayload ();
|
||||
uint32_t tunnelID = bufbe32toh(payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET);
|
||||
uint16_t len = bufbe16toh(payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET);
|
||||
// we make payload as new I2NP message to send
|
||||
msg->offset += sizeof (I2NPHeader) + sizeof (TunnelGatewayHeader);
|
||||
msg->offset += I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE;
|
||||
msg->len = msg->offset + len;
|
||||
LogPrint ("TunnelGateway of ", (int)len, " bytes for tunnel ", (unsigned int)tunnelID, ". Msg type ", (int)msg->GetHeader()->typeID);
|
||||
if (msg->GetHeader()->typeID == eI2NPDatabaseStore ||
|
||||
msg->GetHeader()->typeID == eI2NPDatabaseSearchReply)
|
||||
auto typeID = msg->GetTypeID ();
|
||||
LogPrint ("TunnelGateway of ", (int)len, " bytes for tunnel ", (unsigned int)tunnelID, ". Msg type ", (int)typeID);
|
||||
|
||||
if (typeID == eI2NPDatabaseStore || typeID == eI2NPDatabaseSearchReply)
|
||||
{
|
||||
// transit DatabaseStore my contain new/updated RI
|
||||
// or DatabaseSearchReply with new routers
|
||||
@@ -511,19 +497,18 @@ namespace i2p
|
||||
|
||||
size_t GetI2NPMessageLength (const uint8_t * msg)
|
||||
{
|
||||
I2NPHeader * header = (I2NPHeader *)msg;
|
||||
return be16toh (header->size) + sizeof (I2NPHeader);
|
||||
return bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET) + I2NP_HEADER_SIZE;
|
||||
}
|
||||
|
||||
void HandleI2NPMessage (uint8_t * msg, size_t len)
|
||||
{
|
||||
I2NPHeader * header = (I2NPHeader *)msg;
|
||||
uint32_t msgID = be32toh (header->msgID);
|
||||
LogPrint ("I2NP msg received len=", len,", type=", (int)header->typeID, ", msgID=", (unsigned int)msgID);
|
||||
uint8_t typeID = msg[I2NP_HEADER_TYPEID_OFFSET];
|
||||
uint32_t msgID = bufbe32toh (msg + I2NP_HEADER_MSGID_OFFSET);
|
||||
LogPrint ("I2NP msg received len=", len,", type=", (int)typeID, ", msgID=", (unsigned int)msgID);
|
||||
|
||||
uint8_t * buf = msg + sizeof (I2NPHeader);
|
||||
int size = be16toh (header->size);
|
||||
switch (header->typeID)
|
||||
uint8_t * buf = msg + I2NP_HEADER_SIZE;
|
||||
int size = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET);
|
||||
switch (typeID)
|
||||
{
|
||||
case eI2NPVariableTunnelBuild:
|
||||
LogPrint ("VariableTunnelBuild");
|
||||
@@ -542,7 +527,7 @@ namespace i2p
|
||||
// TODO:
|
||||
break;
|
||||
default:
|
||||
LogPrint ("Unexpected message ", (int)header->typeID);
|
||||
LogPrint ("Unexpected message ", (int)typeID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,7 +535,7 @@ namespace i2p
|
||||
{
|
||||
if (msg)
|
||||
{
|
||||
switch (msg->GetHeader ()->typeID)
|
||||
switch (msg->GetTypeID ())
|
||||
{
|
||||
case eI2NPTunnelData:
|
||||
LogPrint ("TunnelData");
|
||||
@@ -562,8 +547,16 @@ namespace i2p
|
||||
break;
|
||||
case eI2NPGarlic:
|
||||
LogPrint ("Garlic");
|
||||
if (msg->from && msg->from->GetTunnelPool ())
|
||||
msg->from->GetTunnelPool ()->GetGarlicDestination ().ProcessGarlicMessage (msg);
|
||||
if (msg->from)
|
||||
{
|
||||
if (msg->from->GetTunnelPool ())
|
||||
msg->from->GetTunnelPool ()->ProcessGarlicMessage (msg);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogInfo, "Local destination for garlic doesn't exist anymore");
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
}
|
||||
else
|
||||
i2p::context.ProcessGarlicMessage (msg);
|
||||
break;
|
||||
|
||||
211
I2NPProtocol.h
211
I2NPProtocol.h
@@ -3,80 +3,71 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <set>
|
||||
#include <cryptopp/sha.h>
|
||||
#include <string.h>
|
||||
#include "I2PEndian.h"
|
||||
#include "Identity.h"
|
||||
#include "RouterInfo.h"
|
||||
#include "LeaseSet.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
#pragma pack (1)
|
||||
{
|
||||
// I2NP header
|
||||
const size_t I2NP_HEADER_TYPEID_OFFSET = 0;
|
||||
const size_t I2NP_HEADER_MSGID_OFFSET = I2NP_HEADER_TYPEID_OFFSET + 1;
|
||||
const size_t I2NP_HEADER_EXPIRATION_OFFSET = I2NP_HEADER_MSGID_OFFSET + 4;
|
||||
const size_t I2NP_HEADER_SIZE_OFFSET = I2NP_HEADER_EXPIRATION_OFFSET + 8;
|
||||
const size_t I2NP_HEADER_CHKS_OFFSET = I2NP_HEADER_SIZE_OFFSET + 2;
|
||||
const size_t I2NP_HEADER_SIZE = I2NP_HEADER_CHKS_OFFSET + 1;
|
||||
|
||||
struct I2NPHeader
|
||||
{
|
||||
uint8_t typeID;
|
||||
uint32_t msgID;
|
||||
uint64_t expiration;
|
||||
uint16_t size;
|
||||
uint8_t chks;
|
||||
};
|
||||
|
||||
struct I2NPHeaderShort
|
||||
{
|
||||
uint8_t typeID;
|
||||
uint32_t shortExpiration;
|
||||
};
|
||||
|
||||
struct I2NPDatabaseStoreMsg
|
||||
{
|
||||
uint8_t key[32];
|
||||
uint8_t type;
|
||||
uint32_t replyToken;
|
||||
};
|
||||
|
||||
struct I2NPDeliveryStatusMsg
|
||||
{
|
||||
uint32_t msgID;
|
||||
uint64_t timestamp;
|
||||
};
|
||||
// I2NP short header
|
||||
const size_t I2NP_SHORT_HEADER_TYPEID_OFFSET = 0;
|
||||
const size_t I2NP_SHORT_HEADER_EXPIRATION_OFFSET = I2NP_SHORT_HEADER_TYPEID_OFFSET + 1;
|
||||
const size_t I2NP_SHORT_HEADER_SIZE = I2NP_SHORT_HEADER_EXPIRATION_OFFSET + 4;
|
||||
|
||||
struct I2NPBuildRequestRecordClearText
|
||||
{
|
||||
uint32_t receiveTunnel;
|
||||
uint8_t ourIdent[32];
|
||||
uint32_t nextTunnel;
|
||||
uint8_t nextIdent[32];
|
||||
uint8_t layerKey[32];
|
||||
uint8_t ivKey[32];
|
||||
uint8_t replyKey[32];
|
||||
uint8_t replyIV[16];
|
||||
uint8_t flag;
|
||||
uint32_t requestTime;
|
||||
uint32_t nextMessageID;
|
||||
uint8_t filler[29];
|
||||
};
|
||||
// Tunnel Gateway header
|
||||
const size_t TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET = 0;
|
||||
const size_t TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET = TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET + 4;
|
||||
const size_t TUNNEL_GATEWAY_HEADER_SIZE = TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET + 2;
|
||||
|
||||
struct I2NPBuildResponseRecord
|
||||
{
|
||||
uint8_t hash[32];
|
||||
uint8_t padding[495];
|
||||
uint8_t ret;
|
||||
};
|
||||
// DeliveryStatus
|
||||
const size_t DELIVERY_STATUS_MSGID_OFFSET = 0;
|
||||
const size_t DELIVERY_STATUS_TIMESTAMP_OFFSET = DELIVERY_STATUS_MSGID_OFFSET + 4;
|
||||
const size_t DELIVERY_STATUS_SIZE = DELIVERY_STATUS_TIMESTAMP_OFFSET + 8;
|
||||
|
||||
// DatabaseStore
|
||||
const size_t DATABASE_STORE_KEY_OFFSET = 0;
|
||||
const size_t DATABASE_STORE_TYPE_OFFSET = DATABASE_STORE_KEY_OFFSET + 32;
|
||||
const size_t DATABASE_STORE_REPLY_TOKEN_OFFSET = DATABASE_STORE_TYPE_OFFSET + 1;
|
||||
const size_t DATABASE_STORE_HEADER_SIZE = DATABASE_STORE_REPLY_TOKEN_OFFSET + 4;
|
||||
|
||||
// TunnelBuild
|
||||
const size_t TUNNEL_BUILD_RECORD_SIZE = 528;
|
||||
|
||||
//BuildRequestRecordClearText
|
||||
const size_t BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET = 0;
|
||||
const size_t BUILD_REQUEST_RECORD_OUR_IDENT_OFFSET = BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET + 4;
|
||||
const size_t BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET = BUILD_REQUEST_RECORD_OUR_IDENT_OFFSET + 32;
|
||||
const size_t BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET = BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET + 4;
|
||||
const size_t BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET = BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET + 32;
|
||||
const size_t BUILD_REQUEST_RECORD_IV_KEY_OFFSET = BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET + 32;
|
||||
const size_t BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET = BUILD_REQUEST_RECORD_IV_KEY_OFFSET + 32;
|
||||
const size_t BUILD_REQUEST_RECORD_REPLY_IV_OFFSET = BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET + 32;
|
||||
const size_t BUILD_REQUEST_RECORD_FLAG_OFFSET = BUILD_REQUEST_RECORD_REPLY_IV_OFFSET + 16;
|
||||
const size_t BUILD_REQUEST_RECORD_REQUEST_TIME_OFFSET = BUILD_REQUEST_RECORD_FLAG_OFFSET + 1;
|
||||
const size_t BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET = BUILD_REQUEST_RECORD_REQUEST_TIME_OFFSET + 4;
|
||||
const size_t BUILD_REQUEST_RECORD_PADDING_OFFSET = BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET + 4;
|
||||
const size_t BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE = 222;
|
||||
|
||||
struct I2NPBuildRequestRecordElGamalEncrypted
|
||||
{
|
||||
uint8_t toPeer[16];
|
||||
uint8_t encrypted[512];
|
||||
};
|
||||
|
||||
struct TunnelGatewayHeader
|
||||
{
|
||||
uint32_t tunnelID;
|
||||
uint16_t length;
|
||||
};
|
||||
|
||||
// BuildRequestRecordEncrypted
|
||||
const size_t BUILD_REQUEST_RECORD_TO_PEER_OFFSET = 0;
|
||||
const size_t BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET = BUILD_REQUEST_RECORD_TO_PEER_OFFSET + 16;
|
||||
|
||||
#pragma pack ()
|
||||
// BuildResponseRecord
|
||||
const size_t BUILD_RESPONSE_RECORD_HASH_OFFSET = 0;
|
||||
const size_t BUILD_RESPONSE_RECORD_PADDING_OFFSET = 32;
|
||||
const size_t BUILD_RESPONSE_RECORD_PADDING_SIZE = 495;
|
||||
const size_t BUILD_RESPONSE_RECORD_RET_OFFSET = BUILD_RESPONSE_RECORD_PADDING_OFFSET + BUILD_RESPONSE_RECORD_PADDING_SIZE;
|
||||
|
||||
enum I2NPMessageType
|
||||
{
|
||||
@@ -110,14 +101,45 @@ namespace tunnel
|
||||
size_t len, offset, maxLen;
|
||||
i2p::tunnel::InboundTunnel * from;
|
||||
|
||||
I2NPMessage (): buf (nullptr),len (sizeof (I2NPHeader) + 2),
|
||||
offset(2), maxLen (0), from (nullptr) {};
|
||||
// reserve 2 bytes for NTCP header
|
||||
I2NPHeader * GetHeader () { return (I2NPHeader *)GetBuffer (); };
|
||||
uint8_t * GetPayload () { return GetBuffer () + sizeof(I2NPHeader); };
|
||||
I2NPMessage (): buf (nullptr),len (I2NP_HEADER_SIZE + 2),
|
||||
offset(2), maxLen (0), from (nullptr) {}; // reserve 2 bytes for NTCP header
|
||||
|
||||
// header accessors
|
||||
uint8_t * GetHeader () { return GetBuffer (); };
|
||||
const uint8_t * GetHeader () const { return GetBuffer (); };
|
||||
void SetTypeID (uint8_t typeID) { GetHeader ()[I2NP_HEADER_TYPEID_OFFSET] = typeID; };
|
||||
uint8_t GetTypeID () const { return GetHeader ()[I2NP_HEADER_TYPEID_OFFSET]; };
|
||||
void SetMsgID (uint32_t msgID) { htobe32buf (GetHeader () + I2NP_HEADER_MSGID_OFFSET, msgID); };
|
||||
uint32_t GetMsgID () const { return bufbe32toh (GetHeader () + I2NP_HEADER_MSGID_OFFSET); };
|
||||
void SetExpiration (uint64_t expiration) { htobe64buf (GetHeader () + I2NP_HEADER_EXPIRATION_OFFSET, expiration); };
|
||||
uint64_t GetExpiration () const { return bufbe64toh (GetHeader () + I2NP_HEADER_EXPIRATION_OFFSET); };
|
||||
void SetSize (uint16_t size) { htobe16buf (GetHeader () + I2NP_HEADER_SIZE_OFFSET, size); };
|
||||
uint16_t GetSize () const { return bufbe16toh (GetHeader () + I2NP_HEADER_SIZE_OFFSET); };
|
||||
void UpdateSize () { SetSize (GetPayloadLength ()); };
|
||||
void SetChks (uint8_t chks) { GetHeader ()[I2NP_HEADER_CHKS_OFFSET] = chks; };
|
||||
void UpdateChks ()
|
||||
{
|
||||
uint8_t hash[32];
|
||||
CryptoPP::SHA256().CalculateDigest(hash, GetPayload (), GetPayloadLength ());
|
||||
GetHeader ()[I2NP_HEADER_CHKS_OFFSET] = hash[0];
|
||||
}
|
||||
|
||||
// payload
|
||||
uint8_t * GetPayload () { return GetBuffer () + I2NP_HEADER_SIZE; };
|
||||
uint8_t * GetBuffer () { return buf + offset; };
|
||||
const uint8_t * GetBuffer () const { return buf + offset; };
|
||||
size_t GetLength () const { return len - offset; };
|
||||
size_t GetLength () const { return len - offset; };
|
||||
size_t GetPayloadLength () const { return GetLength () - I2NP_HEADER_SIZE; };
|
||||
|
||||
void Align (size_t alignment)
|
||||
{
|
||||
size_t rem = ((size_t)GetBuffer ()) % alignment;
|
||||
if (rem)
|
||||
{
|
||||
offset += (alignment - rem);
|
||||
len += (alignment - rem);
|
||||
}
|
||||
}
|
||||
|
||||
I2NPMessage& operator=(const I2NPMessage& other)
|
||||
{
|
||||
@@ -128,25 +150,25 @@ namespace tunnel
|
||||
}
|
||||
|
||||
// for SSU only
|
||||
uint8_t * GetSSUHeader () { return buf + offset + sizeof(I2NPHeader) - sizeof(I2NPHeaderShort); };
|
||||
uint8_t * GetSSUHeader () { return buf + offset + I2NP_HEADER_SIZE - I2NP_SHORT_HEADER_SIZE; };
|
||||
void FromSSU (uint32_t msgID) // we have received SSU message and convert it to regular
|
||||
{
|
||||
I2NPHeaderShort ssu = *(I2NPHeaderShort *)GetSSUHeader ();
|
||||
I2NPHeader * header = GetHeader ();
|
||||
header->typeID = ssu.typeID;
|
||||
header->msgID = htobe32 (msgID);
|
||||
header->expiration = htobe64 (be32toh (ssu.shortExpiration)*1000LL);
|
||||
header->size = htobe16 (len - offset - sizeof (I2NPHeader));
|
||||
header->chks = 0;
|
||||
const uint8_t * ssu = GetSSUHeader ();
|
||||
GetHeader ()[I2NP_HEADER_TYPEID_OFFSET] = ssu[I2NP_SHORT_HEADER_TYPEID_OFFSET]; // typeid
|
||||
SetMsgID (msgID);
|
||||
SetExpiration (bufbe32toh (ssu + I2NP_SHORT_HEADER_EXPIRATION_OFFSET)*1000LL);
|
||||
SetSize (len - offset - I2NP_HEADER_SIZE);
|
||||
SetChks (0);
|
||||
}
|
||||
uint32_t ToSSU () // return msgID
|
||||
{
|
||||
I2NPHeader header = *GetHeader ();
|
||||
I2NPHeaderShort * ssu = (I2NPHeaderShort *)GetSSUHeader ();
|
||||
ssu->typeID = header.typeID;
|
||||
ssu->shortExpiration = htobe32 (be64toh (header.expiration)/1000LL);
|
||||
len = offset + sizeof (I2NPHeaderShort) + be16toh (header.size);
|
||||
return be32toh (header.msgID);
|
||||
uint8_t header[I2NP_HEADER_SIZE];
|
||||
memcpy (header, GetHeader (), I2NP_HEADER_SIZE);
|
||||
uint8_t * ssu = GetSSUHeader ();
|
||||
ssu[I2NP_SHORT_HEADER_TYPEID_OFFSET] = header[I2NP_HEADER_TYPEID_OFFSET]; // typeid
|
||||
htobe32buf (ssu + I2NP_SHORT_HEADER_EXPIRATION_OFFSET, bufbe64toh (header + I2NP_HEADER_EXPIRATION_OFFSET)/1000LL);
|
||||
len = offset + I2NP_SHORT_HEADER_SIZE + bufbe16toh (header + I2NP_HEADER_SIZE_OFFSET);
|
||||
return bufbe32toh (header + I2NP_HEADER_MSGID_OFFSET);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -167,26 +189,17 @@ namespace tunnel
|
||||
I2NPMessage * CreateI2NPMessage (const uint8_t * buf, int len, i2p::tunnel::InboundTunnel * from = nullptr);
|
||||
|
||||
I2NPMessage * CreateDeliveryStatusMsg (uint32_t msgID);
|
||||
I2NPMessage * CreateDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
|
||||
uint32_t replyTunnelID, bool exploratory = false,
|
||||
std::set<i2p::data::IdentHash> * excludedPeers = nullptr, bool encryption = false,
|
||||
i2p::tunnel::TunnelPool * pool = nullptr);
|
||||
I2NPMessage * CreateRouterInfoDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
|
||||
uint32_t replyTunnelID, bool exploratory = false, std::set<i2p::data::IdentHash> * excludedPeers = nullptr);
|
||||
I2NPMessage * CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest,
|
||||
const std::set<i2p::data::IdentHash>& excludedFloodfills,
|
||||
const i2p::tunnel::InboundTunnel * replyTunnel, const uint8_t * replyKey, const uint8_t * replyTag);
|
||||
I2NPMessage * CreateDatabaseSearchReply (const i2p::data::IdentHash& ident, const i2p::data::RouterInfo * floodfill);
|
||||
|
||||
I2NPMessage * CreateDatabaseStoreMsg (const i2p::data::RouterInfo * router = nullptr);
|
||||
I2NPMessage * CreateDatabaseStoreMsg (const i2p::data::LeaseSet * leaseSet, uint32_t replyToken = 0);
|
||||
|
||||
I2NPBuildRequestRecordClearText CreateBuildRequestRecord (
|
||||
const uint8_t * ourIdent, uint32_t receiveTunnelID,
|
||||
const uint8_t * nextIdent, uint32_t nextTunnelID,
|
||||
const uint8_t * layerKey,const uint8_t * ivKey,
|
||||
const uint8_t * replyKey, const uint8_t * replyIV, uint32_t nextMessageID,
|
||||
bool isGateway, bool isEndpoint);
|
||||
void EncryptBuildRequestRecord (const i2p::data::RouterInfo& router,
|
||||
const I2NPBuildRequestRecordClearText& clearText,
|
||||
I2NPBuildRequestRecordElGamalEncrypted& record);
|
||||
|
||||
bool HandleBuildRequestRecords (int num, I2NPBuildRequestRecordElGamalEncrypted * records, I2NPBuildRequestRecordClearText& clearText);
|
||||
|
||||
bool HandleBuildRequestRecords (int num, uint8_t * records, uint8_t * clearText);
|
||||
void HandleVariableTunnelBuildMsg (uint32_t replyMsgID, uint8_t * buf, size_t len);
|
||||
void HandleVariableTunnelBuildReplyMsg (uint32_t replyMsgID, uint8_t * buf, size_t len);
|
||||
void HandleTunnelBuildMsg (uint8_t * buf, size_t len);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
#include "LittleBigEndian.h"
|
||||
|
||||
#ifdef NEEDS_LOCAL_ENDIAN
|
||||
uint16_t htobe16(uint16_t int16)
|
||||
{
|
||||
BigEndian<uint16_t> u16(int16);
|
||||
@@ -40,6 +41,7 @@ uint64_t be64toh(uint64_t big64)
|
||||
LittleEndian<uint64_t> u64(big64);
|
||||
return u64.raw_value;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* it can be used in Windows 8
|
||||
#include <Winsock2.h>
|
||||
|
||||
71
I2PEndian.h
71
I2PEndian.h
@@ -1,5 +1,7 @@
|
||||
#ifndef I2PENDIAN_H__
|
||||
#define I2PENDIAN_H__
|
||||
#include <inttypes.h>
|
||||
#include <string.h>
|
||||
|
||||
#if defined(__linux__) || defined(__FreeBSD_kernel__)
|
||||
#include <endian.h>
|
||||
@@ -25,6 +27,7 @@
|
||||
#define le64toh(x) OSSwapLittleToHostInt64(x)
|
||||
|
||||
#else
|
||||
#define NEEDS_LOCAL_ENDIAN
|
||||
#include <cstdint>
|
||||
uint16_t htobe16(uint16_t int16);
|
||||
uint32_t htobe32(uint32_t int32);
|
||||
@@ -44,5 +47,73 @@ uint64_t be64toh(uint64_t big64);
|
||||
|
||||
#endif
|
||||
|
||||
inline uint16_t buf16toh(const void *buf)
|
||||
{
|
||||
uint16_t b16;
|
||||
memcpy(&b16, buf, sizeof(uint16_t));
|
||||
return b16;
|
||||
}
|
||||
|
||||
inline uint32_t buf32toh(const void *buf)
|
||||
{
|
||||
uint32_t b32;
|
||||
memcpy(&b32, buf, sizeof(uint32_t));
|
||||
return b32;
|
||||
}
|
||||
|
||||
inline uint64_t buf64toh(const void *buf)
|
||||
{
|
||||
uint64_t b64;
|
||||
memcpy(&b64, buf, sizeof(uint64_t));
|
||||
return b64;
|
||||
}
|
||||
|
||||
inline uint16_t bufbe16toh(const void *buf)
|
||||
{
|
||||
return be16toh(buf16toh(buf));
|
||||
}
|
||||
|
||||
inline uint32_t bufbe32toh(const void *buf)
|
||||
{
|
||||
return be32toh(buf32toh(buf));
|
||||
}
|
||||
|
||||
inline uint64_t bufbe64toh(const void *buf)
|
||||
{
|
||||
return be64toh(buf64toh(buf));
|
||||
}
|
||||
|
||||
inline void htobuf16(void *buf, uint16_t b16)
|
||||
{
|
||||
memcpy(buf, &b16, sizeof(uint16_t));
|
||||
}
|
||||
|
||||
inline void htobuf32(void *buf, uint32_t b32)
|
||||
{
|
||||
memcpy(buf, &b32, sizeof(uint32_t));
|
||||
}
|
||||
|
||||
inline void htobuf64(void *buf, uint64_t b64)
|
||||
{
|
||||
memcpy(buf, &b64, sizeof(uint64_t));
|
||||
}
|
||||
|
||||
inline void htobe16buf(void *buf, uint16_t big16)
|
||||
{
|
||||
htobuf16(buf, htobe16(big16));
|
||||
}
|
||||
|
||||
inline void htobe32buf(void *buf, uint32_t big32)
|
||||
{
|
||||
htobuf32(buf, htobe32(big32));
|
||||
}
|
||||
|
||||
inline void htobe64buf(void *buf, uint64_t big64)
|
||||
{
|
||||
htobuf64(buf, htobe64(big64));
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif // I2PENDIAN_H__
|
||||
|
||||
|
||||
199
I2PTunnel.cpp
199
I2PTunnel.cpp
@@ -1,7 +1,5 @@
|
||||
#include <boost/bind.hpp>
|
||||
#include "base64.h"
|
||||
#include "Log.h"
|
||||
#include "NetDb.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PTunnel.h"
|
||||
@@ -12,21 +10,23 @@ namespace client
|
||||
{
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner,
|
||||
boost::asio::ip::tcp::socket * socket, const i2p::data::LeaseSet * leaseSet):
|
||||
m_Socket (socket), m_Owner (owner)
|
||||
m_Socket (socket), m_Owner (owner), m_RemoteEndpoint (socket->remote_endpoint ()),
|
||||
m_IsQuiet (true)
|
||||
{
|
||||
m_Stream = m_Owner->GetLocalDestination ()->CreateStream (*leaseSet);
|
||||
m_Stream->Send (m_Buffer, 0); // connect
|
||||
StreamReceive ();
|
||||
Receive ();
|
||||
}
|
||||
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner, i2p::stream::Stream * stream,
|
||||
boost::asio::ip::tcp::socket * socket, const boost::asio::ip::tcp::endpoint& target):
|
||||
m_Socket (socket), m_Stream (stream), m_Owner (owner)
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner,
|
||||
boost::asio::ip::tcp::socket * socket, std::shared_ptr<i2p::stream::Stream> stream):
|
||||
m_Socket (socket), m_Stream (stream), m_Owner (owner),
|
||||
m_RemoteEndpoint (socket->remote_endpoint ()), m_IsQuiet (true)
|
||||
{
|
||||
}
|
||||
|
||||
I2PTunnelConnection::I2PTunnelConnection (I2PTunnel * owner, std::shared_ptr<i2p::stream::Stream> stream,
|
||||
boost::asio::ip::tcp::socket * socket, const boost::asio::ip::tcp::endpoint& target, bool quiet):
|
||||
m_Socket (socket), m_Stream (stream), m_Owner (owner), m_RemoteEndpoint (target), m_IsQuiet (quiet)
|
||||
{
|
||||
if (m_Socket)
|
||||
m_Socket->async_connect (target, boost::bind (&I2PTunnelConnection::HandleConnect,
|
||||
this, boost::asio::placeholders::error));
|
||||
}
|
||||
|
||||
I2PTunnelConnection::~I2PTunnelConnection ()
|
||||
@@ -34,31 +34,46 @@ namespace client
|
||||
delete m_Socket;
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::I2PConnect (const uint8_t * msg, size_t len)
|
||||
{
|
||||
if (msg)
|
||||
m_Stream->Send (msg, len); // connect and send
|
||||
else
|
||||
m_Stream->Send (m_Buffer, 0); // connect
|
||||
StreamReceive ();
|
||||
Receive ();
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Connect ()
|
||||
{
|
||||
if (m_Socket)
|
||||
m_Socket->async_connect (m_RemoteEndpoint, std::bind (&I2PTunnelConnection::HandleConnect,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Terminate ()
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
m_Stream->Close ();
|
||||
i2p::stream::DeleteStream (m_Stream);
|
||||
m_Stream = nullptr;
|
||||
m_Stream.reset ();
|
||||
}
|
||||
m_Socket->close ();
|
||||
if (m_Owner)
|
||||
m_Owner->RemoveConnection (this);
|
||||
//delete this;
|
||||
m_Owner->RemoveConnection (shared_from_this ());
|
||||
}
|
||||
|
||||
void I2PTunnelConnection::Receive ()
|
||||
{
|
||||
m_Socket->async_read_some (boost::asio::buffer(m_Buffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
|
||||
boost::bind(&I2PTunnelConnection::HandleReceived, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
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)
|
||||
{
|
||||
{
|
||||
LogPrint ("I2PTunnel read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
@@ -87,8 +102,8 @@ namespace client
|
||||
{
|
||||
if (m_Stream)
|
||||
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, I2P_TUNNEL_CONNECTION_BUFFER_SIZE),
|
||||
boost::bind (&I2PTunnelConnection::HandleStreamReceive, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred),
|
||||
std::bind (&I2PTunnelConnection::HandleStreamReceive, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2),
|
||||
I2P_TUNNEL_CONNECTION_MAX_IDLE);
|
||||
}
|
||||
|
||||
@@ -103,7 +118,7 @@ namespace client
|
||||
else
|
||||
{
|
||||
boost::asio::async_write (*m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
|
||||
boost::bind (&I2PTunnelConnection::HandleWrite, this, boost::asio::placeholders::error));
|
||||
std::bind (&I2PTunnelConnection::HandleWrite, shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,45 +127,49 @@ namespace client
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("I2PTunnel connect error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
if (m_Stream) m_Stream->Close ();
|
||||
i2p::stream::DeleteStream (m_Stream);
|
||||
m_Stream = nullptr;
|
||||
}
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("I2PTunnel connected");
|
||||
StreamReceive ();
|
||||
if (m_IsQuiet)
|
||||
StreamReceive ();
|
||||
else
|
||||
{
|
||||
// send destination first like received from I2P
|
||||
std::string dest = m_Stream->GetRemoteIdentity ().ToBase64 ();
|
||||
dest += "\n";
|
||||
memcpy (m_StreamBuffer, dest.c_str (), dest.size ());
|
||||
HandleStreamReceive (boost::system::error_code (), dest.size ());
|
||||
}
|
||||
Receive ();
|
||||
}
|
||||
}
|
||||
|
||||
void I2PTunnel::AddConnection (I2PTunnelConnection * conn)
|
||||
I2PTunnel::I2PTunnel (ClientDestination * localDestination) :
|
||||
m_LocalDestination (localDestination ? localDestination :
|
||||
i2p::client::context.CreateNewLocalDestination (false, I2P_TUNNEL_DEFAULT_KEY_TYPE))
|
||||
{
|
||||
}
|
||||
void I2PTunnel::AddConnection (std::shared_ptr<I2PTunnelConnection> conn)
|
||||
{
|
||||
m_Connections.insert (conn);
|
||||
}
|
||||
|
||||
void I2PTunnel::RemoveConnection (I2PTunnelConnection * conn)
|
||||
void I2PTunnel::RemoveConnection (std::shared_ptr<I2PTunnelConnection> conn)
|
||||
{
|
||||
m_Connections.erase (conn);
|
||||
}
|
||||
|
||||
void I2PTunnel::ClearConnections ()
|
||||
{
|
||||
for (auto it: m_Connections)
|
||||
delete it;
|
||||
m_Connections.clear ();
|
||||
}
|
||||
|
||||
I2PClientTunnel::I2PClientTunnel (boost::asio::io_service& service, const std::string& destination,
|
||||
int port, ClientDestination * localDestination):
|
||||
I2PTunnel (service, localDestination ? localDestination :
|
||||
i2p::client::context.CreateNewLocalDestination (false, i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256)),
|
||||
m_Acceptor (service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
|
||||
m_Timer (service), m_Destination (destination), m_DestinationIdentHash (nullptr),
|
||||
m_RemoteLeaseSet (nullptr)
|
||||
I2PClientTunnel::I2PClientTunnel (const std::string& destination, int port, ClientDestination * localDestination):
|
||||
I2PTunnel (localDestination),
|
||||
m_Acceptor (GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
|
||||
m_Timer (GetService ()), m_Destination (destination), m_DestinationIdentHash (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -161,11 +180,7 @@ namespace client
|
||||
|
||||
void I2PClientTunnel::Start ()
|
||||
{
|
||||
i2p::data::IdentHash identHash;
|
||||
if (i2p::client::context.GetAddressBook ().GetIdentHash (m_Destination, identHash))
|
||||
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
|
||||
if (!m_DestinationIdentHash)
|
||||
LogPrint ("I2PTunnel unknown destination ", m_Destination);
|
||||
GetIdentHash();
|
||||
m_Acceptor.listen ();
|
||||
Accept ();
|
||||
}
|
||||
@@ -175,84 +190,74 @@ namespace client
|
||||
m_Acceptor.close();
|
||||
m_Timer.cancel ();
|
||||
ClearConnections ();
|
||||
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,"Remote destination ", m_Destination, " not found");
|
||||
}
|
||||
return m_DestinationIdentHash;
|
||||
}
|
||||
|
||||
|
||||
void I2PClientTunnel::Accept ()
|
||||
{
|
||||
auto newSocket = new boost::asio::ip::tcp::socket (GetService ());
|
||||
m_Acceptor.async_accept (*newSocket, boost::bind (&I2PClientTunnel::HandleAccept, this,
|
||||
boost::asio::placeholders::error, newSocket));
|
||||
m_Acceptor.async_accept (*newSocket, std::bind (&I2PClientTunnel::HandleAccept, this,
|
||||
std::placeholders::_1, newSocket));
|
||||
}
|
||||
|
||||
void I2PClientTunnel::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
if (!m_DestinationIdentHash)
|
||||
{
|
||||
i2p::data::IdentHash identHash;
|
||||
if (i2p::client::context.GetAddressBook ().GetIdentHash (m_Destination, identHash))
|
||||
m_DestinationIdentHash = new i2p::data::IdentHash (identHash);
|
||||
}
|
||||
if (m_DestinationIdentHash)
|
||||
{
|
||||
// try to get a LeaseSet
|
||||
m_RemoteLeaseSet = GetLocalDestination ()->FindLeaseSet (*m_DestinationIdentHash);
|
||||
if (m_RemoteLeaseSet && m_RemoteLeaseSet->HasNonExpiredLeases ())
|
||||
CreateConnection (socket);
|
||||
else
|
||||
{
|
||||
i2p::data::netdb.RequestDestination (*m_DestinationIdentHash, true, GetLocalDestination ()->GetTunnelPool ());
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds (I2P_TUNNEL_DESTINATION_REQUEST_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&I2PClientTunnel::HandleDestinationRequestTimer,
|
||||
this, boost::asio::placeholders::error, socket));
|
||||
}
|
||||
}
|
||||
const i2p::data::IdentHash *identHash = GetIdentHash();
|
||||
if (identHash)
|
||||
GetLocalDestination ()->CreateStream (
|
||||
std::bind (&I2PClientTunnel::HandleStreamRequestComplete,
|
||||
this, std::placeholders::_1, socket), *identHash);
|
||||
else
|
||||
{
|
||||
LogPrint ("Remote destination ", m_Destination, " not found");
|
||||
LogPrint (eLogError,"Closing socket");
|
||||
delete socket;
|
||||
}
|
||||
|
||||
}
|
||||
Accept ();
|
||||
}
|
||||
else
|
||||
delete socket;
|
||||
}
|
||||
|
||||
void I2PClientTunnel::HandleDestinationRequestTimer (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
if (m_DestinationIdentHash)
|
||||
{
|
||||
m_RemoteLeaseSet = GetLocalDestination ()->FindLeaseSet (*m_DestinationIdentHash);
|
||||
CreateConnection (socket);
|
||||
return;
|
||||
}
|
||||
LogPrint (eLogError,"Closing socket on accept because: ", ecode.message ());
|
||||
delete socket;
|
||||
}
|
||||
delete socket;
|
||||
}
|
||||
|
||||
void I2PClientTunnel::CreateConnection (boost::asio::ip::tcp::socket * socket)
|
||||
void I2PClientTunnel::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream, boost::asio::ip::tcp::socket * socket)
|
||||
{
|
||||
if (m_RemoteLeaseSet) // leaseSet found
|
||||
{
|
||||
LogPrint ("New I2PTunnel connection");
|
||||
auto connection = new I2PTunnelConnection (this, socket, m_RemoteLeaseSet);
|
||||
if (stream)
|
||||
{
|
||||
LogPrint (eLogInfo,"New I2PTunnel connection");
|
||||
auto connection = std::make_shared<I2PTunnelConnection>(this, socket, stream);
|
||||
AddConnection (connection);
|
||||
connection->I2PConnect ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("LeaseSet for I2PTunnel destination not found");
|
||||
LogPrint (eLogError,"Issue when creating the stream, check the previous warnings for more info.");
|
||||
delete socket;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
I2PServerTunnel::I2PServerTunnel (boost::asio::io_service& service, const std::string& address, int port,
|
||||
ClientDestination * localDestination): I2PTunnel (service, localDestination),
|
||||
m_Endpoint (boost::asio::ip::address::from_string (address), port)
|
||||
I2PServerTunnel::I2PServerTunnel (const std::string& address, int port, ClientDestination * localDestination):
|
||||
I2PTunnel (localDestination), m_Endpoint (boost::asio::ip::address::from_string (address), port)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -275,10 +280,14 @@ namespace client
|
||||
LogPrint ("Local destination not set for server tunnel");
|
||||
}
|
||||
|
||||
void I2PServerTunnel::HandleAccept (i2p::stream::Stream * stream)
|
||||
void I2PServerTunnel::HandleAccept (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
new I2PTunnelConnection (this, stream, new boost::asio::ip::tcp::socket (GetService ()), m_Endpoint);
|
||||
{
|
||||
auto conn = std::make_shared<I2PTunnelConnection> (this, stream, new boost::asio::ip::tcp::socket (GetService ()), m_Endpoint);
|
||||
AddConnection (conn);
|
||||
conn->Connect ();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
44
I2PTunnel.h
44
I2PTunnel.h
@@ -4,6 +4,7 @@
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
#include "Destination.h"
|
||||
@@ -16,18 +17,24 @@ namespace client
|
||||
const size_t I2P_TUNNEL_CONNECTION_BUFFER_SIZE = 8192;
|
||||
const int I2P_TUNNEL_CONNECTION_MAX_IDLE = 3600; // in seconds
|
||||
const int I2P_TUNNEL_DESTINATION_REQUEST_TIMEOUT = 10; // in seconds
|
||||
const i2p::data::SigningKeyType I2P_TUNNEL_DEFAULT_KEY_TYPE = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256;
|
||||
|
||||
class I2PTunnel;
|
||||
class I2PTunnelConnection
|
||||
class I2PTunnelConnection: public std::enable_shared_from_this<I2PTunnelConnection>
|
||||
{
|
||||
public:
|
||||
|
||||
I2PTunnelConnection (I2PTunnel * owner, boost::asio::ip::tcp::socket * socket,
|
||||
const i2p::data::LeaseSet * leaseSet);
|
||||
I2PTunnelConnection (I2PTunnel * owner, i2p::stream::Stream * stream, boost::asio::ip::tcp::socket * socket,
|
||||
const boost::asio::ip::tcp::endpoint& target);
|
||||
const i2p::data::LeaseSet * leaseSet); // to I2P
|
||||
I2PTunnelConnection (I2PTunnel * owner, boost::asio::ip::tcp::socket * socket,
|
||||
std::shared_ptr<i2p::stream::Stream> stream); // to I2P using simplified API :)
|
||||
I2PTunnelConnection (I2PTunnel * owner, std::shared_ptr<i2p::stream::Stream> stream, 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 ();
|
||||
|
||||
private:
|
||||
|
||||
void Terminate ();
|
||||
@@ -44,39 +51,38 @@ namespace client
|
||||
|
||||
uint8_t m_Buffer[I2P_TUNNEL_CONNECTION_BUFFER_SIZE], m_StreamBuffer[I2P_TUNNEL_CONNECTION_BUFFER_SIZE];
|
||||
boost::asio::ip::tcp::socket * m_Socket;
|
||||
i2p::stream::Stream * m_Stream;
|
||||
std::shared_ptr<i2p::stream::Stream> m_Stream;
|
||||
I2PTunnel * m_Owner;
|
||||
boost::asio::ip::tcp::endpoint m_RemoteEndpoint;
|
||||
bool m_IsQuiet; // don't send destination
|
||||
};
|
||||
|
||||
class I2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
I2PTunnel (boost::asio::io_service& service, ClientDestination * localDestination):
|
||||
m_Service (service), m_LocalDestination (localDestination) {};
|
||||
I2PTunnel (ClientDestination * localDestination = nullptr);
|
||||
virtual ~I2PTunnel () { ClearConnections (); };
|
||||
|
||||
void AddConnection (I2PTunnelConnection * conn);
|
||||
void RemoveConnection (I2PTunnelConnection * conn);
|
||||
void AddConnection (std::shared_ptr<I2PTunnelConnection> conn);
|
||||
void RemoveConnection (std::shared_ptr<I2PTunnelConnection> conn);
|
||||
void ClearConnections ();
|
||||
ClientDestination * GetLocalDestination () { return m_LocalDestination; };
|
||||
void SetLocalDestination (ClientDestination * dest) { m_LocalDestination = dest; };
|
||||
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
boost::asio::io_service& GetService () { return m_LocalDestination->GetService (); };
|
||||
|
||||
private:
|
||||
|
||||
boost::asio::io_service& m_Service;
|
||||
ClientDestination * m_LocalDestination;
|
||||
std::set<I2PTunnelConnection *> m_Connections;
|
||||
std::set<std::shared_ptr<I2PTunnelConnection> > m_Connections;
|
||||
};
|
||||
|
||||
class I2PClientTunnel: public I2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
I2PClientTunnel (boost::asio::io_service& service, const std::string& destination, int port,
|
||||
ClientDestination * localDestination = nullptr);
|
||||
I2PClientTunnel (const std::string& destination, int port, ClientDestination * localDestination = nullptr);
|
||||
~I2PClientTunnel ();
|
||||
|
||||
void Start ();
|
||||
@@ -84,10 +90,10 @@ namespace client
|
||||
|
||||
private:
|
||||
|
||||
const i2p::data::IdentHash * GetIdentHash ();
|
||||
void Accept ();
|
||||
void HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket);
|
||||
void HandleDestinationRequestTimer (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket);
|
||||
void CreateConnection (boost::asio::ip::tcp::socket * socket);
|
||||
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream, boost::asio::ip::tcp::socket * socket);
|
||||
|
||||
private:
|
||||
|
||||
@@ -95,15 +101,13 @@ namespace client
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
std::string m_Destination;
|
||||
const i2p::data::IdentHash * m_DestinationIdentHash;
|
||||
const i2p::data::LeaseSet * m_RemoteLeaseSet;
|
||||
};
|
||||
|
||||
class I2PServerTunnel: public I2PTunnel
|
||||
{
|
||||
public:
|
||||
|
||||
I2PServerTunnel (boost::asio::io_service& service, const std::string& address, int port,
|
||||
ClientDestination * localDestination);
|
||||
I2PServerTunnel (const std::string& address, int port, ClientDestination * localDestination);
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
@@ -111,7 +115,7 @@ namespace client
|
||||
private:
|
||||
|
||||
void Accept ();
|
||||
void HandleAccept (i2p::stream::Stream * stream);
|
||||
void HandleAccept (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
private:
|
||||
|
||||
|
||||
283
Identity.cpp
283
Identity.cpp
@@ -5,6 +5,7 @@
|
||||
#include <cryptopp/dsa.h>
|
||||
#include "base64.h"
|
||||
#include "CryptoConst.h"
|
||||
#include "ElGamal.h"
|
||||
#include "RouterContext.h"
|
||||
#include "Identity.h"
|
||||
#include "I2PEndian.h"
|
||||
@@ -42,18 +43,77 @@ namespace data
|
||||
IdentityEx::IdentityEx(const uint8_t * publicKey, const uint8_t * signingKey, SigningKeyType type)
|
||||
{
|
||||
memcpy (m_StandardIdentity.publicKey, publicKey, sizeof (m_StandardIdentity.publicKey));
|
||||
if (type == SIGNING_KEY_TYPE_ECDSA_SHA256_P256)
|
||||
if (type != SIGNING_KEY_TYPE_DSA_SHA1)
|
||||
{
|
||||
memcpy (m_StandardIdentity.signingKey + 64, signingKey, 64);
|
||||
size_t excessLen = 0;
|
||||
uint8_t * excessBuf = nullptr;
|
||||
switch (type)
|
||||
{
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
|
||||
{
|
||||
size_t padding = 128 - i2p::crypto::ECDSAP256_KEY_LENGTH; // 64 = 128 - 64
|
||||
memcpy (m_StandardIdentity.signingKey + padding, signingKey, i2p::crypto::ECDSAP256_KEY_LENGTH);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
|
||||
{
|
||||
size_t padding = 128 - i2p::crypto::ECDSAP384_KEY_LENGTH; // 32 = 128 - 96
|
||||
memcpy (m_StandardIdentity.signingKey + padding, signingKey, i2p::crypto::ECDSAP384_KEY_LENGTH);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
|
||||
{
|
||||
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
|
||||
excessLen = i2p::crypto::ECDSAP521_KEY_LENGTH - 128; // 4 = 132 - 128
|
||||
excessBuf = new uint8_t[excessLen];
|
||||
memcpy (excessBuf, signingKey + 128, excessLen);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
|
||||
{
|
||||
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
|
||||
excessLen = i2p::crypto::RSASHA2562048_KEY_LENGTH - 128; // 128 = 256 - 128
|
||||
excessBuf = new uint8_t[excessLen];
|
||||
memcpy (excessBuf, signingKey + 128, excessLen);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
|
||||
{
|
||||
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
|
||||
excessLen = i2p::crypto::RSASHA3843072_KEY_LENGTH - 128; // 256 = 384 - 128
|
||||
excessBuf = new uint8_t[excessLen];
|
||||
memcpy (excessBuf, signingKey + 128, excessLen);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
|
||||
{
|
||||
memcpy (m_StandardIdentity.signingKey, signingKey, 128);
|
||||
excessLen = i2p::crypto::RSASHA5124096_KEY_LENGTH - 128; // 384 = 512 - 128
|
||||
excessBuf = new uint8_t[excessLen];
|
||||
memcpy (excessBuf, signingKey + 128, excessLen);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LogPrint ("Signing key type ", (int)type, " is not supported");
|
||||
}
|
||||
m_ExtendedLen = 4 + excessLen; // 4 bytes extra + excess length
|
||||
// fill certificate
|
||||
m_StandardIdentity.certificate.type = CERTIFICATE_TYPE_KEY;
|
||||
m_ExtendedLen = 4; // 4 bytes extra
|
||||
m_StandardIdentity.certificate.length = htobe16 (4);
|
||||
m_StandardIdentity.certificate.length = htobe16 (m_ExtendedLen);
|
||||
// fill extended buffer
|
||||
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
|
||||
*(uint16_t *)m_ExtendedBuffer = htobe16 (SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
|
||||
*(uint16_t *)(m_ExtendedBuffer + 2) = htobe16 (CRYPTO_KEY_TYPE_ELGAMAL);
|
||||
uint8_t buf[DEFAULT_IDENTITY_SIZE + 4];
|
||||
ToBuffer (buf, DEFAULT_IDENTITY_SIZE + 4);
|
||||
htobe16buf (m_ExtendedBuffer, type);
|
||||
htobe16buf (m_ExtendedBuffer + 2, CRYPTO_KEY_TYPE_ELGAMAL);
|
||||
if (excessLen && excessBuf)
|
||||
{
|
||||
memcpy (m_ExtendedBuffer + 4, excessBuf, excessLen);
|
||||
delete[] excessBuf;
|
||||
}
|
||||
// calculate ident hash
|
||||
uint8_t * buf = new uint8_t[GetFullLen ()];
|
||||
ToBuffer (buf, GetFullLen ());
|
||||
CryptoPP::SHA256().CalculateDigest(m_IdentHash, buf, GetFullLen ());
|
||||
delete[] buf;
|
||||
}
|
||||
else // DSA-SHA1
|
||||
{
|
||||
@@ -122,14 +182,27 @@ namespace data
|
||||
|
||||
size_t IdentityEx::FromBuffer (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (len < DEFAULT_IDENTITY_SIZE)
|
||||
{
|
||||
LogPrint (eLogError, "Identity buffer length ", len, " is too small");
|
||||
return 0;
|
||||
}
|
||||
memcpy (&m_StandardIdentity, buf, DEFAULT_IDENTITY_SIZE);
|
||||
|
||||
delete[] m_ExtendedBuffer;
|
||||
if (m_StandardIdentity.certificate.length)
|
||||
{
|
||||
m_ExtendedLen = be16toh (m_StandardIdentity.certificate.length);
|
||||
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
|
||||
memcpy (m_ExtendedBuffer, buf + DEFAULT_IDENTITY_SIZE, m_ExtendedLen);
|
||||
if (m_ExtendedLen + DEFAULT_IDENTITY_SIZE <= len)
|
||||
{
|
||||
m_ExtendedBuffer = new uint8_t[m_ExtendedLen];
|
||||
memcpy (m_ExtendedBuffer, buf + DEFAULT_IDENTITY_SIZE, m_ExtendedLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "Certificate length ", m_ExtendedLen, " exceeds buffer length ", len - DEFAULT_IDENTITY_SIZE);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -154,11 +227,21 @@ namespace data
|
||||
|
||||
size_t IdentityEx::FromBase64(const std::string& s)
|
||||
{
|
||||
uint8_t buf[512];
|
||||
auto len = Base64ToByteStream (s.c_str(), s.length(), buf, 512);
|
||||
uint8_t buf[1024];
|
||||
auto len = Base64ToByteStream (s.c_str(), s.length(), buf, 1024);
|
||||
return FromBuffer (buf, len);
|
||||
}
|
||||
|
||||
|
||||
std::string IdentityEx::ToBase64 () const
|
||||
{
|
||||
uint8_t buf[1024];
|
||||
char str[1536];
|
||||
size_t l = ToBuffer (buf, 1024);
|
||||
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, str, 1536);
|
||||
str[l1] = 0;
|
||||
return std::string (str);
|
||||
}
|
||||
|
||||
size_t IdentityEx::GetSigningPublicKeyLen () const
|
||||
{
|
||||
if (!m_Verifier) CreateVerifier ();
|
||||
@@ -167,6 +250,14 @@ namespace data
|
||||
return 128;
|
||||
}
|
||||
|
||||
size_t IdentityEx::GetSigningPrivateKeyLen () const
|
||||
{
|
||||
if (!m_Verifier) CreateVerifier ();
|
||||
if (m_Verifier)
|
||||
return m_Verifier->GetPrivateKeyLen ();
|
||||
return GetSignatureLen ()/2;
|
||||
}
|
||||
|
||||
size_t IdentityEx::GetSignatureLen () const
|
||||
{
|
||||
if (!m_Verifier) CreateVerifier ();
|
||||
@@ -185,9 +276,16 @@ namespace data
|
||||
SigningKeyType IdentityEx::GetSigningKeyType () const
|
||||
{
|
||||
if (m_StandardIdentity.certificate.type == CERTIFICATE_TYPE_KEY && m_ExtendedBuffer)
|
||||
return be16toh (*(const uint16_t *)m_ExtendedBuffer); // signing key
|
||||
return bufbe16toh (m_ExtendedBuffer); // signing key
|
||||
return SIGNING_KEY_TYPE_DSA_SHA1;
|
||||
}
|
||||
|
||||
CryptoKeyType IdentityEx::GetCryptoKeyType () const
|
||||
{
|
||||
if (m_StandardIdentity.certificate.type == CERTIFICATE_TYPE_KEY && m_ExtendedBuffer)
|
||||
return bufbe16toh (m_ExtendedBuffer + 2); // crypto key
|
||||
return CRYPTO_KEY_TYPE_ELGAMAL;
|
||||
}
|
||||
|
||||
void IdentityEx::CreateVerifier () const
|
||||
{
|
||||
@@ -198,19 +296,72 @@ namespace data
|
||||
m_Verifier = new i2p::crypto::DSAVerifier (m_StandardIdentity.signingKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
|
||||
m_Verifier = new i2p::crypto::ECDSAP256Verifier (m_StandardIdentity.signingKey + 64);
|
||||
break;
|
||||
{
|
||||
size_t padding = 128 - i2p::crypto::ECDSAP256_KEY_LENGTH; // 64 = 128 - 64
|
||||
m_Verifier = new i2p::crypto::ECDSAP256Verifier (m_StandardIdentity.signingKey + padding);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
|
||||
{
|
||||
size_t padding = 128 - i2p::crypto::ECDSAP384_KEY_LENGTH; // 32 = 128 - 96
|
||||
m_Verifier = new i2p::crypto::ECDSAP384Verifier (m_StandardIdentity.signingKey + padding);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
|
||||
{
|
||||
uint8_t signingKey[i2p::crypto::ECDSAP521_KEY_LENGTH];
|
||||
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
|
||||
size_t excessLen = i2p::crypto::ECDSAP521_KEY_LENGTH - 128; // 4 = 132- 128
|
||||
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
|
||||
m_Verifier = new i2p::crypto::ECDSAP521Verifier (signingKey);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
|
||||
{
|
||||
uint8_t signingKey[i2p::crypto::RSASHA2562048_KEY_LENGTH];
|
||||
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
|
||||
size_t excessLen = i2p::crypto::RSASHA2562048_KEY_LENGTH - 128; // 128 = 256- 128
|
||||
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
|
||||
m_Verifier = new i2p::crypto:: RSASHA2562048Verifier (signingKey);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
|
||||
{
|
||||
uint8_t signingKey[i2p::crypto::RSASHA3843072_KEY_LENGTH];
|
||||
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
|
||||
size_t excessLen = i2p::crypto::RSASHA3843072_KEY_LENGTH - 128; // 256 = 384- 128
|
||||
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
|
||||
m_Verifier = new i2p::crypto:: RSASHA3843072Verifier (signingKey);
|
||||
break;
|
||||
}
|
||||
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
|
||||
{
|
||||
uint8_t signingKey[i2p::crypto::RSASHA5124096_KEY_LENGTH];
|
||||
memcpy (signingKey, m_StandardIdentity.signingKey, 128);
|
||||
size_t excessLen = i2p::crypto::RSASHA5124096_KEY_LENGTH - 128; // 384 = 512- 128
|
||||
memcpy (signingKey + 128, m_ExtendedBuffer + 4, excessLen); // right after signing and crypto key types
|
||||
m_Verifier = new i2p::crypto:: RSASHA5124096Verifier (signingKey);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LogPrint ("Signing key type ", (int)keyType, " is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
void IdentityEx::DropVerifier ()
|
||||
{
|
||||
auto verifier = m_Verifier;
|
||||
m_Verifier = nullptr; // TODO: make this atomic
|
||||
delete verifier;
|
||||
}
|
||||
|
||||
PrivateKeys& PrivateKeys::operator=(const Keys& keys)
|
||||
{
|
||||
m_Public = Identity (keys);
|
||||
memcpy (m_PrivateKey, keys.privateKey, 256); // 256
|
||||
memcpy (m_SigningPrivateKey, keys.signingPrivateKey, 20); // 20 - DSA
|
||||
memcpy (m_SigningPrivateKey, keys.signingPrivateKey, m_Public.GetSigningPrivateKeyLen ());
|
||||
delete m_Signer;
|
||||
m_Signer = nullptr;
|
||||
CreateSigner ();
|
||||
return *this;
|
||||
}
|
||||
@@ -219,8 +370,9 @@ namespace data
|
||||
{
|
||||
m_Public = other.m_Public;
|
||||
memcpy (m_PrivateKey, other.m_PrivateKey, 256); // 256
|
||||
memcpy (m_SigningPrivateKey, other.m_SigningPrivateKey, 128); // 128
|
||||
memcpy (m_SigningPrivateKey, other.m_SigningPrivateKey, m_Public.GetSigningPrivateKeyLen ());
|
||||
delete m_Signer;
|
||||
m_Signer = nullptr;
|
||||
CreateSigner ();
|
||||
return *this;
|
||||
}
|
||||
@@ -230,10 +382,11 @@ namespace data
|
||||
size_t ret = m_Public.FromBuffer (buf, len);
|
||||
memcpy (m_PrivateKey, buf + ret, 256); // private key always 256
|
||||
ret += 256;
|
||||
size_t signingPrivateKeySize = m_Public.GetSignatureLen ()/2; // 20 for DSA
|
||||
size_t signingPrivateKeySize = m_Public.GetSigningPrivateKeyLen ();
|
||||
memcpy (m_SigningPrivateKey, buf + ret, signingPrivateKeySize);
|
||||
ret += signingPrivateKeySize;
|
||||
delete m_Signer;
|
||||
m_Signer = nullptr;
|
||||
CreateSigner ();
|
||||
return ret;
|
||||
}
|
||||
@@ -243,12 +396,34 @@ namespace data
|
||||
size_t ret = m_Public.ToBuffer (buf, len);
|
||||
memcpy (buf + ret, m_PrivateKey, 256); // private key always 256
|
||||
ret += 256;
|
||||
size_t signingPrivateKeySize = m_Public.GetSignatureLen ()/2; // 20 for DSA
|
||||
size_t signingPrivateKeySize = m_Public.GetSigningPrivateKeyLen ();
|
||||
memcpy (buf + ret, m_SigningPrivateKey, signingPrivateKeySize);
|
||||
ret += signingPrivateKeySize;
|
||||
return ret;
|
||||
}
|
||||
|
||||
size_t PrivateKeys::FromBase64(const std::string& s)
|
||||
{
|
||||
uint8_t * buf = new uint8_t[s.length ()];
|
||||
size_t l = i2p::data::Base64ToByteStream (s.c_str (), s.length (), buf, s.length ());
|
||||
size_t ret = FromBuffer (buf, l);
|
||||
delete[] buf;
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::string PrivateKeys::ToBase64 () const
|
||||
{
|
||||
uint8_t * buf = new uint8_t[GetFullLen ()];
|
||||
char * str = new char[GetFullLen ()*2];
|
||||
size_t l = ToBuffer (buf, GetFullLen ());
|
||||
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, str, GetFullLen ()*2);
|
||||
str[l1] = 0;
|
||||
delete[] buf;
|
||||
std::string ret(str);
|
||||
delete[] str;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void PrivateKeys::Sign (const uint8_t * buf, int len, uint8_t * signature) const
|
||||
{
|
||||
if (m_Signer)
|
||||
@@ -257,26 +432,73 @@ namespace data
|
||||
|
||||
void PrivateKeys::CreateSigner ()
|
||||
{
|
||||
if (m_Public.GetSigningKeyType () == SIGNING_KEY_TYPE_ECDSA_SHA256_P256)
|
||||
m_Signer = new i2p::crypto::ECDSAP256Signer (m_SigningPrivateKey);
|
||||
else
|
||||
m_Signer = new i2p::crypto::DSASigner (m_SigningPrivateKey);
|
||||
switch (m_Public.GetSigningKeyType ())
|
||||
{
|
||||
case SIGNING_KEY_TYPE_DSA_SHA1:
|
||||
m_Signer = new i2p::crypto::DSASigner (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
|
||||
m_Signer = new i2p::crypto::ECDSAP256Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
|
||||
m_Signer = new i2p::crypto::ECDSAP384Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
|
||||
m_Signer = new i2p::crypto::ECDSAP521Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
|
||||
m_Signer = new i2p::crypto::RSASHA2562048Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
|
||||
m_Signer = new i2p::crypto::RSASHA3843072Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
|
||||
m_Signer = new i2p::crypto::RSASHA5124096Signer (m_SigningPrivateKey);
|
||||
break;
|
||||
default:
|
||||
LogPrint ("Signing key type ", (int)m_Public.GetSigningKeyType (), " is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
PrivateKeys PrivateKeys::CreateRandomKeys (SigningKeyType type)
|
||||
{
|
||||
if (type == SIGNING_KEY_TYPE_ECDSA_SHA256_P256)
|
||||
if (type != SIGNING_KEY_TYPE_DSA_SHA1)
|
||||
{
|
||||
PrivateKeys keys;
|
||||
auto& rnd = i2p::context.GetRandomNumberGenerator ();
|
||||
// signature
|
||||
uint8_t signingPublicKey[512]; // signing public key is 512 bytes max
|
||||
switch (type)
|
||||
{
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
|
||||
i2p::crypto::CreateECDSAP256RandomKeys (rnd, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
|
||||
i2p::crypto::CreateECDSAP384RandomKeys (rnd, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
|
||||
i2p::crypto::CreateECDSAP521RandomKeys (rnd, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA256_2048:
|
||||
i2p::crypto::CreateRSARandomKeys (rnd, i2p::crypto::RSASHA2562048_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
|
||||
i2p::crypto::CreateRSARandomKeys (rnd, i2p::crypto::RSASHA3843072_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
|
||||
i2p::crypto::CreateRSARandomKeys (rnd, i2p::crypto::RSASHA5124096_KEY_LENGTH, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
break;
|
||||
default:
|
||||
LogPrint ("Signing key type ", (int)type, " is not supported. Create DSA-SHA1");
|
||||
return PrivateKeys (i2p::data::CreateRandomKeys ()); // DSA-SHA1
|
||||
}
|
||||
// encryption
|
||||
uint8_t publicKey[256];
|
||||
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
|
||||
dh.GenerateKeyPair(rnd, keys.m_PrivateKey, publicKey);
|
||||
// signature
|
||||
uint8_t signingPublicKey[64];
|
||||
i2p::crypto::CreateECDSAP256RandomKeys (rnd, keys.m_SigningPrivateKey, signingPublicKey);
|
||||
keys.m_Public = IdentityEx (publicKey, signingPublicKey, SIGNING_KEY_TYPE_ECDSA_SHA256_P256);
|
||||
// identity
|
||||
keys.m_Public = IdentityEx (publicKey, signingPublicKey, type);
|
||||
|
||||
keys.CreateSigner ();
|
||||
return keys;
|
||||
}
|
||||
@@ -288,8 +510,7 @@ namespace data
|
||||
Keys keys;
|
||||
auto& rnd = i2p::context.GetRandomNumberGenerator ();
|
||||
// encryption
|
||||
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
|
||||
dh.GenerateKeyPair(rnd, keys.privateKey, keys.publicKey);
|
||||
i2p::crypto::GenerateElGamalKeyPair(rnd, keys.privateKey, keys.publicKey);
|
||||
// signing
|
||||
i2p::crypto::CreateDSARandomKeys (rnd, keys.signingPrivateKey, keys.signingKey);
|
||||
return keys;
|
||||
|
||||
28
Identity.h
28
Identity.h
@@ -56,6 +56,11 @@ namespace data
|
||||
return std::string (str);
|
||||
}
|
||||
|
||||
void FromBase32 (const std::string& s)
|
||||
{
|
||||
i2p::data::Base32ToByteStream (s.c_str (), s.length (), m_Buf, sz);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
union // 8 bytes alignment
|
||||
@@ -102,11 +107,17 @@ namespace data
|
||||
Keys CreateRandomKeys ();
|
||||
|
||||
const size_t DEFAULT_IDENTITY_SIZE = sizeof (Identity); // 387 bytes
|
||||
|
||||
|
||||
const uint16_t CRYPTO_KEY_TYPE_ELGAMAL = 0;
|
||||
const uint16_t SIGNING_KEY_TYPE_DSA_SHA1 = 0;
|
||||
const uint16_t SIGNING_KEY_TYPE_ECDSA_SHA256_P256 = 1;
|
||||
const uint16_t SIGNING_KEY_TYPE_ECDSA_SHA384_P384 = 2;
|
||||
const uint16_t SIGNING_KEY_TYPE_ECDSA_SHA512_P521 = 3;
|
||||
const uint16_t SIGNING_KEY_TYPE_RSA_SHA256_2048 = 4;
|
||||
const uint16_t SIGNING_KEY_TYPE_RSA_SHA384_3072 = 5;
|
||||
const uint16_t SIGNING_KEY_TYPE_RSA_SHA512_4096 = 6;
|
||||
typedef uint16_t SigningKeyType;
|
||||
typedef uint16_t CryptoKeyType;
|
||||
|
||||
class IdentityEx
|
||||
{
|
||||
@@ -121,17 +132,21 @@ namespace data
|
||||
IdentityEx& operator=(const IdentityEx& other);
|
||||
IdentityEx& operator=(const Identity& standard);
|
||||
|
||||
size_t FromBase64(const std::string& s);
|
||||
size_t FromBuffer (const uint8_t * buf, size_t len);
|
||||
size_t ToBuffer (uint8_t * buf, size_t len) const;
|
||||
size_t FromBase64(const std::string& s);
|
||||
std::string ToBase64 () const;
|
||||
const Identity& GetStandardIdentity () const { return m_StandardIdentity; };
|
||||
const IdentHash& GetIdentHash () const { return m_IdentHash; };
|
||||
size_t GetFullLen () const { return m_ExtendedLen + DEFAULT_IDENTITY_SIZE; };
|
||||
size_t GetSigningPublicKeyLen () const;
|
||||
size_t GetSigningPrivateKeyLen () const;
|
||||
size_t GetSignatureLen () const;
|
||||
bool Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const;
|
||||
SigningKeyType GetSigningKeyType () const;
|
||||
|
||||
CryptoKeyType GetCryptoKeyType () const;
|
||||
void DropVerifier (); // to save memory
|
||||
|
||||
private:
|
||||
|
||||
void CreateVerifier () const;
|
||||
@@ -161,10 +176,13 @@ namespace data
|
||||
const uint8_t * GetSigningPrivateKey () const { return m_SigningPrivateKey; };
|
||||
void Sign (const uint8_t * buf, int len, uint8_t * signature) const;
|
||||
|
||||
size_t GetFullLen () const { return m_Public.GetFullLen () + 256 + m_Public.GetSignatureLen ()/2; };
|
||||
size_t GetFullLen () const { return m_Public.GetFullLen () + 256 + m_Public.GetSigningPrivateKeyLen (); };
|
||||
size_t FromBuffer (const uint8_t * buf, size_t len);
|
||||
size_t ToBuffer (uint8_t * buf, size_t len) const;
|
||||
|
||||
size_t FromBase64(const std::string& s);
|
||||
std::string ToBase64 () const;
|
||||
|
||||
static PrivateKeys CreateRandomKeys (SigningKeyType type = SIGNING_KEY_TYPE_DSA_SHA1);
|
||||
|
||||
private:
|
||||
@@ -175,7 +193,7 @@ namespace data
|
||||
|
||||
IdentityEx m_Public;
|
||||
uint8_t m_PrivateKey[256];
|
||||
uint8_t m_SigningPrivateKey[128]; // assume private key doesn't exceed 128 bytes
|
||||
uint8_t m_SigningPrivateKey[1024]; // assume private key doesn't exceed 1024 bytes
|
||||
i2p::crypto::Signer * m_Signer;
|
||||
};
|
||||
|
||||
|
||||
33
LeaseSet.cpp
33
LeaseSet.cpp
@@ -1,3 +1,4 @@
|
||||
#include <string.h>
|
||||
#include "I2PEndian.h"
|
||||
#include <cryptopp/dsa.h>
|
||||
#include "CryptoConst.h"
|
||||
@@ -22,11 +23,17 @@ namespace data
|
||||
LeaseSet::LeaseSet (const i2p::tunnel::TunnelPool& pool)
|
||||
{
|
||||
// header
|
||||
const i2p::data::LocalDestination& localDestination = pool.GetLocalDestination ();
|
||||
m_BufferLen = localDestination.GetIdentity ().ToBuffer (m_Buffer, MAX_LS_BUFFER_SIZE);
|
||||
memcpy (m_Buffer + m_BufferLen, localDestination.GetEncryptionPublicKey (), 256);
|
||||
const i2p::data::LocalDestination * localDestination = pool.GetLocalDestination ();
|
||||
if (!localDestination)
|
||||
{
|
||||
m_BufferLen = 0;
|
||||
LogPrint (eLogError, "Destination for local LeaseSet doesn't exist");
|
||||
return;
|
||||
}
|
||||
m_BufferLen = localDestination->GetIdentity ().ToBuffer (m_Buffer, MAX_LS_BUFFER_SIZE);
|
||||
memcpy (m_Buffer + m_BufferLen, localDestination->GetEncryptionPublicKey (), 256);
|
||||
m_BufferLen += 256;
|
||||
auto signingKeyLen = localDestination.GetIdentity ().GetSigningPublicKeyLen ();
|
||||
auto signingKeyLen = localDestination->GetIdentity ().GetSigningPublicKeyLen ();
|
||||
memset (m_Buffer + m_BufferLen, 0, signingKeyLen);
|
||||
m_BufferLen += signingKeyLen;
|
||||
auto tunnels = pool.GetInboundTunnels (5); // 5 tunnels maximum
|
||||
@@ -35,17 +42,18 @@ namespace data
|
||||
// leases
|
||||
for (auto it: tunnels)
|
||||
{
|
||||
Lease * lease = (Lease *)(m_Buffer + m_BufferLen);
|
||||
memcpy (lease->tunnelGateway, it->GetNextIdentHash (), 32);
|
||||
lease->tunnelID = htobe32 (it->GetNextTunnelID ());
|
||||
Lease lease;
|
||||
memcpy (lease.tunnelGateway, it->GetNextIdentHash (), 32);
|
||||
lease.tunnelID = htobe32 (it->GetNextTunnelID ());
|
||||
uint64_t ts = it->GetCreationTime () + i2p::tunnel::TUNNEL_EXPIRATION_TIMEOUT - 60; // 1 minute before expiration
|
||||
ts *= 1000; // in milliseconds
|
||||
lease->endDate = htobe64 (ts);
|
||||
lease.endDate = htobe64 (ts);
|
||||
memcpy(m_Buffer + m_BufferLen, &lease, sizeof(Lease));
|
||||
m_BufferLen += sizeof (Lease);
|
||||
}
|
||||
}
|
||||
// signature
|
||||
localDestination.Sign (m_Buffer, m_BufferLen, m_Buffer + m_BufferLen);
|
||||
m_BufferLen += localDestination.GetIdentity ().GetSignatureLen ();
|
||||
localDestination->Sign (m_Buffer, m_BufferLen, m_Buffer + m_BufferLen);
|
||||
m_BufferLen += localDestination->GetIdentity ().GetSignatureLen ();
|
||||
LogPrint ("Local LeaseSet of ", tunnels.size (), " leases created");
|
||||
|
||||
ReadFromBuffer ();
|
||||
@@ -73,7 +81,8 @@ namespace data
|
||||
const uint8_t * leases = m_Buffer + size;
|
||||
for (int i = 0; i < num; i++)
|
||||
{
|
||||
Lease lease = *(Lease *)leases;
|
||||
Lease lease;
|
||||
memcpy (&lease, leases, sizeof(Lease));
|
||||
lease.tunnelID = be32toh (lease.tunnelID);
|
||||
lease.endDate = be64toh (lease.endDate);
|
||||
m_Leases.push_back (lease);
|
||||
|
||||
@@ -36,7 +36,7 @@ namespace data
|
||||
|
||||
#pragma pack()
|
||||
|
||||
const int MAX_LS_BUFFER_SIZE = 2048;
|
||||
const int MAX_LS_BUFFER_SIZE = 3072;
|
||||
class LeaseSet: public RoutingDestination
|
||||
{
|
||||
public:
|
||||
|
||||
25
Log.cpp
25
Log.cpp
@@ -20,19 +20,24 @@ void LogMsg::Process()
|
||||
|
||||
void Log::Flush ()
|
||||
{
|
||||
if (m_LogFile)
|
||||
m_LogFile->flush();
|
||||
if (m_LogStream)
|
||||
m_LogStream->flush();
|
||||
}
|
||||
|
||||
void Log::SetLogFile (const std::string& fullFilePath)
|
||||
{
|
||||
if (m_LogFile) delete m_LogFile;
|
||||
m_LogFile = new std::ofstream (fullFilePath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
|
||||
if (m_LogFile->is_open ())
|
||||
LogPrint("Logging to file ", fullFilePath, " enabled.");
|
||||
else
|
||||
auto logFile = new std::ofstream (fullFilePath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
|
||||
if (logFile->is_open ())
|
||||
{
|
||||
delete m_LogFile;
|
||||
m_LogFile = nullptr;
|
||||
}
|
||||
SetLogStream (logFile);
|
||||
LogPrint("Logging to file ", fullFilePath, " enabled.");
|
||||
}
|
||||
else
|
||||
delete logFile;
|
||||
}
|
||||
|
||||
void Log::SetLogStream (std::ostream * logStream)
|
||||
{
|
||||
if (m_LogStream) delete m_LogStream;
|
||||
m_LogStream = logStream;
|
||||
}
|
||||
|
||||
21
Log.h
21
Log.h
@@ -32,11 +32,12 @@ class Log: public i2p::util::MsgQueue<LogMsg>
|
||||
{
|
||||
public:
|
||||
|
||||
Log (): m_LogFile (nullptr) { SetOnEmpty (std::bind (&Log::Flush, this)); };
|
||||
~Log () { delete m_LogFile; };
|
||||
Log (): m_LogStream (nullptr) { SetOnEmpty (std::bind (&Log::Flush, this)); };
|
||||
~Log () { delete m_LogStream; };
|
||||
|
||||
void SetLogFile (const std::string& fullFilePath);
|
||||
std::ofstream * GetLogFile () const { return m_LogFile; };
|
||||
void SetLogStream (std::ostream * logStream);
|
||||
std::ostream * GetLogStream () const { return m_LogStream; };
|
||||
|
||||
private:
|
||||
|
||||
@@ -44,7 +45,7 @@ class Log: public i2p::util::MsgQueue<LogMsg>
|
||||
|
||||
private:
|
||||
|
||||
std::ofstream * m_LogFile;
|
||||
std::ostream * m_LogStream;
|
||||
};
|
||||
|
||||
extern Log * g_Log;
|
||||
@@ -59,6 +60,16 @@ inline void StartLog (const std::string& fullFilePath)
|
||||
}
|
||||
}
|
||||
|
||||
inline void StartLog (std::ostream * s)
|
||||
{
|
||||
if (!g_Log)
|
||||
{
|
||||
g_Log = new Log ();
|
||||
if (s)
|
||||
g_Log->SetLogStream (s);
|
||||
}
|
||||
}
|
||||
|
||||
inline void StopLog ()
|
||||
{
|
||||
if (g_Log)
|
||||
@@ -84,7 +95,7 @@ void LogPrint (std::stringstream& s, TValue arg, TArgs... args)
|
||||
template<typename... TArgs>
|
||||
void LogPrint (LogLevel level, TArgs... args)
|
||||
{
|
||||
LogMsg * msg = (g_Log && g_Log->GetLogFile ()) ? new LogMsg (*g_Log->GetLogFile (), level) :
|
||||
LogMsg * msg = (g_Log && g_Log->GetLogStream ()) ? new LogMsg (*g_Log->GetLogStream (), level) :
|
||||
new LogMsg (std::cout, level);
|
||||
LogPrint (msg->s, args...);
|
||||
msg->s << std::endl;
|
||||
|
||||
66
Makefile
66
Makefile
@@ -1,29 +1,73 @@
|
||||
UNAME := $(shell uname -s)
|
||||
SHLIB := libi2pd.so
|
||||
I2PD := i2p
|
||||
GREP := fgrep
|
||||
DEPS := obj/make.dep
|
||||
|
||||
include filelist.mk
|
||||
|
||||
USE_AESNI := yes
|
||||
USE_STATIC := no
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
DAEMON_SRC += DaemonLinux.cpp
|
||||
include Makefile.osx
|
||||
else ifeq ($(UNAME), FreeBSD)
|
||||
else ifeq ($(shell echo $(UNAME) | $(GREP) -c FreeBSD),1)
|
||||
DAEMON_SRC += DaemonLinux.cpp
|
||||
include Makefile.bsd
|
||||
else
|
||||
else ifeq ($(UNAME),Linux)
|
||||
DAEMON_SRC += DaemonLinux.cpp
|
||||
include Makefile.linux
|
||||
else # win32
|
||||
DAEMON_SRC += DaemonWin32.cpp
|
||||
endif
|
||||
|
||||
all: obj i2p
|
||||
all: mk_build_dir $(SHLIB) $(I2PD)
|
||||
|
||||
i2p: $(OBJECTS:obj/%=obj/%)
|
||||
$(CXX) -o $@ $^ $(LDLIBS) $(LDFLAGS) $(LIBS)
|
||||
mk_build_dir:
|
||||
test -d obj || mkdir obj
|
||||
|
||||
.SUFFIXES:
|
||||
.SUFFIXES: .c .cc .C .cpp .o
|
||||
api: $(SHLIB)
|
||||
|
||||
## NOTE: The NEEDED_CXXFLAGS are here so that CXXFLAGS can be specified at build time
|
||||
## **without** overwriting the CXXFLAGS which we need in order to build.
|
||||
## For example, when adding 'hardening flags' to the build
|
||||
## (e.g. -fstack-protector-strong -Wformat -Werror=format-security), we do not want to remove
|
||||
## -std=c++11. If you want to remove this variable please do so in a way that allows setting
|
||||
## custom FLAGS to work at build-time.
|
||||
|
||||
deps:
|
||||
@test -d obj || mkdir obj
|
||||
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) -MM *.cpp > $(DEPS)
|
||||
@sed -i -e '/\.o:/ s/^/obj\//' $(DEPS)
|
||||
|
||||
obj/%.o : %.cpp
|
||||
$(CXX) -o $@ $< -c $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) $(CPU_FLAGS)
|
||||
@test -d obj || mkdir obj
|
||||
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) $(CPU_FLAGS) -c -o $@ $<
|
||||
|
||||
obj:
|
||||
mkdir -p obj
|
||||
# '-' is 'ignore if missing' on first run
|
||||
-include $(DEPS)
|
||||
|
||||
$(I2PD): $(patsubst %.cpp,obj/%.o,$(DAEMON_SRC))
|
||||
$(CXX) -o $@ $^ $(LDLIBS) $(LDFLAGS)
|
||||
|
||||
$(SHLIB): $(patsubst %.cpp,obj/%.o,$(LIB_SRC))
|
||||
ifneq ($(USE_STATIC),yes)
|
||||
$(CXX) $(LDFLAGS) $(LDLIBS) -shared -o $@ $^
|
||||
endif
|
||||
|
||||
clean:
|
||||
rm -fr obj i2p
|
||||
rm -rf obj
|
||||
$(RM) $(I2PD) $(SHLIB)
|
||||
|
||||
LATEST_TAG=$(shell git describe --tags --abbrev=0 master)
|
||||
dist:
|
||||
git archive --format=tar.gz -9 --worktree-attributes \
|
||||
--prefix=i2pd_$(LATEST_TAG)/ $(LATEST_TAG) -o i2pd_$(LATEST_TAG).tar.gz
|
||||
|
||||
.PHONY: all
|
||||
.PHONY: clean
|
||||
.PHONY: deps
|
||||
.PHONY: dist
|
||||
.PHONY: api
|
||||
.PHONY: mk_build_dir
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
CXX = g++
|
||||
CXXFLAGS = -O2
|
||||
## NOTE: NEEDED_CXXFLAGS is here so that custom CXXFLAGS can be specified at build time
|
||||
## **without** overwriting the CXXFLAGS which we need in order to build.
|
||||
## For example, when adding 'hardening flags' to the build
|
||||
## (e.g. -fstack-protector-strong -Wformat -Werror=format-security), we do not want to remove
|
||||
## -std=c++11. If you want to remove this variable please do so in a way that allows setting
|
||||
## custom FLAGS to work at build-time.
|
||||
NEEDED_CXXFLAGS = -std=c++11
|
||||
include filelist.mk
|
||||
INCFLAGS = -I/usr/include/ -I/usr/local/include/
|
||||
LDFLAGS = -Wl,-rpath,/usr/local/lib -L/usr/local/lib
|
||||
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
|
||||
LIBS =
|
||||
|
||||
@@ -1,37 +1,48 @@
|
||||
CXXFLAGS = -g -Wall
|
||||
CXXVER := $(shell $(CXX) -dumpversion)
|
||||
|
||||
FGREP = fgrep
|
||||
IS_64 := $(shell $(CXX) -dumpmachine 2>&1 | $(FGREP) -c "64")
|
||||
USE_AESNI := yes
|
||||
ifeq ($(shell expr match ${CXXVER} "4\.[0-9][0-9]"),4) # >= 4.10
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else ifeq ($(shell expr match ${CXXVER} "4\.[7-9]"),3) # >= 4.7
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else ifeq ($(shell expr match ${CXXVER} "4\.6"),3) # = 4.6
|
||||
NEEDED_CXXFLAGS += -std=c++0x
|
||||
else ifeq ($(shell expr match $(CXX) 'clang'),5)
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else # not supported
|
||||
$(error Compiler too old)
|
||||
endif
|
||||
|
||||
LIBDIR := /usr/lib
|
||||
|
||||
include filelist.mk
|
||||
CXXFLAGS = -g -Wall -fPIC
|
||||
INCFLAGS =
|
||||
ifeq ($(STATIC),yes)
|
||||
LDLIBS += $(LIBDIR)/libcryptopp.a $(LIBDIR)/libboost_system.a
|
||||
LDLIBS += $(LIBDIR)/libboost_date_time.a $(LIBDIR)/libboost_filesystem.a
|
||||
LDLIBS += $(LIBDIR)/libboost_regex.a $(LIBDIR)/libboost_program_options.a
|
||||
LDLIBS += -lpthread -static-libstdc++ -static-libgcc
|
||||
USE_AESNI := no
|
||||
else
|
||||
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
|
||||
|
||||
## NOTE: The NEEDED_CXXFLAGS are here so that custom CXXFLAGS can be specified at build time
|
||||
## **without** overwriting the CXXFLAGS which we need in order to build.
|
||||
## For example, when adding 'hardening flags' to the build
|
||||
## (e.g. -fstack-protector-strong -Wformat -Werror=format-security), we do not want to remove
|
||||
## -std=c++11. If you want to remove this variable please do so in a way that allows setting
|
||||
## custom FLAGS to work at build-time.
|
||||
|
||||
# detect proper flag for c++11 support by gcc
|
||||
CXXVER := $(shell $(CXX) -dumpversion)
|
||||
ifeq ($(shell expr match ${CXXVER} "4\.[0-9][0-9]"),4) # >= 4.10
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else ifeq ($(shell expr match ${CXXVER} "4\.[7-9]"),3) # >= 4.7
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else ifeq ($(shell expr match ${CXXVER} "4\.6"),3) # = 4.6
|
||||
NEEDED_CXXFLAGS += -std=c++0x
|
||||
else ifeq ($(shell expr match $(CXX) 'clang'),5)
|
||||
NEEDED_CXXFLAGS += -std=c++11
|
||||
else # not supported
|
||||
$(error Compiler too old)
|
||||
endif
|
||||
LIBS =
|
||||
|
||||
ifeq ($(USE_STATIC),yes)
|
||||
LIBDIR := /usr/lib
|
||||
LDLIBS = $(LIBDIR)/libboost_system.a
|
||||
LDLIBS += $(LIBDIR)/libboost_date_time.a
|
||||
LDLIBS += $(LIBDIR)/libboost_filesystem.a
|
||||
LDLIBS += $(LIBDIR)/libboost_regex.a
|
||||
LDLIBS += $(LIBDIR)/libboost_program_options.a
|
||||
LDLIBS += $(LIBDIR)/libcryptopp.a
|
||||
LDLIBS += -lpthread -static-libstdc++ -static-libgcc
|
||||
USE_AESNI := no
|
||||
else
|
||||
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
|
||||
endif
|
||||
|
||||
# UPNP Support (miniupnpc 1.5 or 1.6)
|
||||
ifeq ($(USE_UPNP),1)
|
||||
LDFLAGS += -ldl
|
||||
CXXFLAGS += -DUSE_UPNP
|
||||
endif
|
||||
|
||||
IS_64 := $(shell $(CXX) -dumpmachine 2>&1 | $(GREP) -c "64")
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
ifeq ($(IS_64),1)
|
||||
#check if AES-NI is supported by CPU
|
||||
@@ -40,4 +51,3 @@ ifneq ($(shell grep -c aes /proc/cpuinfo),0)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
|
||||
34
Makefile.osx
34
Makefile.osx
@@ -1,27 +1,25 @@
|
||||
CXX = clang++
|
||||
CXXFLAGS = -g -Wall -std=c++11 -lstdc++ -I/usr/local/include
|
||||
include filelist.mk
|
||||
INCFLAGS = -DCRYPTOPP_DISABLE_ASM
|
||||
CXXFLAGS = -g -Wall -std=c++11 -DCRYPTOPP_DISABLE_ASM -DMAC_OSX
|
||||
#CXXFLAGS = -g -O2 -Wall -std=c++11 -DCRYPTOPP_DISABLE_ASM
|
||||
INCFLAGS = -I/usr/local/include
|
||||
LDFLAGS = -Wl,-rpath,/usr/local/lib -L/usr/local/lib
|
||||
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
|
||||
LIBS =
|
||||
|
||||
ifeq ($(USE_UPNP),1)
|
||||
LDFLAGS += -ldl
|
||||
CXXFLAGS += -DUSE_UPNP
|
||||
endif
|
||||
|
||||
# OSX Notes
|
||||
# http://www.hutsby.net/2011/08/macs-with-aes-ni.html
|
||||
# Seems like all recent Mac's have AES-NI, after firmware upgrade 2.2
|
||||
# Found no good way to detect it from command line. TODO: Might be some osx sysinfo magic
|
||||
CXXFLAGS += -maes -DAESNI
|
||||
|
||||
|
||||
${PREFIX}:
|
||||
|
||||
install: all
|
||||
mkdir -p ${PREFIX}/
|
||||
cp -r i2p ${PREFIX}/
|
||||
|
||||
|
||||
|
||||
# Apple Mac OSX
|
||||
UNAME_S := $(shell uname -s)
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
CXXFLAGS += -maes -DAESNI
|
||||
endif
|
||||
|
||||
# Disabled, since it will be the default make rule. I think its better
|
||||
# to define the default rule in Makefile and not Makefile.<ostype> - torkel
|
||||
#install: all
|
||||
# test -d ${PREFIX} || mkdir -p ${PREFIX}/
|
||||
# cp -r i2p ${PREFIX}/
|
||||
|
||||
278
NTCPSession.cpp
278
NTCPSession.cpp
@@ -1,7 +1,6 @@
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include "I2PEndian.h"
|
||||
#include <boost/bind.hpp>
|
||||
#include <cryptopp/dh.h>
|
||||
#include "base64.h"
|
||||
#include "Log.h"
|
||||
@@ -44,7 +43,7 @@ namespace transport
|
||||
uint8_t sharedKey[256];
|
||||
if (!dh.Agree (sharedKey, m_DHKeysPair->privateKey, pubKey))
|
||||
{
|
||||
LogPrint ("Couldn't create shared key");
|
||||
LogPrint (eLogError, "Couldn't create shared key");
|
||||
Terminate ();
|
||||
return;
|
||||
};
|
||||
@@ -66,7 +65,7 @@ namespace transport
|
||||
nonZero++;
|
||||
if (nonZero - sharedKey > 32)
|
||||
{
|
||||
LogPrint ("First 32 bytes of shared key is all zeros. Ignored");
|
||||
LogPrint (eLogWarning, "First 32 bytes of shared key is all zeros. Ignored");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -78,7 +77,6 @@ namespace transport
|
||||
{
|
||||
m_IsEstablished = false;
|
||||
m_Socket.close ();
|
||||
transports.RemoveNTCPSession (this);
|
||||
int numDelayed = 0;
|
||||
for (auto it :m_DelayedMessages)
|
||||
{
|
||||
@@ -89,16 +87,14 @@ namespace transport
|
||||
}
|
||||
m_DelayedMessages.clear ();
|
||||
if (numDelayed > 0)
|
||||
LogPrint ("NTCP session ", numDelayed, " not sent");
|
||||
LogPrint (eLogWarning, "NTCP session ", numDelayed, " not sent");
|
||||
// TODO: notify tunnels
|
||||
|
||||
delete this;
|
||||
transports.RemoveNTCPSession (shared_from_this ());
|
||||
LogPrint ("NTCP session terminated");
|
||||
}
|
||||
|
||||
void NTCPSession::Connected ()
|
||||
{
|
||||
LogPrint ("NTCP session connected");
|
||||
m_IsEstablished = true;
|
||||
|
||||
delete m_Establisher;
|
||||
@@ -131,31 +127,31 @@ namespace transport
|
||||
m_Establisher->phase1.HXxorHI[i] ^= ident[i];
|
||||
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (&m_Establisher->phase1, sizeof (NTCPPhase1)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase1Sent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&NTCPSession::HandlePhase1Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void NTCPSession::ServerLogin ()
|
||||
{
|
||||
// receive Phase1
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase1, sizeof (NTCPPhase1)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase1Received, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&NTCPSession::HandlePhase1Received, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void NTCPSession::HandlePhase1Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Couldn't send Phase 1 message: ", ecode.message ());
|
||||
LogPrint (eLogWarning, "Couldn't send Phase 1 message: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 1 sent: ", bytes_transferred);
|
||||
LogPrint (eLogDebug, "Phase 1 sent: ", bytes_transferred);
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase2, sizeof (NTCPPhase2)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase2Received, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&NTCPSession::HandlePhase2Received, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,13 +159,13 @@ namespace transport
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Phase 1 read error: ", ecode.message ());
|
||||
LogPrint (eLogError, "Phase 1 read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 1 received: ", bytes_transferred);
|
||||
LogPrint (eLogDebug, "Phase 1 received: ", bytes_transferred);
|
||||
// verify ident
|
||||
uint8_t digest[32];
|
||||
CryptoPP::SHA256().CalculateDigest(digest, m_Establisher->phase1.pubKey, 256);
|
||||
@@ -178,7 +174,7 @@ namespace transport
|
||||
{
|
||||
if ((m_Establisher->phase1.HXxorHI[i] ^ ident[i]) != digest[i])
|
||||
{
|
||||
LogPrint ("Wrong ident");
|
||||
LogPrint (eLogError, "Wrong ident");
|
||||
Terminate ();
|
||||
return;
|
||||
}
|
||||
@@ -211,7 +207,7 @@ namespace transport
|
||||
|
||||
m_Encryption.Encrypt ((uint8_t *)&m_Establisher->phase2.encrypted, sizeof(m_Establisher->phase2.encrypted), (uint8_t *)&m_Establisher->phase2.encrypted);
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (&m_Establisher->phase2, sizeof (NTCPPhase2)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase2Sent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, tsB));
|
||||
std::bind(&NTCPSession::HandlePhase2Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, tsB));
|
||||
|
||||
}
|
||||
|
||||
@@ -219,16 +215,16 @@ namespace transport
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Couldn't send Phase 2 message: ", ecode.message ());
|
||||
LogPrint (eLogWarning, "Couldn't send Phase 2 message: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 2 sent: ", bytes_transferred);
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase3, sizeof (NTCPPhase3)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase3Received, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, tsB));
|
||||
LogPrint (eLogDebug, "Phase 2 sent: ", bytes_transferred);
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer, NTCP_DEFAULT_PHASE3_SIZE), boost::asio::transfer_all (),
|
||||
std::bind(&NTCPSession::HandlePhase3Received, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, tsB));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,7 +244,7 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 2 received: ", bytes_transferred);
|
||||
LogPrint (eLogDebug, "Phase 2 received: ", bytes_transferred);
|
||||
|
||||
i2p::crypto::AESKey aesKey;
|
||||
CreateAESKey (m_Establisher->phase2.pubKey, aesKey);
|
||||
@@ -259,13 +255,12 @@ namespace transport
|
||||
|
||||
m_Decryption.Decrypt((uint8_t *)&m_Establisher->phase2.encrypted, sizeof(m_Establisher->phase2.encrypted), (uint8_t *)&m_Establisher->phase2.encrypted);
|
||||
// verify
|
||||
uint8_t xy[512], hxy[32];
|
||||
uint8_t xy[512];
|
||||
memcpy (xy, m_DHKeysPair->publicKey, 256);
|
||||
memcpy (xy + 256, m_Establisher->phase2.pubKey, 256);
|
||||
CryptoPP::SHA256().CalculateDigest(hxy, xy, 512);
|
||||
if (memcmp (hxy, m_Establisher->phase2.encrypted.hxy, 32))
|
||||
if (!CryptoPP::SHA256().VerifyDigest(m_Establisher->phase2.encrypted.hxy, xy, 512))
|
||||
{
|
||||
LogPrint ("Incorrect hash");
|
||||
LogPrint (eLogError, "Incorrect hash");
|
||||
transports.ReuseDHKeysPair (m_DHKeysPair);
|
||||
m_DHKeysPair = nullptr;
|
||||
Terminate ();
|
||||
@@ -277,39 +272,56 @@ namespace transport
|
||||
|
||||
void NTCPSession::SendPhase3 ()
|
||||
{
|
||||
m_Establisher->phase3.size = htons (i2p::data::DEFAULT_IDENTITY_SIZE);
|
||||
memcpy (&m_Establisher->phase3.ident, &i2p::context.GetIdentity ().GetStandardIdentity (), i2p::data::DEFAULT_IDENTITY_SIZE); // TODO:
|
||||
auto keys = i2p::context.GetPrivateKeys ();
|
||||
uint8_t * buf = m_ReceiveBuffer;
|
||||
htobe16buf (buf, keys.GetPublic ().GetFullLen ());
|
||||
buf += 2;
|
||||
buf += i2p::context.GetIdentity ().ToBuffer (buf, NTCP_BUFFER_SIZE);
|
||||
uint32_t tsA = htobe32 (i2p::util::GetSecondsSinceEpoch ());
|
||||
m_Establisher->phase3.timestamp = tsA;
|
||||
|
||||
htobuf32(buf,tsA);
|
||||
buf += 4;
|
||||
size_t signatureLen = keys.GetPublic ().GetSignatureLen ();
|
||||
size_t len = (buf - m_ReceiveBuffer) + signatureLen;
|
||||
size_t paddingSize = len & 0x0F; // %16
|
||||
if (paddingSize > 0)
|
||||
{
|
||||
paddingSize = 16 - paddingSize;
|
||||
// TODO: fill padding with random data
|
||||
buf += paddingSize;
|
||||
len += paddingSize;
|
||||
}
|
||||
|
||||
SignedData s;
|
||||
s.Insert (m_Establisher->phase1.pubKey, 256); // x
|
||||
s.Insert (m_Establisher->phase2.pubKey, 256); // y
|
||||
s.Insert (m_RemoteIdentity.GetIdentHash (), 32); // ident
|
||||
s.Insert (tsA); // tsA
|
||||
s.Insert (m_Establisher->phase2.encrypted.timestamp); // tsB
|
||||
s.Sign (i2p::context.GetPrivateKeys (), m_Establisher->phase3.signature);
|
||||
s.Sign (keys, buf);
|
||||
|
||||
m_Encryption.Encrypt((uint8_t *)&m_Establisher->phase3, sizeof(NTCPPhase3), (uint8_t *)&m_Establisher->phase3);
|
||||
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (&m_Establisher->phase3, sizeof (NTCPPhase3)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase3Sent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, tsA));
|
||||
m_Encryption.Encrypt(m_ReceiveBuffer, len, m_ReceiveBuffer);
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_ReceiveBuffer, len), boost::asio::transfer_all (),
|
||||
std::bind(&NTCPSession::HandlePhase3Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, tsA));
|
||||
}
|
||||
|
||||
void NTCPSession::HandlePhase3Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Couldn't send Phase 3 message: ", ecode.message ());
|
||||
LogPrint (eLogWarning, "Couldn't send Phase 3 message: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 3 sent: ", bytes_transferred);
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase4, sizeof (NTCPPhase4)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase4Received, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, tsA));
|
||||
LogPrint (eLogDebug, "Phase 3 sent: ", bytes_transferred);
|
||||
// wait for phase4
|
||||
auto signatureLen = m_RemoteIdentity.GetSignatureLen ();
|
||||
size_t paddingSize = signatureLen & 0x0F; // %16
|
||||
if (paddingSize > 0) signatureLen += (16 - paddingSize);
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer, signatureLen), boost::asio::transfer_all (),
|
||||
std::bind(&NTCPSession::HandlePhase4Received, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, tsA));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,59 +329,106 @@ namespace transport
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Phase 3 read error: ", ecode.message ());
|
||||
LogPrint (eLogError, "Phase 3 read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 3 received: ", bytes_transferred);
|
||||
m_Decryption.Decrypt ((uint8_t *)&m_Establisher->phase3, sizeof(NTCPPhase3), (uint8_t *)&m_Establisher->phase3);
|
||||
m_RemoteIdentity = m_Establisher->phase3.ident;
|
||||
|
||||
SignedData s;
|
||||
s.Insert (m_Establisher->phase1.pubKey, 256); // x
|
||||
s.Insert (m_Establisher->phase2.pubKey, 256); // y
|
||||
s.Insert (i2p::context.GetRouterInfo ().GetIdentHash (), 32); // ident
|
||||
s.Insert (m_Establisher->phase3.timestamp); // tsA
|
||||
s.Insert (tsB); // tsB
|
||||
if (!s.Verify (m_RemoteIdentity, m_Establisher->phase3.signature))
|
||||
{
|
||||
LogPrint ("signature verification failed");
|
||||
Terminate ();
|
||||
return;
|
||||
}
|
||||
|
||||
SendPhase4 (tsB);
|
||||
LogPrint (eLogDebug, "Phase 3 received: ", bytes_transferred);
|
||||
m_Decryption.Decrypt (m_ReceiveBuffer, bytes_transferred, m_ReceiveBuffer);
|
||||
uint8_t * buf = m_ReceiveBuffer;
|
||||
uint16_t size = bufbe16toh (buf);
|
||||
m_RemoteIdentity.FromBuffer (buf + 2, size);
|
||||
size_t expectedSize = size + 2/*size*/ + 4/*timestamp*/ + m_RemoteIdentity.GetSignatureLen ();
|
||||
size_t paddingLen = expectedSize & 0x0F;
|
||||
if (paddingLen) paddingLen = (16 - paddingLen);
|
||||
if (expectedSize > NTCP_DEFAULT_PHASE3_SIZE)
|
||||
{
|
||||
// we need more bytes for Phase3
|
||||
expectedSize += paddingLen;
|
||||
LogPrint (eLogDebug, "Wait for ", expectedSize, " more bytes for Phase3");
|
||||
boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer + NTCP_DEFAULT_PHASE3_SIZE, expectedSize), boost::asio::transfer_all (),
|
||||
std::bind(&NTCPSession::HandlePhase3ExtraReceived, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, tsB, paddingLen));
|
||||
}
|
||||
else
|
||||
HandlePhase3 (tsB, paddingLen);
|
||||
}
|
||||
}
|
||||
|
||||
void NTCPSession::SendPhase4 (uint32_t tsB)
|
||||
void NTCPSession::HandlePhase3ExtraReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB, size_t paddingLen)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint (eLogError, "Phase 3 extra read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogDebug, "Phase 3 extra received: ", bytes_transferred);
|
||||
m_Decryption.Decrypt (m_ReceiveBuffer + NTCP_DEFAULT_PHASE3_SIZE, bytes_transferred, m_ReceiveBuffer+ NTCP_DEFAULT_PHASE3_SIZE);
|
||||
HandlePhase3 (tsB, paddingLen);
|
||||
}
|
||||
}
|
||||
|
||||
void NTCPSession::HandlePhase3 (uint32_t tsB, size_t paddingLen)
|
||||
{
|
||||
uint8_t * buf = m_ReceiveBuffer + m_RemoteIdentity.GetFullLen () + 2 /*size*/;
|
||||
uint32_t tsA = buf32toh(buf);
|
||||
buf += 4;
|
||||
buf += paddingLen;
|
||||
|
||||
SignedData s;
|
||||
s.Insert (m_Establisher->phase1.pubKey, 256); // x
|
||||
s.Insert (m_Establisher->phase2.pubKey, 256); // y
|
||||
s.Insert (i2p::context.GetRouterInfo ().GetIdentHash (), 32); // ident
|
||||
s.Insert (tsA); // tsA
|
||||
s.Insert (tsB); // tsB
|
||||
if (!s.Verify (m_RemoteIdentity, buf))
|
||||
{
|
||||
LogPrint (eLogError, "signature verification failed");
|
||||
Terminate ();
|
||||
return;
|
||||
}
|
||||
|
||||
SendPhase4 (tsA, tsB);
|
||||
}
|
||||
|
||||
void NTCPSession::SendPhase4 (uint32_t tsA, uint32_t tsB)
|
||||
{
|
||||
SignedData s;
|
||||
s.Insert (m_Establisher->phase1.pubKey, 256); // x
|
||||
s.Insert (m_Establisher->phase2.pubKey, 256); // y
|
||||
s.Insert (m_RemoteIdentity.GetIdentHash (), 32); // ident
|
||||
s.Insert (m_Establisher->phase3.timestamp); // tsA
|
||||
s.Insert (tsA); // tsA
|
||||
s.Insert (tsB); // tsB
|
||||
s.Sign (i2p::context.GetPrivateKeys (), m_Establisher->phase4.signature);
|
||||
m_Encryption.Encrypt ((uint8_t *)&m_Establisher->phase4, sizeof(NTCPPhase4), (uint8_t *)&m_Establisher->phase4);
|
||||
auto keys = i2p::context.GetPrivateKeys ();
|
||||
auto signatureLen = keys.GetPublic ().GetSignatureLen ();
|
||||
s.Sign (keys, m_ReceiveBuffer);
|
||||
size_t paddingSize = signatureLen & 0x0F; // %16
|
||||
if (paddingSize > 0) signatureLen += (16 - paddingSize);
|
||||
m_Encryption.Encrypt (m_ReceiveBuffer, signatureLen, m_ReceiveBuffer);
|
||||
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (&m_Establisher->phase4, sizeof (NTCPPhase4)), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandlePhase4Sent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_ReceiveBuffer, signatureLen), boost::asio::transfer_all (),
|
||||
std::bind(&NTCPSession::HandlePhase4Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void NTCPSession::HandlePhase4Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Couldn't send Phase 4 message: ", ecode.message ());
|
||||
LogPrint (eLogWarning, "Couldn't send Phase 4 message: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 4 sent: ", bytes_transferred);
|
||||
LogPrint (eLogDebug, "Phase 4 sent: ", bytes_transferred);
|
||||
LogPrint ("NTCP server session connected");
|
||||
transports.AddNTCPSession (shared_from_this ());
|
||||
|
||||
Connected ();
|
||||
m_ReceiveBufferOffset = 0;
|
||||
m_NextMessage = nullptr;
|
||||
@@ -381,7 +440,7 @@ namespace transport
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Phase 4 read error: ", ecode.message ());
|
||||
LogPrint (eLogError, "Phase 4 read error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
// this router doesn't like us
|
||||
@@ -391,8 +450,8 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Phase 4 received: ", bytes_transferred);
|
||||
m_Decryption.Decrypt((uint8_t *)&m_Establisher->phase4, sizeof(NTCPPhase4), (uint8_t *)&m_Establisher->phase4);
|
||||
LogPrint (eLogDebug, "Phase 4 received: ", bytes_transferred);
|
||||
m_Decryption.Decrypt(m_ReceiveBuffer, bytes_transferred, m_ReceiveBuffer);
|
||||
|
||||
// verify signature
|
||||
SignedData s;
|
||||
@@ -402,12 +461,13 @@ namespace transport
|
||||
s.Insert (tsA); // tsA
|
||||
s.Insert (m_Establisher->phase2.encrypted.timestamp); // tsB
|
||||
|
||||
if (!s.Verify (m_RemoteIdentity, m_Establisher->phase4.signature))
|
||||
if (!s.Verify (m_RemoteIdentity, m_ReceiveBuffer))
|
||||
{
|
||||
LogPrint ("signature verification failed");
|
||||
LogPrint (eLogError, "signature verification failed");
|
||||
Terminate ();
|
||||
return;
|
||||
}
|
||||
LogPrint ("NTCP session connected");
|
||||
Connected ();
|
||||
|
||||
m_ReceiveBufferOffset = 0;
|
||||
@@ -419,15 +479,15 @@ namespace transport
|
||||
void NTCPSession::Receive ()
|
||||
{
|
||||
m_Socket.async_read_some (boost::asio::buffer(m_ReceiveBuffer + m_ReceiveBufferOffset, NTCP_BUFFER_SIZE - m_ReceiveBufferOffset),
|
||||
boost::bind(&NTCPSession::HandleReceived, this,
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&NTCPSession::HandleReceived, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void NTCPSession::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Read error: ", ecode.message ());
|
||||
LogPrint (eLogError, "Read error: ", ecode.message ());
|
||||
//if (ecode != boost::asio::error::operation_aborted)
|
||||
Terminate ();
|
||||
}
|
||||
@@ -466,13 +526,13 @@ namespace transport
|
||||
m_NextMessageOffset = 0;
|
||||
|
||||
m_Decryption.Decrypt (encrypted, m_NextMessage->buf);
|
||||
uint16_t dataSize = be16toh (*(uint16_t *)m_NextMessage->buf);
|
||||
uint16_t dataSize = bufbe16toh (m_NextMessage->buf);
|
||||
if (dataSize)
|
||||
{
|
||||
// new message
|
||||
if (dataSize > NTCP_MAX_MESSAGE_SIZE)
|
||||
{
|
||||
LogPrint ("NTCP data size ", dataSize, " exceeds max size");
|
||||
LogPrint (eLogError, "NTCP data size ", dataSize, " exceeds max size");
|
||||
i2p::DeleteI2NPMessage (m_NextMessage);
|
||||
m_NextMessage = nullptr;
|
||||
return false;
|
||||
@@ -515,20 +575,20 @@ namespace transport
|
||||
// regular I2NP
|
||||
if (msg->offset < 2)
|
||||
{
|
||||
LogPrint ("Malformed I2NP message");
|
||||
LogPrint (eLogError, "Malformed I2NP message");
|
||||
i2p::DeleteI2NPMessage (msg);
|
||||
}
|
||||
sendBuffer = msg->GetBuffer () - 2;
|
||||
len = msg->GetLength ();
|
||||
*((uint16_t *)sendBuffer) = htobe16 (len);
|
||||
htobe16buf (sendBuffer, len);
|
||||
}
|
||||
else
|
||||
{
|
||||
// prepare timestamp
|
||||
sendBuffer = m_TimeSyncBuffer;
|
||||
len = 4;
|
||||
*((uint16_t *)sendBuffer) = 0;
|
||||
*((uint32_t *)(sendBuffer + 2)) = htobe32 (time (0));
|
||||
htobuf16(sendBuffer, 0);
|
||||
htobe32buf (sendBuffer + 2, time (0));
|
||||
}
|
||||
int rem = (len + 6) & 0x0F; // %16
|
||||
int padding = 0;
|
||||
@@ -540,7 +600,7 @@ namespace transport
|
||||
m_Encryption.Encrypt(sendBuffer, l, sendBuffer);
|
||||
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (sendBuffer, l), boost::asio::transfer_all (),
|
||||
boost::bind(&NTCPSession::HandleSent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, msg));
|
||||
std::bind(&NTCPSession::HandleSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msg));
|
||||
}
|
||||
|
||||
void NTCPSession::HandleSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, i2p::I2NPMessage * msg)
|
||||
@@ -549,7 +609,7 @@ namespace transport
|
||||
i2p::DeleteI2NPMessage (msg);
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Couldn't send msg: ", ecode.message ());
|
||||
LogPrint (eLogWarning, "Couldn't send msg: ", ecode.message ());
|
||||
// we shouldn't call Terminate () here, because HandleReceive takes care
|
||||
// TODO: 'delete this' statement in Terminate () must be eliminated later
|
||||
// Terminate ();
|
||||
@@ -581,8 +641,8 @@ namespace transport
|
||||
{
|
||||
m_TerminationTimer.cancel ();
|
||||
m_TerminationTimer.expires_from_now (boost::posix_time::seconds(NTCP_TERMINATION_TIMEOUT));
|
||||
m_TerminationTimer.async_wait (boost::bind (&NTCPSession::HandleTerminationTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_TerminationTimer.async_wait (std::bind (&NTCPSession::HandleTerminationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void NTCPSession::HandleTerminationTimer (const boost::system::error_code& ecode)
|
||||
@@ -594,47 +654,5 @@ namespace transport
|
||||
m_Socket.close ();// invoke Terminate () from HandleReceive
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
NTCPClient::NTCPClient (boost::asio::io_service& service, const boost::asio::ip::address& address,
|
||||
int port, std::shared_ptr<const i2p::data::RouterInfo> in_RouterInfo):
|
||||
NTCPSession (service, in_RouterInfo), m_Endpoint (address, port)
|
||||
{
|
||||
Connect ();
|
||||
}
|
||||
|
||||
void NTCPClient::Connect ()
|
||||
{
|
||||
LogPrint ("Connecting to ", m_Endpoint.address ().to_string (),":", m_Endpoint.port ());
|
||||
GetSocket ().async_connect (m_Endpoint, boost::bind (&NTCPClient::HandleConnect,
|
||||
this, boost::asio::placeholders::error));
|
||||
}
|
||||
|
||||
void NTCPClient::HandleConnect (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Connect error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
i2p::data::netdb.SetUnreachable (GetRemoteIdentity ().GetIdentHash (), true);
|
||||
Terminate ();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Connected");
|
||||
if (GetSocket ().local_endpoint ().protocol () == boost::asio::ip::tcp::v6()) // ipv6
|
||||
context.UpdateNTCPV6Address (GetSocket ().local_endpoint ().address ());
|
||||
ClientLogin ();
|
||||
}
|
||||
}
|
||||
|
||||
void NTCPServerConnection::Connected ()
|
||||
{
|
||||
LogPrint ("NTCP server session connected");
|
||||
transports.AddNTCPSession (this);
|
||||
NTCPSession::Connected ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <list>
|
||||
#include <boost/asio.hpp>
|
||||
#include <memory>
|
||||
#include <cryptopp/modes.h>
|
||||
#include <cryptopp/aes.h>
|
||||
#include <cryptopp/adler32.h>
|
||||
@@ -35,35 +35,21 @@ namespace transport
|
||||
uint8_t filler[12];
|
||||
} encrypted;
|
||||
};
|
||||
|
||||
struct NTCPPhase3
|
||||
{
|
||||
uint16_t size;
|
||||
i2p::data::Identity ident;
|
||||
uint32_t timestamp;
|
||||
uint8_t padding[15];
|
||||
uint8_t signature[40];
|
||||
};
|
||||
|
||||
|
||||
struct NTCPPhase4
|
||||
{
|
||||
uint8_t signature[40];
|
||||
uint8_t padding[8];
|
||||
};
|
||||
|
||||
#pragma pack()
|
||||
|
||||
const size_t NTCP_MAX_MESSAGE_SIZE = 16384;
|
||||
const size_t NTCP_BUFFER_SIZE = 1040; // fits one tunnel message (1028)
|
||||
const int NTCP_TERMINATION_TIMEOUT = 120; // 2 minutes
|
||||
const size_t NTCP_DEFAULT_PHASE3_SIZE = 2/*size*/ + i2p::data::DEFAULT_IDENTITY_SIZE/*387*/ + 4/*ts*/ + 15/*padding*/ + 40/*signature*/; // 448
|
||||
|
||||
class NTCPSession: public TransportSession
|
||||
class NTCPSession: public TransportSession, public std::enable_shared_from_this<NTCPSession>
|
||||
{
|
||||
public:
|
||||
|
||||
NTCPSession (boost::asio::io_service& service, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter = nullptr);
|
||||
~NTCPSession ();
|
||||
void Terminate ();
|
||||
|
||||
boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
|
||||
bool IsEstablished () const { return m_IsEstablished; };
|
||||
@@ -77,8 +63,7 @@ namespace transport
|
||||
|
||||
protected:
|
||||
|
||||
void Terminate ();
|
||||
virtual void Connected ();
|
||||
void Connected ();
|
||||
void SendTimeSyncMessage ();
|
||||
void SetIsEstablished (bool isEstablished) { m_IsEstablished = isEstablished; }
|
||||
|
||||
@@ -95,10 +80,12 @@ namespace transport
|
||||
|
||||
//server
|
||||
void SendPhase2 ();
|
||||
void SendPhase4 (uint32_t tsB);
|
||||
void SendPhase4 (uint32_t tsA, uint32_t tsB);
|
||||
void HandlePhase1Received (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandlePhase2Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB);
|
||||
void HandlePhase3Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB);
|
||||
void HandlePhase3ExtraReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB, size_t paddingLen);
|
||||
void HandlePhase3 (uint32_t tsB, size_t paddingLen);
|
||||
void HandlePhase4Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
|
||||
// common
|
||||
@@ -128,11 +115,10 @@ namespace transport
|
||||
{
|
||||
NTCPPhase1 phase1;
|
||||
NTCPPhase2 phase2;
|
||||
NTCPPhase3 phase3;
|
||||
NTCPPhase4 phase4;
|
||||
} * m_Establisher;
|
||||
|
||||
uint8_t m_ReceiveBuffer[NTCP_BUFFER_SIZE + 16], m_TimeSyncBuffer[16];
|
||||
i2p::crypto::AESAlignedBuffer<NTCP_BUFFER_SIZE + 16> m_ReceiveBuffer;
|
||||
i2p::crypto::AESAlignedBuffer<16> m_TimeSyncBuffer;
|
||||
int m_ReceiveBufferOffset;
|
||||
|
||||
i2p::I2NPMessage * m_NextMessage;
|
||||
@@ -141,34 +127,6 @@ namespace transport
|
||||
|
||||
size_t m_NumSentBytes, m_NumReceivedBytes;
|
||||
};
|
||||
|
||||
class NTCPClient: public NTCPSession
|
||||
{
|
||||
public:
|
||||
|
||||
NTCPClient (boost::asio::io_service& service, const boost::asio::ip::address& address, int port, std::shared_ptr<const i2p::data::RouterInfo> in_RouterInfo);
|
||||
|
||||
private:
|
||||
|
||||
void Connect ();
|
||||
void HandleConnect (const boost::system::error_code& ecode);
|
||||
|
||||
private:
|
||||
|
||||
boost::asio::ip::tcp::endpoint m_Endpoint;
|
||||
};
|
||||
|
||||
class NTCPServerConnection: public NTCPSession
|
||||
{
|
||||
public:
|
||||
|
||||
NTCPServerConnection (boost::asio::io_service& service):
|
||||
NTCPSession (service) {};
|
||||
|
||||
protected:
|
||||
|
||||
virtual void Connected ();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
230
NetDb.cpp
230
NetDb.cpp
@@ -1,3 +1,4 @@
|
||||
#include <string.h>
|
||||
#include "I2PEndian.h"
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
@@ -24,16 +25,9 @@ namespace data
|
||||
I2NPMessage * RequestedDestination::CreateRequestMessage (std::shared_ptr<const RouterInfo> router,
|
||||
const i2p::tunnel::InboundTunnel * replyTunnel)
|
||||
{
|
||||
I2NPMessage * msg = i2p::CreateDatabaseLookupMsg (m_Destination,
|
||||
I2NPMessage * msg = i2p::CreateRouterInfoDatabaseLookupMsg (m_Destination,
|
||||
replyTunnel->GetNextIdentHash (), replyTunnel->GetNextTunnelID (), m_IsExploratory,
|
||||
&m_ExcludedPeers, m_IsLeaseSet, m_Pool);
|
||||
if (m_IsLeaseSet) // wrap lookup message into garlic
|
||||
{
|
||||
if (m_Pool)
|
||||
msg = m_Pool->GetGarlicDestination ().WrapMessage (*router, msg);
|
||||
else
|
||||
LogPrint ("Can't create garlic message without destination");
|
||||
}
|
||||
&m_ExcludedPeers);
|
||||
m_ExcludedPeers.insert (router->GetIdentHash ());
|
||||
m_LastRouter = router;
|
||||
m_CreationTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
@@ -42,7 +36,7 @@ namespace data
|
||||
|
||||
I2NPMessage * RequestedDestination::CreateRequestMessage (const IdentHash& floodfill)
|
||||
{
|
||||
I2NPMessage * msg = i2p::CreateDatabaseLookupMsg (m_Destination,
|
||||
I2NPMessage * msg = i2p::CreateRouterInfoDatabaseLookupMsg (m_Destination,
|
||||
i2p::context.GetRouterInfo ().GetIdentHash () , 0, false, &m_ExcludedPeers);
|
||||
m_ExcludedPeers.insert (floodfill);
|
||||
m_LastRouter = nullptr;
|
||||
@@ -62,7 +56,7 @@ namespace data
|
||||
#endif
|
||||
NetDb netdb;
|
||||
|
||||
NetDb::NetDb (): m_IsRunning (false), m_ReseedRetries (0), m_Thread (0)
|
||||
NetDb::NetDb (): m_IsRunning (false), m_Thread (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -78,12 +72,27 @@ namespace data
|
||||
void NetDb::Start ()
|
||||
{
|
||||
Load (m_NetDbPath);
|
||||
while (m_RouterInfos.size () < 100 && m_ReseedRetries < 10)
|
||||
{
|
||||
if (m_RouterInfos.size () < 50) // reseed if # of router less than 50
|
||||
{
|
||||
Reseeder reseeder;
|
||||
reseeder.reseedNow();
|
||||
m_ReseedRetries++;
|
||||
Load (m_NetDbPath);
|
||||
reseeder.LoadCertificates (); // we need certificates for SU3 verification
|
||||
|
||||
// try SU3 first
|
||||
int reseedRetries = 0;
|
||||
while (m_RouterInfos.size () < 50 && reseedRetries < 10)
|
||||
{
|
||||
reseeder.ReseedNowSU3();
|
||||
reseedRetries++;
|
||||
}
|
||||
|
||||
// if still not enough download .dat files
|
||||
reseedRetries = 0;
|
||||
while (m_RouterInfos.size () < 50 && reseedRetries < 10)
|
||||
{
|
||||
reseeder.reseedNow();
|
||||
reseedRetries++;
|
||||
Load (m_NetDbPath);
|
||||
}
|
||||
}
|
||||
m_Thread = new std::thread (std::bind (&NetDb::Run, this));
|
||||
}
|
||||
@@ -113,7 +122,7 @@ namespace data
|
||||
{
|
||||
while (msg)
|
||||
{
|
||||
switch (msg->GetHeader ()->typeID)
|
||||
switch (msg->GetTypeID ())
|
||||
{
|
||||
case eI2NPDatabaseStore:
|
||||
LogPrint ("DatabaseStore");
|
||||
@@ -128,7 +137,7 @@ namespace data
|
||||
HandleDatabaseLookupMsg (msg);
|
||||
break;
|
||||
default: // WTF?
|
||||
LogPrint ("NetDb: unexpected message type ", msg->GetHeader ()->typeID);
|
||||
LogPrint ("NetDb: unexpected message type ", msg->GetTypeID ());
|
||||
i2p::HandleI2NPMessage (msg);
|
||||
}
|
||||
msg = m_Queue.Get ();
|
||||
@@ -138,6 +147,7 @@ namespace data
|
||||
{
|
||||
if (!m_IsRunning) break;
|
||||
// if no new DatabaseStore coming, explore it
|
||||
ManageRequests ();
|
||||
auto numRouters = m_RouterInfos.size ();
|
||||
Explore (numRouters < 1500 ? 5 : 1);
|
||||
}
|
||||
@@ -165,6 +175,13 @@ namespace data
|
||||
}
|
||||
}
|
||||
|
||||
void NetDb::AddRouterInfo (const uint8_t * buf, int len)
|
||||
{
|
||||
IdentityEx identity;
|
||||
if (identity.FromBuffer (buf, len))
|
||||
AddRouterInfo (identity.GetIdentHash (), buf, len);
|
||||
}
|
||||
|
||||
void NetDb::AddRouterInfo (const IdentHash& ident, const uint8_t * buf, int len)
|
||||
{
|
||||
DeleteRequestedDestination (ident);
|
||||
@@ -390,66 +407,37 @@ namespace data
|
||||
}
|
||||
}
|
||||
|
||||
void NetDb::RequestDestination (const IdentHash& destination, bool isLeaseSet, i2p::tunnel::TunnelPool * pool)
|
||||
void NetDb::RequestDestination (const IdentHash& destination)
|
||||
{
|
||||
if (isLeaseSet) // we request LeaseSet through tunnels
|
||||
{
|
||||
i2p::tunnel::OutboundTunnel * outbound = pool ? pool->GetNextOutboundTunnel () : i2p::tunnel::tunnels.GetNextOutboundTunnel ();
|
||||
if (outbound)
|
||||
{
|
||||
i2p::tunnel::InboundTunnel * inbound = pool ? pool->GetNextInboundTunnel () :i2p::tunnel::tunnels.GetNextInboundTunnel ();
|
||||
if (inbound)
|
||||
{
|
||||
RequestedDestination * dest = CreateRequestedDestination (destination, true, false, pool);
|
||||
auto floodfill = GetClosestFloodfill (destination, dest->GetExcludedPeers ());
|
||||
if (floodfill)
|
||||
{
|
||||
// DatabaseLookup message
|
||||
outbound->SendTunnelDataMsg (
|
||||
{
|
||||
i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
i2p::tunnel::eDeliveryTypeRouter,
|
||||
floodfill->GetIdentHash (), 0,
|
||||
dest->CreateRequestMessage (floodfill, inbound)
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
LogPrint ("No more floodfills found");
|
||||
}
|
||||
else
|
||||
LogPrint ("No inbound tunnels found");
|
||||
}
|
||||
else
|
||||
LogPrint ("No outbound tunnels found");
|
||||
}
|
||||
else // RouterInfo is requested directly
|
||||
// request RouterInfo directly
|
||||
RequestedDestination * dest = CreateRequestedDestination (destination, false);
|
||||
auto floodfill = GetClosestFloodfill (destination, dest->GetExcludedPeers ());
|
||||
if (floodfill)
|
||||
transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
|
||||
else
|
||||
{
|
||||
RequestedDestination * dest = CreateRequestedDestination (destination, false, false, pool);
|
||||
auto floodfill = GetClosestFloodfill (destination, dest->GetExcludedPeers ());
|
||||
if (floodfill)
|
||||
transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
|
||||
LogPrint (eLogError, "No floodfills found");
|
||||
DeleteRequestedDestination (dest);
|
||||
}
|
||||
}
|
||||
|
||||
void NetDb::HandleDatabaseStoreMsg (I2NPMessage * m)
|
||||
{
|
||||
const uint8_t * buf = m->GetPayload ();
|
||||
size_t len = be16toh (m->GetHeader ()->size);
|
||||
I2NPDatabaseStoreMsg * msg = (I2NPDatabaseStoreMsg *)buf;
|
||||
size_t offset = sizeof (I2NPDatabaseStoreMsg);
|
||||
if (msg->replyToken)
|
||||
size_t len = m->GetSize ();
|
||||
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
|
||||
size_t offset = DATABASE_STORE_HEADER_SIZE;
|
||||
if (replyToken)
|
||||
offset += 36;
|
||||
if (msg->type)
|
||||
if (buf[DATABASE_STORE_TYPE_OFFSET]) // type
|
||||
{
|
||||
LogPrint ("LeaseSet");
|
||||
AddLeaseSet (msg->key, buf + offset, len - offset, m->from);
|
||||
AddLeaseSet (buf + DATABASE_STORE_KEY_OFFSET, buf + offset, len - offset, m->from);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("RouterInfo");
|
||||
size_t size = be16toh (*(uint16_t *)(buf + offset));
|
||||
size_t size = bufbe16toh (buf + offset);
|
||||
if (size > 2048)
|
||||
{
|
||||
LogPrint ("Invalid RouterInfo length ", (int)size);
|
||||
@@ -462,7 +450,7 @@ namespace data
|
||||
uint8_t uncompressed[2048];
|
||||
size_t uncomressedSize = decompressor.MaxRetrievable ();
|
||||
decompressor.Get (uncompressed, uncomressedSize);
|
||||
AddRouterInfo (msg->key, uncompressed, uncomressedSize);
|
||||
AddRouterInfo (buf + DATABASE_STORE_KEY_OFFSET, uncompressed, uncomressedSize);
|
||||
}
|
||||
i2p::DeleteI2NPMessage (m);
|
||||
}
|
||||
@@ -482,9 +470,9 @@ namespace data
|
||||
bool deleteDest = true;
|
||||
if (num > 0)
|
||||
{
|
||||
auto pool = dest ? dest->GetTunnelPool () : nullptr;
|
||||
auto outbound = pool ? pool->GetNextOutboundTunnel () : i2p::tunnel::tunnels.GetNextOutboundTunnel ();
|
||||
auto inbound = pool ? pool->GetNextInboundTunnel () : i2p::tunnel::tunnels.GetNextInboundTunnel ();
|
||||
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
|
||||
auto outbound = pool->GetNextOutboundTunnel ();
|
||||
auto inbound = pool->GetNextInboundTunnel ();
|
||||
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
|
||||
if (!dest->IsExploratory ())
|
||||
{
|
||||
@@ -496,17 +484,14 @@ namespace data
|
||||
{
|
||||
auto nextFloodfill = GetClosestFloodfill (dest->GetDestination (), dest->GetExcludedPeers ());
|
||||
if (nextFloodfill)
|
||||
{
|
||||
if (!dest->IsLeaseSet ())
|
||||
{
|
||||
// tell floodfill about us
|
||||
msgs.push_back (i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
i2p::tunnel::eDeliveryTypeRouter,
|
||||
nextFloodfill->GetIdentHash (), 0,
|
||||
CreateDatabaseStoreMsg ()
|
||||
});
|
||||
}
|
||||
{
|
||||
// tell floodfill about us
|
||||
msgs.push_back (i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
i2p::tunnel::eDeliveryTypeRouter,
|
||||
nextFloodfill->GetIdentHash (), 0,
|
||||
CreateDatabaseStoreMsg ()
|
||||
});
|
||||
|
||||
// request destination
|
||||
LogPrint ("Try ", key, " at ", count, " floodfill ", nextFloodfill->GetIdentHash ().ToBase64 ());
|
||||
@@ -541,7 +526,7 @@ namespace data
|
||||
LogPrint ("Found new/outdated router. Requesting RouterInfo ...");
|
||||
if (outbound && inbound && dest->GetLastRouter ())
|
||||
{
|
||||
RequestedDestination * d1 = CreateRequestedDestination (router, false, false, pool);
|
||||
RequestedDestination * d1 = CreateRequestedDestination (router, false);
|
||||
auto msg = d1->CreateRequestMessage (dest->GetLastRouter (), inbound);
|
||||
msgs.push_back (i2p::tunnel::TunnelMessageBlock
|
||||
{
|
||||
@@ -550,7 +535,7 @@ namespace data
|
||||
});
|
||||
}
|
||||
else
|
||||
RequestDestination (router, false, pool);
|
||||
RequestDestination (router);
|
||||
}
|
||||
else
|
||||
LogPrint ("Bayan");
|
||||
@@ -563,7 +548,7 @@ namespace data
|
||||
{
|
||||
// request router
|
||||
LogPrint ("Found new floodfill. Request it");
|
||||
RequestDestination (router, false, pool);
|
||||
RequestDestination (router);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -613,10 +598,10 @@ namespace data
|
||||
uint32_t replyTunnelID = 0;
|
||||
if (flag & 0x01) //reply to tunnel
|
||||
{
|
||||
replyTunnelID = be32toh (*(uint32_t *)(buf + 64));
|
||||
replyTunnelID = bufbe32toh (buf + 64);
|
||||
excluded += 4;
|
||||
}
|
||||
uint16_t numExcluded = be16toh (*(uint16_t *)excluded);
|
||||
uint16_t numExcluded = bufbe16toh (excluded);
|
||||
excluded += 2;
|
||||
if (numExcluded > 512)
|
||||
{
|
||||
@@ -691,18 +676,6 @@ namespace data
|
||||
|
||||
void NetDb::Explore (int numDestinations)
|
||||
{
|
||||
// clean up previous exploratories
|
||||
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
for (auto it = m_RequestedDestinations.begin (); it != m_RequestedDestinations.end ();)
|
||||
{
|
||||
if (it->second->IsExploratory () || ts > it->second->GetCreationTime () + 60) // no response for 1 minute
|
||||
{
|
||||
delete it->second;
|
||||
it = m_RequestedDestinations.erase (it);
|
||||
}
|
||||
else
|
||||
it++;
|
||||
}
|
||||
// new requests
|
||||
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
|
||||
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : i2p::tunnel::tunnels.GetNextOutboundTunnel ();
|
||||
@@ -717,7 +690,7 @@ namespace data
|
||||
for (int i = 0; i < numDestinations; i++)
|
||||
{
|
||||
rnd.GenerateBlock (randomHash, 32);
|
||||
RequestedDestination * dest = CreateRequestedDestination (IdentHash (randomHash), false, true, exploratoryPool);
|
||||
RequestedDestination * dest = CreateRequestedDestination (IdentHash (randomHash), true);
|
||||
auto floodfill = GetClosestFloodfill (randomHash, dest->GetExcludedPeers ());
|
||||
if (floodfill && !floodfills.count (floodfill.get ())) // request floodfill only once
|
||||
{
|
||||
@@ -762,14 +735,13 @@ namespace data
|
||||
}
|
||||
}
|
||||
|
||||
RequestedDestination * NetDb::CreateRequestedDestination (const IdentHash& dest,
|
||||
bool isLeaseSet, bool isExploratory, i2p::tunnel::TunnelPool * pool)
|
||||
RequestedDestination * NetDb::CreateRequestedDestination (const IdentHash& dest, bool isExploratory)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_RequestedDestinationsMutex);
|
||||
auto it = m_RequestedDestinations.find (dest);
|
||||
if (it == m_RequestedDestinations.end ()) // not exist yet
|
||||
{
|
||||
RequestedDestination * d = new RequestedDestination (dest, isLeaseSet, isExploratory, pool);
|
||||
RequestedDestination * d = new RequestedDestination (dest, isExploratory);
|
||||
m_RequestedDestinations[dest] = d;
|
||||
return d;
|
||||
}
|
||||
@@ -897,25 +869,53 @@ namespace data
|
||||
}
|
||||
}
|
||||
|
||||
void NetDb::PublishLeaseSet (const LeaseSet * leaseSet, i2p::tunnel::TunnelPool * pool)
|
||||
void NetDb::ManageRequests ()
|
||||
{
|
||||
if (!leaseSet || !pool) return;
|
||||
auto outbound = pool->GetNextOutboundTunnel ();
|
||||
if (!outbound)
|
||||
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
for (auto it = m_RequestedDestinations.begin (); it != m_RequestedDestinations.end ();)
|
||||
{
|
||||
LogPrint ("Can't publish LeaseSet. No outbound tunnels");
|
||||
return;
|
||||
}
|
||||
std::set<IdentHash> excluded;
|
||||
auto floodfill = GetClosestFloodfill (leaseSet->GetIdentHash (), excluded);
|
||||
if (!floodfill)
|
||||
{
|
||||
LogPrint ("Can't publish LeaseSet. No floodfills found");
|
||||
return;
|
||||
auto dest = it->second;
|
||||
bool done = false;
|
||||
if (!dest->IsExploratory () && ts < dest->GetCreationTime () + 60) // request is worthless after 1 minute
|
||||
{
|
||||
if (ts > dest->GetCreationTime () + 5) // no response for 5 seconds
|
||||
{
|
||||
auto count = dest->GetExcludedPeers ().size ();
|
||||
if (count < 7)
|
||||
{
|
||||
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
|
||||
auto outbound = pool->GetNextOutboundTunnel ();
|
||||
auto inbound = pool->GetNextInboundTunnel ();
|
||||
auto nextFloodfill = GetClosestFloodfill (dest->GetDestination (), dest->GetExcludedPeers ());
|
||||
if (nextFloodfill && outbound && inbound)
|
||||
outbound->SendTunnelDataMsg (nextFloodfill->GetIdentHash (), 0,
|
||||
dest->CreateRequestMessage (nextFloodfill, inbound));
|
||||
else
|
||||
{
|
||||
done = true;
|
||||
if (!inbound) LogPrint (eLogWarning, "No inbound tunnels");
|
||||
if (!outbound) LogPrint (eLogWarning, "No outbound tunnels");
|
||||
if (!nextFloodfill) LogPrint (eLogWarning, "No more floodfills");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, dest->GetDestination ().ToBase64 (), " not found after 7 attempts");
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
else // delete previous exploratory
|
||||
done = true;
|
||||
|
||||
if (done)
|
||||
{
|
||||
delete it->second;
|
||||
it = m_RequestedDestinations.erase (it);
|
||||
}
|
||||
else
|
||||
it++;
|
||||
}
|
||||
uint32_t replyToken = i2p::context.GetRandomNumberGenerator ().GenerateWord32 ();
|
||||
auto msg = pool->GetGarlicDestination ().WrapMessage (*floodfill, i2p::CreateDatabaseStoreMsg (leaseSet, replyToken));
|
||||
outbound->SendTunnelDataMsg (floodfill->GetIdentHash (), 0, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
25
NetDb.h
25
NetDb.h
@@ -24,19 +24,15 @@ namespace data
|
||||
{
|
||||
public:
|
||||
|
||||
RequestedDestination (const IdentHash& destination, bool isLeaseSet,
|
||||
bool isExploratory = false, i2p::tunnel::TunnelPool * pool = nullptr):
|
||||
m_Destination (destination), m_IsLeaseSet (isLeaseSet), m_IsExploratory (isExploratory),
|
||||
m_Pool (pool), m_CreationTime (0) {};
|
||||
RequestedDestination (const IdentHash& destination, bool isExploratory = false):
|
||||
m_Destination (destination), m_IsExploratory (isExploratory), m_CreationTime (0) {};
|
||||
|
||||
const IdentHash& GetDestination () const { return m_Destination; };
|
||||
int GetNumExcludedPeers () const { return m_ExcludedPeers.size (); };
|
||||
const std::set<IdentHash>& GetExcludedPeers () { return m_ExcludedPeers; };
|
||||
void ClearExcludedPeers ();
|
||||
std::shared_ptr<const RouterInfo> GetLastRouter () const { return m_LastRouter; };
|
||||
i2p::tunnel::TunnelPool * GetTunnelPool () { return m_Pool; };
|
||||
bool IsExploratory () const { return m_IsExploratory; };
|
||||
bool IsLeaseSet () const { return m_IsLeaseSet; };
|
||||
bool IsExcluded (const IdentHash& ident) const { return m_ExcludedPeers.count (ident); };
|
||||
uint64_t GetCreationTime () const { return m_CreationTime; };
|
||||
I2NPMessage * CreateRequestMessage (std::shared_ptr<const RouterInfo>, const i2p::tunnel::InboundTunnel * replyTunnel);
|
||||
@@ -45,8 +41,7 @@ namespace data
|
||||
private:
|
||||
|
||||
IdentHash m_Destination;
|
||||
bool m_IsLeaseSet, m_IsExploratory;
|
||||
i2p::tunnel::TunnelPool * m_Pool;
|
||||
bool m_IsExploratory;
|
||||
std::set<IdentHash> m_ExcludedPeers;
|
||||
std::shared_ptr<const RouterInfo> m_LastRouter;
|
||||
uint64_t m_CreationTime;
|
||||
@@ -62,14 +57,13 @@ namespace data
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
void AddRouterInfo (const uint8_t * buf, int len);
|
||||
void AddRouterInfo (const IdentHash& ident, const uint8_t * buf, int len);
|
||||
void AddLeaseSet (const IdentHash& ident, const uint8_t * buf, int len, i2p::tunnel::InboundTunnel * from);
|
||||
std::shared_ptr<RouterInfo> FindRouter (const IdentHash& ident) const;
|
||||
LeaseSet * FindLeaseSet (const IdentHash& destination) const;
|
||||
|
||||
void PublishLeaseSet (const LeaseSet * leaseSet, i2p::tunnel::TunnelPool * pool);
|
||||
void RequestDestination (const IdentHash& destination, bool isLeaseSet = false,
|
||||
i2p::tunnel::TunnelPool * pool = nullptr);
|
||||
void RequestDestination (const IdentHash& destination);
|
||||
|
||||
void HandleDatabaseStoreMsg (I2NPMessage * msg);
|
||||
void HandleDatabaseSearchReplyMsg (I2NPMessage * msg);
|
||||
@@ -78,6 +72,7 @@ namespace data
|
||||
std::shared_ptr<const RouterInfo> GetRandomRouter () const;
|
||||
std::shared_ptr<const RouterInfo> GetRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const;
|
||||
std::shared_ptr<const RouterInfo> GetHighBandwidthRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const;
|
||||
std::shared_ptr<const RouterInfo> GetClosestFloodfill (const IdentHash& destination, const std::set<IdentHash>& excluded) const;
|
||||
void SetUnreachable (const IdentHash& ident, bool unreachable);
|
||||
|
||||
void PostI2NPMsg (I2NPMessage * msg);
|
||||
@@ -93,13 +88,12 @@ namespace data
|
||||
void Load (const char * directory);
|
||||
void SaveUpdated (const char * directory);
|
||||
void Run (); // exploratory thread
|
||||
void Explore (int numDestinations);
|
||||
void Explore (int numDestinations);
|
||||
void Publish ();
|
||||
std::shared_ptr<const RouterInfo> GetClosestFloodfill (const IdentHash& destination, const std::set<IdentHash>& excluded) const;
|
||||
void ManageLeaseSets ();
|
||||
void ManageRequests ();
|
||||
|
||||
RequestedDestination * CreateRequestedDestination (const IdentHash& dest,
|
||||
bool isLeaseSet, bool isExploratory = false, i2p::tunnel::TunnelPool * pool = nullptr);
|
||||
RequestedDestination * CreateRequestedDestination (const IdentHash& dest, bool isExploratory = false);
|
||||
bool DeleteRequestedDestination (const IdentHash& dest); // returns true if found
|
||||
void DeleteRequestedDestination (RequestedDestination * dest);
|
||||
|
||||
@@ -117,7 +111,6 @@ namespace data
|
||||
std::map<IdentHash, RequestedDestination *> m_RequestedDestinations;
|
||||
|
||||
bool m_IsRunning;
|
||||
int m_ReseedRetries;
|
||||
std::thread * m_Thread;
|
||||
i2p::util::Queue<I2NPMessage> m_Queue; // of I2NPDatabaseStoreMsg
|
||||
|
||||
|
||||
2
Queue.h
2
Queue.h
@@ -142,8 +142,8 @@ namespace util
|
||||
private:
|
||||
|
||||
volatile bool m_IsRunning;
|
||||
std::thread m_Thread;
|
||||
OnEmpty m_OnEmpty;
|
||||
std::thread m_Thread;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
22
README.md
22
README.md
@@ -21,7 +21,7 @@ Build Statuses
|
||||
|
||||
- Linux x64 - [](https://jenkins.nordcloud.no/job/i2pd-linux/)
|
||||
- Linux ARM - To be added
|
||||
- Mac OS X - To be added
|
||||
- Mac OS X - Got it working, but not well tested. (Only works with clang, not GCC.)
|
||||
- Microsoft VC13 - To be added
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@ This should resulting in for example:
|
||||
http://localhost:7070/4oes3rlgrpbkmzv4lqcfili23h3cvpwslqcfjlk6vvguxyggspwa.b32.i2p
|
||||
|
||||
|
||||
Options
|
||||
-------
|
||||
Cmdline options
|
||||
---------------
|
||||
|
||||
* --host= - The external IP
|
||||
* --port= - The port to listen on
|
||||
@@ -64,8 +64,22 @@ Options
|
||||
* --ircport= - The local port of IRC tunnel to listen on. 6668 by default
|
||||
* --ircdest= - I2P destination address of IRC server. For example irc.postman.i2p
|
||||
* --irckeys= - optional keys file for local destination
|
||||
* --eepkeys= - File name containing destination keys. For example privKeys.dat
|
||||
* --eepkeys= - File name containing destination keys, for example privKeys.dat.
|
||||
The file will be created if it does not already exist (issue #110).
|
||||
* --eephost= - Address incoming trafic forward to. 127.0.0.1 by default
|
||||
* --eepport= - Port incoming trafic forward to. 80 by default
|
||||
* --samport= - Port of SAM bridge. Usually 7656. SAM is off if not specified
|
||||
* --bobport= - Port of BOB command channel. Usually 2827. BOB is off if not specified
|
||||
* --conf= - Config file (default: ~/.i2pd/i2p.conf or /var/lib/i2pd/i2p.conf)
|
||||
This parameter will be silently ignored if the specified config file does not exist.
|
||||
Options specified on the command line take precedence over those in the config file.
|
||||
|
||||
Config file
|
||||
-----------
|
||||
|
||||
INI-like, syntax is the following : <key> = <value>.
|
||||
All command-line parameters are allowed as keys, for example:
|
||||
|
||||
log = 1
|
||||
v6 = 0
|
||||
ircdest = irc.postman.i2p
|
||||
|
||||
391
Reseed.cpp
391
Reseed.cpp
@@ -1,11 +1,19 @@
|
||||
#include <iostream>
|
||||
#include <string.h>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <boost/regex.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <cryptopp/gzip.h>
|
||||
#include <cryptopp/osrng.h>
|
||||
#include <cryptopp/asn.h>
|
||||
#include <cryptopp/base64.h>
|
||||
#include <cryptopp/crc.h>
|
||||
#include <cryptopp/zinflate.h>
|
||||
#include "I2PEndian.h"
|
||||
#include "Reseed.h"
|
||||
#include "Log.h"
|
||||
#include "Identity.h"
|
||||
#include "CryptoConst.h"
|
||||
#include "NetDb.h"
|
||||
#include "util.h"
|
||||
|
||||
|
||||
@@ -121,59 +129,374 @@ namespace data
|
||||
return false;
|
||||
}
|
||||
|
||||
void ProcessSU3File (const char * filename)
|
||||
int Reseeder::ReseedNowSU3 ()
|
||||
{
|
||||
static uint32_t headerSignature = htole32 (0x04044B50);
|
||||
CryptoPP::AutoSeededRandomPool rnd;
|
||||
auto ind = rnd.GenerateWord32 (0, httpReseedHostList.size() - 1);
|
||||
std::string reseedHost = httpReseedHostList[ind];
|
||||
return ReseedFromSU3 (reseedHost);
|
||||
}
|
||||
|
||||
int Reseeder::ReseedFromSU3 (const std::string& host)
|
||||
{
|
||||
std::string url = host + "i2pseeds.su3";
|
||||
LogPrint (eLogInfo, "Dowloading SU3 from ", host);
|
||||
std::string su3 = i2p::util::http::httpRequest (url);
|
||||
if (su3.length () > 0)
|
||||
{
|
||||
std::stringstream s(su3);
|
||||
return ProcessSU3Stream (s);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "SU3 download failed");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int Reseeder::ProcessSU3File (const char * filename)
|
||||
{
|
||||
std::ifstream s(filename, std::ifstream::binary);
|
||||
if (s.is_open ())
|
||||
{
|
||||
while (!s.eof ())
|
||||
return ProcessSU3Stream (s);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "Can't open file ", filename);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
const char SU3_MAGIC_NUMBER[]="I2Psu3";
|
||||
const uint32_t ZIP_HEADER_SIGNATURE = 0x04034B50;
|
||||
const uint32_t ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE = 0x02014B50;
|
||||
const uint16_t ZIP_BIT_FLAG_DATA_DESCRIPTOR = 0x0008;
|
||||
int Reseeder::ProcessSU3Stream (std::istream& s)
|
||||
{
|
||||
char magicNumber[7];
|
||||
s.read (magicNumber, 7); // magic number and zero byte 6
|
||||
if (strcmp (magicNumber, SU3_MAGIC_NUMBER))
|
||||
{
|
||||
LogPrint (eLogError, "Unexpected SU3 magic number");
|
||||
return 0;
|
||||
}
|
||||
s.seekg (1, std::ios::cur); // su3 file format version
|
||||
SigningKeyType signatureType;
|
||||
s.read ((char *)&signatureType, 2); // signature type
|
||||
signatureType = be16toh (signatureType);
|
||||
uint16_t signatureLength;
|
||||
s.read ((char *)&signatureLength, 2); // signature length
|
||||
signatureLength = be16toh (signatureLength);
|
||||
s.seekg (1, std::ios::cur); // unused
|
||||
uint8_t versionLength;
|
||||
s.read ((char *)&versionLength, 1); // version length
|
||||
s.seekg (1, std::ios::cur); // unused
|
||||
uint8_t signerIDLength;
|
||||
s.read ((char *)&signerIDLength, 1); // signer ID length
|
||||
uint64_t contentLength;
|
||||
s.read ((char *)&contentLength, 8); // content length
|
||||
contentLength = be64toh (contentLength);
|
||||
s.seekg (1, std::ios::cur); // unused
|
||||
uint8_t fileType;
|
||||
s.read ((char *)&fileType, 1); // file type
|
||||
if (fileType != 0x00) // zip file
|
||||
{
|
||||
LogPrint (eLogError, "Can't handle file type ", (int)fileType);
|
||||
return 0;
|
||||
}
|
||||
s.seekg (1, std::ios::cur); // unused
|
||||
uint8_t contentType;
|
||||
s.read ((char *)&contentType, 1); // content type
|
||||
if (contentType != 0x03) // reseed data
|
||||
{
|
||||
LogPrint (eLogError, "Unexpected content type ", (int)contentType);
|
||||
return 0;
|
||||
}
|
||||
s.seekg (12, std::ios::cur); // unused
|
||||
|
||||
s.seekg (versionLength, std::ios::cur); // skip version
|
||||
char signerID[256];
|
||||
s.read (signerID, signerIDLength); // signerID
|
||||
signerID[signerIDLength] = 0;
|
||||
|
||||
//try to verify signature
|
||||
auto it = m_SigningKeys.find (signerID);
|
||||
if (it != m_SigningKeys.end ())
|
||||
{
|
||||
// TODO: implement all signature types
|
||||
if (signatureType == SIGNING_KEY_TYPE_RSA_SHA512_4096)
|
||||
{
|
||||
uint32_t signature;
|
||||
s.read ((char *)&signature, 4);
|
||||
if (signature == headerSignature)
|
||||
size_t pos = s.tellg ();
|
||||
size_t tbsLen = pos + contentLength;
|
||||
uint8_t * tbs = new uint8_t[tbsLen];
|
||||
s.seekg (0, std::ios::beg);
|
||||
s.read ((char *)tbs, tbsLen);
|
||||
uint8_t * signature = new uint8_t[signatureLength];
|
||||
s.read ((char *)signature, signatureLength);
|
||||
// RSA-raw
|
||||
i2p::crypto::RSASHA5124096RawVerifier verifier(it->second);
|
||||
verifier.Update (tbs, tbsLen);
|
||||
if (!verifier.Verify (signature))
|
||||
LogPrint (eLogWarning, "SU3 signature verification failed");
|
||||
delete[] signature;
|
||||
delete[] tbs;
|
||||
s.seekg (pos, std::ios::beg);
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Signature type ", signatureType, " is not supported");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Certificate for ", signerID, " not loaded");
|
||||
|
||||
// handle content
|
||||
int numFiles = 0;
|
||||
size_t contentPos = s.tellg ();
|
||||
while (!s.eof ())
|
||||
{
|
||||
uint32_t signature;
|
||||
s.read ((char *)&signature, 4);
|
||||
signature = le32toh (signature);
|
||||
if (signature == ZIP_HEADER_SIGNATURE)
|
||||
{
|
||||
// next local file
|
||||
s.seekg (2, std::ios::cur); // version
|
||||
uint16_t bitFlag;
|
||||
s.read ((char *)&bitFlag, 2);
|
||||
bitFlag = le16toh (bitFlag);
|
||||
uint16_t compressionMethod;
|
||||
s.read ((char *)&compressionMethod, 2);
|
||||
compressionMethod = le16toh (compressionMethod);
|
||||
s.seekg (4, std::ios::cur); // skip fields we don't care about
|
||||
uint32_t crc32, compressedSize, uncompressedSize;
|
||||
s.read ((char *)&crc32, 4);
|
||||
crc32 = le32toh (crc32);
|
||||
s.read ((char *)&compressedSize, 4);
|
||||
compressedSize = le32toh (compressedSize);
|
||||
s.read ((char *)&uncompressedSize, 4);
|
||||
uncompressedSize = le32toh (uncompressedSize);
|
||||
uint16_t fileNameLength, extraFieldLength;
|
||||
s.read ((char *)&fileNameLength, 2);
|
||||
fileNameLength = le16toh (fileNameLength);
|
||||
s.read ((char *)&extraFieldLength, 2);
|
||||
extraFieldLength = le16toh (extraFieldLength);
|
||||
char localFileName[255];
|
||||
s.read (localFileName, fileNameLength);
|
||||
localFileName[fileNameLength] = 0;
|
||||
s.seekg (extraFieldLength, std::ios::cur);
|
||||
// take care about data desriptor if presented
|
||||
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
|
||||
{
|
||||
// next local file
|
||||
s.seekg (14, std::ios::cur); // skip field we don't care about
|
||||
uint32_t compressedSize, uncompressedSize;
|
||||
size_t pos = s.tellg ();
|
||||
if (!FindZipDataDescriptor (s))
|
||||
{
|
||||
LogPrint (eLogError, "SU3 archive data descriptor not found");
|
||||
return numFiles;
|
||||
}
|
||||
|
||||
s.read ((char *)&crc32, 4);
|
||||
crc32 = le32toh (crc32);
|
||||
s.read ((char *)&compressedSize, 4);
|
||||
compressedSize = le32toh (compressedSize);
|
||||
compressedSize = le32toh (compressedSize) + 4; // ??? we must consider signature as part of compressed data
|
||||
s.read ((char *)&uncompressedSize, 4);
|
||||
uncompressedSize = le32toh (uncompressedSize);
|
||||
uint16_t fileNameLength, extraFieldLength;
|
||||
s.read ((char *)&fileNameLength, 2);
|
||||
fileNameLength = le32toh (fileNameLength);
|
||||
s.read ((char *)&extraFieldLength, 2);
|
||||
extraFieldLength = le32toh (extraFieldLength);
|
||||
char localFileName[255];
|
||||
s.read (localFileName, fileNameLength);
|
||||
localFileName[fileNameLength] = 0;
|
||||
s.seekg (extraFieldLength, std::ios::cur);
|
||||
|
||||
uint8_t * compressed = new uint8_t[compressedSize];
|
||||
s.read ((char *)compressed, compressedSize);
|
||||
CryptoPP::Gunzip decompressor;
|
||||
decompressor.Put (compressed, compressedSize);
|
||||
delete[] compressed;
|
||||
// now we know compressed and uncompressed size
|
||||
s.seekg (pos, std::ios::beg); // back to compressed data
|
||||
}
|
||||
|
||||
LogPrint (eLogDebug, "Proccessing file ", localFileName, " ", compressedSize, " bytes");
|
||||
if (!compressedSize)
|
||||
{
|
||||
LogPrint (eLogWarning, "Unexpected size 0. Skipped");
|
||||
continue;
|
||||
}
|
||||
|
||||
uint8_t * compressed = new uint8_t[compressedSize];
|
||||
s.read ((char *)compressed, compressedSize);
|
||||
if (compressionMethod) // we assume Deflate
|
||||
{
|
||||
CryptoPP::Inflator decompressor;
|
||||
decompressor.Put (compressed, compressedSize);
|
||||
decompressor.MessageEnd();
|
||||
if (decompressor.MaxRetrievable () <= uncompressedSize)
|
||||
{
|
||||
uint8_t * uncompressed = new uint8_t[uncompressedSize];
|
||||
decompressor.Get (uncompressed, decompressor.MaxRetrievable ());
|
||||
// TODO: save file
|
||||
decompressor.Get (uncompressed, uncompressedSize);
|
||||
if (CryptoPP::CRC32().VerifyDigest ((uint8_t *)&crc32, uncompressed, uncompressedSize))
|
||||
{
|
||||
i2p::data::netdb.AddRouterInfo (uncompressed, uncompressedSize);
|
||||
numFiles++;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "CRC32 verification failed");
|
||||
delete[] uncompressed;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Actual uncompressed size ", decompressor.MaxRetrievable (), " exceed ", uncompressedSize, " from header");
|
||||
}
|
||||
else
|
||||
break; // no more files
|
||||
}
|
||||
else // no compression
|
||||
{
|
||||
i2p::data::netdb.AddRouterInfo (compressed, compressedSize);
|
||||
numFiles++;
|
||||
}
|
||||
delete[] compressed;
|
||||
if (bitFlag & ZIP_BIT_FLAG_DATA_DESCRIPTOR)
|
||||
s.seekg (12, std::ios::cur); // skip data descriptor section if presented (12 = 16 - 4)
|
||||
}
|
||||
else
|
||||
{
|
||||
if (signature != ZIP_CENTRAL_DIRECTORY_HEADER_SIGNATURE)
|
||||
LogPrint (eLogWarning, "Missing zip central directory header");
|
||||
break; // no more files
|
||||
}
|
||||
size_t end = s.tellg ();
|
||||
if (end - contentPos >= contentLength)
|
||||
break; // we are beyond contentLength
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Can't open file ", filename);
|
||||
return numFiles;
|
||||
}
|
||||
|
||||
const uint8_t ZIP_DATA_DESCRIPTOR_SIGNATURE[] = { 0x50, 0x4B, 0x07, 0x08 };
|
||||
bool Reseeder::FindZipDataDescriptor (std::istream& s)
|
||||
{
|
||||
size_t nextInd = 0;
|
||||
while (!s.eof ())
|
||||
{
|
||||
uint8_t nextByte;
|
||||
s.read ((char *)&nextByte, 1);
|
||||
if (nextByte == ZIP_DATA_DESCRIPTOR_SIGNATURE[nextInd])
|
||||
{
|
||||
nextInd++;
|
||||
if (nextInd >= sizeof (ZIP_DATA_DESCRIPTOR_SIGNATURE))
|
||||
return true;
|
||||
}
|
||||
else
|
||||
nextInd = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const char CERTIFICATE_HEADER[] = "-----BEGIN CERTIFICATE-----";
|
||||
const char CERTIFICATE_FOOTER[] = "-----END CERTIFICATE-----";
|
||||
void Reseeder::LoadCertificate (const std::string& filename)
|
||||
{
|
||||
std::ifstream s(filename, std::ifstream::binary);
|
||||
if (s.is_open ())
|
||||
{
|
||||
s.seekg (0, std::ios::end);
|
||||
size_t len = s.tellg ();
|
||||
s.seekg (0, std::ios::beg);
|
||||
char buf[2048];
|
||||
s.read (buf, len);
|
||||
std::string cert (buf, len);
|
||||
// assume file in pem format
|
||||
auto pos1 = cert.find (CERTIFICATE_HEADER);
|
||||
auto pos2 = cert.find (CERTIFICATE_FOOTER);
|
||||
if (pos1 == std::string::npos || pos2 == std::string::npos)
|
||||
{
|
||||
LogPrint (eLogError, "Malformed certificate file");
|
||||
return;
|
||||
}
|
||||
pos1 += strlen (CERTIFICATE_HEADER);
|
||||
pos2 -= pos1;
|
||||
std::string base64 = cert.substr (pos1, pos2);
|
||||
|
||||
CryptoPP::ByteQueue queue;
|
||||
CryptoPP::Base64Decoder decoder; // regular base64 rather than I2P
|
||||
decoder.Attach (new CryptoPP::Redirector (queue));
|
||||
decoder.Put ((const uint8_t *)base64.data(), base64.length());
|
||||
decoder.MessageEnd ();
|
||||
|
||||
// extract X.509
|
||||
CryptoPP::BERSequenceDecoder x509Cert (queue);
|
||||
CryptoPP::BERSequenceDecoder tbsCert (x509Cert);
|
||||
// version
|
||||
uint32_t ver;
|
||||
CryptoPP::BERGeneralDecoder context (tbsCert, CryptoPP::CONTEXT_SPECIFIC | CryptoPP::CONSTRUCTED);
|
||||
CryptoPP::BERDecodeUnsigned<uint32_t>(context, ver, CryptoPP::INTEGER);
|
||||
// serial
|
||||
CryptoPP::Integer serial;
|
||||
serial.BERDecode(tbsCert);
|
||||
// signature
|
||||
CryptoPP::BERSequenceDecoder signature (tbsCert);
|
||||
signature.SkipAll();
|
||||
|
||||
// issuer
|
||||
std::string name;
|
||||
CryptoPP::BERSequenceDecoder issuer (tbsCert);
|
||||
{
|
||||
CryptoPP::BERSetDecoder c (issuer); c.SkipAll();
|
||||
CryptoPP::BERSetDecoder st (issuer); st.SkipAll();
|
||||
CryptoPP::BERSetDecoder l (issuer); l.SkipAll();
|
||||
CryptoPP::BERSetDecoder o (issuer); o.SkipAll();
|
||||
CryptoPP::BERSetDecoder ou (issuer); ou.SkipAll();
|
||||
CryptoPP::BERSetDecoder cn (issuer);
|
||||
{
|
||||
CryptoPP::BERSequenceDecoder attributes (cn);
|
||||
{
|
||||
CryptoPP::BERGeneralDecoder ident(attributes, CryptoPP::OBJECT_IDENTIFIER);
|
||||
ident.SkipAll ();
|
||||
CryptoPP::BERDecodeTextString (attributes, name, CryptoPP::UTF8_STRING);
|
||||
}
|
||||
}
|
||||
}
|
||||
issuer.SkipAll();
|
||||
// validity
|
||||
CryptoPP::BERSequenceDecoder validity (tbsCert);
|
||||
validity.SkipAll();
|
||||
// subject
|
||||
CryptoPP::BERSequenceDecoder subject (tbsCert);
|
||||
subject.SkipAll();
|
||||
// public key
|
||||
CryptoPP::BERSequenceDecoder publicKey (tbsCert);
|
||||
{
|
||||
CryptoPP::BERSequenceDecoder ident (publicKey);
|
||||
ident.SkipAll ();
|
||||
CryptoPP::BERGeneralDecoder key (publicKey, CryptoPP::BIT_STRING);
|
||||
key.Skip (1); // FIXME: probably bug in crypto++
|
||||
CryptoPP::BERSequenceDecoder keyPair (key);
|
||||
CryptoPP::Integer n;
|
||||
n.BERDecode (keyPair);
|
||||
if (name.length () > 0)
|
||||
{
|
||||
PublicKey value;
|
||||
n.Encode (value, 512);
|
||||
m_SigningKeys[name] = value;
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Unknown issuer. Skipped");
|
||||
}
|
||||
publicKey.SkipAll();
|
||||
|
||||
tbsCert.SkipAll();
|
||||
x509Cert.SkipAll();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Can't open certificate file ", filename);
|
||||
}
|
||||
|
||||
void Reseeder::LoadCertificates ()
|
||||
{
|
||||
boost::filesystem::path reseedDir = i2p::util::filesystem::GetCertificatesDir() / "reseed";
|
||||
|
||||
if (!boost::filesystem::exists (reseedDir))
|
||||
{
|
||||
LogPrint (eLogWarning, "Reseed certificates not loaded. ", reseedDir, " doesn't exist");
|
||||
return;
|
||||
}
|
||||
|
||||
int numCertificates = 0;
|
||||
boost::filesystem::directory_iterator end; // empty
|
||||
for (boost::filesystem::directory_iterator it (reseedDir); it != end; ++it)
|
||||
{
|
||||
if (boost::filesystem::is_regular_file (it->status()) && it->path ().extension () == ".crt")
|
||||
{
|
||||
LoadCertificate (it->path ().string ());
|
||||
numCertificates++;
|
||||
}
|
||||
}
|
||||
LogPrint (eLogInfo, numCertificates, " certificates loaded");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
27
Reseed.h
27
Reseed.h
@@ -1,8 +1,11 @@
|
||||
#ifndef RESEED_H
|
||||
#define RESEED_H
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "Identity.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
@@ -11,13 +14,31 @@ namespace data
|
||||
|
||||
class Reseeder
|
||||
{
|
||||
typedef Tag<512> PublicKey;
|
||||
|
||||
public:
|
||||
|
||||
Reseeder();
|
||||
~Reseeder();
|
||||
bool reseedNow();
|
||||
};
|
||||
bool reseedNow(); // depreacted
|
||||
int ReseedNowSU3 ();
|
||||
|
||||
void ProcessSU3File (const char * filename);
|
||||
void LoadCertificates ();
|
||||
|
||||
private:
|
||||
|
||||
void LoadCertificate (const std::string& filename);
|
||||
|
||||
int ReseedFromSU3 (const std::string& host);
|
||||
int ProcessSU3File (const char * filename);
|
||||
int ProcessSU3Stream (std::istream& s);
|
||||
|
||||
bool FindZipDataDescriptor (std::istream& s);
|
||||
|
||||
private:
|
||||
|
||||
std::map<std::string, PublicKey> m_SigningKeys;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,8 +101,12 @@ namespace data
|
||||
{
|
||||
// verify signature
|
||||
int l = m_BufferLen - m_RouterIdentity.GetSignatureLen ();
|
||||
if (!m_RouterIdentity.Verify ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l))
|
||||
LogPrint (eLogError, "signature verification failed");
|
||||
if (!m_RouterIdentity.Verify ((uint8_t *)m_Buffer, l, (uint8_t *)m_Buffer + l))
|
||||
{
|
||||
LogPrint (eLogError, "signature verification failed");
|
||||
m_IsUnreachable = true;
|
||||
}
|
||||
m_RouterIdentity.DropVerifier ();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
308
SAM.cpp
308
SAM.cpp
@@ -3,11 +3,10 @@
|
||||
#ifdef _MSC_VER
|
||||
#include <stdlib.h>
|
||||
#endif
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "base64.h"
|
||||
#include "Identity.h"
|
||||
#include "Log.h"
|
||||
#include "NetDb.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "SAM.h"
|
||||
@@ -25,18 +24,21 @@ namespace client
|
||||
|
||||
SAMSocket::~SAMSocket ()
|
||||
{
|
||||
if (m_Stream)
|
||||
i2p::stream::DeleteStream (m_Stream);
|
||||
Terminate ();
|
||||
}
|
||||
|
||||
void SAMSocket::Terminate ()
|
||||
void SAMSocket::CloseStream ()
|
||||
{
|
||||
if (m_Stream)
|
||||
{
|
||||
m_Stream->Close ();
|
||||
|
||||
// TODO: make this swap atomic
|
||||
auto session = m_Session;
|
||||
m_Session = nullptr;
|
||||
m_Stream.reset ();
|
||||
}
|
||||
}
|
||||
|
||||
void SAMSocket::Terminate ()
|
||||
{
|
||||
CloseStream ();
|
||||
|
||||
switch (m_SocketType)
|
||||
{
|
||||
@@ -45,30 +47,31 @@ namespace client
|
||||
break;
|
||||
case eSAMSocketTypeStream:
|
||||
{
|
||||
if (session)
|
||||
session->sockets.remove (shared_from_this ());
|
||||
if (m_Session)
|
||||
m_Session->sockets.remove (shared_from_this ());
|
||||
break;
|
||||
}
|
||||
case eSAMSocketTypeAcceptor:
|
||||
{
|
||||
if (session)
|
||||
if (m_Session)
|
||||
{
|
||||
session->sockets.remove (shared_from_this ());
|
||||
session->localDestination->StopAcceptingStreams ();
|
||||
m_Session->sockets.remove (shared_from_this ());
|
||||
m_Session->localDestination->StopAcceptingStreams ();
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
;
|
||||
}
|
||||
m_SocketType = eSAMSocketTypeTerminated;
|
||||
m_Socket.close ();
|
||||
}
|
||||
|
||||
void SAMSocket::ReceiveHandshake ()
|
||||
{
|
||||
m_Socket.async_read_some (boost::asio::buffer(m_Buffer, SAM_SOCKET_BUFFER_SIZE),
|
||||
boost::bind(&SAMSocket::HandleHandshakeReceived, shared_from_this (),
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&SAMSocket::HandleHandshakeReceived, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void SAMSocket::HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
@@ -83,12 +86,41 @@ namespace client
|
||||
{
|
||||
m_Buffer[bytes_transferred] = 0;
|
||||
LogPrint ("SAM handshake ", m_Buffer);
|
||||
if (!memcmp (m_Buffer, SAM_HANDSHAKE, strlen (SAM_HANDSHAKE)))
|
||||
char * separator = strchr (m_Buffer, ' ');
|
||||
if (separator)
|
||||
{
|
||||
// TODO: check version
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (SAM_HANDSHAKE_REPLY, strlen (SAM_HANDSHAKE_REPLY)), boost::asio::transfer_all (),
|
||||
boost::bind(&SAMSocket::HandleHandshakeReplySent, shared_from_this (),
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
separator = strchr (separator + 1, ' ');
|
||||
if (separator)
|
||||
*separator = 0;
|
||||
}
|
||||
|
||||
if (!strcmp (m_Buffer, SAM_HANDSHAKE))
|
||||
{
|
||||
std::string version("3.0");
|
||||
// try to find MIN and MAX, 3.0 if not found
|
||||
if (separator)
|
||||
{
|
||||
separator++;
|
||||
std::map<std::string, std::string> params;
|
||||
ExtractParams (separator, bytes_transferred - (separator - m_Buffer), params);
|
||||
auto it = params.find (SAM_PARAM_MAX);
|
||||
// TODO: check MIN as well
|
||||
if (it != params.end ())
|
||||
version = it->second;
|
||||
}
|
||||
if (version[0] == '3') // we support v3 (3.0 and 3.1) only
|
||||
{
|
||||
#ifdef _MSC_VER
|
||||
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
|
||||
#else
|
||||
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
|
||||
#endif
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Buffer, l), boost::asio::transfer_all (),
|
||||
std::bind(&SAMSocket::HandleHandshakeReplySent, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
else
|
||||
SendMessageReply (SAM_HANDSHAKE_I2P_ERROR, strlen (SAM_HANDSHAKE_I2P_ERROR), true);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -109,8 +141,8 @@ namespace client
|
||||
else
|
||||
{
|
||||
m_Socket.async_read_some (boost::asio::buffer(m_Buffer, SAM_SOCKET_BUFFER_SIZE),
|
||||
boost::bind(&SAMSocket::HandleMessage, shared_from_this (),
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind(&SAMSocket::HandleMessage, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,8 +150,8 @@ namespace client
|
||||
{
|
||||
if (!m_IsSilent || m_SocketType == eSAMSocketTypeAcceptor)
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (msg, len), boost::asio::transfer_all (),
|
||||
boost::bind(&SAMSocket::HandleMessageReplySent, shared_from_this (),
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, close));
|
||||
std::bind(&SAMSocket::HandleMessageReplySent, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2, close));
|
||||
else
|
||||
{
|
||||
if (close)
|
||||
@@ -208,14 +240,16 @@ namespace client
|
||||
std::string& style = params[SAM_PARAM_STYLE];
|
||||
std::string& id = params[SAM_PARAM_ID];
|
||||
std::string& destination = params[SAM_PARAM_DESTINATION];
|
||||
m_ID = id;
|
||||
m_ID = id;
|
||||
if (m_Owner.FindSession (id))
|
||||
{
|
||||
// session exists
|
||||
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, strlen(SAM_SESSION_CREATE_DUPLICATED_ID), true);
|
||||
return;
|
||||
}
|
||||
m_Session = m_Owner.CreateSession (id, destination == SAM_VALUE_TRANSIENT ? "" : destination);
|
||||
|
||||
// create destination
|
||||
m_Session = m_Owner.CreateSession (id, destination == SAM_VALUE_TRANSIENT ? "" : destination, ¶ms);
|
||||
if (m_Session)
|
||||
{
|
||||
m_SocketType = eSAMSocketTypeSession;
|
||||
@@ -232,8 +266,8 @@ namespace client
|
||||
else
|
||||
{
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_SESSION_READINESS_CHECK_INTERVAL));
|
||||
m_Timer.async_wait (boost::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
|
||||
shared_from_this (), boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -249,8 +283,8 @@ namespace client
|
||||
else
|
||||
{
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_SESSION_READINESS_CHECK_INTERVAL));
|
||||
m_Timer.async_wait (boost::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
|
||||
shared_from_this (), boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SAMSocket::HandleSessionReadinessCheckTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -283,19 +317,17 @@ namespace client
|
||||
m_Session = m_Owner.FindSession (id);
|
||||
if (m_Session)
|
||||
{
|
||||
uint8_t ident[1024];
|
||||
size_t l = i2p::data::Base64ToByteStream (destination.c_str (), destination.length (), ident, 1024);
|
||||
i2p::data::IdentityEx dest;
|
||||
dest.FromBuffer (ident, l);
|
||||
dest.FromBase64 (destination);
|
||||
context.GetAddressBook ().InsertAddress (dest);
|
||||
auto leaseSet = i2p::data::netdb.FindLeaseSet (dest.GetIdentHash ());
|
||||
if (leaseSet)
|
||||
Connect (*leaseSet);
|
||||
else
|
||||
{
|
||||
i2p::data::netdb.RequestDestination (dest.GetIdentHash (), true, m_Session->localDestination->GetTunnelPool ());
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_CONNECT_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SAMSocket::HandleStreamDestinationRequestTimer,
|
||||
shared_from_this (), boost::asio::placeholders::error, dest.GetIdentHash ()));
|
||||
m_Session->localDestination->RequestDestination (dest.GetIdentHash (),
|
||||
std::bind (&SAMSocket::HandleLeaseSetRequestComplete,
|
||||
shared_from_this (), std::placeholders::_1, dest.GetIdentHash ()));
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -312,38 +344,17 @@ namespace client
|
||||
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false);
|
||||
}
|
||||
|
||||
void SAMSocket::HandleStreamDestinationRequestTimer (const boost::system::error_code& ecode, i2p::data::IdentHash ident)
|
||||
void SAMSocket::HandleLeaseSetRequestComplete (bool success, i2p::data::IdentHash ident)
|
||||
{
|
||||
if (!ecode) // timeout expired
|
||||
const i2p::data::LeaseSet * leaseSet = nullptr;
|
||||
if (success) // timeout expired
|
||||
leaseSet = m_Session->localDestination->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
Connect (*leaseSet);
|
||||
else
|
||||
{
|
||||
auto leaseSet = m_Session->localDestination->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
Connect (*leaseSet);
|
||||
else
|
||||
{
|
||||
LogPrint ("SAM destination to connect not found");
|
||||
SendMessageReply (SAM_STREAM_STATUS_CANT_REACH_PEER, strlen(SAM_STREAM_STATUS_CANT_REACH_PEER), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SAMSocket::HandleNamingLookupDestinationRequestTimer (const boost::system::error_code& ecode, i2p::data::IdentHash ident)
|
||||
{
|
||||
if (!ecode) // timeout expired
|
||||
{
|
||||
auto leaseSet = m_Session->localDestination->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
SendNamingLookupReply (leaseSet);
|
||||
else
|
||||
{
|
||||
LogPrint ("SAM name destination not found");
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_KEY_NOT_FOUND, (ident.ToBase32 () + ".b32.i2p").c_str ());
|
||||
#else
|
||||
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_KEY_NOT_FOUND, (ident.ToBase32 () + ".b32.i2p").c_str ());
|
||||
#endif
|
||||
SendMessageReply (m_Buffer, len, false);
|
||||
}
|
||||
LogPrint ("SAM destination to connect not found");
|
||||
SendMessageReply (SAM_STREAM_STATUS_CANT_REACH_PEER, strlen(SAM_STREAM_STATUS_CANT_REACH_PEER), true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,19 +390,12 @@ namespace client
|
||||
auto localDestination = i2p::client::context.CreateNewLocalDestination ();
|
||||
if (localDestination)
|
||||
{
|
||||
uint8_t buf[1024];
|
||||
char priv[1024], pub[1024];
|
||||
size_t l = localDestination->GetPrivateKeys ().ToBuffer (buf, 1024);
|
||||
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, priv, 1024);
|
||||
priv[l1] = 0;
|
||||
|
||||
l = localDestination->GetIdentity ().ToBuffer (buf, 1024);
|
||||
l1 = i2p::data::ByteStreamToBase64 (buf, l, pub, 1024);
|
||||
pub[l1] = 0;
|
||||
auto priv = localDestination->GetPrivateKeys ().ToBase64 ();
|
||||
auto pub = localDestination->GetIdentity ().ToBase64 ();
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY, pub, priv);
|
||||
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY, pub.c_str (), priv.c_str ());
|
||||
#else
|
||||
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY, pub, priv);
|
||||
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY, pub.c_str (), priv.c_str ());
|
||||
#endif
|
||||
SendMessageReply (m_Buffer, len, true);
|
||||
}
|
||||
@@ -406,22 +410,12 @@ namespace client
|
||||
ExtractParams (buf, len, params);
|
||||
std::string& name = params[SAM_PARAM_NAME];
|
||||
i2p::data::IdentHash ident;
|
||||
i2p::data::IdentityEx identity;
|
||||
if (name == "ME")
|
||||
SendNamingLookupReply (nullptr);
|
||||
else if (m_Session && context.GetAddressBook ().GetIdentHash (name, ident))
|
||||
{
|
||||
auto leaseSet = m_Session->localDestination->FindLeaseSet (ident);
|
||||
if (leaseSet)
|
||||
SendNamingLookupReply (leaseSet);
|
||||
else
|
||||
{
|
||||
i2p::data::netdb.RequestDestination (ident, true, m_Session->localDestination->GetTunnelPool ());
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SAM_NAMING_LOOKUP_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SAMSocket::HandleNamingLookupDestinationRequestTimer,
|
||||
shared_from_this (), boost::asio::placeholders::error, ident));
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (context.GetAddressBook ().GetAddress (name, identity))
|
||||
SendNamingLookupReply (identity);
|
||||
else
|
||||
{
|
||||
#ifdef _MSC_VER
|
||||
size_t len = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
|
||||
@@ -434,18 +428,22 @@ namespace client
|
||||
|
||||
void SAMSocket::SendNamingLookupReply (const i2p::data::LeaseSet * leaseSet)
|
||||
{
|
||||
uint8_t buf[1024];
|
||||
char pub[1024];
|
||||
const i2p::data::IdentityEx& identity = leaseSet ? leaseSet->GetIdentity () : m_Session->localDestination->GetIdentity ();
|
||||
size_t l = identity.ToBuffer (buf, 1024);
|
||||
size_t l1 = i2p::data::ByteStreamToBase64 (buf, l, pub, 1024);
|
||||
pub[l1] = 0;
|
||||
if (leaseSet)
|
||||
// we found LeaseSet for our address, store it to addressbook
|
||||
context.GetAddressBook ().InsertAddress (identity);
|
||||
SendNamingLookupReply (identity);
|
||||
}
|
||||
|
||||
void SAMSocket::SendNamingLookupReply (const i2p::data::IdentityEx& identity)
|
||||
{
|
||||
auto base64 = identity.ToBase64 ();
|
||||
#ifdef _MSC_VER
|
||||
size_t l2 = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, pub);
|
||||
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, base64.c_str ());
|
||||
#else
|
||||
size_t l2 = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, pub);
|
||||
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, base64.c_str ());
|
||||
#endif
|
||||
SendMessageReply (m_Buffer, l2, false);
|
||||
SendMessageReply (m_Buffer, l, false);
|
||||
}
|
||||
|
||||
void SAMSocket::ExtractParams (char * buf, size_t len, std::map<std::string, std::string>& params)
|
||||
@@ -470,8 +468,8 @@ namespace client
|
||||
void SAMSocket::Receive ()
|
||||
{
|
||||
m_Socket.async_read_some (boost::asio::buffer(m_Buffer, SAM_SOCKET_BUFFER_SIZE),
|
||||
boost::bind((m_SocketType == eSAMSocketTypeSession) ? &SAMSocket::HandleMessage : &SAMSocket::HandleReceived,
|
||||
shared_from_this (), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind((m_SocketType == eSAMSocketTypeSession) ? &SAMSocket::HandleMessage : &SAMSocket::HandleReceived,
|
||||
shared_from_this (), std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void SAMSocket::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
@@ -494,8 +492,8 @@ namespace client
|
||||
{
|
||||
if (m_Stream)
|
||||
m_Stream->AsyncReceive (boost::asio::buffer (m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE),
|
||||
boost::bind (&SAMSocket::HandleI2PReceive, shared_from_this (),
|
||||
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred),
|
||||
std::bind (&SAMSocket::HandleI2PReceive, shared_from_this (),
|
||||
std::placeholders::_1, std::placeholders::_2),
|
||||
SAM_SOCKET_CONNECTION_MAX_IDLE);
|
||||
}
|
||||
|
||||
@@ -510,7 +508,7 @@ namespace client
|
||||
else
|
||||
{
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, bytes_transferred),
|
||||
boost::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), boost::asio::placeholders::error));
|
||||
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,12 +524,13 @@ namespace client
|
||||
I2PReceive ();
|
||||
}
|
||||
|
||||
void SAMSocket::HandleI2PAccept (i2p::stream::Stream * stream)
|
||||
void SAMSocket::HandleI2PAccept (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
LogPrint ("SAM incoming I2P connection for session ", m_ID);
|
||||
m_Stream = stream;
|
||||
context.GetAddressBook ().InsertAddress (stream->GetRemoteIdentity ());
|
||||
auto session = m_Owner.FindSession (m_ID);
|
||||
if (session)
|
||||
session->localDestination->StopAcceptingStreams ();
|
||||
@@ -550,25 +549,44 @@ namespace client
|
||||
|
||||
void SAMSocket::HandleI2PDatagramReceive (const i2p::data::IdentityEx& ident, const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint8_t identBuf[1024];
|
||||
size_t l = ident.ToBuffer (identBuf, 1024);
|
||||
size_t l1 = i2p::data::ByteStreamToBase64 (identBuf, l, m_Buffer, SAM_SOCKET_BUFFER_SIZE);
|
||||
m_Buffer[l1] = 0;
|
||||
auto base64 = ident.ToBase64 ();
|
||||
#ifdef _MSC_VER
|
||||
size_t l2 = sprintf_s ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, m_Buffer, len);
|
||||
size_t l = sprintf_s ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, base64.c_str (), len);
|
||||
#else
|
||||
size_t l2 = snprintf ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, m_Buffer, len);
|
||||
size_t l = snprintf ((char *)m_StreamBuffer, SAM_SOCKET_BUFFER_SIZE, SAM_DATAGRAM_RECEIVED, base64.c_str (), len);
|
||||
#endif
|
||||
if (len < SAM_SOCKET_BUFFER_SIZE - l2)
|
||||
if (len < SAM_SOCKET_BUFFER_SIZE - l)
|
||||
{
|
||||
memcpy (m_StreamBuffer + l2, buf, len);
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, len + l2),
|
||||
boost::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), boost::asio::placeholders::error));
|
||||
memcpy (m_StreamBuffer + l, buf, len);
|
||||
boost::asio::async_write (m_Socket, boost::asio::buffer (m_StreamBuffer, len + l),
|
||||
std::bind (&SAMSocket::HandleWriteI2PData, shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Datagram size ", len," exceeds buffer");
|
||||
}
|
||||
|
||||
SAMSession::SAMSession (ClientDestination * dest):
|
||||
localDestination (dest)
|
||||
{
|
||||
}
|
||||
|
||||
SAMSession::~SAMSession ()
|
||||
{
|
||||
for (auto it: sockets)
|
||||
it->SetSocketType (eSAMSocketTypeTerminated);
|
||||
i2p::client::context.DeleteLocalDestination (localDestination);
|
||||
}
|
||||
|
||||
void SAMSession::CloseStreams ()
|
||||
{
|
||||
for (auto it: sockets)
|
||||
{
|
||||
it->CloseStream ();
|
||||
it->SetSocketType (eSAMSocketTypeTerminated);
|
||||
}
|
||||
sockets.clear ();
|
||||
}
|
||||
|
||||
SAMBridge::SAMBridge (int port):
|
||||
m_IsRunning (false), m_Thread (nullptr),
|
||||
m_Acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),
|
||||
@@ -578,7 +596,8 @@ namespace client
|
||||
|
||||
SAMBridge::~SAMBridge ()
|
||||
{
|
||||
Stop ();
|
||||
if (m_IsRunning)
|
||||
Stop ();
|
||||
}
|
||||
|
||||
void SAMBridge::Start ()
|
||||
@@ -592,6 +611,10 @@ namespace client
|
||||
void SAMBridge::Stop ()
|
||||
{
|
||||
m_IsRunning = false;
|
||||
m_Acceptor.cancel ();
|
||||
for (auto it: m_Sessions)
|
||||
delete it.second;
|
||||
m_Sessions.clear ();
|
||||
m_Service.stop ();
|
||||
if (m_Thread)
|
||||
{
|
||||
@@ -619,8 +642,8 @@ namespace client
|
||||
void SAMBridge::Accept ()
|
||||
{
|
||||
auto newSocket = std::make_shared<SAMSocket> (*this);
|
||||
m_Acceptor.async_accept (newSocket->GetSocket (), boost::bind (&SAMBridge::HandleAccept, this,
|
||||
boost::asio::placeholders::error, newSocket));
|
||||
m_Acceptor.async_accept (newSocket->GetSocket (), std::bind (&SAMBridge::HandleAccept, this,
|
||||
std::placeholders::_1, newSocket));
|
||||
}
|
||||
|
||||
void SAMBridge::HandleAccept(const boost::system::error_code& ecode, std::shared_ptr<SAMSocket> socket)
|
||||
@@ -637,29 +660,36 @@ namespace client
|
||||
Accept ();
|
||||
}
|
||||
|
||||
SAMSession * SAMBridge::CreateSession (const std::string& id, const std::string& destination)
|
||||
SAMSession * SAMBridge::CreateSession (const std::string& id, const std::string& destination,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
ClientDestination * localDestination = nullptr;
|
||||
if (destination != "")
|
||||
{
|
||||
uint8_t * buf = new uint8_t[destination.length ()];
|
||||
size_t l = i2p::data::Base64ToByteStream (destination.c_str (), destination.length (), buf, destination.length ());
|
||||
i2p::data::PrivateKeys keys;
|
||||
keys.FromBuffer (buf, l);
|
||||
delete[] buf;
|
||||
localDestination = i2p::client::context.CreateNewLocalDestination (keys);
|
||||
keys.FromBase64 (destination);
|
||||
localDestination = i2p::client::context.CreateNewLocalDestination (keys, true, params);
|
||||
}
|
||||
else // transient
|
||||
localDestination = i2p::client::context.CreateNewLocalDestination ();
|
||||
{
|
||||
// extract signature type
|
||||
i2p::data::SigningKeyType signatureType = i2p::data::SIGNING_KEY_TYPE_DSA_SHA1;
|
||||
if (params)
|
||||
{
|
||||
auto it = params->find (SAM_PARAM_SIGNATURE_TYPE);
|
||||
if (it != params->end ())
|
||||
// TODO: extract string values
|
||||
signatureType = boost::lexical_cast<int> (it->second);
|
||||
}
|
||||
localDestination = i2p::client::context.CreateNewLocalDestination (false, signatureType, params);
|
||||
}
|
||||
if (localDestination)
|
||||
{
|
||||
SAMSession session;
|
||||
session.localDestination = localDestination;
|
||||
std::unique_lock<std::mutex> l(m_SessionsMutex);
|
||||
auto ret = m_Sessions.insert (std::pair<std::string, SAMSession>(id, session));
|
||||
auto ret = m_Sessions.insert (std::pair<std::string, SAMSession *>(id, new SAMSession (localDestination)));
|
||||
if (!ret.second)
|
||||
LogPrint ("Session ", id, " already exists");
|
||||
return &(ret.first->second);
|
||||
return ret.first->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -670,9 +700,10 @@ namespace client
|
||||
auto it = m_Sessions.find (id);
|
||||
if (it != m_Sessions.end ())
|
||||
{
|
||||
it->second.sockets.clear ();
|
||||
it->second.localDestination->Stop ();
|
||||
auto session = it->second;
|
||||
session->CloseStreams ();
|
||||
m_Sessions.erase (it);
|
||||
delete session;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -681,7 +712,7 @@ namespace client
|
||||
std::unique_lock<std::mutex> l(m_SessionsMutex);
|
||||
auto it = m_Sessions.find (id);
|
||||
if (it != m_Sessions.end ())
|
||||
return &it->second;
|
||||
return it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -690,7 +721,7 @@ namespace client
|
||||
m_DatagramSocket.async_receive_from (
|
||||
boost::asio::buffer (m_DatagramReceiveBuffer, i2p::datagram::MAX_DATAGRAM_SIZE),
|
||||
m_SenderEndpoint,
|
||||
boost::bind (&SAMBridge::HandleReceivedDatagram, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
std::bind (&SAMBridge::HandleReceivedDatagram, this, std::placeholders::_1, std::placeholders::_2));
|
||||
}
|
||||
|
||||
void SAMBridge::HandleReceivedDatagram (const boost::system::error_code& ecode, std::size_t bytes_transferred)
|
||||
@@ -713,10 +744,8 @@ namespace client
|
||||
auto session = FindSession (sessionID);
|
||||
if (session)
|
||||
{
|
||||
uint8_t ident[1024];
|
||||
size_t l = i2p::data::Base64ToByteStream (destination, strlen(destination), ident, 1024);
|
||||
i2p::data::IdentityEx dest;
|
||||
dest.FromBuffer (ident, l);
|
||||
dest.FromBase64 (destination);
|
||||
auto leaseSet = i2p::data::netdb.FindLeaseSet (dest.GetIdentHash ());
|
||||
if (leaseSet)
|
||||
session->localDestination->GetDatagramDestination ()->
|
||||
@@ -724,8 +753,7 @@ namespace client
|
||||
else
|
||||
{
|
||||
LogPrint ("SAM datagram destination not found");
|
||||
i2p::data::netdb.RequestDestination (dest.GetIdentHash (), true,
|
||||
session->localDestination->GetTunnelPool ());
|
||||
session->localDestination->RequestDestination (dest.GetIdentHash ());
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
41
SAM.h
41
SAM.h
@@ -19,12 +19,11 @@ namespace i2p
|
||||
namespace client
|
||||
{
|
||||
const size_t SAM_SOCKET_BUFFER_SIZE = 4096;
|
||||
const int SAM_SOCKET_CONNECTION_MAX_IDLE = 3600; // in seconds
|
||||
const int SAM_CONNECT_TIMEOUT = 5; // in seconds
|
||||
const int SAM_NAMING_LOOKUP_TIMEOUT = 5; // in seconds
|
||||
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=3.0\n";
|
||||
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";
|
||||
@@ -42,12 +41,15 @@ namespace client
|
||||
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_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_NAME[] = "NAME";
|
||||
const char SAM_PARAM_SIGNATURE_TYPE[] = "SIGNATURE_TYPE";
|
||||
const char SAM_VALUE_TRANSIENT[] = "TRANSIENT";
|
||||
const char SAM_VALUE_STREAM[] = "STREAM";
|
||||
const char SAM_VALUE_DATAGRAM[] = "DATAGRAM";
|
||||
@@ -60,24 +62,27 @@ namespace client
|
||||
eSAMSocketTypeUnknown,
|
||||
eSAMSocketTypeSession,
|
||||
eSAMSocketTypeStream,
|
||||
eSAMSocketTypeAcceptor
|
||||
eSAMSocketTypeAcceptor,
|
||||
eSAMSocketTypeTerminated
|
||||
};
|
||||
|
||||
class SAMBridge;
|
||||
class SAMSession;
|
||||
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; };
|
||||
|
||||
private:
|
||||
|
||||
void Terminate ();
|
||||
void Terminate ();
|
||||
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);
|
||||
@@ -88,7 +93,7 @@ namespace client
|
||||
|
||||
void I2PReceive ();
|
||||
void HandleI2PReceive (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
void HandleI2PAccept (i2p::stream::Stream * stream);
|
||||
void HandleI2PAccept (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
void HandleWriteI2PData (const boost::system::error_code& ecode);
|
||||
void HandleI2PDatagramReceive (const i2p::data::IdentityEx& ident, const uint8_t * buf, size_t len);
|
||||
|
||||
@@ -100,9 +105,9 @@ namespace client
|
||||
void ExtractParams (char * buf, size_t len, std::map<std::string, std::string>& params);
|
||||
|
||||
void Connect (const i2p::data::LeaseSet& remote);
|
||||
void HandleStreamDestinationRequestTimer (const boost::system::error_code& ecode, i2p::data::IdentHash ident);
|
||||
void HandleNamingLookupDestinationRequestTimer (const boost::system::error_code& ecode, i2p::data::IdentHash ident);
|
||||
void HandleLeaseSetRequestComplete (bool success, i2p::data::IdentHash ident);
|
||||
void SendNamingLookupReply (const i2p::data::LeaseSet * leaseSet);
|
||||
void SendNamingLookupReply (const i2p::data::IdentityEx& identity);
|
||||
void HandleSessionReadinessCheckTimer (const boost::system::error_code& ecode);
|
||||
void SendSessionCreateReplyOk ();
|
||||
|
||||
@@ -116,7 +121,7 @@ namespace client
|
||||
SAMSocketType m_SocketType;
|
||||
std::string m_ID; // nickname
|
||||
bool m_IsSilent;
|
||||
i2p::stream::Stream * m_Stream;
|
||||
std::shared_ptr<i2p::stream::Stream> m_Stream;
|
||||
SAMSession * m_Session;
|
||||
};
|
||||
|
||||
@@ -124,6 +129,11 @@ namespace client
|
||||
{
|
||||
ClientDestination * localDestination;
|
||||
std::list<std::shared_ptr<SAMSocket> > sockets;
|
||||
|
||||
SAMSession (ClientDestination * localDestination);
|
||||
~SAMSession ();
|
||||
|
||||
void CloseStreams ();
|
||||
};
|
||||
|
||||
class SAMBridge
|
||||
@@ -137,7 +147,8 @@ namespace client
|
||||
void Stop ();
|
||||
|
||||
boost::asio::io_service& GetService () { return m_Service; };
|
||||
SAMSession * CreateSession (const std::string& id, const std::string& destination = ""); // empty string means transient
|
||||
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);
|
||||
SAMSession * FindSession (const std::string& id);
|
||||
|
||||
@@ -160,7 +171,7 @@ namespace client
|
||||
boost::asio::ip::udp::endpoint m_DatagramEndpoint, m_SenderEndpoint;
|
||||
boost::asio::ip::udp::socket m_DatagramSocket;
|
||||
std::mutex m_SessionsMutex;
|
||||
std::map<std::string, SAMSession> m_Sessions;
|
||||
std::map<std::string, SAMSession *> m_Sessions;
|
||||
uint8_t m_DatagramReceiveBuffer[i2p::datagram::MAX_DATAGRAM_SIZE+1];
|
||||
};
|
||||
}
|
||||
|
||||
631
SOCKS.cpp
631
SOCKS.cpp
@@ -3,282 +3,447 @@
|
||||
#include "NetDb.h"
|
||||
#include "Destination.h"
|
||||
#include "ClientContext.h"
|
||||
#include "I2PEndian.h"
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <cassert>
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace proxy
|
||||
{
|
||||
const uint8_t socks_leaseset_timeout = 10;
|
||||
const uint8_t socks_timeout = 60;
|
||||
|
||||
void SOCKS4AHandler::AsyncSockRead()
|
||||
void SOCKSHandler::AsyncSockRead()
|
||||
{
|
||||
LogPrint("--- socks4a async sock read");
|
||||
LogPrint(eLogDebug,"--- SOCKS async sock read");
|
||||
if(m_sock) {
|
||||
if (m_state == INITIAL) {
|
||||
m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size),
|
||||
boost::bind(&SOCKS4AHandler::HandleSockRecv, this,
|
||||
boost::asio::placeholders::error,
|
||||
boost::asio::placeholders::bytes_transferred));
|
||||
} else {
|
||||
m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size),
|
||||
boost::bind(&SOCKS4AHandler::HandleSockForward, this,
|
||||
boost::asio::placeholders::error,
|
||||
boost::asio::placeholders::bytes_transferred));
|
||||
}
|
||||
m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size),
|
||||
std::bind(&SOCKSHandler::HandleSockRecv, this,
|
||||
std::placeholders::_1, std::placeholders::_2));
|
||||
} else {
|
||||
LogPrint("--- socks4a no socket for read");
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::AsyncStreamRead()
|
||||
{
|
||||
|
||||
LogPrint("--- socks4a async stream read");
|
||||
if (m_stream) {
|
||||
m_stream->AsyncReceive(
|
||||
boost::asio::buffer(m_stream_buff, socks_buffer_size),
|
||||
boost::bind(&SOCKS4AHandler::HandleStreamRecv, this,
|
||||
boost::asio::placeholders::error,
|
||||
boost::asio::placeholders::bytes_transferred), socks_timeout);
|
||||
} else {
|
||||
LogPrint("--- socks4a no stream for read");
|
||||
LogPrint(eLogError,"--- SOCKS no socket for read");
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::Terminate() {
|
||||
CloseStream();
|
||||
CloseSock();
|
||||
delete this; // ew
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::SocksFailed()
|
||||
{
|
||||
LogPrint("--- socks4a failed");
|
||||
m_sock->send(boost::asio::buffer("\x00\x5b 12345"));
|
||||
Terminate();
|
||||
void SOCKSHandler::Done() {
|
||||
if (m_parent) m_parent->RemoveHandler (shared_from_this ());
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::CloseSock()
|
||||
{
|
||||
|
||||
void SOCKSHandler::Terminate() {
|
||||
if (dead.exchange(true)) return;
|
||||
if (m_sock) {
|
||||
LogPrint("--- socks4a close sock");
|
||||
LogPrint(eLogDebug,"--- SOCKS close sock");
|
||||
m_sock->close();
|
||||
delete m_sock;
|
||||
m_sock = nullptr;
|
||||
}
|
||||
if (m_stream) {
|
||||
LogPrint(eLogDebug,"--- SOCKS close stream");
|
||||
m_stream.reset ();
|
||||
}
|
||||
Done();
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::CloseStream()
|
||||
boost::asio::const_buffers_1 SOCKSHandler::GenerateSOCKS4Response(SOCKSHandler::errTypes error, uint32_t ip, uint16_t port)
|
||||
{
|
||||
if (m_stream) {
|
||||
LogPrint("--- socks4a close stream");
|
||||
delete m_stream;
|
||||
m_stream = nullptr;
|
||||
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;
|
||||
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);
|
||||
}
|
||||
|
||||
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,"--- SOCKS5 authentication negotiation failed");
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksFailed, this, std::placeholders::_1));
|
||||
return false;
|
||||
} else {
|
||||
LogPrint(eLogDebug,"--- SOCKS5 choosing authentication method: ", m_authchosen);
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksResponse, this, std::placeholders::_1));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const size_t socks_hostname_size = 1024;
|
||||
const size_t socks_ident_size = 1024;
|
||||
const size_t destb32_len = 52;
|
||||
|
||||
void SOCKS4AHandler::HandleSockForward(const boost::system::error_code & ecode, std::size_t len)
|
||||
/* All hope is lost beyond this point */
|
||||
void SOCKSHandler::SocksRequestFailed(SOCKSHandler::errTypes error)
|
||||
{
|
||||
if(ecode) {
|
||||
LogPrint("--- socks4a forward got error: ", ecode);
|
||||
Terminate();
|
||||
boost::asio::const_buffers_1 response(nullptr,0);
|
||||
assert(error != SOCKS4_OK && error != SOCKS5_OK);
|
||||
switch (m_socksv) {
|
||||
case SOCKS4:
|
||||
LogPrint(eLogWarning,"--- SOCKS4 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,"--- SOCKS5 failed: ", error);
|
||||
response = GenerateSOCKS5Response(error, m_addrtype, m_address, m_port);
|
||||
break;
|
||||
}
|
||||
boost::asio::async_write(*m_sock, response, std::bind(&SOCKSHandler::SentSocksFailed, 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,"--- SOCKS4 connection success");
|
||||
response = GenerateSOCKS4Response(SOCKS4_OK, m_4aip, m_port);
|
||||
break;
|
||||
case SOCKS5:
|
||||
LogPrint(eLogInfo,"--- SOCKS5 connection success");
|
||||
auto s = i2p::client::context.GetAddressBook().ToAddress(m_parent->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, 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;
|
||||
}
|
||||
|
||||
void 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;
|
||||
}
|
||||
//TODO: we may want to support other address types!
|
||||
if ( m_addrtype != ADDR_DNS ) {
|
||||
switch (m_socksv) {
|
||||
case SOCKS5:
|
||||
LogPrint(eLogError,"--- SOCKS5 unsupported address type: ", m_addrtype);
|
||||
break;
|
||||
case SOCKS4:
|
||||
LogPrint(eLogError,"--- SOCKS4a rejected because it's actually SOCKS4");
|
||||
break;
|
||||
}
|
||||
SocksRequestFailed(SOCKS5_ADDR_UNSUP);
|
||||
return;
|
||||
}
|
||||
//TODO: we may want to support other domains
|
||||
if(m_addrtype == ADDR_DNS && m_address.dns.ToString().find(".i2p") == std::string::npos) {
|
||||
LogPrint(eLogError,"--- SOCKS invalid hostname: ", m_address.dns.ToString());
|
||||
SocksRequestFailed(SOCKS5_ADDR_UNSUP);
|
||||
return;
|
||||
}
|
||||
|
||||
LogPrint("--- socks4a sock forward: ", len);
|
||||
m_stream->Send(m_sock_buff, len);
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
|
||||
bool SOCKSHandler::HandleData(uint8_t *sock_buff, std::size_t len)
|
||||
{
|
||||
LogPrint("--- socks4a sock recv: ", 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(DONE); 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(DONE);
|
||||
} else {
|
||||
EnterState(GET4A_HOST);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case GET4A_HOST:
|
||||
if (!*sock_buff) {
|
||||
EnterState(DONE);
|
||||
break;
|
||||
}
|
||||
if (m_address.dns.size >= max_socks_hostname_size) {
|
||||
LogPrint(eLogError,"--- SOCKS4a 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,"--- SOCKS5 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,"--- SOCKS5 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,"--- SOCKS5 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 (len && m_state == DONE) {
|
||||
LogPrint(eLogError,"--- SOCKS rejected because we can't handle extra data");
|
||||
SocksRequestFailed(SOCKS5_GEN_FAIL);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void SOCKSHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
|
||||
{
|
||||
LogPrint(eLogDebug,"--- SOCKS sock recv: ", len);
|
||||
if(ecode) {
|
||||
LogPrint(" --- sock recv got error: ", ecode);
|
||||
LogPrint(eLogWarning," --- SOCKS sock recv got error: ", ecode);
|
||||
Terminate();
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_state == INITIAL) {
|
||||
|
||||
char hostbuff[socks_hostname_size];
|
||||
char identbuff[socks_ident_size];
|
||||
std::memset(hostbuff, 0, sizeof(hostbuff));
|
||||
std::memset(identbuff, 0, sizeof(hostbuff));
|
||||
std::string dest;
|
||||
// get port
|
||||
uint16_t port = 0;
|
||||
uint16_t idx1 = 0;
|
||||
uint16_t idx2 = 0;
|
||||
|
||||
LogPrint("--- socks4a state initial ", len);
|
||||
|
||||
// check valid request
|
||||
if( m_sock_buff[0] != 4 || m_sock_buff[1] != 1 || m_sock_buff[len-1] ) {
|
||||
LogPrint("--- socks4a rejected invalid");
|
||||
SocksFailed();
|
||||
return;
|
||||
}
|
||||
|
||||
// get port
|
||||
port = m_sock_buff[3] | m_sock_buff[2] << 8;
|
||||
|
||||
// read ident
|
||||
do {
|
||||
LogPrint("--- socks4a ", (int) m_sock_buff[9+idx1]);
|
||||
identbuff[idx1] = m_sock_buff[8+idx1];
|
||||
} while( identbuff[idx1++] && idx1 < socks_ident_size );
|
||||
|
||||
LogPrint("--- socks4a ident ", identbuff);
|
||||
// read hostname
|
||||
do {
|
||||
hostbuff[idx2] = m_sock_buff[8+idx1+idx2];
|
||||
} while( hostbuff[idx2++] && idx2 < socks_hostname_size );
|
||||
|
||||
LogPrint("--- socks4a requested ", hostbuff, ":" , port);
|
||||
|
||||
dest = std::string(hostbuff);
|
||||
if(dest.find(".b32.i2p") == std::string::npos) {
|
||||
LogPrint("--- socks4a invalid hostname: ", dest);
|
||||
SocksFailed();
|
||||
return;
|
||||
}
|
||||
|
||||
if ( i2p::data::Base32ToByteStream(hostbuff, destb32_len, (uint8_t *) m_dest, 32) != 32 ) {
|
||||
LogPrint("--- sock4a invalid b32: ", dest);
|
||||
}
|
||||
|
||||
LogPrint("--- sock4a find lease set");
|
||||
m_ls = i2p::data::netdb.FindLeaseSet(m_dest);
|
||||
if (!m_ls || m_ls->HasNonExpiredLeases()) {
|
||||
i2p::data::netdb.RequestDestination (m_dest, true, i2p::client::context.GetSharedLocalDestination ()->GetTunnelPool ());
|
||||
m_ls_timer.expires_from_now(boost::posix_time::seconds(socks_leaseset_timeout));
|
||||
m_ls_timer.async_wait(boost::bind(&SOCKS4AHandler::LeaseSetTimeout, this, boost::asio::placeholders::error));
|
||||
if (HandleData(m_sock_buff, len)) {
|
||||
if (m_state == DONE) {
|
||||
LogPrint(eLogInfo,"--- SOCKS requested ", m_address.dns.ToString(), ":" , m_port);
|
||||
m_parent->GetLocalDestination ()->CreateStream (
|
||||
std::bind (&SOCKSHandler::HandleStreamRequestComplete,
|
||||
this, std::placeholders::_1), m_address.dns.ToString(), m_port);
|
||||
} else {
|
||||
ConnectionSuccess();
|
||||
}
|
||||
} else {
|
||||
LogPrint("--- socks4a state?? ", m_state);
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::HandleStreamRecv(const boost::system::error_code & ecode, std::size_t len)
|
||||
{
|
||||
if(ecode) { LogPrint("--- socks4a stream recv error: ", ecode); m_state = END; }
|
||||
switch(m_state) {
|
||||
case INITIAL:
|
||||
case END:
|
||||
Terminate();
|
||||
return;
|
||||
case OKAY:
|
||||
LogPrint("--- socks4a stream recv ", len);
|
||||
boost::asio::async_write(*m_sock, boost::asio::buffer(m_stream_buff, len),
|
||||
boost::bind(&SOCKS4AHandler::StreamWrote, this,
|
||||
boost::asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::SockWrote(const boost::system::error_code & ecode)
|
||||
{
|
||||
LogPrint("--- socks4a sock wrote");
|
||||
if(ecode) { LogPrint("--- socks4a SockWrote error: ",ecode); }
|
||||
else { AsyncSockRead(); }
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::StreamWrote(const boost::system::error_code & ecode)
|
||||
{
|
||||
|
||||
LogPrint("--- socks4a stream wrote");
|
||||
if(ecode) { LogPrint("--- socks4a StreamWrote error: ",ecode); }
|
||||
else { AsyncStreamRead(); }
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::LeaseSetTimeout(const boost::system::error_code & ecode)
|
||||
{
|
||||
m_ls = i2p::data::netdb.FindLeaseSet(m_dest);
|
||||
if(m_ls) {
|
||||
ConnectionSuccess();
|
||||
} else {
|
||||
LogPrint("--- socks4a ls timeout");
|
||||
SocksFailed();
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::ConnectionSuccess()
|
||||
{
|
||||
LogPrint("--- socks4a connection success");
|
||||
boost::asio::async_write(*m_sock, boost::asio::buffer("\x00\x5a 12345"),
|
||||
boost::bind(&SOCKS4AHandler::SentConnectionSuccess, this,
|
||||
boost::asio::placeholders::error));
|
||||
}
|
||||
|
||||
void SOCKS4AHandler::SentConnectionSuccess(const boost::system::error_code & ecode)
|
||||
{
|
||||
LogPrint("--- socks4a making connection");
|
||||
m_stream = i2p::client::context.GetSharedLocalDestination ()->CreateStream(*m_ls);
|
||||
m_state = OKAY;
|
||||
LogPrint("--- socks4a state is ", m_state);
|
||||
AsyncSockRead();
|
||||
AsyncStreamRead();
|
||||
}
|
||||
|
||||
void SOCKS4AServer::Run()
|
||||
{
|
||||
LogPrint("--- socks4a run");
|
||||
m_run = true;
|
||||
while(m_run) {
|
||||
try {
|
||||
m_ios.run();
|
||||
} catch (std::runtime_error & exc) {
|
||||
LogPrint("--- socks4a exception: ", exc.what());
|
||||
AsyncSockRead();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AServer::Accept()
|
||||
{
|
||||
m_new_sock = new boost::asio::ip::tcp::socket(m_ios);
|
||||
m_acceptor.async_accept(*m_new_sock,
|
||||
boost::bind(
|
||||
&SOCKS4AServer::HandleAccept, this, boost::asio::placeholders::error));
|
||||
|
||||
}
|
||||
|
||||
void SOCKS4AServer::Start()
|
||||
{
|
||||
m_run = true;
|
||||
m_thread = new std::thread(std::bind(&SOCKS4AServer::Run, this));
|
||||
m_acceptor.listen();
|
||||
Accept();
|
||||
}
|
||||
|
||||
void SOCKS4AServer::Stop()
|
||||
{
|
||||
m_acceptor.close();
|
||||
m_run = false;
|
||||
m_ios.stop();
|
||||
if (m_thread) {
|
||||
m_thread->join();
|
||||
delete m_thread;
|
||||
m_thread = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKS4AServer::HandleAccept(const boost::system::error_code & ecode)
|
||||
void SOCKSHandler::SentSocksFailed(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (!ecode) {
|
||||
LogPrint("--- socks4a accepted");
|
||||
new SOCKS4AHandler(&m_ios, m_new_sock);
|
||||
Accept();
|
||||
Terminate();
|
||||
} else {
|
||||
LogPrint (eLogError,"--- SOCKS Closing socket after sending failure because: ", ecode.message ());
|
||||
Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSHandler::SentSocksDone(const boost::system::error_code & ecode)
|
||||
{
|
||||
if (!ecode) {
|
||||
if (dead.exchange(true)) return;
|
||||
LogPrint (eLogInfo,"--- SOCKS New I2PTunnel connection");
|
||||
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>((i2p::client::I2PTunnel *)m_parent, m_sock, m_stream);
|
||||
m_parent->AddConnection (connection);
|
||||
connection->I2PConnect ();
|
||||
Done();
|
||||
}
|
||||
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 Issue when creating the stream, check the previous warnings for more info.");
|
||||
SocksRequestFailed(SOCKS5_HOST_UNREACH);
|
||||
}
|
||||
}
|
||||
|
||||
void SOCKSServer::Start ()
|
||||
{
|
||||
m_Acceptor.listen ();
|
||||
Accept ();
|
||||
}
|
||||
|
||||
void SOCKSServer::Stop ()
|
||||
{
|
||||
m_Acceptor.close();
|
||||
m_Timer.cancel ();
|
||||
ClearConnections ();
|
||||
ClearHandlers();
|
||||
}
|
||||
|
||||
void SOCKSServer::Accept ()
|
||||
{
|
||||
auto newSocket = new boost::asio::ip::tcp::socket (GetService ());
|
||||
m_Acceptor.async_accept (*newSocket, std::bind (&SOCKSServer::HandleAccept, this,
|
||||
std::placeholders::_1, newSocket));
|
||||
}
|
||||
|
||||
void SOCKSServer::AddHandler (std::shared_ptr<SOCKSHandler> handler) {
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.insert (handler);
|
||||
}
|
||||
|
||||
void SOCKSServer::RemoveHandler (std::shared_ptr<SOCKSHandler> handler)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.erase (handler);
|
||||
}
|
||||
|
||||
void SOCKSServer::ClearHandlers ()
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_HandlersMutex);
|
||||
m_Handlers.clear ();
|
||||
}
|
||||
|
||||
void SOCKSServer::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
|
||||
{
|
||||
if (!ecode)
|
||||
{
|
||||
LogPrint(eLogDebug,"--- SOCKS accepted");
|
||||
AddHandler(std::make_shared<SOCKSHandler> (this, socket));
|
||||
Accept();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError,"--- SOCKS Closing socket on accept because: ", ecode.message ());
|
||||
delete socket;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
212
SOCKS.h
212
SOCKS.h
@@ -1,13 +1,15 @@
|
||||
#ifndef SOCKS4A_H__
|
||||
#define SOCKS4A_H__
|
||||
#ifndef SOCKS_H__
|
||||
#define SOCKS_H__
|
||||
|
||||
#include <thread>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <boost/asio.hpp>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
#include <atomic>
|
||||
#include "Identity.h"
|
||||
#include "Streaming.h"
|
||||
#include "I2PTunnel.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
@@ -15,83 +17,151 @@ namespace proxy
|
||||
{
|
||||
|
||||
const size_t socks_buffer_size = 8192;
|
||||
const size_t max_socks_hostname_size = 255; // Limit for socks5 and bad idea to traverse
|
||||
|
||||
class SOCKS4AHandler {
|
||||
|
||||
private:
|
||||
enum state {
|
||||
INITIAL,
|
||||
OKAY,
|
||||
END
|
||||
};
|
||||
|
||||
void GotClientRequest(boost::system::error_code & ecode, std::string & host, uint16_t port);
|
||||
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void HandleSockForward(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void HandleStreamRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void Terminate();
|
||||
void CloseSock();
|
||||
void CloseStream();
|
||||
void AsyncSockRead();
|
||||
void AsyncStreamRead();
|
||||
void SocksFailed();
|
||||
void LeaseSetTimeout(const boost::system::error_code & ecode);
|
||||
void StreamWrote(const boost::system::error_code & ecode);
|
||||
void SockWrote(const boost::system::error_code & ecode);
|
||||
void SentConnectionSuccess(const boost::system::error_code & ecode);
|
||||
void ConnectionSuccess();
|
||||
|
||||
uint8_t m_sock_buff[socks_buffer_size];
|
||||
uint8_t m_stream_buff[socks_buffer_size];
|
||||
|
||||
boost::asio::io_service * m_ios;
|
||||
boost::asio::ip::tcp::socket * m_sock;
|
||||
boost::asio::deadline_timer m_ls_timer;
|
||||
i2p::stream::Stream * m_stream;
|
||||
i2p::data::LeaseSet * m_ls;
|
||||
i2p::data::IdentHash m_dest;
|
||||
state m_state;
|
||||
|
||||
|
||||
public:
|
||||
SOCKS4AHandler(boost::asio::io_service * ios, boost::asio::ip::tcp::socket * sock) :
|
||||
m_ios(ios), m_sock(sock), m_ls_timer(*ios),
|
||||
m_stream(nullptr), m_ls(nullptr), m_state(INITIAL) { AsyncSockRead(); }
|
||||
|
||||
~SOCKS4AHandler() { CloseSock(); CloseStream(); }
|
||||
bool isComplete() { return m_state == END; }
|
||||
struct SOCKSDnsAddress {
|
||||
uint8_t size;
|
||||
char value[max_socks_hostname_size];
|
||||
void FromString (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 SOCKS4AServer {
|
||||
class SOCKSServer;
|
||||
class SOCKSHandler: 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,
|
||||
DONE
|
||||
};
|
||||
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);
|
||||
void ValidateSOCKSRequest();
|
||||
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
|
||||
void Done();
|
||||
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);
|
||||
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);
|
||||
|
||||
uint8_t m_sock_buff[socks_buffer_size];
|
||||
SOCKSServer * m_parent;
|
||||
boost::asio::ip::tcp::socket * m_sock;
|
||||
std::shared_ptr<i2p::stream::Stream> m_stream;
|
||||
uint8_t m_response[7+max_socks_hostname_size];
|
||||
address m_address; //Address
|
||||
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;
|
||||
std::atomic<bool> dead; //To avoid cleaning up multiple times
|
||||
|
||||
public:
|
||||
SOCKS4AServer(int port) : m_run(false),
|
||||
m_thread(nullptr),
|
||||
m_work(m_ios),
|
||||
m_acceptor(m_ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),
|
||||
m_new_sock(nullptr) { }
|
||||
~SOCKS4AServer() { Stop(); }
|
||||
void Start();
|
||||
void Stop();
|
||||
|
||||
boost::asio::io_service& GetService () { return m_ios; };
|
||||
SOCKSHandler(SOCKSServer * parent, boost::asio::ip::tcp::socket * sock) :
|
||||
m_parent(parent), m_sock(sock), m_stream(nullptr),
|
||||
m_authchosen(AUTH_UNACCEPTABLE), m_addrtype(ADDR_IPV4), dead(false)
|
||||
{ m_address.ip = 0; AsyncSockRead(); EnterState(GET_SOCKSV); }
|
||||
~SOCKSHandler() { Terminate(); }
|
||||
};
|
||||
|
||||
class SOCKSServer: public i2p::client::I2PTunnel
|
||||
{
|
||||
private:
|
||||
std::set<std::shared_ptr<SOCKSHandler> > m_Handlers;
|
||||
boost::asio::ip::tcp::acceptor m_Acceptor;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
std::mutex m_HandlersMutex;
|
||||
|
||||
private:
|
||||
|
||||
void Run();
|
||||
|
||||
void Accept();
|
||||
void HandleAccept(const boost::system::error_code& ecode);
|
||||
void HandleAccept(const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket);
|
||||
|
||||
bool m_run;
|
||||
std::thread * m_thread;
|
||||
boost::asio::io_service m_ios;
|
||||
boost::asio::io_service::work m_work;
|
||||
boost::asio::ip::tcp::acceptor m_acceptor;
|
||||
boost::asio::ip::tcp::socket * m_new_sock;
|
||||
|
||||
public:
|
||||
SOCKSServer(int port) : I2PTunnel(nullptr),
|
||||
m_Acceptor (GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
|
||||
m_Timer (GetService ()) {};
|
||||
~SOCKSServer() { Stop(); }
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
void AddHandler (std::shared_ptr<SOCKSHandler> handler);
|
||||
void RemoveHandler (std::shared_ptr<SOCKSHandler> handler);
|
||||
void ClearHandlers ();
|
||||
};
|
||||
|
||||
typedef SOCKS4AServer SOCKSProxy;
|
||||
typedef SOCKSServer SOCKSProxy;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
93
SSU.cpp
93
SSU.cpp
@@ -9,9 +9,10 @@ namespace i2p
|
||||
{
|
||||
namespace transport
|
||||
{
|
||||
SSUServer::SSUServer (int port): m_Thread (nullptr), m_Work (m_Service),
|
||||
m_Endpoint (boost::asio::ip::udp::v4 (), port), m_EndpointV6 (boost::asio::ip::udp::v6 (), port),
|
||||
m_Socket (m_Service, m_Endpoint), m_SocketV6 (m_Service), m_IntroducersUpdateTimer (m_Service)
|
||||
SSUServer::SSUServer (int port): m_Thread (nullptr), m_ThreadV6 (nullptr), m_Work (m_Service),
|
||||
m_WorkV6 (m_ServiceV6),m_Endpoint (boost::asio::ip::udp::v4 (), port),
|
||||
m_EndpointV6 (boost::asio::ip::udp::v6 (), port), m_Socket (m_Service, m_Endpoint),
|
||||
m_SocketV6 (m_ServiceV6), m_IntroducersUpdateTimer (m_Service)
|
||||
{
|
||||
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (65535));
|
||||
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (65535));
|
||||
@@ -27,17 +28,18 @@ namespace transport
|
||||
|
||||
SSUServer::~SSUServer ()
|
||||
{
|
||||
for (auto it: m_Sessions)
|
||||
delete it.second;
|
||||
}
|
||||
|
||||
void SSUServer::Start ()
|
||||
{
|
||||
m_IsRunning = true;
|
||||
m_Thread = new std::thread (std::bind (&SSUServer::Run, this));
|
||||
m_Service.post (boost::bind (&SSUServer::Receive, this));
|
||||
m_Service.post (std::bind (&SSUServer::Receive, this));
|
||||
if (context.SupportsV6 ())
|
||||
m_Service.post (boost::bind (&SSUServer::ReceiveV6, this));
|
||||
{
|
||||
m_ThreadV6 = new std::thread (std::bind (&SSUServer::RunV6, this));
|
||||
m_ServiceV6.post (std::bind (&SSUServer::ReceiveV6, this));
|
||||
}
|
||||
if (i2p::context.IsUnreachable ())
|
||||
ScheduleIntroducersUpdateTimer ();
|
||||
}
|
||||
@@ -48,12 +50,20 @@ namespace transport
|
||||
m_IsRunning = false;
|
||||
m_Service.stop ();
|
||||
m_Socket.close ();
|
||||
m_ServiceV6.stop ();
|
||||
m_SocketV6.close ();
|
||||
if (m_Thread)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = 0;
|
||||
}
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
if (m_ThreadV6)
|
||||
{
|
||||
m_ThreadV6->join ();
|
||||
delete m_ThreadV6;
|
||||
m_ThreadV6 = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void SSUServer::Run ()
|
||||
@@ -70,13 +80,28 @@ namespace transport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void SSUServer::RunV6 ()
|
||||
{
|
||||
while (m_IsRunning)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_ServiceV6.run ();
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
{
|
||||
LogPrint (eLogError, "SSU V6 server: ", ex.what ());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SSUServer::AddRelay (uint32_t tag, const boost::asio::ip::udp::endpoint& relay)
|
||||
{
|
||||
m_Relays[tag] = relay;
|
||||
}
|
||||
|
||||
SSUSession * SSUServer::FindRelaySession (uint32_t tag)
|
||||
std::shared_ptr<SSUSession> SSUServer::FindRelaySession (uint32_t tag)
|
||||
{
|
||||
auto it = m_Relays.find (tag);
|
||||
if (it != m_Relays.end ())
|
||||
@@ -128,20 +153,21 @@ namespace transport
|
||||
|
||||
void SSUServer::HandleReceivedBuffer (boost::asio::ip::udp::endpoint& from, uint8_t * buf, std::size_t bytes_transferred)
|
||||
{
|
||||
SSUSession * session = nullptr;
|
||||
std::shared_ptr<SSUSession> session;
|
||||
auto it = m_Sessions.find (from);
|
||||
if (it != m_Sessions.end ())
|
||||
session = it->second;
|
||||
if (!session)
|
||||
{
|
||||
session = new SSUSession (*this, from);
|
||||
session = std::make_shared<SSUSession> (*this, from);
|
||||
session->WaitForConnect ();
|
||||
m_Sessions[from] = session;
|
||||
LogPrint ("New SSU session from ", from.address ().to_string (), ":", from.port (), " created");
|
||||
}
|
||||
session->ProcessNextMessage (buf, bytes_transferred, from);
|
||||
}
|
||||
|
||||
SSUSession * SSUServer::FindSession (const i2p::data::RouterInfo * router) const
|
||||
std::shared_ptr<SSUSession> SSUServer::FindSession (std::shared_ptr<const i2p::data::RouterInfo> router) const
|
||||
{
|
||||
if (!router) return nullptr;
|
||||
auto address = router->GetSSUAddress (true); // v4 only
|
||||
@@ -155,7 +181,7 @@ namespace transport
|
||||
return FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
|
||||
}
|
||||
|
||||
SSUSession * SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e) const
|
||||
std::shared_ptr<SSUSession> SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e) const
|
||||
{
|
||||
auto it = m_Sessions.find (e);
|
||||
if (it != m_Sessions.end ())
|
||||
@@ -164,9 +190,9 @@ namespace transport
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
SSUSession * SSUServer::GetSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest)
|
||||
std::shared_ptr<SSUSession> SSUServer::GetSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest)
|
||||
{
|
||||
SSUSession * session = nullptr;
|
||||
std::shared_ptr<SSUSession> session;
|
||||
if (router)
|
||||
{
|
||||
auto address = router->GetSSUAddress (!context.SupportsV6 ());
|
||||
@@ -179,7 +205,7 @@ namespace transport
|
||||
else
|
||||
{
|
||||
// otherwise create new session
|
||||
session = new SSUSession (*this, remoteEndpoint, router, peerTest);
|
||||
session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
|
||||
m_Sessions[remoteEndpoint] = session;
|
||||
|
||||
if (!router->UsesIntroducer ())
|
||||
@@ -195,7 +221,7 @@ namespace transport
|
||||
int numIntroducers = address->introducers.size ();
|
||||
if (numIntroducers > 0)
|
||||
{
|
||||
SSUSession * introducerSession = nullptr;
|
||||
std::shared_ptr<SSUSession> introducerSession;
|
||||
const i2p::data::RouterInfo::Introducer * introducer = nullptr;
|
||||
// we might have a session to introducer already
|
||||
for (int i = 0; i < numIntroducers; i++)
|
||||
@@ -216,7 +242,7 @@ namespace transport
|
||||
LogPrint ("Creating new session to introducer");
|
||||
introducer = &(address->introducers[0]); // TODO:
|
||||
boost::asio::ip::udp::endpoint introducerEndpoint (introducer->iHost, introducer->iPort);
|
||||
introducerSession = new SSUSession (*this, introducerEndpoint, router);
|
||||
introducerSession = std::make_shared<SSUSession> (*this, introducerEndpoint, router);
|
||||
m_Sessions[introducerEndpoint] = introducerSession;
|
||||
}
|
||||
// introduce
|
||||
@@ -231,8 +257,7 @@ namespace transport
|
||||
{
|
||||
LogPrint (eLogWarning, "Can't connect to unreachable router. No introducers presented");
|
||||
m_Sessions.erase (remoteEndpoint);
|
||||
delete session;
|
||||
session = nullptr;
|
||||
session.reset ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,30 +268,26 @@ namespace transport
|
||||
return session;
|
||||
}
|
||||
|
||||
void SSUServer::DeleteSession (SSUSession * session)
|
||||
void SSUServer::DeleteSession (std::shared_ptr<SSUSession> session)
|
||||
{
|
||||
if (session)
|
||||
{
|
||||
session->Close ();
|
||||
m_Sessions.erase (session->GetRemoteEndpoint ());
|
||||
delete session;
|
||||
}
|
||||
}
|
||||
|
||||
void SSUServer::DeleteAllSessions ()
|
||||
{
|
||||
for (auto it: m_Sessions)
|
||||
{
|
||||
it.second->Close ();
|
||||
delete it.second;
|
||||
}
|
||||
m_Sessions.clear ();
|
||||
}
|
||||
|
||||
template<typename Filter>
|
||||
SSUSession * SSUServer::GetRandomSession (Filter filter)
|
||||
std::shared_ptr<SSUSession> SSUServer::GetRandomSession (Filter filter)
|
||||
{
|
||||
std::vector<SSUSession *> filteredSessions;
|
||||
std::vector<std::shared_ptr<SSUSession> > filteredSessions;
|
||||
for (auto s :m_Sessions)
|
||||
if (filter (s.second)) filteredSessions.push_back (s.second);
|
||||
if (filteredSessions.size () > 0)
|
||||
@@ -277,10 +298,10 @@ namespace transport
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
SSUSession * SSUServer::GetRandomEstablishedSession (const SSUSession * excluded)
|
||||
std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedSession (std::shared_ptr<const SSUSession> excluded)
|
||||
{
|
||||
return GetRandomSession (
|
||||
[excluded](SSUSession * session)->bool
|
||||
[excluded](std::shared_ptr<SSUSession> session)->bool
|
||||
{
|
||||
return session->GetState () == eSessionStateEstablished &&
|
||||
session != excluded;
|
||||
@@ -295,16 +316,16 @@ namespace transport
|
||||
for (int i = 0; i < maxNumIntroducers; i++)
|
||||
{
|
||||
auto session = GetRandomSession (
|
||||
[&ret, ts](SSUSession * session)->bool
|
||||
[&ret, ts](std::shared_ptr<SSUSession> session)->bool
|
||||
{
|
||||
return session->GetRelayTag () && !ret.count (session) &&
|
||||
return session->GetRelayTag () && !ret.count (session.get ()) &&
|
||||
session->GetState () == eSessionStateEstablished &&
|
||||
ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION;
|
||||
}
|
||||
);
|
||||
if (session)
|
||||
{
|
||||
ret.insert (session);
|
||||
ret.insert (session.get ());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -314,8 +335,8 @@ namespace transport
|
||||
void SSUServer::ScheduleIntroducersUpdateTimer ()
|
||||
{
|
||||
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
|
||||
m_IntroducersUpdateTimer.async_wait (boost::bind (&SSUServer::HandleIntroducersUpdateTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_IntroducersUpdateTimer.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SSUServer::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode)
|
||||
|
||||
23
SSU.h
23
SSU.h
@@ -31,22 +31,23 @@ namespace transport
|
||||
~SSUServer ();
|
||||
void Start ();
|
||||
void Stop ();
|
||||
SSUSession * GetSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest = false);
|
||||
SSUSession * FindSession (const i2p::data::RouterInfo * router) const;
|
||||
SSUSession * FindSession (const boost::asio::ip::udp::endpoint& e) const;
|
||||
SSUSession * GetRandomEstablishedSession (const SSUSession * excluded);
|
||||
void DeleteSession (SSUSession * session);
|
||||
std::shared_ptr<SSUSession> GetSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest = false);
|
||||
std::shared_ptr<SSUSession> FindSession (std::shared_ptr<const i2p::data::RouterInfo> router) const;
|
||||
std::shared_ptr<SSUSession> FindSession (const boost::asio::ip::udp::endpoint& e) const;
|
||||
std::shared_ptr<SSUSession> GetRandomEstablishedSession (std::shared_ptr<const SSUSession> excluded);
|
||||
void DeleteSession (std::shared_ptr<SSUSession> session);
|
||||
void DeleteAllSessions ();
|
||||
|
||||
boost::asio::io_service& GetService () { return m_Socket.get_io_service(); };
|
||||
const boost::asio::ip::udp::endpoint& GetEndpoint () const { return m_Endpoint; };
|
||||
void Send (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to);
|
||||
void AddRelay (uint32_t tag, const boost::asio::ip::udp::endpoint& relay);
|
||||
SSUSession * FindRelaySession (uint32_t tag);
|
||||
std::shared_ptr<SSUSession> FindRelaySession (uint32_t tag);
|
||||
|
||||
private:
|
||||
|
||||
void Run ();
|
||||
void RunV6 ();
|
||||
void Receive ();
|
||||
void ReceiveV6 ();
|
||||
void HandleReceivedFrom (const boost::system::error_code& ecode, std::size_t bytes_transferred);
|
||||
@@ -54,7 +55,7 @@ namespace transport
|
||||
void HandleReceivedBuffer (boost::asio::ip::udp::endpoint& from, uint8_t * buf, std::size_t bytes_transferred);
|
||||
|
||||
template<typename Filter>
|
||||
SSUSession * GetRandomSession (Filter filter);
|
||||
std::shared_ptr<SSUSession> GetRandomSession (Filter filter);
|
||||
|
||||
std::set<SSUSession *> FindIntroducers (int maxNumIntroducers);
|
||||
void ScheduleIntroducersUpdateTimer ();
|
||||
@@ -63,9 +64,9 @@ namespace transport
|
||||
private:
|
||||
|
||||
bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::io_service::work m_Work;
|
||||
std::thread * m_Thread, * m_ThreadV6;
|
||||
boost::asio::io_service m_Service, m_ServiceV6;
|
||||
boost::asio::io_service::work m_Work, m_WorkV6;
|
||||
boost::asio::ip::udp::endpoint m_Endpoint, m_EndpointV6;
|
||||
boost::asio::ip::udp::socket m_Socket, m_SocketV6;
|
||||
boost::asio::ip::udp::endpoint m_SenderEndpoint, m_SenderEndpointV6;
|
||||
@@ -73,7 +74,7 @@ namespace transport
|
||||
std::list<boost::asio::ip::udp::endpoint> m_Introducers; // introducers we are connected to
|
||||
i2p::crypto::AESAlignedBuffer<2*SSU_MTU_V4> m_ReceiveBuffer;
|
||||
i2p::crypto::AESAlignedBuffer<2*SSU_MTU_V6> m_ReceiveBufferV6;
|
||||
std::map<boost::asio::ip::udp::endpoint, SSUSession *> m_Sessions;
|
||||
std::map<boost::asio::ip::udp::endpoint, std::shared_ptr<SSUSession> > m_Sessions;
|
||||
std::map<uint32_t, boost::asio::ip::udp::endpoint> m_Relays; // we are introducer
|
||||
|
||||
public:
|
||||
|
||||
19
SSUData.cpp
19
SSUData.cpp
@@ -84,7 +84,7 @@ namespace transport
|
||||
uint8_t numAcks =*buf;
|
||||
buf++;
|
||||
for (int i = 0; i < numAcks; i++)
|
||||
ProcessSentMessageAck (be32toh (((uint32_t *)buf)[i]));
|
||||
ProcessSentMessageAck (bufbe32toh (buf+i*4));
|
||||
buf += numAcks*4;
|
||||
}
|
||||
if (flag & DATA_FLAG_ACK_BITFIELDS_INCLUDED)
|
||||
@@ -94,7 +94,7 @@ namespace transport
|
||||
buf++;
|
||||
for (int i = 0; i < numBitfields; i++)
|
||||
{
|
||||
uint32_t msgID = be32toh (*(uint32_t *)buf);
|
||||
uint32_t msgID = bufbe32toh (buf);
|
||||
buf += 4; // msgID
|
||||
auto it = m_SentMessages.find (msgID);
|
||||
// process individual Ack bitfields
|
||||
@@ -137,13 +137,13 @@ namespace transport
|
||||
buf++;
|
||||
for (int i = 0; i < numFragments; i++)
|
||||
{
|
||||
uint32_t msgID = be32toh (*(uint32_t *)buf); // message ID
|
||||
uint32_t msgID = bufbe32toh (buf); // message ID
|
||||
buf += 4;
|
||||
uint8_t frag[4];
|
||||
frag[0] = 0;
|
||||
memcpy (frag + 1, buf, 3);
|
||||
buf += 3;
|
||||
uint32_t fragmentInfo = be32toh (*(uint32_t *)frag); // fragment info
|
||||
uint32_t fragmentInfo = bufbe32toh (frag); // fragment info
|
||||
uint16_t fragmentSize = fragmentInfo & 0x1FFF; // bits 0 - 13
|
||||
bool isLast = fragmentInfo & 0x010000; // bit 16
|
||||
uint8_t fragmentNum = fragmentInfo >> 17; // bits 23 - 17
|
||||
@@ -168,7 +168,7 @@ namespace transport
|
||||
{
|
||||
// create new message
|
||||
msg = NewI2NPMessage ();
|
||||
msg->len -= sizeof (I2NPHeaderShort);
|
||||
msg->len -= I2NP_SHORT_HEADER_SIZE;
|
||||
incompleteMessage = new IncompleteMessage (msg);
|
||||
m_IncomleteMessages[msgID] = incompleteMessage;
|
||||
}
|
||||
@@ -246,13 +246,13 @@ namespace transport
|
||||
else
|
||||
{
|
||||
// we expect DeliveryStatus
|
||||
if (msg->GetHeader ()->typeID == eI2NPDeliveryStatus)
|
||||
if (msg->GetTypeID () == eI2NPDeliveryStatus)
|
||||
{
|
||||
LogPrint ("SSU session established");
|
||||
m_Session.Established ();
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "SSU unexpected message ", (int)msg->GetHeader ()->typeID);
|
||||
LogPrint (eLogError, "SSU unexpected message ", (int)msg->GetTypeID ());
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
}
|
||||
@@ -401,8 +401,9 @@ namespace transport
|
||||
{
|
||||
m_ResendTimer.cancel ();
|
||||
m_ResendTimer.expires_from_now (boost::posix_time::seconds(RESEND_INTERVAL));
|
||||
m_ResendTimer.async_wait (boost::bind (&SSUData::HandleResendTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
auto s = m_Session.shared_from_this();
|
||||
m_ResendTimer.async_wait ([s](const boost::system::error_code& ecode)
|
||||
{ s->m_Data.HandleResendTimer (ecode); });
|
||||
}
|
||||
|
||||
void SSUData::HandleResendTimer (const boost::system::error_code& ecode)
|
||||
|
||||
118
SSUSession.cpp
118
SSUSession.cpp
@@ -21,8 +21,6 @@ namespace transport
|
||||
m_Data (*this), m_NumSentBytes (0), m_NumReceivedBytes (0)
|
||||
{
|
||||
m_CreationTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
if (!router) // incoming session
|
||||
ScheduleConnectTimer ();
|
||||
}
|
||||
|
||||
SSUSession::~SSUSession ()
|
||||
@@ -111,7 +109,7 @@ namespace transport
|
||||
else
|
||||
{
|
||||
LogPrint (eLogError, "MAC verification failed ", len, " bytes from ", senderEndpoint);
|
||||
m_Server.DeleteSession (this);
|
||||
m_Server.DeleteSession (shared_from_this ());
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -123,6 +121,7 @@ namespace transport
|
||||
|
||||
void SSUSession::ProcessMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
|
||||
{
|
||||
//TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
switch (header->GetPayloadType ())
|
||||
{
|
||||
@@ -146,13 +145,13 @@ namespace transport
|
||||
case PAYLOAD_TYPE_SESSION_DESTROYED:
|
||||
{
|
||||
LogPrint (eLogDebug, "SSU session destroy received");
|
||||
m_Server.DeleteSession (this); // delete this
|
||||
m_Server.DeleteSession (shared_from_this ());
|
||||
break;
|
||||
}
|
||||
case PAYLOAD_TYPE_RELAY_RESPONSE:
|
||||
ProcessRelayResponse (buf, len);
|
||||
if (m_State != eSessionStateEstablished)
|
||||
m_Server.DeleteSession (this);
|
||||
m_Server.DeleteSession (shared_from_this ());
|
||||
break;
|
||||
case PAYLOAD_TYPE_RELAY_REQUEST:
|
||||
LogPrint (eLogDebug, "SSU relay request received");
|
||||
@@ -212,7 +211,7 @@ namespace transport
|
||||
}
|
||||
s.Insert (ourAddress, addressSize); // our IP
|
||||
payload += addressSize; // address
|
||||
uint16_t ourPort = be16toh (*(uint16_t *)payload);
|
||||
uint16_t ourPort = bufbe16toh (payload);
|
||||
s.Insert (payload, 2); // our port
|
||||
payload += 2; // port
|
||||
LogPrint ("Our external address is ", ourIP.to_string (), ":", ourPort);
|
||||
@@ -223,13 +222,14 @@ namespace transport
|
||||
s.Insert (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), 16); // remote IP v6
|
||||
s.Insert (htobe16 (m_RemoteEndpoint.port ())); // remote port
|
||||
s.Insert (payload, 8); // relayTag and signed on time
|
||||
m_RelayTag = be32toh (*(uint32_t *)payload);
|
||||
m_RelayTag = bufbe32toh (payload);
|
||||
payload += 4; // relayTag
|
||||
payload += 4; // signed on time
|
||||
// decrypt signature
|
||||
size_t signatureLen = m_RemoteIdentity.GetSignatureLen ();
|
||||
size_t paddingSize = signatureLen & 0x0F; // %16
|
||||
if (paddingSize > 0) signatureLen += (16 - paddingSize);
|
||||
//TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
|
||||
m_SessionKeyDecryption.SetIV (((SSUHeader *)buf)->iv);
|
||||
m_SessionKeyDecryption.Decrypt (payload, signatureLen, payload);
|
||||
// verify
|
||||
@@ -244,7 +244,7 @@ namespace transport
|
||||
LogPrint (eLogDebug, "Session confirmed received");
|
||||
uint8_t * payload = buf + sizeof (SSUHeader);
|
||||
payload++; // identity fragment info
|
||||
uint16_t identitySize = be16toh (*(uint16_t *)payload);
|
||||
uint16_t identitySize = bufbe16toh (payload);
|
||||
payload += 2; // size of identity fragment
|
||||
m_RemoteIdentity.FromBuffer (payload, identitySize);
|
||||
m_Data.UpdatePacketSize (m_RemoteIdentity.GetIdentHash ());
|
||||
@@ -301,18 +301,18 @@ namespace transport
|
||||
|
||||
uint8_t buf[96 + 18];
|
||||
uint8_t * payload = buf + sizeof (SSUHeader);
|
||||
*(uint32_t *)payload = htobe32 (iTag);
|
||||
htobe32buf (payload, iTag);
|
||||
payload += 4;
|
||||
*payload = 0; // no address
|
||||
payload++;
|
||||
*(uint16_t *)payload = 0; // port = 0
|
||||
htobuf16(payload, 0); // port = 0
|
||||
payload += 2;
|
||||
*payload = 0; // challenge
|
||||
payload++;
|
||||
memcpy (payload, (const uint8_t *)address->key, 32);
|
||||
payload += 32;
|
||||
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
|
||||
*(uint32_t *)payload = htobe32 (rnd.GenerateWord32 ()); // nonce
|
||||
htobe32buf (payload, rnd.GenerateWord32 ()); // nonce
|
||||
|
||||
uint8_t iv[16];
|
||||
rnd.GenerateBlock (iv, 16); // random iv
|
||||
@@ -360,7 +360,7 @@ namespace transport
|
||||
s.Insert (payload, 16); // remote endpoint IP V6
|
||||
payload += 16;
|
||||
}
|
||||
*(uint16_t *)(payload) = htobe16 (m_RemoteEndpoint.port ());
|
||||
htobe16buf (payload, m_RemoteEndpoint.port ());
|
||||
s.Insert (payload, 2); // remote port
|
||||
payload += 2;
|
||||
if (address->host.is_v4 ())
|
||||
@@ -375,9 +375,9 @@ namespace transport
|
||||
if (!relayTag) relayTag = 1;
|
||||
m_Server.AddRelay (relayTag, m_RemoteEndpoint);
|
||||
}
|
||||
*(uint32_t *)(payload) = htobe32 (relayTag);
|
||||
htobe32buf (payload, relayTag);
|
||||
payload += 4; // relay tag
|
||||
*(uint32_t *)(payload) = htobe32 (i2p::util::GetSecondsSinceEpoch ()); // signed on time
|
||||
htobe32buf (payload, i2p::util::GetSecondsSinceEpoch ()); // signed on time
|
||||
payload += 4;
|
||||
s.Insert (payload - 8, 8); // relayTag and signed on time
|
||||
s.Sign (i2p::context.GetPrivateKeys (), payload); // DSA signature
|
||||
@@ -406,12 +406,12 @@ namespace transport
|
||||
*payload = 1; // 1 fragment
|
||||
payload++; // info
|
||||
size_t identLen = i2p::context.GetIdentity ().GetFullLen (); // 387+ bytes
|
||||
*(uint16_t *)(payload) = htobe16 (identLen);
|
||||
htobe16buf (payload, identLen);
|
||||
payload += 2; // cursize
|
||||
i2p::context.GetIdentity ().ToBuffer (payload, identLen);
|
||||
payload += identLen;
|
||||
uint32_t signedOnTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
*(uint32_t *)(payload) = htobe32 (signedOnTime); // signed on time
|
||||
htobe32buf (payload, signedOnTime); // signed on time
|
||||
payload += 4;
|
||||
auto signatureLen = i2p::context.GetIdentity ().GetSignatureLen ();
|
||||
size_t paddingSize = ((payload - buf) + signatureLen)%16;
|
||||
@@ -445,7 +445,7 @@ namespace transport
|
||||
|
||||
void SSUSession::ProcessRelayRequest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& from)
|
||||
{
|
||||
uint32_t relayTag = be32toh (*(uint32_t *)buf);
|
||||
uint32_t relayTag = bufbe32toh (buf);
|
||||
auto session = m_Server.FindRelaySession (relayTag);
|
||||
if (session)
|
||||
{
|
||||
@@ -459,9 +459,9 @@ namespace transport
|
||||
buf += challengeSize;
|
||||
uint8_t * introKey = buf;
|
||||
buf += 32; // introkey
|
||||
uint32_t nonce = be32toh (*(uint32_t *)buf);
|
||||
uint32_t nonce = bufbe32toh (buf);
|
||||
SendRelayResponse (nonce, from, introKey, session->m_RemoteEndpoint);
|
||||
SendRelayIntro (session, from);
|
||||
SendRelayIntro (session.get (), from);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,9 +478,9 @@ namespace transport
|
||||
}
|
||||
*payload = 4;
|
||||
payload++; // size
|
||||
*(uint32_t *)payload = htobe32 (to.address ().to_v4 ().to_ulong ()); // Charlie's IP
|
||||
htobe32buf (payload, to.address ().to_v4 ().to_ulong ()); // Charlie's IP
|
||||
payload += 4; // address
|
||||
*(uint16_t *)payload = htobe16 (to.port ()); // Charlie's port
|
||||
htobe16buf (payload, to.port ()); // Charlie's port
|
||||
payload += 2; // port
|
||||
// Alice
|
||||
bool isV4 = from.address ().is_v4 (); // Alice's
|
||||
@@ -498,9 +498,9 @@ namespace transport
|
||||
memcpy (payload, from.address ().to_v6 ().to_bytes ().data (), 16); // Alice's IP V6
|
||||
payload += 16; // address
|
||||
}
|
||||
*(uint16_t *)payload = htobe16 (from.port ()); // Alice's port
|
||||
htobe16buf (payload, from.port ()); // Alice's port
|
||||
payload += 2; // port
|
||||
*(uint32_t *)payload = htobe32 (nonce);
|
||||
htobe32buf (payload, nonce);
|
||||
|
||||
if (m_State == eSessionStateEstablished)
|
||||
{
|
||||
@@ -533,9 +533,9 @@ namespace transport
|
||||
uint8_t * payload = buf + sizeof (SSUHeader);
|
||||
*payload = 4;
|
||||
payload++; // size
|
||||
*(uint32_t *)payload = htobe32 (from.address ().to_v4 ().to_ulong ()); // Alice's IP
|
||||
htobe32buf (payload, from.address ().to_v4 ().to_ulong ()); // Alice's IP
|
||||
payload += 4; // address
|
||||
*(uint16_t *)payload = htobe16 (from.port ()); // Alice's port
|
||||
htobe16buf (payload, from.port ()); // Alice's port
|
||||
payload += 2; // port
|
||||
*payload = 0; // challenge size
|
||||
uint8_t iv[16];
|
||||
@@ -552,9 +552,9 @@ namespace transport
|
||||
uint8_t * payload = buf + sizeof (SSUHeader);
|
||||
uint8_t remoteSize = *payload;
|
||||
payload++; // remote size
|
||||
//boost::asio::ip::address_v4 remoteIP (be32toh (*(uint32_t* )(payload)));
|
||||
//boost::asio::ip::address_v4 remoteIP (bufbe32toh (payload));
|
||||
payload += remoteSize; // remote address
|
||||
//uint16_t remotePort = be16toh (*(uint16_t *)(payload));
|
||||
//uint16_t remotePort = bufbe16toh (payload);
|
||||
payload += 2; // remote port
|
||||
uint8_t ourSize = *payload;
|
||||
payload++; // our size
|
||||
@@ -572,7 +572,7 @@ namespace transport
|
||||
ourIP = boost::asio::ip::address_v6 (bytes);
|
||||
}
|
||||
payload += ourSize; // our address
|
||||
uint16_t ourPort = be16toh (*(uint16_t *)(payload));
|
||||
uint16_t ourPort = bufbe16toh (payload);
|
||||
payload += 2; // our port
|
||||
LogPrint ("Our external address is ", ourIP.to_string (), ":", ourPort);
|
||||
i2p::context.UpdateAddress (ourIP);
|
||||
@@ -584,9 +584,9 @@ namespace transport
|
||||
if (size == 4)
|
||||
{
|
||||
buf++; // size
|
||||
boost::asio::ip::address_v4 address (be32toh (*(uint32_t* )buf));
|
||||
boost::asio::ip::address_v4 address (bufbe32toh (buf));
|
||||
buf += 4; // address
|
||||
uint16_t port = be16toh (*(uint16_t *)buf);
|
||||
uint16_t port = bufbe16toh (buf);
|
||||
// send hole punch of 1 byte
|
||||
m_Server.Send (buf, 0, boost::asio::ip::udp::endpoint (address, port));
|
||||
}
|
||||
@@ -602,10 +602,11 @@ namespace transport
|
||||
LogPrint (eLogError, "Unexpected SSU packet length ", len);
|
||||
return;
|
||||
}
|
||||
//TODO: we are using a dirty solution here but should work for now
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
memcpy (header->iv, iv, 16);
|
||||
header->flag = payloadType << 4; // MSB is 0
|
||||
header->time = htobe32 (i2p::util::GetSecondsSinceEpoch ());
|
||||
htobe32buf (&(header->time), i2p::util::GetSecondsSinceEpoch ());
|
||||
uint8_t * encrypted = &header->flag;
|
||||
uint16_t encryptedLen = len - (encrypted - buf);
|
||||
i2p::crypto::CBCEncryption encryption;
|
||||
@@ -614,7 +615,7 @@ namespace transport
|
||||
encryption.Encrypt (encrypted, encryptedLen, encrypted);
|
||||
// assume actual buffer size is 18 (16 + 2) bytes more
|
||||
memcpy (buf + len, iv, 16);
|
||||
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
|
||||
htobe16buf (buf + len + 16, encryptedLen);
|
||||
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, header->mac);
|
||||
}
|
||||
|
||||
@@ -625,17 +626,18 @@ namespace transport
|
||||
LogPrint (eLogError, "Unexpected SSU packet length ", len);
|
||||
return;
|
||||
}
|
||||
//TODO: we are using a dirty solution here but should work for now
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
i2p::context.GetRandomNumberGenerator ().GenerateBlock (header->iv, 16); // random iv
|
||||
m_SessionKeyEncryption.SetIV (header->iv);
|
||||
header->flag = payloadType << 4; // MSB is 0
|
||||
header->time = htobe32 (i2p::util::GetSecondsSinceEpoch ());
|
||||
htobe32buf (&(header->time), i2p::util::GetSecondsSinceEpoch ());
|
||||
uint8_t * encrypted = &header->flag;
|
||||
uint16_t encryptedLen = len - (encrypted - buf);
|
||||
m_SessionKeyEncryption.Encrypt (encrypted, encryptedLen, encrypted);
|
||||
// assume actual buffer size is 18 (16 + 2) bytes more
|
||||
memcpy (buf + len, header->iv, 16);
|
||||
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
|
||||
htobe16buf (buf + len + 16, encryptedLen);
|
||||
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, m_MacKey, header->mac);
|
||||
}
|
||||
|
||||
@@ -646,6 +648,7 @@ namespace transport
|
||||
LogPrint (eLogError, "Unexpected SSU packet length ", len);
|
||||
return;
|
||||
}
|
||||
//TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
uint8_t * encrypted = &header->flag;
|
||||
uint16_t encryptedLen = len - (encrypted - buf);
|
||||
@@ -662,6 +665,7 @@ namespace transport
|
||||
LogPrint (eLogError, "Unexpected SSU packet length ", len);
|
||||
return;
|
||||
}
|
||||
//TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
uint8_t * encrypted = &header->flag;
|
||||
uint16_t encryptedLen = len - (encrypted - buf);
|
||||
@@ -679,12 +683,13 @@ namespace transport
|
||||
LogPrint (eLogError, "Unexpected SSU packet length ", len);
|
||||
return false;
|
||||
}
|
||||
//TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
|
||||
SSUHeader * header = (SSUHeader *)buf;
|
||||
uint8_t * encrypted = &header->flag;
|
||||
uint16_t encryptedLen = len - (encrypted - buf);
|
||||
// assume actual buffer size is 18 (16 + 2) bytes more
|
||||
memcpy (buf + len, header->iv, 16);
|
||||
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
|
||||
htobe16buf (buf + len + 16, encryptedLen);
|
||||
uint8_t digest[16];
|
||||
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, digest);
|
||||
return !memcmp (header->mac, digest, 16);
|
||||
@@ -701,12 +706,20 @@ namespace transport
|
||||
}
|
||||
}
|
||||
|
||||
void SSUSession::WaitForConnect ()
|
||||
{
|
||||
if (!m_RemoteRouter) // incoming session
|
||||
ScheduleConnectTimer ();
|
||||
else
|
||||
LogPrint (eLogError, "SSU wait for connect for outgoing session");
|
||||
}
|
||||
|
||||
void SSUSession::ScheduleConnectTimer ()
|
||||
{
|
||||
m_Timer.cancel ();
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SSUSession::HandleConnectTimer (const boost::system::error_code& ecode)
|
||||
@@ -725,8 +738,8 @@ namespace transport
|
||||
{
|
||||
// set connect timer
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
SendRelayRequest (iTag, iKey);
|
||||
}
|
||||
@@ -736,8 +749,8 @@ namespace transport
|
||||
m_State = eSessionStateIntroduced;
|
||||
// set connect timer
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SSUSession::Close ()
|
||||
@@ -776,7 +789,7 @@ namespace transport
|
||||
if (m_State != eSessionStateFailed)
|
||||
{
|
||||
m_State = eSessionStateFailed;
|
||||
m_Server.DeleteSession (this); // delete this
|
||||
m_Server.DeleteSession (shared_from_this ());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,8 +797,8 @@ namespace transport
|
||||
{
|
||||
m_Timer.cancel ();
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_TIMEOUT));
|
||||
m_Timer.async_wait (boost::bind (&SSUSession::HandleTerminationTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_Timer.async_wait (std::bind (&SSUSession::HandleTerminationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void SSUSession::HandleTerminationTimer (const boost::system::error_code& ecode)
|
||||
@@ -815,7 +828,7 @@ namespace transport
|
||||
|
||||
void SSUSession::SendI2NPMessage (I2NPMessage * msg)
|
||||
{
|
||||
m_Server.GetService ().post (boost::bind (&SSUSession::PostI2NPMessage, this, msg));
|
||||
m_Server.GetService ().post (std::bind (&SSUSession::PostI2NPMessage, shared_from_this (), msg));
|
||||
}
|
||||
|
||||
void SSUSession::PostI2NPMessage (I2NPMessage * msg)
|
||||
@@ -838,13 +851,14 @@ namespace transport
|
||||
void SSUSession::ProcessPeerTest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
|
||||
{
|
||||
uint8_t * buf1 = buf;
|
||||
uint32_t nonce = be32toh (*(uint32_t *)buf);
|
||||
uint32_t nonce = bufbe32toh (buf);
|
||||
buf += 4; // nonce
|
||||
uint8_t size = *buf;
|
||||
buf++; // size
|
||||
uint32_t address = (size == 4) ? *(uint32_t *)buf : 0; // use it as is
|
||||
|
||||
uint32_t address = (size == 4) ? buf32toh(buf) : 0; // use it as is
|
||||
buf += size; // address
|
||||
uint16_t port = *(uint16_t *)buf; // use it as is
|
||||
uint16_t port = buf16toh(buf); // use it as is
|
||||
buf += 2; // port
|
||||
uint8_t * introKey = buf;
|
||||
if (port && !address)
|
||||
@@ -891,7 +905,7 @@ namespace transport
|
||||
else
|
||||
{
|
||||
LogPrint (eLogDebug, "SSU peer test from Alice. We are Bob");
|
||||
auto session = m_Server.GetRandomEstablishedSession (this); // charlie
|
||||
auto session = m_Server.GetRandomEstablishedSession (shared_from_this ()); // charlie
|
||||
if (session)
|
||||
session->SendPeerTest (nonce, senderEndpoint.address ().to_v4 ().to_ulong (),
|
||||
senderEndpoint.port (), introKey, false);
|
||||
@@ -908,13 +922,13 @@ namespace transport
|
||||
uint8_t buf[80 + 18];
|
||||
uint8_t iv[16];
|
||||
uint8_t * payload = buf + sizeof (SSUHeader);
|
||||
*(uint32_t *)payload = htobe32 (nonce);
|
||||
htobe32buf (payload, nonce);
|
||||
payload += 4; // nonce
|
||||
if (address)
|
||||
{
|
||||
*payload = 4;
|
||||
payload++; // size
|
||||
*(uint32_t *)payload = htobe32 (address);
|
||||
htobe32buf (payload, address);
|
||||
payload += 4; // address
|
||||
}
|
||||
else
|
||||
@@ -922,7 +936,7 @@ namespace transport
|
||||
*payload = 0;
|
||||
payload++; //size
|
||||
}
|
||||
*(uint16_t *)payload = htobe16 (port);
|
||||
htobe16buf (payload, port);
|
||||
payload += 2; // port
|
||||
memcpy (payload, introKey, 32); // intro key
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <inttypes.h>
|
||||
#include <set>
|
||||
#include <list>
|
||||
#include <boost/asio.hpp>
|
||||
#include <memory>
|
||||
#include "aes.h"
|
||||
#include "hmac.h"
|
||||
#include "I2NPProtocol.h"
|
||||
@@ -50,7 +50,7 @@ namespace transport
|
||||
};
|
||||
|
||||
class SSUServer;
|
||||
class SSUSession: public TransportSession
|
||||
class SSUSession: public TransportSession, public std::enable_shared_from_this<SSUSession>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -60,6 +60,7 @@ namespace transport
|
||||
~SSUSession ();
|
||||
|
||||
void Connect ();
|
||||
void WaitForConnect ();
|
||||
void Introduce (uint32_t iTag, const uint8_t * iKey);
|
||||
void WaitForIntroduction ();
|
||||
void Close ();
|
||||
|
||||
324
Signature.h
324
Signature.h
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <cryptopp/dsa.h>
|
||||
#include <cryptopp/rsa.h>
|
||||
#include <cryptopp/asn.h>
|
||||
#include <cryptopp/oids.h>
|
||||
#include <cryptopp/osrng.h>
|
||||
@@ -21,6 +22,7 @@ namespace crypto
|
||||
virtual bool Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const = 0;
|
||||
virtual size_t GetPublicKeyLen () const = 0;
|
||||
virtual size_t GetSignatureLen () const = 0;
|
||||
virtual size_t GetPrivateKeyLen () const { return GetSignatureLen ()/2; };
|
||||
};
|
||||
|
||||
class Signer
|
||||
@@ -87,67 +89,327 @@ namespace crypto
|
||||
publicKey.GetPublicElement ().Encode (signingPublicKey, DSA_PUBLIC_KEY_LENGTH);
|
||||
}
|
||||
|
||||
|
||||
const size_t ECDSAP256_PUBLIC_KEY_LENGTH = 64;
|
||||
const size_t ECDSAP256_PUBLIC_KEY_HALF_LENGTH = ECDSAP256_PUBLIC_KEY_LENGTH/2;
|
||||
const size_t ECDSAP256_SIGNATURE_LENGTH = 64;
|
||||
const size_t ECDSAP256_PRIVATE_KEY_LENGTH = ECDSAP256_SIGNATURE_LENGTH/2;
|
||||
class ECDSAP256Verifier: public Verifier
|
||||
{
|
||||
template<typename Hash, size_t keyLen>
|
||||
class ECDSAVerifier: public Verifier
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP256Verifier (const uint8_t * signingKey)
|
||||
template<typename Curve>
|
||||
ECDSAVerifier (Curve curve, const uint8_t * signingKey)
|
||||
{
|
||||
m_PublicKey.Initialize (CryptoPP::ASN1::secp256r1(),
|
||||
CryptoPP::ECP::Point (CryptoPP::Integer (signingKey, ECDSAP256_PUBLIC_KEY_HALF_LENGTH),
|
||||
CryptoPP::Integer (signingKey + ECDSAP256_PUBLIC_KEY_HALF_LENGTH, ECDSAP256_PUBLIC_KEY_HALF_LENGTH)));
|
||||
}
|
||||
m_PublicKey.Initialize (curve,
|
||||
CryptoPP::ECP::Point (CryptoPP::Integer (signingKey, keyLen/2),
|
||||
CryptoPP::Integer (signingKey + keyLen/2, keyLen/2)));
|
||||
}
|
||||
|
||||
bool Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const
|
||||
{
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::Verifier verifier (m_PublicKey);
|
||||
return verifier.VerifyMessage (buf, len, signature, ECDSAP256_SIGNATURE_LENGTH);
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::Verifier verifier (m_PublicKey);
|
||||
return verifier.VerifyMessage (buf, len, signature, keyLen); // signature length
|
||||
}
|
||||
|
||||
size_t GetPublicKeyLen () const { return ECDSAP256_PUBLIC_KEY_LENGTH; };
|
||||
size_t GetSignatureLen () const { return ECDSAP256_SIGNATURE_LENGTH; };
|
||||
size_t GetPublicKeyLen () const { return keyLen; };
|
||||
size_t GetSignatureLen () const { return keyLen; }; // signature length = key length
|
||||
|
||||
private:
|
||||
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey m_PublicKey;
|
||||
};
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::PublicKey m_PublicKey;
|
||||
};
|
||||
|
||||
class ECDSAP256Signer: public Signer
|
||||
template<typename Hash>
|
||||
class ECDSASigner: public Signer
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP256Signer (const uint8_t * signingPrivateKey)
|
||||
template<typename Curve>
|
||||
ECDSASigner (Curve curve, const uint8_t * signingPrivateKey, size_t keyLen)
|
||||
{
|
||||
m_PrivateKey.Initialize (CryptoPP::ASN1::secp256r1(), CryptoPP::Integer (signingPrivateKey, ECDSAP256_PRIVATE_KEY_LENGTH));
|
||||
m_PrivateKey.Initialize (curve, CryptoPP::Integer (signingPrivateKey, keyLen/2)); // private key length
|
||||
}
|
||||
|
||||
void Sign (CryptoPP::RandomNumberGenerator& rnd, const uint8_t * buf, int len, uint8_t * signature) const
|
||||
{
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::Signer signer (m_PrivateKey);
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::Signer signer (m_PrivateKey);
|
||||
signer.SignMessage (rnd, buf, len, signature);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey m_PrivateKey;
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::PrivateKey m_PrivateKey;
|
||||
};
|
||||
|
||||
template<typename Hash, typename Curve>
|
||||
inline void CreateECDSARandomKeys (CryptoPP::RandomNumberGenerator& rnd, Curve curve,
|
||||
size_t keyLen, uint8_t * signingPrivateKey, uint8_t * signingPublicKey)
|
||||
{
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::PrivateKey privateKey;
|
||||
typename CryptoPP::ECDSA<CryptoPP::ECP, Hash>::PublicKey publicKey;
|
||||
privateKey.Initialize (rnd, curve);
|
||||
privateKey.MakePublicKey (publicKey);
|
||||
privateKey.GetPrivateExponent ().Encode (signingPrivateKey, keyLen/2);
|
||||
auto q = publicKey.GetPublicElement ();
|
||||
q.x.Encode (signingPublicKey, keyLen/2);
|
||||
q.y.Encode (signingPublicKey + keyLen/2, keyLen/2);
|
||||
}
|
||||
|
||||
// ECDSA_SHA256_P256
|
||||
const size_t ECDSAP256_KEY_LENGTH = 64;
|
||||
class ECDSAP256Verifier: public ECDSAVerifier<CryptoPP::SHA256, ECDSAP256_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP256Verifier (const uint8_t * signingKey):
|
||||
ECDSAVerifier (CryptoPP::ASN1::secp256r1(), signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class ECDSAP256Signer: public ECDSASigner<CryptoPP::SHA256>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP256Signer (const uint8_t * signingPrivateKey):
|
||||
ECDSASigner (CryptoPP::ASN1::secp256r1(), signingPrivateKey, ECDSAP256_KEY_LENGTH)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
inline void CreateECDSAP256RandomKeys (CryptoPP::RandomNumberGenerator& rnd, uint8_t * signingPrivateKey, uint8_t * signingPublicKey)
|
||||
{
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey privateKey;
|
||||
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PublicKey publicKey;
|
||||
privateKey.Initialize (rnd, CryptoPP::ASN1::secp256r1());
|
||||
privateKey.MakePublicKey (publicKey);
|
||||
privateKey.GetPrivateExponent ().Encode (signingPrivateKey, ECDSAP256_PRIVATE_KEY_LENGTH);
|
||||
auto q = publicKey.GetPublicElement ();
|
||||
q.x.Encode (signingPublicKey, ECDSAP256_PUBLIC_KEY_HALF_LENGTH);
|
||||
q.y.Encode (signingPublicKey + ECDSAP256_PUBLIC_KEY_HALF_LENGTH, ECDSAP256_PUBLIC_KEY_HALF_LENGTH);
|
||||
CreateECDSARandomKeys<CryptoPP::SHA256> (rnd, CryptoPP::ASN1::secp256r1(), ECDSAP256_KEY_LENGTH, signingPrivateKey, signingPublicKey);
|
||||
}
|
||||
|
||||
// ECDSA_SHA384_P384
|
||||
const size_t ECDSAP384_KEY_LENGTH = 96;
|
||||
class ECDSAP384Verifier: public ECDSAVerifier<CryptoPP::SHA384, ECDSAP384_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP384Verifier (const uint8_t * signingKey):
|
||||
ECDSAVerifier (CryptoPP::ASN1::secp384r1(), signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class ECDSAP384Signer: public ECDSASigner<CryptoPP::SHA384>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP384Signer (const uint8_t * signingPrivateKey):
|
||||
ECDSASigner (CryptoPP::ASN1::secp384r1(), signingPrivateKey, ECDSAP384_KEY_LENGTH)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
inline void CreateECDSAP384RandomKeys (CryptoPP::RandomNumberGenerator& rnd, uint8_t * signingPrivateKey, uint8_t * signingPublicKey)
|
||||
{
|
||||
CreateECDSARandomKeys<CryptoPP::SHA384> (rnd, CryptoPP::ASN1::secp384r1(), ECDSAP384_KEY_LENGTH, signingPrivateKey, signingPublicKey);
|
||||
}
|
||||
|
||||
// ECDSA_SHA512_P521
|
||||
const size_t ECDSAP521_KEY_LENGTH = 132;
|
||||
class ECDSAP521Verifier: public ECDSAVerifier<CryptoPP::SHA512, ECDSAP521_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP521Verifier (const uint8_t * signingKey):
|
||||
ECDSAVerifier (CryptoPP::ASN1::secp521r1(), signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class ECDSAP521Signer: public ECDSASigner<CryptoPP::SHA512>
|
||||
{
|
||||
public:
|
||||
|
||||
ECDSAP521Signer (const uint8_t * signingPrivateKey):
|
||||
ECDSASigner (CryptoPP::ASN1::secp521r1(), signingPrivateKey, ECDSAP521_KEY_LENGTH)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
inline void CreateECDSAP521RandomKeys (CryptoPP::RandomNumberGenerator& rnd, uint8_t * signingPrivateKey, uint8_t * signingPublicKey)
|
||||
{
|
||||
CreateECDSARandomKeys<CryptoPP::SHA512> (rnd, CryptoPP::ASN1::secp521r1(), ECDSAP521_KEY_LENGTH, signingPrivateKey, signingPublicKey);
|
||||
}
|
||||
|
||||
// RSA
|
||||
template<typename Hash, size_t keyLen>
|
||||
class RSAVerifier: public Verifier
|
||||
{
|
||||
public:
|
||||
|
||||
RSAVerifier (const uint8_t * signingKey)
|
||||
{
|
||||
m_PublicKey.Initialize (CryptoPP::Integer (signingKey, keyLen), CryptoPP::Integer (rsae));
|
||||
}
|
||||
|
||||
bool Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const
|
||||
{
|
||||
typename CryptoPP::RSASS<CryptoPP::PKCS1v15, Hash>::Verifier verifier (m_PublicKey);
|
||||
return verifier.VerifyMessage (buf, len, signature, keyLen); // signature length
|
||||
}
|
||||
size_t GetPublicKeyLen () const { return keyLen; }
|
||||
size_t GetSignatureLen () const { return keyLen; }
|
||||
size_t GetPrivateKeyLen () const { return GetSignatureLen ()*2; };
|
||||
|
||||
private:
|
||||
|
||||
CryptoPP::RSA::PublicKey m_PublicKey;
|
||||
};
|
||||
|
||||
|
||||
template<typename Hash>
|
||||
class RSASigner: public Signer
|
||||
{
|
||||
public:
|
||||
|
||||
RSASigner (const uint8_t * signingPrivateKey, size_t keyLen)
|
||||
{
|
||||
m_PrivateKey.Initialize (CryptoPP::Integer (signingPrivateKey, keyLen/2),
|
||||
rsae,
|
||||
CryptoPP::Integer (signingPrivateKey + keyLen/2, keyLen/2));
|
||||
}
|
||||
|
||||
void Sign (CryptoPP::RandomNumberGenerator& rnd, const uint8_t * buf, int len, uint8_t * signature) const
|
||||
{
|
||||
typename CryptoPP::RSASS<CryptoPP::PKCS1v15, Hash>::Signer signer (m_PrivateKey);
|
||||
signer.SignMessage (rnd, buf, len, signature);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
CryptoPP::RSA::PrivateKey m_PrivateKey;
|
||||
};
|
||||
|
||||
inline void CreateRSARandomKeys (CryptoPP::RandomNumberGenerator& rnd,
|
||||
size_t publicKeyLen, uint8_t * signingPrivateKey, uint8_t * signingPublicKey)
|
||||
{
|
||||
CryptoPP::RSA::PrivateKey privateKey;
|
||||
privateKey.Initialize (rnd, publicKeyLen*8, rsae);
|
||||
privateKey.GetModulus ().Encode (signingPrivateKey, publicKeyLen);
|
||||
privateKey.GetPrivateExponent ().Encode (signingPrivateKey + publicKeyLen, publicKeyLen);
|
||||
privateKey.GetModulus ().Encode (signingPublicKey, publicKeyLen);
|
||||
}
|
||||
|
||||
|
||||
// RSA_SHA256_2048
|
||||
const size_t RSASHA2562048_KEY_LENGTH = 256;
|
||||
class RSASHA2562048Verifier: public RSAVerifier<CryptoPP::SHA256, RSASHA2562048_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA2562048Verifier (const uint8_t * signingKey): RSAVerifier (signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class RSASHA2562048Signer: public RSASigner<CryptoPP::SHA256>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA2562048Signer (const uint8_t * signingPrivateKey):
|
||||
RSASigner (signingPrivateKey, RSASHA2562048_KEY_LENGTH*2)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// RSA_SHA384_3072
|
||||
const size_t RSASHA3843072_KEY_LENGTH = 384;
|
||||
class RSASHA3843072Verifier: public RSAVerifier<CryptoPP::SHA384, RSASHA3843072_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA3843072Verifier (const uint8_t * signingKey): RSAVerifier (signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class RSASHA3843072Signer: public RSASigner<CryptoPP::SHA384>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA3843072Signer (const uint8_t * signingPrivateKey):
|
||||
RSASigner (signingPrivateKey, RSASHA3843072_KEY_LENGTH*2)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// RSA_SHA512_4096
|
||||
const size_t RSASHA5124096_KEY_LENGTH = 512;
|
||||
class RSASHA5124096Verifier: public RSAVerifier<CryptoPP::SHA512, RSASHA5124096_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA5124096Verifier (const uint8_t * signingKey): RSAVerifier (signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class RSASHA5124096Signer: public RSASigner<CryptoPP::SHA512>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA5124096Signer (const uint8_t * signingPrivateKey):
|
||||
RSASigner (signingPrivateKey, RSASHA5124096_KEY_LENGTH*2)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// Raw verifiers
|
||||
class RawVerifier
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~RawVerifier () {};
|
||||
virtual void Update (const uint8_t * buf, size_t len) = 0;
|
||||
virtual bool Verify (const uint8_t * signature) = 0;
|
||||
};
|
||||
|
||||
template<typename Hash, size_t keyLen>
|
||||
class RSARawVerifier: public RawVerifier
|
||||
{
|
||||
public:
|
||||
|
||||
RSARawVerifier (const uint8_t * signingKey):
|
||||
n (signingKey, keyLen)
|
||||
{
|
||||
}
|
||||
|
||||
void Update (const uint8_t * buf, size_t len)
|
||||
{
|
||||
m_Hash.Update (buf, len);
|
||||
}
|
||||
|
||||
bool Verify (const uint8_t * signature)
|
||||
{
|
||||
// RSA encryption first
|
||||
CryptoPP::Integer enSig (a_exp_b_mod_c (CryptoPP::Integer (signature, keyLen),
|
||||
CryptoPP::Integer (i2p::crypto::rsae), n)); // s^e mod n
|
||||
uint8_t enSigBuf[keyLen];
|
||||
enSig.Encode (enSigBuf, keyLen);
|
||||
|
||||
uint8_t digest[Hash::DIGESTSIZE];
|
||||
m_Hash.Final (digest);
|
||||
if ((int)keyLen < Hash::DIGESTSIZE) return false; // can't verify digest longer than key
|
||||
// we assume digest is right aligned, at least for PKCS#1 v1.5 padding
|
||||
return !memcmp (enSigBuf + (keyLen - Hash::DIGESTSIZE), digest, Hash::DIGESTSIZE);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
CryptoPP::Integer n; // RSA modulus
|
||||
Hash m_Hash;
|
||||
};
|
||||
|
||||
class RSASHA5124096RawVerifier: public RSARawVerifier<CryptoPP::SHA512, RSASHA5124096_KEY_LENGTH>
|
||||
{
|
||||
public:
|
||||
|
||||
RSASHA5124096RawVerifier (const uint8_t * signingKey): RSARawVerifier (signingKey)
|
||||
{
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
273
Streaming.cpp
273
Streaming.cpp
@@ -15,9 +15,9 @@ namespace stream
|
||||
const i2p::data::LeaseSet& remote, int port): m_Service (service), m_SendStreamID (0),
|
||||
m_SequenceNumber (0), m_LastReceivedSequenceNumber (-1), m_IsOpen (false),
|
||||
m_IsReset (false), m_IsAckSendScheduled (false), m_LocalDestination (local),
|
||||
m_RemoteLeaseSet (&remote), m_RoutingSession (nullptr), m_ReceiveTimer (m_Service),
|
||||
m_ResendTimer (m_Service), m_AckSendTimer (m_Service), m_NumSentBytes (0),
|
||||
m_NumReceivedBytes (0), m_Port (port)
|
||||
m_RemoteLeaseSet (&remote), m_RoutingSession (nullptr), m_CurrentOutboundTunnel (nullptr),
|
||||
m_ReceiveTimer (m_Service), m_ResendTimer (m_Service), m_AckSendTimer (m_Service),
|
||||
m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (port)
|
||||
{
|
||||
m_RecvStreamID = i2p::context.GetRandomNumberGenerator ().GenerateWord32 ();
|
||||
UpdateCurrentRemoteLease ();
|
||||
@@ -26,9 +26,9 @@ namespace stream
|
||||
Stream::Stream (boost::asio::io_service& service, StreamingDestination& local):
|
||||
m_Service (service), m_SendStreamID (0), m_SequenceNumber (0), m_LastReceivedSequenceNumber (-1),
|
||||
m_IsOpen (false), m_IsReset (false), m_IsAckSendScheduled (false), m_LocalDestination (local),
|
||||
m_RemoteLeaseSet (nullptr), m_RoutingSession (nullptr), m_ReceiveTimer (m_Service),
|
||||
m_ResendTimer (m_Service), m_AckSendTimer (m_Service), m_NumSentBytes (0),
|
||||
m_NumReceivedBytes (0), m_Port (0)
|
||||
m_RemoteLeaseSet (nullptr), m_RoutingSession (nullptr), m_CurrentOutboundTunnel (nullptr),
|
||||
m_ReceiveTimer (m_Service), m_ResendTimer (m_Service), m_AckSendTimer (m_Service),
|
||||
m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (0)
|
||||
{
|
||||
m_RecvStreamID = i2p::context.GetRandomNumberGenerator ().GenerateWord32 ();
|
||||
}
|
||||
@@ -52,8 +52,7 @@ namespace stream
|
||||
for (auto it: m_SavedPackets)
|
||||
delete it;
|
||||
m_SavedPackets.clear ();
|
||||
|
||||
Close ();
|
||||
LogPrint (eLogDebug, "Stream deleted");
|
||||
}
|
||||
|
||||
void Stream::HandleNextPacket (Packet * packet)
|
||||
@@ -70,12 +69,12 @@ namespace stream
|
||||
if (!receivedSeqn && !isSyn)
|
||||
{
|
||||
// plain ack
|
||||
LogPrint ("Plain ACK received");
|
||||
LogPrint (eLogDebug, "Plain ACK received");
|
||||
delete packet;
|
||||
return;
|
||||
}
|
||||
|
||||
LogPrint ("Received seqn=", receivedSeqn);
|
||||
LogPrint (eLogDebug, "Received seqn=", receivedSeqn);
|
||||
if (isSyn || receivedSeqn == m_LastReceivedSequenceNumber + 1)
|
||||
{
|
||||
// we have received next in sequence message
|
||||
@@ -102,8 +101,8 @@ namespace stream
|
||||
{
|
||||
m_IsAckSendScheduled = true;
|
||||
m_AckSendTimer.expires_from_now (boost::posix_time::milliseconds(ACK_SEND_TIMEOUT));
|
||||
m_AckSendTimer.async_wait (boost::bind (&Stream::HandleAckSendTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_AckSendTimer.async_wait (std::bind (&Stream::HandleAckSendTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
else if (isSyn)
|
||||
@@ -115,17 +114,24 @@ namespace stream
|
||||
if (receivedSeqn <= m_LastReceivedSequenceNumber)
|
||||
{
|
||||
// we have received duplicate. Most likely our outbound tunnel is dead
|
||||
LogPrint ("Duplicate message ", receivedSeqn, " received");
|
||||
m_LocalDestination.GetOwner ().ResetCurrentOutboundTunnel (); // pick another outbound tunnel
|
||||
LogPrint (eLogWarning, "Duplicate message ", receivedSeqn, " received");
|
||||
m_CurrentOutboundTunnel = nullptr; // pick another outbound tunnel
|
||||
UpdateCurrentRemoteLease (); // pick another lease
|
||||
SendQuickAck (); // resend ack for previous message again
|
||||
delete packet; // packet dropped
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Missing messages from ", m_LastReceivedSequenceNumber + 1, " to ", receivedSeqn - 1);
|
||||
LogPrint (eLogWarning, "Missing messages from ", m_LastReceivedSequenceNumber + 1, " to ", receivedSeqn - 1);
|
||||
// save message and wait for missing message again
|
||||
SavePacket (packet);
|
||||
// send NACKs for missing messages ASAP
|
||||
if (m_IsAckSendScheduled)
|
||||
{
|
||||
m_IsAckSendScheduled = false;
|
||||
m_AckSendTimer.cancel ();
|
||||
}
|
||||
SendQuickAck ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,11 +146,11 @@ namespace stream
|
||||
// process flags
|
||||
uint32_t receivedSeqn = packet->GetSeqn ();
|
||||
uint16_t flags = packet->GetFlags ();
|
||||
LogPrint ("Process seqn=", receivedSeqn, ", flags=", flags);
|
||||
LogPrint (eLogDebug, "Process seqn=", receivedSeqn, ", flags=", flags);
|
||||
|
||||
const uint8_t * optionData = packet->GetOptionData ();
|
||||
if (flags & PACKET_FLAG_SYNCHRONIZE)
|
||||
LogPrint ("Synchronize");
|
||||
LogPrint (eLogDebug, "Synchronize");
|
||||
|
||||
if (flags & PACKET_FLAG_DELAY_REQUESTED)
|
||||
{
|
||||
@@ -154,28 +160,28 @@ namespace stream
|
||||
if (flags & PACKET_FLAG_FROM_INCLUDED)
|
||||
{
|
||||
optionData += m_RemoteIdentity.FromBuffer (optionData, packet->GetOptionSize ());
|
||||
LogPrint ("From identity ", m_RemoteIdentity.GetIdentHash ().ToBase64 ());
|
||||
LogPrint (eLogInfo, "From identity ", m_RemoteIdentity.GetIdentHash ().ToBase64 ());
|
||||
if (!m_RemoteLeaseSet)
|
||||
LogPrint ("Incoming stream from ", m_RemoteIdentity.GetIdentHash ().ToBase64 ());
|
||||
LogPrint (eLogDebug, "Incoming stream from ", m_RemoteIdentity.GetIdentHash ().ToBase64 ());
|
||||
}
|
||||
|
||||
if (flags & PACKET_FLAG_MAX_PACKET_SIZE_INCLUDED)
|
||||
{
|
||||
uint16_t maxPacketSize = be16toh (*(uint16_t *)optionData);
|
||||
LogPrint ("Max packet size ", maxPacketSize);
|
||||
uint16_t maxPacketSize = bufbe16toh (optionData);
|
||||
LogPrint (eLogDebug, "Max packet size ", maxPacketSize);
|
||||
optionData += 2;
|
||||
}
|
||||
|
||||
if (flags & PACKET_FLAG_SIGNATURE_INCLUDED)
|
||||
{
|
||||
LogPrint ("Signature");
|
||||
LogPrint (eLogDebug, "Signature");
|
||||
uint8_t signature[256];
|
||||
auto signatureLen = m_RemoteIdentity.GetSignatureLen ();
|
||||
memcpy (signature, optionData, signatureLen);
|
||||
memset (const_cast<uint8_t *>(optionData), 0, signatureLen);
|
||||
if (!m_RemoteIdentity.Verify (packet->GetBuffer (), packet->GetLength (), signature))
|
||||
{
|
||||
LogPrint ("Signature verification failed");
|
||||
LogPrint (eLogError, "Signature verification failed");
|
||||
Close ();
|
||||
flags |= PACKET_FLAG_CLOSE;
|
||||
}
|
||||
@@ -196,13 +202,10 @@ namespace stream
|
||||
|
||||
if (flags & PACKET_FLAG_CLOSE)
|
||||
{
|
||||
LogPrint ("Closed");
|
||||
SendQuickAck (); // send ack for close explicitly?
|
||||
LogPrint (eLogInfo, "Closed");
|
||||
Close ();
|
||||
m_IsOpen = false;
|
||||
m_IsReset = true;
|
||||
m_ReceiveTimer.cancel ();
|
||||
m_ResendTimer.cancel ();
|
||||
m_AckSendTimer.cancel ();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,13 +229,13 @@ namespace stream
|
||||
}
|
||||
if (nacked)
|
||||
{
|
||||
LogPrint ("Packet ", seqn, " NACK");
|
||||
LogPrint (eLogDebug, "Packet ", seqn, " NACK");
|
||||
it++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
auto sentPacket = *it;
|
||||
LogPrint ("Packet ", seqn, " acknowledged");
|
||||
LogPrint (eLogDebug, "Packet ", seqn, " acknowledged");
|
||||
m_SentPackets.erase (it++);
|
||||
delete sentPacket;
|
||||
}
|
||||
@@ -246,25 +249,27 @@ namespace stream
|
||||
size_t Stream::Send (const uint8_t * buf, size_t len)
|
||||
{
|
||||
bool isNoAck = m_LastReceivedSequenceNumber < 0; // first packet
|
||||
std::vector<Packet *> packets;
|
||||
while (!m_IsOpen || len > 0)
|
||||
{
|
||||
Packet * p = new Packet ();
|
||||
uint8_t * packet = p->GetBuffer ();
|
||||
// TODO: implement setters
|
||||
size_t size = 0;
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_SendStreamID);
|
||||
htobe32buf (packet + size, m_SendStreamID);
|
||||
size += 4; // sendStreamID
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_RecvStreamID);
|
||||
htobe32buf (packet + size, m_RecvStreamID);
|
||||
size += 4; // receiveStreamID
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_SequenceNumber++);
|
||||
htobe32buf (packet + size, m_SequenceNumber++);
|
||||
size += 4; // sequenceNum
|
||||
if (isNoAck)
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_LastReceivedSequenceNumber);
|
||||
htobe32buf (packet + size, m_LastReceivedSequenceNumber);
|
||||
else
|
||||
*(uint32_t *)(packet + size) = 0;
|
||||
htobuf32 (packet + size, 0);
|
||||
size += 4; // ack Through
|
||||
packet[size] = 0;
|
||||
size++; // NACK count
|
||||
packet[size] = RESEND_TIMEOUT;
|
||||
size++; // resend delay
|
||||
if (!m_IsOpen)
|
||||
{
|
||||
@@ -273,15 +278,15 @@ namespace stream
|
||||
uint16_t flags = PACKET_FLAG_SYNCHRONIZE | PACKET_FLAG_FROM_INCLUDED |
|
||||
PACKET_FLAG_SIGNATURE_INCLUDED | PACKET_FLAG_MAX_PACKET_SIZE_INCLUDED;
|
||||
if (isNoAck) flags |= PACKET_FLAG_NO_ACK;
|
||||
*(uint16_t *)(packet + size) = htobe16 (flags);
|
||||
htobe16buf (packet + size, flags);
|
||||
size += 2; // flags
|
||||
size_t identityLen = m_LocalDestination.GetOwner ().GetIdentity ().GetFullLen ();
|
||||
size_t signatureLen = m_LocalDestination.GetOwner ().GetIdentity ().GetSignatureLen ();
|
||||
*(uint16_t *)(packet + size) = htobe16 (identityLen + signatureLen + 2); // identity + signature + packet size
|
||||
htobe16buf (packet + size, identityLen + signatureLen + 2); // identity + signature + packet size
|
||||
size += 2; // options size
|
||||
m_LocalDestination.GetOwner ().GetIdentity ().ToBuffer (packet + size, identityLen);
|
||||
size += identityLen; // from
|
||||
*(uint16_t *)(packet + size) = htobe16 (STREAMING_MTU);
|
||||
htobe16buf (packet + size, STREAMING_MTU);
|
||||
size += 2; // max packet size
|
||||
uint8_t * signature = packet + size; // set it later
|
||||
memset (signature, 0, signatureLen); // zeroes for now
|
||||
@@ -297,9 +302,9 @@ namespace stream
|
||||
else
|
||||
{
|
||||
// follow on packet
|
||||
*(uint16_t *)(packet + size) = 0;
|
||||
htobuf16 (packet + size, 0);
|
||||
size += 2; // flags
|
||||
*(uint16_t *)(packet + size) = 0; // no options
|
||||
htobuf16 (packet + size, 0); // no options
|
||||
size += 2; // options size
|
||||
size_t sentLen = STREAMING_MTU - size;
|
||||
if (len < sentLen) sentLen = len;
|
||||
@@ -309,37 +314,75 @@ namespace stream
|
||||
size += sentLen; // payload
|
||||
}
|
||||
p->len = size;
|
||||
m_Service.post (boost::bind (&Stream::SendPacket, this, p));
|
||||
packets.push_back (p);
|
||||
}
|
||||
|
||||
if (packets.size () > 0)
|
||||
m_Service.post (std::bind (&Stream::PostPackets, shared_from_this (), packets));
|
||||
return len;
|
||||
}
|
||||
|
||||
|
||||
void Stream::SendQuickAck ()
|
||||
{
|
||||
int32_t lastReceivedSeqn = m_LastReceivedSequenceNumber;
|
||||
if (!m_SavedPackets.empty ())
|
||||
{
|
||||
int32_t seqn = (*m_SavedPackets.rbegin ())->GetSeqn ();
|
||||
if (seqn > lastReceivedSeqn) lastReceivedSeqn = seqn;
|
||||
}
|
||||
if (lastReceivedSeqn < 0)
|
||||
{
|
||||
LogPrint (eLogError, "No packets have been received yet");
|
||||
return;
|
||||
}
|
||||
|
||||
Packet p;
|
||||
uint8_t * packet = p.GetBuffer ();
|
||||
size_t size = 0;
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_SendStreamID);
|
||||
htobe32buf (packet + size, m_SendStreamID);
|
||||
size += 4; // sendStreamID
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_RecvStreamID);
|
||||
htobe32buf (packet + size, m_RecvStreamID);
|
||||
size += 4; // receiveStreamID
|
||||
*(uint32_t *)(packet + size) = 0; // this is plain Ack message
|
||||
htobuf32 (packet + size, 0); // this is plain Ack message
|
||||
size += 4; // sequenceNum
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_LastReceivedSequenceNumber);
|
||||
htobe32buf (packet + size, lastReceivedSeqn);
|
||||
size += 4; // ack Through
|
||||
packet[size] = 0;
|
||||
size++; // NACK count
|
||||
uint8_t numNacks = 0;
|
||||
if (lastReceivedSeqn > m_LastReceivedSequenceNumber)
|
||||
{
|
||||
// fill NACKs
|
||||
uint8_t * nacks = packet + size + 1;
|
||||
auto nextSeqn = m_LastReceivedSequenceNumber + 1;
|
||||
for (auto it: m_SavedPackets)
|
||||
{
|
||||
auto seqn = it->GetSeqn ();
|
||||
for (uint32_t i = nextSeqn; i < seqn; i++)
|
||||
{
|
||||
htobe32buf (nacks, i);
|
||||
nacks += 4;
|
||||
numNacks++;
|
||||
}
|
||||
nextSeqn = seqn + 1;
|
||||
}
|
||||
packet[size] = numNacks;
|
||||
size++; // NACK count
|
||||
size += numNacks*4; // NACKs
|
||||
}
|
||||
else
|
||||
{
|
||||
// No NACKs
|
||||
packet[size] = 0;
|
||||
size++; // NACK count
|
||||
}
|
||||
size++; // resend delay
|
||||
*(uint16_t *)(packet + size) = 0; // nof flags set
|
||||
htobuf16 (packet + size, 0); // nof flags set
|
||||
size += 2; // flags
|
||||
*(uint16_t *)(packet + size) = 0; // no options
|
||||
htobuf16 (packet + size, 0); // no options
|
||||
size += 2; // options size
|
||||
p.len = size;
|
||||
|
||||
SendPackets (std::vector<Packet *> { &p });
|
||||
LogPrint ("Quick Ack sent");
|
||||
LogPrint ("Quick Ack sent. ", (int)numNacks, " NACKs");
|
||||
}
|
||||
|
||||
void Stream::Close ()
|
||||
@@ -350,21 +393,21 @@ namespace stream
|
||||
Packet * p = new Packet ();
|
||||
uint8_t * packet = p->GetBuffer ();
|
||||
size_t size = 0;
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_SendStreamID);
|
||||
htobe32buf (packet + size, m_SendStreamID);
|
||||
size += 4; // sendStreamID
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_RecvStreamID);
|
||||
htobe32buf (packet + size, m_RecvStreamID);
|
||||
size += 4; // receiveStreamID
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_SequenceNumber++);
|
||||
htobe32buf (packet + size, m_SequenceNumber++);
|
||||
size += 4; // sequenceNum
|
||||
*(uint32_t *)(packet + size) = htobe32 (m_LastReceivedSequenceNumber);
|
||||
htobe32buf (packet + size, m_LastReceivedSequenceNumber);
|
||||
size += 4; // ack Through
|
||||
packet[size] = 0;
|
||||
size++; // NACK count
|
||||
size++; // resend delay
|
||||
*(uint16_t *)(packet + size) = htobe16 (PACKET_FLAG_CLOSE | PACKET_FLAG_SIGNATURE_INCLUDED);
|
||||
htobe16buf (packet + size, PACKET_FLAG_CLOSE | PACKET_FLAG_SIGNATURE_INCLUDED);
|
||||
size += 2; // flags
|
||||
size_t signatureLen = m_LocalDestination.GetOwner ().GetIdentity ().GetSignatureLen ();
|
||||
*(uint16_t *)(packet + size) = htobe16 (signatureLen); // signature only
|
||||
htobe16buf (packet + size, signatureLen); // signature only
|
||||
size += 2; // options size
|
||||
uint8_t * signature = packet + size;
|
||||
memset (packet + size, 0, signatureLen);
|
||||
@@ -372,8 +415,10 @@ namespace stream
|
||||
m_LocalDestination.GetOwner ().Sign (packet, size, signature);
|
||||
|
||||
p->len = size;
|
||||
SendPacket (p);
|
||||
m_Service.post (std::bind (&Stream::SendPacket, shared_from_this (), p));
|
||||
LogPrint ("FIN sent");
|
||||
m_ReceiveTimer.cancel ();
|
||||
m_LocalDestination.DeleteStream (shared_from_this ());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,7 +465,31 @@ namespace stream
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
void Stream::PostPackets (const std::vector<Packet *> packets)
|
||||
{
|
||||
if (m_IsOpen)
|
||||
{
|
||||
if (packets.size () > 0)
|
||||
{
|
||||
m_IsAckSendScheduled = false;
|
||||
m_AckSendTimer.cancel ();
|
||||
}
|
||||
bool isEmpty = m_SentPackets.empty ();
|
||||
for (auto it: packets)
|
||||
m_SentPackets.insert (it);
|
||||
SendPackets (packets);
|
||||
if (isEmpty)
|
||||
ScheduleResend ();
|
||||
}
|
||||
else
|
||||
{
|
||||
// delete
|
||||
for (auto it: packets)
|
||||
delete it;
|
||||
}
|
||||
}
|
||||
|
||||
void Stream::SendPackets (const std::vector<Packet *>& packets)
|
||||
{
|
||||
if (!m_RemoteLeaseSet)
|
||||
@@ -432,6 +501,12 @@ namespace stream
|
||||
return;
|
||||
}
|
||||
}
|
||||
m_CurrentOutboundTunnel = m_LocalDestination.GetOwner ().GetTunnelPool ()->GetNextOutboundTunnel (m_CurrentOutboundTunnel);
|
||||
if (!m_CurrentOutboundTunnel)
|
||||
{
|
||||
LogPrint ("No outbound tunnels in the pool");
|
||||
return;
|
||||
}
|
||||
|
||||
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
if (ts >= m_CurrentRemoteLease.endDate)
|
||||
@@ -450,7 +525,7 @@ namespace stream
|
||||
});
|
||||
m_NumSentBytes += it->GetLength ();
|
||||
}
|
||||
m_LocalDestination.GetOwner ().SendTunnelDataMsgs (msgs);
|
||||
m_CurrentOutboundTunnel->SendTunnelDataMsg (msgs);
|
||||
}
|
||||
else
|
||||
LogPrint ("All leases are expired");
|
||||
@@ -460,8 +535,8 @@ namespace stream
|
||||
{
|
||||
m_ResendTimer.cancel ();
|
||||
m_ResendTimer.expires_from_now (boost::posix_time::seconds(RESEND_TIMEOUT));
|
||||
m_ResendTimer.async_wait (boost::bind (&Stream::HandleResendTimer,
|
||||
this, boost::asio::placeholders::error));
|
||||
m_ResendTimer.async_wait (std::bind (&Stream::HandleResendTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
|
||||
void Stream::HandleResendTimer (const boost::system::error_code& ecode)
|
||||
@@ -476,7 +551,8 @@ namespace stream
|
||||
packets.push_back (it);
|
||||
else
|
||||
{
|
||||
Close ();
|
||||
LogPrint (eLogWarning, "Packet ", it->GetSeqn (), "was not ACKed after ", MAX_NUM_RESEND_ATTEMPTS, " attempts. Terminate");
|
||||
m_IsOpen = false;
|
||||
m_IsReset = true;
|
||||
m_ReceiveTimer.cancel ();
|
||||
return;
|
||||
@@ -484,7 +560,7 @@ namespace stream
|
||||
}
|
||||
if (packets.size () > 0)
|
||||
{
|
||||
m_LocalDestination.GetOwner ().ResetCurrentOutboundTunnel (); // pick another outbound tunnel
|
||||
m_CurrentOutboundTunnel = nullptr; // pick another outbound tunnel
|
||||
UpdateCurrentRemoteLease (); // pick another lease
|
||||
SendPackets (packets);
|
||||
}
|
||||
@@ -542,11 +618,11 @@ namespace stream
|
||||
compressor.MessageEnd();
|
||||
int size = compressor.MaxRetrievable ();
|
||||
uint8_t * buf = msg->GetPayload ();
|
||||
*(uint32_t *)buf = htobe32 (size); // length
|
||||
htobe32buf (buf, size); // length
|
||||
buf += 4;
|
||||
compressor.Get (buf, size);
|
||||
*(uint16_t *)(buf + 4) = 0; // source port
|
||||
*(uint16_t *)(buf + 6) = htobe16 (m_Port); // destination port
|
||||
htobuf16(buf + 4, 0); // source port
|
||||
htobe16buf (buf + 6, m_Port); // destination port
|
||||
buf[9] = i2p::client::PROTOCOL_TYPE_STREAMING; // streaming protocol
|
||||
msg->len += size + 4;
|
||||
FillI2NPMessageHeader (msg, eI2NPData);
|
||||
@@ -563,12 +639,10 @@ namespace stream
|
||||
ResetAcceptor ();
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_StreamsMutex);
|
||||
for (auto it: m_Streams)
|
||||
delete it.second;
|
||||
m_Streams.clear ();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void StreamingDestination::HandleNextPacket (Packet * packet)
|
||||
{
|
||||
uint32_t sendStreamID = packet->GetSendStreamID ();
|
||||
@@ -579,54 +653,65 @@ namespace stream
|
||||
it->second->HandleNextPacket (packet);
|
||||
else
|
||||
{
|
||||
LogPrint ("Unknown stream ", sendStreamID);
|
||||
LogPrint ("Unknown stream sendStreamID=", sendStreamID);
|
||||
delete packet;
|
||||
}
|
||||
}
|
||||
else // new incoming stream
|
||||
else
|
||||
{
|
||||
auto incomingStream = CreateNewIncomingStream ();
|
||||
incomingStream->HandleNextPacket (packet);
|
||||
if (m_Acceptor != nullptr)
|
||||
m_Acceptor (incomingStream);
|
||||
else
|
||||
if (packet->IsSYN () && !packet->GetSeqn ()) // new incoming stream
|
||||
{
|
||||
auto incomingStream = CreateNewIncomingStream ();
|
||||
incomingStream->HandleNextPacket (packet);
|
||||
if (m_Acceptor != nullptr)
|
||||
m_Acceptor (incomingStream);
|
||||
else
|
||||
{
|
||||
LogPrint ("Acceptor for incoming stream is not set");
|
||||
DeleteStream (incomingStream);
|
||||
}
|
||||
}
|
||||
else // follow on packet without SYN
|
||||
{
|
||||
LogPrint ("Acceptor for incoming stream is not set");
|
||||
DeleteStream (incomingStream);
|
||||
}
|
||||
uint32_t receiveStreamID = packet->GetReceiveStreamID ();
|
||||
for (auto it: m_Streams)
|
||||
if (it.second->GetSendStreamID () == receiveStreamID)
|
||||
{
|
||||
// found
|
||||
it.second->HandleNextPacket (packet);
|
||||
return;
|
||||
}
|
||||
// TODO: should queue it up
|
||||
LogPrint ("Unknown stream receiveStreamID=", receiveStreamID);
|
||||
delete packet;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Stream * StreamingDestination::CreateNewOutgoingStream (const i2p::data::LeaseSet& remote, int port)
|
||||
std::shared_ptr<Stream> StreamingDestination::CreateNewOutgoingStream (const i2p::data::LeaseSet& remote, int port)
|
||||
{
|
||||
Stream * s = new Stream (*m_Owner.GetService (), *this, remote, port);
|
||||
auto s = std::make_shared<Stream> (m_Owner.GetService (), *this, remote, port);
|
||||
std::unique_lock<std::mutex> l(m_StreamsMutex);
|
||||
m_Streams[s->GetRecvStreamID ()] = s;
|
||||
return s;
|
||||
}
|
||||
|
||||
Stream * StreamingDestination::CreateNewIncomingStream ()
|
||||
std::shared_ptr<Stream> StreamingDestination::CreateNewIncomingStream ()
|
||||
{
|
||||
Stream * s = new Stream (*m_Owner.GetService (), *this);
|
||||
auto s = std::make_shared<Stream> (m_Owner.GetService (), *this);
|
||||
std::unique_lock<std::mutex> l(m_StreamsMutex);
|
||||
m_Streams[s->GetRecvStreamID ()] = s;
|
||||
return s;
|
||||
}
|
||||
|
||||
void StreamingDestination::DeleteStream (Stream * stream)
|
||||
void StreamingDestination::DeleteStream (std::shared_ptr<Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_StreamsMutex);
|
||||
auto it = m_Streams.find (stream->GetRecvStreamID ());
|
||||
if (it != m_Streams.end ())
|
||||
{
|
||||
m_Streams.erase (it);
|
||||
if (m_Owner.GetService ())
|
||||
m_Owner.GetService ()->post ([stream](void) { delete stream; });
|
||||
else
|
||||
delete stream;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -650,11 +735,5 @@ namespace stream
|
||||
delete uncompressed;
|
||||
}
|
||||
}
|
||||
|
||||
void DeleteStream (Stream * stream)
|
||||
{
|
||||
if (stream)
|
||||
stream->GetLocalDestination ().DeleteStream (stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
46
Streaming.h
46
Streaming.h
@@ -7,8 +7,8 @@
|
||||
#include <set>
|
||||
#include <queue>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include "I2PEndian.h"
|
||||
#include "Identity.h"
|
||||
#include "LeaseSet.h"
|
||||
@@ -45,23 +45,23 @@ namespace stream
|
||||
|
||||
struct Packet
|
||||
{
|
||||
uint8_t buf[MAX_PACKET_SIZE];
|
||||
size_t len, offset;
|
||||
uint8_t buf[MAX_PACKET_SIZE];
|
||||
int numResendAttempts;
|
||||
|
||||
Packet (): len (0), offset (0), numResendAttempts (0) {};
|
||||
uint8_t * GetBuffer () { return buf + offset; };
|
||||
size_t GetLength () const { return len - offset; };
|
||||
|
||||
uint32_t GetSendStreamID () const { return be32toh (*(uint32_t *)buf); };
|
||||
uint32_t GetReceiveStreamID () const { return be32toh (*(uint32_t *)(buf + 4)); };
|
||||
uint32_t GetSeqn () const { return be32toh (*(uint32_t *)(buf + 8)); };
|
||||
uint32_t GetAckThrough () const { return be32toh (*(uint32_t *)(buf + 12)); };
|
||||
uint32_t GetSendStreamID () const { return bufbe32toh (buf); };
|
||||
uint32_t GetReceiveStreamID () const { return bufbe32toh (buf + 4); };
|
||||
uint32_t GetSeqn () const { return bufbe32toh (buf + 8); };
|
||||
uint32_t GetAckThrough () const { return bufbe32toh (buf + 12); };
|
||||
uint8_t GetNACKCount () const { return buf[16]; };
|
||||
uint32_t GetNACK (int i) const { return be32toh (((uint32_t *)(buf + 17))[i]); };
|
||||
uint32_t GetNACK (int i) const { return bufbe32toh (buf + 17 + 4 * i); };
|
||||
const uint8_t * GetOption () const { return buf + 17 + GetNACKCount ()*4 + 3; }; // 3 = resendDelay + flags
|
||||
uint16_t GetFlags () const { return be16toh (*(uint16_t *)(GetOption () - 2)); };
|
||||
uint16_t GetOptionSize () const { return be16toh (*(uint16_t *)GetOption ()); };
|
||||
uint16_t GetFlags () const { return bufbe16toh (GetOption () - 2); };
|
||||
uint16_t GetOptionSize () const { return bufbe16toh (GetOption ()); };
|
||||
const uint8_t * GetOptionData () const { return GetOption () + 2; };
|
||||
const uint8_t * GetPayload () const { return GetOptionData () + GetOptionSize (); };
|
||||
|
||||
@@ -78,7 +78,7 @@ namespace stream
|
||||
};
|
||||
|
||||
class StreamingDestination;
|
||||
class Stream
|
||||
class Stream: public std::enable_shared_from_this<Stream>
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -100,8 +100,10 @@ namespace stream
|
||||
|
||||
template<typename Buffer, typename ReceiveHandler>
|
||||
void AsyncReceive (const Buffer& buffer, ReceiveHandler handler, int timeout = 0);
|
||||
|
||||
size_t ReadSome (uint8_t * buf, size_t len) { return ConcatenatePackets (buf, len); };
|
||||
|
||||
void Close ();
|
||||
void Cancel () { m_ReceiveTimer.cancel (); };
|
||||
|
||||
size_t GetNumSentBytes () const { return m_NumSentBytes; };
|
||||
size_t GetNumReceivedBytes () const { return m_NumReceivedBytes; };
|
||||
@@ -112,6 +114,7 @@ namespace stream
|
||||
|
||||
void SendQuickAck ();
|
||||
bool SendPacket (Packet * packet);
|
||||
void PostPackets (const std::vector<Packet *> packets);
|
||||
void SendPackets (const std::vector<Packet *>& packets);
|
||||
|
||||
void SavePacket (Packet * packet);
|
||||
@@ -141,6 +144,7 @@ namespace stream
|
||||
const i2p::data::LeaseSet * m_RemoteLeaseSet;
|
||||
i2p::garlic::GarlicRoutingSession * m_RoutingSession;
|
||||
i2p::data::Lease m_CurrentRemoteLease;
|
||||
i2p::tunnel::OutboundTunnel * m_CurrentOutboundTunnel;
|
||||
std::queue<Packet *> m_ReceiveQueue;
|
||||
std::set<Packet *, PacketCmp> m_SavedPackets;
|
||||
std::set<Packet *, PacketCmp> m_SentPackets;
|
||||
@@ -153,7 +157,7 @@ namespace stream
|
||||
{
|
||||
public:
|
||||
|
||||
typedef std::function<void (Stream *)> Acceptor;
|
||||
typedef std::function<void (std::shared_ptr<Stream>)> Acceptor;
|
||||
|
||||
StreamingDestination (i2p::client::ClientDestination& owner): m_Owner (owner) {};
|
||||
~StreamingDestination () {};
|
||||
@@ -161,8 +165,8 @@ namespace stream
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
Stream * CreateNewOutgoingStream (const i2p::data::LeaseSet& remote, int port = 0);
|
||||
void DeleteStream (Stream * stream);
|
||||
std::shared_ptr<Stream> CreateNewOutgoingStream (const i2p::data::LeaseSet& remote, int port = 0);
|
||||
void DeleteStream (std::shared_ptr<Stream> stream);
|
||||
void SetAcceptor (const Acceptor& acceptor) { m_Acceptor = acceptor; };
|
||||
void ResetAcceptor () { m_Acceptor = nullptr; };
|
||||
bool IsAcceptorSet () const { return m_Acceptor != nullptr; };
|
||||
@@ -173,13 +177,13 @@ namespace stream
|
||||
private:
|
||||
|
||||
void HandleNextPacket (Packet * packet);
|
||||
Stream * CreateNewIncomingStream ();
|
||||
std::shared_ptr<Stream> CreateNewIncomingStream ();
|
||||
|
||||
private:
|
||||
|
||||
i2p::client::ClientDestination& m_Owner;
|
||||
std::mutex m_StreamsMutex;
|
||||
std::map<uint32_t, Stream *> m_Streams;
|
||||
std::map<uint32_t, std::shared_ptr<Stream> > m_Streams;
|
||||
Acceptor m_Acceptor;
|
||||
|
||||
public:
|
||||
@@ -188,8 +192,6 @@ namespace stream
|
||||
const decltype(m_Streams)& GetStreams () const { return m_Streams; };
|
||||
};
|
||||
|
||||
void DeleteStream (Stream * stream);
|
||||
|
||||
//-------------------------------------------------
|
||||
|
||||
template<typename Buffer, typename ReceiveHandler>
|
||||
@@ -197,15 +199,17 @@ namespace stream
|
||||
{
|
||||
if (!m_ReceiveQueue.empty ())
|
||||
{
|
||||
m_Service.post ([=](void) { this->HandleReceiveTimer (
|
||||
auto s = shared_from_this();
|
||||
m_Service.post ([=](void) { s->HandleReceiveTimer (
|
||||
boost::asio::error::make_error_code (boost::asio::error::operation_aborted),
|
||||
buffer, handler); });
|
||||
}
|
||||
else
|
||||
{
|
||||
m_ReceiveTimer.expires_from_now (boost::posix_time::seconds(timeout));
|
||||
auto s = shared_from_this();
|
||||
m_ReceiveTimer.async_wait ([=](const boost::system::error_code& ecode)
|
||||
{ this->HandleReceiveTimer (ecode, buffer, handler); });
|
||||
{ s->HandleReceiveTimer (ecode, buffer, handler); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,7 +226,7 @@ namespace stream
|
||||
else
|
||||
// socket closed
|
||||
handler (m_IsReset ? boost::asio::error::make_error_code (boost::asio::error::connection_reset) :
|
||||
boost::asio::error::make_error_code (boost::asio::error::operation_aborted), 0);
|
||||
boost::asio::error::make_error_code (boost::asio::error::operation_aborted), received);
|
||||
}
|
||||
else
|
||||
// timeout expired
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace tunnel
|
||||
|
||||
LogPrint ("TransitTunnel: ",m_TunnelID,"->", m_NextTunnelID);
|
||||
m_NumTransmittedBytes += tunnelMsg->GetLength ();
|
||||
*(uint32_t *)(tunnelMsg->GetPayload ()) = htobe32 (m_NextTunnelID);
|
||||
htobe32buf (tunnelMsg->GetPayload (), m_NextTunnelID);
|
||||
FillI2NPMessageHeader (tunnelMsg, eI2NPTunnelData);
|
||||
|
||||
i2p::transport::transports.SendMessage (m_NextIdent, tunnelMsg);
|
||||
|
||||
@@ -121,7 +121,7 @@ namespace transport
|
||||
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), address.port));
|
||||
|
||||
LogPrint ("Start listening TCP port ", address.port);
|
||||
auto conn = new NTCPServerConnection (m_Service);
|
||||
auto conn = std::make_shared<NTCPSession>(m_Service);
|
||||
m_NTCPAcceptor->async_accept(conn->GetSocket (), boost::bind (&Transports::HandleAccept, this,
|
||||
conn, boost::asio::placeholders::error));
|
||||
|
||||
@@ -134,7 +134,7 @@ namespace transport
|
||||
m_NTCPV6Acceptor->listen ();
|
||||
|
||||
LogPrint ("Start listening V6 TCP port ", address.port);
|
||||
auto conn = new NTCPServerConnection (m_Service);
|
||||
auto conn = std::make_shared<NTCPSession> (m_Service);
|
||||
m_NTCPV6Acceptor->async_accept(conn->GetSocket (), boost::bind (&Transports::HandleAcceptV6,
|
||||
this, conn, boost::asio::placeholders::error));
|
||||
}
|
||||
@@ -162,10 +162,8 @@ namespace transport
|
||||
delete m_SSUServer;
|
||||
m_SSUServer = nullptr;
|
||||
}
|
||||
|
||||
for (auto session: m_NTCPSessions)
|
||||
delete session.second;
|
||||
m_NTCPSessions.clear ();
|
||||
|
||||
delete m_NTCPAcceptor;
|
||||
m_NTCPAcceptor = nullptr;
|
||||
delete m_NTCPV6Acceptor;
|
||||
@@ -197,55 +195,79 @@ namespace transport
|
||||
}
|
||||
}
|
||||
|
||||
void Transports::AddNTCPSession (NTCPSession * session)
|
||||
void Transports::AddNTCPSession (std::shared_ptr<NTCPSession> session)
|
||||
{
|
||||
if (session)
|
||||
m_NTCPSessions[session->GetRemoteIdentity ().GetIdentHash ()] = session;
|
||||
}
|
||||
|
||||
void Transports::RemoveNTCPSession (NTCPSession * session)
|
||||
void Transports::RemoveNTCPSession (std::shared_ptr<NTCPSession> session)
|
||||
{
|
||||
if (session)
|
||||
m_NTCPSessions.erase (session->GetRemoteIdentity ().GetIdentHash ());
|
||||
}
|
||||
|
||||
void Transports::HandleAccept (NTCPServerConnection * conn, const boost::system::error_code& error)
|
||||
void Transports::HandleAccept (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
LogPrint ("Connected from ", conn->GetSocket ().remote_endpoint().address ().to_string ());
|
||||
conn->ServerLogin ();
|
||||
}
|
||||
else
|
||||
delete conn;
|
||||
|
||||
|
||||
if (error != boost::asio::error::operation_aborted)
|
||||
{
|
||||
conn = new NTCPServerConnection (m_Service);
|
||||
conn = std::make_shared<NTCPSession> (m_Service);
|
||||
m_NTCPAcceptor->async_accept(conn->GetSocket (), boost::bind (&Transports::HandleAccept, this,
|
||||
conn, boost::asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void Transports::HandleAcceptV6 (NTCPServerConnection * conn, const boost::system::error_code& error)
|
||||
void Transports::HandleAcceptV6 (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
LogPrint ("Connected from ", conn->GetSocket ().remote_endpoint().address ().to_string ());
|
||||
conn->ServerLogin ();
|
||||
}
|
||||
else
|
||||
delete conn;
|
||||
|
||||
if (error != boost::asio::error::operation_aborted)
|
||||
{
|
||||
conn = new NTCPServerConnection (m_Service);
|
||||
conn = std::make_shared<NTCPSession> (m_Service);
|
||||
m_NTCPV6Acceptor->async_accept(conn->GetSocket (), boost::bind (&Transports::HandleAcceptV6, this,
|
||||
conn, boost::asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
NTCPSession * Transports::GetNextNTCPSession ()
|
||||
void Transports::Connect (const boost::asio::ip::address& address, int port, std::shared_ptr<NTCPSession> conn)
|
||||
{
|
||||
LogPrint ("Connecting to ", address ,":", port);
|
||||
conn->GetSocket ().async_connect (boost::asio::ip::tcp::endpoint (address, port),
|
||||
boost::bind (&Transports::HandleConnect, this, boost::asio::placeholders::error, conn));
|
||||
}
|
||||
|
||||
void Transports::HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCPSession> conn)
|
||||
{
|
||||
if (ecode)
|
||||
{
|
||||
LogPrint ("Connect error: ", ecode.message ());
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
i2p::data::netdb.SetUnreachable (conn->GetRemoteIdentity ().GetIdentHash (), true);
|
||||
conn->Terminate ();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("Connected");
|
||||
if (conn->GetSocket ().local_endpoint ().protocol () == boost::asio::ip::tcp::v6()) // ipv6
|
||||
context.UpdateNTCPV6Address (conn->GetSocket ().local_endpoint ().address ());
|
||||
conn->ClientLogin ();
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<NTCPSession> Transports::GetNextNTCPSession ()
|
||||
{
|
||||
for (auto session: m_NTCPSessions)
|
||||
if (session.second->IsEstablished ())
|
||||
@@ -253,7 +275,7 @@ namespace transport
|
||||
return 0;
|
||||
}
|
||||
|
||||
NTCPSession * Transports::FindNTCPSession (const i2p::data::IdentHash& ident)
|
||||
std::shared_ptr<NTCPSession> Transports::FindNTCPSession (const i2p::data::IdentHash& ident)
|
||||
{
|
||||
auto it = m_NTCPSessions.find (ident);
|
||||
if (it != m_NTCPSessions.end ())
|
||||
@@ -280,7 +302,7 @@ namespace transport
|
||||
auto r = netdb.FindRouter (ident);
|
||||
if (r)
|
||||
{
|
||||
auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (r.get ()) : nullptr;
|
||||
auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (r) : nullptr;
|
||||
if (ssuSession)
|
||||
ssuSession->SendI2NPMessage (msg);
|
||||
else
|
||||
@@ -290,9 +312,10 @@ namespace transport
|
||||
auto address = r->GetNTCPAddress (!context.SupportsV6 ());
|
||||
if (address && !r->UsesIntroducer () && !r->IsUnreachable () && msg->GetLength () < NTCP_MAX_MESSAGE_SIZE)
|
||||
{
|
||||
auto s = new NTCPClient (m_Service, address->host, address->port, r);
|
||||
auto s = std::make_shared<NTCPSession> (m_Service, r);
|
||||
AddNTCPSession (s);
|
||||
s->SendI2NPMessage (msg);
|
||||
Connect (address->host, address->port, s);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -337,13 +360,13 @@ namespace transport
|
||||
delete timer;
|
||||
}
|
||||
|
||||
void Transports::CloseSession (const i2p::data::RouterInfo * router)
|
||||
void Transports::CloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
|
||||
{
|
||||
if (!router) return;
|
||||
m_Service.post (boost::bind (&Transports::PostCloseSession, this, router));
|
||||
}
|
||||
|
||||
void Transports::PostCloseSession (const i2p::data::RouterInfo * router)
|
||||
void Transports::PostCloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
|
||||
{
|
||||
auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (router) : nullptr;
|
||||
if (ssuSession) // try SSU first
|
||||
|
||||
22
Transports.h
22
Transports.h
@@ -8,6 +8,7 @@
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <cryptopp/osrng.h>
|
||||
#include <boost/asio.hpp>
|
||||
#include "TransportSession.h"
|
||||
@@ -63,25 +64,28 @@ namespace transport
|
||||
i2p::transport::DHKeysPair * GetNextDHKeysPair ();
|
||||
void ReuseDHKeysPair (DHKeysPair * pair);
|
||||
|
||||
void AddNTCPSession (NTCPSession * session);
|
||||
void RemoveNTCPSession (NTCPSession * session);
|
||||
void AddNTCPSession (std::shared_ptr<NTCPSession> session);
|
||||
void RemoveNTCPSession (std::shared_ptr<NTCPSession> session);
|
||||
|
||||
NTCPSession * GetNextNTCPSession ();
|
||||
NTCPSession * FindNTCPSession (const i2p::data::IdentHash& ident);
|
||||
std::shared_ptr<NTCPSession> GetNextNTCPSession ();
|
||||
std::shared_ptr<NTCPSession> FindNTCPSession (const i2p::data::IdentHash& ident);
|
||||
|
||||
void SendMessage (const i2p::data::IdentHash& ident, i2p::I2NPMessage * msg);
|
||||
void CloseSession (const i2p::data::RouterInfo * router);
|
||||
void CloseSession (std::shared_ptr<const i2p::data::RouterInfo> router);
|
||||
|
||||
private:
|
||||
|
||||
void Run ();
|
||||
void HandleAccept (NTCPServerConnection * conn, const boost::system::error_code& error);
|
||||
void HandleAcceptV6 (NTCPServerConnection * conn, const boost::system::error_code& error);
|
||||
void HandleAccept (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error);
|
||||
void HandleAcceptV6 (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error);
|
||||
void HandleResendTimer (const boost::system::error_code& ecode, boost::asio::deadline_timer * timer,
|
||||
const i2p::data::IdentHash& ident, i2p::I2NPMessage * msg);
|
||||
void PostMessage (const i2p::data::IdentHash& ident, i2p::I2NPMessage * msg);
|
||||
void PostCloseSession (const i2p::data::RouterInfo * router);
|
||||
void PostCloseSession (std::shared_ptr<const i2p::data::RouterInfo> router);
|
||||
|
||||
void Connect (const boost::asio::ip::address& address, int port, std::shared_ptr<NTCPSession> conn);
|
||||
void HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCPSession> conn);
|
||||
|
||||
void DetectExternalIP ();
|
||||
|
||||
private:
|
||||
@@ -92,7 +96,7 @@ namespace transport
|
||||
boost::asio::io_service::work m_Work;
|
||||
boost::asio::ip::tcp::acceptor * m_NTCPAcceptor, * m_NTCPV6Acceptor;
|
||||
|
||||
std::map<i2p::data::IdentHash, NTCPSession *> m_NTCPSessions;
|
||||
std::map<i2p::data::IdentHash, std::shared_ptr<NTCPSession> > m_NTCPSessions;
|
||||
SSUServer * m_SSUServer;
|
||||
|
||||
DHKeysPairSupplier m_DHKeysPairSupplier;
|
||||
|
||||
54
Tunnel.cpp
54
Tunnel.cpp
@@ -1,3 +1,4 @@
|
||||
#include <string.h>
|
||||
#include "I2PEndian.h"
|
||||
#include <thread>
|
||||
#include <algorithm>
|
||||
@@ -33,7 +34,7 @@ namespace tunnel
|
||||
int numRecords = numHops <= STANDARD_NUM_RECORDS ? STANDARD_NUM_RECORDS : numHops;
|
||||
I2NPMessage * msg = NewI2NPMessage ();
|
||||
*msg->GetPayload () = numRecords;
|
||||
msg->len += numRecords*sizeof (I2NPBuildRequestRecordElGamalEncrypted) + 1;
|
||||
msg->len += numRecords*TUNNEL_BUILD_RECORD_SIZE + 1;
|
||||
|
||||
// shuffle records
|
||||
std::vector<int> recordIndicies;
|
||||
@@ -41,22 +42,14 @@ namespace tunnel
|
||||
std::random_shuffle (recordIndicies.begin(), recordIndicies.end());
|
||||
|
||||
// create real records
|
||||
I2NPBuildRequestRecordElGamalEncrypted * records = (I2NPBuildRequestRecordElGamalEncrypted *)(msg->GetPayload () + 1);
|
||||
uint8_t * records = msg->GetPayload () + 1;
|
||||
TunnelHopConfig * hop = m_Config->GetFirstHop ();
|
||||
int i = 0;
|
||||
while (hop)
|
||||
{
|
||||
int idx = recordIndicies[i];
|
||||
EncryptBuildRequestRecord (*hop->router,
|
||||
CreateBuildRequestRecord (hop->router->GetIdentHash (),
|
||||
hop->tunnelID,
|
||||
hop->nextRouter->GetIdentHash (),
|
||||
hop->nextTunnelID,
|
||||
hop->layerKey, hop->ivKey,
|
||||
hop->replyKey, hop->replyIV,
|
||||
hop->next ? rnd.GenerateWord32 () : replyMsgID, // we set replyMsgID for last hop only
|
||||
hop->isGateway, hop->isEndpoint),
|
||||
records[idx]);
|
||||
hop->CreateBuildRequestRecord (records + idx*TUNNEL_BUILD_RECORD_SIZE,
|
||||
hop->next ? rnd.GenerateWord32 () : replyMsgID); // we set replyMsgID for last hop only
|
||||
hop->recordIndex = idx;
|
||||
i++;
|
||||
hop = hop->next;
|
||||
@@ -65,7 +58,7 @@ namespace tunnel
|
||||
for (int i = numHops; i < numRecords; i++)
|
||||
{
|
||||
int idx = recordIndicies[i];
|
||||
rnd.GenerateBlock ((uint8_t *)(records + idx), sizeof (records[idx]));
|
||||
rnd.GenerateBlock (records + idx*TUNNEL_BUILD_RECORD_SIZE, TUNNEL_BUILD_RECORD_SIZE);
|
||||
}
|
||||
|
||||
// decrypt real records
|
||||
@@ -79,9 +72,8 @@ namespace tunnel
|
||||
while (hop1)
|
||||
{
|
||||
decryption.SetIV (hop->replyIV);
|
||||
decryption.Decrypt((uint8_t *)&records[hop1->recordIndex],
|
||||
sizeof (I2NPBuildRequestRecordElGamalEncrypted),
|
||||
(uint8_t *)&records[hop1->recordIndex]);
|
||||
uint8_t * record = records + hop1->recordIndex*TUNNEL_BUILD_RECORD_SIZE;
|
||||
decryption.Decrypt(record, TUNNEL_BUILD_RECORD_SIZE, record);
|
||||
hop1 = hop1->next;
|
||||
}
|
||||
hop = hop->prev;
|
||||
@@ -111,9 +103,9 @@ namespace tunnel
|
||||
auto idx = hop1->recordIndex;
|
||||
if (idx >= 0 && idx < msg[0])
|
||||
{
|
||||
uint8_t * record = msg + 1 + idx*sizeof (I2NPBuildResponseRecord);
|
||||
uint8_t * record = msg + 1 + idx*TUNNEL_BUILD_RECORD_SIZE;
|
||||
decryption.SetIV (hop->replyIV);
|
||||
decryption.Decrypt(record, sizeof (I2NPBuildResponseRecord), record);
|
||||
decryption.Decrypt(record, TUNNEL_BUILD_RECORD_SIZE, record);
|
||||
}
|
||||
else
|
||||
LogPrint ("Tunnel hop index ", idx, " is out of range");
|
||||
@@ -126,9 +118,10 @@ namespace tunnel
|
||||
hop = m_Config->GetFirstHop ();
|
||||
while (hop)
|
||||
{
|
||||
I2NPBuildResponseRecord * record = (I2NPBuildResponseRecord *)(msg + 1 + hop->recordIndex*sizeof (I2NPBuildResponseRecord));
|
||||
LogPrint ("Ret code=", (int)record->ret);
|
||||
if (record->ret)
|
||||
const uint8_t * record = msg + 1 + hop->recordIndex*TUNNEL_BUILD_RECORD_SIZE;
|
||||
uint8_t ret = record[BUILD_RESPONSE_RECORD_RET_OFFSET];
|
||||
LogPrint ("Ret code=", (int)ret);
|
||||
if (ret)
|
||||
// if any of participants declined the tunnel is not established
|
||||
established = false;
|
||||
hop = hop->next;
|
||||
@@ -221,7 +214,7 @@ namespace tunnel
|
||||
m_PendingTunnels.clear ();*/
|
||||
|
||||
for (auto& it: m_Pools)
|
||||
delete it.second;
|
||||
delete it;
|
||||
m_Pools.clear ();
|
||||
}
|
||||
|
||||
@@ -287,11 +280,11 @@ namespace tunnel
|
||||
return tunnel;
|
||||
}
|
||||
|
||||
TunnelPool * Tunnels::CreateTunnelPool (i2p::garlic::GarlicDestination& localDestination, int numHops)
|
||||
TunnelPool * Tunnels::CreateTunnelPool (i2p::garlic::GarlicDestination * localDestination, int numInboundHops, int numOutboundHops)
|
||||
{
|
||||
auto pool = new TunnelPool (localDestination, numHops);
|
||||
auto pool = new TunnelPool (localDestination, numInboundHops, numOutboundHops);
|
||||
std::unique_lock<std::mutex> l(m_PoolsMutex);
|
||||
m_Pools[pool->GetIdentHash ()] = pool;
|
||||
m_Pools.push_back (pool);
|
||||
return pool;
|
||||
}
|
||||
|
||||
@@ -300,7 +293,10 @@ namespace tunnel
|
||||
if (pool)
|
||||
{
|
||||
StopTunnelPool (pool);
|
||||
m_Pools.erase (pool->GetLocalDestination ().GetIdentHash ());
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_PoolsMutex);
|
||||
m_Pools.remove (pool);
|
||||
}
|
||||
for (auto it: m_PendingTunnels)
|
||||
if (it.second->GetTunnelPool () == pool)
|
||||
it.second->SetTunnelPool (nullptr);
|
||||
@@ -353,7 +349,7 @@ namespace tunnel
|
||||
I2NPMessage * msg = m_Queue.GetNextWithTimeout (1000); // 1 sec
|
||||
while (msg)
|
||||
{
|
||||
uint32_t tunnelID = be32toh (*(uint32_t *)msg->GetPayload ());
|
||||
uint32_t tunnelID = bufbe32toh (msg->GetPayload ());
|
||||
InboundTunnel * tunnel = GetInboundTunnel (tunnelID);
|
||||
if (tunnel)
|
||||
tunnel->HandleTunnelDataMsg (msg);
|
||||
@@ -510,7 +506,7 @@ namespace tunnel
|
||||
LogPrint ("Creating zero hops inbound tunnel...");
|
||||
CreateZeroHopsInboundTunnel ();
|
||||
if (!m_ExploratoryPool)
|
||||
m_ExploratoryPool = CreateTunnelPool (i2p::context, 2); // 2-hop exploratory
|
||||
m_ExploratoryPool = CreateTunnelPool (&i2p::context, 2, 2); // 2-hop exploratory
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -551,7 +547,7 @@ namespace tunnel
|
||||
std::unique_lock<std::mutex> l(m_PoolsMutex);
|
||||
for (auto it: m_Pools)
|
||||
{
|
||||
TunnelPool * pool = it.second;
|
||||
TunnelPool * pool = it;
|
||||
if (pool->IsActive ())
|
||||
{
|
||||
pool->CreateTunnels ();
|
||||
|
||||
4
Tunnel.h
4
Tunnel.h
@@ -129,7 +129,7 @@ namespace tunnel
|
||||
void PostTunnelData (I2NPMessage * msg);
|
||||
template<class TTunnel>
|
||||
TTunnel * CreateTunnel (TunnelConfig * config, OutboundTunnel * outboundTunnel = 0);
|
||||
TunnelPool * CreateTunnelPool (i2p::garlic::GarlicDestination& localDestination, int numHops);
|
||||
TunnelPool * CreateTunnelPool (i2p::garlic::GarlicDestination * localDestination, int numInboundHops, int numOuboundHops);
|
||||
void DeleteTunnelPool (TunnelPool * pool);
|
||||
void StopTunnelPool (TunnelPool * pool);
|
||||
|
||||
@@ -157,7 +157,7 @@ namespace tunnel
|
||||
std::mutex m_TransitTunnelsMutex;
|
||||
std::map<uint32_t, TransitTunnel *> m_TransitTunnels;
|
||||
std::mutex m_PoolsMutex;
|
||||
std::map<i2p::data::IdentHash, TunnelPool *> m_Pools;
|
||||
std::list<TunnelPool *> m_Pools;
|
||||
TunnelPool * m_ExploratoryPool;
|
||||
i2p::util::Queue<I2NPMessage> m_Queue;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "aes.h"
|
||||
#include "RouterInfo.h"
|
||||
#include "RouterContext.h"
|
||||
#include "Timestamp.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
@@ -82,6 +83,28 @@ namespace tunnel
|
||||
isGateway = false;
|
||||
}
|
||||
}
|
||||
|
||||
void CreateBuildRequestRecord (uint8_t * record, uint32_t replyMsgID)
|
||||
{
|
||||
uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
|
||||
htobe32buf (clearText + BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET, tunnelID);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_OUR_IDENT_OFFSET, router->GetIdentHash (), 32);
|
||||
htobe32buf (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET, nextTunnelID);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET, nextRouter->GetIdentHash (), 32);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET, layerKey, 32);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_IV_KEY_OFFSET, ivKey, 32);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET, replyKey, 32);
|
||||
memcpy (clearText + BUILD_REQUEST_RECORD_REPLY_IV_OFFSET, replyIV, 16);
|
||||
uint8_t flag = 0;
|
||||
if (isGateway) flag |= 0x80;
|
||||
if (isEndpoint) flag |= 0x40;
|
||||
clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] = flag;
|
||||
htobe32buf (clearText + BUILD_REQUEST_RECORD_REQUEST_TIME_OFFSET, i2p::util::GetHoursSinceEpoch ());
|
||||
htobe32buf (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET, replyMsgID);
|
||||
// TODO: fill padding
|
||||
router->GetElGamalEncryption ()->Encrypt (clearText, BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE, record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET);
|
||||
memcpy (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)router->GetIdentHash (), 16);
|
||||
}
|
||||
};
|
||||
|
||||
class TunnelConfig
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace tunnel
|
||||
break;
|
||||
case eDeliveryTypeTunnel: // 1
|
||||
LogPrint ("Delivery type tunnel");
|
||||
m.tunnelID = be32toh (*(uint32_t *)fragment);
|
||||
m.tunnelID = bufbe32toh (fragment);
|
||||
fragment += 4; // tunnelID
|
||||
m.hash = i2p::data::IdentHash (fragment);
|
||||
fragment += 32; // hash
|
||||
@@ -79,7 +79,7 @@ namespace tunnel
|
||||
if (isFragmented)
|
||||
{
|
||||
// Message ID
|
||||
msgID = be32toh (*(uint32_t *)fragment);
|
||||
msgID = bufbe32toh (fragment);
|
||||
fragment += 4;
|
||||
LogPrint ("Fragmented message ", msgID);
|
||||
isLastFragment = false;
|
||||
@@ -88,14 +88,14 @@ namespace tunnel
|
||||
else
|
||||
{
|
||||
// follow on
|
||||
msgID = be32toh (*(uint32_t *)fragment); // MessageID
|
||||
msgID = bufbe32toh (fragment); // MessageID
|
||||
fragment += 4;
|
||||
fragmentNum = (flag >> 1) & 0x3F; // 6 bits
|
||||
isLastFragment = flag & 0x01;
|
||||
LogPrint ("Follow on fragment ", fragmentNum, " of message ", msgID, isLastFragment ? " last" : " non-last");
|
||||
}
|
||||
|
||||
uint16_t size = be16toh (*(uint16_t *)fragment);
|
||||
uint16_t size = bufbe16toh (fragment);
|
||||
fragment += 2;
|
||||
LogPrint ("Fragment size=", (int)size);
|
||||
|
||||
@@ -105,8 +105,8 @@ namespace tunnel
|
||||
{
|
||||
// this is not last message. we have to copy it
|
||||
m.data = NewI2NPMessage ();
|
||||
m.data->offset += sizeof (TunnelGatewayHeader); // reserve room for TunnelGateway header
|
||||
m.data->len += sizeof (TunnelGatewayHeader);
|
||||
m.data->offset += TUNNEL_GATEWAY_HEADER_SIZE; // reserve room for TunnelGateway header
|
||||
m.data->len += TUNNEL_GATEWAY_HEADER_SIZE;
|
||||
*(m.data) = *msg;
|
||||
}
|
||||
else
|
||||
@@ -228,7 +228,7 @@ namespace tunnel
|
||||
|
||||
void TunnelEndpoint::HandleNextMessage (const TunnelMessageBlock& msg)
|
||||
{
|
||||
LogPrint ("TunnelMessage: handle fragment of ", msg.data->GetLength ()," bytes. Msg type ", (int)msg.data->GetHeader()->typeID);
|
||||
LogPrint ("TunnelMessage: handle fragment of ", msg.data->GetLength ()," bytes. Msg type ", (int)msg.data->GetTypeID ());
|
||||
switch (msg.deliveryType)
|
||||
{
|
||||
case eDeliveryTypeLocal:
|
||||
@@ -245,8 +245,8 @@ namespace tunnel
|
||||
// to somebody else
|
||||
if (!m_IsInbound) // outbound transit tunnel
|
||||
{
|
||||
if (msg.data->GetHeader()->typeID == eI2NPDatabaseStore ||
|
||||
msg.data->GetHeader()->typeID == eI2NPDatabaseSearchReply )
|
||||
auto typeID = msg.data->GetTypeID ();
|
||||
if (typeID == eI2NPDatabaseStore || typeID == eI2NPDatabaseSearchReply )
|
||||
{
|
||||
// catch RI or reply with new list of routers
|
||||
auto ds = NewI2NPMessage ();
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace tunnel
|
||||
{
|
||||
if (block.deliveryType == eDeliveryTypeTunnel)
|
||||
{
|
||||
*(uint32_t *)(di + diLen) = htobe32 (block.tunnelID);
|
||||
htobe32buf (di + diLen, block.tunnelID);
|
||||
diLen += 4; // tunnelID
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace tunnel
|
||||
if (fullMsgLen <= m_RemainingSize)
|
||||
{
|
||||
// message fits. First and last fragment
|
||||
*(uint16_t *)(di + diLen) = htobe16 (msg->GetLength ());
|
||||
htobe16buf (di + diLen, msg->GetLength ());
|
||||
diLen += 2; // size
|
||||
memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
|
||||
memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), msg->GetLength ());
|
||||
@@ -68,14 +68,15 @@ namespace tunnel
|
||||
if (diLen + 6 <= m_RemainingSize)
|
||||
{
|
||||
// delivery instructions fit
|
||||
uint32_t msgID = msg->GetHeader ()->msgID; // in network bytes order
|
||||
uint32_t msgID;
|
||||
memcpy (&msgID, msg->GetHeader () + I2NP_HEADER_MSGID_OFFSET, 4); // in network bytes order
|
||||
size_t size = m_RemainingSize - diLen - 6; // 6 = 4 (msgID) + 2 (size)
|
||||
|
||||
// first fragment
|
||||
di[0] |= 0x08; // fragmented
|
||||
*(uint32_t *)(di + diLen) = msgID;
|
||||
htobuf32 (di + diLen, msgID);
|
||||
diLen += 4; // Message ID
|
||||
*(uint16_t *)(di + diLen) = htobe16 (size);
|
||||
htobe16buf (di + diLen, size);
|
||||
diLen += 2; // size
|
||||
memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
|
||||
memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), size);
|
||||
@@ -96,9 +97,9 @@ namespace tunnel
|
||||
{
|
||||
buf[0] |= 0x01;
|
||||
isLastFragment = true;
|
||||
}
|
||||
*(uint32_t *)(buf + 1) = msgID; //Message ID
|
||||
*(uint16_t *)(buf + 5) = htobe16 (s); // size
|
||||
}
|
||||
htobuf32 (buf + 1, msgID); //Message ID
|
||||
htobe16buf (buf + 5, s); // size
|
||||
memcpy (buf + 7, msg->GetBuffer () + size, s);
|
||||
m_CurrentTunnelDataMsg->len += s+7;
|
||||
if (isLastFragment)
|
||||
@@ -132,8 +133,9 @@ namespace tunnel
|
||||
void TunnelGatewayBuffer::CreateCurrentTunnelDataMessage ()
|
||||
{
|
||||
m_CurrentTunnelDataMsg = NewI2NPMessage ();
|
||||
m_CurrentTunnelDataMsg->Align (12);
|
||||
// we reserve space for padding
|
||||
m_CurrentTunnelDataMsg->offset += TUNNEL_DATA_MSG_SIZE + sizeof (I2NPHeader);
|
||||
m_CurrentTunnelDataMsg->offset += TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE;
|
||||
m_CurrentTunnelDataMsg->len = m_CurrentTunnelDataMsg->offset;
|
||||
m_RemainingSize = TUNNEL_DATA_MAX_PAYLOAD_SIZE;
|
||||
}
|
||||
@@ -144,9 +146,9 @@ namespace tunnel
|
||||
uint8_t * payload = m_CurrentTunnelDataMsg->GetBuffer ();
|
||||
size_t size = m_CurrentTunnelDataMsg->len - m_CurrentTunnelDataMsg->offset;
|
||||
|
||||
m_CurrentTunnelDataMsg->offset = m_CurrentTunnelDataMsg->len - TUNNEL_DATA_MSG_SIZE - sizeof (I2NPHeader);
|
||||
m_CurrentTunnelDataMsg->offset = m_CurrentTunnelDataMsg->len - TUNNEL_DATA_MSG_SIZE - I2NP_HEADER_SIZE;
|
||||
uint8_t * buf = m_CurrentTunnelDataMsg->GetPayload ();
|
||||
*(uint32_t *)(buf) = htobe32 (m_TunnelID);
|
||||
htobe32buf (buf, m_TunnelID);
|
||||
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
|
||||
rnd.GenerateBlock (buf + 4, 16); // original IV
|
||||
memcpy (payload + size, buf + 4, 16); // copy IV for checksum
|
||||
|
||||
@@ -10,9 +10,9 @@ namespace i2p
|
||||
{
|
||||
namespace tunnel
|
||||
{
|
||||
TunnelPool::TunnelPool (i2p::garlic::GarlicDestination& localDestination, int numHops, int numTunnels):
|
||||
m_LocalDestination (localDestination), m_NumHops (numHops), m_NumTunnels (numTunnels),
|
||||
m_IsActive (true)
|
||||
TunnelPool::TunnelPool (i2p::garlic::GarlicDestination * localDestination, int numInboundHops, int numOutboundHops, int numTunnels):
|
||||
m_LocalDestination (localDestination), m_NumInboundHops (numInboundHops), m_NumOutboundHops (numOutboundHops),
|
||||
m_NumTunnels (numTunnels), m_IsActive (true)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ namespace tunnel
|
||||
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
|
||||
m_InboundTunnels.insert (createdTunnel);
|
||||
}
|
||||
m_LocalDestination.SetLeaseSetUpdated ();
|
||||
if (m_LocalDestination)
|
||||
m_LocalDestination->SetLeaseSetUpdated ();
|
||||
}
|
||||
|
||||
void TunnelPool::TunnelExpired (InboundTunnel * expiredTunnel)
|
||||
@@ -183,13 +184,15 @@ namespace tunnel
|
||||
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
|
||||
m_InboundTunnels.erase (it.second.second);
|
||||
}
|
||||
m_LocalDestination.SetLeaseSetUpdated ();
|
||||
if (m_LocalDestination)
|
||||
m_LocalDestination->SetLeaseSetUpdated ();
|
||||
}
|
||||
else
|
||||
it.second.second->SetState (eTunnelStateTestFailed);
|
||||
}
|
||||
}
|
||||
m_Tests.clear ();
|
||||
m_Tests.clear ();
|
||||
// new tests
|
||||
auto it1 = m_OutboundTunnels.begin ();
|
||||
auto it2 = m_InboundTunnels.begin ();
|
||||
while (it1 != m_OutboundTunnels.end () && it2 != m_InboundTunnels.end ())
|
||||
@@ -207,19 +210,34 @@ namespace tunnel
|
||||
}
|
||||
if (!failed)
|
||||
{
|
||||
uint32_t msgID = rnd.GenerateWord32 ();
|
||||
m_Tests[msgID] = std::make_pair (*it1, *it2);
|
||||
(*it1)->SendTunnelDataMsg ((*it2)->GetNextIdentHash (), (*it2)->GetNextTunnelID (),
|
||||
uint32_t msgID = rnd.GenerateWord32 ();
|
||||
m_Tests[msgID] = std::make_pair (*it1, *it2);
|
||||
(*it1)->SendTunnelDataMsg ((*it2)->GetNextIdentHash (), (*it2)->GetNextTunnelID (),
|
||||
CreateDeliveryStatusMsg (msgID));
|
||||
it1++; it2++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TunnelPool::ProcessGarlicMessage (I2NPMessage * msg)
|
||||
{
|
||||
if (m_LocalDestination)
|
||||
m_LocalDestination->ProcessGarlicMessage (msg);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "Local destination doesn't exist. Dropped");
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
}
|
||||
|
||||
void TunnelPool::ProcessDeliveryStatus (I2NPMessage * msg)
|
||||
{
|
||||
I2NPDeliveryStatusMsg * deliveryStatus = (I2NPDeliveryStatusMsg *)msg->GetPayload ();
|
||||
auto it = m_Tests.find (be32toh (deliveryStatus->msgID));
|
||||
const uint8_t * buf = msg->GetPayload ();
|
||||
uint32_t msgID = bufbe32toh (buf);
|
||||
buf += 4;
|
||||
uint64_t timestamp = bufbe64toh (buf);
|
||||
|
||||
auto it = m_Tests.find (msgID);
|
||||
if (it != m_Tests.end ())
|
||||
{
|
||||
// restore from test failed state if any
|
||||
@@ -227,18 +245,28 @@ namespace tunnel
|
||||
it->second.first->SetState (eTunnelStateEstablished);
|
||||
if (it->second.second->GetState () == eTunnelStateTestFailed)
|
||||
it->second.second->SetState (eTunnelStateEstablished);
|
||||
LogPrint ("Tunnel test ", it->first, " successive. ", i2p::util::GetMillisecondsSinceEpoch () - be64toh (deliveryStatus->timestamp), " milliseconds");
|
||||
LogPrint ("Tunnel test ", it->first, " successive. ", i2p::util::GetMillisecondsSinceEpoch () - timestamp, " milliseconds");
|
||||
m_Tests.erase (it);
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
else
|
||||
m_LocalDestination.ProcessDeliveryStatusMessage (msg);
|
||||
{
|
||||
if (m_LocalDestination)
|
||||
m_LocalDestination->ProcessDeliveryStatusMessage (msg);
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "Local destination doesn't exist. Dropped");
|
||||
DeleteI2NPMessage (msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop) const
|
||||
{
|
||||
auto hop = m_NumHops >= 3 ? i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop) :
|
||||
i2p::data::netdb.GetRandomRouter (prevHop);
|
||||
bool isExploratory = (m_LocalDestination == &i2p::context); // TODO: implement it better
|
||||
auto hop = isExploratory ? i2p::data::netdb.GetRandomRouter (prevHop):
|
||||
i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop);
|
||||
|
||||
if (!hop)
|
||||
hop = i2p::data::netdb.GetRandomRouter ();
|
||||
return hop;
|
||||
@@ -252,7 +280,7 @@ namespace tunnel
|
||||
LogPrint ("Creating destination inbound tunnel...");
|
||||
auto prevHop = i2p::context.GetSharedRouterInfo ();
|
||||
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
|
||||
int numHops = m_NumHops;
|
||||
int numHops = m_NumInboundHops;
|
||||
if (outboundTunnel)
|
||||
{
|
||||
// last hop
|
||||
@@ -296,7 +324,7 @@ namespace tunnel
|
||||
|
||||
auto prevHop = i2p::context.GetSharedRouterInfo ();
|
||||
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
|
||||
for (int i = 0; i < m_NumHops; i++)
|
||||
for (int i = 0; i < m_NumOutboundHops; i++)
|
||||
{
|
||||
auto hop = SelectNextHop (prevHop);
|
||||
prevHop = hop;
|
||||
|
||||
19
TunnelPool.h
19
TunnelPool.h
@@ -26,14 +26,11 @@ namespace tunnel
|
||||
{
|
||||
public:
|
||||
|
||||
TunnelPool (i2p::garlic::GarlicDestination& localDestination, int numHops, int numTunnels = 5);
|
||||
TunnelPool (i2p::garlic::GarlicDestination * localDestination, int numInboundHops, int numOutboundHops, int numTunnels = 5);
|
||||
~TunnelPool ();
|
||||
|
||||
const uint8_t * GetEncryptionPrivateKey () const { return m_LocalDestination.GetEncryptionPrivateKey (); };
|
||||
const uint8_t * GetEncryptionPublicKey () const { return m_LocalDestination.GetEncryptionPublicKey (); };
|
||||
const i2p::data::LocalDestination& GetLocalDestination () const { return m_LocalDestination; };
|
||||
i2p::garlic::GarlicDestination& GetGarlicDestination () const { return m_LocalDestination; };
|
||||
bool IsExploratory () const { return GetIdentHash () == i2p::context.GetIdentHash (); };
|
||||
|
||||
i2p::garlic::GarlicDestination * GetLocalDestination () const { return m_LocalDestination; };
|
||||
void SetLocalDestination (i2p::garlic::GarlicDestination * destination) { m_LocalDestination = destination; };
|
||||
|
||||
void CreateTunnels ();
|
||||
void TunnelCreated (InboundTunnel * createdTunnel);
|
||||
@@ -42,10 +39,10 @@ namespace tunnel
|
||||
void TunnelExpired (OutboundTunnel * expiredTunnel);
|
||||
std::vector<InboundTunnel *> GetInboundTunnels (int num) const;
|
||||
OutboundTunnel * GetNextOutboundTunnel (OutboundTunnel * suggested = nullptr) const;
|
||||
InboundTunnel * GetNextInboundTunnel (InboundTunnel * suggested = nullptr) const;
|
||||
const i2p::data::IdentHash& GetIdentHash () const { return m_LocalDestination.GetIdentHash (); };
|
||||
InboundTunnel * GetNextInboundTunnel (InboundTunnel * suggested = nullptr) const;
|
||||
|
||||
void TestTunnels ();
|
||||
void ProcessGarlicMessage (I2NPMessage * msg);
|
||||
void ProcessDeliveryStatus (I2NPMessage * msg);
|
||||
|
||||
bool IsActive () const { return m_IsActive; };
|
||||
@@ -65,8 +62,8 @@ namespace tunnel
|
||||
|
||||
private:
|
||||
|
||||
i2p::garlic::GarlicDestination& m_LocalDestination;
|
||||
int m_NumHops, m_NumTunnels;
|
||||
i2p::garlic::GarlicDestination * m_LocalDestination;
|
||||
int m_NumInboundHops, m_NumOutboundHops, m_NumTunnels;
|
||||
mutable std::mutex m_InboundTunnelsMutex;
|
||||
std::set<InboundTunnel *, TunnelCreationTimeCmp> m_InboundTunnels; // recent tunnel appears first
|
||||
mutable std::mutex m_OutboundTunnelsMutex;
|
||||
|
||||
314
UPnP.cpp
314
UPnP.cpp
@@ -1,68 +1,270 @@
|
||||
#ifdef USE_UPNP
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include <thread>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include <boost/thread/thread.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
|
||||
#include "Log.h"
|
||||
#include "RouterContext.h"
|
||||
#include "UPnP.h"
|
||||
#include "NetDb.h"
|
||||
#include "util.h"
|
||||
|
||||
#include <miniupnpc/miniupnpc.h>
|
||||
#include <miniupnpc/upnpcommands.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#ifndef UPNPDISCOVER_SUCCESS
|
||||
/* miniupnpc 1.5 */
|
||||
typedef UPNPDev* (*upnp_upnpDiscoverFunc) (int, const char *, const char *, int);
|
||||
typedef int (*upnp_UPNP_AddPortMappingFunc) (const char *, const char *, const char *, const char *,
|
||||
const char *, const char *, const char *, const char *);
|
||||
#else
|
||||
/* miniupnpc 1.6 */
|
||||
typedef UPNPDev* (*upnp_upnpDiscoverFunc) (int, const char *, const char *, int, int, int *);
|
||||
typedef int (*upnp_UPNP_AddPortMappingFunc) (const char *, const char *, const char *, const char *,
|
||||
const char *, const char *, const char *, const char *, const char *);
|
||||
#endif
|
||||
typedef int (*upnp_UPNP_GetValidIGDFunc) (struct UPNPDev *, struct UPNPUrls *, struct IGDdatas *, char *, int);
|
||||
typedef int (*upnp_UPNP_GetExternalIPAddressFunc) (const char *, const char *, char *);
|
||||
typedef int (*upnp_UPNP_DeletePortMappingFunc) (const char *, const char *, const char *, const char *, const char *);
|
||||
typedef void (*upnp_freeUPNPDevlistFunc) (struct UPNPDev *);
|
||||
typedef void (*upnp_FreeUPNPUrlsFunc) (struct UPNPUrls *);
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
UPnP::UPnP (): m_Timer (m_Service),
|
||||
m_Endpoint (boost::asio::ip::udp::v4 (), UPNP_REPLY_PORT),
|
||||
m_MulticastEndpoint (boost::asio::ip::address::from_string (UPNP_GROUP), UPNP_PORT),
|
||||
m_Socket (m_Service, m_Endpoint.protocol ())
|
||||
{
|
||||
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (65535));
|
||||
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (65535));
|
||||
m_Socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
|
||||
}
|
||||
|
||||
UPnP::~UPnP ()
|
||||
{
|
||||
}
|
||||
namespace UPnP
|
||||
{
|
||||
UPnP upnpc;
|
||||
|
||||
void UPnP::Run ()
|
||||
{
|
||||
DiscoverRouter ();
|
||||
m_Service.run ();
|
||||
}
|
||||
|
||||
void UPnP::DiscoverRouter ()
|
||||
{
|
||||
m_Timer.expires_from_now (boost::posix_time::seconds(5)); // 5 seconds
|
||||
m_Timer.async_wait (boost::bind (&UPnP::HandleTimer, this, boost::asio::placeholders::error));
|
||||
UPnP::UPnP () : m_Thread (nullptr) , m_IsModuleLoaded (false)
|
||||
{
|
||||
}
|
||||
|
||||
std::string address = UPNP_GROUP;
|
||||
address += ":" + boost::lexical_cast<std::string>(UPNP_PORT);
|
||||
std::string request = "M-SEARCH * HTTP/1.1\r\n"
|
||||
"HOST: " + address + "\r\n"
|
||||
"ST:" + UPNP_ROUTER + "\r\n"
|
||||
"MAN:\"ssdp:discover\"\r\n"
|
||||
"MX:3\r\n"
|
||||
"\r\n\r\n";
|
||||
m_Socket.send_to (boost::asio::buffer (request.c_str (), request.length ()), m_MulticastEndpoint);
|
||||
Receive ();
|
||||
}
|
||||
void UPnP::Stop ()
|
||||
{
|
||||
if (m_Thread)
|
||||
{
|
||||
m_Thread->join ();
|
||||
delete m_Thread;
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void UPnP::Receive ()
|
||||
{
|
||||
m_Socket.async_receive_from (boost::asio::buffer (m_ReceiveBuffer, UPNP_MAX_PACKET_LEN), m_SenderEndpoint,
|
||||
boost::bind (&UPnP::HandleReceivedFrom, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void UPnP::HandleReceivedFrom (const boost::system::error_code& ecode, size_t bytes_transferred)
|
||||
{
|
||||
LogPrint ("UPnP: ", bytes_transferred, " received from ", m_SenderEndpoint.address ());
|
||||
std::string str (m_ReceiveBuffer, bytes_transferred);
|
||||
LogPrint (str);
|
||||
m_Timer.cancel ();
|
||||
}
|
||||
void UPnP::Start()
|
||||
{
|
||||
m_Thread = new std::thread (std::bind (&UPnP::Run, this));
|
||||
}
|
||||
|
||||
UPnP::~UPnP ()
|
||||
{
|
||||
}
|
||||
|
||||
void UPnP::Run ()
|
||||
{
|
||||
#ifdef MAC_OSX
|
||||
m_Module = dlopen ("libminiupnpc.dylib", RTLD_LAZY);
|
||||
#elif _WIN32
|
||||
m_Module = LoadLibrary ("libminiupnpc.dll");
|
||||
if (m_Module == NULL)
|
||||
{
|
||||
LogPrint ("Error loading UPNP library. This often happens if there is version mismatch!");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_IsModuleLoaded = true;
|
||||
}
|
||||
#else
|
||||
m_Module = dlopen ("libminiupnpc.so", RTLD_LAZY);
|
||||
#endif
|
||||
#ifndef _WIN32
|
||||
if (!m_Module)
|
||||
{
|
||||
LogPrint ("no UPnP module available (", dlerror (), ")");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_IsModuleLoaded = true;
|
||||
}
|
||||
#endif
|
||||
for (auto& address : context.GetRouterInfo ().GetAddresses ())
|
||||
{
|
||||
if (!address.host.is_v6 ())
|
||||
{
|
||||
m_Port = std::to_string (util::config::GetArg ("-port", address.port));
|
||||
Discover ();
|
||||
if (address.transportStyle == data::RouterInfo::eTransportSSU )
|
||||
{
|
||||
TryPortMapping (I2P_UPNP_UDP);
|
||||
}
|
||||
else if (address.transportStyle == data::RouterInfo::eTransportNTCP )
|
||||
{
|
||||
TryPortMapping (I2P_UPNP_TCP);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UPnP::Discover ()
|
||||
{
|
||||
const char *error;
|
||||
#ifdef _WIN32
|
||||
upnp_upnpDiscoverFunc upnpDiscoverFunc = (upnp_upnpDiscoverFunc) GetProcAddress (m_Module, "upnpDiscover");
|
||||
#else
|
||||
upnp_upnpDiscoverFunc upnpDiscoverFunc = (upnp_upnpDiscoverFunc) dlsym (m_Module, "upnpDiscover");
|
||||
// reinterpret_cast<upnp_upnpDiscoverFunc> (dlsym(...));
|
||||
if ( (error = dlerror ()))
|
||||
{
|
||||
LogPrint ("Error loading UPNP library. This often happens if there is version mismatch!");
|
||||
return;
|
||||
}
|
||||
#endif // _WIN32
|
||||
#ifndef UPNPDISCOVER_SUCCESS
|
||||
/* miniupnpc 1.5 */
|
||||
m_Devlist = upnpDiscoverFunc (2000, m_MulticastIf, m_Minissdpdpath, 0);
|
||||
#else
|
||||
/* miniupnpc 1.6 */
|
||||
int nerror = 0;
|
||||
m_Devlist = upnpDiscoverFunc (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, &nerror);
|
||||
#endif
|
||||
|
||||
int r;
|
||||
#ifdef _WIN32
|
||||
upnp_UPNP_GetValidIGDFunc UPNP_GetValidIGDFunc = (upnp_UPNP_GetValidIGDFunc) GetProcAddress (m_Module, "UPNP_GetValidIGD");
|
||||
#else
|
||||
upnp_UPNP_GetValidIGDFunc UPNP_GetValidIGDFunc = (upnp_UPNP_GetValidIGDFunc) dlsym (m_Module, "UPNP_GetValidIGD");
|
||||
#endif
|
||||
r = (*UPNP_GetValidIGDFunc) (m_Devlist, &m_upnpUrls, &m_upnpData, m_NetworkAddr, sizeof (m_NetworkAddr));
|
||||
if (r == 1)
|
||||
{
|
||||
upnp_UPNP_GetExternalIPAddressFunc UPNP_GetExternalIPAddressFunc = (upnp_UPNP_GetExternalIPAddressFunc) dlsym (m_Module, "UPNP_GetExternalIPAddress");
|
||||
r = UPNP_GetExternalIPAddressFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);
|
||||
if(r != UPNPCOMMAND_SUCCESS)
|
||||
{
|
||||
LogPrint ("UPnP: UPNP_GetExternalIPAddress () returned ", r);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_externalIPAddress[0])
|
||||
{
|
||||
LogPrint ("UPnP: ExternalIPAddress = ", m_externalIPAddress);
|
||||
i2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("UPnP: GetExternalIPAddress failed.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UPnP::TryPortMapping (int type)
|
||||
{
|
||||
std::string strType;
|
||||
switch (type)
|
||||
{
|
||||
case I2P_UPNP_TCP:
|
||||
strType = "TCP";
|
||||
break;
|
||||
case I2P_UPNP_UDP:
|
||||
default:
|
||||
strType = "UDP";
|
||||
}
|
||||
int r;
|
||||
std::string strDesc = "I2Pd";
|
||||
try {
|
||||
for (;;) {
|
||||
#ifdef _WIN32
|
||||
upnp_UPNP_AddPortMappingFunc UPNP_AddPortMappingFunc = (upnp_UPNP_AddPortMappingFunc) GetProcAddress (m_Module, "UPNP_AddPortMapping");
|
||||
#else
|
||||
upnp_UPNP_AddPortMappingFunc UPNP_AddPortMappingFunc = (upnp_UPNP_AddPortMappingFunc) dlsym (m_Module, "UPNP_AddPortMapping");
|
||||
#endif
|
||||
#ifndef UPNPDISCOVER_SUCCESS
|
||||
/* miniupnpc 1.5 */
|
||||
r = UPNP_AddPortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), m_Port.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0);
|
||||
#else
|
||||
/* miniupnpc 1.6 */
|
||||
r = UPNP_AddPortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), m_Port.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0, "0");
|
||||
#endif
|
||||
if (r!=UPNPCOMMAND_SUCCESS)
|
||||
{
|
||||
LogPrint ("AddPortMapping (", m_Port.c_str () ,", ", m_Port.c_str () ,", ", m_NetworkAddr, ") failed with code ", r);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint ("UPnP Port Mapping successful. (", m_NetworkAddr ,":", m_Port.c_str(), " type ", strType.c_str () ," -> ", m_externalIPAddress ,":", m_Port.c_str() ,")");
|
||||
return;
|
||||
}
|
||||
sleep(20*60);
|
||||
}
|
||||
}
|
||||
catch (boost::thread_interrupted)
|
||||
{
|
||||
CloseMapping(type);
|
||||
Close();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void UPnP::CloseMapping (int type)
|
||||
{
|
||||
std::string strType;
|
||||
switch (type)
|
||||
{
|
||||
case I2P_UPNP_TCP:
|
||||
strType = "TCP";
|
||||
break;
|
||||
case I2P_UPNP_UDP:
|
||||
default:
|
||||
strType = "UDP";
|
||||
}
|
||||
int r = 0;
|
||||
#ifdef _WIN32
|
||||
upnp_UPNP_DeletePortMappingFunc UPNP_DeletePortMappingFunc = (upnp_UPNP_DeletePortMappingFunc) GetProcAddress (m_Module, "UPNP_DeletePortMapping");
|
||||
#else
|
||||
upnp_UPNP_DeletePortMappingFunc UPNP_DeletePortMappingFunc = (upnp_UPNP_DeletePortMappingFunc) dlsym (m_Module, "UPNP_DeletePortMapping");
|
||||
#endif
|
||||
r = UPNP_DeletePortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), strType.c_str (), 0);
|
||||
LogPrint ("UPNP_DeletePortMapping() returned : ", r, "\n");
|
||||
}
|
||||
|
||||
void UPnP::Close ()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
upnp_freeUPNPDevlistFunc freeUPNPDevlistFunc = (upnp_freeUPNPDevlistFunc) GetProcAddress (m_Module, "freeUPNPDevlist");
|
||||
#else
|
||||
upnp_freeUPNPDevlistFunc freeUPNPDevlistFunc = (upnp_freeUPNPDevlistFunc) dlsym (m_Module, "freeUPNPDevlist");
|
||||
#endif
|
||||
freeUPNPDevlistFunc (m_Devlist);
|
||||
m_Devlist = 0;
|
||||
#ifdef _WIN32
|
||||
upnp_FreeUPNPUrlsFunc FreeUPNPUrlsFunc = (upnp_FreeUPNPUrlsFunc) GetProcAddress (m_Module, "FreeUPNPUrlsFunc");
|
||||
#else
|
||||
upnp_FreeUPNPUrlsFunc FreeUPNPUrlsFunc = (upnp_FreeUPNPUrlsFunc) dlsym (m_Module, "FreeUPNPUrlsFunc");
|
||||
#endif
|
||||
FreeUPNPUrlsFunc (&m_upnpUrls);
|
||||
#ifndef _WIN32
|
||||
dlclose (m_Module);
|
||||
#else
|
||||
FreeLibrary (m_Module);
|
||||
#endif
|
||||
}
|
||||
|
||||
void UPnP::HandleTimer (const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
LogPrint ("UPnP: timeout expired");
|
||||
m_Service.stop ();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
76
UPnP.h
76
UPnP.h
@@ -1,41 +1,65 @@
|
||||
#ifndef UPNP_H__
|
||||
#define UPNP_H__
|
||||
#ifndef __UPNP_H__
|
||||
#define __UPNP_H__
|
||||
|
||||
#ifdef USE_UPNP
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include <miniupnpc/miniwget.h>
|
||||
#include <miniupnpc/miniupnpc.h>
|
||||
#include <miniupnpc/upnpcommands.h>
|
||||
#include <miniupnpc/upnperrors.h>
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
|
||||
#include "util.h"
|
||||
|
||||
#define I2P_UPNP_TCP 1
|
||||
#define I2P_UPNP_UDP 2
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
const int UPNP_MAX_PACKET_LEN = 1500;
|
||||
const char UPNP_GROUP[] = "239.255.255.250";
|
||||
const int UPNP_PORT = 1900;
|
||||
const int UPNP_REPLY_PORT = 1901;
|
||||
const char UPNP_ROUTER[] = "urn:schemas-upnp-org:device:InternetGatewayDevice:1";
|
||||
|
||||
namespace UPnP
|
||||
{
|
||||
class UPnP
|
||||
{
|
||||
public:
|
||||
public:
|
||||
|
||||
UPnP ();
|
||||
~UPnP ();
|
||||
UPnP ();
|
||||
~UPnP ();
|
||||
void Close ();
|
||||
|
||||
void Run ();
|
||||
|
||||
void Start ();
|
||||
void Stop ();
|
||||
|
||||
private:
|
||||
void Discover ();
|
||||
void TryPortMapping (int type);
|
||||
void CloseMapping (int type);
|
||||
private:
|
||||
void Run ();
|
||||
|
||||
void DiscoverRouter ();
|
||||
void Receive ();
|
||||
void HandleReceivedFrom (const boost::system::error_code& ecode, size_t bytes_transferred);
|
||||
void HandleTimer (const boost::system::error_code& ecode);
|
||||
|
||||
private:
|
||||
std::thread * m_Thread;
|
||||
struct UPNPUrls m_upnpUrls;
|
||||
struct IGDdatas m_upnpData;
|
||||
|
||||
boost::asio::io_service m_Service;
|
||||
boost::asio::deadline_timer m_Timer;
|
||||
boost::asio::ip::udp::endpoint m_Endpoint, m_MulticastEndpoint, m_SenderEndpoint;
|
||||
boost::asio::ip::udp::socket m_Socket;
|
||||
char m_ReceiveBuffer[UPNP_MAX_PACKET_LEN];
|
||||
};
|
||||
// For miniupnpc
|
||||
char * m_MulticastIf = 0;
|
||||
char * m_Minissdpdpath = 0;
|
||||
struct UPNPDev * m_Devlist = 0;
|
||||
char m_NetworkAddr[64];
|
||||
char m_externalIPAddress[40];
|
||||
bool m_IsModuleLoaded;
|
||||
std::string m_Port = std::to_string (util::config::GetArg ("-port", 17070));
|
||||
#ifndef _WIN32
|
||||
void *m_Module;
|
||||
#else
|
||||
HINSTANCE *m_Module;
|
||||
#endif
|
||||
};
|
||||
extern UPnP upnpc;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<ClCompile Include="..\AddressBook.cpp" />
|
||||
<ClCompile Include="..\aes.cpp" />
|
||||
<ClCompile Include="..\base64.cpp" />
|
||||
<ClCompile Include="..\BOB.cpp" />
|
||||
<ClCompile Include="..\CryptoConst.cpp" />
|
||||
<ClCompile Include="..\Daemon.cpp" />
|
||||
<ClCompile Include="..\DaemonWin32.cpp" />
|
||||
@@ -62,6 +63,7 @@
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\AddressBook.h" />
|
||||
<ClInclude Include="..\base64.h" />
|
||||
<ClInclude Include="..\BOB.h" />
|
||||
<ClInclude Include="..\CryptoConst.h" />
|
||||
<ClInclude Include="..\Daemon.h" />
|
||||
<ClInclude Include="..\ElGamal.h" />
|
||||
@@ -278,4 +280,4 @@
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
26
aes.cpp
26
aes.cpp
@@ -25,7 +25,7 @@ namespace crypto
|
||||
"movaps %%xmm3, %%xmm4 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
@@ -66,7 +66,7 @@ namespace crypto
|
||||
"movups %%xmm1, 224(%[sched]) \n"
|
||||
: // output
|
||||
: [key]"r"((const uint8_t *)key), [sched]"r"(GetKeySchedule ()) // input
|
||||
: "%xmm1", "%xmm2", "%xmm3", "%xmm4" // clogged
|
||||
: "%xmm1", "%xmm2", "%xmm3", "%xmm4", "memory" // clogged
|
||||
);
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ namespace crypto
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
EncryptAES256(sched)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0"
|
||||
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ namespace crypto
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
DecryptAES256(sched)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0"
|
||||
: : [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out) : "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ namespace crypto
|
||||
CallAESIMC(176)
|
||||
CallAESIMC(192)
|
||||
CallAESIMC(208)
|
||||
: : [shed]"r"(GetKeySchedule ()) : "%xmm0"
|
||||
: : [shed]"r"(GetKeySchedule ()) : "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ namespace crypto
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"block_e: \n"
|
||||
"1: \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
EncryptAES256(sched)
|
||||
@@ -172,7 +172,7 @@ namespace crypto
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"dec %[num] \n"
|
||||
"jnz block_e; \n"
|
||||
"jnz 1b \n"
|
||||
"movups %%xmm1, (%[iv]) \n"
|
||||
:
|
||||
: [iv]"r"(&m_LastBlock), [sched]"r"(m_ECBEncryption.GetKeySchedule ()),
|
||||
@@ -222,7 +222,7 @@ namespace crypto
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"block_d: \n"
|
||||
"1: \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"movaps %%xmm0, %%xmm2 \n"
|
||||
DecryptAES256(sched)
|
||||
@@ -232,7 +232,7 @@ namespace crypto
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"dec %[num] \n"
|
||||
"jnz block_d; \n"
|
||||
"jnz 1b \n"
|
||||
"movups %%xmm1, (%[iv]) \n"
|
||||
:
|
||||
: [iv]"r"(&m_IV), [sched]"r"(m_ECBDecryption.GetKeySchedule ()),
|
||||
@@ -289,7 +289,7 @@ namespace crypto
|
||||
EncryptAES256(sched_iv)
|
||||
"movups %%xmm0, (%[payload]) \n"
|
||||
// encrypt data, IV is xmm1
|
||||
"block_et: \n"
|
||||
"1: \n"
|
||||
"add $16, %[payload] \n"
|
||||
"movups (%[payload]), %%xmm0 \n"
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
@@ -297,7 +297,7 @@ namespace crypto
|
||||
"movaps %%xmm0, %%xmm1 \n"
|
||||
"movups %%xmm0, (%[payload]) \n"
|
||||
"dec %[num] \n"
|
||||
"jnz block_et; \n"
|
||||
"jnz 1b \n"
|
||||
:
|
||||
: [sched_iv]"r"(m_IVEncryption.GetKeySchedule ()), [sched_l]"r"(m_LayerEncryption.GetKeySchedule ()),
|
||||
[payload]"r"(payload), [num]"r"(63) // 63 blocks = 1008 bytes
|
||||
@@ -324,7 +324,7 @@ namespace crypto
|
||||
DecryptAES256(sched_iv)
|
||||
"movups %%xmm0, (%[payload]) \n"
|
||||
// decrypt data, IV is xmm1
|
||||
"block_dt: \n"
|
||||
"1: \n"
|
||||
"add $16, %[payload] \n"
|
||||
"movups (%[payload]), %%xmm0 \n"
|
||||
"movaps %%xmm0, %%xmm2 \n"
|
||||
@@ -333,7 +333,7 @@ namespace crypto
|
||||
"movups %%xmm0, (%[payload]) \n"
|
||||
"movaps %%xmm2, %%xmm1 \n"
|
||||
"dec %[num] \n"
|
||||
"jnz block_dt; \n"
|
||||
"jnz 1b \n"
|
||||
:
|
||||
: [sched_iv]"r"(m_IVDecryption.GetKeySchedule ()), [sched_l]"r"(m_LayerDecryption.GetKeySchedule ()),
|
||||
[payload]"r"(payload), [num]"r"(63) // 63 blocks = 1008 bytes
|
||||
|
||||
2
aes.h
2
aes.h
@@ -45,7 +45,7 @@ namespace crypto
|
||||
AESAlignedBuffer ()
|
||||
{
|
||||
m_Buf = m_UnalignedBuffer;
|
||||
uint8_t rem = ((uint64_t)m_Buf) & 0x0f;
|
||||
uint8_t rem = ((size_t)m_Buf) & 0x0f;
|
||||
if (rem)
|
||||
m_Buf += (16 - rem);
|
||||
}
|
||||
|
||||
@@ -21,9 +21,12 @@ namespace api
|
||||
i2p::context.Init ();
|
||||
}
|
||||
|
||||
void StartI2P ()
|
||||
void StartI2P (std::ostream * logStream)
|
||||
{
|
||||
StartLog (i2p::util::filesystem::GetAppName () + ".log");
|
||||
if (logStream)
|
||||
StartLog (logStream);
|
||||
else
|
||||
StartLog (i2p::util::filesystem::GetAppName () + ".log");
|
||||
i2p::data::netdb.Start();
|
||||
LogPrint("NetDB started");
|
||||
i2p::transport::transports.Start();
|
||||
@@ -44,16 +47,19 @@ namespace api
|
||||
StopLog ();
|
||||
}
|
||||
|
||||
i2p::client::ClientDestination * CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic)
|
||||
i2p::client::ClientDestination * CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
auto localDestination = new i2p::client::ClientDestination (keys, isPublic);
|
||||
auto localDestination = new i2p::client::ClientDestination (keys, isPublic, params);
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
|
||||
i2p::client::ClientDestination * CreateLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType)
|
||||
i2p::client::ClientDestination * CreateLocalDestination (bool isPublic, i2p::data::SigningKeyType sigType,
|
||||
const std::map<std::string, std::string> * params)
|
||||
{
|
||||
auto localDestination = new i2p::client::ClientDestination (isPublic, sigType);
|
||||
i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType);
|
||||
auto localDestination = new i2p::client::ClientDestination (keys, isPublic, params);
|
||||
localDestination->Start ();
|
||||
return localDestination;
|
||||
}
|
||||
@@ -70,12 +76,13 @@ namespace api
|
||||
void RequestLeaseSet (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote)
|
||||
{
|
||||
if (dest)
|
||||
i2p::data::netdb.RequestDestination (remote, true, dest->GetTunnelPool ());
|
||||
dest->RequestDestination (remote);
|
||||
}
|
||||
|
||||
i2p::stream::Stream * CreateStream (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote)
|
||||
std::shared_ptr<i2p::stream::Stream> CreateStream (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote)
|
||||
{
|
||||
auto leaseSet = i2p::data::netdb.FindLeaseSet (remote);
|
||||
if (!dest) return nullptr;
|
||||
auto leaseSet = dest->FindLeaseSet (remote);
|
||||
if (leaseSet)
|
||||
{
|
||||
auto stream = dest->CreateStream (*leaseSet);
|
||||
@@ -95,13 +102,10 @@ namespace api
|
||||
dest->AcceptStreams (acceptor);
|
||||
}
|
||||
|
||||
void DestroyStream (i2p::stream::Stream * stream)
|
||||
void DestroyStream (std::shared_ptr<i2p::stream::Stream> stream)
|
||||
{
|
||||
if (stream)
|
||||
{
|
||||
stream->Close ();
|
||||
i2p::stream::DeleteStream (stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
36
api.h
Normal file
36
api.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef API_H__
|
||||
#define API_H__
|
||||
|
||||
#include <memory>
|
||||
#include <iostream>
|
||||
#include "Identity.h"
|
||||
#include "Destination.h"
|
||||
#include "Streaming.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace api
|
||||
{
|
||||
// initialization start and stop
|
||||
void InitI2P (int argc, char* argv[], const char * appName);
|
||||
void StartI2P (std::ostream * logStream = nullptr);
|
||||
// write system log to logStream, if not specified to <appName>.log in application's folder
|
||||
void StopI2P ();
|
||||
|
||||
// destinations
|
||||
i2p::client::ClientDestination * CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic = true,
|
||||
const std::map<std::string, std::string> * params = nullptr);
|
||||
i2p::client::ClientDestination * CreateLocalDestination (bool isPublic = false, i2p::data::SigningKeyType sigType = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256,
|
||||
const std::map<std::string, std::string> * params = nullptr); // transient destinations usually not published
|
||||
void DestroyLocalDestination (i2p::client::ClientDestination * dest);
|
||||
|
||||
// streams
|
||||
void RequestLeaseSet (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote);
|
||||
std::shared_ptr<i2p::stream::Stream> CreateStream (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote);
|
||||
void AcceptStream (i2p::client::ClientDestination * dest, const i2p::stream::StreamingDestination::Acceptor& acceptor);
|
||||
void DestroyStream (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
33
api/Makefile
33
api/Makefile
@@ -1,33 +0,0 @@
|
||||
UNAME := $(shell uname -s)
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
include ../Makefile.osx
|
||||
else ifeq ($(UNAME), FreeBSD)
|
||||
include ../Makefile.bsd
|
||||
else
|
||||
include ../Makefile.linux
|
||||
endif
|
||||
|
||||
SHARED_LIB = libi2pd.so
|
||||
all: obj $(SHARED_LIB)
|
||||
|
||||
$(SHARED_LIB): $(OBJECTS:obj/%=obj/%)
|
||||
$(CXX) -shared -o $(SHARED_LIB) $^
|
||||
|
||||
.SUFFIXES:
|
||||
.SUFFIXES: .c .cc .C .cpp .o
|
||||
|
||||
obj/%.o : ../%.cpp
|
||||
$(CXX) -o $@ $< -c $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) -I.. -fPIC $(CPU_FLAGS)
|
||||
|
||||
obj/api.o: api.cpp
|
||||
$(CXX) -o obj/api.o api.cpp -c $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) -I.. -fPIC $(CPU_FLAGS)
|
||||
|
||||
obj:
|
||||
mkdir -p obj
|
||||
|
||||
clean:
|
||||
rm -fr obj $(SHARED_LIB)
|
||||
|
||||
.PHONY: all
|
||||
.PHONY: clean
|
||||
31
api/api.h
31
api/api.h
@@ -1,31 +0,0 @@
|
||||
#ifndef API_H__
|
||||
#define API_H__
|
||||
|
||||
#include "Identity.h"
|
||||
#include "Destination.h"
|
||||
#include "Streaming.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace api
|
||||
{
|
||||
// initialization start and stop
|
||||
void InitI2P (int argc, char* argv[], const char * appName);
|
||||
void StartI2P ();
|
||||
void StopI2P ();
|
||||
|
||||
// destinations
|
||||
i2p::client::ClientDestination * CreateLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic = true);
|
||||
i2p::client::ClientDestination * CreateLocalDestination (bool isPublic = false, i2p::data::SigningKeyType sigType = i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); // transient destinations usually not published
|
||||
void DestoroyLocalDestination (i2p::client::ClientDestination * dest);
|
||||
|
||||
// streams
|
||||
void RequestLeaseSet (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote);
|
||||
i2p::stream::Stream * CreateStream (i2p::client::ClientDestination * dest, const i2p::data::IdentHash& remote);
|
||||
void AcceptStream (i2p::client::ClientDestination * dest, const i2p::stream::StreamingDestination::Acceptor& acceptor);
|
||||
void DestroyStream (i2p::stream::Stream * stream);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
|
||||
|
||||
CPP_FILES := ../CryptoConst.cpp ../base64.cpp ../NTCPSession.cpp ../RouterInfo.cpp \
|
||||
../Transports.cpp ../RouterContext.cpp ../NetDb.cpp ../LeaseSet.cpp Tunnel.cpp \
|
||||
../TunnelEndpoint.cpp ../TunnelGateway.cpp ../TransitTunnel.cpp ../I2NPProtocol.cpp \
|
||||
../Log.cpp ../Garlic.cpp ../Streaming.cpp ../Destination.cpp ../Identity.cpp \
|
||||
../SSU.cpp ../SSUSession.cpp ../SSUData.cpp ../util.cpp ../Reseed.cpp ../SSUData.cpp \
|
||||
../aes.cpp ../TunnelPool.cpp ../AddressBook.cpp ../Datagram.cpp api.cpp
|
||||
|
||||
|
||||
H_FILES := ../CryptoConst.h ../base64.h ../NTCPSession.h ../RouterInfo.h ../Transports.h \
|
||||
../RouterContext.h ../NetDb.h ../LeaseSet.h ../Tunnel.h ../TunnelEndpoint.h \
|
||||
../TunnelGateway.h ../TransitTunnel.h ../I2NPProtocol.h ../Log.h ../Garlic.h \
|
||||
../Streaming.h ../Destination.h ../Identity.h ../SSU.h ../SSUSession.h ../SSUData.h \
|
||||
../util.h ../Reseed.h ../SSUData.h ../aes.h ../TunnelPool.h ../AddressBook.h ../version.h \
|
||||
../Signature.h ../TransportSession.h ../Datagram.h api.h
|
||||
|
||||
OBJECTS = $(addprefix obj/, $(notdir $(CPP_FILES:.cpp=.o)))
|
||||
|
||||
@@ -79,7 +79,7 @@ namespace data
|
||||
outCount = 4*n;
|
||||
else
|
||||
outCount = 4*(n+1);
|
||||
if (outCount > len) return -1;
|
||||
if (outCount > len) return 0;
|
||||
pd = (unsigned char *)OutBuffer;
|
||||
for ( i = 0; i<n; i++ ){
|
||||
acc_1 = *ps++;
|
||||
@@ -158,7 +158,7 @@ namespace data
|
||||
outCount = 3*n;
|
||||
else {
|
||||
outCount = 0;
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
ps = (unsigned char *)(InBuffer + InCount - 1);
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
cmake_minimum_required ( VERSION 2.8 )
|
||||
cmake_minimum_required ( VERSION 2.8.5 )
|
||||
project ( "i2pd" )
|
||||
|
||||
# configurale options
|
||||
option(WITH_AESNI "Use AES-NI instructions set" OFF)
|
||||
option(WITH_HARDENING "Use hardening compiler flags" OFF)
|
||||
option(WITH_LIBRARY "Build library" ON)
|
||||
option(WITH_BINARY "Build binary" ON)
|
||||
option(WITH_STATIC "Static build" OFF)
|
||||
|
||||
# paths
|
||||
set ( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules" )
|
||||
set ( CMAKE_SOURCE_DIR ".." )
|
||||
|
||||
set (SOURCES
|
||||
"${CMAKE_SOURCE_DIR}/AddressBook.cpp"
|
||||
set (COMMON_SRC
|
||||
"${CMAKE_SOURCE_DIR}/AddressBook.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/CryptoConst.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Daemon.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Garlic.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/HTTPProxy.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/HTTPServer.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/I2NPProtocol.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/I2PTunnel.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Identity.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/LeaseSet.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Log.cpp"
|
||||
@@ -26,9 +25,9 @@ set (SOURCES
|
||||
"${CMAKE_SOURCE_DIR}/Reseed.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/RouterContext.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/RouterInfo.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SOCKS.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SSU.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SSUData.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SSUSession.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Streaming.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Destination.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/TransitTunnel.cpp"
|
||||
@@ -37,21 +36,34 @@ set (SOURCES
|
||||
"${CMAKE_SOURCE_DIR}/Transports.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/TunnelEndpoint.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/TunnelPool.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/UPnP.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/aes.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/base64.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/i2p.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/util.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SAM.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/ClientContext.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Datagram.cpp"
|
||||
)
|
||||
|
||||
set (DAEMON_SRC
|
||||
"${CMAKE_SOURCE_DIR}/BOB.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/ClientContext.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/Daemon.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/HTTPProxy.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/HTTPServer.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/I2PTunnel.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SAM.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/SOCKS.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/UPnP.cpp"
|
||||
"${CMAKE_SOURCE_DIR}/i2p.cpp"
|
||||
)
|
||||
|
||||
set (LIBRARY_SRC
|
||||
"${CMAKE_SOURCE_DIR}/api.cpp"
|
||||
)
|
||||
|
||||
file (GLOB HEADERS "${CMAKE_SOURCE_DIR}/*.h")
|
||||
|
||||
# MSVS grouping
|
||||
source_group ("Header Files" FILES ${HEADERS})
|
||||
source_group ("Source Files" FILES ${SOURCES})
|
||||
source_group ("Source Files" FILES ${COMMON_SRC} ${DAEMON_SRC} ${LIBRARY_SRC})
|
||||
|
||||
# Default build is Debug
|
||||
if (CMAKE_BUILD_TYPE STREQUAL "Release")
|
||||
@@ -61,7 +73,7 @@ else ()
|
||||
endif ()
|
||||
|
||||
# compiler flags customization (by vendor)
|
||||
add_definitions ( "-Wall -Wextra" )
|
||||
add_definitions ( "-Wall -Wextra -fPIC" )
|
||||
|
||||
# check for c++11 support
|
||||
include(CheckCXXCompilerFlag)
|
||||
@@ -80,7 +92,6 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
add_definitions( "-D_FORTIFY_SOURCE=2" )
|
||||
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wformat -Wformat-security -Werror=format-security" )
|
||||
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector --param ssp-buffer-size=4" )
|
||||
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIE -pie" )
|
||||
endif ()
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
# more tweaks
|
||||
@@ -88,13 +99,15 @@ endif ()
|
||||
|
||||
# compiler flags customization (by system)
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
list (APPEND SOURCES "../DaemonLinux.cpp")
|
||||
list (APPEND DAEMON_SRC "${CMAKE_SOURCE_DIR}/DaemonLinux.cpp")
|
||||
elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
|
||||
list (APPEND SOURCES "../DaemonLinux.cpp")
|
||||
list (APPEND DAEMON_SRC "${CMAKE_SOURCE_DIR}/DaemonLinux.cpp")
|
||||
# "'sleep_for' is not a member of 'std::this_thread'" in gcc 4.7/4.8
|
||||
add_definitions( "-D_GLIBCXX_USE_NANOSLEEP=1" )
|
||||
elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
|
||||
list (APPEND DAEMON_SRC "${CMAKE_SOURCE_DIR}/DaemonLinux.cpp")
|
||||
elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||
list (APPEND SOURCES "../DaemonWin32.cpp")
|
||||
list (APPEND DAEMON_SRC "${CMAKE_SOURCE_DIR}/DaemonWin32.cpp")
|
||||
endif ()
|
||||
|
||||
if (WITH_AESNI)
|
||||
@@ -115,7 +128,7 @@ if(NOT DEFINED CRYPTO++_INCLUDE_DIR)
|
||||
endif()
|
||||
|
||||
# load includes
|
||||
include_directories( ${Boost_INCLUDE_DIRS} ${CRYPTO++_INCLUDE_DIR})
|
||||
include_directories( ${Boost_INCLUDE_DIRS} ${CRYPTO++_INCLUDE_DIR} "${CMAKE_SOURCE_DIR}/..")
|
||||
|
||||
# show summary
|
||||
message(STATUS "---------------------------------------")
|
||||
@@ -127,14 +140,33 @@ message(STATUS "Install prefix: : ${CMAKE_INSTALL_PREFIX}")
|
||||
message(STATUS "Options:")
|
||||
message(STATUS " AESNI : ${WITH_AESNI}")
|
||||
message(STATUS " HARDENING : ${WITH_HARDENING}")
|
||||
message(STATUS " LIBRARY : ${WITH_LIBRARY}")
|
||||
message(STATUS " BINARY : ${WITH_BINARY}")
|
||||
message(STATUS " STATIC BUILD : ${WITH_STATIC}")
|
||||
message(STATUS "---------------------------------------")
|
||||
|
||||
add_executable ( ${PROJECT_NAME} ${SOURCES} )
|
||||
#Handle paths nicely
|
||||
include(GNUInstallDirs)
|
||||
|
||||
if (WITH_HARDENING AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "-z relro -z now" )
|
||||
if (WITH_BINARY)
|
||||
add_executable ( "${PROJECT_NAME}-bin" ${COMMON_SRC} ${DAEMON_SRC})
|
||||
set_target_properties("${PROJECT_NAME}-bin" PROPERTIES OUTPUT_NAME "${PROJECT_NAME}")
|
||||
|
||||
if (WITH_HARDENING AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
set_target_properties("${PROJECT_NAME}-bin" PROPERTIES LINK_FLAGS "-z relro -z now" )
|
||||
endif ()
|
||||
|
||||
if (WITH_STATIC)
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
set_target_properties("${PROJECT_NAME}-bin" PROPERTIES LINK_FLAGS "-static" )
|
||||
endif ()
|
||||
|
||||
target_link_libraries( "${PROJECT_NAME}-bin" ${Boost_LIBRARIES} ${CRYPTO++_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} )
|
||||
|
||||
install(TARGETS "${PROJECT_NAME}-bin" RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} )
|
||||
endif ()
|
||||
|
||||
target_link_libraries( ${PROJECT_NAME} ${Boost_LIBRARIES} ${CRYPTO++_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} )
|
||||
|
||||
install(TARGETS i2pd RUNTIME DESTINATION "bin")
|
||||
if (WITH_LIBRARY)
|
||||
add_library(${PROJECT_NAME} SHARED ${COMMON_SRC} ${LIBRARY_SRC})
|
||||
install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} )
|
||||
endif ()
|
||||
|
||||
@@ -115,7 +115,7 @@ am_i2p_OBJECTS = AddressBook.$(OBJEXT) CryptoConst.$(OBJEXT) \
|
||||
TunnelGateway.$(OBJEXT) TunnelPool.$(OBJEXT) UPnP.$(OBJEXT) \
|
||||
aes.$(OBJEXT) base64.$(OBJEXT) i2p.$(OBJEXT) util.$(OBJEXT) \
|
||||
SAM.$(OBJEXT) Destination.$(OBJEXT) ClientContext.$(OBJEXT) \
|
||||
Datagram.$(OBJEXT) SSUSession.$(OBJEXT)
|
||||
Datagram.$(OBJEXT) SSUSession.$(OBJEXT) BOB.$(OBJEXT)
|
||||
i2p_OBJECTS = $(am_i2p_OBJECTS)
|
||||
i2p_LDADD = $(LDADD)
|
||||
AM_V_P = $(am__v_P_@AM_V@)
|
||||
@@ -326,7 +326,7 @@ i2p_SOURCES = AddressBook.cpp CryptoConst.cpp Daemon.cpp \
|
||||
Transports.cpp Tunnel.cpp TunnelEndpoint.cpp \
|
||||
TunnelGateway.cpp TunnelPool.cpp UPnP.cpp aes.cpp \
|
||||
base64.cpp i2p.cpp util.cpp SAM.cpp Destination.cpp \
|
||||
ClientContext.cpp DataFram.cpp SSUSession.cpp \
|
||||
ClientContext.cpp DataFram.cpp SSUSession.cpp BOB.cpp \
|
||||
\
|
||||
AddressBook.h CryptoConst.h Daemon.h ElGamal.h \
|
||||
Garlic.h HTTPProxy.h HTTPServer.h I2NPProtocol.h \
|
||||
@@ -338,7 +338,7 @@ i2p_SOURCES = AddressBook.cpp CryptoConst.cpp Daemon.cpp \
|
||||
TunnelConfig.h TunnelEndpoint.h TunnelGateway.h \
|
||||
TunnelPool.h UPnP.h aes.h base64.h config.h hmac.h \
|
||||
util.h version.h Destination.h ClientContext.h \
|
||||
TransportSession.h Datagram.h SSUSession.h
|
||||
TransportSession.h Datagram.h SSUSession.h BOB.h
|
||||
|
||||
AM_LDFLAGS = @BOOST_DATE_TIME_LIB@ @BOOST_FILESYSTEM_LIB@ \
|
||||
@BOOST_PROGRAM_OPTIONS_LIB@ @BOOST_REGEX_LIB@ \
|
||||
@@ -486,6 +486,7 @@ distclean-compile:
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/i2p.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/util.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SAM.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BOB.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ClientContext.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Datagram.Po@am__quote@
|
||||
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SSUSession.Po@am__quote@
|
||||
|
||||
32
contrib/certificates/reseed/bugme_at_mail.i2p.crt
Normal file
32
contrib/certificates/reseed/bugme_at_mail.i2p.crt
Normal file
@@ -0,0 +1,32 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIFezCCA2OgAwIBAgIEUQYyQjANBgkqhkiG9w0BAQ0FADBuMQswCQYDVQQGEwJY
|
||||
WDELMAkGA1UECBMCWFgxCzAJBgNVBAcTAlhYMR4wHAYDVQQKExVJMlAgQW5vbnlt
|
||||
b3VzIE5ldHdvcmsxDDAKBgNVBAsTA0kyUDEXMBUGA1UEAwwOYnVnbWVAbWFpbC5p
|
||||
MnAwHhcNMTQxMTA2MDkxMTE0WhcNMjQxMTA1MDkxMTE0WjBuMQswCQYDVQQGEwJY
|
||||
WDELMAkGA1UECBMCWFgxCzAJBgNVBAcTAlhYMR4wHAYDVQQKExVJMlAgQW5vbnlt
|
||||
b3VzIE5ldHdvcmsxDDAKBgNVBAsTA0kyUDEXMBUGA1UEAwwOYnVnbWVAbWFpbC5p
|
||||
MnAwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCrThOH0eSDT0VnCSBC
|
||||
sqYmAydWH+O8eNttDXr2mSvZLhvAW+6/xHTkKhaWvkIvvS0Vh8hujMnD90Cgp4Fk
|
||||
TKCxMj9K527o5xIZwWW05OevbjlBwIpVLO1PjmsfsoD1nIX14eEzJSEoAulKsv7V
|
||||
jGUC/6hC11mmVvH9buQLSRv6sCjuAcMszmw3TAD+XYBIs+z57KuwYXtX3+OA543c
|
||||
l1/ZKLYkkwY8cwzZqWDVWqTKP5TfVae58t40HhJk3bOsr21FZsaOjlmao3GO+d/3
|
||||
exKuUGJRcolSqskL3sZ1ovFqko81obvvx0upI0YA0iMr/NRGl3VPuf/LJvRppYGc
|
||||
LsJHgy9TIgtHvaXRi5Nt4CbKl9sZh/7WkkTTI5YGvevu00btlabAN+DSAZZqdsB3
|
||||
wY8HhM1MHiA9SWsqwU65TwErcRrjNna2FiDHEu0xk5+/iAGl6CSKHZBmNcYKXSv8
|
||||
cwShB0jjmciK0a05nC638RPgj0fng7KRrSglyzfjXRrljmZ40LSBL/GGMZMWpOM7
|
||||
mEsBH5UZJ/2BEmjc9X9257zBdx8BK8y1TXpAligpNBsERcTw1WP1PJ35einZvlXW
|
||||
qI3GwMf0sl26sn+evcK0gDl27jVDZ45MtNQEq64M4NV3Tn9zq0eg/39YvjVeqrI5
|
||||
l7sxmYqYGR6BuSncwdc4x+t6swIDAQABoyEwHzAdBgNVHQ4EFgQU/REZ7NMbVZHr
|
||||
Xkao6Q8Ccqv2kAMwDQYJKoZIhvcNAQENBQADggIBACc2YjLVNbl1kJUdg2klCLJt
|
||||
5LjNTiIZa2Cha5GStlC/lyoRRge6+q/y9TN3tTptlzLPS9pI9EE1GfIQaE+HAk+e
|
||||
/bC3KUOAHgVuETvsNAbfpaVsPCdWpFuXmp/4b9iDN7qZy4afTKUPA/Ir/cLfNp14
|
||||
JULfP4z2yFOsCQZ5viNFAs1u99FrwobV2LBzUSIJQewsksuOwj96zIyau0Y629oJ
|
||||
k+og88Tifd9EH3MVZNGhdpojQDDdwHQSITnCDgfRP5yER1WIA4jg6l+mM90QkvLY
|
||||
5NjWTna5kJ3X6UizvgCk365yzT2sbN3R9UGXfCJa9GBcnnviJtJF3+/gC0abwY2f
|
||||
NtVYp32Xky45NY/NdRhDg0bjHP3psxmX+Sc0M9NuQcDQ+fUR+CzM0IGeiszkzXOs
|
||||
RG+bOou2cZ81G4oxWdAALHIRrn7VvLGlkFMxiIZyhYcTGQZzsTPT6n18dY99+DAV
|
||||
yQWZfIRdm8DOnt0G+cwfeohc/9ZwDmj4jJAAi0aeTXdY6NEGIVydk6MAycEhg2Hx
|
||||
9EV96kRwZNIW0AGY8CozECFL3Eyo2ClQVV4Q35SsBibsitDjM03usc2DJ/qjynXA
|
||||
C8HoOSWgbddiBvqZueqK8GdhykOy3J3ysr+MNN/lbG48LqkQr1OWxev9rGGQ6RJT
|
||||
wpBgPyAFAwouPy1whmnx
|
||||
-----END CERTIFICATE-----
|
||||
25
contrib/certificates/ssl/ieb9oopo.mooo.com2.crt
Normal file
25
contrib/certificates/ssl/ieb9oopo.mooo.com2.crt
Normal file
@@ -0,0 +1,25 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIESzCCAzOgAwIBAgIJAKII1waVnWddMA0GCSqGSIb3DQEBCwUAMIG7MQswCQYD
|
||||
VQQGEwJERTEaMBgGA1UECAwRaWViOW9vcG8ubW9vby5jb20xGjAYBgNVBAcMEWll
|
||||
Yjlvb3BvLm1vb28uY29tMRowGAYDVQQKDBFpZWI5b29wby5tb29vLmNvbTEaMBgG
|
||||
A1UECwwRaWViOW9vcG8ubW9vby5jb20xGjAYBgNVBAMMEWllYjlvb3BvLm1vb28u
|
||||
Y29tMSAwHgYJKoZIhvcNAQkBFhFpZWI5b29wby5tb29vLmNvbTAeFw0xNDExMjIx
|
||||
MzQzNThaFw0yMDA1MTQxMzQzNThaMIG7MQswCQYDVQQGEwJERTEaMBgGA1UECAwR
|
||||
aWViOW9vcG8ubW9vby5jb20xGjAYBgNVBAcMEWllYjlvb3BvLm1vb28uY29tMRow
|
||||
GAYDVQQKDBFpZWI5b29wby5tb29vLmNvbTEaMBgGA1UECwwRaWViOW9vcG8ubW9v
|
||||
by5jb20xGjAYBgNVBAMMEWllYjlvb3BvLm1vb28uY29tMSAwHgYJKoZIhvcNAQkB
|
||||
FhFpZWI5b29wby5tb29vLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
|
||||
ggEBAMhcnkSifOMw5bd66UlvYVsc42H22Nuy64qhtJHtggofrwBooF38kRCBVFL8
|
||||
9Xjzr0xsSshvO6p7E+CEUtA8v55l5vNbUTAvGP9WmzeZyZuCFg9Heo3orNMbIK7m
|
||||
ppwKhwh6tFEIEpUTz/+xF5NRt0+CqcS4aNHuH3JPwNugfTBuSa86GeSaqL7K4eEZ
|
||||
bZXqQ16Onvi0yyMqRJDp/ijRFxr2eKGPWb55kuRSET9PxVhlgRKULZkr39Dh9q1c
|
||||
wb9lAMLMRZIzPVnyvC9jWkIqSDl5bkAAto0n1Jkw92rRp6EVKgSLA/4vl9wTb6xf
|
||||
WfT5cs7pykAE0WXBr9TqpS3okncCAwEAAaNQME4wHQYDVR0OBBYEFGeEOHhWiKwZ
|
||||
TGbc7uuK3DD7YjYZMB8GA1UdIwQYMBaAFGeEOHhWiKwZTGbc7uuK3DD7YjYZMAwG
|
||||
A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAAzRA/0OpJtCO4kQkTn/hux9
|
||||
dRi9T6B54Xav5jG53iAPLTeMxsaLkvweh2pZ3kvEUrQhvW0JF8QBrHTsgxzb4Wd6
|
||||
FNDHSgJbZv3uCjFtWeuUh+GTG1k9uwgNIEnx7J9Vp0JCi4ezi/HMNI7c+LjinM9f
|
||||
hrAzclkeRPLYg645DkxckLyDUbrc9v1qWFoTpezXSBPO7n3Wk4sCytdoA1FkTdXh
|
||||
RF4BWCl/3uOxcrn0TqoC9vCh8RcxnllOiOO5j4+PQ1Z6NkQ/5oRCK/jjaWc3Lr6/
|
||||
FicOZJe29BVnrPGynqe0Ky1o+kTdXFflKowfr7g8dwn8k9YavjtGbl1ZSHeuMF8=
|
||||
-----END CERTIFICATE-----
|
||||
24
contrib/certificates/ssl/link.mx24.eu.crt
Normal file
24
contrib/certificates/ssl/link.mx24.eu.crt
Normal file
@@ -0,0 +1,24 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEDzCCAvegAwIBAgIJAMsPNG1k0yV4MA0GCSqGSIb3DQEBCwUAMIGdMQswCQYD
|
||||
VQQGEwJERTEVMBMGA1UECAwMbGluay5teDI0LmV1MRUwEwYDVQQHDAxsaW5rLm14
|
||||
MjQuZXUxFTATBgNVBAoMDGxpbmsubXgyNC5ldTEVMBMGA1UECwwMbGluay5teDI0
|
||||
LmV1MRUwEwYDVQQDDAxsaW5rLm14MjQuZXUxGzAZBgkqhkiG9w0BCQEWDGxpbmsu
|
||||
bXgyNC5ldTAeFw0xNDExMTkxOTE4NTRaFw0yMDA1MTExOTE4NTRaMIGdMQswCQYD
|
||||
VQQGEwJERTEVMBMGA1UECAwMbGluay5teDI0LmV1MRUwEwYDVQQHDAxsaW5rLm14
|
||||
MjQuZXUxFTATBgNVBAoMDGxpbmsubXgyNC5ldTEVMBMGA1UECwwMbGluay5teDI0
|
||||
LmV1MRUwEwYDVQQDDAxsaW5rLm14MjQuZXUxGzAZBgkqhkiG9w0BCQEWDGxpbmsu
|
||||
bXgyNC5ldTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL8modDBRkyh
|
||||
SHSm92pTfguO3F6n5ocsBJ4vaVoosYq3ILCsapjqmynMHZUef6gEB7+Gn5cKXsH2
|
||||
JaKOeb8DHrOFCaxfj187x1QfZj1UNMQblx2T9q4th12tqp+k4JuLwgemr+2uAUpM
|
||||
xx/uHRJXD0hf67+fHQFYNVfa+WvT46xlKGsWDQ0LBsA/z4YGnyeaV4PrS5nj3euA
|
||||
IbdfDj7rJea3bfhSqYA1ZH1cquKlsXOOYO5cIcXsa5dxDWX51QS+i7+ocph+JN1X
|
||||
dRh6ZirE9OXZVXwXXVRnJSYjgBlP/DQBdE7YkE1R3LyCVZsgxJaaLV/ujijOIK61
|
||||
SqEhHvFNRe0CAwEAAaNQME4wHQYDVR0OBBYEFB6XRz6VZlrAE+3xL6AyKrkq+y2X
|
||||
MB8GA1UdIwQYMBaAFB6XRz6VZlrAE+3xL6AyKrkq+y2XMAwGA1UdEwQFMAMBAf8w
|
||||
DQYJKoZIhvcNAQELBQADggEBADhxBA5GHisDVf5a+1hIi7FBGBjJJLqzlaKh+bFB
|
||||
gTCYfk3F4wYzndr1HpdCZSSYDtY3mXFNMWQCpwvwvy1DM+9AMRY68wKNXHa/WypW
|
||||
zQSqTfEH8cdaIXUALB7pdWFVr3rx0f7/8I0Gj/ByUbJ94rzd22vduX5riY0Rag6B
|
||||
dPtW0M9bJrC1AIjexzDcStupj9v/ceGYZQYC4zb2tZ7Ek/6q+vei8TxWZjku7Dl4
|
||||
YRPXXufyB24uQ1hJVy2fSyIJ63tIRJoEFLBNaKDOB53i10xLWBcsJpXKY57AOQMn
|
||||
flqW4HG8uGJ/o1WjhiOB9eI7T9toy08zNzt+kSI/blFIoek=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,41 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290
|
||||
IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB
|
||||
IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA
|
||||
Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO
|
||||
BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi
|
||||
MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ
|
||||
ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC
|
||||
CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ
|
||||
8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6
|
||||
zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y
|
||||
fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7
|
||||
w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc
|
||||
G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k
|
||||
epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q
|
||||
laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ
|
||||
QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU
|
||||
fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826
|
||||
YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w
|
||||
ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY
|
||||
gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe
|
||||
MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0
|
||||
IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy
|
||||
dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw
|
||||
czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0
|
||||
dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl
|
||||
aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC
|
||||
AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg
|
||||
b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB
|
||||
ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc
|
||||
nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg
|
||||
18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c
|
||||
gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl
|
||||
Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY
|
||||
sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T
|
||||
SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF
|
||||
CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum
|
||||
GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk
|
||||
zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW
|
||||
omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD
|
||||
-----END CERTIFICATE-----
|
||||
34
filelist.mk
34
filelist.mk
@@ -1,20 +1,24 @@
|
||||
COMMON_SRC = \
|
||||
AddressBook.cpp CryptoConst.cpp Datagram.cpp Garlic.cpp I2NPProtocol.cpp \
|
||||
LeaseSet.cpp Log.cpp NTCPSession.cpp NetDb.cpp Reseed.cpp RouterContext.cpp \
|
||||
RouterInfo.cpp SSU.cpp SSUSession.cpp SSUData.cpp Streaming.cpp Identity.cpp \
|
||||
TransitTunnel.cpp Transports.cpp Tunnel.cpp TunnelEndpoint.cpp TunnelPool.cpp \
|
||||
TunnelGateway.cpp Destination.cpp util.cpp aes.cpp base64.cpp
|
||||
|
||||
|
||||
CPP_FILES := CryptoConst.cpp base64.cpp NTCPSession.cpp RouterInfo.cpp Transports.cpp \
|
||||
RouterContext.cpp NetDb.cpp LeaseSet.cpp Tunnel.cpp TunnelEndpoint.cpp TunnelGateway.cpp \
|
||||
TransitTunnel.cpp I2NPProtocol.cpp Log.cpp Garlic.cpp HTTPServer.cpp Streaming.cpp \
|
||||
Destination.cpp Identity.cpp SSU.cpp SSUSession.cpp SSUData.cpp util.cpp Reseed.cpp \
|
||||
DaemonLinux.cpp SSUData.cpp aes.cpp SOCKS.cpp UPnP.cpp TunnelPool.cpp HTTPProxy.cpp \
|
||||
AddressBook.cpp Daemon.cpp I2PTunnel.cpp SAM.cpp ClientContext.cpp Datagram.cpp i2p.cpp
|
||||
ifeq ($(UNAME),Darwin)
|
||||
# This is needed on OS X for some reason I don't understand (yet).
|
||||
# Else will get linker error about unknown symbols. - torkel
|
||||
COMMON_SRC += \
|
||||
BOB.cpp ClientContext.cpp Daemon.cpp I2PTunnel.cpp SAM.cpp SOCKS.cpp \
|
||||
UPnP.cpp HTTPServer.cpp HTTPProxy.cpp i2p.cpp DaemonLinux.cpp
|
||||
endif
|
||||
|
||||
|
||||
H_FILES := CryptoConst.h base64.h NTCPSession.h RouterInfo.h Transports.h \
|
||||
RouterContext.h NetDb.h LeaseSet.h Tunnel.h TunnelEndpoint.h TunnelGateway.h \
|
||||
TransitTunnel.h I2NPProtocol.h Log.h Garlic.h HTTPServer.h Streaming.h Destination.h \
|
||||
Identity.h SSU.h SSUSession.h SSUData.h util.h Reseed.h DaemonLinux.h SSUData.h \
|
||||
aes.h SOCKS.h UPnP.h TunnelPool.h HTTPProxy.h AddressBook.h Daemon.h I2PTunnel.h \
|
||||
version.h Signature.h SAM.h ClientContext.h TransportSession.h Datagram.h
|
||||
|
||||
|
||||
OBJECTS = $(addprefix obj/, $(notdir $(CPP_FILES:.cpp=.o)))
|
||||
# also: Daemon{Linux,Win32}.cpp will be added later
|
||||
DAEMON_SRC = $(COMMON_SRC) \
|
||||
BOB.cpp ClientContext.cpp Daemon.cpp I2PTunnel.cpp SAM.cpp SOCKS.cpp UPnP.cpp \
|
||||
HTTPServer.cpp HTTPProxy.cpp i2p.cpp
|
||||
|
||||
LIB_SRC := $(COMMON_SRC) \
|
||||
api.cpp
|
||||
|
||||
1
i2p.cpp
1
i2p.cpp
@@ -1,6 +1,7 @@
|
||||
#include <thread>
|
||||
#include <stdlib.h>
|
||||
#include "Daemon.h"
|
||||
#include "Reseed.h"
|
||||
|
||||
int main( int argc, char* argv[] )
|
||||
{
|
||||
|
||||
44
util.cpp
44
util.cpp
@@ -211,6 +211,11 @@ namespace filesystem
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
boost::filesystem::path GetCertificatesDir()
|
||||
{
|
||||
return GetDataDir () / "certificates";
|
||||
}
|
||||
}
|
||||
|
||||
namespace http
|
||||
@@ -234,7 +239,7 @@ namespace http
|
||||
if (site)
|
||||
{
|
||||
// User-Agent is needed to get the server list routerInfo files.
|
||||
site << "GET " << u.path_ << " HTTP/1.0\r\nHost: " << u.host_
|
||||
site << "GET " << u.path_ << " HTTP/1.1\r\nHost: " << u.host_
|
||||
<< "\r\nAccept: */*\r\n" << "User-Agent: Wget/1.11.4\r\n" << "Connection: close\r\n\r\n";
|
||||
// read response
|
||||
std::string version, statusMessage;
|
||||
@@ -244,10 +249,25 @@ namespace http
|
||||
std::getline (site, statusMessage);
|
||||
if (status == 200) // OK
|
||||
{
|
||||
bool isChunked = false;
|
||||
std::string header;
|
||||
while (std::getline(site, header) && header != "\r"){}
|
||||
while (!site.eof () && header != "\r")
|
||||
{
|
||||
std::getline(site, header);
|
||||
auto colon = header.find (':');
|
||||
if (colon != std::string::npos)
|
||||
{
|
||||
std::string field = header.substr (0, colon);
|
||||
if (field == i2p::util::http::TRANSFER_ENCODING)
|
||||
isChunked = (header.find ("chunked", colon + 1) != std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream ss;
|
||||
ss << site.rdbuf();
|
||||
if (isChunked)
|
||||
MergeChunkedResponse (site, ss);
|
||||
else
|
||||
ss << site.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
else
|
||||
@@ -269,6 +289,24 @@ namespace http
|
||||
}
|
||||
}
|
||||
|
||||
void MergeChunkedResponse (std::istream& response, std::ostream& merged)
|
||||
{
|
||||
while (!response.eof ())
|
||||
{
|
||||
std::string hexLen;
|
||||
int len;
|
||||
std::getline (response, hexLen);
|
||||
std::istringstream iss (hexLen);
|
||||
iss >> std::hex >> len;
|
||||
if (!len) break;
|
||||
char * buf = new char[len];
|
||||
response.read (buf, len);
|
||||
merged.write (buf, len);
|
||||
delete[] buf;
|
||||
std::getline (response, hexLen); // read \r\n after chunk
|
||||
}
|
||||
}
|
||||
|
||||
int httpRequestViaI2pProxy(const std::string& address, std::string &content)
|
||||
{
|
||||
content = "";
|
||||
|
||||
9
util.h
9
util.h
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/filesystem/fstream.hpp>
|
||||
@@ -34,11 +35,19 @@ namespace util
|
||||
boost::filesystem::path GetConfigFile();
|
||||
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet,
|
||||
std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
|
||||
boost::filesystem::path GetCertificatesDir();
|
||||
}
|
||||
|
||||
namespace http
|
||||
{
|
||||
const char ETAG[] = "ETag";
|
||||
const char IF_NONE_MATCH[] = "If-None-Match";
|
||||
const char IF_MODIFIED_SINCE[] = "If-Modified-Since";
|
||||
const char LAST_MODIFIED[] = "Last-Modified";
|
||||
const char TRANSFER_ENCODING[] = "Transfer-Encoding";
|
||||
|
||||
std::string httpRequest(const std::string& address);
|
||||
void MergeChunkedResponse (std::istream& response, std::ostream& merged);
|
||||
int httpRequestViaI2pProxy(const std::string& address, std::string &content); // return http code
|
||||
|
||||
struct url {
|
||||
|
||||
Reference in New Issue
Block a user