NodeStore.c 87 KB

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