Pathfinder.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/AddressCalc.h"
  16. #include "dht/Pathfinder.h"
  17. #include "dht/DHTModule.h"
  18. #include "dht/Address.h"
  19. #include "util/version/Version.h"
  20. #include "wire/DataHeader.h"
  21. #include "wire/RouteHeader.h"
  22. #include "dht/ReplyModule.h"
  23. #include "dht/EncodingSchemeModule.h"
  24. #include "dht/Pathfinder_pvt.h"
  25. #include "dht/SerializationModule.h"
  26. #include "dht/dhtcore/RouterModule.h"
  27. #include "dht/dhtcore/RouterModule_admin.h"
  28. #include "dht/dhtcore/RumorMill.h"
  29. #include "dht/dhtcore/SearchRunner.h"
  30. #include "dht/dhtcore/SearchRunner_admin.h"
  31. #include "dht/dhtcore/NodeStore_admin.h"
  32. #include "dht/dhtcore/Janitor_admin.h"
  33. #include "dht/dhtcore/Janitor.h"
  34. #include "dht/dhtcore/Router_new.h"
  35. #include "util/AddrTools.h"
  36. #include "util/events/Timeout.h"
  37. #include "wire/Error.h"
  38. #include "wire/PFChan.h"
  39. #include "util/CString.h"
  40. #include "wire/Metric.h"
  41. ///////////////////// [ Address ][ content... ]
  42. #define RUMORMILL_CAPACITY 64
  43. struct Pathfinder_pvt
  44. {
  45. struct Pathfinder pub;
  46. struct DHTModule dhtModule;
  47. struct Allocator* alloc;
  48. struct Log* log;
  49. EventBase_t* base;
  50. struct Random* rand;
  51. struct Admin* admin;
  52. #define Pathfinder_pvt_state_INITIALIZING 0
  53. #define Pathfinder_pvt_state_RUNNING 1
  54. int state;
  55. int bestPathChanges;
  56. // After begin connected, these fields will be filled.
  57. struct Address myAddr;
  58. struct DHTModuleRegistry* registry;
  59. struct NodeStore* nodeStore;
  60. struct Router* router;
  61. struct SearchRunner* searchRunner;
  62. struct RumorMill* rumorMill;
  63. struct Janitor* janitor;
  64. Identity
  65. };
  66. struct NodeStore* Pathfinder_getNodeStore(struct Pathfinder* pathfinder)
  67. {
  68. struct Pathfinder_pvt* pf = Identity_check((struct Pathfinder_pvt*) pathfinder);
  69. return pf->nodeStore;
  70. }
  71. static int incomingFromDHT(struct DHTMessage* dmessage, void* vpf)
  72. {
  73. struct Pathfinder_pvt* pf = Identity_check((struct Pathfinder_pvt*) vpf);
  74. Message_t* msg = dmessage->binMessage;
  75. struct Address* addr = dmessage->address;
  76. if (addr->path == 1) {
  77. // Message to myself, can't handle this later because encrypting a message to yourself
  78. // causes problems.
  79. DHTModuleRegistry_handleIncoming(dmessage, pf->registry);
  80. return 0;
  81. }
  82. // This seems to be happening, this whole section of the code is deprecated so lets not
  83. // try to debug it too much and just squash the message.
  84. if (addr->path == 0xffffffffffffffffull) {
  85. return 0;
  86. }
  87. // Sanity check (make sure the addr was actually calculated)
  88. Assert_true(AddressCalc_validAddress(addr->ip6.bytes));
  89. Err_assert(Message_eshift(msg, PFChan_Msg_MIN_SIZE));
  90. struct PFChan_Msg* emsg = (struct PFChan_Msg*) Message_bytes(msg);
  91. Bits_memset(emsg, 0, PFChan_Msg_MIN_SIZE);
  92. DataHeader_setVersion(&emsg->data, DataHeader_CURRENT_VERSION);
  93. DataHeader_setContentType(&emsg->data, ContentType_CJDHT);
  94. Bits_memcpy(emsg->route.ip6, addr->ip6.bytes, 16);
  95. emsg->route.version_be = Endian_hostToBigEndian32(addr->protocolVersion);
  96. emsg->route.sh.label_be = Endian_hostToBigEndian64(addr->path);
  97. emsg->route.flags |= RouteHeader_flags_PATHFINDER;
  98. SwitchHeader_setVersion(&emsg->route.sh, SwitchHeader_CURRENT_VERSION);
  99. Bits_memcpy(emsg->route.publicKey, addr->key, 32);
  100. Assert_true(!Bits_isZero(emsg->route.publicKey, 32));
  101. Assert_true(emsg->route.sh.label_be);
  102. Assert_true(emsg->route.sh.label_be != 0xffffffffffffffffull);
  103. Assert_true(emsg->route.version_be);
  104. Err_assert(Message_epush32be(msg, PFChan_Pathfinder_SENDMSG));
  105. if (dmessage->replyTo) {
  106. // see incomingMsg
  107. dmessage->replyTo->pleaseRespond = true;
  108. //Log_debug(pf->log, "send DHT reply");
  109. return 0;
  110. }
  111. //Log_debug(pf->log, "send DHT request");
  112. Iface_send(&pf->pub.eventIf, msg);
  113. return 0;
  114. }
  115. static void nodeForAddress(struct PFChan_Node* nodeOut, struct Address* addr, uint32_t metric)
  116. {
  117. Bits_memset(nodeOut, 0, PFChan_Node_SIZE);
  118. nodeOut->version_be = Endian_hostToBigEndian32(addr->protocolVersion);
  119. nodeOut->metric_be = Endian_hostToBigEndian32(metric);
  120. nodeOut->path_be = Endian_hostToBigEndian64(addr->path);
  121. Bits_memcpy(nodeOut->publicKey, addr->key, 32);
  122. Bits_memcpy(nodeOut->ip6, addr->ip6.bytes, 16);
  123. }
  124. static Iface_DEFUN sendNode(Message_t* msg,
  125. struct Address* addr,
  126. uint32_t metric,
  127. struct Pathfinder_pvt* pf)
  128. {
  129. Message_reset(msg);
  130. Err(Message_eshift(msg, PFChan_Node_SIZE));
  131. nodeForAddress((struct PFChan_Node*) Message_bytes(msg), addr, metric);
  132. if (addr->path == UINT64_MAX) {
  133. ((struct PFChan_Node*) Message_bytes(msg))->path_be = 0;
  134. }
  135. Err(Message_epush32be(msg, PFChan_Pathfinder_NODE));
  136. return Iface_next(&pf->pub.eventIf, msg);
  137. }
  138. static void onBestPathChange(void* vPathfinder, struct Node_Two* node)
  139. {
  140. struct Pathfinder_pvt* pf = Identity_check((struct Pathfinder_pvt*) vPathfinder);
  141. struct Allocator* alloc = Allocator_child(pf->alloc);
  142. if (pf->bestPathChanges > 128) {
  143. String* addrPrinted = Address_toString(&node->address, alloc);
  144. Log_debug(pf->log, "Ignore best path change from NodeStore [%s]", addrPrinted->bytes);
  145. } else {
  146. pf->bestPathChanges++;
  147. Message_t* msg = Message_new(0, 256, alloc);
  148. Iface_CALL(sendNode, msg, &node->address,
  149. (Node_getCost(node) & Metric_DHT_MASK) | Metric_DHT,
  150. pf);
  151. }
  152. Allocator_free(alloc);
  153. }
  154. static Iface_DEFUN connected(struct Pathfinder_pvt* pf, Message_t* msg)
  155. {
  156. Log_debug(pf->log, "INIT");
  157. struct PFChan_Core_Connect conn;
  158. Err(Message_epop(msg, &conn, PFChan_Core_Connect_SIZE));
  159. Assert_true(!Message_getLength(msg));
  160. Bits_memcpy(pf->myAddr.key, conn.publicKey, 32);
  161. Address_getPrefix(&pf->myAddr);
  162. pf->myAddr.path = 1;
  163. // begin
  164. pf->registry = DHTModuleRegistry_new(pf->alloc, pf->log);
  165. ReplyModule_register(pf->registry, pf->alloc);
  166. pf->rumorMill = RumorMill_new(pf->alloc, &pf->myAddr, RUMORMILL_CAPACITY, pf->log, "extern");
  167. pf->nodeStore = NodeStore_new(&pf->myAddr, pf->alloc, pf->base, pf->log, pf->rumorMill);
  168. if (pf->pub.fullVerify) {
  169. NodeStore_setFullVerify(pf->nodeStore, true);
  170. }
  171. pf->nodeStore->onBestPathChange = onBestPathChange;
  172. pf->nodeStore->onBestPathChangeCtx = pf;
  173. struct RouterModule* routerModule = RouterModule_register(pf->registry,
  174. pf->alloc,
  175. pf->myAddr.key,
  176. pf->base,
  177. pf->log,
  178. pf->rand,
  179. pf->nodeStore);
  180. pf->searchRunner = SearchRunner_new(pf->nodeStore,
  181. pf->log,
  182. pf->base,
  183. routerModule,
  184. pf->myAddr.ip6.bytes,
  185. pf->rumorMill,
  186. pf->alloc);
  187. pf->janitor = Janitor_new(routerModule,
  188. pf->nodeStore,
  189. pf->searchRunner,
  190. pf->rumorMill,
  191. pf->log,
  192. pf->alloc,
  193. pf->base,
  194. pf->rand);
  195. EncodingSchemeModule_register(pf->registry, pf->log, pf->alloc);
  196. SerializationModule_register(pf->registry, pf->log, pf->alloc);
  197. DHTModuleRegistry_register(&pf->dhtModule, pf->registry);
  198. pf->router = Router_new(routerModule, pf->nodeStore, pf->searchRunner, pf->alloc);
  199. // Now the admin stuff...
  200. if (pf->admin) {
  201. NodeStore_admin_register(pf->nodeStore, pf->admin, pf->alloc);
  202. RouterModule_admin_register(routerModule, pf->router, pf->admin, pf->alloc);
  203. SearchRunner_admin_register(pf->searchRunner, pf->admin, pf->alloc);
  204. Janitor_admin_register(pf->janitor, pf->admin, pf->alloc);
  205. }
  206. pf->state = Pathfinder_pvt_state_RUNNING;
  207. return NULL;
  208. }
  209. static void addressForNode(struct Address* addrOut, Message_t* msg)
  210. {
  211. struct PFChan_Node node;
  212. Err_assert(Message_epop(msg, &node, PFChan_Node_SIZE));
  213. Assert_true(!Message_getLength(msg));
  214. addrOut->protocolVersion = Endian_bigEndianToHost32(node.version_be);
  215. addrOut->path = Endian_bigEndianToHost64(node.path_be);
  216. Bits_memcpy(addrOut->key, node.publicKey, 32);
  217. Bits_memcpy(addrOut->ip6.bytes, node.ip6, 16);
  218. }
  219. static Iface_DEFUN switchErr(Message_t* msg, struct Pathfinder_pvt* pf)
  220. {
  221. struct PFChan_Core_SwitchErr switchErr;
  222. Err(Message_epop(msg, &switchErr, PFChan_Core_SwitchErr_MIN_SIZE));
  223. uint64_t path = Endian_bigEndianToHost64(switchErr.sh.label_be);
  224. uint64_t pathAtErrorHop = Endian_bigEndianToHost64(switchErr.ctrlErr.cause.label_be);
  225. uint8_t pathStr[20];
  226. AddrTools_printPath(pathStr, path);
  227. int err = Endian_bigEndianToHost32(switchErr.ctrlErr.errorType_be);
  228. Log_debug(pf->log, "switch err from [%s] type [%d]", pathStr, err);
  229. struct Node_Link* link = NodeStore_linkForPath(pf->nodeStore, path);
  230. uint8_t nodeAddr[16];
  231. if (link) {
  232. Bits_memcpy(nodeAddr, link->child->address.ip6.bytes, 16);
  233. }
  234. NodeStore_brokenLink(pf->nodeStore, path, pathAtErrorHop);
  235. if (link) {
  236. // Don't touch the node again, it might be a dangling pointer
  237. SearchRunner_search(nodeAddr, 20, 3, pf->searchRunner, pf->alloc);
  238. }
  239. return NULL;
  240. }
  241. static Iface_DEFUN searchReq(Message_t* msg, struct Pathfinder_pvt* pf)
  242. {
  243. uint8_t addr[16];
  244. Err(Message_epop(msg, addr, 16));
  245. uint32_t discard = 0;
  246. Err(Message_epop32be(&discard, msg));
  247. uint32_t version = 0;
  248. Err(Message_epop32be(&version, msg));
  249. if (version && version >= 20) { return NULL; }
  250. Assert_true(!Message_getLength(msg));
  251. uint8_t printedAddr[40];
  252. AddrTools_printIp(printedAddr, addr);
  253. Log_debug(pf->log, "Search req [%s]", printedAddr);
  254. struct Node_Two* node = NodeStore_nodeForAddr(pf->nodeStore, addr);
  255. if (node) {
  256. onBestPathChange(pf, node);
  257. } else {
  258. SearchRunner_search(addr, 20, 3, pf->searchRunner, pf->alloc);
  259. }
  260. return NULL;
  261. }
  262. static Iface_DEFUN peer(Message_t* msg, struct Pathfinder_pvt* pf)
  263. {
  264. struct Address addr = {0};
  265. addressForNode(&addr, msg);
  266. String* str = Address_toString(&addr, Message_getAlloc(msg));
  267. Log_debug(pf->log, "Peer [%s]", str->bytes);
  268. struct Node_Link* link = NodeStore_linkForPath(pf->nodeStore, addr.path);
  269. // It exists, it's parent is the self-node, and it's label is equal to the switchLabel.
  270. if (link
  271. && Node_getBestParent(link->child)
  272. && Node_getBestParent(link->child)->parent->address.path == 1
  273. && Node_getBestParent(link->child)->cannonicalLabel == addr.path)
  274. {
  275. return NULL;
  276. }
  277. //RumorMill_addNode(pf->rumorMill, &addr);
  278. Router_sendGetPeers(pf->router, &addr, 0, 0, pf->alloc);
  279. return sendNode(msg, &addr, Metric_DHT_PEER, pf);
  280. }
  281. static Iface_DEFUN peerGone(Message_t* msg, struct Pathfinder_pvt* pf)
  282. {
  283. struct Address addr = {0};
  284. addressForNode(&addr, msg);
  285. String* str = Address_toString(&addr, Message_getAlloc(msg));
  286. Log_debug(pf->log, "Peer gone [%s]", str->bytes);
  287. NodeStore_disconnectedPeer(pf->nodeStore, addr.path);
  288. // We notify about the node but with max metric so it will be removed soon.
  289. return sendNode(msg, &addr, Metric_DEAD_LINK, pf);
  290. }
  291. static Iface_DEFUN session(Message_t* msg, struct Pathfinder_pvt* pf)
  292. {
  293. struct Address addr = {0};
  294. addressForNode(&addr, msg);
  295. String* str = Address_toString(&addr, Message_getAlloc(msg));
  296. Log_debug(pf->log, "Session [%s]", str->bytes);
  297. /* This triggers for every little ping we send to some random node out there which
  298. * sucks too much to ever get into the nodeStore.
  299. struct Node_Two* node = NodeStore_nodeForAddr(pf->nodeStore, addr.ip6.bytes);
  300. if (!node) {
  301. SearchRunner_search(addr.ip6.bytes, 20, 3, pf->searchRunner, pf->alloc);
  302. }*/
  303. return NULL;
  304. }
  305. static Iface_DEFUN sessionEnded(Message_t* msg, struct Pathfinder_pvt* pf)
  306. {
  307. struct Address addr = {0};
  308. addressForNode(&addr, msg);
  309. String* str = Address_toString(&addr, Message_getAlloc(msg));
  310. Log_debug(pf->log, "Session ended [%s]", str->bytes);
  311. return NULL;
  312. }
  313. static Iface_DEFUN discoveredPath(Message_t* msg, struct Pathfinder_pvt* pf)
  314. {
  315. struct Address addr = {0};
  316. addressForNode(&addr, msg);
  317. // We're somehow aware of this path (even if it's unused)
  318. if (NodeStore_linkForPath(pf->nodeStore, addr.path)) { return NULL; }
  319. // If we don't already care about the destination, then don't do anything.
  320. struct Node_Two* nn = NodeStore_nodeForAddr(pf->nodeStore, addr.ip6.bytes);
  321. if (!nn) { return NULL; }
  322. // Our best path is "shorter" (label bits which is somewhat representitive of hop count)
  323. // basically this is just to dampen the flood to the RM because otherwise it prevents Janitor
  324. // from getting any actual work done.
  325. if (nn->address.path < addr.path) { return NULL; }
  326. addr.protocolVersion = nn->address.protocolVersion;
  327. Log_debug(pf->log, "Discovered path [%s]", Address_toString(&addr, Message_getAlloc(msg))->bytes);
  328. RumorMill_addNode(pf->rumorMill, &addr);
  329. return NULL;
  330. }
  331. static Iface_DEFUN handlePing(Message_t* msg, struct Pathfinder_pvt* pf)
  332. {
  333. Log_debug(pf->log, "Received ping");
  334. Err(Message_epush32be(msg, PFChan_Pathfinder_PONG));
  335. return Iface_next(&pf->pub.eventIf, msg);
  336. }
  337. static Iface_DEFUN handlePong(Message_t* msg, struct Pathfinder_pvt* pf)
  338. {
  339. Log_debug(pf->log, "Received pong");
  340. return NULL;
  341. }
  342. static Iface_DEFUN incomingMsg(Message_t* msg, struct Pathfinder_pvt* pf)
  343. {
  344. struct Address addr = {0};
  345. struct RouteHeader* hdr = (struct RouteHeader*) Message_bytes(msg);
  346. Err(Message_eshift(msg, -(RouteHeader_SIZE + DataHeader_SIZE)));
  347. Bits_memcpy(addr.ip6.bytes, hdr->ip6, 16);
  348. Bits_memcpy(addr.key, hdr->publicKey, 32);
  349. addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
  350. addr.padding = 0;
  351. addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);
  352. //Log_debug(pf->log, "Incoming DHT");
  353. struct DHTMessage dht = {
  354. .address = &addr,
  355. .binMessage = msg,
  356. .allocator = Message_getAlloc(msg)
  357. };
  358. DHTModuleRegistry_handleIncoming(&dht, pf->registry);
  359. Message_t* nodeMsg = Message_new(0, 256, Message_getAlloc(msg));
  360. Iface_CALL(sendNode, nodeMsg, &addr, Metric_DHT_INCOMING, pf);
  361. if (dht.pleaseRespond) {
  362. // what a beautiful hack, see incomingFromDHT
  363. return Iface_next(&pf->pub.eventIf, msg);
  364. }
  365. return NULL;
  366. }
  367. static Iface_DEFUN incomingFromEventIf(Message_t* msg, struct Iface* eventIf)
  368. {
  369. struct Pathfinder_pvt* pf = Identity_containerOf(eventIf, struct Pathfinder_pvt, pub.eventIf);
  370. enum PFChan_Core ev = 0;
  371. Err(Message_epop32be(&ev, msg));
  372. if (Pathfinder_pvt_state_INITIALIZING == pf->state) {
  373. Assert_true(ev == PFChan_Core_CONNECT);
  374. return connected(pf, msg);
  375. }
  376. // Let the PF send another 128 path changes again because it's basically a new tick.
  377. pf->bestPathChanges = 0;
  378. switch (ev) {
  379. case PFChan_Core_SWITCH_ERR: return switchErr(msg, pf);
  380. case PFChan_Core_SEARCH_REQ: return searchReq(msg, pf);
  381. case PFChan_Core_PEER: return peer(msg, pf);
  382. case PFChan_Core_PEER_GONE: return peerGone(msg, pf);
  383. case PFChan_Core_SESSION: return session(msg, pf);
  384. case PFChan_Core_SESSION_ENDED: return sessionEnded(msg, pf);
  385. case PFChan_Core_DISCOVERED_PATH: return discoveredPath(msg, pf);
  386. case PFChan_Core_MSG: return incomingMsg(msg, pf);
  387. case PFChan_Core_PING: return handlePing(msg, pf);
  388. case PFChan_Core_PONG: return handlePong(msg, pf);
  389. case PFChan_Core_UNSETUP_SESSION:
  390. case PFChan_Core_LINK_STATE:
  391. case PFChan_Core_CTRL_MSG: return NULL;
  392. default:;
  393. }
  394. Assert_failure("unexpected event [%d]", ev);
  395. }
  396. static void sendEvent(struct Pathfinder_pvt* pf, enum PFChan_Pathfinder ev, void* data, int size)
  397. {
  398. struct Allocator* alloc = Allocator_child(pf->alloc);
  399. Message_t* msg = Message_new(0, 512+size, alloc);
  400. Err_assert(Message_epush(msg, data, size));
  401. Err_assert(Message_epush32be(msg, ev));
  402. Iface_send(&pf->pub.eventIf, msg);
  403. Allocator_free(alloc);
  404. }
  405. static void init(void* vpf)
  406. {
  407. struct Pathfinder_pvt* pf = Identity_check((struct Pathfinder_pvt*) vpf);
  408. struct PFChan_Pathfinder_Connect conn = {
  409. .superiority_be = Endian_hostToBigEndian32(1),
  410. .version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL)
  411. };
  412. CString_safeStrncpy(conn.userAgent, "Cjdns internal pathfinder", 64);
  413. sendEvent(pf, PFChan_Pathfinder_CONNECT, &conn, PFChan_Pathfinder_Connect_SIZE);
  414. }
  415. struct Pathfinder* Pathfinder_register(struct Allocator* allocator,
  416. struct Log* log,
  417. EventBase_t* base,
  418. struct Random* rand,
  419. struct Admin* admin)
  420. {
  421. struct Allocator* alloc = Allocator_child(allocator);
  422. struct Pathfinder_pvt* pf = Allocator_calloc(alloc, sizeof(struct Pathfinder_pvt), 1);
  423. Identity_set(pf);
  424. pf->alloc = alloc;
  425. pf->log = log;
  426. pf->base = base;
  427. pf->rand = rand;
  428. pf->admin = admin;
  429. pf->pub.eventIf.send = incomingFromEventIf;
  430. pf->dhtModule.context = pf;
  431. pf->dhtModule.handleOutgoing = incomingFromDHT;
  432. // This needs to be done asynchronously so the pf can be plumbed to the core
  433. Timeout_setTimeout(init, pf, 0, base, alloc);
  434. return &pf->pub;
  435. }