cjdroute2.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "admin/AdminClient.h"
  16. #include "admin/angel/AngelInit.h"
  17. #include "admin/angel/Core.h"
  18. #include "admin/angel/InterfaceWaiter.h"
  19. #include "admin/Configurator.h"
  20. #include "benc/Dict.h"
  21. #include "benc/Int.h"
  22. #include "benc/List.h"
  23. #include "benc/serialization/BencSerializer.h"
  24. #include "benc/serialization/json/JsonBencSerializer.h"
  25. #include "benc/serialization/standard/BencMessageReader.h"
  26. #include "benc/serialization/standard/BencMessageWriter.h"
  27. #include "crypto/AddressCalc.h"
  28. #include "dht/Address.h"
  29. #include "exception/Except.h"
  30. #include "interface/Iface.h"
  31. #include "io/FileReader.h"
  32. #include "io/FileWriter.h"
  33. #include "io/Reader.h"
  34. #include "io/Writer.h"
  35. #include "memory/Allocator.h"
  36. #include "memory/MallocAllocator.h"
  37. #include "util/ArchInfo.h"
  38. #include "util/Assert.h"
  39. #include "util/Base32.h"
  40. #include "util/CString.h"
  41. #include "util/events/EventBase.h"
  42. #include "util/events/Pipe.h"
  43. #include "util/events/Process.h"
  44. #include "util/Hex.h"
  45. #include "util/log/Log.h"
  46. #include "util/log/WriterLog.h"
  47. #include "util/SysInfo.h"
  48. #include "util/version/Version.h"
  49. #include "crypto_scalarmult_curve25519.h"
  50. #include <stdint.h>
  51. #include <stdio.h>
  52. #include <unistd.h>
  53. #define DEFAULT_TUN_DEV "tun0"
  54. static int genAddress(uint8_t addressOut[40],
  55. uint8_t privateKeyHexOut[65],
  56. uint8_t publicKeyBase32Out[53],
  57. struct Random* rand)
  58. {
  59. struct Address address;
  60. uint8_t privateKey[32];
  61. for (;;) {
  62. Random_bytes(rand, privateKey, 32);
  63. crypto_scalarmult_curve25519_base(address.key, privateKey);
  64. // Brute force for keys until one matches FC00:/8
  65. if (AddressCalc_addressForPublicKey(address.ip6.bytes, address.key)) {
  66. Hex_encode(privateKeyHexOut, 65, privateKey, 32);
  67. Base32_encode(publicKeyBase32Out, 53, address.key, 32);
  68. Address_printShortIp(addressOut, &address);
  69. return 0;
  70. }
  71. }
  72. }
  73. static int genconf(struct Random* rand, bool eth)
  74. {
  75. uint8_t password[32];
  76. uint8_t password2[32];
  77. uint8_t password3[32];
  78. uint8_t password4[32];
  79. Random_base32(rand, password, 32);
  80. Random_base32(rand, password2, 32);
  81. Random_base32(rand, password3, 32);
  82. Random_base32(rand, password4, 32);
  83. uint8_t adminPassword[32];
  84. Random_base32(rand, adminPassword, 32);
  85. uint16_t port = 0;
  86. while (port <= 1024) {
  87. port = Random_uint16(rand);
  88. }
  89. uint8_t publicKeyBase32[53];
  90. uint8_t address[40];
  91. uint8_t privateKeyHex[65];
  92. genAddress(address, privateKeyHex, publicKeyBase32, rand);
  93. printf("{\n");
  94. printf(" // Private key:\n"
  95. " // Your confidentiality and data integrity depend on this key, keep it secret!\n"
  96. " \"privateKey\": \"%s\",\n\n", privateKeyHex);
  97. printf(" // This key corresponds to the public key and ipv6 address:\n"
  98. " \"publicKey\": \"%s.k\",\n", publicKeyBase32);
  99. printf(" \"ipv6\": \"%s\",\n", address);
  100. printf("\n"
  101. " // Anyone connecting and offering these passwords on connection will be allowed.\n"
  102. " //\n"
  103. " // WARNING: Currently there is no key derivation done on the password field,\n"
  104. " // DO NOT USE A PASSWORD HERE use something which is truly random and\n"
  105. " // cannot be guessed.\n"
  106. " // Including a username in the beginning of the password string is encouraged\n"
  107. " // to aid in remembering which users are who.\n"
  108. " //\n"
  109. " \"authorizedPasswords\":\n"
  110. " [\n"
  111. " // A unique string which is known to the client and server.\n"
  112. " {\"password\": \"%s\"}\n", password);
  113. printf("\n"
  114. " // More passwords should look like this.\n"
  115. " // {\"password\": \"%s\"},\n", password2);
  116. printf(" // {\"password\": \"%s\"},\n", password3);
  117. printf(" // {\"password\": \"%s\"},\n", password4);
  118. printf("\n"
  119. " // Below is an example of your connection credentials\n"
  120. " // that you can give to other people so they can connect\n"
  121. " // to you using your default password (from above)\n"
  122. " // Adding a unique password for each user is advisable\n"
  123. " // so that leaks can be isolated.\n"
  124. " //\n"
  125. " // \"your.external.ip.goes.here:%u\":{", port);
  126. printf("\"password\":\"%s\",", password);
  127. printf("\"publicKey\":\"%s.k\"}\n", publicKeyBase32);
  128. printf(" ],\n"
  129. "\n"
  130. " // Settings for administering and extracting information from your router.\n"
  131. " // This interface provides functions which can be called through a UDP socket.\n"
  132. " // See admin/Readme.md for more information about the API and try:\n"
  133. " // ./contrib/python/cexec 'functions'\n"
  134. " // For a list of functions which can be called.\n"
  135. " // For example: ./contrib/python/cexec 'memory()'\n"
  136. " // will call a function which gets the core's current memory consumption.\n"
  137. " // ./contrib/python/cjdnslog\n"
  138. " // is a tool which uses this admin interface to get logs from cjdns.\n"
  139. " \"admin\":\n"
  140. " {\n"
  141. " // Port to bind the admin RPC server to.\n"
  142. " \"bind\": \"127.0.0.1:11234\",\n"
  143. "\n"
  144. " // Password for admin RPC server.\n"
  145. " \"password\": \"%s\"\n", adminPassword);
  146. printf(" },\n"
  147. "\n"
  148. " // Interfaces to connect to the switch core.\n"
  149. " \"interfaces\":\n"
  150. " {\n"
  151. " // The interface which connects over UDP/IP based VPN tunnel.\n"
  152. " \"UDPInterface\":\n"
  153. " [\n"
  154. " {\n"
  155. " // Bind to this port.\n"
  156. " \"bind\": \"0.0.0.0:%u\",\n", port);
  157. printf("\n"
  158. " // Nodes to connect to.\n"
  159. " \"connectTo\":\n"
  160. " {\n"
  161. " // Add connection credentials here to join the network\n"
  162. " // Ask somebody who is already connected.\n"
  163. " }\n"
  164. " }\n"
  165. " ]\n");
  166. #ifdef HAS_ETH_INTERFACE
  167. printf("\n");
  168. if (!eth) {
  169. printf(" /*\n");
  170. }
  171. printf(" \"ETHInterface\":\n"
  172. " [\n"
  173. " // Alternatively bind to just one device and either beacon and/or\n"
  174. " // connect to a specified MAC address\n"
  175. " {\n"
  176. " // Bind to this device (interface name, not MAC)\n"
  177. " // \"all\" is a pseudo-name which will try to connect to all devices.\n"
  178. " \"bind\": \"all\",\n"
  179. "\n"
  180. " // Auto-connect to other cjdns nodes on the same network.\n"
  181. " // Options:\n"
  182. " //\n"
  183. " // 0 -- Disabled.\n"
  184. " //\n"
  185. " // 1 -- Accept beacons, this will cause cjdns to accept incoming\n"
  186. " // beacon messages and try connecting to the sender.\n"
  187. " //\n"
  188. " // 2 -- Accept and send beacons, this will cause cjdns to broadcast\n"
  189. " // messages on the local network which contain a randomly\n"
  190. " // generated per-session password, other nodes which have this\n"
  191. " // set to 1 or 2 will hear the beacon messages and connect\n"
  192. " // automatically.\n"
  193. " //\n"
  194. " \"beacon\": 2,\n"
  195. "\n"
  196. " // Node(s) to connect to manually\n"
  197. " // Note: does not work with \"all\" pseudo-device-name\n"
  198. " \"connectTo\":\n"
  199. " {\n"
  200. " // Credentials for connecting look similar to UDP credientials\n"
  201. " // except they begin with the mac address, for example:\n"
  202. " // \"01:02:03:04:05:06\":{\"password\":\"a\",\"publicKey\":\"b\"}\n"
  203. " }\n"
  204. " }\n"
  205. " ]\n");
  206. if (!eth) {
  207. printf(" */\n");
  208. }
  209. printf("\n");
  210. #endif
  211. printf(" },\n"
  212. "\n"
  213. " // Configuration for the router.\n"
  214. " \"router\":\n"
  215. " {\n"
  216. " // The interface which is used for connecting to the cjdns network.\n"
  217. " \"interface\":\n"
  218. " {\n"
  219. " // The type of interface (only TUNInterface is supported for now)\n"
  220. " \"type\": \"TUNInterface\"\n"
  221. #ifndef __APPLE__
  222. "\n"
  223. " // The name of a persistent TUN device to use.\n"
  224. " // This for starting cjdroute as its own user.\n"
  225. " // *MOST USERS DON'T NEED THIS*\n"
  226. " //\"tunDevice\": \"" DEFAULT_TUN_DEV "\"\n"
  227. #endif
  228. " },\n"
  229. "\n"
  230. " // System for tunneling IPv4 and ICANN IPv6 through cjdns.\n"
  231. " // This is using the cjdns switch layer as a VPN carrier.\n"
  232. " \"ipTunnel\":\n"
  233. " {\n"
  234. " // Nodes allowed to connect to us.\n"
  235. " // When a node with the given public key connects, give them the\n"
  236. " // ip4 and/or ip6 addresses listed.\n"
  237. " \"allowedConnections\":\n"
  238. " [\n"
  239. " // Give the client an address on 192.168.1.0/24, and an address\n"
  240. " // it thinks has all of IPv6 behind it.\n"
  241. " // {\n"
  242. " // \"publicKey\": "
  243. "\"f64hfl7c4uxt6krmhPutTheRealAddressOfANodeHere7kfm5m0.k\",\n"
  244. " // \"ip4Address\": \"192.168.1.24\",\n"
  245. " // \"ip4Prefix\": 24,\n"
  246. " // \"ip6Address\": \"2001:123:ab::10\",\n"
  247. " // \"ip6Prefix\": 0\n"
  248. " // },\n"
  249. "\n"
  250. " // It's ok to only specify one address.\n"
  251. " // {\n"
  252. " // \"publicKey\": "
  253. "\"ydq8csdk8p8ThisIsJustAnExampleAddresstxuyqdf27hvn2z0.k\",\n"
  254. " // \"ip4Address\": \"192.168.1.25\",\n"
  255. " // \"ip4Prefix\": 24\n"
  256. " // }\n"
  257. " ],\n"
  258. "\n"
  259. " \"outgoingConnections\":\n"
  260. " [\n"
  261. " // Connect to one or more machines and ask them for IP addresses.\n"
  262. " // \"6743gf5tw80ExampleExampleExampleExamplevlyb23zfnuzv0.k\",\n"
  263. " // \"pw9tfmr8pcrExampleExampleExampleExample8rhg1pgwpwf80.k\",\n"
  264. " // \"g91lxyxhq0kExampleExampleExampleExample6t0mknuhw75l0.k\"\n"
  265. " ]\n"
  266. " }\n"
  267. " },\n"
  268. "\n"
  269. " // Dropping permissions.\n"
  270. " \"security\":\n"
  271. " [\n"
  272. " // Change the user id to this user after starting up and getting resources.\n"
  273. " // exemptAngel exempts the Angel process from setting userId, the Angel is\n"
  274. " // a small isolated piece of code which exists outside of the core's strict\n"
  275. " // sandbox but does not handle network traffic.\n"
  276. " // This must be enabled for IpTunnel to automatically set IP addresses\n"
  277. " // for the TUN device.\n"
  278. " { \"setuser\": \"nobody\", \"exemptAngel\": 1 }\n"
  279. " ],\n"
  280. "\n"
  281. " // Logging\n"
  282. " \"logging\":\n"
  283. " {\n"
  284. " // Uncomment to have cjdns log to stdout rather than making logs available\n"
  285. " // via the admin socket.\n"
  286. " // \"logTo\":\"stdout\"\n"
  287. " },\n"
  288. "\n"
  289. " // If set to non-zero, cjdns will not fork to the background.\n"
  290. " // Recommended for use in conjunction with \"logTo\":\"stdout\".\n"
  291. " \"noBackground\":0,\n"
  292. "}\n");
  293. return 0;
  294. }
  295. static int usage(struct Allocator* alloc, char* appName)
  296. {
  297. char* archInfo = ArchInfo_describe(ArchInfo_detect(), alloc);
  298. char* sysInfo = SysInfo_describe(SysInfo_detect(), alloc);
  299. printf("Cjdns %s %s\n"
  300. "Usage: %s [--help] [--genconf] [--bench] [--version] [--cleanconf] [--nobg]\n"
  301. "\n"
  302. "To get the router up and running.\n"
  303. "Step 1:\n"
  304. " Generate a new configuration file.\n"
  305. " %s --genconf > cjdroute.conf\n"
  306. "\n"
  307. "Step 2:\n"
  308. " Find somebody to connect to.\n"
  309. " Check out the IRC channel or http://hyperboria.net/\n"
  310. " for information about how to meet new people and make connect to them.\n"
  311. "\n"
  312. "Step 3:\n"
  313. " Fire it up!\n"
  314. " sudo %s < cjdroute.conf\n"
  315. "\n"
  316. "For more information about other functions and non-standard setups, see README.md\n",
  317. archInfo, sysInfo, appName, appName, appName);
  318. return 0;
  319. }
  320. static int benchmark()
  321. {
  322. // TODO(cjd):reimplement bench
  323. Assert_failure("unimplemented");
  324. /*
  325. struct Allocator* alloc = MallocAllocator_new(1<<22);
  326. struct EventBase* base = EventBase_new(alloc);
  327. struct Writer* logWriter = FileWriter_new(stdout, alloc);
  328. struct Log* logger = WriterLog_new(logWriter, alloc);
  329. CryptoAuth_benchmark(base, logger, alloc);
  330. */
  331. return 0;
  332. }
  333. struct CheckRunningInstanceContext
  334. {
  335. struct EventBase* base;
  336. struct Allocator* alloc;
  337. struct AdminClient_Result* res;
  338. };
  339. static void checkRunningInstanceCallback(struct AdminClient_Promise* p,
  340. struct AdminClient_Result* res)
  341. {
  342. struct CheckRunningInstanceContext* ctx = p->userData;
  343. // Prevent this from freeing until after we drop out of the loop.
  344. Allocator_adopt(ctx->alloc, p->alloc);
  345. ctx->res = res;
  346. EventBase_endLoop(ctx->base);
  347. }
  348. static void checkRunningInstance(struct Allocator* allocator,
  349. struct EventBase* base,
  350. String* addr,
  351. String* password,
  352. struct Log* logger,
  353. struct Except* eh)
  354. {
  355. struct Allocator* alloc = Allocator_child(allocator);
  356. struct Sockaddr_storage pingAddrStorage;
  357. if (Sockaddr_parse(addr->bytes, &pingAddrStorage)) {
  358. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  359. addr->bytes);
  360. }
  361. struct AdminClient* adminClient =
  362. AdminClient_new(&pingAddrStorage.addr, password, base, logger, alloc);
  363. // 100 milliseconds is plenty to wait for a process to respond on the same machine.
  364. adminClient->millisecondsToWait = 100;
  365. Dict* pingArgs = Dict_new(alloc);
  366. struct AdminClient_Promise* pingPromise =
  367. AdminClient_rpcCall(String_new("ping", alloc), pingArgs, adminClient, alloc);
  368. struct CheckRunningInstanceContext* ctx =
  369. Allocator_malloc(alloc, sizeof(struct CheckRunningInstanceContext));
  370. ctx->base = base;
  371. ctx->alloc = alloc;
  372. ctx->res = NULL;
  373. pingPromise->callback = checkRunningInstanceCallback;
  374. pingPromise->userData = ctx;
  375. EventBase_beginLoop(base);
  376. Assert_true(ctx->res);
  377. if (ctx->res->err != AdminClient_Error_TIMEOUT) {
  378. Except_throw(eh, "Startup failed: cjdroute is already running. [%d]", ctx->res->err);
  379. }
  380. Allocator_free(alloc);
  381. }
  382. int main(int argc, char** argv)
  383. {
  384. #ifdef Log_KEYS
  385. fprintf(stderr, "Log_LEVEL = KEYS, EXPECT TO SEE PRIVATE KEYS IN YOUR LOGS!\n");
  386. #endif
  387. if (argc < 2) {
  388. // Fall through.
  389. } else if (!CString_strcmp("angel", argv[1])) {
  390. return AngelInit_main(argc, argv);
  391. } else if (!CString_strcmp("core", argv[1])) {
  392. return Core_main(argc, argv);
  393. }
  394. Assert_ifParanoid(argc > 0);
  395. struct Except* eh = NULL;
  396. // Allow it to allocate 8MB
  397. struct Allocator* allocator = MallocAllocator_new(1<<23);
  398. struct Random* rand = Random_new(allocator, NULL, eh);
  399. struct EventBase* eventBase = EventBase_new(allocator);
  400. if (argc >= 2) {
  401. // one argument
  402. if ((CString_strcmp(argv[1], "--help") == 0) || (CString_strcmp(argv[1], "-h") == 0)) {
  403. return usage(allocator, argv[0]);
  404. } else if (CString_strcmp(argv[1], "--genconf") == 0) {
  405. bool eth = 0;
  406. for (int i = 1; i < argc; i++) {
  407. if (!CString_strcmp(argv[i], "--eth")) {
  408. eth = 1;
  409. }
  410. }
  411. return genconf(rand, eth);
  412. } else if (CString_strcmp(argv[1], "--pidfile") == 0) {
  413. // deprecated
  414. fprintf(stderr, "'--pidfile' option is deprecated.\n");
  415. return 0;
  416. } else if (CString_strcmp(argv[1], "--reconf") == 0) {
  417. // Performed after reading the configuration
  418. } else if (CString_strcmp(argv[1], "--bench") == 0) {
  419. return benchmark();
  420. } else if ((CString_strcmp(argv[1], "--version") == 0)
  421. || (CString_strcmp(argv[1], "-v") == 0))
  422. {
  423. printf("Cjdns protocol version: %d\n", Version_CURRENT_PROTOCOL);
  424. return 0;
  425. } else if (CString_strcmp(argv[1], "--cleanconf") == 0) {
  426. // Performed after reading configuration
  427. } else if (CString_strcmp(argv[1], "--nobg") == 0) {
  428. // Performed while reading configuration
  429. } else {
  430. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[1]);
  431. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  432. return -1;
  433. }
  434. } else if (argc > 2) {
  435. // more than one argument?
  436. fprintf(stderr, "%s: too many arguments [%s]\n", argv[0], argv[1]);
  437. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  438. // because of '--pidfile $filename'?
  439. if (CString_strcmp(argv[1], "--pidfile") == 0)
  440. {
  441. fprintf(stderr, "\n'--pidfile' option is deprecated.\n");
  442. }
  443. return -1;
  444. }
  445. if (isatty(STDIN_FILENO)) {
  446. // We were started from a terminal
  447. // The chances an user wants to type in a configuration
  448. // bij hand are pretty slim so we show him the usage
  449. return usage(allocator, argv[0]);
  450. } else {
  451. // We assume stdin is a configuration file and that we should
  452. // start routing
  453. }
  454. struct Reader* stdinReader = FileReader_new(stdin, allocator);
  455. Dict config;
  456. if (JsonBencSerializer_get()->parseDictionary(stdinReader, allocator, &config)) {
  457. fprintf(stderr, "Failed to parse configuration.\n");
  458. return -1;
  459. }
  460. if (argc == 2 && CString_strcmp(argv[1], "--cleanconf") == 0) {
  461. struct Writer* stdoutWriter = FileWriter_new(stdout, allocator);
  462. JsonBencSerializer_get()->serializeDictionary(stdoutWriter, &config);
  463. printf("\n");
  464. return 0;
  465. }
  466. int forceNoBackground = 0;
  467. if (argc == 2 && CString_strcmp(argv[1], "--nobg") == 0) {
  468. forceNoBackground = 1;
  469. }
  470. struct Writer* logWriter = FileWriter_new(stdout, allocator);
  471. struct Log* logger = WriterLog_new(logWriter, allocator);
  472. // --------------------- Get Admin --------------------- //
  473. Dict* configAdmin = Dict_getDict(&config, String_CONST("admin"));
  474. String* adminPass = Dict_getString(configAdmin, String_CONST("password"));
  475. String* adminBind = Dict_getString(configAdmin, String_CONST("bind"));
  476. if (!adminPass) {
  477. adminPass = String_newBinary(NULL, 32, allocator);
  478. Random_base32(rand, (uint8_t*) adminPass->bytes, 32);
  479. adminPass->len = CString_strlen(adminPass->bytes);
  480. }
  481. if (!adminBind) {
  482. Except_throw(eh, "You must specify admin.bind in the cjdroute.conf file.");
  483. }
  484. // --------------------- Welcome to cjdns ---------------------- //
  485. char* archInfo = ArchInfo_describe(ArchInfo_detect(), allocator);
  486. char* sysInfo = SysInfo_describe(SysInfo_detect(), allocator);
  487. Log_info(logger, "Cjdns %s %s", archInfo, sysInfo);
  488. // --------------------- Check for running instance --------------------- //
  489. Log_info(logger, "Checking for running instance...");
  490. checkRunningInstance(allocator, eventBase, adminBind, adminPass, logger, eh);
  491. // --------------------- Setup Pipes to Angel --------------------- //
  492. char angelPipeName[64] = "client-angel-";
  493. Random_base32(rand, (uint8_t*)angelPipeName+13, 31);
  494. Assert_ifParanoid(EventBase_eventCount(eventBase) == 0);
  495. struct Pipe* angelPipe = Pipe_named(angelPipeName, eventBase, eh, allocator);
  496. Assert_ifParanoid(EventBase_eventCount(eventBase) == 2);
  497. angelPipe->logger = logger;
  498. char* args[] = { "angel", angelPipeName, NULL };
  499. // --------------------- Spawn Angel --------------------- //
  500. String* privateKey = Dict_getString(&config, String_CONST("privateKey"));
  501. char* corePath = Process_getPath(allocator);
  502. if (!corePath) {
  503. Except_throw(eh, "Can't find a usable cjdns core executable, "
  504. "make sure it is in the same directory as cjdroute");
  505. }
  506. if (!privateKey) {
  507. Except_throw(eh, "Need to specify privateKey.");
  508. }
  509. Log_info(logger, "Forking angel to background.");
  510. Process_spawn(corePath, args, eventBase, allocator);
  511. // --------------------- Get user for angel to setuid() ---------------------- //
  512. String* securityUser = NULL;
  513. List* securityConf = Dict_getList(&config, String_CONST("security"));
  514. for (int i = 0; securityConf && i < List_size(securityConf); i++) {
  515. securityUser = Dict_getString(List_getDict(securityConf, i), String_CONST("setuser"));
  516. if (securityUser) {
  517. int64_t* ea = Dict_getInt(List_getDict(securityConf, i), String_CONST("exemptAngel"));
  518. if (ea && *ea) {
  519. securityUser = NULL;
  520. }
  521. break;
  522. }
  523. }
  524. // --------------------- Pre-Configure Angel ------------------------- //
  525. Dict* preConf = Dict_new(allocator);
  526. Dict* adminPreConf = Dict_new(allocator);
  527. Dict_putDict(preConf, String_CONST("admin"), adminPreConf, allocator);
  528. Dict_putString(adminPreConf, String_CONST("core"), String_new(corePath, allocator), allocator);
  529. Dict_putString(preConf, String_CONST("privateKey"), privateKey, allocator);
  530. Dict_putString(adminPreConf, String_CONST("bind"), adminBind, allocator);
  531. Dict_putString(adminPreConf, String_CONST("pass"), adminPass, allocator);
  532. if (securityUser) {
  533. Dict_putString(adminPreConf, String_CONST("user"), securityUser, allocator);
  534. }
  535. Dict* logging = Dict_getDict(&config, String_CONST("logging"));
  536. if (logging) {
  537. Dict_putDict(preConf, String_CONST("logging"), logging, allocator);
  538. }
  539. struct Message* toAngelMsg = Message_new(0, 1024, allocator);
  540. BencMessageWriter_write(preConf, toAngelMsg, eh);
  541. Iface_CALL(angelPipe->iface.send, toAngelMsg, &angelPipe->iface);
  542. Log_debug(logger, "Sent [%d] bytes to angel process", toAngelMsg->length);
  543. // --------------------- Get Response from Angel --------------------- //
  544. struct Message* fromAngelMsg =
  545. InterfaceWaiter_waitForData(&angelPipe->iface, eventBase, allocator, eh);
  546. Dict* responseFromAngel = BencMessageReader_read(fromAngelMsg, allocator, eh);
  547. // --------------------- Get Admin Addr/Port/Passwd --------------------- //
  548. Dict* responseFromAngelAdmin = Dict_getDict(responseFromAngel, String_CONST("admin"));
  549. adminBind = Dict_getString(responseFromAngelAdmin, String_CONST("bind"));
  550. if (!adminBind) {
  551. Except_throw(eh, "didn't get address and port back from angel");
  552. }
  553. struct Sockaddr_storage adminAddr;
  554. if (Sockaddr_parse(adminBind->bytes, &adminAddr)) {
  555. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  556. adminBind->bytes);
  557. }
  558. // sanity check, Pipe_named() creates 2 events, see above.
  559. Assert_ifParanoid(EventBase_eventCount(eventBase) == 2);
  560. // --------------------- Configuration ------------------------- //
  561. Configurator_config(&config,
  562. &adminAddr.addr,
  563. adminPass,
  564. eventBase,
  565. logger,
  566. allocator);
  567. // --------------------- noBackground ------------------------ //
  568. int64_t* noBackground = Dict_getInt(&config, String_CONST("noBackground"));
  569. if (forceNoBackground || (noBackground && *noBackground)) {
  570. EventBase_beginLoop(eventBase);
  571. }
  572. //Allocator_free(allocator);
  573. return 0;
  574. }