1
0

Core.c 21 KB

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