NodeStore.c 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  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. // truncate the label to the part which this node uses...
  1624. label &= Bits_maxBits64(NumberCompress_bitsUsedForLabel(label));
  1625. struct NodeList* out = Allocator_calloc(allocator, sizeof(struct NodeList), 1);
  1626. out->nodes = Allocator_calloc(allocator, sizeof(char*), max);
  1627. struct Node_Link* next = NULL;
  1628. RB_FOREACH_REVERSE(next, PeerRBTree, &store->pub.selfNode->peerTree) {
  1629. uint64_t p = next->child->address.path;
  1630. if (p > (((uint64_t)1)<<63)) { continue; }
  1631. int j;
  1632. for (j = 0; j < (int)max; j++) {
  1633. if (out->nodes[j] && (out->nodes[j]->address.path ^ label) < (p ^ label)) {
  1634. break;
  1635. }
  1636. }
  1637. switch (j) {
  1638. default: Bits_memmove(out->nodes, &out->nodes[1], (j - 1) * sizeof(char*));
  1639. case 1: out->nodes[j - 1] = next->child;
  1640. case 0:;
  1641. }
  1642. }
  1643. out->size = 0;
  1644. for (int i = 0; i < (int)max; i++) {
  1645. if (out->nodes[i]) {
  1646. out->nodes = &out->nodes[i];
  1647. out->size = max - i;
  1648. break;
  1649. }
  1650. }
  1651. for (int i = 0; i < (int)out->size; i++) {
  1652. Identity_check(out->nodes[i]);
  1653. checkNode(out->nodes[i], store);
  1654. Assert_true(out->nodes[i]->address.path);
  1655. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1656. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1657. }
  1658. return out;
  1659. }
  1660. static bool isOkAnswer(struct Node_Two* node,
  1661. uint32_t compatVer,
  1662. struct NodeStore_pvt* store)
  1663. {
  1664. if (node->address.path == UINT64_MAX) {
  1665. // (very) unreachable
  1666. return false;
  1667. }
  1668. if (!Version_isCompatible(compatVer, node->address.protocolVersion)) {
  1669. return false;
  1670. }
  1671. if (node == store->pub.selfNode) {
  1672. return false;
  1673. }
  1674. return true;
  1675. }
  1676. /** See: NodeStore.h */
  1677. struct NodeList* NodeStore_getClosestNodes(struct NodeStore* nodeStore,
  1678. struct Address* targetAddress,
  1679. const uint32_t count,
  1680. uint32_t compatVer,
  1681. struct Allocator* allocator)
  1682. {
  1683. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1684. struct NodeList* out = Allocator_malloc(allocator, sizeof(struct NodeList));
  1685. out->nodes = Allocator_calloc(allocator, count, sizeof(char*));
  1686. out->size = count;
  1687. struct Node_Two fakeNode = { .marked = 0 };
  1688. Bits_memcpyConst(&fakeNode.address, targetAddress, sizeof(struct Address));
  1689. struct Node_Two* next = Identity_ncheck(RB_NFIND(NodeRBTree, &store->nodeTree, &fakeNode));
  1690. if (!next) {
  1691. out->size = 0;
  1692. return out;
  1693. }
  1694. struct Node_Two* prev = Identity_ncheck(NodeRBTree_RB_PREV(next));
  1695. int idx = out->size-1;
  1696. while (idx > -1) {
  1697. if (prev && (!next || Address_closest(targetAddress, &next->address, &prev->address) > 0)) {
  1698. if (isOkAnswer(prev, compatVer, store)) { out->nodes[idx--] = prev; }
  1699. prev = Identity_ncheck(NodeRBTree_RB_PREV(prev));
  1700. continue;
  1701. }
  1702. if (next && (!prev || Address_closest(targetAddress, &next->address, &prev->address) < 0)) {
  1703. if (isOkAnswer(next, compatVer, store)) { out->nodes[idx--] = next; }
  1704. next = Identity_ncheck(NodeRBTree_RB_NEXT(next));
  1705. continue;
  1706. }
  1707. break;
  1708. }
  1709. out->nodes = &out->nodes[idx+1];
  1710. out->size -= idx+1;
  1711. for (int i = 0; i < (int)out->size; i++) {
  1712. Identity_check(out->nodes[i]);
  1713. Assert_true(out->nodes[i]->address.path);
  1714. Assert_true(out->nodes[i]->address.path < (((uint64_t)1)<<63));
  1715. out->nodes[i] = Allocator_clone(allocator, out->nodes[i]);
  1716. }
  1717. return out;
  1718. }
  1719. void NodeStore_disconnectedPeer(struct NodeStore* nodeStore, uint64_t path)
  1720. {
  1721. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1722. struct Node_Link* nl = NodeStore_linkForPath(nodeStore, path);
  1723. if (!nl) { return; }
  1724. if (Defined(Log_DEBUG)) {
  1725. uint8_t pathStr[20];
  1726. AddrTools_printPath(pathStr, path);
  1727. Log_debug(store->logger, "NodeStore_disconnectedPeer(%s)", pathStr);
  1728. }
  1729. NodeStore_unlinkNodes(&store->pub, nl);
  1730. }
  1731. static void brokenLink(struct NodeStore_pvt* store, struct Node_Link* brokenLink)
  1732. {
  1733. NodeStore_unlinkNodes(&store->pub, brokenLink);
  1734. }
  1735. void NodeStore_brokenLink(struct NodeStore* nodeStore, uint64_t path, uint64_t pathAtErrorHop)
  1736. {
  1737. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1738. if (Defined(Log_DEBUG)) {
  1739. uint8_t pathStr[20];
  1740. uint8_t pathAtErrorHopStr[20];
  1741. AddrTools_printPath(pathStr, path);
  1742. AddrTools_printPath(pathAtErrorHopStr, pathAtErrorHop);
  1743. Log_debug(store->logger, "NodeStore_brokenLink(%s, %s)", pathStr, pathAtErrorHopStr);
  1744. }
  1745. struct Node_Link* link = store->selfLink;
  1746. uint64_t thisPath = path;
  1747. for (;;) {
  1748. uint64_t nextPath = firstHopInPath(thisPath, &link, link, store);
  1749. uint64_t mask = (((uint64_t)1) << (Bits_log2x64(thisPath) + 1)) - 1;
  1750. if (Defined(Log_DEBUG)) {
  1751. uint8_t maskStr[20];
  1752. uint8_t pathStr[20];
  1753. AddrTools_printPath(pathStr, nextPath);
  1754. AddrTools_printPath(maskStr, mask);
  1755. Log_debug(store->logger, "NodeStore_brokenLink() nextPath = [%s] mask = [%s]",
  1756. pathStr, maskStr);
  1757. }
  1758. if ((pathAtErrorHop & mask) >= nextPath) {
  1759. uint64_t cannPathAtErrorHop =
  1760. EncodingScheme_convertLabel(link->child->encodingScheme,
  1761. (pathAtErrorHop & mask),
  1762. EncodingScheme_convertLabel_convertTo_CANNONICAL);
  1763. uint8_t cannPathAtErrorHopStr[20];
  1764. AddrTools_printPath(cannPathAtErrorHopStr, cannPathAtErrorHop);
  1765. Log_debug(store->logger, "NodeStore_brokenLink() converted pathAtErrorHop to [%s]",
  1766. cannPathAtErrorHopStr);
  1767. if (cannPathAtErrorHop != UINT64_MAX && (cannPathAtErrorHop & mask) == thisPath) {
  1768. Log_debug(store->logger, "NodeStore_brokenLink() Great Success!");
  1769. brokenLink(store, link);
  1770. return;
  1771. }
  1772. } else if (firstHopInPath_NO_NEXT_LINK == nextPath && thisPath == 1) {
  1773. Log_debug(store->logger, "NodeStore_brokenLink() Great Success! (1link)");
  1774. Assert_ifParanoid(NodeStore_linkForPath(nodeStore, path) == link);
  1775. brokenLink(store, link);
  1776. return;
  1777. }
  1778. if (firstHopInPath_NO_NEXT_LINK == nextPath) {
  1779. Log_debug(store->logger, "NodeStore_brokenLink() firstHopInPath_NO_NEXT_LINK");
  1780. // fails if pathAtErrorHop is garbage.
  1781. Assert_ifTesting(!NodeStore_linkForPath(nodeStore, path));
  1782. return;
  1783. }
  1784. if (firstHopInPath_INVALID == nextPath) {
  1785. Log_debug(store->logger, "NodeStore_brokenLink() firstHopInPath_INVALID");
  1786. return;
  1787. }
  1788. Assert_true(link);
  1789. thisPath = nextPath;
  1790. }
  1791. }
  1792. // When a response comes in, we need to pay attention to the path used.
  1793. static void updatePathReach(struct NodeStore_pvt* store, const uint64_t path, uint32_t newReach)
  1794. {
  1795. struct Node_Link* link = store->selfLink;
  1796. uint64_t pathFrag = path;
  1797. uint64_t now = Time_currentTimeMilliseconds(store->eventBase);
  1798. for (;;) {
  1799. struct Node_Link* nextLink = NULL;
  1800. uint64_t nextPath = firstHopInPath(pathFrag, &nextLink, link, store);
  1801. if (firstHopInPath_ERR(nextPath)) {
  1802. break;
  1803. }
  1804. // expecting behavior of nextLinkOnPath()
  1805. Assert_ifParanoid(nextLink->parent == link->child);
  1806. if (Node_getBestParent(nextLink->child) != nextLink) {
  1807. // If nextLink->child->bestParent is worse than nextLink, we should replace it.
  1808. uint64_t newPath = extendRoute(nextLink->parent->address.path,
  1809. nextLink->parent->encodingScheme,
  1810. nextLink->cannonicalLabel,
  1811. link->inverseLinkEncodingFormNumber);
  1812. if (newPath != extendRoute_INVALID &&
  1813. Node_getReach(nextLink->child) < newReach &&
  1814. Node_getReach(nextLink->parent) > newReach &&
  1815. Node_getReach(nextLink->child) < guessReachOfChild(nextLink))
  1816. {
  1817. // This path apparently gives us a better route than our current bestParent.
  1818. updateBestParent(nextLink, newReach, store);
  1819. }
  1820. }
  1821. if (Node_getBestParent(nextLink->child) == nextLink) {
  1822. // This is a performance hack, if nextLink->child->bestParent->parent is this node
  1823. // we'll skip updating reach here since even if we did, it would be updated all over
  1824. // again by the recursion inside of handleGoodNews because we're not deincrementing
  1825. // newReach per hop.
  1826. } else if (Node_getReach(link->child) >= newReach) {
  1827. // Node already has enough reach...
  1828. // selfNode reach == UINT32_MAX so this case handles it.
  1829. } else if (!LabelSplicer_routesThrough(path, link->child->address.path)) {
  1830. // The path the packet came in on is not actually the best known path to the node.
  1831. } else {
  1832. handleNews(link->child, newReach, store);
  1833. }
  1834. if (Node_getBestParent(link->child) == link) {
  1835. // Update linkState.
  1836. uint32_t guessedLinkState = subReach(Node_getReach(link->parent), newReach);
  1837. uint32_t linkStateDiff = (guessedLinkState > link->linkState)
  1838. ? (guessedLinkState - link->linkState)
  1839. : 1;
  1840. update(link, linkStateDiff, store);
  1841. } else {
  1842. // Well we at least know it's not dead.
  1843. update(link, 1, store);
  1844. }
  1845. nextLink->timeLastSeen = now;
  1846. pathFrag = nextPath;
  1847. link = nextLink;
  1848. }
  1849. // Now we have to unconditionally update the reach for the last link in the chain.
  1850. if (link->child && link->child->address.path == path) {
  1851. // Behavior of nextLinkOnPath()
  1852. Assert_ifParanoid(pathFrag == 1);
  1853. handleNews(link->child, newReach, store);
  1854. uint32_t newLinkState = subReach(Node_getReach(link->parent), newReach);
  1855. update(link, newLinkState - link->linkState, store);
  1856. }
  1857. link->child->timeLastPinged = Time_currentTimeMilliseconds(store->eventBase);
  1858. }
  1859. void NodeStore_pathResponse(struct NodeStore* nodeStore, uint64_t path, uint64_t milliseconds)
  1860. {
  1861. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1862. struct Node_Link* link = NodeStore_linkForPath(nodeStore, path);
  1863. if (!link || link == store->selfLink) { return; }
  1864. struct Node_Two* node = link->child;
  1865. uint32_t newReach;
  1866. if (node->address.path == path) {
  1867. // Use old reach value to calculate new reach.
  1868. newReach = calcNextReach(Node_getReach(node), milliseconds);
  1869. }
  1870. else {
  1871. // Old reach value doesn't relate to this path, so we should do something different
  1872. // FIXME(arceliar): calcNextReach is guessing what the reach would stabilize to
  1873. // I think actually fixing this would require storing reach (or latency?) per link,
  1874. // so we can calculate the expected reach for an arbitrary path
  1875. newReach = calcNextReach(0, milliseconds);
  1876. }
  1877. updatePathReach(store, path, newReach);
  1878. }
  1879. void NodeStore_pathTimeout(struct NodeStore* nodeStore, uint64_t path)
  1880. {
  1881. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1882. struct Node_Link* link = store->selfLink;
  1883. uint64_t pathFrag = path;
  1884. for (;;) {
  1885. struct Node_Link* nextLink = NULL;
  1886. uint64_t nextPath = firstHopInPath(pathFrag, &nextLink, link, store);
  1887. if (firstHopInPath_ERR(nextPath)) {
  1888. break;
  1889. }
  1890. // expecting behavior of nextLinkOnPath()
  1891. Assert_true(nextLink->parent == link->child);
  1892. if (link != store->selfLink) {
  1893. // TODO(arceliar): Something sane. We don't know which link on the path is bad.
  1894. // For now, just penalize them all.
  1895. // The good ones will be rewarded again when they relay another ping.
  1896. update(link, reachAfterTimeout(link->linkState)-link->linkState, store);
  1897. }
  1898. pathFrag = nextPath;
  1899. link = nextLink;
  1900. }
  1901. link = NodeStore_linkForPath(nodeStore, path);
  1902. if (!link || link->child->address.path != path) { return; }
  1903. struct Node_Two* node = link->child;
  1904. uint32_t newReach = reachAfterTimeout(Node_getReach(node));
  1905. if (!newReach) {
  1906. // The node hasn't responded in a really long time.
  1907. // Possible causes:
  1908. // 1) The node is offline, and for some reason we're not getting an error packet back.
  1909. // 2) The node is behind a node that's offline, and for some reason we're not getting error.
  1910. // 3) The node is online, but in a bad state, where it cannot respond to pings.
  1911. // (E.g. Our CA session broke and it refuses to reset, known bug in old versions.)
  1912. // If we don't do something, we'll guessReachOfChild to re-discover a path through the link.
  1913. // Doing that can get the node store stuck in a bad state where this node is blackholed.
  1914. // As a workaround, break the link. That prevents re-discovering the same broken path.
  1915. // If 2), we might accidentally break a valid link, but we should re-discover it the
  1916. // next time we successfully contact link->child (via another path).
  1917. brokenLink(store, link);
  1918. return;
  1919. }
  1920. if (Defined(Log_DEBUG)) {
  1921. uint8_t addr[60];
  1922. Address_print(addr, &node->address);
  1923. Log_debug(store->logger,
  1924. "Ping timeout for %s. changing reach from %u to %u\n",
  1925. addr,
  1926. Node_getReach(node),
  1927. newReach);
  1928. }
  1929. handleNews(node, newReach, store);
  1930. if (node->address.path != path) { return; }
  1931. // TODO(cjd): What we really should be doing here is storing this link in a
  1932. // potentially-down-list, after pinging the parent, if the parent does not respond
  1933. // and then we replace the link with the parent's link and walk backwards up
  1934. // the tree. If the parent does respond then we keep pinging the child of the path
  1935. // hoping it will respond or die and as it's link-state is destroyed by subsequent
  1936. // lost packets, children will be re-parented to other paths.
  1937. // Keep checking until we're sure it's either OK or down.
  1938. RumorMill_addNode(store->renumberMill, &node->address);
  1939. if (link->parent != store->pub.selfNode) {
  1940. // All we know for sure is that link->child didn't respond.
  1941. // That could be because an earlier link is down.
  1942. // Same idea as the workaround in NodeStore_brokenPath();
  1943. RumorMill_addNode(store->renumberMill, &link->parent->address);
  1944. }
  1945. }
  1946. /* Find the address that describes the source's Nth (furthest-away) bucket. */
  1947. struct Address NodeStore_addrForBucket(struct Address* source, uint16_t bucket)
  1948. {
  1949. if (bucket >= NodeStore_bucketNumber) {
  1950. // This does not exist.
  1951. return *source;
  1952. } else {
  1953. struct Address addr = *source;
  1954. // Figure out which bits of our address to flip for this step in keyspace.
  1955. // Note: This assumes NodeStore_bucketNumber == 512
  1956. // (Some of those, the fc and every 16th bucket, won't actually have nodes)
  1957. Assert_compileTime(NodeStore_bucketNumber == 512);
  1958. uint64_t extras = 15 - ((bucket % 256)/16);
  1959. uint64_t prefix = 0x0F - (bucket % 16);
  1960. uint64_t bitmask = prefix << (4*extras);
  1961. // We have the bitmask for this bucket, now we need to apply it.
  1962. uint64_t* addrPart = (bucket < 256) ? &addr.ip6.longs.one_be : &addr.ip6.longs.two_be;
  1963. *addrPart = Endian_bigEndianToHost64(*addrPart);
  1964. *addrPart ^= bitmask;
  1965. *addrPart = Endian_hostToBigEndian64(*addrPart);
  1966. // Just to be sure...
  1967. Assert_ifParanoid((bucket % 16) == 15 || NodeStore_bucketForAddr(source, &addr) == bucket);
  1968. return addr;
  1969. }
  1970. }
  1971. uint16_t NodeStore_bucketForAddr(struct Address* source, struct Address* dest)
  1972. {
  1973. uint16_t retVal = 0;
  1974. // This is a place where the implementation depends on how buckets work.
  1975. Assert_compileTime(NodeStore_bucketNumber == 512);
  1976. uint64_t addrPart = source->ip6.longs.one_be ^ dest->ip6.longs.one_be;
  1977. if (!addrPart) {
  1978. // We're apparently close enough in keyspace to use two_be instead.
  1979. addrPart = source->ip6.longs.two_be ^ dest->ip6.longs.two_be;
  1980. retVal += 256;
  1981. }
  1982. addrPart = Endian_bigEndianToHost64(addrPart);
  1983. uint64_t extras = Bits_log2x64(addrPart)/4;
  1984. uint64_t prefix = addrPart >> (4*extras);
  1985. retVal += (15 - extras)*16;
  1986. retVal += 0x0F - prefix;
  1987. return retVal;
  1988. }
  1989. uint64_t NodeStore_timeSinceLastPing(struct NodeStore* nodeStore, struct Node_Two* node)
  1990. {
  1991. struct NodeStore_pvt* store = Identity_check((struct NodeStore_pvt*)nodeStore);
  1992. uint64_t now = Time_currentTimeMilliseconds(store->eventBase);
  1993. uint64_t lastSeen = node->timeLastPinged;
  1994. struct Node_Link* link = Node_getBestParent(node);
  1995. while (link && link != store->selfLink) {
  1996. lastSeen = (link->timeLastSeen < lastSeen) ? link->timeLastSeen : lastSeen;
  1997. link = Node_getBestParent(link->parent);
  1998. }
  1999. return now - lastSeen;
  2000. }