Core.c 21 KB

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