Core.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 "admin/Admin.h"
  16. #include "admin/AdminLog.h"
  17. #include "admin/angel/Angel.h"
  18. #include "admin/angel/Core.h"
  19. #include "admin/angel/InterfaceWaiter.h"
  20. #include "admin/angel/Hermes.h"
  21. #include "admin/AuthorizedPasswords.h"
  22. #include "benc/Int.h"
  23. #include "benc/serialization/standard/BencMessageReader.h"
  24. #include "crypto/AddressCalc.h"
  25. #include "crypto/random/Random.h"
  26. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  27. #include "dht/ReplyModule.h"
  28. #include "dht/EncodingSchemeModule.h"
  29. #include "dht/SerializationModule.h"
  30. #include "dht/dhtcore/RouterModule.h"
  31. #include "dht/dhtcore/RouterModule_admin.h"
  32. #include "dht/dhtcore/RumorMill.h"
  33. #include "dht/dhtcore/SearchRunner.h"
  34. #include "dht/dhtcore/SearchRunner_admin.h"
  35. #include "dht/dhtcore/NodeStore_admin.h"
  36. #include "dht/dhtcore/Janitor.h"
  37. #include "dht/dhtcore/Router_new.h"
  38. #include "exception/Jmp.h"
  39. #include "interface/addressable/AddrInterface.h"
  40. #include "interface/addressable/UDPAddrInterface.h"
  41. #include "interface/UDPInterface_admin.h"
  42. #ifdef HAS_ETH_INTERFACE
  43. #include "interface/ETHInterface_admin.h"
  44. #endif
  45. #include "interface/tuntap/TUNInterface.h"
  46. #include "interface/InterfaceConnector.h"
  47. #include "interface/InterfaceController_admin.h"
  48. #include "interface/FramingInterface.h"
  49. #include "interface/RainflyClient.h"
  50. #include "interface/RainflyClient_admin.h"
  51. #include "interface/DNSServer.h"
  52. #include "interface/addressable/PacketHeaderToUDPAddrInterface.h"
  53. #include "memory/Allocator.h"
  54. #include "memory/MallocAllocator.h"
  55. #include "memory/Allocator_admin.h"
  56. #include "net/Ducttape.h"
  57. #include "interface/InterfaceController.h"
  58. #include "net/SwitchPinger.h"
  59. #include "net/SwitchPinger_admin.h"
  60. #include "switch/SwitchCore.h"
  61. #include "tunnel/IpTunnel.h"
  62. #include "tunnel/IpTunnel_admin.h"
  63. #include "util/events/Timeout.h"
  64. #include "util/events/EventBase.h"
  65. #include "util/events/Pipe.h"
  66. #include "util/events/Timeout.h"
  67. #include "util/Hex.h"
  68. #include "util/log/FileWriterLog.h"
  69. #include "util/log/IndirectLog.h"
  70. #include "util/platform/netdev/NetDev.h"
  71. #include "util/Security_admin.h"
  72. #include "util/Security.h"
  73. #include "util/version/Version.h"
  74. #include "interface/SessionManager_admin.h"
  75. #include "wire/SwitchHeader.h"
  76. #include "wire/CryptoHeader.h"
  77. #include <crypto_scalarmult_curve25519.h>
  78. #include <stdlib.h>
  79. #include <unistd.h>
  80. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  81. #define ALLOCATOR_FAILSAFE (1<<23)
  82. /** The number of milliseconds between attempting local maintenance searches. */
  83. #define LOCAL_MAINTENANCE_SEARCH_MILLISECONDS 1000
  84. /**
  85. * The number of milliseconds to pass between global maintainence searches.
  86. * These are searches for random targets which are used to discover new nodes.
  87. */
  88. #define GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS 30000
  89. #define RUMORMILL_CAPACITY 64
  90. /**
  91. * The worst possible packet overhead.
  92. * assuming the packet needs to be handed off to another node
  93. * because we have no route to the destination.
  94. * and the CryptoAuths to both the destination and the handoff node are both timed out.
  95. */
  96. #define WORST_CASE_OVERHEAD ( \
  97. /* TODO(cjd): Headers_IPv4_SIZE */ 20 \
  98. + Headers_UDPHeader_SIZE \
  99. + 4 /* Nonce */ \
  100. + 16 /* Poly1305 authenticator */ \
  101. + SwitchHeader_SIZE \
  102. + CryptoHeader_SIZE \
  103. + Headers_IP6Header_SIZE \
  104. + CryptoHeader_SIZE \
  105. )
  106. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  107. #define DEFAULT_MTU ( \
  108. 1492 \
  109. - WORST_CASE_OVERHEAD \
  110. + Headers_IP6Header_SIZE /* The OS subtracts the IP6 header. */ \
  111. + CryptoHeader_SIZE /* Linux won't let set the MTU below 1280.
  112. TODO(cjd): make sure we never hand off to a node for which the CA session is expired. */ \
  113. )
  114. static void parsePrivateKey(uint8_t privateKey[32],
  115. struct Address* addr,
  116. struct Except* eh)
  117. {
  118. crypto_scalarmult_curve25519_base(addr->key, privateKey);
  119. AddressCalc_addressForPublicKey(addr->ip6.bytes, addr->key);
  120. if (!AddressCalc_validAddress(addr->ip6.bytes)) {
  121. Except_throw(eh, "Ip address outside of the FC00/8 range, invalid private key.");
  122. }
  123. }
  124. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  125. {
  126. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  127. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  128. }
  129. static void adminPid(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  130. {
  131. int pid = getpid();
  132. Dict d = Dict_CONST(String_CONST("pid"), Int_OBJ(pid), NULL);
  133. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  134. }
  135. struct Context
  136. {
  137. struct Allocator* allocator;
  138. struct Admin* admin;
  139. struct Log* logger;
  140. struct Hermes* hermes;
  141. struct EventBase* base;
  142. String* exitTxid;
  143. };
  144. static void shutdown(void* vcontext)
  145. {
  146. struct Context* context = vcontext;
  147. Allocator_free(context->allocator);
  148. }
  149. static void onAngelExitResponse(Dict* message, void* vcontext)
  150. {
  151. struct Context* context = vcontext;
  152. Log_info(context->logger, "Angel stopped");
  153. Log_info(context->logger, "Exiting");
  154. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  155. Admin_sendMessage(&d, context->exitTxid, context->admin);
  156. Timeout_setTimeout(shutdown, context, 1, context->base, context->allocator);
  157. }
  158. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  159. {
  160. struct Context* context = vcontext;
  161. Log_info(context->logger, "Got request to exit");
  162. Log_info(context->logger, "Stopping angel");
  163. context->exitTxid = String_clone(txid, context->allocator);
  164. Dict angelExit = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("Angel_exit")), NULL);
  165. Hermes_callAngel(&angelExit,
  166. onAngelExitResponse,
  167. context,
  168. context->allocator,
  169. NULL,
  170. context->hermes);
  171. }
  172. static void angelDied(struct Pipe* p, int status)
  173. {
  174. exit(1);
  175. }
  176. struct Core_Context
  177. {
  178. struct Sockaddr* ipAddr;
  179. struct Ducttape* ducttape;
  180. struct Log* logger;
  181. struct Allocator* alloc;
  182. struct Admin* admin;
  183. struct EventBase* eventBase;
  184. struct IpTunnel* ipTunnel;
  185. };
  186. static void sendResponse(String* error,
  187. struct Admin* admin,
  188. String* txid,
  189. struct Allocator* tempAlloc)
  190. {
  191. Dict* output = Dict_new(tempAlloc);
  192. Dict_putString(output, String_CONST("error"), error, tempAlloc);
  193. Admin_sendMessage(output, txid, admin);
  194. }
  195. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  196. {
  197. struct Core_Context* const ctx = (struct Core_Context*) vcontext;
  198. struct Jmp jmp;
  199. Jmp_try(jmp) {
  200. Core_initTunnel(Dict_getString(args, String_CONST("desiredTunName")),
  201. ctx->ipAddr,
  202. 8,
  203. ctx->ducttape,
  204. ctx->logger,
  205. ctx->ipTunnel,
  206. ctx->eventBase,
  207. ctx->alloc,
  208. &jmp.handler);
  209. } Jmp_catch {
  210. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  211. sendResponse(error, ctx->admin, txid, requestAlloc);
  212. return;
  213. }
  214. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  215. }
  216. void Core_admin_register(struct Sockaddr* ipAddr,
  217. struct Ducttape* dt,
  218. struct Log* logger,
  219. struct IpTunnel* ipTunnel,
  220. struct Allocator* alloc,
  221. struct Admin* admin,
  222. struct EventBase* eventBase)
  223. {
  224. struct Core_Context* ctx = Allocator_malloc(alloc, sizeof(struct Core_Context));
  225. ctx->ipAddr = ipAddr;
  226. ctx->ducttape = dt;
  227. ctx->logger = logger;
  228. ctx->alloc = alloc;
  229. ctx->admin = admin;
  230. ctx->eventBase = eventBase;
  231. ctx->ipTunnel = ipTunnel;
  232. struct Admin_FunctionArg args[] = {
  233. { .name = "desiredTunName", .required = 0, .type = "String" }
  234. };
  235. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true, args, admin);
  236. }
  237. static Dict* getInitialConfig(struct Interface* iface,
  238. struct EventBase* eventBase,
  239. struct Allocator* alloc,
  240. struct Except* eh)
  241. {
  242. struct Message* m = InterfaceWaiter_waitForData(iface, eventBase, alloc, eh);
  243. return BencMessageReader_read(m, alloc, eh);
  244. }
  245. void Core_initTunnel(String* desiredDeviceName,
  246. struct Sockaddr* addr,
  247. uint8_t addressPrefix,
  248. struct Ducttape* dt,
  249. struct Log* logger,
  250. struct IpTunnel* ipTunnel,
  251. struct EventBase* eventBase,
  252. struct Allocator* alloc,
  253. struct Except* eh)
  254. {
  255. Log_debug(logger, "Initializing TUN device [%s]",
  256. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  257. char assignedTunName[TUNInterface_IFNAMSIZ];
  258. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  259. struct Interface* tun =
  260. TUNInterface_new(desiredName, assignedTunName, 0, eventBase, logger, eh, alloc);
  261. IpTunnel_setTunName(assignedTunName, ipTunnel);
  262. Ducttape_setUserInterface(dt, tun);
  263. NetDev_addAddress(assignedTunName, addr, addressPrefix, logger, eh);
  264. NetDev_setMTU(assignedTunName, DEFAULT_MTU, logger, eh);
  265. }
  266. /** This is a response from a call which is intended only to send information to the angel. */
  267. static void angelResponse(Dict* resp, void* vNULL)
  268. {
  269. // do nothing
  270. }
  271. void Core_init(struct Allocator* alloc,
  272. struct Log* logger,
  273. struct EventBase* eventBase,
  274. struct Interface* angelIface,
  275. struct Random* rand,
  276. struct Except* eh)
  277. {
  278. struct Allocator* tempAlloc = Allocator_child(alloc);
  279. Dict* config = getInitialConfig(angelIface, eventBase, tempAlloc, eh);
  280. struct Hermes* hermes = Hermes_new(angelIface, eventBase, logger, alloc);
  281. String* privateKeyHex = Dict_getString(config, String_CONST("privateKey"));
  282. Dict* adminConf = Dict_getDict(config, String_CONST("admin"));
  283. String* pass = Dict_getString(adminConf, String_CONST("pass"));
  284. String* bind = Dict_getString(adminConf, String_CONST("bind"));
  285. if (!(pass && privateKeyHex && bind)) {
  286. if (!pass) {
  287. Except_throw(eh, "Expected 'pass'");
  288. }
  289. if (!bind) {
  290. Except_throw(eh, "Expected 'bind'");
  291. }
  292. if (!privateKeyHex) {
  293. Except_throw(eh, "Expected 'privateKey'");
  294. }
  295. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  296. }
  297. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  298. uint8_t privateKey[32];
  299. if (privateKeyHex->len != 64
  300. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  301. {
  302. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  303. }
  304. struct Sockaddr_storage bindAddr;
  305. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  306. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  307. }
  308. struct AddrInterface* udpAdmin =
  309. UDPAddrInterface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  310. struct Admin* admin = Admin_new(udpAdmin, alloc, logger, eventBase, pass);
  311. char* boundAddr = Sockaddr_print(udpAdmin->addr, tempAlloc);
  312. Dict adminResponse = Dict_CONST(
  313. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  314. );
  315. Dict response = Dict_CONST(
  316. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  317. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  318. ));
  319. // This always times out because the angel doesn't respond.
  320. Hermes_callAngel(&response, angelResponse, NULL, alloc, eh, hermes);
  321. // --------------------- Setup the Logger --------------------- //
  322. Dict* logging = Dict_getDict(config, String_CONST("logging"));
  323. String* logTo = Dict_getString(logging, String_CONST("logTo"));
  324. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  325. // do nothing, continue logging to stdout.
  326. } else {
  327. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand, eventBase);
  328. IndirectLog_set(logger, adminLogger);
  329. logger = adminLogger;
  330. }
  331. // CryptoAuth
  332. struct Address addr = { .protocolVersion = Version_CURRENT_PROTOCOL };
  333. parsePrivateKey(privateKey, &addr, eh);
  334. struct CryptoAuth* cryptoAuth = CryptoAuth_new(alloc, privateKey, eventBase, logger, rand);
  335. struct Sockaddr* myAddr = Sockaddr_fromBytes(addr.ip6.bytes, Sockaddr_AF_INET6, alloc);
  336. struct SwitchCore* switchCore = SwitchCore_new(logger, alloc, eventBase);
  337. struct DHTModuleRegistry* registry = DHTModuleRegistry_new(alloc);
  338. ReplyModule_register(registry, alloc);
  339. struct RumorMill* rumorMill = RumorMill_new(alloc, &addr, RUMORMILL_CAPACITY, logger, "extern");
  340. struct NodeStore* nodeStore = NodeStore_new(&addr, alloc, eventBase, logger, rumorMill);
  341. struct RouterModule* routerModule = RouterModule_register(registry,
  342. alloc,
  343. addr.key,
  344. eventBase,
  345. logger,
  346. rand,
  347. nodeStore);
  348. struct SearchRunner* searchRunner = SearchRunner_new(nodeStore,
  349. logger,
  350. eventBase,
  351. routerModule,
  352. addr.ip6.bytes,
  353. rumorMill,
  354. alloc);
  355. Janitor_new(LOCAL_MAINTENANCE_SEARCH_MILLISECONDS,
  356. GLOBAL_MAINTENANCE_SEARCH_MILLISECONDS,
  357. routerModule,
  358. nodeStore,
  359. searchRunner,
  360. rumorMill,
  361. logger,
  362. alloc,
  363. eventBase,
  364. rand);
  365. EncodingSchemeModule_register(registry, logger, alloc);
  366. SerializationModule_register(registry, logger, alloc);
  367. struct IpTunnel* ipTun = IpTunnel_new(logger, eventBase, alloc, rand, hermes);
  368. struct Router* router = Router_new(routerModule, nodeStore, searchRunner, alloc);
  369. struct Ducttape* dt = Ducttape_register(privateKey,
  370. registry,
  371. router,
  372. switchCore,
  373. eventBase,
  374. alloc,
  375. logger,
  376. ipTun,
  377. rand);
  378. struct SwitchPinger* sp =
  379. SwitchPinger_new(&dt->switchPingerIf, eventBase, rand, logger, &addr, alloc);
  380. // Interfaces.
  381. struct InterfaceController* ifController =
  382. InterfaceController_new(cryptoAuth, switchCore, router, rumorMill,
  383. logger, eventBase, sp, rand, alloc);
  384. // ------------------- DNS -------------------------//
  385. struct Sockaddr_storage rainflyAddr;
  386. Assert_true(!Sockaddr_parse("::", &rainflyAddr));
  387. struct AddrInterface* rainflyIface =
  388. UDPAddrInterface_new(eventBase, &rainflyAddr.addr, alloc, eh, logger);
  389. struct RainflyClient* rainfly = RainflyClient_new(rainflyIface, eventBase, rand, logger);
  390. Assert_true(!Sockaddr_parse("[fc00::1]:53", &rainflyAddr));
  391. struct AddrInterface* magicUDP =
  392. PacketHeaderToUDPAddrInterface_new(&dt->magicInterface, alloc, &rainflyAddr.addr);
  393. DNSServer_new(magicUDP, logger, rainfly);
  394. // ------------------- Register RPC functions ----------------------- //
  395. InterfaceController_admin_register(ifController, nodeStore, admin, alloc);
  396. SwitchPinger_admin_register(sp, admin, alloc);
  397. UDPInterface_admin_register(eventBase, alloc, logger, admin, ifController);
  398. #ifdef HAS_ETH_INTERFACE
  399. ETHInterface_admin_register(eventBase, alloc, logger, admin, ifController);
  400. #endif
  401. NodeStore_admin_register(nodeStore, admin, alloc);
  402. RouterModule_admin_register(routerModule, router, admin, alloc);
  403. SearchRunner_admin_register(searchRunner, admin, alloc);
  404. AuthorizedPasswords_init(admin, cryptoAuth, alloc);
  405. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  406. Core_admin_register(myAddr, dt, logger, ipTun, alloc, admin, eventBase);
  407. Security_admin_register(alloc, logger, admin);
  408. IpTunnel_admin_register(ipTun, admin, alloc);
  409. SessionManager_admin_register(dt->sessionManager, admin, alloc);
  410. RainflyClient_admin_register(rainfly, admin, alloc);
  411. Allocator_admin_register(alloc, admin);
  412. struct Context* ctx = Allocator_clone(alloc, (&(struct Context) {
  413. .allocator = alloc,
  414. .admin = admin,
  415. .logger = logger,
  416. .hermes = hermes,
  417. .base = eventBase,
  418. }));
  419. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  420. Admin_registerFunction("Core_pid", adminPid, admin, false, NULL, admin);
  421. }
  422. int Core_main(int argc, char** argv)
  423. {
  424. struct Except* eh = NULL;
  425. if (argc != 3) {
  426. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  427. }
  428. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  429. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  430. struct EventBase* eventBase = EventBase_new(alloc);
  431. // -------------------- Setup the Pre-Logger ---------------------- //
  432. struct Log* logger = IndirectLog_new(alloc);
  433. IndirectLog_set(logger, preLogger);
  434. // -------------------- Setup the PRNG ---------------------- //
  435. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  436. // -------------------- Change Canary Value ---------------------- //
  437. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  438. // The first read inside of getInitialConfig() will begin it waiting.
  439. struct Pipe* angelPipe = Pipe_named(argv[2], eventBase, eh, alloc);
  440. angelPipe->logger = logger;
  441. angelPipe->onClose = angelDied;
  442. struct Interface* angelIface = FramingInterface_new(65535, &angelPipe->iface, alloc);
  443. Core_init(alloc, logger, eventBase, angelIface, rand, eh);
  444. EventBase_beginLoop(eventBase);
  445. return 0;
  446. }