I2NPProtocol.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. #include <string.h>
  2. #include <atomic>
  3. #include "Base.h"
  4. #include "Log.h"
  5. #include "Crypto.h"
  6. #include "I2PEndian.h"
  7. #include "Timestamp.h"
  8. #include "RouterContext.h"
  9. #include "NetDb.hpp"
  10. #include "Tunnel.h"
  11. #include "Transports.h"
  12. #include "Garlic.h"
  13. #include "I2NPProtocol.h"
  14. #include "version.h"
  15. using namespace i2p::transport;
  16. namespace i2p
  17. {
  18. std::shared_ptr<I2NPMessage> NewI2NPMessage ()
  19. {
  20. return std::make_shared<I2NPMessageBuffer<I2NP_MAX_MESSAGE_SIZE> >();
  21. }
  22. std::shared_ptr<I2NPMessage> NewI2NPShortMessage ()
  23. {
  24. return std::make_shared<I2NPMessageBuffer<I2NP_MAX_SHORT_MESSAGE_SIZE> >();
  25. }
  26. std::shared_ptr<I2NPMessage> NewI2NPTunnelMessage ()
  27. {
  28. auto msg = new I2NPMessageBuffer<i2p::tunnel::TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + 34>(); // reserved for alignment and NTCP 16 + 6 + 12
  29. msg->Align (12);
  30. return std::shared_ptr<I2NPMessage>(msg);
  31. }
  32. std::shared_ptr<I2NPMessage> NewI2NPMessage (size_t len)
  33. {
  34. return (len < I2NP_MAX_SHORT_MESSAGE_SIZE - I2NP_HEADER_SIZE - 2) ? NewI2NPShortMessage () : NewI2NPMessage ();
  35. }
  36. void I2NPMessage::FillI2NPMessageHeader (I2NPMessageType msgType, uint32_t replyMsgID)
  37. {
  38. SetTypeID (msgType);
  39. if (!replyMsgID) RAND_bytes ((uint8_t *)&replyMsgID, 4);
  40. SetMsgID (replyMsgID);
  41. SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + I2NP_MESSAGE_EXPIRATION_TIMEOUT);
  42. UpdateSize ();
  43. UpdateChks ();
  44. }
  45. void I2NPMessage::RenewI2NPMessageHeader ()
  46. {
  47. uint32_t msgID;
  48. RAND_bytes ((uint8_t *)&msgID, 4);
  49. SetMsgID (msgID);
  50. SetExpiration (i2p::util::GetMillisecondsSinceEpoch () + I2NP_MESSAGE_EXPIRATION_TIMEOUT);
  51. }
  52. bool I2NPMessage::IsExpired () const
  53. {
  54. auto ts = i2p::util::GetMillisecondsSinceEpoch ();
  55. auto exp = GetExpiration ();
  56. return (ts > exp + I2NP_MESSAGE_CLOCK_SKEW) || (ts < exp - 3*I2NP_MESSAGE_CLOCK_SKEW); // check if expired or too far in future
  57. }
  58. std::shared_ptr<I2NPMessage> CreateI2NPMessage (I2NPMessageType msgType, const uint8_t * buf, size_t len, uint32_t replyMsgID)
  59. {
  60. auto msg = NewI2NPMessage (len);
  61. if (msg->Concat (buf, len) < len)
  62. LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length ", msg->maxLen);
  63. msg->FillI2NPMessageHeader (msgType, replyMsgID);
  64. return msg;
  65. }
  66. std::shared_ptr<I2NPMessage> CreateI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from)
  67. {
  68. auto msg = NewI2NPMessage ();
  69. if (msg->offset + len < msg->maxLen)
  70. {
  71. memcpy (msg->GetBuffer (), buf, len);
  72. msg->len = msg->offset + len;
  73. msg->from = from;
  74. }
  75. else
  76. LogPrint (eLogError, "I2NP: message length ", len, " exceeds max length");
  77. return msg;
  78. }
  79. std::shared_ptr<I2NPMessage> CopyI2NPMessage (std::shared_ptr<I2NPMessage> msg)
  80. {
  81. if (!msg) return nullptr;
  82. auto newMsg = NewI2NPMessage (msg->len);
  83. newMsg->offset = msg->offset;
  84. *newMsg = *msg;
  85. return newMsg;
  86. }
  87. std::shared_ptr<I2NPMessage> CreateDeliveryStatusMsg (uint32_t msgID)
  88. {
  89. auto m = NewI2NPShortMessage ();
  90. uint8_t * buf = m->GetPayload ();
  91. if (msgID)
  92. {
  93. htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, msgID);
  94. htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, i2p::util::GetMillisecondsSinceEpoch ());
  95. }
  96. else // for SSU establishment
  97. {
  98. RAND_bytes ((uint8_t *)&msgID, 4);
  99. htobe32buf (buf + DELIVERY_STATUS_MSGID_OFFSET, msgID);
  100. htobe64buf (buf + DELIVERY_STATUS_TIMESTAMP_OFFSET, i2p::context.GetNetID ());
  101. }
  102. m->len += DELIVERY_STATUS_SIZE;
  103. m->FillI2NPMessageHeader (eI2NPDeliveryStatus);
  104. return m;
  105. }
  106. std::shared_ptr<I2NPMessage> CreateRouterInfoDatabaseLookupMsg (const uint8_t * key, const uint8_t * from,
  107. uint32_t replyTunnelID, bool exploratory, std::set<i2p::data::IdentHash> * excludedPeers)
  108. {
  109. auto m = excludedPeers ? NewI2NPMessage () : NewI2NPShortMessage ();
  110. uint8_t * buf = m->GetPayload ();
  111. memcpy (buf, key, 32); // key
  112. buf += 32;
  113. memcpy (buf, from, 32); // from
  114. buf += 32;
  115. uint8_t flag = exploratory ? DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP : DATABASE_LOOKUP_TYPE_ROUTERINFO_LOOKUP;
  116. if (replyTunnelID)
  117. {
  118. *buf = flag | DATABASE_LOOKUP_DELIVERY_FLAG; // set delivery flag
  119. htobe32buf (buf+1, replyTunnelID);
  120. buf += 5;
  121. }
  122. else
  123. {
  124. *buf = flag; // flag
  125. buf++;
  126. }
  127. if (excludedPeers)
  128. {
  129. int cnt = excludedPeers->size ();
  130. htobe16buf (buf, cnt);
  131. buf += 2;
  132. for (auto& it: *excludedPeers)
  133. {
  134. memcpy (buf, it, 32);
  135. buf += 32;
  136. }
  137. }
  138. else
  139. {
  140. // nothing to exclude
  141. htobuf16 (buf, 0);
  142. buf += 2;
  143. }
  144. m->len += (buf - m->GetPayload ());
  145. m->FillI2NPMessageHeader (eI2NPDatabaseLookup);
  146. return m;
  147. }
  148. std::shared_ptr<I2NPMessage> CreateLeaseSetDatabaseLookupMsg (const i2p::data::IdentHash& dest,
  149. const std::set<i2p::data::IdentHash>& excludedFloodfills,
  150. std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel, const uint8_t * replyKey, const uint8_t * replyTag)
  151. {
  152. int cnt = excludedFloodfills.size ();
  153. auto m = cnt > 0 ? NewI2NPMessage () : NewI2NPShortMessage ();
  154. uint8_t * buf = m->GetPayload ();
  155. memcpy (buf, dest, 32); // key
  156. buf += 32;
  157. memcpy (buf, replyTunnel->GetNextIdentHash (), 32); // reply tunnel GW
  158. buf += 32;
  159. *buf = DATABASE_LOOKUP_DELIVERY_FLAG | DATABASE_LOOKUP_ENCRYPTION_FLAG | DATABASE_LOOKUP_TYPE_LEASESET_LOOKUP; // flags
  160. buf ++;
  161. htobe32buf (buf, replyTunnel->GetNextTunnelID ()); // reply tunnel ID
  162. buf += 4;
  163. // excluded
  164. htobe16buf (buf, cnt);
  165. buf += 2;
  166. if (cnt > 0)
  167. {
  168. for (auto& it: excludedFloodfills)
  169. {
  170. memcpy (buf, it, 32);
  171. buf += 32;
  172. }
  173. }
  174. // encryption
  175. memcpy (buf, replyKey, 32);
  176. buf[32] = uint8_t( 1 ); // 1 tag
  177. memcpy (buf + 33, replyTag, 32);
  178. buf += 65;
  179. m->len += (buf - m->GetPayload ());
  180. m->FillI2NPMessageHeader (eI2NPDatabaseLookup);
  181. return m;
  182. }
  183. std::shared_ptr<I2NPMessage> CreateDatabaseSearchReply (const i2p::data::IdentHash& ident,
  184. std::vector<i2p::data::IdentHash> routers)
  185. {
  186. auto m = NewI2NPShortMessage ();
  187. uint8_t * buf = m->GetPayload ();
  188. size_t len = 0;
  189. memcpy (buf, ident, 32);
  190. len += 32;
  191. buf[len] = routers.size ();
  192. len++;
  193. for (const auto& it: routers)
  194. {
  195. memcpy (buf + len, it, 32);
  196. len += 32;
  197. }
  198. memcpy (buf + len, i2p::context.GetRouterInfo ().GetIdentHash (), 32);
  199. len += 32;
  200. m->len += len;
  201. m->FillI2NPMessageHeader (eI2NPDatabaseSearchReply);
  202. return m;
  203. }
  204. std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (std::shared_ptr<const i2p::data::RouterInfo> router, uint32_t replyToken)
  205. {
  206. if (!router) // we send own RouterInfo
  207. router = context.GetSharedRouterInfo ();
  208. auto m = NewI2NPShortMessage ();
  209. uint8_t * payload = m->GetPayload ();
  210. memcpy (payload + DATABASE_STORE_KEY_OFFSET, router->GetIdentHash (), 32);
  211. payload[DATABASE_STORE_TYPE_OFFSET] = 0; // RouterInfo
  212. htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, replyToken);
  213. uint8_t * buf = payload + DATABASE_STORE_HEADER_SIZE;
  214. if (replyToken)
  215. {
  216. memset (buf, 0, 4); // zero tunnelID means direct reply
  217. buf += 4;
  218. memcpy (buf, router->GetIdentHash (), 32);
  219. buf += 32;
  220. }
  221. uint8_t * sizePtr = buf;
  222. buf += 2;
  223. m->len += (buf - payload); // payload size
  224. i2p::data::GzipDeflator deflator;
  225. size_t size = deflator.Deflate (router->GetBuffer (), router->GetBufferLen (), buf, m->maxLen -m->len);
  226. if (size)
  227. {
  228. htobe16buf (sizePtr, size); // size
  229. m->len += size;
  230. }
  231. else
  232. m = nullptr;
  233. if (m)
  234. m->FillI2NPMessageHeader (eI2NPDatabaseStore);
  235. return m;
  236. }
  237. std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (const i2p::data::IdentHash& storeHash, std::shared_ptr<const i2p::data::LeaseSet> leaseSet)
  238. {
  239. if (!leaseSet) return nullptr;
  240. auto m = NewI2NPShortMessage ();
  241. uint8_t * payload = m->GetPayload ();
  242. memcpy (payload + DATABASE_STORE_KEY_OFFSET, storeHash, 32);
  243. payload[DATABASE_STORE_TYPE_OFFSET] = leaseSet->GetStoreType (); // 1 for LeaseSet
  244. htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
  245. size_t size = DATABASE_STORE_HEADER_SIZE;
  246. memcpy (payload + size, leaseSet->GetBuffer (), leaseSet->GetBufferLen ());
  247. size += leaseSet->GetBufferLen ();
  248. m->len += size;
  249. m->FillI2NPMessageHeader (eI2NPDatabaseStore);
  250. return m;
  251. }
  252. std::shared_ptr<I2NPMessage> CreateDatabaseStoreMsg (std::shared_ptr<const i2p::data::LocalLeaseSet> leaseSet, uint32_t replyToken, std::shared_ptr<const i2p::tunnel::InboundTunnel> replyTunnel)
  253. {
  254. if (!leaseSet) return nullptr;
  255. auto m = NewI2NPShortMessage ();
  256. uint8_t * payload = m->GetPayload ();
  257. memcpy (payload + DATABASE_STORE_KEY_OFFSET, leaseSet->GetStoreHash (), 32);
  258. payload[DATABASE_STORE_TYPE_OFFSET] = leaseSet->GetStoreType (); // LeaseSet or LeaseSet2
  259. htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, replyToken);
  260. size_t size = DATABASE_STORE_HEADER_SIZE;
  261. if (replyToken && replyTunnel)
  262. {
  263. if (replyTunnel)
  264. {
  265. htobe32buf (payload + size, replyTunnel->GetNextTunnelID ());
  266. size += 4; // reply tunnelID
  267. memcpy (payload + size, replyTunnel->GetNextIdentHash (), 32);
  268. size += 32; // reply tunnel gateway
  269. }
  270. else
  271. htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0);
  272. }
  273. memcpy (payload + size, leaseSet->GetBuffer (), leaseSet->GetBufferLen ());
  274. size += leaseSet->GetBufferLen ();
  275. m->len += size;
  276. m->FillI2NPMessageHeader (eI2NPDatabaseStore);
  277. return m;
  278. }
  279. bool IsRouterInfoMsg (std::shared_ptr<I2NPMessage> msg)
  280. {
  281. if (!msg || msg->GetTypeID () != eI2NPDatabaseStore) return false;
  282. return !msg->GetPayload ()[DATABASE_STORE_TYPE_OFFSET]; // 0- RouterInfo
  283. }
  284. static uint16_t g_MaxNumTransitTunnels = DEFAULT_MAX_NUM_TRANSIT_TUNNELS; // TODO:
  285. void SetMaxNumTransitTunnels (uint16_t maxNumTransitTunnels)
  286. {
  287. if (maxNumTransitTunnels > 0 && maxNumTransitTunnels <= 10000 && g_MaxNumTransitTunnels != maxNumTransitTunnels)
  288. {
  289. LogPrint (eLogDebug, "I2NP: Max number of transit tunnels set to ", maxNumTransitTunnels);
  290. g_MaxNumTransitTunnels = maxNumTransitTunnels;
  291. }
  292. }
  293. bool HandleBuildRequestRecords (int num, uint8_t * records, uint8_t * clearText)
  294. {
  295. for (int i = 0; i < num; i++)
  296. {
  297. uint8_t * record = records + i*TUNNEL_BUILD_RECORD_SIZE;
  298. if (!memcmp (record + BUILD_REQUEST_RECORD_TO_PEER_OFFSET, (const uint8_t *)i2p::context.GetRouterInfo ().GetIdentHash (), 16))
  299. {
  300. LogPrint (eLogDebug, "I2NP: Build request record ", i, " is ours");
  301. BN_CTX * ctx = BN_CTX_new ();
  302. i2p::context.DecryptTunnelBuildRecord (record + BUILD_REQUEST_RECORD_ENCRYPTED_OFFSET, clearText, ctx);
  303. BN_CTX_free (ctx);
  304. // replace record to reply
  305. if (i2p::context.AcceptsTunnels () &&
  306. i2p::tunnel::tunnels.GetTransitTunnels ().size () <= g_MaxNumTransitTunnels &&
  307. !i2p::transport::transports.IsBandwidthExceeded () &&
  308. !i2p::transport::transports.IsTransitBandwidthExceeded ())
  309. {
  310. auto transitTunnel = i2p::tunnel::CreateTransitTunnel (
  311. bufbe32toh (clearText + BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
  312. clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
  313. bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
  314. clearText + BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET,
  315. clearText + BUILD_REQUEST_RECORD_IV_KEY_OFFSET,
  316. clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x80,
  317. clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET ] & 0x40);
  318. i2p::tunnel::tunnels.AddTransitTunnel (transitTunnel);
  319. record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 0;
  320. }
  321. else
  322. record[BUILD_RESPONSE_RECORD_RET_OFFSET] = 30; // always reject with bandwidth reason (30)
  323. //TODO: fill filler
  324. SHA256 (record + BUILD_RESPONSE_RECORD_PADDING_OFFSET, BUILD_RESPONSE_RECORD_PADDING_SIZE + 1, // + 1 byte of ret
  325. record + BUILD_RESPONSE_RECORD_HASH_OFFSET);
  326. // encrypt reply
  327. i2p::crypto::CBCEncryption encryption;
  328. for (int j = 0; j < num; j++)
  329. {
  330. encryption.SetKey (clearText + BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET);
  331. encryption.SetIV (clearText + BUILD_REQUEST_RECORD_REPLY_IV_OFFSET);
  332. uint8_t * reply = records + j*TUNNEL_BUILD_RECORD_SIZE;
  333. encryption.Encrypt(reply, TUNNEL_BUILD_RECORD_SIZE, reply);
  334. }
  335. return true;
  336. }
  337. }
  338. return false;
  339. }
  340. void HandleVariableTunnelBuildMsg (uint32_t replyMsgID, uint8_t * buf, size_t len)
  341. {
  342. int num = buf[0];
  343. LogPrint (eLogDebug, "I2NP: VariableTunnelBuild ", num, " records");
  344. if (len < num*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE + 1)
  345. {
  346. LogPrint (eLogError, "VaribleTunnelBuild message of ", num, " records is too short ", len);
  347. return;
  348. }
  349. auto tunnel = i2p::tunnel::tunnels.GetPendingInboundTunnel (replyMsgID);
  350. if (tunnel)
  351. {
  352. // endpoint of inbound tunnel
  353. LogPrint (eLogDebug, "I2NP: VariableTunnelBuild reply for tunnel ", tunnel->GetTunnelID ());
  354. if (tunnel->HandleTunnelBuildResponse (buf, len))
  355. {
  356. LogPrint (eLogInfo, "I2NP: Inbound tunnel ", tunnel->GetTunnelID (), " has been created");
  357. tunnel->SetState (i2p::tunnel::eTunnelStateEstablished);
  358. i2p::tunnel::tunnels.AddInboundTunnel (tunnel);
  359. }
  360. else
  361. {
  362. LogPrint (eLogInfo, "I2NP: Inbound tunnel ", tunnel->GetTunnelID (), " has been declined");
  363. tunnel->SetState (i2p::tunnel::eTunnelStateBuildFailed);
  364. }
  365. }
  366. else
  367. {
  368. uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
  369. if (HandleBuildRequestRecords (num, buf + 1, clearText))
  370. {
  371. if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outboud tunnel
  372. {
  373. // so we send it to reply tunnel
  374. transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
  375. CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
  376. eI2NPVariableTunnelBuildReply, buf, len,
  377. bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
  378. }
  379. else
  380. transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
  381. CreateI2NPMessage (eI2NPVariableTunnelBuild, buf, len,
  382. bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
  383. }
  384. }
  385. }
  386. void HandleTunnelBuildMsg (uint8_t * buf, size_t len)
  387. {
  388. if (len < NUM_TUNNEL_BUILD_RECORDS*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE)
  389. {
  390. LogPrint (eLogError, "TunnelBuild message is too short ", len);
  391. return;
  392. }
  393. uint8_t clearText[BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE];
  394. if (HandleBuildRequestRecords (NUM_TUNNEL_BUILD_RECORDS, buf, clearText))
  395. {
  396. if (clearText[BUILD_REQUEST_RECORD_FLAG_OFFSET] & 0x40) // we are endpoint of outbound tunnel
  397. {
  398. // so we send it to reply tunnel
  399. transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
  400. CreateTunnelGatewayMsg (bufbe32toh (clearText + BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
  401. eI2NPTunnelBuildReply, buf, len,
  402. bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
  403. }
  404. else
  405. transports.SendMessage (clearText + BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
  406. CreateI2NPMessage (eI2NPTunnelBuild, buf, len,
  407. bufbe32toh (clearText + BUILD_REQUEST_RECORD_SEND_MSG_ID_OFFSET)));
  408. }
  409. }
  410. void HandleVariableTunnelBuildReplyMsg (uint32_t replyMsgID, uint8_t * buf, size_t len)
  411. {
  412. int num = buf[0];
  413. LogPrint (eLogDebug, "I2NP: VariableTunnelBuildReplyMsg of ", num, " records replyMsgID=", replyMsgID);
  414. if (len < num*BUILD_REQUEST_RECORD_CLEAR_TEXT_SIZE + 1)
  415. {
  416. LogPrint (eLogError, "VaribleTunnelBuildReply message of ", num, " records is too short ", len);
  417. return;
  418. }
  419. auto tunnel = i2p::tunnel::tunnels.GetPendingOutboundTunnel (replyMsgID);
  420. if (tunnel)
  421. {
  422. // reply for outbound tunnel
  423. if (tunnel->HandleTunnelBuildResponse (buf, len))
  424. {
  425. LogPrint (eLogInfo, "I2NP: Outbound tunnel ", tunnel->GetTunnelID (), " has been created");
  426. tunnel->SetState (i2p::tunnel::eTunnelStateEstablished);
  427. i2p::tunnel::tunnels.AddOutboundTunnel (tunnel);
  428. }
  429. else
  430. {
  431. LogPrint (eLogInfo, "I2NP: Outbound tunnel ", tunnel->GetTunnelID (), " has been declined");
  432. tunnel->SetState (i2p::tunnel::eTunnelStateBuildFailed);
  433. }
  434. }
  435. else
  436. LogPrint (eLogWarning, "I2NP: Pending tunnel for message ", replyMsgID, " not found");
  437. }
  438. std::shared_ptr<I2NPMessage> CreateTunnelDataMsg (const uint8_t * buf)
  439. {
  440. auto msg = NewI2NPTunnelMessage ();
  441. msg->Concat (buf, i2p::tunnel::TUNNEL_DATA_MSG_SIZE);
  442. msg->FillI2NPMessageHeader (eI2NPTunnelData);
  443. return msg;
  444. }
  445. std::shared_ptr<I2NPMessage> CreateTunnelDataMsg (uint32_t tunnelID, const uint8_t * payload)
  446. {
  447. auto msg = NewI2NPTunnelMessage ();
  448. htobe32buf (msg->GetPayload (), tunnelID);
  449. msg->len += 4; // tunnelID
  450. msg->Concat (payload, i2p::tunnel::TUNNEL_DATA_MSG_SIZE - 4);
  451. msg->FillI2NPMessageHeader (eI2NPTunnelData);
  452. return msg;
  453. }
  454. std::shared_ptr<I2NPMessage> CreateEmptyTunnelDataMsg ()
  455. {
  456. auto msg = NewI2NPTunnelMessage ();
  457. msg->len += i2p::tunnel::TUNNEL_DATA_MSG_SIZE;
  458. return msg;
  459. }
  460. std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, const uint8_t * buf, size_t len)
  461. {
  462. auto msg = NewI2NPMessage (len);
  463. uint8_t * payload = msg->GetPayload ();
  464. htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
  465. htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
  466. msg->len += TUNNEL_GATEWAY_HEADER_SIZE;
  467. if (msg->Concat (buf, len) < len)
  468. LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen);
  469. msg->FillI2NPMessageHeader (eI2NPTunnelGateway);
  470. return msg;
  471. }
  472. std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, std::shared_ptr<I2NPMessage> msg)
  473. {
  474. if (msg->offset >= I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE)
  475. {
  476. // message is capable to be used without copying
  477. uint8_t * payload = msg->GetBuffer () - TUNNEL_GATEWAY_HEADER_SIZE;
  478. htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
  479. int len = msg->GetLength ();
  480. htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
  481. msg->offset -= (I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE);
  482. msg->len = msg->offset + I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE +len;
  483. msg->FillI2NPMessageHeader (eI2NPTunnelGateway);
  484. return msg;
  485. }
  486. else
  487. return CreateTunnelGatewayMsg (tunnelID, msg->GetBuffer (), msg->GetLength ());
  488. }
  489. std::shared_ptr<I2NPMessage> CreateTunnelGatewayMsg (uint32_t tunnelID, I2NPMessageType msgType,
  490. const uint8_t * buf, size_t len, uint32_t replyMsgID)
  491. {
  492. auto msg = NewI2NPMessage (len);
  493. size_t gatewayMsgOffset = I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE;
  494. msg->offset += gatewayMsgOffset;
  495. msg->len += gatewayMsgOffset;
  496. if (msg->Concat (buf, len) < len)
  497. LogPrint (eLogError, "I2NP: tunnel gateway buffer overflow ", msg->maxLen);
  498. msg->FillI2NPMessageHeader (msgType, replyMsgID); // create content message
  499. len = msg->GetLength ();
  500. msg->offset -= gatewayMsgOffset;
  501. uint8_t * payload = msg->GetPayload ();
  502. htobe32buf (payload + TUNNEL_GATEWAY_HEADER_TUNNELID_OFFSET, tunnelID);
  503. htobe16buf (payload + TUNNEL_GATEWAY_HEADER_LENGTH_OFFSET, len);
  504. msg->FillI2NPMessageHeader (eI2NPTunnelGateway); // gateway message
  505. return msg;
  506. }
  507. size_t GetI2NPMessageLength (const uint8_t * msg, size_t len)
  508. {
  509. if (len < I2NP_HEADER_SIZE_OFFSET + 2)
  510. {
  511. LogPrint (eLogError, "I2NP: message length ", len, " is smaller than header");
  512. return len;
  513. }
  514. auto l = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET) + I2NP_HEADER_SIZE;
  515. if (l > len)
  516. {
  517. LogPrint (eLogError, "I2NP: message length ", l, " exceeds buffer length ", len);
  518. l = len;
  519. }
  520. return l;
  521. }
  522. void HandleI2NPMessage (uint8_t * msg, size_t len)
  523. {
  524. if (len < I2NP_HEADER_SIZE)
  525. {
  526. LogPrint (eLogError, "I2NP: message length ", len, " is smaller than header");
  527. return;
  528. }
  529. uint8_t typeID = msg[I2NP_HEADER_TYPEID_OFFSET];
  530. uint32_t msgID = bufbe32toh (msg + I2NP_HEADER_MSGID_OFFSET);
  531. LogPrint (eLogDebug, "I2NP: msg received len=", len,", type=", (int)typeID, ", msgID=", (unsigned int)msgID);
  532. uint8_t * buf = msg + I2NP_HEADER_SIZE;
  533. auto size = bufbe16toh (msg + I2NP_HEADER_SIZE_OFFSET);
  534. len -= I2NP_HEADER_SIZE;
  535. if (size > len)
  536. {
  537. LogPrint (eLogError, "I2NP: payload size ", size, " exceeds buffer length ", len);
  538. size = len;
  539. }
  540. switch (typeID)
  541. {
  542. case eI2NPVariableTunnelBuild:
  543. HandleVariableTunnelBuildMsg (msgID, buf, size);
  544. break;
  545. case eI2NPVariableTunnelBuildReply:
  546. HandleVariableTunnelBuildReplyMsg (msgID, buf, size);
  547. break;
  548. case eI2NPTunnelBuild:
  549. HandleTunnelBuildMsg (buf, size);
  550. break;
  551. case eI2NPTunnelBuildReply:
  552. // TODO:
  553. break;
  554. default:
  555. LogPrint (eLogWarning, "I2NP: Unexpected message ", (int)typeID);
  556. }
  557. }
  558. void HandleI2NPMessage (std::shared_ptr<I2NPMessage> msg)
  559. {
  560. if (msg)
  561. {
  562. uint8_t typeID = msg->GetTypeID ();
  563. LogPrint (eLogDebug, "I2NP: Handling message with type ", (int)typeID);
  564. switch (typeID)
  565. {
  566. case eI2NPTunnelData:
  567. i2p::tunnel::tunnels.PostTunnelData (msg);
  568. break;
  569. case eI2NPTunnelGateway:
  570. i2p::tunnel::tunnels.PostTunnelData (msg);
  571. break;
  572. case eI2NPGarlic:
  573. {
  574. if (msg->from)
  575. {
  576. if (msg->from->GetTunnelPool ())
  577. msg->from->GetTunnelPool ()->ProcessGarlicMessage (msg);
  578. else
  579. LogPrint (eLogInfo, "I2NP: Local destination for garlic doesn't exist anymore");
  580. }
  581. else
  582. i2p::context.ProcessGarlicMessage (msg);
  583. break;
  584. }
  585. case eI2NPDatabaseStore:
  586. case eI2NPDatabaseSearchReply:
  587. case eI2NPDatabaseLookup:
  588. // forward to netDb
  589. i2p::data::netdb.PostI2NPMsg (msg);
  590. break;
  591. case eI2NPDeliveryStatus:
  592. {
  593. if (msg->from && msg->from->GetTunnelPool ())
  594. msg->from->GetTunnelPool ()->ProcessDeliveryStatus (msg);
  595. else
  596. i2p::context.ProcessDeliveryStatusMessage (msg);
  597. break;
  598. }
  599. case eI2NPVariableTunnelBuild:
  600. case eI2NPVariableTunnelBuildReply:
  601. case eI2NPTunnelBuild:
  602. case eI2NPTunnelBuildReply:
  603. // forward to tunnel thread
  604. i2p::tunnel::tunnels.PostTunnelData (msg);
  605. break;
  606. default:
  607. HandleI2NPMessage (msg->GetBuffer (), msg->GetLength ());
  608. }
  609. }
  610. }
  611. I2NPMessagesHandler::~I2NPMessagesHandler ()
  612. {
  613. Flush ();
  614. }
  615. void I2NPMessagesHandler::PutNextMessage (std::shared_ptr<I2NPMessage> msg)
  616. {
  617. if (msg)
  618. {
  619. switch (msg->GetTypeID ())
  620. {
  621. case eI2NPTunnelData:
  622. m_TunnelMsgs.push_back (msg);
  623. break;
  624. case eI2NPTunnelGateway:
  625. m_TunnelGatewayMsgs.push_back (msg);
  626. break;
  627. default:
  628. HandleI2NPMessage (msg);
  629. }
  630. }
  631. }
  632. void I2NPMessagesHandler::Flush ()
  633. {
  634. if (!m_TunnelMsgs.empty ())
  635. {
  636. i2p::tunnel::tunnels.PostTunnelData (m_TunnelMsgs);
  637. m_TunnelMsgs.clear ();
  638. }
  639. if (!m_TunnelGatewayMsgs.empty ())
  640. {
  641. i2p::tunnel::tunnels.PostTunnelData (m_TunnelGatewayMsgs);
  642. m_TunnelGatewayMsgs.clear ();
  643. }
  644. }
  645. }