RouterModule.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "benc/String.h"
  16. #include "dht/Address.h"
  17. #include "dht/dhtcore/RouterModule.h"
  18. #include "dht/dhtcore/RouterModule_pvt.h"
  19. #include "dht/dhtcore/Node.h"
  20. #include "dht/dhtcore/NodeList.h"
  21. #include "dht/dhtcore/NodeStore.h"
  22. #include "dht/dhtcore/VersionList.h"
  23. #include "dht/CJDHTConstants.h"
  24. #include "dht/DHTMessage.h"
  25. #include "dht/DHTModule.h"
  26. #include "dht/DHTModuleRegistry.h"
  27. #include "util/log/Log.h"
  28. #include "memory/Allocator.h"
  29. #include "switch/LabelSplicer.h"
  30. #include "switch/NumberCompress.h"
  31. #include "util/events/EventBase.h"
  32. #include "util/AverageRoller.h"
  33. #include "util/Bits.h"
  34. #include "util/Hex.h"
  35. #include "util/Endian.h"
  36. #include "util/Pinger.h"
  37. #include "util/events/Time.h"
  38. #include "util/events/Timeout.h"
  39. #include "util/version/Version.h"
  40. #include "wire/Message.h"
  41. /*
  42. * The router module is the central part of the DHT engine.
  43. * It's job is to maintain a routing table which is updated by all incoming packets.
  44. * When it gets an incoming query, its job is to add nodes to the reply so that the asking node
  45. * can find other nodes which are closer to its target than us.
  46. *
  47. * This implementation does not split nodes explicitly into buckets not does it explicitly try to
  48. * distinguish between "good" and "bad" nodes. Instead it tries to determine which node will help
  49. * get to the requested record the fastest. Instead of periodicly pinging a random node in each
  50. * "bucket", this implementation periodically searches for a random[1] hash. When a node is sent a
  51. * query, the the distance[2] between it and the first node is divided by the amount of time it
  52. * takes the node to respond, for each successful search, this number is added to an attribute of
  53. * the node called "reach".
  54. *
  55. * Visually representing a node as an area whose location is defined by the node id and its size is
  56. * defined by the node reach, you can see that there is a possibility for a record to be closer in
  57. * key space to node2 while is is still further inside of node1's reach thus node1 is a better
  58. * choice for the next node to ask.
  59. *
  60. * |<--------- Node 1 ---------->|
  61. * |<--- Node 2 ---->|
  62. * ^----- Desired record location.
  63. *
  64. * New nodes are inserted into the table but with a reach of 0. It is up to the search client to
  65. * send search requests to them so they can prove their validity and have their reach number
  66. * updated.
  67. *
  68. * Reach of a node is incremented by 2 every time the node responds to a query and incremented by 1
  69. * every time a node sends a query of its own. This has almost no effect except that it means a
  70. * node which has recently sent data will be preferred over one which has not.
  71. *
  72. * When a search is carried out, the next K returned nodes are not necessarily the closest known
  73. * nodes to the id of the record. The nodes returned will be the nodes with the lowest
  74. * distance:reach ratio. The distance:reach ratio is calculated by dividing the distance between
  75. * the node and the record by the node's reach number. Actually it is done by multiplying
  76. * UINT32_MAX minus the distance by the reach so that it does not need to use slower divison.
  77. * See: NodeCollector.h
  78. *
  79. * Since information about a node becomes stale over time, all reach numbers are decreased by
  80. * the constant REACH_DECREASE_PER_SECOND times the number of seconds since the last cycle,
  81. * this operation is performed periodicly every LOCAL_MAINTENANCE_SEARCH_MILLISECONDS unless
  82. * a local maintainence search is being run which is not often once the network is stable.
  83. *
  84. * TODO(cjd): ---
  85. * In order to have the nodes with least distance:reach ratio ready to handle any incoming search,
  86. * we precompute the borders where the "best next node" changes. This computation is best understood
  87. * by graphing the nodes with their location in keyspace on the X axis and their reach on the Y
  88. * axis. The border between two nodes, nodeA and nodeB is the location where a line drawn from the
  89. * X axis up to either node location would be the same angle.
  90. *
  91. * ^ ^
  92. * | nodeA | nodeA
  93. * | |\ | |\__
  94. * | | \ | | \__
  95. * | | \ nodeB | | \nodeB
  96. * | | \ /| | | \__
  97. * | | \ / | | | | \__
  98. * | | \/ | | | | \__
  99. * +---------------------------------------> +--------------------------------------->
  100. * ^-- border ^-- border2
  101. *
  102. * Everything to the left of the border and everything to the right of border2 is to be serviced by
  103. * nodeA. Everything between the two borders is serviced by nodeB. Border2 is found by
  104. * drawing a line from the point given for nodeA to through the point given for nodeB and finding
  105. * the intersection of that line with the Y axis. border and border2 are shown on different graphs
  106. * only to limit clutter, they are the same nodeA and nodeB.
  107. *
  108. * When resolving a search, this implementation will lookup the location of the searched for record
  109. * and return the nodes which belong to the insides of the nearest K borders, this guarantees return
  110. * of the nodes whose distance:reach ratio is the lowest for that location.
  111. * ---
  112. *
  113. * This implementation must never respond to a search by sending any node who's id is not closer
  114. * to the target than its own. Such an event would lead to the possibility of "routing loops" and
  115. * must be prevented. Searches for which this node has the lowest distance:reach ratio will be
  116. * replied to with nodes which have 0 reach but are closer than this node or, if there are no such
  117. * nodes, no nodes at all.
  118. *
  119. * The search consumer in this routing module tries to minimize the amount of traffic sent when
  120. * doing a lookup. To achieve this, it sends a request only to the last node in the search response
  121. * packet, after the global mean response time has passed without it getting a response, it sends
  122. * requests to the second to last and so forth, working backward. Nodes which fail to respond in
  123. * time have their reach immedietly set to zero.
  124. *
  125. * The global mean response time is the average amount of time it takes a node to respond to a
  126. * search query. It is a rolling average over the past 256 seconds.
  127. *
  128. * To maximize the quality of service offered by this node this implementation will repeat
  129. * searches which it handles every number of seconds given by the constant:
  130. * GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS.
  131. * Any incoming search with a get_peers request is eligable to be repeated.
  132. *
  133. * [1] The implementation runs periodic searches for random hashes but unless the search target
  134. * is closer in keyspace to this node than it is to any node with non-zero reach, the search
  135. * is not performed. This means that the node will send out lots of searches when it doesn't
  136. * know many reliable nodes but it will taper off like a governer as it becomes more
  137. * integrated in the network. These searches are run every number of milliseconds given
  138. * by the constant LOCAL_MAINTENANCE_SEARCH_MILLISECONDS.
  139. *
  140. * [2] If a response "overshoots" the record requested then it is calculated as if it had undershot
  141. * by the same amount so as not to provide arbitrage advantage to nodes who return results which
  142. * are very far away yet very inaccurate. If it overshoots by more than the distance between the
  143. * node and the searched for location (this should never happen), it is considered to be 0.
  144. */
  145. /*--------------------Constants--------------------*/
  146. /** The number of seconds of time overwhich to calculate the global mean response time. */
  147. #define GMRT_SECONDS 256
  148. /**
  149. * The number to initialize the global mean response time averager with so that it will
  150. * return sane results early on, this number can be much higher than the expected average.
  151. */
  152. #define GMRT_INITAL_MILLISECONDS 5000
  153. /** The number of nodes which we will keep track of. */
  154. #define NODE_STORE_SIZE 8192
  155. /** The number of milliseconds between attempting local maintenance searches. */
  156. #define LOCAL_MAINTENANCE_SEARCH_MILLISECONDS 1000
  157. /**
  158. * The number of milliseconds to pass between global maintainence searches.
  159. * These are searches for random targets which are used to discover new nodes.
  160. */
  161. #define GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS 30000
  162. #define SEARCH_REPEAT_MILLISECONDS 7500
  163. /** The number of times the GMRT before pings should be timed out. */
  164. #define PING_TIMEOUT_GMRT_MULTIPLIER 100
  165. /** The minimum amount of time before a ping should timeout. */
  166. #define PING_TIMEOUT_MINIMUM 3000
  167. /** You are not expected to understand this. */
  168. #define LINK_STATE_MULTIPLIER 536870
  169. /** All searches will be killed after this amount of time nomatter how bad the GMRT is. */
  170. #define MAX_TIMEOUT 10000
  171. /** Never allow a search to be timed out in less than this number of milliseconds. */
  172. #define MIN_TIMEOUT 10
  173. /*--------------------Prototypes--------------------*/
  174. static int handleIncoming(struct DHTMessage* message, void* vcontext);
  175. static int handleOutgoing(struct DHTMessage* message, void* vcontext);
  176. /*--------------------Interface--------------------*/
  177. /**
  178. * Register a new RouterModule.
  179. *
  180. * @param registry the DHT module registry for signal handling.
  181. * @param allocator a means to allocate memory.
  182. * @param myAddress the address for this DHT node.
  183. * @param nodeStore the place to put the nodes
  184. * @return the RouterModule.
  185. */
  186. struct RouterModule* RouterModule_register(struct DHTModuleRegistry* registry,
  187. struct Allocator* allocator,
  188. const uint8_t myAddress[Address_KEY_SIZE],
  189. struct EventBase* eventBase,
  190. struct Log* logger,
  191. struct Random* rand,
  192. struct NodeStore* nodeStore)
  193. {
  194. struct RouterModule* const out = Allocator_calloc(allocator, sizeof(struct RouterModule), 1);
  195. struct DHTModule* dm = Allocator_clone(allocator, (&(struct DHTModule) {
  196. .name = "RouterModule",
  197. .context = out,
  198. .handleIncoming = handleIncoming,
  199. .handleOutgoing = handleOutgoing
  200. }));
  201. DHTModuleRegistry_register(dm, registry);
  202. Address_forKey(&out->address, myAddress);
  203. out->gmrtRoller = AverageRoller_new(GMRT_SECONDS, eventBase, allocator);
  204. AverageRoller_update(out->gmrtRoller, GMRT_INITAL_MILLISECONDS);
  205. out->nodeStore = nodeStore;
  206. out->registry = registry;
  207. out->eventBase = eventBase;
  208. out->logger = logger;
  209. out->allocator = allocator;
  210. out->rand = rand;
  211. out->pinger = Pinger_new(eventBase, rand, logger, allocator);
  212. Identity_set(out);
  213. return out;
  214. }
  215. /**
  216. * The amount of time to wait before skipping over the first node and trying another in a search.
  217. * Any node which can't beat this time will have its reach set to 0.
  218. *
  219. * @param module this module.
  220. * @return the timeout time.
  221. */
  222. uint64_t RouterModule_searchTimeoutMilliseconds(struct RouterModule* module)
  223. {
  224. uint64_t x = (((uint64_t) AverageRoller_getAverage(module->gmrtRoller)) * 4);
  225. x = x + (Random_uint32(module->rand) % (x | 1)) / 2;
  226. return (x > MAX_TIMEOUT) ? MAX_TIMEOUT : (x < MIN_TIMEOUT) ? MIN_TIMEOUT : x;
  227. }
  228. static inline int sendNodes(struct NodeList* nodeList,
  229. struct DHTMessage* message,
  230. struct RouterModule* module,
  231. uint32_t askerVersion)
  232. {
  233. struct DHTMessage* query = message->replyTo;
  234. String* nodes =
  235. String_newBinary(NULL, nodeList->size * Address_SERIALIZED_SIZE, message->allocator);
  236. struct VersionList* versions = VersionList_new(nodeList->size, message->allocator);
  237. int i = 0;
  238. for (; i < (int)nodeList->size; i++) {
  239. // We have to modify the reply in case this node uses a longer label discriminator
  240. // in our switch than its target address, the target address *must* have the same
  241. // length or longer.
  242. struct Address addr;
  243. Bits_memcpyConst(&addr, &nodeList->nodes[i]->address, sizeof(struct Address));
  244. addr.path = LabelSplicer_getLabelFor(addr.path, query->address->path);
  245. Address_serialize(&nodes->bytes[i * Address_SERIALIZED_SIZE], &addr);
  246. versions->versions[i] = nodeList->nodes[i]->address.protocolVersion;
  247. Assert_ifParanoid(!Bits_isZero(&nodes->bytes[i * Address_SERIALIZED_SIZE],
  248. Address_SERIALIZED_SIZE));
  249. }
  250. nodes->len = i * Address_SERIALIZED_SIZE;
  251. versions->length = i;
  252. if (i > 0) {
  253. Dict_putString(message->asDict, CJDHTConstants_NODES, nodes, message->allocator);
  254. String* versionsStr = VersionList_stringify(versions, message->allocator);
  255. Dict_putString(message->asDict,
  256. CJDHTConstants_NODE_PROTOCOLS,
  257. versionsStr,
  258. message->allocator);
  259. }
  260. return 0;
  261. }
  262. /**
  263. * Handle an incoming search query.
  264. * This is setup to handle the outgoing *response* to the query, it should
  265. * be called from handleOutgoing() and populate the response with nodes.
  266. *
  267. * @param message the empty response message to populate.
  268. * @param replyArgs the arguments dictionary in the response (to be populated).
  269. * @param module the routing module context.
  270. * @return 0 as long as the packet should not be stopped (at this point always 0).
  271. */
  272. static inline int handleQuery(struct DHTMessage* message,
  273. struct RouterModule* module)
  274. {
  275. struct DHTMessage* query = message->replyTo;
  276. int64_t* versionPtr = Dict_getInt(query->asDict, CJDHTConstants_PROTOCOL);
  277. uint32_t version = (versionPtr && *versionPtr <= UINT32_MAX) ? *versionPtr : 0;
  278. struct NodeList* nodeList = NULL;
  279. String* queryType = Dict_getString(query->asDict, CJDHTConstants_QUERY);
  280. if (String_equals(queryType, CJDHTConstants_QUERY_FN)) {
  281. // get the target
  282. String* target = Dict_getString(query->asDict, CJDHTConstants_TARGET);
  283. if (target == NULL || target->len != Address_SEARCH_TARGET_SIZE) {
  284. return 0;
  285. }
  286. struct Address targetAddr = { .path = 0 };
  287. Bits_memcpyConst(targetAddr.ip6.bytes, target->bytes, Address_SEARCH_TARGET_SIZE);
  288. // send the closest nodes
  289. nodeList = NodeStore_getClosestNodes(module->nodeStore,
  290. &targetAddr,
  291. RouterModule_K,
  292. version,
  293. message->allocator);
  294. } else if (String_equals(queryType, CJDHTConstants_QUERY_GP)) {
  295. // get the target
  296. String* target = Dict_getString(query->asDict, CJDHTConstants_TARGET);
  297. if (target == NULL || target->len != 8) {
  298. return 0;
  299. }
  300. uint64_t targetPath;
  301. Bits_memcpyConst(&targetPath, target->bytes, 8);
  302. targetPath = Endian_bigEndianToHost64(targetPath);
  303. nodeList =
  304. NodeStore_getPeers(targetPath, RouterModule_K, message->allocator, module->nodeStore);
  305. }
  306. return (nodeList) ? sendNodes(nodeList, message, module, version) : 0;
  307. }
  308. /**
  309. * We handle 2 kinds of packets on the outgoing.
  310. * 1. our requests
  311. * 2. our replies to others' requests.
  312. * Everything is tagged with our address, replies to requests which are not ping requests
  313. * will also be given a list of nodes.
  314. */
  315. static int handleOutgoing(struct DHTMessage* message, void* vcontext)
  316. {
  317. struct RouterModule* module = Identity_check((struct RouterModule*) vcontext);
  318. Dict_putInt(message->asDict,
  319. CJDHTConstants_PROTOCOL,
  320. Version_CURRENT_PROTOCOL,
  321. message->allocator);
  322. if (message->replyTo != NULL) {
  323. return handleQuery(message, module);
  324. }
  325. return 0;
  326. }
  327. struct PingContext
  328. {
  329. struct RouterModule_Promise pub;
  330. /** nonNull if this ping is part of a search. */
  331. struct SearchContext* search;
  332. struct RouterModule* router;
  333. struct Address address;
  334. /** The internal ping structure */
  335. struct Pinger_Ping* pp;
  336. /** A template of the message to be sent. */
  337. Dict* messageDict;
  338. Identity
  339. };
  340. static void sendMsg(String* txid, void* vpingContext)
  341. {
  342. struct PingContext* pc = Identity_check((struct PingContext*) vpingContext);
  343. // "t":"1234"
  344. Dict_putString(pc->messageDict, CJDHTConstants_TXID, txid, pc->pp->pingAlloc);
  345. struct Allocator* temp = Allocator_child(pc->pp->pingAlloc);
  346. struct Message* msg = Message_new(0, DHTMessage_MAX_SIZE + 512, temp);
  347. struct DHTMessage* dmesg = Allocator_calloc(temp, sizeof(struct DHTMessage), 1);
  348. dmesg->binMessage = msg;
  349. dmesg->address = &pc->address;
  350. dmesg->asDict = pc->messageDict;
  351. dmesg->allocator = temp;
  352. DHTModuleRegistry_handleOutgoing(dmesg, pc->router->registry);
  353. }
  354. static void onTimeout(uint32_t milliseconds, struct PingContext* pctx)
  355. {
  356. struct Node_Two* n = NodeStore_closestNode(pctx->router->nodeStore, pctx->address.path);
  357. // Ping timeout -> decrease reach
  358. if (n && !Bits_memcmp(pctx->address.key, n->address.key, 32)) {
  359. NodeStore_pathTimeout(pctx->router->nodeStore, pctx->address.path);
  360. }
  361. if (pctx->pub.callback) {
  362. pctx->pub.callback(&pctx->pub, milliseconds, NULL, NULL);
  363. }
  364. }
  365. static uint64_t pingTimeoutMilliseconds(struct RouterModule* module)
  366. {
  367. uint64_t out = AverageRoller_getAverage(module->gmrtRoller) * PING_TIMEOUT_GMRT_MULTIPLIER;
  368. return (out < PING_TIMEOUT_MINIMUM) ? PING_TIMEOUT_MINIMUM : out;
  369. }
  370. /**
  371. * The only type of message we handle on the incoming side is
  372. * a response to one of our queries.
  373. */
  374. static int handleIncoming(struct DHTMessage* message, void* vcontext)
  375. {
  376. String* txid = Dict_getString(message->asDict, CJDHTConstants_TXID);
  377. String* query = Dict_getString(message->asDict, CJDHTConstants_QUERY);
  378. if (query || !txid) {
  379. return 0;
  380. }
  381. struct RouterModule* module = Identity_check((struct RouterModule*) vcontext);
  382. // This is retreived below by onResponseOrTimeout()
  383. module->currentMessage = message;
  384. Pinger_pongReceived(txid, module->pinger);
  385. module->currentMessage = NULL;
  386. return 0;
  387. }
  388. // ping or search response came in
  389. static void onResponseOrTimeout(String* data, uint32_t milliseconds, void* vping)
  390. {
  391. struct PingContext* pctx = Identity_check((struct PingContext*) vping);
  392. if (data == NULL) {
  393. // This is how Pinger signals a timeout.
  394. onTimeout(milliseconds, pctx);
  395. return;
  396. }
  397. struct RouterModule* module = pctx->router;
  398. // Grab out the message which was put here in handleIncoming()
  399. struct DHTMessage* message = module->currentMessage;
  400. module->currentMessage = NULL;
  401. // This should never happen
  402. if (!Address_isSameIp(&pctx->address, message->address)) {
  403. #ifdef Log_WARN
  404. uint8_t expectedAddr[60];
  405. Address_print(expectedAddr, &pctx->address);
  406. uint8_t receivedAddr[60];
  407. Address_print(receivedAddr, message->address);
  408. Log_warn(module->logger,
  409. "Got return packet from different address than search was sent!\n"
  410. "Expected:%s\n"
  411. " Got:%s\n",
  412. expectedAddr,
  413. receivedAddr);
  414. #endif
  415. return;
  416. }
  417. // update the GMRT
  418. AverageRoller_update(pctx->router->gmrtRoller, milliseconds);
  419. /*
  420. Log_debug(pctx->router->logger,
  421. "Received response in %u milliseconds, gmrt now %u\n",
  422. milliseconds,
  423. AverageRoller_getAverage(pctx->router->gmrtRoller));
  424. */
  425. // prevent division by zero
  426. if (milliseconds == 0) { milliseconds++; }
  427. struct Node_Two* node = NodeStore_closestNode(module->nodeStore, message->address->path);
  428. if (node && !Bits_memcmp(node->address.key, message->address->key, 32)) {
  429. NodeStore_pathResponse(module->nodeStore, message->address->path, milliseconds);
  430. } else {
  431. struct Node_Link* link = NodeStore_discoverNode(module->nodeStore,
  432. message->address,
  433. message->encodingScheme,
  434. message->encIndex,
  435. milliseconds);
  436. node = (link) ? link->child : NULL;
  437. }
  438. // EncodingSchemeModule should have added this node to the store, check it.
  439. if (!node) {
  440. #ifdef Log_DEBUG
  441. uint8_t printedAddr[60];
  442. Address_print(printedAddr, message->address);
  443. Log_info(module->logger, "Got message from nonexistant node! [%s]\n", printedAddr);
  444. #endif
  445. return;
  446. }
  447. #ifdef Log_DEBUG
  448. String* versionBin = Dict_getString(message->asDict, CJDHTConstants_VERSION);
  449. if (versionBin && versionBin->len == 20) {
  450. uint8_t printedAddr[60];
  451. Address_print(printedAddr, message->address);
  452. uint8_t versionStr[41];
  453. Hex_encode(versionStr, 41, (uint8_t*) versionBin->bytes, 20);
  454. Log_debug(module->logger, "Got pong! [%s] ver[%s]\n", printedAddr, versionStr);
  455. }
  456. #endif
  457. if (pctx->pub.callback) {
  458. pctx->pub.callback(&pctx->pub, milliseconds, message->address, message->asDict);
  459. }
  460. }
  461. struct RouterModule_Promise* RouterModule_newMessage(struct Address* addr,
  462. uint32_t timeoutMilliseconds,
  463. struct RouterModule* module,
  464. struct Allocator* alloc)
  465. {
  466. // sending yourself a ping?
  467. // Assert_true(Bits_memcmp(addr->key, module->address.key, 32));
  468. Assert_ifParanoid(addr->path ==
  469. EncodingScheme_convertLabel(module->nodeStore->selfNode->encodingScheme,
  470. addr->path,
  471. EncodingScheme_convertLabel_convertTo_CANNONICAL));
  472. if (timeoutMilliseconds == 0) {
  473. timeoutMilliseconds = pingTimeoutMilliseconds(module);
  474. }
  475. struct Pinger_Ping* pp = Pinger_newPing(NULL,
  476. onResponseOrTimeout,
  477. sendMsg,
  478. timeoutMilliseconds,
  479. alloc,
  480. module->pinger);
  481. struct PingContext* pctx = Allocator_clone(pp->pingAlloc, (&(struct PingContext) {
  482. .pub = {
  483. .alloc = pp->pingAlloc
  484. },
  485. .router = module,
  486. .pp = pp
  487. }));
  488. Identity_set(pctx);
  489. Bits_memcpyConst(&pctx->address, addr, sizeof(struct Address));
  490. pp->context = pctx;
  491. return &pctx->pub;
  492. }
  493. void RouterModule_sendMessage(struct RouterModule_Promise* promise, Dict* request)
  494. {
  495. struct PingContext* pctx = Identity_check((struct PingContext*)promise);
  496. pctx->messageDict = request;
  497. // actual send is triggered asynchronously
  498. }
  499. struct RouterModule_Promise* RouterModule_pingNode(struct Address* addr,
  500. uint32_t timeoutMilliseconds,
  501. struct RouterModule* module,
  502. struct Allocator* alloc)
  503. {
  504. struct RouterModule_Promise* promise =
  505. RouterModule_newMessage(addr, timeoutMilliseconds, module, alloc);
  506. Dict* d = Dict_new(promise->alloc);
  507. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_PING, promise->alloc);
  508. RouterModule_sendMessage(promise, d);
  509. #ifdef Log_DEBUG
  510. uint8_t buff[60];
  511. Address_print(buff, addr);
  512. Log_debug(module->logger, "Sending ping [%u] to [%s]",
  513. ((struct PingContext*)promise)->pp->handle, buff);
  514. #endif
  515. Assert_true(addr->path != 0);
  516. return promise;
  517. }
  518. struct RouterModule_Promise* RouterModule_getPeers(struct Address* addr,
  519. uint64_t nearbyLabel,
  520. uint32_t timeoutMilliseconds,
  521. struct RouterModule* module,
  522. struct Allocator* alloc)
  523. {
  524. struct RouterModule_Promise* promise =
  525. RouterModule_newMessage(addr, timeoutMilliseconds, module, alloc);
  526. Dict* d = Dict_new(promise->alloc);
  527. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_GP, promise->alloc);
  528. uint64_t nearbyLabel_be = Endian_hostToBigEndian64(nearbyLabel);
  529. String* target = String_newBinary((char*)&nearbyLabel_be, 8, promise->alloc);
  530. Dict_putString(d, CJDHTConstants_TARGET, target, promise->alloc);
  531. RouterModule_sendMessage(promise, d);
  532. return promise;
  533. }
  534. struct Node_Two* RouterModule_lookup(uint8_t targetAddr[Address_SEARCH_TARGET_SIZE],
  535. struct RouterModule* module)
  536. {
  537. struct Address addr = { .path = 0 };
  538. Bits_memcpyConst(addr.ip6.bytes, targetAddr, Address_SEARCH_TARGET_SIZE);
  539. return NodeStore_getBest(&addr, module->nodeStore);
  540. }
  541. struct Node_Two* RouterModule_nodeForPath(uint64_t path, struct RouterModule* module)
  542. {
  543. struct Node_Link* link = NodeStore_linkForPath(module->nodeStore, path);
  544. if (!link) { return NULL; }
  545. return link->child;
  546. }
  547. void RouterModule_brokenPath(const uint64_t path, struct RouterModule* module)
  548. {
  549. NodeStore_brokenPath(path, module->nodeStore);
  550. }
  551. uint32_t RouterModule_globalMeanResponseTime(struct RouterModule* module)
  552. {
  553. return (uint32_t) AverageRoller_getAverage(module->gmrtRoller);
  554. }
  555. void RouterModule_peerIsReachable(uint64_t pathToPeer,
  556. uint64_t lagMilliseconds,
  557. struct RouterModule* module)
  558. {
  559. Assert_ifParanoid(LabelSplicer_isOneHop(pathToPeer));
  560. struct Node_Two* nn = RouterModule_nodeForPath(pathToPeer, module);
  561. for (struct Node_Link* peerLink = nn->reversePeers; peerLink; peerLink = peerLink->nextPeer) {
  562. if (peerLink->parent != module->nodeStore->selfNode) { continue; }
  563. if (peerLink->cannonicalLabel != pathToPeer) { continue; }
  564. struct Address address = { .path = 0 };
  565. Bits_memcpyConst(&address, &nn->address, sizeof(struct Address));
  566. address.path = pathToPeer;
  567. NodeStore_discoverNode(module->nodeStore,
  568. &address,
  569. nn->encodingScheme,
  570. peerLink->inverseLinkEncodingFormNumber,
  571. lagMilliseconds);
  572. return;
  573. }
  574. Assert_true(0);
  575. }