RouterModule.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. } else if (String_equals(queryType, CJDHTConstants_QUERY_NH)) {
  306. // get the target
  307. String* target = Dict_getString(query->asDict, CJDHTConstants_TARGET);
  308. if (target == NULL || target->len != Address_SEARCH_TARGET_SIZE) {
  309. return 0;
  310. }
  311. struct Node_Two* nn = NodeStore_getBest(module->nodeStore, target->bytes);
  312. nodeList = Allocator_calloc(message->allocator, sizeof(struct NodeList), 1);
  313. if (nn) {
  314. nodeList->size = 1;
  315. nodeList->nodes = Allocator_calloc(message->allocator, sizeof(char*), 1);
  316. nodeList->nodes[0] = nn;
  317. }
  318. }
  319. return (nodeList) ? sendNodes(nodeList, message, module, version) : 0;
  320. }
  321. /**
  322. * We handle 2 kinds of packets on the outgoing.
  323. * 1. our requests
  324. * 2. our replies to others' requests.
  325. * Everything is tagged with our address, replies to requests which are not ping requests
  326. * will also be given a list of nodes.
  327. */
  328. static int handleOutgoing(struct DHTMessage* message, void* vcontext)
  329. {
  330. struct RouterModule* module = Identity_check((struct RouterModule*) vcontext);
  331. Dict_putInt(message->asDict,
  332. CJDHTConstants_PROTOCOL,
  333. Version_CURRENT_PROTOCOL,
  334. message->allocator);
  335. if (message->replyTo != NULL) {
  336. return handleQuery(message, module);
  337. }
  338. return 0;
  339. }
  340. struct PingContext
  341. {
  342. struct RouterModule_Promise pub;
  343. /** nonNull if this ping is part of a search. */
  344. struct SearchContext* search;
  345. struct RouterModule* router;
  346. struct Address address;
  347. /** The internal ping structure */
  348. struct Pinger_Ping* pp;
  349. /** A template of the message to be sent. */
  350. Dict* messageDict;
  351. Identity
  352. };
  353. static void sendMsg(String* txid, void* vpingContext)
  354. {
  355. struct PingContext* pc = Identity_check((struct PingContext*) vpingContext);
  356. // "t":"1234"
  357. Dict_putString(pc->messageDict, CJDHTConstants_TXID, txid, pc->pp->pingAlloc);
  358. struct Allocator* temp = Allocator_child(pc->pp->pingAlloc);
  359. struct Message* msg = Message_new(0, DHTMessage_MAX_SIZE + 512, temp);
  360. struct DHTMessage* dmesg = Allocator_calloc(temp, sizeof(struct DHTMessage), 1);
  361. dmesg->binMessage = msg;
  362. dmesg->address = &pc->address;
  363. dmesg->asDict = pc->messageDict;
  364. dmesg->allocator = temp;
  365. DHTModuleRegistry_handleOutgoing(dmesg, pc->router->registry);
  366. }
  367. static void onTimeout(uint32_t milliseconds, struct PingContext* pctx)
  368. {
  369. struct Node_Two* n = NodeStore_closestNode(pctx->router->nodeStore, pctx->address.path);
  370. // Ping timeout -> decrease reach
  371. if (n && !Bits_memcmp(pctx->address.key, n->address.key, 32)) {
  372. NodeStore_pathTimeout(pctx->router->nodeStore, pctx->address.path);
  373. }
  374. if (pctx->pub.callback) {
  375. pctx->pub.callback(&pctx->pub, milliseconds, NULL, NULL);
  376. }
  377. }
  378. static uint64_t pingTimeoutMilliseconds(struct RouterModule* module)
  379. {
  380. uint64_t out = AverageRoller_getAverage(module->gmrtRoller) * PING_TIMEOUT_GMRT_MULTIPLIER;
  381. return (out < PING_TIMEOUT_MINIMUM) ? PING_TIMEOUT_MINIMUM : out;
  382. }
  383. /**
  384. * The only type of message we handle on the incoming side is
  385. * a response to one of our queries.
  386. */
  387. static int handleIncoming(struct DHTMessage* message, void* vcontext)
  388. {
  389. String* txid = Dict_getString(message->asDict, CJDHTConstants_TXID);
  390. String* query = Dict_getString(message->asDict, CJDHTConstants_QUERY);
  391. if (query || !txid) {
  392. return 0;
  393. }
  394. struct RouterModule* module = Identity_check((struct RouterModule*) vcontext);
  395. // This is retreived below by onResponseOrTimeout()
  396. module->currentMessage = message;
  397. Pinger_pongReceived(txid, module->pinger);
  398. module->currentMessage = NULL;
  399. return 0;
  400. }
  401. // ping or search response came in
  402. static void onResponseOrTimeout(String* data, uint32_t milliseconds, void* vping)
  403. {
  404. struct PingContext* pctx = Identity_check((struct PingContext*) vping);
  405. if (data == NULL) {
  406. // This is how Pinger signals a timeout.
  407. onTimeout(milliseconds, pctx);
  408. return;
  409. }
  410. struct RouterModule* module = pctx->router;
  411. // Grab out the message which was put here in handleIncoming()
  412. struct DHTMessage* message = module->currentMessage;
  413. module->currentMessage = NULL;
  414. // This should never happen
  415. if (!Address_isSameIp(&pctx->address, message->address)) {
  416. #ifdef Log_WARN
  417. uint8_t expectedAddr[60];
  418. Address_print(expectedAddr, &pctx->address);
  419. uint8_t receivedAddr[60];
  420. Address_print(receivedAddr, message->address);
  421. Log_warn(module->logger,
  422. "Got return packet from different address than search was sent!\n"
  423. "Expected:%s\n"
  424. " Got:%s\n",
  425. expectedAddr,
  426. receivedAddr);
  427. #endif
  428. return;
  429. }
  430. // update the GMRT
  431. AverageRoller_update(pctx->router->gmrtRoller, milliseconds);
  432. /*
  433. Log_debug(pctx->router->logger,
  434. "Received response in %u milliseconds, gmrt now %u\n",
  435. milliseconds,
  436. AverageRoller_getAverage(pctx->router->gmrtRoller));
  437. */
  438. // prevent division by zero
  439. if (milliseconds == 0) { milliseconds++; }
  440. struct Node_Two* node = NodeStore_closestNode(module->nodeStore, message->address->path);
  441. if (node && !Bits_memcmp(node->address.key, message->address->key, 32)) {
  442. NodeStore_pathResponse(module->nodeStore, message->address->path, milliseconds);
  443. } else {
  444. struct Node_Link* link = NodeStore_discoverNode(module->nodeStore,
  445. message->address,
  446. message->encodingScheme,
  447. message->encIndex,
  448. milliseconds);
  449. node = (link) ? link->child : NULL;
  450. }
  451. // EncodingSchemeModule should have added this node to the store, check it.
  452. if (!node) {
  453. #ifdef Log_DEBUG
  454. uint8_t printedAddr[60];
  455. Address_print(printedAddr, message->address);
  456. Log_info(module->logger, "Got message from nonexistant node! [%s]\n", printedAddr);
  457. #endif
  458. return;
  459. }
  460. #ifdef Log_DEBUG
  461. String* versionBin = Dict_getString(message->asDict, CJDHTConstants_VERSION);
  462. if (versionBin && versionBin->len == 20) {
  463. uint8_t printedAddr[60];
  464. Address_print(printedAddr, message->address);
  465. uint8_t versionStr[41];
  466. Hex_encode(versionStr, 41, (uint8_t*) versionBin->bytes, 20);
  467. Log_debug(module->logger, "Got pong! [%s] ver[%s]\n", printedAddr, versionStr);
  468. }
  469. #endif
  470. if (pctx->pub.callback) {
  471. pctx->pub.callback(&pctx->pub, milliseconds, message->address, message->asDict);
  472. }
  473. }
  474. struct RouterModule_Promise* RouterModule_newMessage(struct Address* addr,
  475. uint32_t timeoutMilliseconds,
  476. struct RouterModule* module,
  477. struct Allocator* alloc)
  478. {
  479. // sending yourself a ping?
  480. // Assert_true(Bits_memcmp(addr->key, module->address.key, 32));
  481. Assert_true(addr->path != 1);
  482. Assert_ifParanoid(addr->path ==
  483. EncodingScheme_convertLabel(module->nodeStore->selfNode->encodingScheme,
  484. addr->path,
  485. EncodingScheme_convertLabel_convertTo_CANNONICAL));
  486. if (timeoutMilliseconds == 0) {
  487. timeoutMilliseconds = pingTimeoutMilliseconds(module);
  488. }
  489. struct Pinger_Ping* pp = Pinger_newPing(NULL,
  490. onResponseOrTimeout,
  491. sendMsg,
  492. timeoutMilliseconds,
  493. alloc,
  494. module->pinger);
  495. struct PingContext* pctx = Allocator_clone(pp->pingAlloc, (&(struct PingContext) {
  496. .pub = {
  497. .alloc = pp->pingAlloc
  498. },
  499. .router = module,
  500. .pp = pp
  501. }));
  502. Identity_set(pctx);
  503. Bits_memcpyConst(&pctx->address, addr, sizeof(struct Address));
  504. pp->context = pctx;
  505. return &pctx->pub;
  506. }
  507. void RouterModule_sendMessage(struct RouterModule_Promise* promise, Dict* request)
  508. {
  509. struct PingContext* pctx = Identity_check((struct PingContext*)promise);
  510. pctx->messageDict = request;
  511. // actual send is triggered asynchronously
  512. }
  513. struct RouterModule_Promise* RouterModule_pingNode(struct Address* addr,
  514. uint32_t timeoutMilliseconds,
  515. struct RouterModule* module,
  516. struct Allocator* alloc)
  517. {
  518. struct RouterModule_Promise* promise =
  519. RouterModule_newMessage(addr, timeoutMilliseconds, module, alloc);
  520. Dict* d = Dict_new(promise->alloc);
  521. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_PING, promise->alloc);
  522. RouterModule_sendMessage(promise, d);
  523. #ifdef Log_DEBUG
  524. uint8_t buff[60];
  525. Address_print(buff, addr);
  526. Log_debug(module->logger, "Sending ping [%u] to [%s]",
  527. ((struct PingContext*)promise)->pp->handle, buff);
  528. #endif
  529. Assert_true(addr->path != 0);
  530. return promise;
  531. }
  532. struct RouterModule_Promise* RouterModule_nextHop(struct Address* whoToAsk,
  533. uint8_t target[16],
  534. uint32_t timeoutMilliseconds,
  535. struct RouterModule* module,
  536. struct Allocator* alloc)
  537. {
  538. struct RouterModule_Promise* promise =
  539. RouterModule_newMessage(whoToAsk, timeoutMilliseconds, module, alloc);
  540. Dict* d = Dict_new(promise->alloc);
  541. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_NH, promise->alloc);
  542. String* targetStr = String_newBinary(target, 16, promise->alloc);
  543. Dict_putString(d, CJDHTConstants_TARGET, targetStr, promise->alloc);
  544. RouterModule_sendMessage(promise, d);
  545. return promise;
  546. }
  547. struct RouterModule_Promise* RouterModule_findNode(struct Address* whoToAsk,
  548. uint8_t target[16],
  549. uint32_t timeoutMilliseconds,
  550. struct RouterModule* module,
  551. struct Allocator* alloc)
  552. {
  553. struct RouterModule_Promise* promise =
  554. RouterModule_newMessage(whoToAsk, timeoutMilliseconds, module, alloc);
  555. Dict* d = Dict_new(promise->alloc);
  556. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_FN, promise->alloc);
  557. String* targetStr = String_newBinary(target, 16, promise->alloc);
  558. Dict_putString(d, CJDHTConstants_TARGET, targetStr, promise->alloc);
  559. RouterModule_sendMessage(promise, d);
  560. return promise;
  561. }
  562. struct RouterModule_Promise* RouterModule_getPeers(struct Address* addr,
  563. uint64_t nearbyLabel,
  564. uint32_t timeoutMilliseconds,
  565. struct RouterModule* module,
  566. struct Allocator* alloc)
  567. {
  568. struct RouterModule_Promise* promise =
  569. RouterModule_newMessage(addr, timeoutMilliseconds, module, alloc);
  570. Dict* d = Dict_new(promise->alloc);
  571. Dict_putString(d, CJDHTConstants_QUERY, CJDHTConstants_QUERY_GP, promise->alloc);
  572. uint64_t nearbyLabel_be = Endian_hostToBigEndian64(nearbyLabel);
  573. uint8_t nearbyLabelBytes[8];
  574. Bits_memcpyConst(nearbyLabelBytes, &nearbyLabel_be, 8);
  575. String* target = String_newBinary(nearbyLabelBytes, 8, promise->alloc);
  576. Dict_putString(d, CJDHTConstants_TARGET, target, promise->alloc);
  577. RouterModule_sendMessage(promise, d);
  578. return promise;
  579. }
  580. struct Node_Two* RouterModule_nodeForPath(uint64_t path, struct RouterModule* module)
  581. {
  582. struct Node_Link* link = NodeStore_linkForPath(module->nodeStore, path);
  583. if (!link) { return NULL; }
  584. return link->child;
  585. }
  586. /*void RouterModule_brokenPath(const uint64_t path, struct RouterModule* module)
  587. {
  588. NodeStore_brokenPath(path, module->nodeStore);
  589. }*/
  590. uint32_t RouterModule_globalMeanResponseTime(struct RouterModule* module)
  591. {
  592. return (uint32_t) AverageRoller_getAverage(module->gmrtRoller);
  593. }
  594. void RouterModule_peerIsReachable(uint64_t pathToPeer,
  595. uint64_t lagMilliseconds,
  596. struct RouterModule* module)
  597. {
  598. Assert_ifParanoid(LabelSplicer_isOneHop(pathToPeer));
  599. struct Node_Two* nn = RouterModule_nodeForPath(pathToPeer, module);
  600. for (struct Node_Link* peerLink = nn->reversePeers; peerLink; peerLink = peerLink->nextPeer) {
  601. if (peerLink->parent != module->nodeStore->selfNode) { continue; }
  602. if (peerLink->cannonicalLabel != pathToPeer) { continue; }
  603. struct Address address = { .path = 0 };
  604. Bits_memcpyConst(&address, &nn->address, sizeof(struct Address));
  605. address.path = pathToPeer;
  606. NodeStore_discoverNode(module->nodeStore,
  607. &address,
  608. nn->encodingScheme,
  609. peerLink->inverseLinkEncodingFormNumber,
  610. lagMilliseconds);
  611. return;
  612. }
  613. Assert_true(0);
  614. }