1
0

Core.c 20 KB

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