AddressBook.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. #include <string.h>
  2. #include <inttypes.h>
  3. #include <string>
  4. #include <map>
  5. #include <fstream>
  6. #include <chrono>
  7. #include <condition_variable>
  8. #include <openssl/rand.h>
  9. #include <boost/algorithm/string.hpp>
  10. #include <boost/filesystem.hpp>
  11. #include "Base.h"
  12. #include "util.h"
  13. #include "Identity.h"
  14. #include "FS.h"
  15. #include "Log.h"
  16. #include "HTTP.h"
  17. #include "NetDb.hpp"
  18. #include "ClientContext.h"
  19. #include "AddressBook.h"
  20. #include "Config.h"
  21. namespace i2p
  22. {
  23. namespace client
  24. {
  25. // TODO: this is actually proxy class
  26. class AddressBookFilesystemStorage: public AddressBookStorage
  27. {
  28. private:
  29. i2p::fs::HashedStorage storage;
  30. std::string etagsPath, indexPath, localPath;
  31. public:
  32. AddressBookFilesystemStorage (): storage("addressbook", "b", "", "b32")
  33. {
  34. i2p::config::GetOption("persist.addressbook", m_IsPersist);
  35. }
  36. std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) const;
  37. void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address);
  38. void RemoveAddress (const i2p::data::IdentHash& ident);
  39. bool Init ();
  40. int Load (std::map<std::string, std::shared_ptr<Address> > & addresses);
  41. int LoadLocal (std::map<std::string, std::shared_ptr<Address> >& addresses);
  42. int Save (const std::map<std::string, std::shared_ptr<Address> >& addresses);
  43. void SaveEtag (const i2p::data::IdentHash& subsciption, const std::string& etag, const std::string& lastModified);
  44. bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified);
  45. void ResetEtags ();
  46. private:
  47. int LoadFromFile (const std::string& filename, std::map<std::string, std::shared_ptr<Address> >& addresses); // returns -1 if can't open file, otherwise number of records
  48. private:
  49. bool m_IsPersist;
  50. };
  51. bool AddressBookFilesystemStorage::Init()
  52. {
  53. storage.SetPlace(i2p::fs::GetDataDir());
  54. // init storage
  55. if (storage.Init(i2p::data::GetBase32SubstitutionTable(), 32))
  56. {
  57. // init ETags
  58. etagsPath = i2p::fs::StorageRootPath (storage, "etags");
  59. if (!i2p::fs::Exists (etagsPath))
  60. i2p::fs::CreateDirectory (etagsPath);
  61. // init address files
  62. indexPath = i2p::fs::StorageRootPath (storage, "addresses.csv");
  63. localPath = i2p::fs::StorageRootPath (storage, "local.csv");
  64. return true;
  65. }
  66. return false;
  67. }
  68. std::shared_ptr<const i2p::data::IdentityEx> AddressBookFilesystemStorage::GetAddress (const i2p::data::IdentHash& ident) const
  69. {
  70. if (!m_IsPersist)
  71. {
  72. LogPrint(eLogDebug, "Addressbook: Persistence is disabled");
  73. return nullptr;
  74. }
  75. std::string filename = storage.Path(ident.ToBase32());
  76. std::ifstream f(filename, std::ifstream::binary);
  77. if (!f.is_open ()) {
  78. LogPrint(eLogDebug, "Addressbook: Requested, but not found: ", filename);
  79. return nullptr;
  80. }
  81. f.seekg (0,std::ios::end);
  82. size_t len = f.tellg ();
  83. if (len < i2p::data::DEFAULT_IDENTITY_SIZE) {
  84. LogPrint (eLogError, "Addressbook: File ", filename, " is too short: ", len);
  85. return nullptr;
  86. }
  87. f.seekg(0, std::ios::beg);
  88. uint8_t * buf = new uint8_t[len];
  89. f.read((char *)buf, len);
  90. auto address = std::make_shared<i2p::data::IdentityEx>(buf, len);
  91. delete[] buf;
  92. return address;
  93. }
  94. void AddressBookFilesystemStorage::AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address)
  95. {
  96. if (!m_IsPersist) return;
  97. std::string path = storage.Path( address->GetIdentHash().ToBase32() );
  98. std::ofstream f (path, std::ofstream::binary | std::ofstream::out);
  99. if (!f.is_open ()) {
  100. LogPrint (eLogError, "Addressbook: can't open file ", path);
  101. return;
  102. }
  103. size_t len = address->GetFullLen ();
  104. uint8_t * buf = new uint8_t[len];
  105. address->ToBuffer (buf, len);
  106. f.write ((char *)buf, len);
  107. delete[] buf;
  108. }
  109. void AddressBookFilesystemStorage::RemoveAddress (const i2p::data::IdentHash& ident)
  110. {
  111. if (!m_IsPersist) return;
  112. storage.Remove( ident.ToBase32() );
  113. }
  114. int AddressBookFilesystemStorage::LoadFromFile (const std::string& filename, std::map<std::string, std::shared_ptr<Address> >& addresses)
  115. {
  116. int num = 0;
  117. std::ifstream f (filename, std::ifstream::in); // in text mode
  118. if (!f) return -1;
  119. addresses.clear ();
  120. while (!f.eof ())
  121. {
  122. std::string s;
  123. getline(f, s);
  124. if (!s.length()) continue; // skip empty line
  125. std::size_t pos = s.find(',');
  126. if (pos != std::string::npos)
  127. {
  128. std::string name = s.substr(0, pos++);
  129. std::string addr = s.substr(pos);
  130. addresses[name] = std::make_shared<Address>(addr);
  131. num++;
  132. }
  133. }
  134. return num;
  135. }
  136. int AddressBookFilesystemStorage::Load (std::map<std::string, std::shared_ptr<Address> >& addresses)
  137. {
  138. int num = LoadFromFile (indexPath, addresses);
  139. if (num < 0)
  140. {
  141. LogPrint(eLogWarning, "Addressbook: Can't open ", indexPath);
  142. return 0;
  143. }
  144. LogPrint(eLogInfo, "Addressbook: using index file ", indexPath);
  145. LogPrint (eLogInfo, "Addressbook: ", num, " addresses loaded from storage");
  146. return num;
  147. }
  148. int AddressBookFilesystemStorage::LoadLocal (std::map<std::string, std::shared_ptr<Address> >& addresses)
  149. {
  150. int num = LoadFromFile (localPath, addresses);
  151. if (num < 0) return 0;
  152. LogPrint (eLogInfo, "Addressbook: ", num, " local addresses loaded");
  153. return num;
  154. }
  155. int AddressBookFilesystemStorage::Save (const std::map<std::string, std::shared_ptr<Address> >& addresses)
  156. {
  157. if (addresses.empty()) {
  158. LogPrint(eLogWarning, "Addressbook: not saving empty addressbook");
  159. return 0;
  160. }
  161. int num = 0;
  162. std::ofstream f (indexPath, std::ofstream::out); // in text mode
  163. if (!f.is_open ()) {
  164. LogPrint (eLogWarning, "Addressbook: Can't open ", indexPath);
  165. return 0;
  166. }
  167. for (const auto& it: addresses)
  168. {
  169. f << it.first << ",";
  170. if (it.second->IsIdentHash ())
  171. f << it.second->identHash.ToBase32 ();
  172. else
  173. f << it.second->blindedPublicKey->ToB33 ();
  174. f << std::endl;
  175. num++;
  176. }
  177. LogPrint (eLogInfo, "Addressbook: ", num, " addresses saved");
  178. return num;
  179. }
  180. void AddressBookFilesystemStorage::SaveEtag (const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified)
  181. {
  182. std::string fname = etagsPath + i2p::fs::dirSep + subscription.ToBase32 () + ".txt";
  183. std::ofstream f (fname, std::ofstream::out | std::ofstream::trunc);
  184. if (f)
  185. {
  186. f << etag << std::endl;
  187. f<< lastModified << std::endl;
  188. }
  189. }
  190. bool AddressBookFilesystemStorage::GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified)
  191. {
  192. std::string fname = etagsPath + i2p::fs::dirSep + subscription.ToBase32 () + ".txt";
  193. std::ifstream f (fname, std::ofstream::in);
  194. if (!f || f.eof ()) return false;
  195. std::getline (f, etag);
  196. if (f.eof ()) return false;
  197. std::getline (f, lastModified);
  198. return true;
  199. }
  200. void AddressBookFilesystemStorage::ResetEtags ()
  201. {
  202. LogPrint (eLogError, "Addressbook: resetting eTags");
  203. for (boost::filesystem::directory_iterator it (etagsPath); it != boost::filesystem::directory_iterator (); ++it)
  204. {
  205. if (!boost::filesystem::is_regular_file (it->status ()))
  206. continue;
  207. boost::filesystem::remove (it->path ());
  208. }
  209. }
  210. //---------------------------------------------------------------------
  211. Address::Address (const std::string& b32)
  212. {
  213. if (b32.length () <= B33_ADDRESS_THRESHOLD)
  214. {
  215. addressType = eAddressIndentHash;
  216. identHash.FromBase32 (b32);
  217. }
  218. else
  219. {
  220. addressType = eAddressBlindedPublicKey;
  221. blindedPublicKey = std::make_shared<i2p::data::BlindedPublicKey>(b32);
  222. }
  223. }
  224. Address::Address (const i2p::data::IdentHash& hash)
  225. {
  226. addressType = eAddressIndentHash;
  227. identHash = hash;
  228. }
  229. AddressBook::AddressBook (): m_Storage(nullptr), m_IsLoaded (false), m_IsDownloading (false),
  230. m_NumRetries (0), m_DefaultSubscription (nullptr), m_SubscriptionsUpdateTimer (nullptr)
  231. {
  232. }
  233. AddressBook::~AddressBook ()
  234. {
  235. Stop ();
  236. }
  237. void AddressBook::Start ()
  238. {
  239. if (!m_Storage)
  240. m_Storage = new AddressBookFilesystemStorage;
  241. m_Storage->Init();
  242. LoadHosts (); /* try storage, then hosts.txt, then download */
  243. StartSubscriptions ();
  244. StartLookups ();
  245. }
  246. void AddressBook::StartResolvers ()
  247. {
  248. LoadLocal ();
  249. }
  250. void AddressBook::Stop ()
  251. {
  252. StopLookups ();
  253. StopSubscriptions ();
  254. if (m_SubscriptionsUpdateTimer)
  255. {
  256. delete m_SubscriptionsUpdateTimer;
  257. m_SubscriptionsUpdateTimer = nullptr;
  258. }
  259. if (m_IsDownloading)
  260. {
  261. LogPrint (eLogInfo, "Addressbook: subscriptions are downloading, abort");
  262. for (int i = 0; i < 30; i++)
  263. {
  264. if (!m_IsDownloading)
  265. {
  266. LogPrint (eLogInfo, "Addressbook: subscriptions download complete");
  267. break;
  268. }
  269. std::this_thread::sleep_for (std::chrono::seconds (1)); // wait for 1 seconds
  270. }
  271. LogPrint (eLogError, "Addressbook: subscription download timeout");
  272. m_IsDownloading = false;
  273. }
  274. if (m_Storage)
  275. {
  276. m_Storage->Save (m_Addresses);
  277. delete m_Storage;
  278. m_Storage = nullptr;
  279. }
  280. m_DefaultSubscription = nullptr;
  281. m_Subscriptions.clear ();
  282. }
  283. std::shared_ptr<const Address> AddressBook::GetAddress (const std::string& address)
  284. {
  285. auto pos = address.find(".b32.i2p");
  286. if (pos != std::string::npos)
  287. return std::make_shared<const Address>(address.substr (0, pos));
  288. else
  289. {
  290. pos = address.find (".i2p");
  291. if (pos != std::string::npos)
  292. {
  293. auto addr = FindAddress (address);
  294. if (!addr)
  295. LookupAddress (address); // TODO:
  296. return addr;
  297. }
  298. }
  299. // if not .b32 we assume full base64 address
  300. i2p::data::IdentityEx dest;
  301. if (!dest.FromBase64 (address))
  302. return nullptr;
  303. return std::make_shared<const Address>(dest.GetIdentHash ());
  304. }
  305. std::shared_ptr<const Address> AddressBook::FindAddress (const std::string& address)
  306. {
  307. auto it = m_Addresses.find (address);
  308. if (it != m_Addresses.end ())
  309. return it->second;
  310. return nullptr;
  311. }
  312. void AddressBook::InsertAddress (const std::string& address, const std::string& jump)
  313. {
  314. auto pos = jump.find(".b32.i2p");
  315. if (pos != std::string::npos)
  316. {
  317. m_Addresses[address] = std::make_shared<Address>(jump.substr (0, pos));
  318. LogPrint (eLogInfo, "Addressbook: added ", address," -> ", jump);
  319. }
  320. else
  321. {
  322. // assume base64
  323. auto ident = std::make_shared<i2p::data::IdentityEx>();
  324. if (ident->FromBase64 (jump))
  325. {
  326. m_Storage->AddAddress (ident);
  327. m_Addresses[address] = std::make_shared<Address>(ident->GetIdentHash ());
  328. LogPrint (eLogInfo, "Addressbook: added ", address," -> ", ToAddress(ident->GetIdentHash ()));
  329. }
  330. else
  331. LogPrint (eLogError, "Addressbook: malformed address ", jump);
  332. }
  333. }
  334. void AddressBook::InsertFullAddress (std::shared_ptr<const i2p::data::IdentityEx> address)
  335. {
  336. m_Storage->AddAddress (address);
  337. }
  338. std::shared_ptr<const i2p::data::IdentityEx> AddressBook::GetFullAddress (const std::string& address)
  339. {
  340. auto addr = GetAddress (address);
  341. if (!addr || !addr->IsIdentHash ()) return nullptr;
  342. return m_Storage->GetAddress (addr->identHash);
  343. }
  344. void AddressBook::LoadHosts ()
  345. {
  346. if (m_Storage->Load (m_Addresses) > 0)
  347. {
  348. m_IsLoaded = true;
  349. return;
  350. }
  351. // then try hosts.txt
  352. std::ifstream f (i2p::fs::DataDirPath("hosts.txt"), std::ifstream::in); // in text mode
  353. if (f.is_open ())
  354. {
  355. LoadHostsFromStream (f, false);
  356. m_IsLoaded = true;
  357. }
  358. // reset eTags, because we don’t know how old hosts.txt is or can't load addressbook
  359. m_Storage->ResetEtags ();
  360. }
  361. bool AddressBook::LoadHostsFromStream (std::istream& f, bool is_update)
  362. {
  363. std::unique_lock<std::mutex> l(m_AddressBookMutex);
  364. int numAddresses = 0;
  365. bool incomplete = false;
  366. std::string s;
  367. while (!f.eof ())
  368. {
  369. getline(f, s);
  370. if (!s.length() || s[0] == '#')
  371. continue; // skip empty or comment line
  372. size_t pos = s.find('=');
  373. if (pos != std::string::npos)
  374. {
  375. std::string name = s.substr(0, pos++);
  376. std::string addr = s.substr(pos);
  377. size_t pos = s.find('#');
  378. if (pos != std::string::npos)
  379. addr = addr.substr(pos); // remove comments
  380. auto ident = std::make_shared<i2p::data::IdentityEx> ();
  381. if (!ident->FromBase64(addr)) {
  382. LogPrint (eLogError, "Addressbook: malformed address ", addr, " for ", name);
  383. incomplete = f.eof ();
  384. continue;
  385. }
  386. numAddresses++;
  387. auto it = m_Addresses.find (name);
  388. if (it != m_Addresses.end ()) // already exists ?
  389. {
  390. if (it->second->IsIdentHash () && it->second->identHash != ident->GetIdentHash ()) // address changed?
  391. {
  392. it->second->identHash = ident->GetIdentHash ();
  393. m_Storage->AddAddress (ident);
  394. LogPrint (eLogInfo, "Addressbook: updated host: ", name);
  395. }
  396. }
  397. else
  398. {
  399. //m_Addresses.emplace (name, std::make_shared<Address>(ident->GetIdentHash ()));
  400. m_Addresses[name] = std::make_shared<Address>(ident->GetIdentHash ()); // for gcc 4.7
  401. m_Storage->AddAddress (ident);
  402. if (is_update)
  403. LogPrint (eLogInfo, "Addressbook: added new host: ", name);
  404. }
  405. }
  406. else
  407. incomplete = f.eof ();
  408. }
  409. LogPrint (eLogInfo, "Addressbook: ", numAddresses, " addresses processed");
  410. if (numAddresses > 0)
  411. {
  412. if (!incomplete) m_IsLoaded = true;
  413. m_Storage->Save (m_Addresses);
  414. }
  415. return !incomplete;
  416. }
  417. void AddressBook::LoadSubscriptions ()
  418. {
  419. if (!m_Subscriptions.size ())
  420. {
  421. std::ifstream f (i2p::fs::DataDirPath ("subscriptions.txt"), std::ifstream::in); // in text mode
  422. if (f.is_open ())
  423. {
  424. std::string s;
  425. while (!f.eof ())
  426. {
  427. getline(f, s);
  428. if (!s.length()) continue; // skip empty line
  429. m_Subscriptions.push_back (std::make_shared<AddressBookSubscription> (*this, s));
  430. }
  431. LogPrint (eLogInfo, "Addressbook: ", m_Subscriptions.size (), " subscriptions urls loaded");
  432. LogPrint (eLogWarning, "Addressbook: subscriptions.txt usage is deprecated, use config file instead");
  433. }
  434. else if (!i2p::config::IsDefault("addressbook.subscriptions"))
  435. {
  436. // using config file items
  437. std::string subscriptionURLs; i2p::config::GetOption("addressbook.subscriptions", subscriptionURLs);
  438. std::vector<std::string> subsList;
  439. boost::split(subsList, subscriptionURLs, boost::is_any_of(","), boost::token_compress_on);
  440. for (size_t i = 0; i < subsList.size (); i++)
  441. {
  442. m_Subscriptions.push_back (std::make_shared<AddressBookSubscription> (*this, subsList[i]));
  443. }
  444. LogPrint (eLogInfo, "Addressbook: ", m_Subscriptions.size (), " subscriptions urls loaded");
  445. }
  446. }
  447. else
  448. LogPrint (eLogError, "Addressbook: subscriptions already loaded");
  449. }
  450. void AddressBook::LoadLocal ()
  451. {
  452. std::map<std::string, std::shared_ptr<Address>> localAddresses;
  453. m_Storage->LoadLocal (localAddresses);
  454. for (const auto& it: localAddresses)
  455. {
  456. if (!it.second->IsIdentHash ()) continue; // skip blinded for now
  457. auto dot = it.first.find ('.');
  458. if (dot != std::string::npos)
  459. {
  460. auto domain = it.first.substr (dot + 1);
  461. auto it1 = m_Addresses.find (domain); // find domain in our addressbook
  462. if (it1 != m_Addresses.end () && it1->second->IsIdentHash ())
  463. {
  464. auto dest = context.FindLocalDestination (it1->second->identHash);
  465. if (dest)
  466. {
  467. // address is ours
  468. std::shared_ptr<AddressResolver> resolver;
  469. auto it2 = m_Resolvers.find (it1->second->identHash);
  470. if (it2 != m_Resolvers.end ())
  471. resolver = it2->second; // resolver exists
  472. else
  473. {
  474. // create new resolver
  475. resolver = std::make_shared<AddressResolver>(dest);
  476. m_Resolvers.insert (std::make_pair(it1->second->identHash, resolver));
  477. }
  478. resolver->AddAddress (it.first, it.second->identHash);
  479. }
  480. }
  481. }
  482. }
  483. }
  484. bool AddressBook::GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified)
  485. {
  486. if (m_Storage)
  487. return m_Storage->GetEtag (subscription, etag, lastModified);
  488. else
  489. return false;
  490. }
  491. void AddressBook::DownloadComplete (bool success, const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified)
  492. {
  493. m_IsDownloading = false;
  494. m_NumRetries++;
  495. int nextUpdateTimeout = m_NumRetries*CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT;
  496. if (m_NumRetries > CONTINIOUS_SUBSCRIPTION_MAX_NUM_RETRIES || nextUpdateTimeout > CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT)
  497. nextUpdateTimeout = CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT;
  498. if (success)
  499. {
  500. m_NumRetries = 0;
  501. if (m_DefaultSubscription) m_DefaultSubscription = nullptr;
  502. if (m_IsLoaded)
  503. nextUpdateTimeout = CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT;
  504. else
  505. m_IsLoaded = true;
  506. if (m_Storage) m_Storage->SaveEtag (subscription, etag, lastModified);
  507. }
  508. if (m_SubscriptionsUpdateTimer)
  509. {
  510. m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(nextUpdateTimeout));
  511. m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
  512. this, std::placeholders::_1));
  513. }
  514. }
  515. void AddressBook::StartSubscriptions ()
  516. {
  517. LoadSubscriptions ();
  518. if (m_IsLoaded && m_Subscriptions.empty ()) return;
  519. auto dest = i2p::client::context.GetSharedLocalDestination ();
  520. if (dest)
  521. {
  522. m_SubscriptionsUpdateTimer = new boost::asio::deadline_timer (dest->GetService ());
  523. m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT));
  524. m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
  525. this, std::placeholders::_1));
  526. }
  527. else
  528. LogPrint (eLogError, "Addressbook: can't start subscriptions: missing shared local destination");
  529. }
  530. void AddressBook::StopSubscriptions ()
  531. {
  532. if (m_SubscriptionsUpdateTimer)
  533. m_SubscriptionsUpdateTimer->cancel ();
  534. }
  535. void AddressBook::HandleSubscriptionsUpdateTimer (const boost::system::error_code& ecode)
  536. {
  537. if (ecode != boost::asio::error::operation_aborted)
  538. {
  539. auto dest = i2p::client::context.GetSharedLocalDestination ();
  540. if (!dest) {
  541. LogPrint(eLogWarning, "Addressbook: missing local destination, skip subscription update");
  542. return;
  543. }
  544. if (!m_IsDownloading && dest->IsReady ())
  545. {
  546. if (!m_IsLoaded)
  547. {
  548. // download it from default subscription
  549. LogPrint (eLogInfo, "Addressbook: trying to download it from default subscription.");
  550. std::string defaultSubURL; i2p::config::GetOption("addressbook.defaulturl", defaultSubURL);
  551. if (!m_DefaultSubscription)
  552. m_DefaultSubscription = std::make_shared<AddressBookSubscription>(*this, defaultSubURL);
  553. m_IsDownloading = true;
  554. std::thread load_hosts(std::bind (&AddressBookSubscription::CheckUpdates, m_DefaultSubscription));
  555. load_hosts.detach(); // TODO: use join
  556. }
  557. else if (!m_Subscriptions.empty ())
  558. {
  559. // pick random subscription
  560. auto ind = rand () % m_Subscriptions.size();
  561. m_IsDownloading = true;
  562. std::thread load_hosts(std::bind (&AddressBookSubscription::CheckUpdates, m_Subscriptions[ind]));
  563. load_hosts.detach(); // TODO: use join
  564. }
  565. }
  566. else
  567. {
  568. // try it again later
  569. m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(INITIAL_SUBSCRIPTION_RETRY_TIMEOUT));
  570. m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
  571. this, std::placeholders::_1));
  572. }
  573. }
  574. }
  575. void AddressBook::StartLookups ()
  576. {
  577. auto dest = i2p::client::context.GetSharedLocalDestination ();
  578. if (dest)
  579. {
  580. auto datagram = dest->GetDatagramDestination ();
  581. if (!datagram)
  582. datagram = dest->CreateDatagramDestination ();
  583. datagram->SetReceiver (std::bind (&AddressBook::HandleLookupResponse, this,
  584. std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5),
  585. ADDRESS_RESPONSE_DATAGRAM_PORT);
  586. }
  587. }
  588. void AddressBook::StopLookups ()
  589. {
  590. auto dest = i2p::client::context.GetSharedLocalDestination ();
  591. if (dest)
  592. {
  593. auto datagram = dest->GetDatagramDestination ();
  594. if (datagram) datagram->ResetReceiver (ADDRESS_RESPONSE_DATAGRAM_PORT);
  595. }
  596. }
  597. void AddressBook::LookupAddress (const std::string& address)
  598. {
  599. std::shared_ptr<const Address> addr;
  600. auto dot = address.find ('.');
  601. if (dot != std::string::npos)
  602. addr = FindAddress (address.substr (dot + 1));
  603. if (!addr || !addr->IsIdentHash ()) // TODO:
  604. {
  605. LogPrint (eLogError, "Addressbook: Can't find domain for ", address);
  606. return;
  607. }
  608. auto dest = i2p::client::context.GetSharedLocalDestination ();
  609. if (dest)
  610. {
  611. auto datagram = dest->GetDatagramDestination ();
  612. if (datagram)
  613. {
  614. uint32_t nonce;
  615. RAND_bytes ((uint8_t *)&nonce, 4);
  616. {
  617. std::unique_lock<std::mutex> l(m_LookupsMutex);
  618. m_Lookups[nonce] = address;
  619. }
  620. LogPrint (eLogDebug, "Addressbook: Lookup of ", address, " to ", addr->identHash.ToBase32 (), " nonce=", nonce);
  621. size_t len = address.length () + 9;
  622. uint8_t * buf = new uint8_t[len];
  623. memset (buf, 0, 4);
  624. htobe32buf (buf + 4, nonce);
  625. buf[8] = address.length ();
  626. memcpy (buf + 9, address.c_str (), address.length ());
  627. datagram->SendDatagramTo (buf, len, addr->identHash, ADDRESS_RESPONSE_DATAGRAM_PORT, ADDRESS_RESOLVER_DATAGRAM_PORT);
  628. delete[] buf;
  629. }
  630. }
  631. }
  632. void AddressBook::HandleLookupResponse (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
  633. {
  634. if (len < 44)
  635. {
  636. LogPrint (eLogError, "Addressbook: Lookup response is too short ", len);
  637. return;
  638. }
  639. uint32_t nonce = bufbe32toh (buf + 4);
  640. LogPrint (eLogDebug, "Addressbook: Lookup response received from ", from.GetIdentHash ().ToBase32 (), " nonce=", nonce);
  641. std::string address;
  642. {
  643. std::unique_lock<std::mutex> l(m_LookupsMutex);
  644. auto it = m_Lookups.find (nonce);
  645. if (it != m_Lookups.end ())
  646. {
  647. address = it->second;
  648. m_Lookups.erase (it);
  649. }
  650. }
  651. if (address.length () > 0)
  652. {
  653. // TODO: verify from
  654. i2p::data::IdentHash hash(buf + 8);
  655. if (!hash.IsZero ())
  656. m_Addresses[address] = std::make_shared<Address>(hash);
  657. else
  658. LogPrint (eLogInfo, "AddressBook: Lookup response: ", address, " not found");
  659. }
  660. }
  661. AddressBookSubscription::AddressBookSubscription (AddressBook& book, const std::string& link):
  662. m_Book (book), m_Link (link)
  663. {
  664. }
  665. void AddressBookSubscription::CheckUpdates ()
  666. {
  667. bool result = MakeRequest ();
  668. m_Book.DownloadComplete (result, m_Ident, m_Etag, m_LastModified);
  669. }
  670. bool AddressBookSubscription::MakeRequest ()
  671. {
  672. i2p::http::URL url;
  673. // must be run in separate thread
  674. LogPrint (eLogInfo, "Addressbook: Downloading hosts database from ", m_Link);
  675. if (!url.parse(m_Link))
  676. {
  677. LogPrint(eLogError, "Addressbook: failed to parse url: ", m_Link);
  678. return false;
  679. }
  680. auto addr = m_Book.GetAddress (url.host);
  681. if (!addr || !addr->IsIdentHash ())
  682. {
  683. LogPrint (eLogError, "Addressbook: Can't resolve ", url.host);
  684. return false;
  685. }
  686. else
  687. m_Ident = addr->identHash;
  688. /* this code block still needs some love */
  689. std::condition_variable newDataReceived;
  690. std::mutex newDataReceivedMutex;
  691. auto leaseSet = i2p::client::context.GetSharedLocalDestination ()->FindLeaseSet (m_Ident);
  692. if (!leaseSet)
  693. {
  694. std::unique_lock<std::mutex> l(newDataReceivedMutex);
  695. i2p::client::context.GetSharedLocalDestination ()->RequestDestination (m_Ident,
  696. [&newDataReceived, &leaseSet, &newDataReceivedMutex](std::shared_ptr<i2p::data::LeaseSet> ls)
  697. {
  698. leaseSet = ls;
  699. std::unique_lock<std::mutex> l1(newDataReceivedMutex);
  700. newDataReceived.notify_all ();
  701. });
  702. if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT)) == std::cv_status::timeout)
  703. {
  704. LogPrint (eLogError, "Addressbook: Subscription LeaseSet request timeout expired");
  705. i2p::client::context.GetSharedLocalDestination ()->CancelDestinationRequest (m_Ident, false); // don't notify, because we know it already
  706. return false;
  707. }
  708. }
  709. if (!leaseSet) {
  710. /* still no leaseset found */
  711. LogPrint (eLogError, "Addressbook: LeaseSet for address ", url.host, " not found");
  712. return false;
  713. }
  714. if (m_Etag.empty() && m_LastModified.empty()) {
  715. m_Book.GetEtag (m_Ident, m_Etag, m_LastModified);
  716. LogPrint (eLogDebug, "Addressbook: loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified);
  717. }
  718. /* save url parts for later use */
  719. std::string dest_host = url.host;
  720. int dest_port = url.port ? url.port : 80;
  721. /* create http request & send it */
  722. i2p::http::HTTPReq req;
  723. req.AddHeader("Host", dest_host);
  724. req.AddHeader("User-Agent", "Wget/1.11.4");
  725. req.AddHeader("X-Accept-Encoding", "x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0");
  726. req.AddHeader("Connection", "close");
  727. if (!m_Etag.empty())
  728. req.AddHeader("If-None-Match", m_Etag);
  729. if (!m_LastModified.empty())
  730. req.AddHeader("If-Modified-Since", m_LastModified);
  731. /* convert url to relative */
  732. url.schema = "";
  733. url.host = "";
  734. req.uri = url.to_string();
  735. auto stream = i2p::client::context.GetSharedLocalDestination ()->CreateStream (leaseSet, dest_port);
  736. std::string request = req.to_string();
  737. stream->Send ((const uint8_t *) request.data(), request.length());
  738. /* read response */
  739. std::string response;
  740. uint8_t recv_buf[4096];
  741. bool end = false;
  742. int numAttempts = 0;
  743. while (!end)
  744. {
  745. stream->AsyncReceive (boost::asio::buffer (recv_buf, 4096),
  746. [&](const boost::system::error_code& ecode, std::size_t bytes_transferred)
  747. {
  748. if (bytes_transferred)
  749. response.append ((char *)recv_buf, bytes_transferred);
  750. if (ecode == boost::asio::error::timed_out || !stream->IsOpen ())
  751. end = true;
  752. newDataReceived.notify_all ();
  753. },
  754. SUBSCRIPTION_REQUEST_TIMEOUT);
  755. std::unique_lock<std::mutex> l(newDataReceivedMutex);
  756. // wait 1 more second
  757. if (newDataReceived.wait_for (l, std::chrono::seconds (SUBSCRIPTION_REQUEST_TIMEOUT + 1)) == std::cv_status::timeout)
  758. {
  759. LogPrint (eLogError, "Addressbook: subscriptions request timeout expired");
  760. numAttempts++;
  761. if (numAttempts > 5) end = true;
  762. }
  763. }
  764. // process remaining buffer
  765. while (size_t len = stream->ReadSome (recv_buf, sizeof(recv_buf)))
  766. response.append ((char *)recv_buf, len);
  767. /* parse response */
  768. i2p::http::HTTPRes res;
  769. int res_head_len = res.parse(response);
  770. if (res_head_len < 0)
  771. {
  772. LogPrint(eLogError, "Addressbook: can't parse http response from ", dest_host);
  773. return false;
  774. }
  775. if (res_head_len == 0)
  776. {
  777. LogPrint(eLogError, "Addressbook: incomplete http response from ", dest_host, ", interrupted by timeout");
  778. return false;
  779. }
  780. /* assert: res_head_len > 0 */
  781. response.erase(0, res_head_len);
  782. if (res.code == 304)
  783. {
  784. LogPrint (eLogInfo, "Addressbook: no updates from ", dest_host, ", code 304");
  785. return false;
  786. }
  787. if (res.code != 200)
  788. {
  789. LogPrint (eLogWarning, "Adressbook: can't get updates from ", dest_host, ", response code ", res.code);
  790. return false;
  791. }
  792. int len = res.content_length();
  793. if (response.empty())
  794. {
  795. LogPrint(eLogError, "Addressbook: empty response from ", dest_host, ", expected ", len, " bytes");
  796. return false;
  797. }
  798. if (!res.is_gzipped () && len > 0 && len != (int) response.length())
  799. {
  800. LogPrint(eLogError, "Addressbook: response size mismatch, expected: ", len, ", got: ", response.length(), "bytes");
  801. return false;
  802. }
  803. /* assert: res.code == 200 */
  804. auto it = res.headers.find("ETag");
  805. if (it != res.headers.end()) m_Etag = it->second;
  806. it = res.headers.find("If-Modified-Since");
  807. if (it != res.headers.end()) m_LastModified = it->second;
  808. if (res.is_chunked())
  809. {
  810. std::stringstream in(response), out;
  811. i2p::http::MergeChunkedResponse (in, out);
  812. response = out.str();
  813. }
  814. else if (res.is_gzipped())
  815. {
  816. std::stringstream out;
  817. i2p::data::GzipInflator inflator;
  818. inflator.Inflate ((const uint8_t *) response.data(), response.length(), out);
  819. if (out.fail())
  820. {
  821. LogPrint(eLogError, "Addressbook: can't gunzip http response");
  822. return false;
  823. }
  824. response = out.str();
  825. }
  826. std::stringstream ss(response);
  827. LogPrint (eLogInfo, "Addressbook: got update from ", dest_host);
  828. m_Book.LoadHostsFromStream (ss, true);
  829. return true;
  830. }
  831. AddressResolver::AddressResolver (std::shared_ptr<ClientDestination> destination):
  832. m_LocalDestination (destination)
  833. {
  834. if (m_LocalDestination)
  835. {
  836. auto datagram = m_LocalDestination->GetDatagramDestination ();
  837. if (!datagram)
  838. datagram = m_LocalDestination->CreateDatagramDestination ();
  839. datagram->SetReceiver (std::bind (&AddressResolver::HandleRequest, this,
  840. std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5),
  841. ADDRESS_RESOLVER_DATAGRAM_PORT);
  842. }
  843. }
  844. AddressResolver::~AddressResolver ()
  845. {
  846. if (m_LocalDestination)
  847. {
  848. auto datagram = m_LocalDestination->GetDatagramDestination ();
  849. if (datagram)
  850. datagram->ResetReceiver (ADDRESS_RESOLVER_DATAGRAM_PORT);
  851. }
  852. }
  853. void AddressResolver::HandleRequest (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len)
  854. {
  855. if (len < 9 || len < buf[8] + 9U)
  856. {
  857. LogPrint (eLogError, "Addressbook: Address request is too short ", len);
  858. return;
  859. }
  860. // read requested address
  861. uint8_t l = buf[8];
  862. char address[255];
  863. memcpy (address, buf + 9, l);
  864. address[l] = 0;
  865. LogPrint (eLogDebug, "Addressbook: Address request ", address);
  866. // send response
  867. uint8_t response[44];
  868. memset (response, 0, 4); // reserved
  869. memcpy (response + 4, buf + 4, 4); // nonce
  870. auto it = m_LocalAddresses.find (address); // address lookup
  871. if (it != m_LocalAddresses.end ())
  872. memcpy (response + 8, it->second, 32); // ident
  873. else
  874. memset (response + 8, 0, 32); // not found
  875. memset (response + 40, 0, 4); // set expiration time to zero
  876. m_LocalDestination->GetDatagramDestination ()->SendDatagramTo (response, 44, from.GetIdentHash(), toPort, fromPort);
  877. }
  878. void AddressResolver::AddAddress (const std::string& name, const i2p::data::IdentHash& ident)
  879. {
  880. m_LocalAddresses[name] = ident;
  881. }
  882. }
  883. }