NodeStore.c 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180
  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 "dht/Address.h"
  16. #include "dht/dhtcore/Node.h"
  17. #include "dht/dhtcore/NodeStore.h"
  18. #include "dht/dhtcore/NodeList.h"
  19. #include "util/AddrTools.h"
  20. #include "util/Assert.h"
  21. #include "util/Bits.h"
  22. #include "util/log/Log.h"
  23. #include "util/version/Version.h"
  24. #include "switch/NumberCompress.h"
  25. #include "switch/LabelSplicer.h"
  26. #include "util/Gcc.h"
  27. #include "util/Defined.h"
  28. #include <tree.h>
  29. /** A list of DHT nodes. */
  30. struct NodeStore_pvt
  31. {
  32. struct NodeStore pub;
  33. /** A fake link where we are both the parent and child. */
  34. struct Node_Link* selfLink;
  35. /** A tree containing all nodes ordered by ipv6 */
  36. struct NodeRBTree {
  37. struct Node_Two* rbh_root;
  38. } nodeTree;
  39. struct Allocator* alloc;
  40. /**
  41. * The links to be freed next time freePendingLinks() is called.
  42. */
  43. struct Node_Link* linksToFree;
  44. /** Nodes which have very likely been reset. */
  45. struct RumorMill* renumberMill;
  46. /** The means for this node store to log. */
  47. struct Log* logger;
  48. Identity
  49. };
  50. // My memory is really bad
  51. #define A_COMES_FIRST 1
  52. #define B_COMES_FIRST -1
  53. static int comparePeers(const struct Node_Link* la, const struct Node_Link* lb)
  54. {
  55. Identity_check(lb);
  56. uint64_t a = la->cannonicalLabel;
  57. uint64_t b = lb->cannonicalLabel;
  58. int log2Diff = Bits_log2x64(b) - Bits_log2x64(a);
  59. if (log2Diff) {
  60. return log2Diff;
  61. }
  62. if (Bits_bitReverse64(a) < Bits_bitReverse64(b)) {
  63. return A_COMES_FIRST;
  64. } else if (a == b) {
  65. return 0;
  66. }
  67. return B_COMES_FIRST;
  68. }
  69. RB_GENERATE_STATIC(PeerRBTree, Node_Link, peerTree, comparePeers)
  70. static int compareNodes(const struct Node_Two* na, const struct Node_Two* nb)
  71. {
  72. Identity_check(nb);
  73. int ret;
  74. ret = Address_xorcmp(0, na->address.ip6.ints.one_be, nb->address.ip6.ints.one_be);
  75. if (ret) { return ret; }
  76. ret = Address_xorcmp(0, na->address.ip6.ints.two_be, nb->address.ip6.ints.two_be);
  77. if (ret) { return ret; }
  78. ret = Address_xorcmp(0, na->address.ip6.ints.three_be, nb->address.ip6.ints.three_be);
  79. if (ret) { return ret; }
  80. ret = Address_xorcmp(0, na->address.ip6.ints.four_be, nb->address.ip6.ints.four_be);
  81. return ret;
  82. }
  83. RB_GENERATE_STATIC(NodeRBTree, Node_Two, nodeTree, compareNodes)
  84. static void freeLink(struct Node_Link* link, struct NodeStore_pvt* store)
  85. {
  86. Allocator_realloc(store->alloc, link, 0);
  87. store->pub.linkCount--;
  88. }
  89. static struct Node_Link* getLink(struct NodeStore_pvt* store)
  90. {
  91. store->pub.linkCount++;
  92. return Allocator_calloc(store->alloc, sizeof(struct Node_Link), 1);
  93. }
  94. static void logLink(struct NodeStore_pvt* store,
  95. struct Node_Link* link,
  96. char* message)
  97. {
  98. if (!Defined(Log_DEBUG)) {
  99. return;
  100. }
  101. uint8_t parent[40];
  102. uint8_t child[40];
  103. AddrTools_printIp(parent, link->parent->address.ip6.bytes);
  104. AddrTools_printIp(child, link->child->address.ip6.bytes);
  105. uint8_t path[20];
  106. AddrTools_printPath(path, link->cannonicalLabel);
  107. Log_debug(store->logger, "link[%s]->[%s] [%s] %s", parent, child, path, message);
  108. }
  109. static void _checkNode(struct Node_Two* node, struct NodeStore_pvt* store, char* file, int line)
  110. {
  111. if (!Defined(PARANOIA)) {
  112. return;
  113. }
  114. Assert_true(node->address.path ==
  115. EncodingScheme_convertLabel(store->pub.selfNode->encodingScheme,
  116. node->address.path,
  117. EncodingScheme_convertLabel_convertTo_CANNONICAL));
  118. struct Node_Link* link;
  119. for (link = node->reversePeers; link; link = link->nextPeer) {
  120. Assert_fileLine(link->child == node, file, line);
  121. Assert_fileLine(RB_FIND(PeerRBTree, &link->parent->peerTree, link) == link, file, line);
  122. // This is for you arc
  123. int ok = 0;
  124. struct Node_Link* nl = NULL;
  125. while ((nl = NodeStore_nextLink(link->parent, nl))) {
  126. if (nl == link) { ok = 1; break; }
  127. }
  128. Assert_fileLine(ok, file, line);
  129. //
  130. }
  131. struct Node_Link* lastLink = NULL;
  132. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  133. Assert_fileLine(!EncodingScheme_isSelfRoute(link->parent->encodingScheme,
  134. link->cannonicalLabel)
  135. || link == store->selfLink,
  136. file, line);
  137. Assert_fileLine(Node_getBestParent(node) || Node_getBestParent(link->child) != link,
  138. file, line);
  139. Assert_fileLine(link->parent == node, file, line);
  140. Assert_fileLine(link->child != node || link == store->selfLink, file, line);
  141. Assert_fileLine(!lastLink || link->cannonicalLabel != lastLink->cannonicalLabel,
  142. file, line);
  143. Assert_fileLine(link->cannonicalLabel < UINT64_MAX && link->cannonicalLabel > 0,
  144. file, line);
  145. // Make sure there isn't a link which has a completely wacky link encoding number.
  146. // Also make sure links are all flushed if a node is discovered to have changed it's
  147. // encoding scheme...
  148. Assert_fileLine(link->inverseLinkEncodingFormNumber < link->child->encodingScheme->count,
  149. file, line);
  150. struct Node_Link* rlink = NULL;
  151. for (rlink = link->child->reversePeers; rlink; rlink = rlink->nextPeer) {
  152. if (rlink == link) {
  153. break;
  154. }
  155. }
  156. Assert_fileLine(rlink && "child contains reverse link", file, line);
  157. lastLink = link;
  158. }
  159. if (Node_getBestParent(node)) {
  160. Assert_fileLine(Node_getReach(Node_getBestParent(node)->parent) > Node_getReach(node)
  161. || node == store->pub.selfNode, file, line);
  162. Assert_fileLine(node->address.path != UINT64_MAX, file, line);
  163. Assert_fileLine(Node_getReach(node) > 0, file, line);
  164. struct Node_Two* nn = node;
  165. do {
  166. Assert_fileLine(
  167. LabelSplicer_routesThrough(nn->address.path,
  168. Node_getBestParent(nn)->parent->address.path),
  169. file,
  170. line
  171. );
  172. nn = Node_getBestParent(nn)->parent;
  173. } while (nn != store->pub.selfNode);
  174. } else {
  175. Assert_fileLine(node->address.path == UINT64_MAX, file, line);
  176. Assert_fileLine(Node_getReach(node) == 0, file, line);
  177. }
  178. }
  179. #define checkNode(node, store) _checkNode(node, store, Gcc_SHORT_FILE, Gcc_LINE)
  180. static void _verifyNode(struct Node_Two* node, struct NodeStore_pvt* store, char* file, int line)
  181. {
  182. if (!Defined(PARANOIA)) {
  183. return;
  184. }
  185. // #1 check the node (do the basic checks)
  186. _checkNode(node, store, file, line);
  187. // #2 make sure all of the node's outgoing links are split properly
  188. struct Node_Link* link = NULL;
  189. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  190. // make sure any peers of this node are split properly
  191. struct Node_Link* linkB = link;
  192. struct Node_Link* linkC = link;
  193. RB_FOREACH_REVERSE_FROM(linkB, PeerRBTree, linkC) {
  194. if (linkB == link || link == store->selfLink) { continue; }
  195. Assert_fileLine(
  196. !LabelSplicer_routesThrough(linkB->cannonicalLabel, link->cannonicalLabel),
  197. file, line
  198. );
  199. }
  200. Assert_true(!link->nextInSplitList);
  201. }
  202. // #3 make sure looking for the node by address will actually find the correct node.
  203. if (Node_getBestParent(node)) {
  204. Assert_fileLine(node == NodeStore_closestNode(&store->pub, node->address.path), file, line);
  205. }
  206. // #4 no persistant markings are allowed.
  207. Assert_true(!node->marked);
  208. }
  209. #define verifyNode(node, store) _verifyNode(node, store, Gcc_SHORT_FILE, Gcc_LINE)
  210. // Verify is more thorough than check because it makes sure all links are split properly.
  211. static void _verify(struct NodeStore_pvt* store, char* file, int line)
  212. {
  213. if (!Defined(PARANOIA)) {
  214. return;
  215. }
  216. Assert_true(Node_getBestParent(store->pub.selfNode) == store->selfLink || !store->selfLink);
  217. int linkedNodes = 0;
  218. struct Node_Two* nn = NULL;
  219. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  220. _verifyNode(nn, store, file, line);
  221. if (Node_getBestParent(nn)) { linkedNodes++; }
  222. }
  223. Assert_fileLine(linkedNodes == store->pub.linkedNodes, file, line);
  224. }
  225. #define verify(store) _verify(store, Gcc_SHORT_FILE, Gcc_LINE)
  226. static void _check(struct NodeStore_pvt* store, char* file, int line)
  227. {
  228. if (!Defined(PARANOIA)) {
  229. return;
  230. }
  231. Assert_true(Node_getBestParent(store->pub.selfNode) == store->selfLink || !store->selfLink);
  232. struct Node_Two* nn = NULL;
  233. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  234. _checkNode(nn, store, file, line);
  235. }
  236. }
  237. #define check(store) _check(store, Gcc_SHORT_FILE, Gcc_LINE)
  238. /**
  239. * Extend a route by splicing on another link.
  240. * This will modify the Encoding Form of the first Director in next section of the route to make
  241. * it's size greater than or equal to the size of the return route through the parent node in the
  242. * link.
  243. *
  244. * @param routeToParent the label for reaching the parent node
  245. * @param parentScheme the label encoding scheme used by the parent node
  246. * @param routeParentToChild the cannonicalLabel for the link from parent to child
  247. * @param previousLinkEncoding the encoding used for the parent's interface back to the grandparent
  248. * @return a converted/spliced label or extendRoute_INVALID if it happens that the parent
  249. * or ~0 if the label is too long to represent.
  250. */
  251. #define extendRoute_INVALID (((uint64_t)~0)-1)
  252. static uint64_t extendRoute(uint64_t routeToParent,
  253. struct EncodingScheme* parentScheme,
  254. uint64_t routeParentToChild,
  255. int previousLinkEncoding)
  256. {
  257. Assert_true(routeParentToChild != EncodingScheme_convertLabel_INVALID);
  258. // Make sure they didn't send us a 'silly' route.
  259. int nextLinkEncoding = EncodingScheme_getFormNum(parentScheme, routeParentToChild);
  260. if (nextLinkEncoding == EncodingScheme_getFormNum_INVALID) { return extendRoute_INVALID; }
  261. // If the encoding to get to the parent uses more bits than the encoding to get from parent
  262. // to child, we need to change the encoding...
  263. if (previousLinkEncoding > nextLinkEncoding) {
  264. routeParentToChild =
  265. EncodingScheme_convertLabel(parentScheme, routeParentToChild, previousLinkEncoding);
  266. Assert_true(routeParentToChild != EncodingScheme_convertLabel_INVALID);
  267. }
  268. return LabelSplicer_splice(routeParentToChild, routeToParent);
  269. }
  270. static void update(struct Node_Link* link,
  271. int64_t linkStateDiff,
  272. struct NodeStore_pvt* store)
  273. {
  274. if (linkStateDiff + link->linkState > UINT32_MAX) {
  275. link->linkState = UINT32_MAX;
  276. logLink(store, link, "link state set to maximum");
  277. } else if (linkStateDiff + link->linkState < 0) {
  278. link->linkState = 0;
  279. logLink(store, link, "link state set to zero");
  280. } else {
  281. link->linkState += linkStateDiff;
  282. }
  283. }
  284. static bool isPeer(struct Node_Two* node, struct NodeStore_pvt* store)
  285. {
  286. if (!Node_getBestParent(node)) { return false; }
  287. return Node_getBestParent(node)->parent == store->pub.selfNode
  288. && LabelSplicer_isOneHop(Node_getBestParent(node)->cannonicalLabel);
  289. }
  290. static void unreachable(struct Node_Two* node, struct NodeStore_pvt* store)
  291. {
  292. struct Node_Link* next = NULL;
  293. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  294. if (Node_getBestParent(next->child) == next) { unreachable(next->child, store); }
  295. }
  296. // We think the link is down, so reset the link state.
  297. struct Node_Link* bp = Node_getBestParent(node);
  298. if (bp) {
  299. update(bp, -UINT32_MAX, store);
  300. store->pub.linkedNodes--;
  301. }
  302. Node_setParentReachAndPath(node, NULL, 0, UINT64_MAX);
  303. }
  304. /** Adds the reach of path A->B to path B->C to get the expected reach of A->C. */
  305. static uint32_t addReach(uint32_t reachAB, uint32_t reachBC)
  306. {
  307. uint64_t b = reachAB;
  308. uint64_t c = reachBC;
  309. uint64_t reachAC = (b * c) / (b + c);
  310. if (reachAC > UINT32_MAX) { return UINT32_MAX; }
  311. return reachAC;
  312. }
  313. /** Subtracts the reach of path A->B from path A->B->C, to get reach of B->C. */
  314. static uint32_t subReach(uint32_t reachAB, uint32_t reachAC)
  315. {
  316. if (reachAB <= reachAC) { return UINT32_MAX; }
  317. uint64_t b = reachAB;
  318. uint64_t c = reachAC;
  319. uint64_t reachBC = (b * c) / (b - c);
  320. if (reachBC > UINT32_MAX) { return UINT32_MAX; }
  321. return reachBC;
  322. }
  323. /**
  324. * This is called when we have no idea what the reach should be for the next hop
  325. * because the path we previously used to get to it is broken and we need to use
  326. * a different one. Take a somewhat educated guess as to what it might be in a way
  327. * that will make the reach non-zero.
  328. */
  329. static uint32_t guessReachOfChild(struct Node_Link* link)
  330. {
  331. uint32_t r;
  332. if (LabelSplicer_isOneHop(link->cannonicalLabel)) {
  333. // Single-hop link, so guess that it's 3/4 the parent's reach
  334. r = (Node_getReach(link->parent) * 3) / 4;
  335. }
  336. else {
  337. // Multi-hop link, so let's assume 1/2 the parent's reach.
  338. r = Node_getReach(link->parent) / 2;
  339. }
  340. if (r < (1<<12)) {
  341. r = Node_getReach(link->parent) - 1;
  342. } else if (r < (1<<16)) {
  343. r = Node_getReach(link->parent) - Bits_log2x64(link->cannonicalLabel);
  344. }
  345. // Educated guess, parent's latency + link's latency (neither of which is known perfectly).
  346. uint32_t guess = addReach(Node_getReach(link->parent), link->linkState);
  347. if (guess < Node_getReach(link->parent) && guess > r) {
  348. // Our guess is sensible, so use it.
  349. r = guess;
  350. }
  351. Assert_true(r < Node_getReach(link->parent) && r != 0);
  352. return r;
  353. }
  354. static int updateBestParentCycle(struct Node_Link* newBestLink,
  355. int cycle,
  356. int limit,
  357. uint32_t nextReach,
  358. struct NodeStore_pvt* store)
  359. {
  360. Assert_true(cycle < 1000);
  361. struct Node_Two* node = newBestLink->child;
  362. if (cycle < limit) {
  363. int total = 0;
  364. struct Node_Link* next = NULL;
  365. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  366. if (Node_getBestParent(next->child) == next && next->child != node) {
  367. total += updateBestParentCycle(next, cycle+1, limit, nextReach, store);
  368. }
  369. }
  370. return total;
  371. }
  372. struct Node_Two* newBest = newBestLink->parent;
  373. uint64_t bestPath = extendRoute(newBest->address.path,
  374. newBest->encodingScheme,
  375. newBestLink->cannonicalLabel,
  376. Node_getBestParent(newBest)->inverseLinkEncodingFormNumber);
  377. if (bestPath == UINT64_MAX) {
  378. // too long to splice.
  379. unreachable(node, store);
  380. return 1;
  381. }
  382. Assert_true(bestPath != extendRoute_INVALID);
  383. /*if (Defined(Log_DEBUG)) {
  384. if (node->address.path != bestPath) {
  385. uint8_t pathStr[20];
  386. AddrTools_printPath(pathStr, bestPath);
  387. uint8_t addrStr[40];
  388. AddrTools_printIp(addrStr, node->address.ip6.bytes);
  389. Log_debug(store->logger, "New best path [%s@%s]", addrStr, pathStr);
  390. }
  391. }*/
  392. if (limit) {
  393. // We're only altering the reach of the top node in the chain.
  394. // If we want to deduce reach of further nodes along the path, here's the place.
  395. nextReach = Node_getReach(node);
  396. }
  397. if (!Node_getBestParent(node)) { store->pub.linkedNodes++; }
  398. Node_setParentReachAndPath(node, newBestLink, nextReach, bestPath);
  399. checkNode(node, store);
  400. return 1;
  401. }
  402. /**
  403. * Update the best parent of this node.
  404. * propigating path changes out through the tree.
  405. *
  406. * @param newBestParent the new best link to the node. The affected node is newBestParent->child.
  407. * @param nextReach the reach to set the node to.
  408. * @param store the nodestore.
  409. */
  410. static void updateBestParent(struct Node_Link* newBestParent,
  411. uint32_t nextReach,
  412. struct NodeStore_pvt* store)
  413. {
  414. check(store);
  415. Assert_true(newBestParent);
  416. for (int i = 0; i < 10000; i++) {
  417. if (!updateBestParentCycle(newBestParent, 0, i, nextReach, store)) {
  418. check(store);
  419. return;
  420. }
  421. }
  422. Assert_true(0);
  423. }
  424. static void handleGoodNews(struct Node_Two* node,
  425. uint32_t newReach,
  426. struct NodeStore_pvt* store)
  427. {
  428. // TODO(cjd): Paths longer than 1024 will blow up, handle more gracefully
  429. Assert_true(newReach != UINT32_MAX);
  430. Assert_true(newReach > Node_getReach(node));
  431. // The nodestore thinks it's unreachable, we can't very well update the reach.
  432. if (Node_getBestParent(node) == NULL) { return; }
  433. struct Node_Two* bp = Node_getBestParent(node)->parent;
  434. if (newReach+1 > Node_getReach(bp)) {
  435. handleGoodNews(bp, newReach+1, store);
  436. }
  437. Node_setReach(node, newReach);
  438. struct Node_Link* link = NULL;
  439. RB_FOREACH_REVERSE(link, PeerRBTree, &node->peerTree) {
  440. Identity_check(link);
  441. struct Node_Two* child = link->child;
  442. struct Node_Link* childBestParent = Node_getBestParent(child);
  443. if (!childBestParent || Node_getReach(childBestParent->parent) < newReach) {
  444. uint32_t nextReach = guessReachOfChild(link);
  445. if (Node_getReach(child) > nextReach) { continue; }
  446. updateBestParent(link, nextReach, store);
  447. }
  448. }
  449. }
  450. /**
  451. * The news has hit (in handleBadNewsOne) and now all of the nodes in the affected zone have
  452. * been knocked down. Now lets see if there's a better path for any of them.
  453. */
  454. static void handleBadNewsTwo(struct Node_Link* link, struct NodeStore_pvt* store, bool firstCall)
  455. {
  456. struct Node_Link* next = NULL;
  457. RB_FOREACH_REVERSE(next, PeerRBTree, &link->child->peerTree) {
  458. if (!next) { continue; }
  459. if (Node_getBestParent(next->child) != next) { continue; }
  460. if (next == store->selfLink) { continue; }
  461. handleBadNewsTwo(next, store, false);
  462. }
  463. if (firstCall) { return; }
  464. Assert_true(Node_getBestParent(link->child) == link);
  465. struct Node_Two* node = link->child;
  466. struct Node_Link* rp = link->child->reversePeers;
  467. struct Node_Link* best = Node_getBestParent(node);
  468. while (rp) {
  469. if (rp->linkState && Node_getReach(rp->parent) >= Node_getReach(best->parent)) {
  470. if (Node_getReach(rp->parent) > Node_getReach(best->parent)
  471. || rp->parent->address.path < best->parent->address.path)
  472. {
  473. best = rp;
  474. }
  475. }
  476. rp = rp->nextPeer;
  477. }
  478. if (best == Node_getBestParent(node)) { return; }
  479. uint32_t nextReach = guessReachOfChild(best);
  480. if (nextReach <= Node_getReach(node)) { return; }
  481. Assert_true(Node_getReach(node) < Node_getReach(best->parent));
  482. check(store);
  483. updateBestParent(best, nextReach, store);
  484. check(store);
  485. }
  486. /**
  487. * First thing we do is knock down everybody's reach.
  488. * This way they don't all cling to eachother for safety making
  489. * endless routing loops and stupid processing.
  490. */
  491. static void handleBadNewsOne(struct Node_Link* link,
  492. uint32_t newReach,
  493. struct NodeStore_pvt* store)
  494. {
  495. struct Node_Link* next = NULL;
  496. RB_FOREACH_REVERSE(next, PeerRBTree, &link->child->peerTree) {
  497. if (Node_getBestParent(next->child) != next) { continue; }
  498. if (next == store->selfLink) { continue; }
  499. if (Node_getReach(next->child) < newReach) { continue; }
  500. handleBadNewsOne(next, newReach ? (newReach - 1) : 0, store);
  501. }
  502. Assert_true(link->child != store->pub.selfNode);
  503. if (!newReach) {
  504. unreachable(link->child, store);
  505. } else {
  506. Node_setReach(link->child, newReach);
  507. }
  508. }
  509. static void handleBadNews(struct Node_Two* node,
  510. uint32_t newReach,
  511. struct NodeStore_pvt* store)
  512. {
  513. Assert_true(newReach < Node_getReach(node));
  514. // might be destroyed by handleBadNewsOne()
  515. struct Node_Link* bp = Node_getBestParent(node);
  516. // no bestParent implies a reach of 0
  517. Assert_true(bp && bp != store->selfLink);
  518. handleBadNewsOne(bp, newReach, store);
  519. check(store);
  520. handleBadNewsTwo(bp, store, true);
  521. check(store);
  522. }
  523. static void handleNews(struct Node_Two* node, uint32_t newReach, struct NodeStore_pvt* store)
  524. {
  525. // This is because reach is used to prevent loops so it must be 1 more for each hop closer
  526. // to the root.
  527. if (newReach > (UINT32_MAX - 1024)) { newReach = (UINT32_MAX - 1024); }
  528. check(store);
  529. if (newReach < Node_getReach(node)) {
  530. handleBadNews(node, newReach, store);
  531. check(store);
  532. } else if (newReach > Node_getReach(node)) {
  533. handleGoodNews(node, newReach, store);
  534. check(store);
  535. }
  536. }
  537. void NodeStore_unlinkNodes(struct NodeStore* nodeStore, struct Node_Link* link)
  538. {
  539. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*) nodeStore);
  540. struct Node_Two* child = Identity_check(link->child);
  541. struct Node_Two* parent = Identity_check(link->parent);
  542. check(store);
  543. if (parent == store->pub.selfNode) {
  544. // yuh ok
  545. if (link == store->selfLink) { return; }
  546. Assert_true(LabelSplicer_isOneHop(link->cannonicalLabel));
  547. store->pub.peerCount--;
  548. if (Defined(Log_INFO)) {
  549. uint8_t addr[60];
  550. Address_print(addr, &child->address);
  551. Log_info(store->logger, "Direct peer [%s] has been unlinked", addr);
  552. }
  553. }
  554. // Change the best parent and path if necessary
  555. if (Node_getBestParent(child) == link) {
  556. handleBadNews(child, 0, store);
  557. }
  558. if (Node_getBestParent(child) == link) {
  559. unreachable(child, store);
  560. }
  561. check(store);
  562. // Remove the entry from the reversePeers
  563. struct Node_Link* current = child->reversePeers;
  564. struct Node_Link** currentP = &child->reversePeers;
  565. while (current) {
  566. if (current == link) {
  567. *currentP = current->nextPeer;
  568. break;
  569. }
  570. currentP = &(current->nextPeer);
  571. current = *currentP;
  572. }
  573. Assert_true(current);
  574. // Remove the RBTree entry
  575. Assert_ifParanoid(link == RB_FIND(PeerRBTree, &parent->peerTree, link));
  576. RB_REMOVE(PeerRBTree, &parent->peerTree, link);
  577. link->nextPeer = store->linksToFree;
  578. store->linksToFree = link;
  579. // prevent double-free of link.
  580. link->parent = NULL;
  581. link->child = NULL;
  582. check(store);
  583. }
  584. /**
  585. * Link two nodes in the graph together.
  586. * If a parent of the child node is also a parent of the parent node, they are
  587. * unlinked (the link is split and the child is inserted in the middle).
  588. *
  589. * @param parent the current end of the graph
  590. * @param child the new node to extend the graph
  591. * @param cannonicalLabel the label for getting from the parent to the child.
  592. * @param linkStateDiff how much to change the link state for this link.
  593. * @param store
  594. */
  595. static struct Node_Link* linkNodes(struct Node_Two* parent,
  596. struct Node_Two* child,
  597. uint64_t cannonicalLabel,
  598. int64_t linkStateDiff,
  599. int inverseLinkEncodingFormNumber,
  600. uint64_t discoveredPath,
  601. struct NodeStore_pvt* store)
  602. {
  603. check(store);
  604. if (Defined(Log_DEBUG)) {
  605. uint8_t parentIp[40];
  606. uint8_t childIp[40];
  607. AddrTools_printIp(parentIp, parent->address.ip6.bytes);
  608. AddrTools_printIp(childIp, child->address.ip6.bytes);
  609. uint8_t printedLabel[20];
  610. AddrTools_printPath(printedLabel, cannonicalLabel);
  611. Log_debug(store->logger, "Linking [%s] with [%s] with label fragment [%s]",
  612. parentIp, childIp, printedLabel);
  613. }
  614. // It's ok to link a node with itself via some loopey route.
  615. // in practice it should never actually be used and it might yield some interesting
  616. // information when the link is split, self-routes are not allowed unless the self
  617. // link is being set up :)
  618. Assert_true(cannonicalLabel != 1 || store->selfLink == NULL);
  619. if (Defined(PARANOIA)) {
  620. uint64_t definitelyCannonical =
  621. EncodingScheme_convertLabel(parent->encodingScheme,
  622. cannonicalLabel,
  623. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  624. Assert_true(definitelyCannonical == cannonicalLabel);
  625. }
  626. {
  627. struct Node_Link* link;
  628. RB_FOREACH_REVERSE(link, PeerRBTree, &parent->peerTree) {
  629. Identity_check(link);
  630. if (link->child == child) {
  631. if (link->cannonicalLabel != cannonicalLabel) {
  632. // multiple paths between A and B are ok because they
  633. // will have divergent paths following the first director.
  634. continue;
  635. } else if (link->inverseLinkEncodingFormNumber != inverseLinkEncodingFormNumber) {
  636. logLink(store, link, "Relinking nodes with different encoding form");
  637. // This can happen when C renumbers but B->C is the same because B did
  638. // not renumber, EG: if C restarts.
  639. link->inverseLinkEncodingFormNumber = inverseLinkEncodingFormNumber;
  640. }
  641. update(link, linkStateDiff, store);
  642. return link;
  643. }
  644. }
  645. }
  646. if (Defined(PARANOIA)) {
  647. struct Node_Link dummy = { .cannonicalLabel = cannonicalLabel };
  648. struct Node_Link* link = Identity_ncheck(RB_FIND(PeerRBTree, &parent->peerTree, &dummy));
  649. if (link) {
  650. logLink(store, link, "Attempted to create alternate link with same label!");
  651. Assert_true(0);
  652. return link;
  653. }
  654. }
  655. Assert_true(cannonicalLabel <= discoveredPath);
  656. struct Node_Link* link = getLink(store);
  657. // set it up
  658. link->cannonicalLabel = cannonicalLabel;
  659. link->inverseLinkEncodingFormNumber = inverseLinkEncodingFormNumber;
  660. link->child = child;
  661. link->parent = parent;
  662. link->discoveredPath = discoveredPath;
  663. link->linkState = 0;
  664. Identity_set(link);
  665. // reverse link
  666. link->nextPeer = child->reversePeers;
  667. child->reversePeers = link;
  668. // forward link
  669. Assert_ifParanoid(!RB_FIND(PeerRBTree, &parent->peerTree, link));
  670. RB_INSERT(PeerRBTree, &parent->peerTree, link);
  671. if (!Node_getBestParent(child)) {
  672. if (Node_getBestParent(parent)) {
  673. updateBestParent(link, guessReachOfChild(link), store);
  674. } else {
  675. unreachable(child, store);
  676. }
  677. }
  678. // update the child's link state and possibly change it's preferred path
  679. update(link, linkStateDiff, store);
  680. if (parent == store->pub.selfNode && child != store->pub.selfNode) {
  681. Assert_true(LabelSplicer_isOneHop(cannonicalLabel));
  682. store->pub.peerCount++;
  683. if (Defined(Log_DEBUG)) {
  684. uint8_t addr[60];
  685. Address_print(addr, &child->address);
  686. Log_info(store->logger, "Direct peer [%s] has been linked", addr);
  687. }
  688. }
  689. check(store);
  690. return link;
  691. }
  692. #define removeLinkFromLabel_IMPOSSIBLE UINT64_MAX
  693. #define removeLinkFromLabel_OVERSIZE (UINT64_MAX-1)
  694. #define removeLinkFromLabel_ERR(x) (((uint64_t)x) >> 63)
  695. // TODO(cjd): This does not depend on nodeStore or alter the link, consider moving to Node.c
  696. static uint64_t removeLinkFromLabel(struct Node_Link* link, uint64_t label)
  697. {
  698. // First we splice off the parent's Director leaving the child's Director.
  699. uint64_t unspliced = LabelSplicer_unsplice(label, link->cannonicalLabel);
  700. int formNum = EncodingScheme_getFormNum(link->child->encodingScheme, unspliced);
  701. if (formNum < link->inverseLinkEncodingFormNumber) {
  702. // Can't get there from here.
  703. return removeLinkFromLabel_IMPOSSIBLE;
  704. }
  705. uint64_t cannonical =
  706. EncodingScheme_convertLabel(link->child->encodingScheme,
  707. unspliced,
  708. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  709. // Check that they didn't waste space by sending an oversize encoding form.
  710. if (formNum > link->inverseLinkEncodingFormNumber && cannonical != unspliced) {
  711. return removeLinkFromLabel_OVERSIZE;
  712. }
  713. Assert_true(cannonical != EncodingScheme_convertLabel_INVALID);
  714. return cannonical;
  715. }
  716. /**
  717. * Find the next hop on a given path.
  718. * Given a label representing a path from parentLink to some destination, set
  719. * outLink to the first link along that journey and return the path from outLink
  720. * to the original destination.
  721. * Feeding outLink back in to parentLink and the return value back into label argument
  722. * will allow you to iteratively walk a path.
  723. *
  724. * @param label the path from parentLink to some unspecified destination.
  725. * @param outLink a pointer to a location which will receive the first link in the path.
  726. * @param parentLink the link where to begin the trek.
  727. * @param store
  728. * @return a label which would take you from the node in memory location outLink to the
  729. * destination provided by the label argument. OR: firstHopInPath_INVALID if the
  730. * label argument traverces a node whose encoding scheme is inconsistent with
  731. * the label. OR: firstHopInPath_NO_NEXT_LINK if there are no *known* further
  732. * links along the path. If the result is firstHopInPath_INVALID, outLink will
  733. * still be set to the node. Use firstHopInPath_ERR() to check if the return
  734. * is an error code.
  735. */
  736. #define firstHopInPath_INVALID UINT64_MAX
  737. #define firstHopInPath_NO_NEXT_LINK (UINT64_MAX-1)
  738. #define firstHopInPath_ERR(path) (path >= firstHopInPath_NO_NEXT_LINK)
  739. static uint64_t firstHopInPath(uint64_t label,
  740. struct Node_Link** outLink,
  741. struct Node_Link* parentLink,
  742. struct NodeStore_pvt* store)
  743. {
  744. // Then we search for the next peer in the path
  745. // RB_NFIND will find a link for which we know that no link before it is in the path.
  746. // Unfortunately I have not found a way to store links in a tree where the search time
  747. // is less than O(n) where n = peers of a given node.
  748. struct Node_Link tmpl = { .cannonicalLabel = label };
  749. struct Node_Link* nextLink =
  750. Identity_ncheck(RB_NFIND(PeerRBTree, &parentLink->child->peerTree, &tmpl));
  751. // Now we walk back through the potential candidates looking for a path which it routes though.
  752. while (nextLink && !LabelSplicer_routesThrough(label, nextLink->cannonicalLabel)) {
  753. nextLink = Identity_ncheck(RB_NEXT(PeerRBTree, NULL, nextLink));
  754. }
  755. // This node has no peers, if it's us then it always has a peer (which is the selfLink)
  756. if (!nextLink || nextLink == store->selfLink) {
  757. return firstHopInPath_NO_NEXT_LINK;
  758. }
  759. // check for a looping link, this should never happen but adding the assert helps me
  760. // refactor this function a little more agressively.
  761. Assert_true(nextLink != parentLink);
  762. if (label == nextLink->cannonicalLabel) {
  763. //logLink(store, nextLink, "Exact match");
  764. *outLink = nextLink;
  765. return 1;
  766. }
  767. if (!LabelSplicer_routesThrough(label, nextLink->cannonicalLabel)) {
  768. // child of next link is not in the path, we reached the end.
  769. return firstHopInPath_NO_NEXT_LINK;
  770. }
  771. *outLink = nextLink;
  772. // Cannoicalize the child's Director
  773. label = removeLinkFromLabel(nextLink, label);
  774. if (removeLinkFromLabel_ERR(label)) {
  775. return firstHopInPath_INVALID;
  776. }
  777. return label;
  778. }
  779. #define findClosest_INVALID (~((uint64_t)0))
  780. static uint64_t findClosest(uint64_t path,
  781. struct Node_Link** output,
  782. struct Node_Link* parentLink,
  783. struct NodeStore_pvt* store)
  784. {
  785. for (;;) {
  786. struct Node_Link* nextLink = NULL;
  787. uint64_t nextPath = firstHopInPath(path, &nextLink, parentLink, store);
  788. if (nextPath == firstHopInPath_NO_NEXT_LINK) {
  789. *output = parentLink;
  790. return path;
  791. }
  792. if (firstHopInPath_INVALID == nextPath) {
  793. return findClosest_INVALID;
  794. }
  795. Assert_true(nextLink);
  796. path = nextPath;
  797. parentLink = nextLink;
  798. }
  799. }
  800. static struct Node_Two* nodeForIp(struct NodeStore_pvt* store, uint8_t ip[16])
  801. {
  802. struct Node_Two fakeNode;
  803. Identity_set(&fakeNode);
  804. Bits_memcpyConst(fakeNode.address.ip6.bytes, ip, 16);
  805. return Identity_ncheck(RB_FIND(NodeRBTree, &store->nodeTree, &fakeNode));
  806. }
  807. static void freePendingLinks(struct NodeStore_pvt* store)
  808. {
  809. struct Node_Link* link;
  810. while ((link = store->linksToFree)) {
  811. store->linksToFree = link->nextPeer;
  812. freeLink(link, store);
  813. }
  814. }
  815. static struct Node_Link* discoverLinkC(struct NodeStore_pvt* store,
  816. struct Node_Link* closestKnown,
  817. uint64_t pathKnownParentChild,
  818. struct Node_Two* child,
  819. uint64_t discoveredPath,
  820. int inverseLinkEncodingFormNumber)
  821. {
  822. // Make sure this link cannot be split before beginning.
  823. struct Node_Link* closest = NULL;
  824. uint64_t pathParentChild = findClosest(pathKnownParentChild, &closest, closestKnown, store);
  825. if (pathParentChild == findClosest_INVALID) {
  826. return NULL;
  827. }
  828. struct Node_Two* parent = closest->child;
  829. if (Defined(Log_DEBUG)) {
  830. uint8_t parentStr[40];
  831. uint8_t childStr[40];
  832. uint8_t pathStr[20];
  833. AddrTools_printIp(parentStr, parent->address.ip6.bytes);
  834. AddrTools_printIp(childStr, child->address.ip6.bytes);
  835. AddrTools_printPath(pathStr, pathParentChild);
  836. Log_debug(store->logger, "discoverLinkC( [%s]->[%s] [%s] )", parentStr, childStr, pathStr);
  837. }
  838. if (closest == store->selfLink && !LabelSplicer_isOneHop(pathParentChild)) {
  839. Log_debug(store->logger, "Attempting to create a link with no parent peer");
  840. return NULL;
  841. }
  842. if (parent == child) {
  843. if (pathParentChild == 1) {
  844. // Link is already known.
  845. update(closest, 0, store);
  846. //Log_debug(store->logger, "Already known");
  847. return closest;
  848. }
  849. Log_debug(store->logger, "Loopey route");
  850. // lets not bother storing this link, a link with the same parent and child is
  851. // invalid according to verify() and it's just going to take up space in the store
  852. // we'll return closest which is a perfectly valid path to the same node.
  853. // We could reasonably return the closest since it is the same node but it causes
  854. // problems with an assertion in discoverLink.
  855. return NULL;
  856. }
  857. if (EncodingScheme_isSelfRoute(parent->encodingScheme, pathParentChild)) {
  858. logLink(store, closest, "Node at end of path appears to have changed");
  859. // This should never happen for a direct peer or for a direct decendent in a split link.
  860. // This sometimes triggers because a link is split which contains an invalid encoding
  861. // somewhere in the middle.
  862. // It is not harmful to remove it becaue the route is not re-added.
  863. Assert_ifTesting(closestKnown != closest);
  864. // This probably means the parent node has renumbered it's switch...
  865. RumorMill_addNode(store->renumberMill, &closest->parent->address);
  866. check(store);
  867. // But it's possible someone is just lieing to us.
  868. return NULL;
  869. }
  870. // link parent to child
  871. //
  872. // ACKTUNG: From this point forward, the nodeStore is in an invalid state, calls to _verify()
  873. // will fail (calls to _check() will still succeed). We have linked parent with child
  874. // but we have not split all of the splitLinks from parent.
  875. //
  876. // TODO(cjd): linking every node with 0 link state, this can't be right.
  877. struct Node_Link* parentLink = linkNodes(parent,
  878. child,
  879. pathParentChild,
  880. 0,
  881. inverseLinkEncodingFormNumber,
  882. discoveredPath,
  883. store);
  884. if (!RB_FIND(NodeRBTree, &store->nodeTree, child)) {
  885. checkNode(child, store);
  886. RB_INSERT(NodeRBTree, &store->nodeTree, child);
  887. store->pub.nodeCount++;
  888. }
  889. check(store);
  890. return parentLink;
  891. }
  892. static void fixLink(struct Node_Link* parentLink,
  893. struct Node_Link** outLinks,
  894. struct NodeStore_pvt* store)
  895. {
  896. int verifyOrder = 0;
  897. // Check whether the parent is already linked with a node which is "behind" the child.
  898. // splitLink appears to be a "sibling link" to the closest->node link but in reality the
  899. // splitLink link should be split and node should be inserted in the middle.
  900. struct Node_Link* splitLink = RB_MIN(PeerRBTree, &parentLink->parent->peerTree);
  901. while (splitLink) {
  902. if (splitLink == parentLink) {
  903. if (Defined(PARANOIA)) {
  904. verifyOrder = 1;
  905. splitLink = PeerRBTree_RB_NEXT(splitLink);
  906. continue;
  907. } else {
  908. // Since they're in order, definitely not found.
  909. break;
  910. }
  911. }
  912. if (!LabelSplicer_routesThrough(splitLink->cannonicalLabel, parentLink->cannonicalLabel)) {
  913. splitLink = PeerRBTree_RB_NEXT(splitLink);
  914. continue;
  915. }
  916. if (Defined(PARANOIA)) {
  917. Assert_true(!verifyOrder);
  918. }
  919. struct Node_Two* grandChild = splitLink->child;
  920. if (parentLink->child == grandChild) {
  921. // loopey route, kill it and let the bestParent pivit over to parentLink
  922. } else {
  923. logLink(store, splitLink, "Splitting link");
  924. // unsplice and cannonicalize so we now have a path from child to grandchild
  925. uint64_t childToGrandchild =
  926. LabelSplicer_unsplice(splitLink->cannonicalLabel, parentLink->cannonicalLabel);
  927. childToGrandchild =
  928. EncodingScheme_convertLabel(parentLink->child->encodingScheme,
  929. childToGrandchild,
  930. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  931. Assert_true(childToGrandchild < UINT64_MAX);
  932. Assert_true(childToGrandchild != 1);
  933. Assert_true(splitLink->cannonicalLabel != parentLink->cannonicalLabel);
  934. // We forgot what was the discovered path for the link when we split (destroyed)
  935. // it so we'll just assume the worst among these two possibilities.
  936. // There is an assertion that discoveredPath is never < cannonicalLabel so we must.
  937. uint64_t discoveredPath = parentLink->discoveredPath;
  938. if (childToGrandchild > discoveredPath) { discoveredPath = childToGrandchild; }
  939. struct Node_Link* childLink =
  940. discoverLinkC(store, parentLink, childToGrandchild, grandChild,
  941. discoveredPath, splitLink->inverseLinkEncodingFormNumber);
  942. if (childLink) {
  943. // Order the list so that the next set of links will be split from
  944. // smallest to largest and nothing will ever be split twice.
  945. for (struct Node_Link** x = outLinks;; x = &(*x)->nextInSplitList) {
  946. if (*x == childLink) { break; }
  947. if (*x && (*x)->cannonicalLabel <= childLink->cannonicalLabel) { continue; }
  948. Assert_true(!childLink->nextInSplitList);
  949. childLink->nextInSplitList = *x;
  950. *x = childLink;
  951. break;
  952. }
  953. }
  954. }
  955. check(store);
  956. struct Node_Link* next = PeerRBTree_RB_NEXT(splitLink);
  957. NodeStore_unlinkNodes(&store->pub, splitLink);
  958. splitLink = next;
  959. }
  960. }
  961. static void fixLinks(struct Node_Link* parentLinkList,
  962. struct Node_Link** outLinks,
  963. struct NodeStore_pvt* store)
  964. {
  965. while (parentLinkList) {
  966. struct Node_Link* next = parentLinkList->nextInSplitList;
  967. parentLinkList->nextInSplitList = NULL;
  968. // else the parent link has been trashed by splitting another link.
  969. if (parentLinkList->child) {
  970. fixLink(parentLinkList, outLinks, store);
  971. }
  972. parentLinkList = next;
  973. }
  974. }
  975. static struct Node_Link* discoverLink(struct NodeStore_pvt* store,
  976. uint64_t path,
  977. struct Node_Two* child,
  978. int inverseLinkEncodingFormNumber)
  979. {
  980. struct Node_Link* link =
  981. discoverLinkC(store, store->selfLink, path, child, path, inverseLinkEncodingFormNumber);
  982. if (!link) { return NULL; }
  983. uint64_t pathParentChild = findClosest(path, &link, store->selfLink, store);
  984. // This should always be 1 because the link is gone only because it was just split!
  985. Assert_true(pathParentChild == 1);
  986. struct Node_Link* ol = NULL;
  987. struct Node_Link* nl = NULL;
  988. fixLinks(link, &ol, store);
  989. for (;;) {
  990. if (ol) {
  991. fixLinks(ol, &nl, store);
  992. ol = NULL;
  993. } else if (nl) {
  994. fixLinks(nl, &ol, store);
  995. nl = NULL;
  996. } else {
  997. break;
  998. }
  999. }
  1000. verify(store);
  1001. return link;
  1002. }
  1003. static struct Node_Two* whichIsWorse(struct Node_Two* one,
  1004. struct Node_Two* two,
  1005. struct NodeStore_pvt* store)
  1006. {
  1007. // a peer is nevar worse
  1008. int peers = isPeer(one, store) - isPeer(two, store);
  1009. if (peers) {
  1010. return (peers > 0) ? two : one;
  1011. }
  1012. if (one->address.protocolVersion != two->address.protocolVersion) {
  1013. if (one->address.protocolVersion < Version_CURRENT_PROTOCOL) {
  1014. if (two->address.protocolVersion >= Version_CURRENT_PROTOCOL) {
  1015. return one;
  1016. }
  1017. } else if (two->address.protocolVersion < Version_CURRENT_PROTOCOL) {
  1018. if (one->address.protocolVersion >= Version_CURRENT_PROTOCOL) {
  1019. return two;
  1020. }
  1021. }
  1022. }
  1023. if (Node_getReach(one) < Node_getReach(two)) { return one; }
  1024. if (Node_getReach(two) < Node_getReach(one)) { return two; }
  1025. if (Address_closest(&store->pub.selfNode->address, &one->address, &two->address) > 0) {
  1026. return one;
  1027. }
  1028. return two;
  1029. }
  1030. static bool markBestNodes(struct NodeStore_pvt* store,
  1031. struct Address* targetAddress,
  1032. const uint32_t count)
  1033. {
  1034. struct Allocator* nodeListAlloc = Allocator_child(store->alloc);
  1035. struct NodeList* nodeList = Allocator_malloc(nodeListAlloc, sizeof(struct NodeList));
  1036. nodeList->nodes = Allocator_calloc(nodeListAlloc, count, sizeof(char*));
  1037. nodeList->size = 0;
  1038. struct Node_Two* nn = NULL;
  1039. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1040. if (Address_closest(targetAddress, store->pub.selfAddress, &nn->address) > 0) {
  1041. // This node is closer to the destination than we are.
  1042. struct Node_Two* newNode = nn;
  1043. struct Node_Two* tempNode = NULL;
  1044. for (uint32_t i = 0 ; i < count ; i++) {
  1045. if (nodeList->size < i+1) {
  1046. // The list isn't full yet, so insert at the end.
  1047. nodeList->size = i+1;
  1048. nodeList->nodes[i] = newNode;
  1049. break;
  1050. }
  1051. if ( (newNode->marked && !nodeList->nodes[i]->marked) ||
  1052. whichIsWorse(nodeList->nodes[i], newNode, store) == nodeList->nodes[i] ) {
  1053. // If we've already marked nodes because they're a bestParent,
  1054. // lets give them priority in the bucket since we need to keep
  1055. // them either way.
  1056. // Otherwise, highest reach wins.
  1057. // Insertion sorted list.
  1058. tempNode = nodeList->nodes[i];
  1059. nodeList->nodes[i] = newNode;
  1060. newNode = tempNode;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. bool retVal = false;
  1066. if (nodeList->size > 0) { retVal = true; }
  1067. for (uint32_t i = 0; i < nodeList->size; i++) {
  1068. // Now mark the nodes in the list to protect them.
  1069. Identity_check(nodeList->nodes[i]);
  1070. nodeList->nodes[i]->marked = 1;
  1071. }
  1072. // Cleanup
  1073. Allocator_free(nodeListAlloc);
  1074. return retVal;
  1075. }
  1076. static void markKeyspaceNodes(struct NodeStore_pvt* store)
  1077. {
  1078. for (uint8_t i = 0; i < NodeStore_bucketNumber ; i++) {
  1079. // Bitwise walk across keyspace
  1080. if (63 < i && i < 72) {
  1081. // We want to leave the 0xfc alone
  1082. continue;
  1083. }
  1084. struct Address addr = NodeStore_addrForBucket(store->pub.selfAddress, i);
  1085. markBestNodes(store, &addr, NodeStore_bucketSize);
  1086. }
  1087. }
  1088. /**
  1089. * We define the worst node the node with the lowest reach, excluding nodes which are required for
  1090. * the DHT, and nodes which are somebody's bestParent (only relevant if they're the bestParent of
  1091. * a DHT-required node, as otherwise their child would always be lower reach).
  1092. * If two nodes tie (e.g. two unreachable nodes with 0 reach) then the node which is
  1093. * further from us in keyspace is worse.
  1094. */
  1095. static struct Node_Two* getWorstNode(struct NodeStore_pvt* store)
  1096. {
  1097. struct Node_Two* worst = NULL;
  1098. struct Node_Two* nn = NULL;
  1099. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1100. // first cycle we set markings so markings remain if they are behind us
  1101. struct Node_Link* parentLink = Node_getBestParent(nn);
  1102. if (parentLink) {
  1103. parentLink->parent->marked = 1;
  1104. } else if (!worst || whichIsWorse(nn, worst, store) == nn) {
  1105. // this time around we're only addressing nodes which are unreachable.
  1106. worst = nn;
  1107. }
  1108. }
  1109. if (worst) {
  1110. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1111. if (nn->marked) { nn->marked = false; }
  1112. }
  1113. return worst;
  1114. }
  1115. // Mark the nodes that we need to protect for keyspace reasons.
  1116. markKeyspaceNodes(store);
  1117. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1118. if (nn->marked) {
  1119. nn->marked = false;
  1120. } else if (!worst || whichIsWorse(nn, worst, store) == nn) {
  1121. worst = nn;
  1122. }
  1123. }
  1124. if (worst) { return worst; }
  1125. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1126. // third cycle, every node is apparently important but we need to get rid of someone
  1127. // get whoever is worst if we ignore markings
  1128. // by definition, this shouldn't be a bestParent, because their children have lower reach
  1129. // so we're potentially creating a keyspace hole (routing blackhole) when we do this.
  1130. // TODO(arceliar): protect keyspace, evict the worst bestParent instead?
  1131. // Would require something like a forgetNode() to splice links together between
  1132. // that node's bestParent and all its children, before we kill it.
  1133. if (!worst || whichIsWorse(nn, worst, store) == nn) {
  1134. worst = nn;
  1135. }
  1136. }
  1137. // somebody has to be at the end of the line, not *everyone* can be someone's best parent!
  1138. Assert_true(worst);
  1139. return worst;
  1140. }
  1141. static void destroyNode(struct Node_Two* node, struct NodeStore_pvt* store)
  1142. {
  1143. // careful, undefined unless debug is enabled...
  1144. uint8_t address_debug[60];
  1145. if (Defined(Log_DEBUG)) {
  1146. Address_print(address_debug, &node->address);
  1147. }
  1148. struct Node_Link* link;
  1149. RB_FOREACH(link, PeerRBTree, &node->peerTree) {
  1150. Identity_check(link);
  1151. NodeStore_unlinkNodes(&store->pub, link);
  1152. }
  1153. // If the node has a bestParent, it will be changed a number
  1154. // of times as we kill off all of it's parent links.
  1155. // This is an optimization:
  1156. if (!Defined(PARANOIA)) {
  1157. store->pub.linkedNodes--;
  1158. Node_setParentReachAndPath(node, NULL, 0, UINT64_MAX);
  1159. }
  1160. link = node->reversePeers;
  1161. while (link) {
  1162. struct Node_Link* nextLink = link->nextPeer;
  1163. NodeStore_unlinkNodes(&store->pub, link);
  1164. link = nextLink;
  1165. }
  1166. Assert_ifParanoid(!Node_getBestParent(node));
  1167. Assert_ifParanoid(node == RB_FIND(NodeRBTree, &store->nodeTree, node));
  1168. RB_REMOVE(NodeRBTree, &store->nodeTree, node);
  1169. store->pub.nodeCount--;
  1170. Allocator_free(node->alloc);
  1171. }
  1172. // Must be at least 2 to avoid multiplying by 0.
  1173. // If too large, path choice may become unstable due to a guess we make in calcNextReach.
  1174. // This is fixable by storing reach based on links. A lot of work.
  1175. // In the mean time, just don't use a large value.
  1176. #define NodeStore_latencyWindow 8
  1177. static uint32_t reachAfterDecay(const uint32_t oldReach)
  1178. {
  1179. // Reduce the reach by 1/Xth where X = NodeStore_latencyWindow
  1180. // This is used to keep a weighted rolling average
  1181. return (oldReach - (oldReach / NodeStore_latencyWindow));
  1182. }
  1183. static uint32_t reachAfterTimeout(const uint32_t oldReach)
  1184. {
  1185. // TODO(arceliar) just use reachAfterDecay?... would be less penalty for timeouts...
  1186. return (oldReach / 2);
  1187. }
  1188. static uint32_t calcNextReach(const uint32_t oldReach, const uint32_t millisecondsLag)
  1189. {
  1190. int64_t out = reachAfterDecay(oldReach) +
  1191. ((UINT32_MAX / NodeStore_latencyWindow) / (millisecondsLag + 1));
  1192. if (!oldReach) {
  1193. // We don't know the old reach for this path.
  1194. // If every response comes in after same millisecondsLag, then we expect that the
  1195. // reach will stabilize to a value of (out * NodeStoare_latencyWindow).
  1196. // Lets guess what the reach will stabilize to, but try to be a little conservative,
  1197. // so we don't cause bestParents to switch unless the new route is appreciably better.
  1198. out = out * (NodeStore_latencyWindow - 1);
  1199. }
  1200. // TODO(arceliar): is this safe?
  1201. Assert_true(out < (UINT32_MAX - 1024) && out > 0);
  1202. return out;
  1203. }
  1204. struct Node_Link* NodeStore_discoverNode(struct NodeStore* nodeStore,
  1205. struct Address* addr,
  1206. struct EncodingScheme* scheme,
  1207. int inverseLinkEncodingFormNumber,
  1208. uint64_t milliseconds)
  1209. {
  1210. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1211. verify(store);
  1212. // conservative guess of what the reach would stabilize to
  1213. uint32_t reach = calcNextReach(0, milliseconds);
  1214. struct Node_Two* child = nodeForIp(store, addr->ip6.bytes);
  1215. if (Defined(Log_DEBUG)) {
  1216. uint8_t printedAddr[60];
  1217. Address_print(printedAddr, addr);
  1218. Log_debug(store->logger, "Discover node [%s]", printedAddr);
  1219. }
  1220. if (child && EncodingScheme_compare(child->encodingScheme, scheme)) {
  1221. // Shit.
  1222. // Box reset *and* they just updated and changed their encoding scheme.
  1223. RumorMill_addNode(store->renumberMill, &child->address);
  1224. if (addr->path > (child->address.path | (child->address.path << 3))) {
  1225. Log_debug(store->logger, "Node appears to have changed it's encoding scheme "
  1226. "but the message came from far away and we will not trust it");
  1227. return NULL;
  1228. } else {
  1229. Log_debug(store->logger, "Node appears to have changed it's encoding scheme "
  1230. "dropping him from the table and re-inserting");
  1231. destroyNode(child, store);
  1232. child = NULL;
  1233. }
  1234. } else if (child && child->address.protocolVersion != addr->protocolVersion) {
  1235. child->address.protocolVersion = addr->protocolVersion;
  1236. }
  1237. struct Allocator* alloc = NULL;
  1238. if (!child) {
  1239. alloc = Allocator_child(store->alloc);
  1240. child = Allocator_calloc(alloc, sizeof(struct Node_Two), 1);
  1241. child->alloc = alloc;
  1242. Bits_memcpyConst(&child->address, addr, sizeof(struct Address));
  1243. child->encodingScheme = EncodingScheme_clone(scheme, child->alloc);
  1244. Identity_set(child);
  1245. }
  1246. struct Node_Link* link = NULL;
  1247. for (;;) {
  1248. link = discoverLink(store,
  1249. addr->path,
  1250. child,
  1251. inverseLinkEncodingFormNumber);
  1252. if (link) { break; }
  1253. // We might have a broken link in the store which is causing new links to be rejected.
  1254. // On the other hand, this path might actually be garbage :)
  1255. // There's a DoS risk in that someone might use garbage paths to evict all of the
  1256. // existing good paths.
  1257. // While an attacker can send in a packet, it will necessarily follow a ridiculous path
  1258. // in order that the path contains one of their nodes.
  1259. // To resolve this, we'll walk the path looking for the "bad" link, then we'll check that
  1260. // node to see if the path we took to reach it is actually the *best* path to that node.
  1261. uint64_t path = addr->path;
  1262. struct Node_Link* lastLink = store->selfLink;
  1263. do {
  1264. struct Node_Link* nextLink = NULL;
  1265. path = firstHopInPath(path, &nextLink, lastLink, store);
  1266. lastLink = nextLink;
  1267. if (path == firstHopInPath_NO_NEXT_LINK) {
  1268. // discoverNode() failed for some other reason.
  1269. lastLink = NULL;
  1270. break;
  1271. }
  1272. } while (firstHopInPath_INVALID != path);
  1273. if (lastLink && LabelSplicer_routesThrough(addr->path, lastLink->child->address.path)) {
  1274. // checking for sillyness...
  1275. Assert_true(lastLink != store->selfLink);
  1276. NodeStore_unlinkNodes(&store->pub, lastLink);
  1277. continue;
  1278. }
  1279. if (alloc) {
  1280. Allocator_free(alloc);
  1281. }
  1282. verify(store);
  1283. Log_debug(store->logger, "Invalid path");
  1284. return NULL;
  1285. }
  1286. if (link->parent == store->pub.selfNode && !Node_getBestParent(link->child)) {
  1287. updateBestParent(link, reach, store);
  1288. }
  1289. handleNews(link->child, reach, store);
  1290. freePendingLinks(store);
  1291. while (store->pub.nodeCount - store->pub.peerCount > store->pub.nodeCapacity
  1292. || store->pub.linkCount > store->pub.linkCapacity)
  1293. {
  1294. struct Node_Two* worst = getWorstNode(store);
  1295. if (Defined(Log_DEBUG)) {
  1296. uint8_t worstAddr[60];
  1297. Address_print(worstAddr, &worst->address);
  1298. Log_debug(store->logger, "store full, removing worst node: [%s] nodes [%d] links [%d]",
  1299. worstAddr, store->pub.nodeCount, store->pub.linkCount);
  1300. }
  1301. Assert_true(!isPeer(worst, store));
  1302. destroyNode(worst, store);
  1303. freePendingLinks(store);
  1304. }
  1305. verify(store);
  1306. return link;
  1307. }
  1308. struct Node_Two* NodeStore_nodeForAddr(struct NodeStore* nodeStore, uint8_t addr[16])
  1309. {
  1310. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1311. struct Node_Two* n = nodeForIp(store, addr);
  1312. if (n && n->address.path == UINT64_MAX) {
  1313. if (Defined(Log_DEBUG)) {
  1314. uint8_t addrStr[40];
  1315. AddrTools_printIp(addrStr, n->address.ip6.bytes);
  1316. Log_debug(store->logger, "No way to represent path to [%s]", addrStr);
  1317. }
  1318. return NULL;
  1319. }
  1320. return n;
  1321. }
  1322. struct Node_Two* NodeStore_closestNode(struct NodeStore* nodeStore, uint64_t path)
  1323. {
  1324. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1325. struct Node_Link* out = NULL;
  1326. findClosest(path, &out, store->selfLink, store);
  1327. if (!out) { return NULL; }
  1328. return Identity_check(out->child);
  1329. }
  1330. struct Node_Link* NodeStore_linkForPath(struct NodeStore* nodeStore, uint64_t path)
  1331. {
  1332. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1333. struct Node_Link* out = NULL;
  1334. uint64_t pathParentChild = findClosest(path, &out, store->selfLink, store);
  1335. if (pathParentChild != 1) { return NULL; }
  1336. return Identity_check(out);
  1337. }
  1338. struct Node_Link* NodeStore_firstHopInPath(struct NodeStore* nodeStore,
  1339. uint64_t path,
  1340. uint64_t* correctedPath,
  1341. struct Node_Link* startingPoint)
  1342. {
  1343. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1344. if (!startingPoint) { startingPoint = store->selfLink; }
  1345. if (!Node_getBestParent(startingPoint->parent)) { return NULL; }
  1346. struct Node_Link* out = NULL;
  1347. path = firstHopInPath(path, &out, startingPoint, store);
  1348. if (firstHopInPath_ERR(path)) { return NULL; }
  1349. if (correctedPath) { *correctedPath = path; }
  1350. return out;
  1351. }
  1352. char* NodeStore_getRouteLabel_strerror(uint64_t returnVal)
  1353. {
  1354. switch (returnVal) {
  1355. case NodeStore_getRouteLabel_PARENT_NOT_FOUND:
  1356. return "NodeStore_getRouteLabel_PARENT_NOT_FOUND";
  1357. case NodeStore_getRouteLabel_CHILD_NOT_FOUND:
  1358. return "NodeStore_getRouteLabel_CHILD_NOT_FOUND";
  1359. default: return NULL;
  1360. }
  1361. }
  1362. uint64_t NodeStore_getRouteLabel(struct NodeStore* nodeStore,
  1363. uint64_t pathToParent,
  1364. uint64_t pathParentToChild)
  1365. {
  1366. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1367. struct Node_Link* linkToParent;
  1368. if (findClosest(pathToParent, &linkToParent, store->selfLink, store) != 1) {
  1369. return NodeStore_getRouteLabel_PARENT_NOT_FOUND;
  1370. }
  1371. logLink(store, linkToParent, "NodeStore_getRouteLabel() PARENT");
  1372. struct Node_Link* linkToChild = NULL;
  1373. RB_FOREACH_REVERSE(linkToChild, PeerRBTree, &linkToParent->child->peerTree) {
  1374. if (pathParentToChild == linkToChild->cannonicalLabel) {
  1375. if (linkToParent == store->selfLink) {
  1376. return linkToChild->cannonicalLabel;
  1377. }
  1378. // TODO(cjd): this could return ~0
  1379. return extendRoute(pathToParent,
  1380. linkToChild->parent->encodingScheme,
  1381. linkToChild->cannonicalLabel,
  1382. linkToParent->inverseLinkEncodingFormNumber);
  1383. }
  1384. }
  1385. return NodeStore_getRouteLabel_CHILD_NOT_FOUND;
  1386. }
  1387. uint64_t NodeStore_optimizePath(struct NodeStore* nodeStore, uint64_t path)
  1388. {
  1389. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1390. struct Node_Link* linkToParent;
  1391. uint64_t next = findClosest(path, &linkToParent, store->selfLink, store);
  1392. if (next == findClosest_INVALID) {
  1393. return NodeStore_optimizePath_INVALID;
  1394. }
  1395. if (EncodingScheme_isSelfRoute(linkToParent->child->encodingScheme, next)) {
  1396. // cannoicalize all the other wild ways that they can represent self routes.
  1397. // TODO(cjd): this has been the source of assert failures and we might be sweeping
  1398. // a significant bug under the carpet.
  1399. next = 1;
  1400. }
  1401. if (linkToParent == store->selfLink) {
  1402. if (next == 1) { return 1; }
  1403. return path;
  1404. }
  1405. if (next == 1) { return linkToParent->child->address.path; }
  1406. struct Node_Link* childBestParent = Node_getBestParent(linkToParent->child);
  1407. if (childBestParent) {
  1408. linkToParent = childBestParent;
  1409. }
  1410. uint64_t optimized = extendRoute(linkToParent->child->address.path,
  1411. linkToParent->child->encodingScheme,
  1412. next,
  1413. linkToParent->inverseLinkEncodingFormNumber);
  1414. if (optimized != UINT64_MAX) {
  1415. return optimized;
  1416. }
  1417. if (optimized == extendRoute_INVALID) {
  1418. if (Defined(Log_DEBUG)) {
  1419. do {
  1420. uint8_t pathStr[20];
  1421. uint8_t nextStr[20];
  1422. uint8_t bestPathStr[20];
  1423. AddrTools_printPath(pathStr, path);
  1424. AddrTools_printPath(nextStr, next);
  1425. AddrTools_printPath(bestPathStr, linkToParent->child->address.path);
  1426. Log_debug(store->logger, "Failed to optimize path [%s] with closest known [%s] and "
  1427. "best path to closest known [%s]",
  1428. pathStr, nextStr, bestPathStr);
  1429. } while (0);
  1430. }
  1431. return path;
  1432. }
  1433. // path is too long...
  1434. /*if (Defined(Log_DEBUG)) {
  1435. do {
  1436. uint8_t pathStr[20];
  1437. uint8_t nextStr[20];
  1438. uint8_t bestPathStr[20];
  1439. AddrTools_printPath(pathStr, path);
  1440. AddrTools_printPath(nextStr, next);
  1441. AddrTools_printPath(bestPathStr, linkToParent->child->address.path);
  1442. Log_debug(store->logger, "Failed to optimize path [%s] with closest known [%s] and best "
  1443. "path to closest known [%s]", pathStr, nextStr, bestPathStr);
  1444. } while (0);
  1445. }*/
  1446. return path;
  1447. }
  1448. struct Node_Link* NodeStore_nextLink(struct Node_Two* parent, struct Node_Link* startLink)
  1449. {
  1450. if (!startLink) {
  1451. return RB_MIN(PeerRBTree, &parent->peerTree);
  1452. }
  1453. return PeerRBTree_RB_NEXT(startLink);
  1454. }
  1455. /** See: NodeStore.h */
  1456. struct NodeStore* NodeStore_new(struct Address* myAddress,
  1457. struct Allocator* allocator,
  1458. struct Log* logger,
  1459. struct RumorMill* renumberMill)
  1460. {
  1461. struct Allocator* alloc = Allocator_child(allocator);
  1462. struct NodeStore_pvt* out = Allocator_clone(alloc, (&(struct NodeStore_pvt) {
  1463. .pub = {
  1464. .nodeCapacity = NodeStore_DEFAULT_NODE_CAPACITY,
  1465. .linkCapacity = NodeStore_DEFAULT_LINK_CAPACITY
  1466. },
  1467. .renumberMill = renumberMill,
  1468. .logger = logger,
  1469. .alloc = alloc
  1470. }));
  1471. Identity_set(out);
  1472. // Create the self node
  1473. struct Node_Two* selfNode = Allocator_calloc(alloc, sizeof(struct Node_Two), 1);
  1474. Bits_memcpyConst(&selfNode->address, myAddress, sizeof(struct Address));
  1475. selfNode->encodingScheme = NumberCompress_defineScheme(alloc);
  1476. selfNode->alloc = alloc;
  1477. Identity_set(selfNode);
  1478. out->pub.linkedNodes = 1;
  1479. out->pub.selfNode = selfNode;
  1480. struct Node_Link* selfLink = linkNodes(selfNode, selfNode, 1, 0xffffffffu, 0, 1, out);
  1481. Node_setParentReachAndPath(selfNode, selfLink, UINT32_MAX, 1);
  1482. out->selfLink = selfLink;
  1483. RB_INSERT(NodeRBTree, &out->nodeTree, selfNode);
  1484. out->pub.selfAddress = &out->selfLink->child->address;
  1485. return &out->pub;
  1486. }
  1487. //////////////////////////////////////////////////////////////////////////////////////////////
  1488. //////////////////////////////////////////////////////////////////////////////////////////////
  1489. //////////////////////////////////////////////////////////////////////////////////////////////
  1490. /**
  1491. * Dump the table, one node at a time.
  1492. */
  1493. struct Node_Two* NodeStore_dumpTable(struct NodeStore* nodeStore, uint32_t index)
  1494. {
  1495. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1496. // TODO(cjd): Schlameil the painter
  1497. uint32_t i = 0;
  1498. struct Node_Two* nn = NULL;
  1499. RB_FOREACH(nn, NodeRBTree, &store->nodeTree) {
  1500. if (i++ == index) { return nn; }
  1501. }
  1502. return NULL;
  1503. }
  1504. struct Node_Two* NodeStore_getNextNode(struct NodeStore* nodeStore, struct Node_Two* lastNode)
  1505. {
  1506. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1507. if (!lastNode) {
  1508. return Identity_ncheck(RB_MIN(NodeRBTree, &store->nodeTree));
  1509. }
  1510. return Identity_ncheck(NodeRBTree_RB_NEXT(lastNode));
  1511. }
  1512. static struct Node_Two* getBestCycleB(struct Node_Two* node,
  1513. uint8_t target[16],
  1514. struct NodeStore_pvt* store)
  1515. {
  1516. uint32_t targetPfx = Address_prefixForIp6(target);
  1517. uint32_t ourDistance = Address_getPrefix(store->pub.selfAddress) ^ targetPfx;
  1518. struct Node_Link* next = NULL;
  1519. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  1520. if (Node_getBestParent(next->child) != next || next == store->selfLink) { continue; }
  1521. if (next->child->address.path == UINT64_MAX) { continue; }
  1522. if ((Address_getPrefix(&next->child->address) ^ targetPfx) >= ourDistance) { continue; }
  1523. return next->child;
  1524. }
  1525. return NULL;
  1526. }
  1527. static int getBestCycle(struct Node_Two* node,
  1528. uint8_t target[16],
  1529. struct Node_Two** output,
  1530. int limit,
  1531. int cycle,
  1532. struct NodeStore_pvt* store)
  1533. {
  1534. Assert_true(cycle < 1000);
  1535. if (cycle < limit) {
  1536. int total = 0;
  1537. struct Node_Link* next = NULL;
  1538. RB_FOREACH_REVERSE(next, PeerRBTree, &node->peerTree) {
  1539. if (*output) { return total; }
  1540. if (Node_getBestParent(next->child) != next || next == store->selfLink) { continue; }
  1541. total += getBestCycle(next->child, target, output, limit, cycle+1, store);
  1542. }
  1543. return total;
  1544. }
  1545. *output = getBestCycleB(node, target, store);
  1546. return 1;
  1547. }
  1548. struct Node_Two* NodeStore_getBest(struct NodeStore* nodeStore, uint8_t targetAddress[16])
  1549. {
  1550. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1551. struct Node_Two* n = NodeStore_nodeForAddr(nodeStore, targetAddress);
  1552. if (n && Node_getBestParent(n)) { return n; }
  1553. for (int i = 0; i < 10000; i++) {
  1554. int ret = getBestCycle(store->pub.selfNode, targetAddress, &n, i, 0, store);
  1555. if (n || !ret) {
  1556. if (n) { Assert_true(Node_getBestParent(n)); }
  1557. return n;
  1558. }
  1559. }
  1560. return NULL;
  1561. }
  1562. struct NodeList* NodeStore_getPeers(uint64_t label,
  1563. const uint32_t max,
  1564. struct Allocator* allocator,
  1565. struct NodeStore* nodeStore)
  1566. {
  1567. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1568. // truncate the label to the part which this node uses...
  1569. label &= Bits_maxBits64(NumberCompress_bitsUsedForLabel(label));
  1570. struct NodeList* out = Allocator_calloc(allocator, sizeof(struct NodeList), 1);
  1571. out->nodes = Allocator_calloc(allocator, sizeof(char*), max);
  1572. struct Node_Link* next = NULL;
  1573. RB_FOREACH_REVERSE(next, PeerRBTree, &store->pub.selfNode->peerTree) {
  1574. uint64_t p = next->child->address.path;
  1575. if (p > (((uint64_t)1)<<63)) { continue; }
  1576. int j;
  1577. for (j = 0; j < (int)max; j++) {
  1578. if (out->nodes[j] && (out->nodes[j]->address.path ^ label) < (p ^ label)) {
  1579. break;
  1580. }
  1581. }
  1582. switch (j) {
  1583. default: Bits_memmove(out->nodes, &out->nodes[1], (j - 1) * sizeof(char*));
  1584. case 1: out->nodes[j - 1] = next->child;
  1585. case 0:;
  1586. }
  1587. }
  1588. out->size = 0;
  1589. for (int i = 0; i < (int)max; i++) {
  1590. if (out->nodes[i]) {
  1591. out->nodes = &out->nodes[i];
  1592. out->size = max - i;
  1593. break;
  1594. }
  1595. }
  1596. for (int i = 0; i < (int)out->size; i++) {
  1597. Identity_check(out->nodes[i]);
  1598. checkNode(out->nodes[i], store);
  1599. Assert_true(out->nodes[i]->address.path);
  1600. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1601. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1602. }
  1603. return out;
  1604. }
  1605. static bool isOkAnswer(struct Node_Two* node,
  1606. uint32_t compatVer,
  1607. struct NodeStore_pvt* store)
  1608. {
  1609. if (node->address.path == UINT64_MAX) {
  1610. // (very) unreachable
  1611. return false;
  1612. }
  1613. if (!Version_isCompatible(compatVer, node->address.protocolVersion)) {
  1614. return false;
  1615. }
  1616. if (node == store->pub.selfNode) {
  1617. return false;
  1618. }
  1619. return true;
  1620. }
  1621. /** See: NodeStore.h */
  1622. struct NodeList* NodeStore_getClosestNodes(struct NodeStore* nodeStore,
  1623. struct Address* targetAddress,
  1624. const uint32_t count,
  1625. uint32_t compatVer,
  1626. struct Allocator* allocator)
  1627. {
  1628. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1629. struct NodeList* out = Allocator_malloc(allocator, sizeof(struct NodeList));
  1630. out->nodes = Allocator_calloc(allocator, count, sizeof(char*));
  1631. out->size = count;
  1632. struct Node_Two fakeNode = { .marked = 0 };
  1633. Bits_memcpyConst(&fakeNode.address, targetAddress, sizeof(struct Address));
  1634. struct Node_Two* next = Identity_ncheck(RB_NFIND(NodeRBTree, &store->nodeTree, &fakeNode));
  1635. if (!next) {
  1636. out->size = 0;
  1637. return out;
  1638. }
  1639. struct Node_Two* prev = Identity_ncheck(NodeRBTree_RB_PREV(next));
  1640. int idx = out->size-1;
  1641. while (idx > -1) {
  1642. if (prev && (!next || Address_closest(targetAddress, &next->address, &prev->address) > 0)) {
  1643. if (isOkAnswer(prev, compatVer, store)) { out->nodes[idx--] = prev; }
  1644. prev = Identity_ncheck(NodeRBTree_RB_PREV(prev));
  1645. continue;
  1646. }
  1647. if (next && (!prev || Address_closest(targetAddress, &next->address, &prev->address) < 0)) {
  1648. if (isOkAnswer(next, compatVer, store)) { out->nodes[idx--] = next; }
  1649. next = Identity_ncheck(NodeRBTree_RB_NEXT(next));
  1650. continue;
  1651. }
  1652. break;
  1653. }
  1654. out->nodes = &out->nodes[idx+1];
  1655. out->size -= idx+1;
  1656. for (int i = 0; i < (int)out->size; i++) {
  1657. Identity_check(out->nodes[i]);
  1658. Assert_true(out->nodes[i]->address.path);
  1659. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1660. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1661. }
  1662. return out;
  1663. }
  1664. void NodeStore_disconnectedPeer(struct NodeStore* nodeStore, uint64_t path)
  1665. {
  1666. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1667. struct Node_Link* nl = NodeStore_linkForPath(nodeStore, path);
  1668. if (!nl) { return; }
  1669. if (Defined(Log_DEBUG)) {
  1670. uint8_t pathStr[20];
  1671. AddrTools_printPath(pathStr, path);
  1672. Log_debug(store->logger, "NodeStore_disconnectedPeer(%s)", pathStr);
  1673. }
  1674. NodeStore_unlinkNodes(&store->pub, nl);
  1675. }
  1676. static void brokenLink(struct NodeStore_pvt* store, struct Node_Link* brokenLink)
  1677. {
  1678. NodeStore_unlinkNodes(&store->pub, brokenLink);
  1679. }
  1680. void NodeStore_brokenLink(struct NodeStore* nodeStore, uint64_t path, uint64_t pathAtErrorHop)
  1681. {
  1682. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1683. if (Defined(Log_DEBUG)) {
  1684. uint8_t pathStr[20];
  1685. uint8_t pathAtErrorHopStr[20];
  1686. AddrTools_printPath(pathStr, path);
  1687. AddrTools_printPath(pathAtErrorHopStr, pathAtErrorHop);
  1688. Log_debug(store->logger, "NodeStore_brokenLink(%s, %s)", pathStr, pathAtErrorHopStr);
  1689. }
  1690. struct Node_Link* link = store->selfLink;
  1691. uint64_t thisPath = path;
  1692. for (;;) {
  1693. uint64_t nextPath = firstHopInPath(thisPath, &link, link, store);
  1694. uint64_t mask = (((uint64_t)1) << (Bits_log2x64(thisPath) + 1)) - 1;
  1695. if (Defined(Log_DEBUG)) {
  1696. uint8_t maskStr[20];
  1697. uint8_t pathStr[20];
  1698. AddrTools_printPath(pathStr, nextPath);
  1699. AddrTools_printPath(maskStr, mask);
  1700. Log_debug(store->logger, "NodeStore_brokenLink() nextPath = [%s] mask = [%s]",
  1701. pathStr, maskStr);
  1702. }
  1703. if ((pathAtErrorHop & mask) >= nextPath) {
  1704. uint64_t cannPathAtErrorHop =
  1705. EncodingScheme_convertLabel(link->child->encodingScheme,
  1706. (pathAtErrorHop & mask),
  1707. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  1708. uint8_t cannPathAtErrorHopStr[20];
  1709. AddrTools_printPath(cannPathAtErrorHopStr, cannPathAtErrorHop);
  1710. Log_debug(store->logger, "NodeStore_brokenLink() converted pathAtErrorHop to [%s]",
  1711. cannPathAtErrorHopStr);
  1712. if (cannPathAtErrorHop != UINT64_MAX && (cannPathAtErrorHop & mask) == thisPath) {
  1713. Log_debug(store->logger, "NodeStore_brokenLink() Great Success!");
  1714. brokenLink(store, link);
  1715. return;
  1716. }
  1717. } else if (firstHopInPath_NO_NEXT_LINK == nextPath && thisPath == 1) {
  1718. Log_debug(store->logger, "NodeStore_brokenLink() Great Success! (1link)");
  1719. Assert_ifParanoid(NodeStore_linkForPath(nodeStore, path) == link);
  1720. brokenLink(store, link);
  1721. return;
  1722. }
  1723. if (firstHopInPath_NO_NEXT_LINK == nextPath) {
  1724. Log_debug(store->logger, "NodeStore_brokenLink() firstHopInPath_NO_NEXT_LINK");
  1725. // fails if pathAtErrorHop is garbage.
  1726. Assert_ifTesting(!NodeStore_linkForPath(nodeStore, path));
  1727. return;
  1728. }
  1729. if (firstHopInPath_INVALID == nextPath) {
  1730. Log_debug(store->logger, "NodeStore_brokenLink() firstHopInPath_INVALID");
  1731. return;
  1732. }
  1733. Assert_true(link);
  1734. thisPath = nextPath;
  1735. }
  1736. }
  1737. // When a response comes in, we need to pay attention to the path used.
  1738. static void updatePathReach(struct NodeStore_pvt* store, const uint64_t path, uint32_t newReach)
  1739. {
  1740. struct Node_Link* link = store->selfLink;
  1741. uint64_t pathFrag = path;
  1742. for (;;) {
  1743. struct Node_Link* nextLink = NULL;
  1744. uint64_t nextPath = firstHopInPath(pathFrag, &nextLink, link, store);
  1745. if (firstHopInPath_ERR(nextPath)) {
  1746. break;
  1747. }
  1748. // expecting behavior of nextLinkOnPath()
  1749. Assert_ifParanoid(nextLink->parent == link->child);
  1750. if (Node_getBestParent(nextLink->child) == nextLink) {
  1751. // This is a performance hack, if nextLink->child->bestParent->parent is this node
  1752. // we'll skip updating reach here since even if we did, it would be updated all over
  1753. // again by the recursion inside of handleGoodNews because we're not deincrementing
  1754. // newReach per hop.
  1755. } else if (Node_getReach(link->child) >= newReach) {
  1756. // Node already has enough reach...
  1757. // selfNode reach == UINT32_MAX so this case handles it.
  1758. } else if (!LabelSplicer_routesThrough(path, link->child->address.path)) {
  1759. // The path the packet came in on is not actually the best known path to the node.
  1760. } else {
  1761. handleNews(link->child, newReach, store);
  1762. }
  1763. if (Node_getBestParent(link->child) == link) {
  1764. // Update linkState.
  1765. uint32_t guessedLinkState = subReach(Node_getReach(link->parent), newReach);
  1766. uint32_t linkStateDiff = (guessedLinkState > link->linkState)
  1767. ? (guessedLinkState - link->linkState)
  1768. : 1;
  1769. update(link, linkStateDiff, store);
  1770. }
  1771. pathFrag = nextPath;
  1772. link = nextLink;
  1773. }
  1774. // Now we have to unconditionally update the reach for the last link in the chain.
  1775. if (link->child && link->child->address.path == path) {
  1776. // Behavior of nextLinkOnPath()
  1777. Assert_ifParanoid(pathFrag == 1);
  1778. handleNews(link->child, newReach, store);
  1779. uint32_t newLinkState = subReach(Node_getReach(link->parent), newReach);
  1780. update(link, newLinkState - link->linkState, store);
  1781. }
  1782. }
  1783. void NodeStore_pathResponse(struct NodeStore* nodeStore, uint64_t path, uint64_t milliseconds)
  1784. {
  1785. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1786. struct Node_Link* link = NodeStore_linkForPath(nodeStore, path);
  1787. if (!link || link == store->selfLink) { return; }
  1788. struct Node_Two* node = link->child;
  1789. uint32_t newReach;
  1790. if (node->address.path == path) {
  1791. // Use old reach value to calculate new reach
  1792. newReach = calcNextReach(Node_getReach(node), milliseconds);
  1793. }
  1794. else {
  1795. // Old reach value doesn't relate to this path, so we should do something different
  1796. // FIXME(arceliar): calcNextReach is guessing what the reach would stabilize to
  1797. // I think actually fixing this would require storing reach (or latency?) per link,
  1798. // so we can calculate the expected reach for an arbitrary path
  1799. newReach = calcNextReach(0, milliseconds);
  1800. }
  1801. updatePathReach(store, path, newReach);
  1802. }
  1803. void NodeStore_pathTimeout(struct NodeStore* nodeStore, uint64_t path)
  1804. {
  1805. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1806. struct Node_Link* link = store->selfLink;
  1807. uint64_t pathFrag = path;
  1808. for (;;) {
  1809. struct Node_Link* nextLink = NULL;
  1810. uint64_t nextPath = firstHopInPath(pathFrag, &nextLink, link, store);
  1811. if (firstHopInPath_ERR(nextPath)) {
  1812. break;
  1813. }
  1814. // expecting behavior of nextLinkOnPath()
  1815. Assert_true(nextLink->parent == link->child);
  1816. if (link != store->selfLink) {
  1817. // TODO(arceliar): Something sane. We don't know which link on the path is bad.
  1818. // For now, just penalize them all.
  1819. // The good ones will be rewarded again when they relay another ping.
  1820. update(link, -link->linkState/2, store);
  1821. }
  1822. pathFrag = nextPath;
  1823. link = nextLink;
  1824. }
  1825. link = NodeStore_linkForPath(nodeStore, path);
  1826. if (!link || link->child->address.path != path) { return; }
  1827. struct Node_Two* node = link->child;
  1828. uint32_t newReach = reachAfterTimeout(Node_getReach(node));
  1829. if (Defined(Log_DEBUG)) {
  1830. uint8_t addr[60];
  1831. Address_print(addr, &node->address);
  1832. Log_debug(store->logger,
  1833. "Ping timeout for %s. changing reach from %u to %u\n",
  1834. addr,
  1835. Node_getReach(node),
  1836. newReach);
  1837. }
  1838. handleNews(node, newReach, store);
  1839. if (newReach > 1024) {
  1840. // Keep checking until we're sure it's either OK or down.
  1841. RumorMill_addNode(store->renumberMill, &node->address);
  1842. }
  1843. /* This workaround can lock the rumorMill in a bad state.
  1844. if (link->parent != store->pub.selfNode) {
  1845. // All we know for sure is that link->child didn't respond.
  1846. // That could be because an earlier link is down.
  1847. // Same idea as the workaround in NodeStore_brokenPath();
  1848. RumorMill_addNode(store->renumberMill, &link->parent->address);
  1849. }*/
  1850. }
  1851. /* Find the address that describes the source's Nth furthest-away bucket. */
  1852. struct Address NodeStore_addrForBucket(struct Address* source, uint8_t bucket)
  1853. {
  1854. if (bucket >= NodeStore_bucketNumber) {
  1855. // This does not exist.
  1856. return *source;
  1857. } else if (63 < bucket && bucket < 72) {
  1858. // We want to leave the 0xfc alone
  1859. // We also want a RouterModule_lookup() to succeed.
  1860. // Lets just return the furthest possible bucket.
  1861. return NodeStore_addrForBucket(source, 0);
  1862. } else {
  1863. uint8_t bit;
  1864. uint8_t byte;
  1865. struct Address addr = *source;
  1866. // Figure out which bit of our address to flip for this step in keyspace.
  1867. // This looks ugly because of the rot64 done in distance calculations.
  1868. if (bucket < 64) { byte = 8 + (bucket/8); }
  1869. else { byte = (bucket/8) - 8; }
  1870. bit = (bucket % 8);
  1871. addr.ip6.bytes[byte] = addr.ip6.bytes[byte] ^ (0x80 >> bit);
  1872. // Needed in case source == selfNode->address, and we want to put this in a RumorMill.
  1873. addr.key[0] = addr.key[0] ^ 0x80;
  1874. // Hack, store bucket # in path, in case we need to check this.
  1875. addr.path = bucket;
  1876. return addr;
  1877. }
  1878. }
  1879. uint8_t NodeStore_bucketForAddr(struct Address* source, struct Address* dest)
  1880. {
  1881. uint64_t partDist;
  1882. partDist = source->ip6.longs.one_be ^ dest->ip6.longs.one_be;
  1883. if (partDist) { return 63 - Bits_log2x64(partDist); }
  1884. partDist = source->ip6.longs.two_be ^ dest->ip6.longs.two_be;
  1885. return 127 - Bits_log2x64(partDist);
  1886. }