Pathfinder.c 18 KB

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