ClientContext.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. #include <fstream>
  2. #include <iostream>
  3. #include <boost/property_tree/ptree.hpp>
  4. #include <boost/property_tree/ini_parser.hpp>
  5. #include "Config.h"
  6. #include "FS.h"
  7. #include "Log.h"
  8. #include "Identity.h"
  9. #include "util.h"
  10. #include "ClientContext.h"
  11. #include "SOCKS.h"
  12. #include "WebSocks.h"
  13. #include "MatchedDestination.h"
  14. namespace i2p
  15. {
  16. namespace client
  17. {
  18. ClientContext context;
  19. ClientContext::ClientContext (): m_SharedLocalDestination (nullptr),
  20. m_HttpProxy (nullptr), m_SocksProxy (nullptr), m_SamBridge (nullptr),
  21. m_BOBCommandChannel (nullptr), m_I2CPServer (nullptr)
  22. {
  23. }
  24. ClientContext::~ClientContext ()
  25. {
  26. delete m_HttpProxy;
  27. delete m_SocksProxy;
  28. delete m_SamBridge;
  29. delete m_BOBCommandChannel;
  30. delete m_I2CPServer;
  31. }
  32. void ClientContext::Start ()
  33. {
  34. // shared local destination
  35. if (!m_SharedLocalDestination)
  36. CreateNewSharedLocalDestination ();
  37. // addressbook
  38. m_AddressBook.Start ();
  39. // HTTP proxy
  40. ReadHttpProxy ();
  41. // SOCKS proxy
  42. ReadSocksProxy ();
  43. // I2P tunnels
  44. ReadTunnels ();
  45. // SAM
  46. bool sam; i2p::config::GetOption("sam.enabled", sam);
  47. if (sam) {
  48. std::string samAddr; i2p::config::GetOption("sam.address", samAddr);
  49. uint16_t samPort; i2p::config::GetOption("sam.port", samPort);
  50. LogPrint(eLogInfo, "Clients: starting SAM bridge at ", samAddr, ":", samPort);
  51. try {
  52. m_SamBridge = new SAMBridge (samAddr, samPort);
  53. m_SamBridge->Start ();
  54. } catch (std::exception& e) {
  55. LogPrint(eLogError, "Clients: Exception in SAM bridge: ", e.what());
  56. }
  57. }
  58. // BOB
  59. bool bob; i2p::config::GetOption("bob.enabled", bob);
  60. if (bob) {
  61. std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr);
  62. uint16_t bobPort; i2p::config::GetOption("bob.port", bobPort);
  63. LogPrint(eLogInfo, "Clients: starting BOB command channel at ", bobAddr, ":", bobPort);
  64. try {
  65. m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort);
  66. m_BOBCommandChannel->Start ();
  67. } catch (std::exception& e) {
  68. LogPrint(eLogError, "Clients: Exception in BOB bridge: ", e.what());
  69. }
  70. }
  71. // I2CP
  72. bool i2cp; i2p::config::GetOption("i2cp.enabled", i2cp);
  73. if (i2cp)
  74. {
  75. std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr);
  76. uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort);
  77. LogPrint(eLogInfo, "Clients: starting I2CP at ", i2cpAddr, ":", i2cpPort);
  78. try
  79. {
  80. m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort);
  81. m_I2CPServer->Start ();
  82. }
  83. catch (std::exception& e)
  84. {
  85. LogPrint(eLogError, "Clients: Exception in I2CP: ", e.what());
  86. }
  87. }
  88. m_AddressBook.StartResolvers ();
  89. // start UDP cleanup
  90. if (!m_ServerForwards.empty ())
  91. {
  92. m_CleanupUDPTimer.reset (new boost::asio::deadline_timer(m_SharedLocalDestination->GetService ()));
  93. ScheduleCleanupUDP();
  94. }
  95. }
  96. void ClientContext::Stop ()
  97. {
  98. if (m_HttpProxy)
  99. {
  100. LogPrint(eLogInfo, "Clients: stopping HTTP Proxy");
  101. m_HttpProxy->Stop();
  102. delete m_HttpProxy;
  103. m_HttpProxy = nullptr;
  104. }
  105. if (m_SocksProxy)
  106. {
  107. LogPrint(eLogInfo, "Clients: stopping SOCKS Proxy");
  108. m_SocksProxy->Stop();
  109. delete m_SocksProxy;
  110. m_SocksProxy = nullptr;
  111. }
  112. for (auto& it: m_ClientTunnels)
  113. {
  114. LogPrint(eLogInfo, "Clients: stopping I2P client tunnel on port ", it.first);
  115. it.second->Stop ();
  116. }
  117. m_ClientTunnels.clear ();
  118. for (auto& it: m_ServerTunnels)
  119. {
  120. LogPrint(eLogInfo, "Clients: stopping I2P server tunnel");
  121. it.second->Stop ();
  122. }
  123. m_ServerTunnels.clear ();
  124. if (m_SamBridge)
  125. {
  126. LogPrint(eLogInfo, "Clients: stopping SAM bridge");
  127. m_SamBridge->Stop ();
  128. delete m_SamBridge;
  129. m_SamBridge = nullptr;
  130. }
  131. if (m_BOBCommandChannel)
  132. {
  133. LogPrint(eLogInfo, "Clients: stopping BOB command channel");
  134. m_BOBCommandChannel->Stop ();
  135. delete m_BOBCommandChannel;
  136. m_BOBCommandChannel = nullptr;
  137. }
  138. if (m_I2CPServer)
  139. {
  140. LogPrint(eLogInfo, "Clients: stopping I2CP");
  141. m_I2CPServer->Stop ();
  142. delete m_I2CPServer;
  143. m_I2CPServer = nullptr;
  144. }
  145. LogPrint(eLogInfo, "Clients: stopping AddressBook");
  146. m_AddressBook.Stop ();
  147. {
  148. std::lock_guard<std::mutex> lock(m_ForwardsMutex);
  149. m_ServerForwards.clear();
  150. m_ClientForwards.clear();
  151. }
  152. if (m_CleanupUDPTimer)
  153. {
  154. m_CleanupUDPTimer->cancel ();
  155. m_CleanupUDPTimer = nullptr;
  156. }
  157. for (auto& it: m_Destinations)
  158. it.second->Stop ();
  159. m_Destinations.clear ();
  160. m_SharedLocalDestination = nullptr;
  161. }
  162. void ClientContext::ReloadConfig ()
  163. {
  164. // TODO: handle config changes
  165. /*std::string config; i2p::config::GetOption("conf", config);
  166. i2p::config::ParseConfig(config);*/
  167. // handle tunnels
  168. // reset isUpdated for each tunnel
  169. VisitTunnels ([](I2PService * s)->bool { s->isUpdated = false; return true; });
  170. // reload tunnels
  171. ReadTunnels();
  172. // delete not updated tunnels (not in config anymore)
  173. VisitTunnels ([](I2PService * s)->bool { return s->isUpdated; });
  174. // change shared local destination
  175. m_SharedLocalDestination->Release ();
  176. CreateNewSharedLocalDestination ();
  177. // recreate HTTP proxy
  178. if (m_HttpProxy)
  179. {
  180. m_HttpProxy->Stop ();
  181. m_HttpProxy = nullptr;
  182. }
  183. ReadHttpProxy ();
  184. // recreate SOCKS proxy
  185. if (m_SocksProxy)
  186. {
  187. m_SocksProxy->Stop ();
  188. m_SocksProxy = nullptr;
  189. }
  190. ReadSocksProxy ();
  191. // delete unused destinations
  192. std::unique_lock<std::mutex> l(m_DestinationsMutex);
  193. for (auto it = m_Destinations.begin (); it != m_Destinations.end ();)
  194. {
  195. auto dest = it->second;
  196. if (dest->GetRefCounter () > 0) ++it; // skip
  197. else
  198. {
  199. dest->Stop ();
  200. it = m_Destinations.erase (it);
  201. }
  202. }
  203. }
  204. bool ClientContext::LoadPrivateKeys (i2p::data::PrivateKeys& keys, const std::string& filename,
  205. i2p::data::SigningKeyType sigType, i2p::data::CryptoKeyType cryptoType)
  206. {
  207. if (filename == "transient")
  208. {
  209. keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType);
  210. LogPrint (eLogInfo, "Clients: New transient keys address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
  211. return true;
  212. }
  213. bool success = true;
  214. std::string fullPath = i2p::fs::DataDirPath (filename);
  215. std::ifstream s(fullPath, std::ifstream::binary);
  216. if (s.is_open ())
  217. {
  218. s.seekg (0, std::ios::end);
  219. size_t len = s.tellg();
  220. s.seekg (0, std::ios::beg);
  221. uint8_t * buf = new uint8_t[len];
  222. s.read ((char *)buf, len);
  223. if(!keys.FromBuffer (buf, len))
  224. {
  225. LogPrint (eLogError, "Clients: failed to load keyfile ", filename);
  226. success = false;
  227. }
  228. else
  229. LogPrint (eLogInfo, "Clients: Local address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " loaded");
  230. delete[] buf;
  231. }
  232. else
  233. {
  234. LogPrint (eLogError, "Clients: can't open file ", fullPath, " Creating new one with signature type ", sigType, " crypto type ", cryptoType);
  235. keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType);
  236. std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
  237. size_t len = keys.GetFullLen ();
  238. uint8_t * buf = new uint8_t[len];
  239. len = keys.ToBuffer (buf, len);
  240. f.write ((char *)buf, len);
  241. delete[] buf;
  242. LogPrint (eLogInfo, "Clients: New private keys file ", fullPath, " for ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
  243. }
  244. return success;
  245. }
  246. std::vector<std::shared_ptr<DatagramSessionInfo> > ClientContext::GetForwardInfosFor(const i2p::data::IdentHash & destination)
  247. {
  248. std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
  249. std::lock_guard<std::mutex> lock(m_ForwardsMutex);
  250. for(const auto & c : m_ClientForwards)
  251. {
  252. if (c.second->IsLocalDestination(destination))
  253. {
  254. for (auto & i : c.second->GetSessions()) infos.push_back(i);
  255. break;
  256. }
  257. }
  258. for(const auto & s : m_ServerForwards)
  259. {
  260. if(std::get<0>(s.first) == destination)
  261. {
  262. for( auto & i : s.second->GetSessions()) infos.push_back(i);
  263. break;
  264. }
  265. }
  266. return infos;
  267. }
  268. std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (bool isPublic,
  269. i2p::data::SigningKeyType sigType, i2p::data::CryptoKeyType cryptoType,
  270. const std::map<std::string, std::string> * params)
  271. {
  272. i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType);
  273. auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
  274. std::unique_lock<std::mutex> l(m_DestinationsMutex);
  275. m_Destinations[localDestination->GetIdentHash ()] = localDestination;
  276. localDestination->Start ();
  277. return localDestination;
  278. }
  279. std::shared_ptr<ClientDestination> ClientContext::CreateNewMatchedTunnelDestination(const i2p::data::PrivateKeys &keys, const std::string & name, const std::map<std::string, std::string> * params)
  280. {
  281. MatchedTunnelDestination * cl = new MatchedTunnelDestination(keys, name, params);
  282. auto localDestination = std::shared_ptr<ClientDestination>(cl);
  283. std::unique_lock<std::mutex> l(m_DestinationsMutex);
  284. m_Destinations[localDestination->GetIdentHash ()] = localDestination;
  285. localDestination->Start ();
  286. return localDestination;
  287. }
  288. void ClientContext::DeleteLocalDestination (std::shared_ptr<ClientDestination> destination)
  289. {
  290. if (!destination) return;
  291. auto it = m_Destinations.find (destination->GetIdentHash ());
  292. if (it != m_Destinations.end ())
  293. {
  294. auto d = it->second;
  295. {
  296. std::unique_lock<std::mutex> l(m_DestinationsMutex);
  297. m_Destinations.erase (it);
  298. }
  299. d->Stop ();
  300. }
  301. }
  302. std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
  303. const std::map<std::string, std::string> * params)
  304. {
  305. auto it = m_Destinations.find (keys.GetPublic ()->GetIdentHash ());
  306. if (it != m_Destinations.end ())
  307. {
  308. LogPrint (eLogWarning, "Clients: Local destination ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " exists");
  309. if (!it->second->IsRunning ())
  310. it->second->Start ();
  311. return it->second;
  312. }
  313. auto localDestination = std::make_shared<ClientDestination> (keys, isPublic, params);
  314. std::unique_lock<std::mutex> l(m_DestinationsMutex);
  315. m_Destinations[keys.GetPublic ()->GetIdentHash ()] = localDestination;
  316. localDestination->Start ();
  317. return localDestination;
  318. }
  319. void ClientContext::CreateNewSharedLocalDestination ()
  320. {
  321. m_SharedLocalDestination = CreateNewLocalDestination (); // non-public, EDDSA
  322. m_SharedLocalDestination->Acquire ();
  323. }
  324. std::shared_ptr<ClientDestination> ClientContext::FindLocalDestination (const i2p::data::IdentHash& destination) const
  325. {
  326. auto it = m_Destinations.find (destination);
  327. if (it != m_Destinations.end ())
  328. return it->second;
  329. return nullptr;
  330. }
  331. template<typename Section, typename Type>
  332. std::string ClientContext::GetI2CPOption (const Section& section, const std::string& name, const Type& value) const
  333. {
  334. return section.second.get (boost::property_tree::ptree::path_type (name, '/'), std::to_string (value));
  335. }
  336. template<typename Section>
  337. std::string ClientContext::GetI2CPStringOption (const Section& section, const std::string& name, const std::string& value) const
  338. {
  339. return section.second.get (boost::property_tree::ptree::path_type (name, '/'), value);
  340. }
  341. template<typename Section>
  342. void ClientContext::ReadI2CPOptionsGroup (const Section& section, const std::string& group, std::map<std::string, std::string>& options) const
  343. {
  344. for (auto it: section.second)
  345. {
  346. if (it.first.length () >= group.length () && !it.first.compare (0, group.length (), group))
  347. options[it.first] = it.second.get_value ("");
  348. }
  349. }
  350. template<typename Section>
  351. void ClientContext::ReadI2CPOptions (const Section& section, std::map<std::string, std::string>& options) const
  352. {
  353. options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNEL_LENGTH, DEFAULT_INBOUND_TUNNEL_LENGTH);
  354. options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, DEFAULT_OUTBOUND_TUNNEL_LENGTH);
  355. options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, DEFAULT_INBOUND_TUNNELS_QUANTITY);
  356. options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, DEFAULT_OUTBOUND_TUNNELS_QUANTITY);
  357. options[I2CP_PARAM_TAGS_TO_SEND] = GetI2CPOption (section, I2CP_PARAM_TAGS_TO_SEND, DEFAULT_TAGS_TO_SEND);
  358. options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MIN_TUNNEL_LATENCY, DEFAULT_MIN_TUNNEL_LATENCY);
  359. options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MAX_TUNNEL_LATENCY, DEFAULT_MAX_TUNNEL_LATENCY);
  360. options[I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY] = GetI2CPOption(section, I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY, DEFAULT_INITIAL_ACK_DELAY);
  361. options[I2CP_PARAM_LEASESET_TYPE] = GetI2CPOption(section, I2CP_PARAM_LEASESET_TYPE, DEFAULT_LEASESET_TYPE);
  362. std::string encType = GetI2CPStringOption(section, I2CP_PARAM_LEASESET_ENCRYPTION_TYPE, "");
  363. if (encType.length () > 0) options[I2CP_PARAM_LEASESET_ENCRYPTION_TYPE] = encType;
  364. std::string privKey = GetI2CPStringOption(section, I2CP_PARAM_LEASESET_PRIV_KEY, "");
  365. if (privKey.length () > 0) options[I2CP_PARAM_LEASESET_PRIV_KEY] = privKey;
  366. auto authType = GetI2CPOption(section, I2CP_PARAM_LEASESET_AUTH_TYPE, 0);
  367. if (authType != "0") // auth is set
  368. {
  369. options[I2CP_PARAM_LEASESET_TYPE] = authType;
  370. if (authType == "1") // DH
  371. ReadI2CPOptionsGroup (section, I2CP_PARAM_LEASESET_CLIENT_DH, options);
  372. else if (authType == "2") // PSK
  373. ReadI2CPOptionsGroup (section, I2CP_PARAM_LEASESET_CLIENT_PSK, options);
  374. }
  375. }
  376. void ClientContext::ReadI2CPOptionsFromConfig (const std::string& prefix, std::map<std::string, std::string>& options) const
  377. {
  378. std::string value;
  379. if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNEL_LENGTH, value))
  380. options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = value;
  381. if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, value))
  382. options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = value;
  383. if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, value))
  384. options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = value;
  385. if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, value))
  386. options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = value;
  387. if (i2p::config::GetOption(prefix + I2CP_PARAM_MIN_TUNNEL_LATENCY, value))
  388. options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = value;
  389. if (i2p::config::GetOption(prefix + I2CP_PARAM_MAX_TUNNEL_LATENCY, value))
  390. options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = value;
  391. }
  392. void ClientContext::ReadTunnels ()
  393. {
  394. int numClientTunnels = 0, numServerTunnels = 0;
  395. std::string tunConf; i2p::config::GetOption("tunconf", tunConf);
  396. if (tunConf.empty ())
  397. {
  398. // TODO: cleanup this in 2.8.0
  399. tunConf = i2p::fs::DataDirPath ("tunnels.cfg");
  400. if (i2p::fs::Exists(tunConf))
  401. LogPrint(eLogWarning, "Clients: please rename tunnels.cfg -> tunnels.conf here: ", tunConf);
  402. else
  403. tunConf = i2p::fs::DataDirPath ("tunnels.conf");
  404. }
  405. LogPrint(eLogDebug, "Clients: tunnels config file: ", tunConf);
  406. ReadTunnels (tunConf, numClientTunnels, numServerTunnels);
  407. std::string tunDir; i2p::config::GetOption("tunnelsdir", tunDir);
  408. if (tunDir.empty ())
  409. tunDir = i2p::fs::DataDirPath ("tunnels.d");
  410. if (i2p::fs::Exists (tunDir))
  411. {
  412. std::vector<std::string> files;
  413. if (i2p::fs::ReadDir (tunDir, files))
  414. {
  415. for (auto& it: files)
  416. {
  417. LogPrint(eLogDebug, "Clients: tunnels extra config file: ", it);
  418. ReadTunnels (it, numClientTunnels, numServerTunnels);
  419. }
  420. }
  421. }
  422. LogPrint (eLogInfo, "Clients: ", numClientTunnels, " I2P client tunnels created");
  423. LogPrint (eLogInfo, "Clients: ", numServerTunnels, " I2P server tunnels created");
  424. }
  425. void ClientContext::ReadTunnels (const std::string& tunConf, int& numClientTunnels, int& numServerTunnels)
  426. {
  427. boost::property_tree::ptree pt;
  428. try
  429. {
  430. boost::property_tree::read_ini (tunConf, pt);
  431. }
  432. catch (std::exception& ex)
  433. {
  434. LogPrint (eLogWarning, "Clients: Can't read ", tunConf, ": ", ex.what ());
  435. return;
  436. }
  437. for (auto& section: pt)
  438. {
  439. std::string name = section.first;
  440. try
  441. {
  442. std::string type = section.second.get<std::string> (I2P_TUNNELS_SECTION_TYPE);
  443. if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT
  444. || type == I2P_TUNNELS_SECTION_TYPE_SOCKS
  445. || type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS
  446. || type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY
  447. || type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
  448. {
  449. // mandatory params
  450. std::string dest;
  451. if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT || type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
  452. dest = section.second.get<std::string> (I2P_CLIENT_TUNNEL_DESTINATION);
  453. int port = section.second.get<int> (I2P_CLIENT_TUNNEL_PORT);
  454. // optional params
  455. bool matchTunnels = section.second.get(I2P_CLIENT_TUNNEL_MATCH_TUNNELS, false);
  456. std::string keys = section.second.get (I2P_CLIENT_TUNNEL_KEYS, "transient");
  457. std::string address = section.second.get (I2P_CLIENT_TUNNEL_ADDRESS, "127.0.0.1");
  458. int destinationPort = section.second.get (I2P_CLIENT_TUNNEL_DESTINATION_PORT, 0);
  459. i2p::data::SigningKeyType sigType = section.second.get (I2P_CLIENT_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519);
  460. i2p::data::CryptoKeyType cryptoType = section.second.get (I2P_CLIENT_TUNNEL_CRYPTO_TYPE, i2p::data::CRYPTO_KEY_TYPE_ELGAMAL);
  461. // I2CP
  462. std::map<std::string, std::string> options;
  463. ReadI2CPOptions (section, options);
  464. std::shared_ptr<ClientDestination> localDestination = nullptr;
  465. if (keys.length () > 0)
  466. {
  467. i2p::data::PrivateKeys k;
  468. if(LoadPrivateKeys (k, keys, sigType, cryptoType))
  469. {
  470. localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
  471. if (!localDestination)
  472. {
  473. if(matchTunnels)
  474. localDestination = CreateNewMatchedTunnelDestination(k, dest, &options);
  475. else
  476. localDestination = CreateNewLocalDestination (k, type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT, &options);
  477. }
  478. }
  479. }
  480. if (type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT) {
  481. // udp client
  482. // TODO: hostnames
  483. boost::asio::ip::udp::endpoint end(boost::asio::ip::address::from_string(address), port);
  484. if (!localDestination)
  485. {
  486. localDestination = m_SharedLocalDestination;
  487. }
  488. auto clientTunnel = std::make_shared<I2PUDPClientTunnel>(name, dest, end, localDestination, destinationPort);
  489. if(m_ClientForwards.insert(std::make_pair(end, clientTunnel)).second)
  490. {
  491. clientTunnel->Start();
  492. }
  493. else
  494. LogPrint(eLogError, "Clients: I2P Client forward for endpoint ", end, " already exists");
  495. } else {
  496. boost::asio::ip::tcp::endpoint clientEndpoint;
  497. std::shared_ptr<I2PService> clientTunnel;
  498. if (type == I2P_TUNNELS_SECTION_TYPE_SOCKS)
  499. {
  500. // socks proxy
  501. std::string outproxy = section.second.get("outproxy", "");
  502. auto tun = std::make_shared<i2p::proxy::SOCKSProxy>(name, address, port, !outproxy.empty(), outproxy, destinationPort, localDestination);
  503. clientTunnel = tun;
  504. clientEndpoint = tun->GetLocalEndpoint ();
  505. }
  506. else if (type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY)
  507. {
  508. // http proxy
  509. std::string outproxy = section.second.get("outproxy", "");
  510. bool addresshelper = section.second.get("addresshelper", true);
  511. auto tun = std::make_shared<i2p::proxy::HTTPProxy>(name, address, port, outproxy, addresshelper, localDestination);
  512. clientTunnel = tun;
  513. clientEndpoint = tun->GetLocalEndpoint ();
  514. }
  515. else if (type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS)
  516. {
  517. // websocks proxy
  518. auto tun = std::make_shared<WebSocks>(address, port, localDestination);
  519. clientTunnel = tun;
  520. clientEndpoint = tun->GetLocalEndpoint();
  521. }
  522. else
  523. {
  524. // tcp client
  525. auto tun = std::make_shared<I2PClientTunnel> (name, dest, address, port, localDestination, destinationPort);
  526. clientTunnel = tun;
  527. clientEndpoint = tun->GetLocalEndpoint ();
  528. }
  529. uint32_t timeout = section.second.get<uint32_t>(I2P_CLIENT_TUNNEL_CONNECT_TIMEOUT, 0);
  530. if(timeout)
  531. {
  532. clientTunnel->SetConnectTimeout(timeout);
  533. LogPrint(eLogInfo, "Clients: I2P Client tunnel connect timeout set to ", timeout);
  534. }
  535. auto ins = m_ClientTunnels.insert (std::make_pair (clientEndpoint, clientTunnel));
  536. if (ins.second)
  537. {
  538. clientTunnel->Start ();
  539. numClientTunnels++;
  540. }
  541. else
  542. {
  543. // TODO: update
  544. if (ins.first->second->GetLocalDestination () != clientTunnel->GetLocalDestination ())
  545. {
  546. LogPrint (eLogInfo, "Clients: I2P client tunnel destination updated");
  547. ins.first->second->SetLocalDestination (clientTunnel->GetLocalDestination ());
  548. }
  549. ins.first->second->isUpdated = true;
  550. LogPrint (eLogInfo, "Clients: I2P client tunnel for endpoint ", clientEndpoint, " already exists");
  551. }
  552. }
  553. }
  554. else if (type == I2P_TUNNELS_SECTION_TYPE_SERVER
  555. || type == I2P_TUNNELS_SECTION_TYPE_HTTP
  556. || type == I2P_TUNNELS_SECTION_TYPE_IRC
  557. || type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
  558. {
  559. // mandatory params
  560. std::string host = section.second.get<std::string> (I2P_SERVER_TUNNEL_HOST);
  561. int port = section.second.get<int> (I2P_SERVER_TUNNEL_PORT);
  562. std::string keys = section.second.get<std::string> (I2P_SERVER_TUNNEL_KEYS);
  563. // optional params
  564. int inPort = section.second.get (I2P_SERVER_TUNNEL_INPORT, 0);
  565. std::string accessList = section.second.get (I2P_SERVER_TUNNEL_ACCESS_LIST, "");
  566. std::string hostOverride = section.second.get (I2P_SERVER_TUNNEL_HOST_OVERRIDE, "");
  567. std::string webircpass = section.second.get<std::string> (I2P_SERVER_TUNNEL_WEBIRC_PASSWORD, "");
  568. bool gzip = section.second.get (I2P_SERVER_TUNNEL_GZIP, true);
  569. i2p::data::SigningKeyType sigType = section.second.get (I2P_SERVER_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519);
  570. i2p::data::CryptoKeyType cryptoType = section.second.get (I2P_CLIENT_TUNNEL_CRYPTO_TYPE, i2p::data::CRYPTO_KEY_TYPE_ELGAMAL);
  571. std::string address = section.second.get<std::string> (I2P_SERVER_TUNNEL_ADDRESS, "127.0.0.1");
  572. bool isUniqueLocal = section.second.get(I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL, true);
  573. // I2CP
  574. std::map<std::string, std::string> options;
  575. ReadI2CPOptions (section, options);
  576. std::shared_ptr<ClientDestination> localDestination = nullptr;
  577. i2p::data::PrivateKeys k;
  578. if(!LoadPrivateKeys (k, keys, sigType, cryptoType))
  579. continue;
  580. localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
  581. if (!localDestination)
  582. localDestination = CreateNewLocalDestination (k, true, &options);
  583. if (type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
  584. {
  585. // udp server tunnel
  586. // TODO: hostnames
  587. auto localAddress = boost::asio::ip::address::from_string(address);
  588. boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
  589. auto serverTunnel = std::make_shared<I2PUDPServerTunnel>(name, localDestination, localAddress, endpoint, port);
  590. if(!isUniqueLocal)
  591. {
  592. LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
  593. serverTunnel->SetUniqueLocal(isUniqueLocal);
  594. }
  595. std::lock_guard<std::mutex> lock(m_ForwardsMutex);
  596. if(m_ServerForwards.insert(
  597. std::make_pair(
  598. std::make_pair(
  599. localDestination->GetIdentHash(), port),
  600. serverTunnel)).second)
  601. {
  602. serverTunnel->Start();
  603. LogPrint(eLogInfo, "Clients: I2P Server Forward created for UDP Endpoint ", host, ":", port, " bound on ", address, " for ",localDestination->GetIdentHash().ToBase32());
  604. }
  605. else
  606. LogPrint(eLogError, "Clients: I2P Server Forward for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash()), "/", port, "already exists");
  607. continue;
  608. }
  609. std::shared_ptr<I2PServerTunnel> serverTunnel;
  610. if (type == I2P_TUNNELS_SECTION_TYPE_HTTP)
  611. serverTunnel = std::make_shared<I2PServerTunnelHTTP> (name, host, port, localDestination, hostOverride, inPort, gzip);
  612. else if (type == I2P_TUNNELS_SECTION_TYPE_IRC)
  613. serverTunnel = std::make_shared<I2PServerTunnelIRC> (name, host, port, localDestination, webircpass, inPort, gzip);
  614. else // regular server tunnel by default
  615. serverTunnel = std::make_shared<I2PServerTunnel> (name, host, port, localDestination, inPort, gzip);
  616. if(!isUniqueLocal)
  617. {
  618. LogPrint(eLogInfo, "Clients: disabling loopback address mapping");
  619. serverTunnel->SetUniqueLocal(isUniqueLocal);
  620. }
  621. if (accessList.length () > 0)
  622. {
  623. std::set<i2p::data::IdentHash> idents;
  624. size_t pos = 0, comma;
  625. do
  626. {
  627. comma = accessList.find (',', pos);
  628. i2p::data::IdentHash ident;
  629. ident.FromBase32 (accessList.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
  630. idents.insert (ident);
  631. pos = comma + 1;
  632. }
  633. while (comma != std::string::npos);
  634. serverTunnel->SetAccessList (idents);
  635. }
  636. auto ins = m_ServerTunnels.insert (std::make_pair (
  637. std::make_pair (localDestination->GetIdentHash (), inPort),
  638. serverTunnel));
  639. if (ins.second)
  640. {
  641. serverTunnel->Start ();
  642. numServerTunnels++;
  643. }
  644. else
  645. {
  646. // TODO: update
  647. if (ins.first->second->GetLocalDestination () != serverTunnel->GetLocalDestination ())
  648. {
  649. LogPrint (eLogInfo, "Clients: I2P server tunnel destination updated");
  650. ins.first->second->SetLocalDestination (serverTunnel->GetLocalDestination ());
  651. }
  652. ins.first->second->isUpdated = true;
  653. LogPrint (eLogInfo, "Clients: I2P server tunnel for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash ()), "/", inPort, " already exists");
  654. }
  655. }
  656. else
  657. LogPrint (eLogWarning, "Clients: Unknown section type=", type, " of ", name, " in ", tunConf);
  658. }
  659. catch (std::exception& ex)
  660. {
  661. LogPrint (eLogError, "Clients: Can't read tunnel ", name, " params: ", ex.what ());
  662. }
  663. }
  664. }
  665. void ClientContext::ReadHttpProxy ()
  666. {
  667. std::shared_ptr<ClientDestination> localDestination;
  668. bool httproxy; i2p::config::GetOption("httpproxy.enabled", httproxy);
  669. if (httproxy)
  670. {
  671. std::string httpProxyKeys; i2p::config::GetOption("httpproxy.keys", httpProxyKeys);
  672. std::string httpProxyAddr; i2p::config::GetOption("httpproxy.address", httpProxyAddr);
  673. uint16_t httpProxyPort; i2p::config::GetOption("httpproxy.port", httpProxyPort);
  674. i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType);
  675. std::string httpOutProxyURL; i2p::config::GetOption("httpproxy.outproxy", httpOutProxyURL);
  676. bool httpAddresshelper; i2p::config::GetOption("httpproxy.addresshelper", httpAddresshelper);
  677. LogPrint(eLogInfo, "Clients: starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort);
  678. if (httpProxyKeys.length () > 0)
  679. {
  680. i2p::data::PrivateKeys keys;
  681. if(LoadPrivateKeys (keys, httpProxyKeys, sigType))
  682. {
  683. std::map<std::string, std::string> params;
  684. ReadI2CPOptionsFromConfig ("httpproxy.", params);
  685. localDestination = CreateNewLocalDestination (keys, false, &params);
  686. if (localDestination) localDestination->Acquire ();
  687. }
  688. else
  689. LogPrint(eLogError, "Clients: failed to load HTTP Proxy key");
  690. }
  691. try
  692. {
  693. m_HttpProxy = new i2p::proxy::HTTPProxy("HTTP Proxy", httpProxyAddr, httpProxyPort, httpOutProxyURL, httpAddresshelper, localDestination);
  694. m_HttpProxy->Start();
  695. }
  696. catch (std::exception& e)
  697. {
  698. LogPrint(eLogError, "Clients: Exception in HTTP Proxy: ", e.what());
  699. }
  700. }
  701. }
  702. void ClientContext::ReadSocksProxy ()
  703. {
  704. std::shared_ptr<ClientDestination> localDestination;
  705. bool socksproxy; i2p::config::GetOption("socksproxy.enabled", socksproxy);
  706. if (socksproxy)
  707. {
  708. std::string socksProxyKeys; i2p::config::GetOption("socksproxy.keys", socksProxyKeys);
  709. std::string socksProxyAddr; i2p::config::GetOption("socksproxy.address", socksProxyAddr);
  710. uint16_t socksProxyPort; i2p::config::GetOption("socksproxy.port", socksProxyPort);
  711. bool socksOutProxy; i2p::config::GetOption("socksproxy.outproxy.enabled", socksOutProxy);
  712. std::string socksOutProxyAddr; i2p::config::GetOption("socksproxy.outproxy", socksOutProxyAddr);
  713. uint16_t socksOutProxyPort; i2p::config::GetOption("socksproxy.outproxyport", socksOutProxyPort);
  714. i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype", sigType);
  715. LogPrint(eLogInfo, "Clients: starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort);
  716. if (socksProxyKeys.length () > 0)
  717. {
  718. i2p::data::PrivateKeys keys;
  719. if (LoadPrivateKeys (keys, socksProxyKeys, sigType))
  720. {
  721. std::map<std::string, std::string> params;
  722. ReadI2CPOptionsFromConfig ("socksproxy.", params);
  723. localDestination = CreateNewLocalDestination (keys, false, &params);
  724. if (localDestination) localDestination->Acquire ();
  725. }
  726. else
  727. LogPrint(eLogError, "Clients: failed to load SOCKS Proxy key");
  728. }
  729. try
  730. {
  731. m_SocksProxy = new i2p::proxy::SOCKSProxy("SOCKS", socksProxyAddr, socksProxyPort,
  732. socksOutProxy, socksOutProxyAddr, socksOutProxyPort, localDestination);
  733. m_SocksProxy->Start();
  734. }
  735. catch (std::exception& e)
  736. {
  737. LogPrint(eLogError, "Clients: Exception in SOCKS Proxy: ", e.what());
  738. }
  739. }
  740. }
  741. void ClientContext::ScheduleCleanupUDP()
  742. {
  743. if (m_CleanupUDPTimer)
  744. {
  745. // schedule cleanup in 17 seconds
  746. m_CleanupUDPTimer->expires_from_now (boost::posix_time::seconds (17));
  747. m_CleanupUDPTimer->async_wait(std::bind(&ClientContext::CleanupUDP, this, std::placeholders::_1));
  748. }
  749. }
  750. void ClientContext::CleanupUDP(const boost::system::error_code & ecode)
  751. {
  752. if(!ecode)
  753. {
  754. std::lock_guard<std::mutex> lock(m_ForwardsMutex);
  755. for (auto & s : m_ServerForwards ) s.second->ExpireStale();
  756. ScheduleCleanupUDP();
  757. }
  758. }
  759. template<typename Container, typename Visitor>
  760. void VisitTunnelsContainer (Container& c, Visitor v)
  761. {
  762. for (auto it = c.begin (); it != c.end ();)
  763. {
  764. if (!v (it->second.get ()))
  765. {
  766. it->second->Stop ();
  767. it = c.erase (it);
  768. }
  769. else
  770. it++;
  771. }
  772. }
  773. template<typename Visitor>
  774. void ClientContext::VisitTunnels (Visitor v)
  775. {
  776. VisitTunnelsContainer (m_ClientTunnels, v);
  777. VisitTunnelsContainer (m_ServerTunnels, v);
  778. // TODO: implement UDP forwards
  779. }
  780. }
  781. }