Core.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 "admin/Admin.h"
  16. #include "admin/AdminLog.h"
  17. #include "admin/angel/Core.h"
  18. #include "admin/angel/InterfaceWaiter.h"
  19. #include "admin/AuthorizedPasswords.h"
  20. #include "benc/Int.h"
  21. #include "benc/serialization/standard/BencMessageReader.h"
  22. #include "benc/serialization/standard/BencMessageWriter.h"
  23. #include "crypto/AddressCalc.h"
  24. #include "crypto/random/Random.h"
  25. #include "crypto/random/libuv/LibuvEntropyProvider.h"
  26. #include "subnode/SubnodePathfinder.h"
  27. #include "subnode/SupernodeHunter_admin.h"
  28. #include "subnode/ReachabilityCollector_admin.h"
  29. #ifndef SUBNODE
  30. #include "dht/Pathfinder.h"
  31. #endif
  32. #include "exception/Jmp.h"
  33. #include "interface/Iface.h"
  34. #include "util/events/UDPAddrIface.h"
  35. #include "interface/tuntap/TUNInterface.h"
  36. #include "interface/tuntap/SocketInterface.h"
  37. #include "interface/tuntap/SocketWrapper.h"
  38. #include "interface/tuntap/AndroidWrapper.h"
  39. #include "interface/UDPInterface_admin.h"
  40. #ifdef HAS_ETH_INTERFACE
  41. #include "interface/ETHInterface_admin.h"
  42. #endif
  43. #include "net/InterfaceController_admin.h"
  44. #include "interface/addressable/PacketHeaderToUDPAddrIface.h"
  45. #include "interface/ASynchronizer.h"
  46. #include "memory/Allocator.h"
  47. #include "memory/MallocAllocator.h"
  48. #include "memory/Allocator_admin.h"
  49. #include "net/SwitchPinger_admin.h"
  50. #include "net/UpperDistributor_admin.h"
  51. #define NumberCompress_OLD_CODE
  52. #include "switch/NumberCompress.h"
  53. #include "tunnel/IpTunnel_admin.h"
  54. #include "tunnel/RouteGen_admin.h"
  55. #include "util/events/EventBase.h"
  56. #include "util/events/libuv/FileNo_admin.h"
  57. #include "util/events/Pipe.h"
  58. #include "util/events/Timeout.h"
  59. #include "util/Hex.h"
  60. #include "util/log/FileWriterLog.h"
  61. #include "util/log/IndirectLog.h"
  62. #include "util/platform/netdev/NetDev.h"
  63. #include "util/Security_admin.h"
  64. #include "util/Security.h"
  65. #include "util/version/Version.h"
  66. #include "util/GlobalConfig.h"
  67. #include "net/SessionManager_admin.h"
  68. #include "wire/SwitchHeader.h"
  69. #include "wire/CryptoHeader.h"
  70. #include "wire/Headers.h"
  71. #include "net/NetCore.h"
  72. #include <crypto_scalarmult_curve25519.h>
  73. #include <stdlib.h>
  74. #include <unistd.h>
  75. // Failsafe: abort if more than 2^23 bytes are allocated (8MB)
  76. #define ALLOCATOR_FAILSAFE (1<<23)
  77. // TODO(cjd): we need to begin detecting MTU and informing the OS properly!
  78. /**
  79. * The worst possible packet overhead, we're in session setup with the endpoint.
  80. */
  81. #define WORST_CASE_OVERHEAD ( \
  82. Headers_IP4Header_SIZE \
  83. + Headers_UDPHeader_SIZE \
  84. + 4 /* Nonce */ \
  85. + 16 /* Poly1305 authenticator */ \
  86. + SwitchHeader_SIZE \
  87. + CryptoHeader_SIZE \
  88. + 4 /* Handle */ \
  89. + DataHeader_SIZE \
  90. )
  91. /** The default MTU, assuming the external MTU is 1492 (common for PPPoE DSL) */
  92. #define DEFAULT_MTU ( 1492 - WORST_CASE_OVERHEAD )
  93. static void adminPing(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  94. {
  95. Dict d = Dict_CONST(String_CONST("q"), String_OBJ(String_CONST("pong")), NULL);
  96. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  97. }
  98. static void adminPid(Dict* input, void* vadmin, String* txid, struct Allocator* requestAlloc)
  99. {
  100. int pid = getpid();
  101. Dict d = Dict_CONST(String_CONST("pid"), Int_OBJ(pid), NULL);
  102. Admin_sendMessage(&d, txid, (struct Admin*) vadmin);
  103. }
  104. struct Context
  105. {
  106. struct Allocator* alloc;
  107. struct Admin* admin;
  108. struct Log* logger;
  109. struct EventBase* base;
  110. struct NetCore* nc;
  111. struct IpTunnel* ipTunnel;
  112. struct EncodingScheme* encodingScheme;
  113. struct GlobalConfig* globalConf;
  114. Identity
  115. };
  116. static void shutdown(void* vcontext)
  117. {
  118. struct Context* context = Identity_check((struct Context*) vcontext);
  119. Allocator_free(context->alloc);
  120. }
  121. static void adminExit(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
  122. {
  123. struct Context* context = Identity_check((struct Context*) vcontext);
  124. Log_info(context->logger, "Got request to exit");
  125. Dict d = Dict_CONST(String_CONST("error"), String_OBJ(String_CONST("none")), NULL);
  126. Admin_sendMessage(&d, txid, context->admin);
  127. Timeout_setTimeout(shutdown, context, 1, context->base, context->alloc);
  128. }
  129. static void sendResponse(String* error,
  130. struct Admin* admin,
  131. String* txid,
  132. struct Allocator* tempAlloc)
  133. {
  134. Dict* output = Dict_new(tempAlloc);
  135. Dict_putStringC(output, "error", error, tempAlloc);
  136. Admin_sendMessage(output, txid, admin);
  137. }
  138. static void initSocket2(String* socketFullPath,
  139. bool attemptToCreate,
  140. struct Context* ctx,
  141. uint8_t addressPrefix,
  142. struct Except* eh)
  143. {
  144. Log_debug(ctx->logger, "Initializing socket: %s;", socketFullPath->bytes);
  145. struct Iface* rawSocketIf = SocketInterface_new(
  146. socketFullPath->bytes, attemptToCreate, ctx->base, ctx->logger, NULL, ctx->alloc);
  147. struct SocketWrapper* sw = SocketWrapper_new(ctx->alloc, ctx->logger);
  148. Iface_plumb(&sw->externalIf, rawSocketIf);
  149. Iface_plumb(&sw->internalIf, &ctx->nc->tunAdapt->tunIf);
  150. SocketWrapper_addAddress(&sw->externalIf, ctx->nc->myAddress->ip6.bytes, ctx->logger,
  151. eh, ctx->alloc);
  152. SocketWrapper_setMTU(&sw->externalIf, DEFAULT_MTU, ctx->logger, eh, ctx->alloc);
  153. }
  154. static void initTunnel2(String* desiredDeviceName,
  155. struct Context* ctx,
  156. uint8_t addressPrefix,
  157. struct Except* eh)
  158. {
  159. Log_debug(ctx->logger, "Initializing TUN device [%s]",
  160. (desiredDeviceName) ? desiredDeviceName->bytes : "<auto>");
  161. char assignedTunName[TUNInterface_IFNAMSIZ];
  162. char* desiredName = (desiredDeviceName) ? desiredDeviceName->bytes : NULL;
  163. struct Iface* tun = TUNInterface_new(
  164. desiredName, assignedTunName, 0, ctx->base, ctx->logger, eh, ctx->alloc);
  165. Iface_plumb(tun, &ctx->nc->tunAdapt->tunIf);
  166. GlobalConfig_setTunName(ctx->globalConf, String_CONST(assignedTunName));
  167. struct Sockaddr* myAddr =
  168. Sockaddr_fromBytes(ctx->nc->myAddress->ip6.bytes, Sockaddr_AF_INET6, ctx->alloc);
  169. myAddr->prefix = addressPrefix;
  170. myAddr->flags |= Sockaddr_flags_PREFIX;
  171. NetDev_addAddress(assignedTunName, myAddr, ctx->logger, eh);
  172. NetDev_setMTU(assignedTunName, DEFAULT_MTU, ctx->logger, eh);
  173. }
  174. static void initTunfd(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  175. {
  176. struct Context* ctx = Identity_check((struct Context*) vcontext);
  177. struct Jmp jmp;
  178. Jmp_try(jmp) {
  179. int64_t* tunfd = Dict_getIntC(args, "tunfd");
  180. int64_t* tuntype = Dict_getIntC(args, "type");
  181. if (!tunfd || *tunfd < 0) {
  182. String* error = String_printf(requestAlloc, "Invalid tunfd");
  183. sendResponse(error, ctx->admin, txid, requestAlloc);
  184. return;
  185. }
  186. int fileno = *tunfd;
  187. int type = (*tuntype) ? *tuntype : FileNo_Type_NORMAL;
  188. struct Pipe* p = Pipe_forFiles(fileno, fileno, ctx->base, &jmp.handler, ctx->alloc);
  189. p->logger = ctx->logger;
  190. if (type == FileNo_Type_ANDROID) {
  191. struct AndroidWrapper* aw = AndroidWrapper_new(ctx->alloc, ctx->logger);
  192. Iface_plumb(&aw->externalIf, &p->iface);
  193. Iface_plumb(&aw->internalIf, &ctx->nc->tunAdapt->tunIf);
  194. } else {
  195. Iface_plumb(&p->iface, &ctx->nc->tunAdapt->tunIf);
  196. }
  197. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  198. } Jmp_catch {
  199. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  200. sendResponse(error, ctx->admin, txid, requestAlloc);
  201. return;
  202. }
  203. }
  204. static void initTunnel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  205. {
  206. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  207. struct Jmp jmp;
  208. Jmp_try(jmp) {
  209. String* desiredName = Dict_getStringC(args, "desiredTunName");
  210. initTunnel2(desiredName, ctx, AddressCalc_ADDRESS_PREFIX_BITS, &jmp.handler);
  211. } Jmp_catch {
  212. String* error = String_printf(requestAlloc, "Failed to configure tunnel [%s]", jmp.message);
  213. sendResponse(error, ctx->admin, txid, requestAlloc);
  214. return;
  215. }
  216. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  217. }
  218. static void initSocket(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  219. {
  220. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  221. struct Jmp jmp;
  222. Jmp_try(jmp) {
  223. String* socketFullPath = Dict_getStringC(args, "socketFullPath");
  224. bool socketAttemptToCreate = *Dict_getIntC(args, "socketAttemptToCreate");
  225. initSocket2(socketFullPath, socketAttemptToCreate, ctx, AddressCalc_ADDRESS_PREFIX_BITS,
  226. &jmp.handler);
  227. } Jmp_catch {
  228. String* error = String_printf(requestAlloc, "Failed to configure socket [%s]",
  229. jmp.message);
  230. sendResponse(error, ctx->admin, txid, requestAlloc);
  231. return;
  232. }
  233. sendResponse(String_CONST("none"), ctx->admin, txid, requestAlloc);
  234. }
  235. static void nodeInfo(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
  236. {
  237. struct Context* const ctx = Identity_check((struct Context*) vcontext);
  238. String* myAddr = Address_toString(ctx->nc->myAddress, requestAlloc);
  239. String* schemeStr = EncodingScheme_serialize(ctx->encodingScheme, requestAlloc);
  240. List* schemeList = EncodingScheme_asList(ctx->encodingScheme, requestAlloc);
  241. Dict* out = Dict_new(requestAlloc);
  242. Dict_putStringC(out, "myAddr", myAddr, requestAlloc);
  243. char* schemeHex = Hex_print(schemeStr->bytes, schemeStr->len, requestAlloc);
  244. Dict_putStringCC(out, "compressedSchemeHex", schemeHex, requestAlloc);
  245. Dict_putListC(out, "encodingScheme", schemeList, requestAlloc);
  246. Dict_putIntC(out, "version", Version_CURRENT_PROTOCOL, requestAlloc);
  247. Dict_putStringCC(out, "error", "none", requestAlloc);
  248. Admin_sendMessage(out, txid, ctx->admin);
  249. }
  250. void Core_init(struct Allocator* alloc,
  251. struct Log* logger,
  252. struct EventBase* eventBase,
  253. uint8_t privateKey[32],
  254. struct Admin* admin,
  255. struct Random* rand,
  256. struct Except* eh,
  257. struct FakeNetwork* fakeNet,
  258. bool noSec)
  259. {
  260. struct Security* sec = NULL;
  261. if (!noSec) {
  262. sec = Security_new(alloc, logger, eventBase);
  263. }
  264. struct GlobalConfig* globalConf = GlobalConfig_new(alloc);
  265. struct NetCore* nc = NetCore_new(privateKey, alloc, eventBase, rand, logger);
  266. struct RouteGen* rg = RouteGen_new(alloc, logger);
  267. struct IpTunnel* ipTunnel =
  268. IpTunnel_new(logger, eventBase, alloc, rand, rg, globalConf);
  269. Iface_plumb(&nc->tunAdapt->ipTunnelIf, &ipTunnel->tunInterface);
  270. Iface_plumb(&nc->upper->ipTunnelIf, &ipTunnel->nodeInterface);
  271. struct EncodingScheme* encodingScheme = NumberCompress_defineScheme(alloc);
  272. // The link between the Pathfinder and the core needs to be asynchronous.
  273. struct SubnodePathfinder* spf = SubnodePathfinder_new(
  274. alloc, logger, eventBase, rand, nc->myAddress, privateKey, encodingScheme);
  275. struct ASynchronizer* spfAsync = ASynchronizer_new(alloc, eventBase, logger);
  276. Iface_plumb(&spfAsync->ifA, &spf->eventIf);
  277. EventEmitter_regPathfinderIface(nc->ee, &spfAsync->ifB);
  278. #ifndef SUBNODE
  279. struct Pathfinder* opf = Pathfinder_register(alloc, logger, eventBase, rand, admin);
  280. struct ASynchronizer* opfAsync = ASynchronizer_new(alloc, eventBase, logger);
  281. Iface_plumb(&opfAsync->ifA, &opf->eventIf);
  282. EventEmitter_regPathfinderIface(nc->ee, &opfAsync->ifB);
  283. #endif
  284. SubnodePathfinder_start(spf);
  285. // ------------------- Register RPC functions ----------------------- //
  286. UpperDistributor_admin_register(nc->upper, admin, alloc);
  287. RouteGen_admin_register(rg, admin, alloc);
  288. InterfaceController_admin_register(nc->ifController, admin, alloc);
  289. SwitchPinger_admin_register(nc->sp, admin, alloc);
  290. UDPInterface_admin_register(
  291. eventBase, alloc, logger, admin, nc->ifController, fakeNet, globalConf);
  292. #ifdef HAS_ETH_INTERFACE
  293. ETHInterface_admin_register(eventBase, alloc, logger, admin, nc->ifController);
  294. #endif
  295. FileNo_admin_register(admin, alloc, eventBase, logger, eh);
  296. SupernodeHunter_admin_register(spf->snh, admin, alloc);
  297. ReachabilityCollector_admin_register(spf->rc, admin, alloc);
  298. AuthorizedPasswords_init(admin, nc->ca, alloc);
  299. Admin_registerFunction("ping", adminPing, admin, false, NULL, admin);
  300. if (!noSec) {
  301. Security_admin_register(alloc, logger, sec, admin);
  302. }
  303. IpTunnel_admin_register(ipTunnel, admin, alloc);
  304. SessionManager_admin_register(nc->sm, admin, alloc);
  305. Allocator_admin_register(alloc, admin);
  306. struct Context* ctx = Allocator_calloc(alloc, sizeof(struct Context), 1);
  307. Identity_set(ctx);
  308. ctx->alloc = alloc;
  309. ctx->admin = admin;
  310. ctx->logger = logger;
  311. ctx->base = eventBase;
  312. ctx->ipTunnel = ipTunnel;
  313. ctx->nc = nc;
  314. ctx->encodingScheme = encodingScheme;
  315. ctx->globalConf = globalConf;
  316. Admin_registerFunction("Core_exit", adminExit, ctx, true, NULL, admin);
  317. Admin_registerFunction("Core_pid", adminPid, admin, false, NULL, admin);
  318. Admin_registerFunction("Core_initTunnel", initTunnel, ctx, true,
  319. ((struct Admin_FunctionArg[]) {
  320. { .name = "desiredTunName", .required = 0, .type = "String" }
  321. }), admin);
  322. Admin_registerFunction("Core_initTunfd", initTunfd, ctx, true,
  323. ((struct Admin_FunctionArg[]) {
  324. { .name = "tunfd", .required = 1, .type = "Int" },
  325. { .name = "type", .required = 0, .type = "Int" }
  326. }), admin);
  327. Admin_registerFunction("Core_nodeInfo", nodeInfo, ctx, false, NULL, admin);
  328. Admin_registerFunction("Core_initSocket", initSocket, ctx, true,
  329. ((struct Admin_FunctionArg[]) {
  330. { .name = "socketFullPath", .required = 1, .type = "String" },
  331. { .name = "socketAttemptToCreate", .required = 1, .type = "Int" }
  332. }), admin);
  333. }
  334. int Core_main(int argc, char** argv)
  335. {
  336. struct Except* eh = NULL;
  337. if (argc != 4) {
  338. Except_throw(eh, "This is internal to cjdns and shouldn't started manually.");
  339. }
  340. struct Allocator* alloc = MallocAllocator_new(ALLOCATOR_FAILSAFE);
  341. struct Log* preLogger = FileWriterLog_new(stderr, alloc);
  342. struct EventBase* eventBase = EventBase_new(alloc);
  343. // -------------------- Setup the Pre-Logger ---------------------- //
  344. struct Log* logger = IndirectLog_new(alloc);
  345. IndirectLog_set(logger, preLogger);
  346. // -------------------- Setup the PRNG ---------------------- //
  347. struct Random* rand = LibuvEntropyProvider_newDefaultRandom(eventBase, logger, eh, alloc);
  348. // -------------------- Change Canary Value ---------------------- //
  349. Allocator_setCanary(alloc, (unsigned long)Random_uint64(rand));
  350. struct Allocator* tempAlloc = Allocator_child(alloc);
  351. struct Pipe* clientPipe = Pipe_named(argv[2], argv[3], eventBase, eh, tempAlloc);
  352. clientPipe->logger = logger;
  353. Log_debug(logger, "Getting pre-configuration from client");
  354. struct Message* preConf =
  355. InterfaceWaiter_waitForData(&clientPipe->iface, eventBase, tempAlloc, eh);
  356. Log_debug(logger, "Finished getting pre-configuration from client");
  357. Dict* config = BencMessageReader_read(preConf, tempAlloc, eh);
  358. String* privateKeyHex = Dict_getStringC(config, "privateKey");
  359. Dict* adminConf = Dict_getDictC(config, "admin");
  360. String* pass = Dict_getStringC(adminConf, "pass");
  361. String* bind = Dict_getStringC(adminConf, "bind");
  362. if (!(pass && privateKeyHex && bind)) {
  363. if (!pass) {
  364. Except_throw(eh, "Expected 'pass'");
  365. }
  366. if (!bind) {
  367. Except_throw(eh, "Expected 'bind'");
  368. }
  369. if (!privateKeyHex) {
  370. Except_throw(eh, "Expected 'privateKey'");
  371. }
  372. Except_throw(eh, "Expected 'pass', 'privateKey' and 'bind' in configuration.");
  373. }
  374. Log_keys(logger, "Starting core with admin password [%s]", pass->bytes);
  375. uint8_t privateKey[32];
  376. if (privateKeyHex->len != 64
  377. || Hex_decode(privateKey, 32, (uint8_t*) privateKeyHex->bytes, 64) != 32)
  378. {
  379. Except_throw(eh, "privateKey must be 64 bytes of hex.");
  380. }
  381. struct Sockaddr_storage bindAddr;
  382. if (Sockaddr_parse(bind->bytes, &bindAddr)) {
  383. Except_throw(eh, "bind address [%s] unparsable", bind->bytes);
  384. }
  385. // --------------------- Bind Admin UDP --------------------- //
  386. struct UDPAddrIface* udpAdmin = UDPAddrIface_new(eventBase, &bindAddr.addr, alloc, eh, logger);
  387. // --------------------- Setup Admin --------------------- //
  388. struct Admin* admin = Admin_new(&udpAdmin->generic, logger, eventBase, pass);
  389. // --------------------- Setup the Logger --------------------- //
  390. Dict* logging = Dict_getDictC(config, "logging");
  391. String* logTo = Dict_getStringC(logging, "logTo");
  392. if (logTo && String_equals(logTo, String_CONST("stdout"))) {
  393. // do nothing, continue logging to stdout.
  394. } else {
  395. struct Log* adminLogger = AdminLog_registerNew(admin, alloc, rand, eventBase);
  396. IndirectLog_set(logger, adminLogger);
  397. logger = adminLogger;
  398. }
  399. // --------------------- Inform client of UDP Addr --------------------- //
  400. char* boundAddr = Sockaddr_print(udpAdmin->generic.addr, tempAlloc);
  401. Dict adminResponse = Dict_CONST(
  402. String_CONST("bind"), String_OBJ(String_CONST(boundAddr)), NULL
  403. );
  404. Dict response = Dict_CONST(
  405. String_CONST("error"), String_OBJ(String_CONST("none")), Dict_CONST(
  406. String_CONST("admin"), Dict_OBJ(&adminResponse), NULL
  407. ));
  408. // This always times out because the angel doesn't respond.
  409. struct Message* clientResponse = Message_new(0, 512, tempAlloc);
  410. BencMessageWriter_write(&response, clientResponse, eh);
  411. Iface_CALL(clientPipe->iface.send, clientResponse, &clientPipe->iface);
  412. Allocator_free(tempAlloc);
  413. Core_init(alloc, logger, eventBase, privateKey, admin, rand, eh, NULL, false);
  414. EventBase_beginLoop(eventBase);
  415. return 0;
  416. }