NodeStore.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  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 "crypto/AddressCalc.h"
  16. #include "dht/Address.h"
  17. #include "dht/dhtcore/Node.h"
  18. #include "dht/dhtcore/NodeStore.h"
  19. #include "dht/dhtcore/NodeList.h"
  20. #include "util/AddrTools.h"
  21. #include "util/Assert.h"
  22. #include "util/Bits.h"
  23. #include "util/log/Log.h"
  24. #include "util/version/Version.h"
  25. #include "switch/NumberCompress.h"
  26. #include "switch/LabelSplicer.h"
  27. #include "util/Gcc.h"
  28. #include <stdbool.h>
  29. #include <inttypes.h>
  30. #include <tree.h>
  31. /** A list of DHT nodes. */
  32. struct NodeStore_pvt
  33. {
  34. struct NodeStore pub;
  35. /** A fake link where we are both the parent and child. */
  36. struct Node_Link* selfLink;
  37. /** A tree containing all nodes ordered by ipv6 */
  38. struct NodeRBTree {
  39. struct Node_Two* rbh_root;
  40. } nodeTree;
  41. struct Allocator* alloc;
  42. /** The maximum number of nodes which can be allocated. TODO: make use of */
  43. int capacity;
  44. /**
  45. * The links to be freed next time freePendingLinks() is called.
  46. */
  47. struct Node_Link* linksToFree;
  48. /** The means for this node store to log. */
  49. struct Log* logger;
  50. Identity
  51. };
  52. // My memory is really bad
  53. #define A_COMES_FIRST 1
  54. #define B_COMES_FIRST -1
  55. static int comparePeers(const struct Node_Link* la, const struct Node_Link* lb)
  56. {
  57. Identity_check(lb);
  58. uint64_t a = la->cannonicalLabel;
  59. uint64_t b = lb->cannonicalLabel;
  60. int log2Diff = Bits_log2x64(b) - Bits_log2x64(a);
  61. if (log2Diff) {
  62. return log2Diff;
  63. }
  64. if (Bits_bitReverse64(a) < Bits_bitReverse64(b)) {
  65. return A_COMES_FIRST;
  66. } else if (a == b) {
  67. return 0;
  68. }
  69. return B_COMES_FIRST;
  70. }
  71. RB_GENERATE_STATIC(PeerRBTree, Node_Link, peerTree, comparePeers)
  72. static int compareNodes(const struct Node_Two* na, const struct Node_Two* nb)
  73. {
  74. Identity_check(nb);
  75. int ret;
  76. ret = Address_xorcmp(0, na->address.ip6.ints.one_be, nb->address.ip6.ints.one_be);
  77. if (ret) { return ret; }
  78. ret = Address_xorcmp(0, na->address.ip6.ints.two_be, nb->address.ip6.ints.two_be);
  79. if (ret) { return ret; }
  80. ret = Address_xorcmp(0, na->address.ip6.ints.three_be, nb->address.ip6.ints.three_be);
  81. if (ret) { return ret; }
  82. ret = Address_xorcmp(0, na->address.ip6.ints.four_be, nb->address.ip6.ints.four_be);
  83. return ret;
  84. }
  85. RB_GENERATE_STATIC(NodeRBTree, Node_Two, nodeTree, compareNodes)
  86. static void freeLink(struct Node_Link* link, struct NodeStore_pvt* store)
  87. {
  88. Allocator_realloc(store->alloc, link, 0);
  89. store->pub.linkCount--;
  90. }
  91. static struct Node_Link* getLink(struct NodeStore_pvt* store)
  92. {
  93. store->pub.linkCount++;
  94. return Allocator_calloc(store->alloc, sizeof(struct Node_Link), 1);
  95. }
  96. static void logLink(struct NodeStore_pvt* store,
  97. struct Node_Link* link,
  98. char* message)
  99. {
  100. #ifndef Log_DEBUG
  101. return;
  102. #endif
  103. uint8_t parent[40];
  104. uint8_t child[40];
  105. AddrTools_printIp(parent, link->parent->address.ip6.bytes);
  106. AddrTools_printIp(child, link->child->address.ip6.bytes);
  107. uint8_t path[20];
  108. AddrTools_printPath(path, link->cannonicalLabel);
  109. Log_debug(store->logger, "link[%s]->[%s] [%s] %s", parent, child, path, message);
  110. }
  111. static void _checkNode(struct Node_Two* node, struct NodeStore_pvt* store, char* file, int line)
  112. {
  113. #ifndef PARANOIA
  114. return;
  115. #endif
  116. Assert_true(node->address.path ==
  117. EncodingScheme_convertLabel(store->pub.selfNode->encodingScheme,
  118. node->address.path,
  119. EncodingScheme_convertLabel_convertTo_CANNONICAL));
  120. struct Node_Link* link;
  121. for (link = node->reversePeers; link; link = link->nextPeer) {
  122. Assert_fileLine(link->child == node, file, line);
  123. Assert_fileLine(RB_FIND(PeerRBTree, &link->parent->peerTree, link) == link, file, line);
  124. }
  125. struct Node_Link* lastLink = NULL;
  126. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  127. Assert_fileLine(node->bestParent || link->child->bestParent != link, file, line);
  128. Assert_fileLine(link->parent == node, file, line);
  129. Assert_fileLine(link->child != node || link == store->selfLink, file, line);
  130. Assert_fileLine(!lastLink || link->cannonicalLabel != lastLink->cannonicalLabel,
  131. file, line);
  132. Assert_fileLine(link->cannonicalLabel < UINT64_MAX && link->cannonicalLabel > 0,
  133. file, line);
  134. struct Node_Link* rlink = NULL;
  135. for (rlink = link->child->reversePeers; rlink; rlink = rlink->nextPeer) {
  136. if (rlink == link) {
  137. break;
  138. }
  139. }
  140. Assert_fileLine(rlink && "child contains reverse link", file, line);
  141. lastLink = link;
  142. }
  143. if (node->bestParent) {
  144. Assert_fileLine(Node_getReach(node->bestParent->parent) > Node_getReach(node)
  145. || node == store->pub.selfNode, file, line);
  146. Assert_fileLine(node->address.path != UINT64_MAX, file, line);
  147. // Should never get as low as 512...
  148. Assert_fileLine(Node_getReach(node) > 512, file, line);
  149. struct Node_Two* nn = node;
  150. do {
  151. Assert_fileLine(
  152. LabelSplicer_routesThrough(nn->address.path, nn->bestParent->parent->address.path),
  153. file,
  154. line
  155. );
  156. nn = nn->bestParent->parent;
  157. } while (nn != store->pub.selfNode);
  158. } else {
  159. Assert_fileLine(node->address.path == UINT64_MAX, file, line);
  160. Assert_fileLine(Node_getReach(node) == 0, file, line);
  161. }
  162. }
  163. #define checkNode(node, store) _checkNode(node, store, Gcc_SHORT_FILE, Gcc_LINE)
  164. static void _verifyNode(struct Node_Two* node, struct NodeStore_pvt* store, char* file, int line)
  165. {
  166. #ifndef PARANOIA
  167. return;
  168. #endif
  169. // #1 check the node (do the basic checks)
  170. _checkNode(node, store, file, line);
  171. // #2 make sure all of the node's outgoing links are split properly
  172. struct Node_Link* link = NULL;
  173. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  174. // make sure any peers of this node are split properly
  175. struct Node_Link* linkB = link;
  176. struct Node_Link* linkC = link;
  177. RB_FOREACH_REVERSE_FROM(linkB, PeerRBTree, linkC) {
  178. if (linkB == link || link == store->selfLink) { continue; }
  179. Assert_fileLine(
  180. !LabelSplicer_routesThrough(linkB->cannonicalLabel, link->cannonicalLabel),
  181. file, line
  182. );
  183. }
  184. }
  185. // #3 make sure looking for the node by address will actually find the correct node.
  186. if (node->bestParent) {
  187. Assert_fileLine(node == NodeStore_closestNode(&store->pub, node->address.path), file, line);
  188. }
  189. }
  190. #define verifyNode(node, store) _verifyNode(node, store, Gcc_SHORT_FILE, Gcc_LINE)
  191. // Verify is more thorough than check because it makes sure all links are split properly.
  192. static void _verify(struct NodeStore_pvt* store, char* file, int line)
  193. {
  194. #ifndef PARANOIA
  195. return;
  196. #endif
  197. Assert_true(store->pub.selfNode->bestParent == store->selfLink || !store->selfLink);
  198. struct Node_Two* nn = NULL;
  199. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  200. _verifyNode(nn, store, file, line);
  201. }
  202. }
  203. #define verify(store) _verify(store, Gcc_SHORT_FILE, Gcc_LINE)
  204. static void _check(struct NodeStore_pvt* store, char* file, int line)
  205. {
  206. #ifndef PARANOIA
  207. return;
  208. #endif
  209. Assert_true(store->pub.selfNode->bestParent == store->selfLink || !store->selfLink);
  210. struct Node_Two* nn = NULL;
  211. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  212. _checkNode(nn, store, file, line);
  213. }
  214. }
  215. #define check(store) _check(store, Gcc_SHORT_FILE, Gcc_LINE)
  216. /**
  217. * Extend a route by splicing on another link.
  218. * This will modify the Encoding Form of the first Director in next section of the route to make
  219. * it's size greater than or equal to the size of the return route through the parent node in the
  220. * link.
  221. *
  222. * @param routeLabel the label for reaching the parent node
  223. * @param link the link to extend the route with
  224. * @param previousLinkEncoding the encoding used for the parent's interface back to the grandparent
  225. */
  226. static uint64_t extendRoute(uint64_t routeLabel,
  227. struct EncodingScheme* parentScheme,
  228. uint64_t parentChildLabel,
  229. int previousLinkEncoding)
  230. {
  231. uint64_t next = parentChildLabel;
  232. int nextLinkEncoding = EncodingScheme_getFormNum(parentScheme, next);
  233. if (previousLinkEncoding > nextLinkEncoding) {
  234. next = EncodingScheme_convertLabel(parentScheme, next, previousLinkEncoding);
  235. }
  236. Assert_true(next != EncodingScheme_convertLabel_INVALID);
  237. return LabelSplicer_splice(next, routeLabel);
  238. }
  239. static void setReach(struct Node_Two* node, uint32_t newReach)
  240. {
  241. if (newReach) {
  242. Assert_true(node->bestParent);
  243. Assert_true(node->address.path < UINT64_MAX);
  244. Assert_true(newReach > 512);
  245. } else {
  246. Assert_true(!node->bestParent);
  247. Assert_true(node->address.path == UINT64_MAX);
  248. }
  249. node->reach_ro = newReach;
  250. }
  251. static void unreachable(struct Node_Two* node, struct NodeStore_pvt* store)
  252. {
  253. struct Node_Link* next = NULL;
  254. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  255. if (next->child->bestParent == next) { unreachable(next->child, store); }
  256. }
  257. node->bestParent = NULL;
  258. node->address.path = UINT64_MAX;
  259. setReach(node, 0);
  260. }
  261. /**
  262. * This is called when we have no idea what the reach should be for the next hop
  263. * because the path we previously used to get to it is broken and we need to use
  264. * a different one. Take a somewhat educated guess as to what it might be in a way
  265. * that will make the reach non-zero.
  266. */
  267. static uint32_t guessReachOfChild(struct Node_Link* link)
  268. {
  269. // return 3/4 of the parent's reach if it's 1 hop, 1/2 otherwise.
  270. uint32_t r = Node_getReach(link->parent) / 2;
  271. if (r < (1<<12)) {
  272. r = Node_getReach(link->parent) - 1;
  273. } else if (r < (1<<16)) {
  274. r = Node_getReach(link->parent) - Bits_log2x64(link->cannonicalLabel);
  275. }
  276. Assert_true(r < Node_getReach(link->parent) && r != 0);
  277. return r;
  278. }
  279. static int updateBestParentCycle(struct Node_Two* node,
  280. int cycle,
  281. int limit,
  282. uint32_t nextReach,
  283. struct NodeStore_pvt* store)
  284. {
  285. Assert_always(cycle < 1000);
  286. if (cycle < limit) {
  287. int total = 0;
  288. struct Node_Link* next = NULL;
  289. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  290. if (next->child->bestParent == next && next->child != node) {
  291. total += updateBestParentCycle(next->child, cycle+1, limit, nextReach, store);
  292. }
  293. }
  294. return total;
  295. }
  296. struct Node_Link* newBestLink = node->bestParent;
  297. struct Node_Two* newBest = newBestLink->parent;
  298. uint64_t bestPath = extendRoute(newBest->address.path,
  299. newBest->encodingScheme,
  300. newBestLink->cannonicalLabel,
  301. newBest->bestParent->inverseLinkEncodingFormNumber);
  302. if (bestPath == UINT64_MAX) {
  303. unreachable(node, store);
  304. return 1;
  305. }
  306. /*#ifdef Log_DEBUG
  307. if (node->address.path != bestPath) {
  308. uint8_t pathStr[20];
  309. AddrTools_printPath(pathStr, bestPath);
  310. uint8_t addrStr[40];
  311. AddrTools_printIp(addrStr, node->address.ip6.bytes);
  312. Log_debug(store->logger, "New best path [%s@%s]", addrStr, pathStr);
  313. }
  314. #endif*/
  315. node->address.path = bestPath;
  316. if (!limit) {
  317. setReach(node, nextReach);
  318. }
  319. checkNode(node, store);
  320. return 1;
  321. }
  322. static void updateBestParent(struct Node_Two* node,
  323. struct Node_Link* newBestParent,
  324. uint32_t nextReach,
  325. struct NodeStore_pvt* store)
  326. {
  327. check(store);
  328. node->bestParent = newBestParent;
  329. Assert_true(newBestParent);
  330. //Assert_true(nextReach > 1023);
  331. Assert_true(nextReach < Node_getReach(newBestParent->parent));
  332. for (int i = 0; i < 10000; i++) {
  333. if (!updateBestParentCycle(node, 0, i, nextReach, store)) {
  334. check(store);
  335. return;
  336. }
  337. }
  338. Assert_true(0);
  339. }
  340. static void handleGoodNews(struct Node_Two* node,
  341. uint32_t newReach,
  342. struct NodeStore_pvt* store)
  343. {
  344. // TODO: Paths longer than 1024 will blow up, handle more gracefully
  345. Assert_always(newReach != UINT32_MAX);
  346. Assert_always(newReach > 1023);
  347. Assert_true(newReach > Node_getReach(node));
  348. // The nodestore thinks it's unreachable, we can't very well update the reach.
  349. if (node->bestParent == NULL) { return; }
  350. if (newReach+1 > Node_getReach(node->bestParent->parent)) {
  351. handleGoodNews(node->bestParent->parent, newReach+1, store);
  352. }
  353. setReach(node, newReach);
  354. struct Node_Link* link = NULL;
  355. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  356. struct Node_Two* child = link->child;
  357. if (!child->bestParent || Node_getReach(child->bestParent->parent) < newReach) {
  358. uint32_t nextReach = guessReachOfChild(link);
  359. if (Node_getReach(child) > nextReach) { continue; }
  360. updateBestParent(child, link, nextReach, store);
  361. }
  362. }
  363. }
  364. /**
  365. * The news has hit (in handleBadNewsOne) and now all of the nodes in the affected zone have
  366. * been knocked down. Now lets see if there's a better path for any of them.
  367. */
  368. static void handleBadNewsTwo(struct Node_Link* link, struct NodeStore_pvt* store)
  369. {
  370. struct Node_Link* next = NULL;
  371. RB_FOREACH_REVERSE(next, PeerRBTree, &link->child->peerTree) {
  372. if (!next) { continue; }
  373. if (next->child->bestParent != next) { continue; }
  374. if (next == store->selfLink) { continue; }
  375. handleBadNewsTwo(next, store);
  376. }
  377. // node was relinked by a recursion of this function.
  378. if (link->child->bestParent != link) { return; }
  379. struct Node_Two* node = link->child;
  380. struct Node_Link* rp = link->child->reversePeers;
  381. struct Node_Link* best = node->bestParent;
  382. while (rp) {
  383. if (Node_getReach(rp->parent) >= Node_getReach(best->parent)) {
  384. if (Node_getReach(rp->parent) > Node_getReach(best->parent)
  385. || rp->parent->address.path < best->parent->address.path)
  386. {
  387. best = rp;
  388. }
  389. }
  390. rp = rp->nextPeer;
  391. }
  392. if (best == node->bestParent) { return; }
  393. uint32_t nextReach = guessReachOfChild(best);
  394. if (nextReach <= Node_getReach(node)) { return; }
  395. Assert_true(Node_getReach(node) < Node_getReach(best->parent));
  396. check(store);
  397. updateBestParent(node, best, nextReach, store);
  398. check(store);
  399. }
  400. /**
  401. * First thing we do is knock down everybody's reach.
  402. * This way they don't all cling to eachother for safety making
  403. * endless routing loops and stupid processing.
  404. */
  405. static uint32_t handleBadNewsOne(struct Node_Link* link,
  406. uint32_t newReach,
  407. struct NodeStore_pvt* store)
  408. {
  409. struct Node_Link* next = NULL;
  410. uint32_t highestRet = 0;
  411. RB_FOREACH_REVERSE(next, PeerRBTree, &link->child->peerTree) {
  412. if (next->child->bestParent != next) { continue; }
  413. if (next == store->selfLink) { continue; }
  414. if (Node_getReach(next->child) < newReach) { continue; }
  415. uint32_t ret = handleBadNewsOne(next, newReach, store);
  416. if (ret > highestRet) { highestRet = ret; }
  417. }
  418. if (!highestRet) { highestRet = newReach; }
  419. Assert_true(link->child != store->pub.selfNode);
  420. if (!highestRet) {
  421. unreachable(link->child, store);
  422. } else {
  423. setReach(link->child, highestRet);
  424. }
  425. if (highestRet < 1023) { highestRet = 1023; }
  426. return highestRet+1;
  427. }
  428. static void handleBadNews(struct Node_Two* node,
  429. uint32_t newReach,
  430. struct NodeStore_pvt* store)
  431. {
  432. Assert_true(newReach < Node_getReach(node));
  433. // no bestParent implies a reach of 0
  434. Assert_true(node->bestParent);
  435. Assert_true(node->bestParent != store->selfLink);
  436. // might be destroyed by handleBadNewsOne()
  437. struct Node_Link* bp = node->bestParent;
  438. Assert_true(!newReach || newReach > 1023);
  439. handleBadNewsOne(node->bestParent, newReach, store);
  440. // If our bad news actually improved the reach number for the node (because it was previously
  441. // 0 and that node has children) then we need to handle it as good news as well.
  442. if (node->bestParent) {
  443. if (Node_getReach(node) >= Node_getReach(node->bestParent->parent)) {
  444. handleGoodNews(node->bestParent->parent, Node_getReach(node)+1, store);
  445. }
  446. Assert_true(Node_getReach(node) < Node_getReach(node->bestParent->parent));
  447. }
  448. check(store);
  449. handleBadNewsTwo(bp, store);
  450. check(store);
  451. }
  452. static void handleNews(struct Node_Two* node, uint32_t newReach, struct NodeStore_pvt* store)
  453. {
  454. // This is because reach is used to prevent loops so it must be 1 more for each hop closer
  455. // to the root.
  456. if (newReach > (UINT32_MAX - 1024)) { newReach = (UINT32_MAX - 1024); }
  457. if (newReach < 1024) { newReach = 1024; }
  458. check(store);
  459. if (newReach < Node_getReach(node)) {
  460. handleBadNews(node, newReach, store);
  461. check(store);
  462. } else if (newReach > Node_getReach(node)) {
  463. handleGoodNews(node, newReach, store);
  464. check(store);
  465. }
  466. }
  467. static void unlinkNodes(struct Node_Link* link, struct NodeStore_pvt* store)
  468. {
  469. struct Node_Two* child = Identity_check(link->child);
  470. struct Node_Two* parent = Identity_check(link->parent);
  471. check(store);
  472. // Change the best parent and path if necessary
  473. if (child->bestParent == link) {
  474. handleBadNews(child, 0, store);
  475. }
  476. if (child->bestParent == link) {
  477. unreachable(child, store);
  478. }
  479. check(store);
  480. // Remove the entry from the reversePeers
  481. struct Node_Link* current = child->reversePeers;
  482. struct Node_Link** currentP = &child->reversePeers;
  483. while (current) {
  484. if (current == link) {
  485. *currentP = current->nextPeer;
  486. break;
  487. }
  488. currentP = &(current->nextPeer);
  489. current = *currentP;
  490. }
  491. Assert_true(current);
  492. // Remove the RBTree entry
  493. Assert_ifParanoid(link == RB_FIND(PeerRBTree, &parent->peerTree, link));
  494. RB_REMOVE(PeerRBTree, &parent->peerTree, link);
  495. link->nextPeer = store->linksToFree;
  496. store->linksToFree = link;
  497. // prevent double-free of link.
  498. link->parent = NULL;
  499. link->child = NULL;
  500. check(store);
  501. }
  502. static void update(struct Node_Link* link,
  503. int64_t linkStateDiff,
  504. struct NodeStore_pvt* store)
  505. {
  506. /** TODO: Link state is not taken into account yet
  507. if (linkStateDiff + link->linkState > UINT32_MAX) {
  508. link->linkState = UINT32_MAX;
  509. logLink(store, link, "link state set to maximum");
  510. } else if (linkStateDiff + link->linkState < 0) {
  511. link->linkState = UINT32_MAX;
  512. logLink(store, link, "link state set to zero");
  513. } else {
  514. link->linkState += linkStateDiff;
  515. }
  516. */
  517. }
  518. /**
  519. * Link two nodes in the graph together.
  520. * If a parent of the child node is also a parent of the parent node, they are
  521. * unlinked (the link is split and the child is inserted in the middle).
  522. *
  523. * @param parent the current end of the graph
  524. * @param child the new node to extend the graph
  525. * @param cannonicalLabel the label for getting from the parent to the child.
  526. * @param linkStateDiff how much to change the link state for this link.
  527. * @param store
  528. */
  529. static struct Node_Link* linkNodes(struct Node_Two* parent,
  530. struct Node_Two* child,
  531. uint64_t cannonicalLabel,
  532. int64_t linkStateDiff,
  533. int inverseLinkEncodingFormNumber,
  534. uint64_t discoveredPath,
  535. struct NodeStore_pvt* store)
  536. {
  537. check(store);
  538. #ifdef Log_DEBUG
  539. uint8_t parentIp[40];
  540. uint8_t childIp[40];
  541. AddrTools_printIp(parentIp, parent->address.ip6.bytes);
  542. AddrTools_printIp(childIp, child->address.ip6.bytes);
  543. uint8_t printedLabel[20];
  544. AddrTools_printPath(printedLabel, cannonicalLabel);
  545. Log_debug(store->logger, "Linking [%s] with [%s] with label fragment [%s]",
  546. parentIp, childIp, printedLabel);
  547. #endif
  548. // It's ok to link a node with itself via some loopey route.
  549. // in practice it should never actually be used and it might yield some interesting
  550. // information when the link is split, self-routes are not allowed unless the self
  551. // link is being set up :)
  552. Assert_true(cannonicalLabel != 1 || store->selfLink == NULL);
  553. #ifdef PARANOIA
  554. uint64_t definitelyCannonical =
  555. EncodingScheme_convertLabel(parent->encodingScheme,
  556. cannonicalLabel,
  557. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  558. Assert_true(definitelyCannonical == cannonicalLabel);
  559. #endif
  560. struct Node_Link* link;
  561. RB_FOREACH_REVERSE(link, PeerRBTree, &parent->peerTree) {
  562. Identity_check(link);
  563. if (link->child == child) {
  564. if (link->cannonicalLabel != cannonicalLabel) {
  565. // multiple paths between A and B are ok because they
  566. // will have divergent paths following the first director.
  567. continue;
  568. } else if (link->inverseLinkEncodingFormNumber != inverseLinkEncodingFormNumber) {
  569. logLink(store, link, "Relinking nodes with different encoding form");
  570. // This can happen when C renumbers but B->C is the same because B did
  571. // not renumber, EG: if C restarts.
  572. link->inverseLinkEncodingFormNumber = inverseLinkEncodingFormNumber;
  573. }
  574. update(link, linkStateDiff, store);
  575. return link;
  576. }
  577. }
  578. struct Node_Link dummy = { .cannonicalLabel = cannonicalLabel };
  579. link = Identity_ncheck(RB_FIND(PeerRBTree, &parent->peerTree, &dummy));
  580. if (link) {
  581. logLink(store, link, "Attempted to create alternate link with same label!");
  582. Assert_true(0);
  583. return link;
  584. }
  585. link = getLink(store);
  586. // set it up
  587. link->cannonicalLabel = cannonicalLabel;
  588. link->inverseLinkEncodingFormNumber = inverseLinkEncodingFormNumber;
  589. link->child = child;
  590. link->parent = parent;
  591. link->discoveredPath = discoveredPath;
  592. Identity_set(link);
  593. // reverse link
  594. link->nextPeer = child->reversePeers;
  595. child->reversePeers = link;
  596. // forward link
  597. Assert_ifParanoid(!RB_FIND(PeerRBTree, &parent->peerTree, link));
  598. RB_INSERT(PeerRBTree, &parent->peerTree, link);
  599. if (!child->bestParent) {
  600. if (parent->bestParent) {
  601. updateBestParent(child, link, guessReachOfChild(link), store);
  602. } else {
  603. unreachable(child, store);
  604. }
  605. }
  606. // update the child's link state and possibly change it's preferred path
  607. update(link, linkStateDiff, store);
  608. check(store);
  609. return link;
  610. }
  611. /**
  612. * Find the closest node to the given path.
  613. * Pay especially close attention to the comments in this function, they're critical to
  614. * understanting what it actually does.
  615. *
  616. * @param path the path to the node which we want the closest node to.
  617. * @param output a pointer to be set to the link to the closest node.
  618. * @param hops a pointer to an integer which is initially the limit on the number of allowed hops.
  619. * If there are more than this number of hope in the label, the search will terminate
  620. * early. At the end this will be set to the actual number of hops until the find.
  621. * @param store
  622. * @return the label fragment linking outputNode with the given path.
  623. */
  624. #define findClosest_INVALID (~((uint64_t)0))
  625. static uint64_t findClosest(const uint64_t path,
  626. struct Node_Link** output,
  627. uint32_t* hops,
  628. struct Node_Link* parentLink,
  629. struct NodeStore_pvt* store)
  630. {
  631. struct Node_Link tmpl = {
  632. // The path from us is always cannonical
  633. .cannonicalLabel = path
  634. };
  635. struct Node_Link* nextLink;
  636. struct Node_Link* link = parentLink;
  637. uint32_t actualHops = 0;
  638. for (; !hops || actualHops < *hops; actualHops++) {
  639. // Then we cannoicalize the child's Director
  640. if (link != parentLink) {
  641. // First we splice off the parent's Director leaving the child's Director.
  642. tmpl.cannonicalLabel =
  643. LabelSplicer_unsplice(tmpl.cannonicalLabel, link->cannonicalLabel);
  644. int formNum =
  645. EncodingScheme_getFormNum(link->child->encodingScheme, tmpl.cannonicalLabel);
  646. // Check that they didn't send us an obviously invalid route.
  647. if (formNum < link->inverseLinkEncodingFormNumber) {
  648. Assert_ifTesting(!"invalid route");
  649. Log_info(store->logger, "Invalid route");
  650. return findClosest_INVALID;
  651. }
  652. uint64_t cannonical =
  653. EncodingScheme_convertLabel(link->child->encodingScheme,
  654. tmpl.cannonicalLabel,
  655. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  656. // Check that they didn't waste space by sending an oversize encoding form.
  657. if (formNum > link->inverseLinkEncodingFormNumber
  658. && cannonical != tmpl.cannonicalLabel)
  659. {
  660. Assert_ifTesting(!"wasting space");
  661. Log_info(store->logger, "Wasted space");
  662. return findClosest_INVALID;
  663. }
  664. tmpl.cannonicalLabel = cannonical;
  665. }
  666. Assert_true(tmpl.cannonicalLabel != EncodingScheme_convertLabel_INVALID);
  667. // Then we search for the next peer in the path
  668. nextLink = Identity_ncheck(RB_NFIND(PeerRBTree, &link->child->peerTree, &tmpl));
  669. while (nextLink
  670. && !LabelSplicer_routesThrough(tmpl.cannonicalLabel, nextLink->cannonicalLabel))
  671. {
  672. //logLink(store, nextLink, "GETTING NEXT LINK");
  673. nextLink = Identity_ncheck(RB_NEXT(PeerRBTree, NULL, nextLink));
  674. }
  675. if (!nextLink || nextLink == store->selfLink) {
  676. // ignore the comments, they're mostly wrong anyway
  677. break;
  678. }
  679. Identity_check(nextLink);
  680. Assert_true(nextLink->child->encodingScheme);
  681. if (tmpl.cannonicalLabel == nextLink->cannonicalLabel) {
  682. //logLink(store, nextLink, "Exact match");
  683. tmpl.cannonicalLabel = 1;
  684. *output = nextLink;
  685. if (hops) { *hops = actualHops; }
  686. return 1;
  687. }
  688. if (!LabelSplicer_routesThrough(tmpl.cannonicalLabel, nextLink->cannonicalLabel)) {
  689. // child of next link is not in the path, we reached the end.
  690. break;
  691. }
  692. /*#ifdef Log_DEBUG
  693. uint8_t labelA[20];
  694. uint8_t labelB[20];
  695. uint8_t searchingFor[20];
  696. AddrTools_printPath(labelA, tmpl.cannonicalLabel);
  697. AddrTools_printPath(searchingFor, path);
  698. AddrTools_printPath(labelB, link->cannonicalLabel);
  699. Log_debug(store->logger, "[%s] is behind [%s] searching for [%s]",
  700. labelA, labelB, searchingFor);
  701. #endif*/
  702. link = nextLink;
  703. }
  704. /*#ifdef Log_DEBUG
  705. uint8_t labelA[20];
  706. uint8_t labelB[20] = "NONE";
  707. uint8_t labelC[20];
  708. AddrTools_printPath(labelA, tmpl.cannonicalLabel);
  709. if (nextLink) {
  710. AddrTools_printPath(labelB, nextLink->cannonicalLabel);
  711. }
  712. AddrTools_printPath(labelC, link->cannonicalLabel);
  713. Log_debug(store->logger, "[%s] is not behind [%s] closest: [%s]", labelA, labelB, labelC);
  714. #endif*/
  715. Assert_true(tmpl.cannonicalLabel);/// TODO remove this
  716. *output = link;
  717. if (hops) { *hops = actualHops; }
  718. return tmpl.cannonicalLabel;
  719. }
  720. static struct Node_Two* nodeForIp(struct NodeStore_pvt* store, uint8_t ip[16])
  721. {
  722. struct Node_Two fakeNode;
  723. Identity_set(&fakeNode);
  724. Bits_memcpyConst(fakeNode.address.ip6.bytes, ip, 16);
  725. return Identity_ncheck(RB_FIND(NodeRBTree, &store->nodeTree, &fakeNode));
  726. }
  727. static bool isAncestorOf(struct NodeStore_pvt* store,
  728. struct Node_Two* maybeAncestor,
  729. struct Node_Two* maybeDecendent)
  730. {
  731. struct Node_Link* parent = maybeDecendent->bestParent;
  732. for (int i = 0; i < 1000; i++) {
  733. if (!maybeDecendent->bestParent) { return false; }
  734. if (store->pub.selfNode == parent->parent) { return false; }
  735. if (maybeAncestor == parent->parent) { return true; }
  736. parent = parent->parent->bestParent;
  737. }
  738. Assert_always(0);
  739. }
  740. static void freePendingLinks(struct NodeStore_pvt* store)
  741. {
  742. struct Node_Link* link;
  743. while ((link = store->linksToFree)) {
  744. store->linksToFree = link->nextPeer;
  745. freeLink(link, store);
  746. }
  747. }
  748. static struct Node_Link* discoverLink(struct NodeStore_pvt* store,
  749. struct Node_Link* closestKnown,
  750. uint64_t pathKnownParentChild,
  751. struct Node_Two* child,
  752. uint64_t discoveredPath,
  753. int inverseLinkEncodingFormNumber)
  754. {
  755. // Make sure this link cannot be split before beginning.
  756. struct Node_Link* closest = NULL;
  757. uint64_t pathParentChild =
  758. findClosest(pathKnownParentChild, &closest, NULL, closestKnown, store);
  759. if (pathParentChild == findClosest_INVALID) {
  760. return NULL;
  761. }
  762. struct Node_Two* parent = closest->child;
  763. #ifdef Log_DEBUG
  764. {
  765. uint8_t parentStr[40];
  766. uint8_t childStr[40];
  767. uint8_t pathStr[20];
  768. AddrTools_printIp(parentStr, parent->address.ip6.bytes);
  769. AddrTools_printIp(childStr, child->address.ip6.bytes);
  770. AddrTools_printPath(pathStr, pathParentChild);
  771. Log_debug(store->logger, "discoverLink( [%s]->[%s] [%s] )", parentStr, childStr, pathStr);
  772. }
  773. #endif
  774. if (parent == child) {
  775. if (pathParentChild == 1) {
  776. // Link is already known.
  777. update(closest, 0, store);
  778. //Log_debug(store->logger, "Already known");
  779. return closest;
  780. }
  781. Log_debug(store->logger, "Loopey route");
  782. // lets not bother storing this link, a link with the same parent and child is
  783. // invalid according to verify() and it's just going to take up space in the store
  784. // we'll return closest which is a perfectly valid path to the same node.
  785. return closest;
  786. }
  787. while (pathParentChild == 1) {
  788. logLink(store, closest, "Node at end of path appears to have changed");
  789. // This should never happen for a direct peer or for a direct decendent in
  790. // a split link.
  791. Assert_always(closestKnown != closest);
  792. unlinkNodes(closest, store);
  793. pathParentChild =
  794. findClosest(pathKnownParentChild, &closest, NULL, closestKnown, store);
  795. if (pathParentChild != findClosest_INVALID) {
  796. // TODO: handle this in some way other than just failing to install the route.
  797. logLink(store, closestKnown, "Apparently the reverse link encoding scheme for "
  798. "link has changed.");
  799. return NULL;
  800. }
  801. parent = closest->child;
  802. check(store);
  803. }
  804. // link parent to child
  805. // TODO: linking every node with 0 link state, this can't be right.
  806. struct Node_Link* parentLink = linkNodes(parent,
  807. child,
  808. pathParentChild,
  809. 0,
  810. inverseLinkEncodingFormNumber,
  811. discoveredPath,
  812. store);
  813. if (!RB_FIND(NodeRBTree, &store->nodeTree, child)) {
  814. checkNode(child, store);
  815. RB_INSERT(NodeRBTree, &store->nodeTree, child);
  816. store->pub.nodeCount++;
  817. }
  818. check(store);
  819. // Check whether the parent is already linked with a node which is "behind" the child.
  820. // previous appears to be a "sibling link" to the closest->node link but in reality the
  821. // previous link should be split and node should be inserted in the middle.
  822. struct Node_Link* splitLink = RB_MIN(PeerRBTree, &parent->peerTree);
  823. while (splitLink) {
  824. if (splitLink->cannonicalLabel <= pathParentChild) {
  825. if (splitLink->cannonicalLabel == pathParentChild) {
  826. Assert_true(splitLink->child == child);
  827. splitLink = PeerRBTree_RB_NEXT(splitLink);
  828. continue;
  829. } else {
  830. // Since they're in order, definitely not found.
  831. break;
  832. }
  833. }
  834. if (!LabelSplicer_routesThrough(splitLink->cannonicalLabel, pathParentChild)) {
  835. splitLink = PeerRBTree_RB_NEXT(splitLink);
  836. continue;
  837. }
  838. struct Node_Two* grandChild = splitLink->child;
  839. // unsplice and cannonicalize so we now have a path from child to grandchild
  840. uint64_t childToGrandchild =
  841. LabelSplicer_unsplice(splitLink->cannonicalLabel, pathParentChild);
  842. childToGrandchild =
  843. EncodingScheme_convertLabel(child->encodingScheme,
  844. childToGrandchild,
  845. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  846. // just so we're on the same page here
  847. Assert_true(splitLink->parent == parent);
  848. Assert_true(childToGrandchild < UINT64_MAX);
  849. #ifdef Log_DEBUG
  850. {
  851. uint8_t parentStr[40];
  852. uint8_t childStr[40];
  853. uint8_t pathStr[20];
  854. AddrTools_printIp(parentStr, splitLink->parent->address.ip6.bytes);
  855. AddrTools_printIp(childStr, splitLink->child->address.ip6.bytes);
  856. AddrTools_printPath(pathStr, splitLink->cannonicalLabel);
  857. Log_debug(store->logger, "Splitting link [%s]->[%s] [%s]",
  858. parentStr, childStr, pathStr);
  859. AddrTools_printIp(parentStr, splitLink->parent->address.ip6.bytes);
  860. AddrTools_printIp(childStr, child->address.ip6.bytes);
  861. AddrTools_printPath(pathStr, pathParentChild);
  862. Log_debug(store->logger, "New parent [%s]->[%s] [%s]", parentStr, childStr, pathStr);
  863. AddrTools_printIp(parentStr, child->address.ip6.bytes);
  864. AddrTools_printIp(childStr, splitLink->child->address.ip6.bytes);
  865. AddrTools_printPath(pathStr, childToGrandchild);
  866. Log_debug(store->logger, "New child [%s]->[%s] [%s]", parentStr, childStr, pathStr);
  867. }
  868. #endif
  869. if (child == grandChild) {
  870. // There's an existing link from the parent to the child and it loops
  871. // it takes a detour over to some other nodes and then comes back to the grandChild
  872. Log_debug(store->logger, "replace existing link which contains a loop...");
  873. goto done;
  874. }
  875. if (grandChild->bestParent == splitLink
  876. && Node_getReach(child) <= Node_getReach(grandChild))
  877. {
  878. // We know that the grandchild decends from the parent because splitLink is parent-->gc
  879. // Two possibilities:
  880. // someRoute-->child-->parent
  881. // someRoute-->parent-->child
  882. check(store);
  883. if (Node_getReach(parent) >= Node_getReach(child)) {
  884. // Parent definitely does not decend from child.
  885. Assert_true(Node_getReach(grandChild) < UINT32_MAX);
  886. updateBestParent(child, parentLink, Node_getReach(child), store);
  887. } else {
  888. // Child definitely does not decend from parent
  889. // Parent may decend from child, if it does we cannot safely re-root child
  890. // if not then we could but if we believe the reach of the child is better,
  891. // we might as well use the route which goes via the child rather than re-rooting
  892. // it anyway.
  893. }
  894. handleGoodNews(child, Node_getReach(grandChild)+1, store);
  895. // Node_getReach(parent) is by definition higher than Node_getReach(grandChild)
  896. // so if child is a decendent of grandChild then it should have been switched.
  897. Assert_true(Node_getReach(child) > Node_getReach(grandChild));
  898. check(store);
  899. }
  900. Assert_true(splitLink->cannonicalLabel != pathParentChild);
  901. Assert_true(childToGrandchild != 1);
  902. struct Node_Link* lcg = discoverLink(store,
  903. parentLink,
  904. childToGrandchild,
  905. grandChild,
  906. discoveredPath,
  907. splitLink->inverseLinkEncodingFormNumber);
  908. // so...
  909. // There is a chance... that in the recursion, the link we JUST CREATED (parentLink)
  910. // was split and unlinked. If that is so, we really should just return because
  911. // everything we were planning to do here has been done for us.
  912. if (!parentLink->child) {
  913. // return that last link along pathParentChild.
  914. struct Node_Link* link = NULL;
  915. findClosest(pathParentChild, &link, NULL, closest, store);
  916. Assert_always(link);
  917. return link;
  918. }
  919. if (grandChild->bestParent != splitLink) {
  920. // The link has been created and we don't care much about it because it's not
  921. // the best path.
  922. goto done;
  923. }
  924. if (!lcg) {
  925. // The path is probably broken... TODO: log or something
  926. goto done;
  927. }
  928. if (!lcg->parent->bestParent) {
  929. // The path is probably too long so it can't be represented, unreachable...
  930. goto done;
  931. }
  932. // Normally we would expect lcg->parent to be equal to child but because of the
  933. // findClosest() call at the beginning of the discoverLink() function, that is not
  934. // necessarily true. One or more nodes along the path childToGrandchild might
  935. // already be known, in which case lcg->parent will be the last known node along
  936. // that path.
  937. //
  938. // Worse, lcg->parent->bestParent might actually be grandChild or a decendent
  939. // thereof. Consider a path looking like this:
  940. // parent<-child<-Alice<-Bob Charlie->Dave->grandChild
  941. //
  942. // The best path to grandChild is obviously via child and therefor Charlie and Dave
  943. // are mistaken and this is a phantom loop.
  944. if (Node_getReach(lcg->parent) <= Node_getReach(grandChild)) {
  945. // I know, I repeat myself...
  946. Assert_true(Node_getReach(child) > Node_getReach(grandChild));
  947. if (isAncestorOf(store, grandChild, lcg->parent)) {
  948. // Again, just making dead sure that the child is not a decendent of the
  949. // grandChild, this should not be possible at this point
  950. Assert_true(parentLink->child != lcg->parent);
  951. // Now we're going to walk the path, when we encounter a node which decends from
  952. // grandChild, we're going to switch it to decend from the previous node along the
  953. // path.
  954. struct Node_Link* link = NULL;
  955. for (int limit = 1; ; limit++) {
  956. int limitCpy = limit;
  957. link = NULL;
  958. findClosest(childToGrandchild,
  959. &link,
  960. &limitCpy,
  961. parentLink,
  962. store);
  963. Assert_always(link);
  964. if (link->child == grandChild) { break; }
  965. // We should never get here because the if statement below should have
  966. // handled this in the previous round.
  967. Assert_true(Node_getReach(link->parent) >= Node_getReach(grandChild));
  968. if (Node_getReach(link->child) <= Node_getReach(grandChild)) {
  969. // Ok we're found a node whose pathQuality is less than grandChild's
  970. // and this node is in the best path *to* the grandChild so it's quality
  971. // needs to be increased and we need to swap it's bestParent so that we're
  972. // sure it doesn't decend from grandChild.
  973. if (link->child->bestParent != link) {
  974. if (Node_getReach(link->parent) <= Node_getReach(grandChild)+1) {
  975. handleGoodNews(link->parent, Node_getReach(grandChild)+2, store);
  976. }
  977. Assert_true(Node_getReach(link->parent) > Node_getReach(grandChild));
  978. updateBestParent(link->child, link, Node_getReach(grandChild)+1, store);
  979. }
  980. if (Node_getReach(link->child) <= Node_getReach(grandChild)) {
  981. handleGoodNews(link->child, Node_getReach(grandChild)+1, store);
  982. }
  983. Assert_true(Node_getReach(link->child) > Node_getReach(grandChild));
  984. }
  985. }
  986. // Guess what!
  987. // grandChild *might* just show up MULTIPLE times in the path (phantom loop),
  988. // of so, link is now the first instance of grandChild and lcg is the final
  989. // instance (end of the path). We don't care much about the path beyond the first
  990. // instance of grandChild so we're just going to quietly swap the lcg for link
  991. // if it happens that they are not the same.
  992. lcg = link;
  993. Assert_true(Node_getReach(lcg->parent) > Node_getReach(grandChild));
  994. } else {
  995. handleGoodNews(lcg->parent, Node_getReach(grandChild)+1, store);
  996. Assert_true(Node_getReach(lcg->parent) > Node_getReach(grandChild));
  997. }
  998. Assert_true(Node_getReach(lcg->parent) > Node_getReach(grandChild));
  999. updateBestParent(grandChild, lcg, Node_getReach(grandChild), store);
  1000. }
  1001. // pfew
  1002. done:
  1003. check(store);
  1004. // be careful!
  1005. // splitLink might have been unlinked by the recursive discoverLink() call.
  1006. if (splitLink->parent) {
  1007. unlinkNodes(splitLink, store);
  1008. }
  1009. // link RB_NEXT might have also been freed by a recursive call to discoverLink()
  1010. // so we'll just start over from the beginning and walk the list of links.
  1011. splitLink = RB_MIN(PeerRBTree, &parent->peerTree);
  1012. }
  1013. check(store);
  1014. return parentLink;
  1015. }
  1016. static struct Node_Two* whichIsWorse(struct Node_Two* one,
  1017. struct Node_Two* two,
  1018. struct NodeStore_pvt* store)
  1019. {
  1020. if (one->address.protocolVersion != two->address.protocolVersion) {
  1021. if (one->address.protocolVersion < Version_CURRENT_PROTOCOL) {
  1022. if (two->address.protocolVersion >= Version_CURRENT_PROTOCOL) {
  1023. return one;
  1024. }
  1025. } else if (two->address.protocolVersion < Version_CURRENT_PROTOCOL) {
  1026. if (one->address.protocolVersion >= Version_CURRENT_PROTOCOL) {
  1027. return two;
  1028. }
  1029. }
  1030. }
  1031. if (Address_closest(&store->pub.selfNode->address, &one->address, &two->address) > 0) {
  1032. return one;
  1033. }
  1034. return two;
  1035. }
  1036. /**
  1037. * We define the worst node as either node which is furthest in address space
  1038. * from us which is either unreachable or, if no nodes are unreachable, has no
  1039. * nodes for which it is the bestParent.
  1040. * This metric will take into account both reach and address distance, although
  1041. * reach is not directly fed into the function but rather the function relies on
  1042. * the structure of the store which is affected by the reach.
  1043. * O(2n)
  1044. */
  1045. static struct Node_Two* getWorstNode(struct NodeStore_pvt* store)
  1046. {
  1047. struct Node_Two* worst = NULL;
  1048. struct Node_Two* nn = NULL;
  1049. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1050. // first cycle we clear all markings as we go and set markings
  1051. // so markings remain if they are behind us
  1052. nn->marked = 0;
  1053. if (nn->bestParent) {
  1054. nn->bestParent->parent->marked = 1;
  1055. } else if (!worst || whichIsWorse(nn, worst, store) == nn) {
  1056. // this time around we're only addressing nodes which are unreachable.
  1057. worst = nn;
  1058. }
  1059. }
  1060. if (worst) { return worst; }
  1061. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1062. // second cycle we set the markings as we go but if they are behind the
  1063. // node which would have marked them, they are already set.
  1064. if (nn->bestParent) {
  1065. nn->bestParent->parent->marked = 1;
  1066. }
  1067. if (nn->marked) { continue; }
  1068. if (!worst || whichIsWorse(nn, worst, store) == nn) {
  1069. worst = nn;
  1070. }
  1071. }
  1072. // somebody has to be at the end of the line, not *everyone* can be someone's best parent!
  1073. Assert_true(worst);
  1074. return worst;
  1075. }
  1076. static void destroyNode(struct Node_Two* node, struct NodeStore_pvt* store)
  1077. {
  1078. struct Node_Link* link;
  1079. RB_FOREACH(link, PeerRBTree, &node->peerTree) {
  1080. Identity_check(link);
  1081. unlinkNodes(link, store);
  1082. }
  1083. // optimization
  1084. #ifndef PARANOIA
  1085. node->bestParent = NULL;
  1086. node->address.path = UINT64_MAX;
  1087. #endif
  1088. link = node->reversePeers;
  1089. while (link) {
  1090. struct Node_Link* nextLink = link->nextPeer;
  1091. unlinkNodes(link, store);
  1092. link = nextLink;
  1093. }
  1094. Assert_true(!node->bestParent);
  1095. Assert_ifParanoid(node == RB_FIND(NodeRBTree, &store->nodeTree, node));
  1096. RB_REMOVE(NodeRBTree, &store->nodeTree, node);
  1097. store->pub.nodeCount--;
  1098. Allocator_free(node->alloc);
  1099. }
  1100. struct Node_Link* NodeStore_discoverNode(struct NodeStore* nodeStore,
  1101. struct Address* addr,
  1102. struct EncodingScheme* scheme,
  1103. int inverseLinkEncodingFormNumber,
  1104. uint32_t reach)
  1105. {
  1106. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1107. verify(store);
  1108. struct Node_Two* child = nodeForIp(store, addr->ip6.bytes);
  1109. #ifdef Log_DEBUG
  1110. uint8_t printedAddr[60];
  1111. Address_print(printedAddr, addr);
  1112. Log_debug(store->logger, "Discover node [%s]", printedAddr);
  1113. #endif
  1114. struct Allocator* alloc = NULL;
  1115. if (!child) {
  1116. alloc = Allocator_child(store->alloc);
  1117. child = Allocator_calloc(alloc, sizeof(struct Node_Two), 1);
  1118. child->alloc = alloc;
  1119. Bits_memcpyConst(&child->address, addr, sizeof(struct Address));
  1120. child->encodingScheme = EncodingScheme_clone(scheme, child->alloc);
  1121. Identity_set(child);
  1122. }
  1123. // False if someone just updated.
  1124. //Assert_true(child->address.protocolVersion);
  1125. //Assert_true(EncodingScheme_equals(scheme, child->encodingScheme));//TODO
  1126. struct Node_Link* link = discoverLink(store,
  1127. store->selfLink,
  1128. addr->path,
  1129. child,
  1130. addr->path,
  1131. inverseLinkEncodingFormNumber);
  1132. if (!link) {
  1133. if (alloc) {
  1134. Allocator_free(alloc);
  1135. }
  1136. verify(store);
  1137. Log_debug(store->logger, "Invalid path");
  1138. return NULL;
  1139. }
  1140. if (link->parent == store->pub.selfNode && !link->child->bestParent) {
  1141. updateBestParent(link->child, link, reach, store);
  1142. }
  1143. handleNews(link->child, reach, store);
  1144. freePendingLinks(store);
  1145. while (store->pub.nodeCount >= store->pub.nodeCapacity
  1146. || store->pub.linkCount >= store->pub.linkCapacity)
  1147. {
  1148. struct Node_Two* worst = getWorstNode(store);
  1149. #ifdef Log_DEBUG
  1150. uint8_t worstAddr[60];
  1151. Address_print(worstAddr, &worst->address);
  1152. Log_debug(store->logger, "store full, removing worst node: [%s] nodes [%d] links [%d]",
  1153. worstAddr, store->pub.nodeCount, store->pub.linkCount);
  1154. #endif
  1155. destroyNode(worst, store);
  1156. freePendingLinks(store);
  1157. }
  1158. verify(store);
  1159. return link;
  1160. }
  1161. struct Node_Two* NodeStore_nodeForAddr(struct NodeStore* nodeStore, uint8_t addr[16])
  1162. {
  1163. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1164. struct Node_Two* n = nodeForIp(store, addr);
  1165. if (n && n->address.path == UINT64_MAX) {
  1166. #ifdef Log_DEBUG
  1167. uint8_t addrStr[40];
  1168. AddrTools_printIp(addrStr, n->address.ip6.bytes);
  1169. Log_debug(store->logger, "No way to represent path to [%s]", addrStr);
  1170. #endif
  1171. return NULL;
  1172. }
  1173. return n;
  1174. }
  1175. struct Node_Two* NodeStore_closestNode(struct NodeStore* nodeStore, uint64_t path)
  1176. {
  1177. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1178. struct Node_Link* out = NULL;
  1179. findClosest(path, &out, NULL, store->selfLink, store);
  1180. if (!out) { return NULL; }
  1181. return Identity_check(out->child);
  1182. }
  1183. struct Node_Two* NodeStore_nodeForPath(struct NodeStore* nodeStore, uint64_t path)
  1184. {
  1185. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1186. struct Node_Link* out = NULL;
  1187. uint64_t pathParentChild = findClosest(path, &out, NULL, store->selfLink, store);
  1188. if (pathParentChild != 1) { return NULL; }
  1189. return Identity_check(out->child);
  1190. }
  1191. struct Node_Link* NodeStore_getLinkOnPath(struct NodeStore* nodeStore,
  1192. uint64_t routeLabel,
  1193. uint32_t hopNum)
  1194. {
  1195. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1196. struct Node_Link* link = NULL;
  1197. uint32_t num = hopNum;
  1198. uint64_t path = findClosest(routeLabel, &link, &num, store->selfLink, store);
  1199. if (path == findClosest_INVALID || num < hopNum) {
  1200. return NULL;
  1201. }
  1202. return link;
  1203. }
  1204. struct Node_Link* NodeStore_getLink(struct Node_Two* parent, uint32_t linkNum)
  1205. {
  1206. struct Node_Link* link = NULL;
  1207. RB_FOREACH_REVERSE(link, PeerRBTree, &parent->peerTree) {
  1208. if (!linkNum--) {
  1209. return link;
  1210. }
  1211. }
  1212. return NULL;
  1213. }
  1214. char* NodeStore_getRouteLabel_strerror(uint64_t returnVal)
  1215. {
  1216. switch (returnVal) {
  1217. case NodeStore_getRouteLabel_PARENT_NOT_FOUND:
  1218. return "NodeStore_getRouteLabel_PARENT_NOT_FOUND";
  1219. case NodeStore_getRouteLabel_CHILD_NOT_FOUND:
  1220. return "NodeStore_getRouteLabel_CHILD_NOT_FOUND";
  1221. default: return NULL;
  1222. }
  1223. }
  1224. uint64_t NodeStore_getRouteLabel(struct NodeStore* nodeStore,
  1225. uint64_t pathToParent,
  1226. uint64_t pathParentToChild)
  1227. {
  1228. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1229. struct Node_Link* linkToParent;
  1230. if (findClosest(pathToParent, &linkToParent, NULL, store->selfLink, store) != 1) {
  1231. return NodeStore_getRouteLabel_PARENT_NOT_FOUND;
  1232. }
  1233. logLink(store, linkToParent, "NodeStore_getRouteLabel() PARENT");
  1234. struct Node_Link* linkToChild = NULL;
  1235. RB_FOREACH_REVERSE(linkToChild, PeerRBTree, &linkToParent->child->peerTree) {
  1236. if (pathParentToChild == linkToChild->cannonicalLabel) {
  1237. if (linkToParent == store->selfLink) {
  1238. return linkToChild->cannonicalLabel;
  1239. }
  1240. return extendRoute(pathToParent,
  1241. linkToChild->parent->encodingScheme,
  1242. linkToChild->cannonicalLabel,
  1243. linkToParent->inverseLinkEncodingFormNumber);
  1244. }
  1245. }
  1246. return NodeStore_getRouteLabel_CHILD_NOT_FOUND;
  1247. }
  1248. uint64_t NodeStore_optimizePath(struct NodeStore* nodeStore, uint64_t path)
  1249. {
  1250. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1251. struct Node_Link* linkToParent;
  1252. uint64_t next = findClosest(path, &linkToParent, NULL, store->selfLink, store);
  1253. if (next == findClosest_INVALID) {
  1254. return NodeStore_optimizePath_INVALID;
  1255. }
  1256. if (linkToParent == store->selfLink) {
  1257. if (next == 1) { return 1; }
  1258. return path;
  1259. }
  1260. if (next == 1) { return linkToParent->child->address.path; }
  1261. if (linkToParent->child->bestParent) {
  1262. linkToParent = linkToParent->child->bestParent;
  1263. }
  1264. uint64_t optimized = extendRoute(linkToParent->child->address.path,
  1265. linkToParent->child->encodingScheme,
  1266. next,
  1267. linkToParent->inverseLinkEncodingFormNumber);
  1268. if (optimized < UINT64_MAX) {
  1269. return optimized;
  1270. }
  1271. return path;
  1272. }
  1273. uint32_t NodeStore_linkCount(struct Node_Two* node)
  1274. {
  1275. uint32_t i = 0;
  1276. struct Node_Link* link;
  1277. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  1278. i++;
  1279. }
  1280. return i;
  1281. }
  1282. /** See: NodeStore.h */
  1283. struct NodeStore* NodeStore_new(struct Address* myAddress,
  1284. const uint32_t capacity,
  1285. struct Allocator* allocator,
  1286. struct Log* logger)
  1287. {
  1288. struct Allocator* alloc = Allocator_child(allocator);
  1289. struct NodeStore_pvt* out = Allocator_clone(alloc, (&(struct NodeStore_pvt) {
  1290. .pub = {
  1291. .nodeCapacity = NodeStore_DEFAULT_NODE_CAPACITY,
  1292. .linkCapacity = NodeStore_DEFAULT_LINK_CAPACITY
  1293. },
  1294. .capacity = capacity,
  1295. .logger = logger,
  1296. .alloc = alloc
  1297. }));
  1298. Identity_set(out);
  1299. // Create the self node
  1300. struct Node_Two* selfNode = Allocator_calloc(alloc, sizeof(struct Node_Two), 1);
  1301. Bits_memcpyConst(&selfNode->address, myAddress, sizeof(struct Address));
  1302. selfNode->encodingScheme = NumberCompress_defineScheme(alloc);
  1303. selfNode->alloc = alloc;
  1304. Identity_set(selfNode);
  1305. out->pub.selfNode = selfNode;
  1306. selfNode->bestParent = linkNodes(selfNode, selfNode, 1, 0xffffffffu, 0, 1, out);
  1307. selfNode->address.path = 1;
  1308. setReach(selfNode, UINT32_MAX);
  1309. out->selfLink = selfNode->reversePeers;
  1310. RB_INSERT(NodeRBTree, &out->nodeTree, selfNode);
  1311. out->pub.selfAddress = &out->selfLink->child->address;
  1312. return &out->pub;
  1313. }
  1314. //////////////////////////////////////////////////////////////////////////////////////////////
  1315. //////////////////////////////////////////////////////////////////////////////////////////////
  1316. //////////////////////////////////////////////////////////////////////////////////////////////
  1317. /**
  1318. * Dump the table, one node at a time.
  1319. */
  1320. struct Node_Two* NodeStore_dumpTable(struct NodeStore* nodeStore, uint32_t index)
  1321. {
  1322. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1323. // TODO: Schlameil the painter
  1324. uint32_t i = 0;
  1325. struct Node_Two* nn = NULL;
  1326. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1327. if (i++ == index) { return nn; }
  1328. }
  1329. return NULL;
  1330. }
  1331. static struct Node_Two* getBestCycleB(struct Node_Two* node,
  1332. struct Address* target,
  1333. struct NodeStore_pvt* store)
  1334. {
  1335. uint32_t targetPfx = Address_getPrefix(target);
  1336. uint32_t ourDistance = Address_getPrefix(store->pub.selfAddress) ^ targetPfx;
  1337. struct Node_Link* next = NULL;
  1338. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  1339. if (next->child->bestParent != next || next == store->selfLink) { continue; }
  1340. if (next->child->address.path == UINT64_MAX) { continue; }
  1341. if ((Address_getPrefix(&next->child->address) ^ targetPfx) >= ourDistance) { continue; }
  1342. return next->child;
  1343. }
  1344. return NULL;
  1345. }
  1346. static int getBestCycle(struct Node_Two* node,
  1347. struct Address* target,
  1348. struct Node_Two** output,
  1349. int limit,
  1350. int cycle,
  1351. struct NodeStore_pvt* store)
  1352. {
  1353. Assert_always(cycle < 1000);
  1354. if (cycle < limit) {
  1355. int total = 0;
  1356. struct Node_Link* next = NULL;
  1357. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  1358. if (*output) { return total; }
  1359. if (next->child->bestParent != next || next == store->selfLink) { continue; }
  1360. total += getBestCycle(next->child, target, output, limit, cycle+1, store);
  1361. }
  1362. return total;
  1363. }
  1364. *output = getBestCycleB(node, target, store);
  1365. return 1;
  1366. }
  1367. struct Node_Two* NodeStore_getBest(struct Address* targetAddress, struct NodeStore* nodeStore)
  1368. {
  1369. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1370. struct Node_Two* n = NodeStore_nodeForAddr(nodeStore, targetAddress->ip6.bytes);
  1371. if (n && n->bestParent) { return n; }
  1372. for (int i = 0; i < 10000; i++) {
  1373. int ret = getBestCycle(store->pub.selfNode, targetAddress, &n, i, 0, store);
  1374. if (n || !ret) { return n; }
  1375. }
  1376. return NULL;
  1377. }
  1378. struct NodeList* NodeStore_getPeers(uint64_t label,
  1379. const uint32_t max,
  1380. struct Allocator* allocator,
  1381. struct NodeStore* nodeStore)
  1382. {
  1383. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1384. // truncate the label to the part which this node uses...
  1385. label &= Bits_maxBits64(NumberCompress_bitsUsedForLabel(label));
  1386. struct NodeList* out = Allocator_calloc(allocator, sizeof(struct NodeList), 1);
  1387. out->nodes = Allocator_calloc(allocator, sizeof(char*), max);
  1388. struct Node_Link* next = NULL;
  1389. RB_FOREACH_REVERSE(next, PeerRBTree, &store->pub.selfNode->peerTree) {
  1390. uint64_t p = next->child->address.path;
  1391. if (p > (((uint64_t)1)<<63)) { continue; }
  1392. int j;
  1393. for (j = 0; j < (int)max; j++) {
  1394. if (out->nodes[j] && (out->nodes[j]->address.path ^ label) < (p ^ label)) {
  1395. break;
  1396. }
  1397. }
  1398. switch (j) {
  1399. default: Bits_memmove(out->nodes, &out->nodes[1], (j - 1) * sizeof(char*));
  1400. case 1: out->nodes[j - 1] = next->child;
  1401. case 0:;
  1402. }
  1403. }
  1404. out->size = 0;
  1405. for (int i = 0; i < (int)max; i++) {
  1406. if (out->nodes[i]) {
  1407. out->nodes = &out->nodes[i];
  1408. out->size = max - i;
  1409. break;
  1410. }
  1411. }
  1412. for (int i = 0; i < (int)out->size; i++) {
  1413. Identity_check(out->nodes[i]);
  1414. checkNode(out->nodes[i], store);
  1415. Assert_true(out->nodes[i]->address.path);
  1416. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1417. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1418. }
  1419. return out;
  1420. }
  1421. static bool isOkAnswer(struct Node_Two* node,
  1422. uint32_t compatVer,
  1423. struct NodeStore_pvt* store)
  1424. {
  1425. if (node->address.path == UINT64_MAX) {
  1426. // (very) unreachable
  1427. return false;
  1428. }
  1429. if (!Version_isCompatible(compatVer, node->address.protocolVersion)) {
  1430. return false;
  1431. }
  1432. if (node == store->pub.selfNode) {
  1433. return false;
  1434. }
  1435. return true;
  1436. }
  1437. /** See: NodeStore.h */
  1438. struct NodeList* NodeStore_getClosestNodes(struct NodeStore* nodeStore,
  1439. struct Address* targetAddress,
  1440. const uint32_t count,
  1441. uint32_t compatVer,
  1442. struct Allocator* allocator)
  1443. {
  1444. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1445. struct NodeList* out = Allocator_malloc(allocator, sizeof(struct NodeList));
  1446. out->nodes = Allocator_calloc(allocator, count, sizeof(char*));
  1447. out->size = count;
  1448. struct Node_Two fakeNode = { .marked = 0 };
  1449. Bits_memcpyConst(&fakeNode.address, targetAddress, sizeof(struct Address));
  1450. struct Node_Two* next = Identity_ncheck(RB_NFIND(NodeRBTree, &store->nodeTree, &fakeNode));
  1451. if (!next) {
  1452. out->size = 0;
  1453. return out;
  1454. }
  1455. struct Node_Two* prev = Identity_ncheck(NodeRBTree_RB_PREV(next));
  1456. int idx = out->size-1;
  1457. while (idx > -1) {
  1458. if (prev && (!next || Address_closest(targetAddress, &next->address, &prev->address) > 0)) {
  1459. if (isOkAnswer(prev, compatVer, store)) { out->nodes[idx--] = prev; }
  1460. prev = Identity_ncheck(NodeRBTree_RB_PREV(prev));
  1461. continue;
  1462. }
  1463. if (next && (!prev || Address_closest(targetAddress, &next->address, &prev->address) < 0)) {
  1464. if (isOkAnswer(next, compatVer, store)) { out->nodes[idx--] = next; }
  1465. next = Identity_ncheck(NodeRBTree_RB_NEXT(next));
  1466. continue;
  1467. }
  1468. break;
  1469. }
  1470. out->nodes = &out->nodes[idx+1];
  1471. out->size -= idx+1;
  1472. for (int i = 0; i < (int)out->size; i++) {
  1473. Identity_check(out->nodes[i]);
  1474. Assert_true(out->nodes[i]->address.path);
  1475. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1476. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1477. }
  1478. return out;
  1479. }
  1480. void NodeStore_updateReach(struct NodeStore* nodeStore, struct Node_Two* node, uint32_t newReach)
  1481. {
  1482. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1483. handleNews(node, newReach, store);
  1484. }
  1485. void NodeStore_brokenPath(uint64_t path, struct NodeStore* nodeStore)
  1486. {
  1487. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1488. verify(store);
  1489. #ifdef Log_DEBUG
  1490. uint8_t pathStr[20];
  1491. AddrTools_printPath(pathStr, path);
  1492. Log_debug(store->logger, "NodeStore_brokenPath(%s)", pathStr);
  1493. #endif
  1494. struct Node_Two* nn = NodeStore_nodeForPath(nodeStore, path);
  1495. if (nn && Node_getReach(nn) > 0) {
  1496. handleBadNews(nn, 0, store);
  1497. }
  1498. verify(store);
  1499. }