cjdroute2.c 27 KB

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