Pathfinder.c 18 KB

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