cjdroute2.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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 "client/AdminClient.h"
  16. #include "admin/angel/Core.h"
  17. #include "admin/angel/InterfaceWaiter.h"
  18. #include "client/Configurator.h"
  19. #include "benc/Dict.h"
  20. #include "benc/Int.h"
  21. #include "benc/List.h"
  22. #include "benc/serialization/BencSerializer.h"
  23. #include "benc/serialization/json/JsonBencSerializer.h"
  24. #include "benc/serialization/standard/BencMessageReader.h"
  25. #include "benc/serialization/standard/BencMessageWriter.h"
  26. #include "crypto/AddressCalc.h"
  27. #include "crypto/CryptoAuth.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/Defined.h"
  42. #include "util/events/UDPAddrIface.h"
  43. #include "util/events/Time.h"
  44. #include "util/events/EventBase.h"
  45. #include "util/events/Pipe.h"
  46. #include "util/events/Process.h"
  47. #include "util/events/FakeNetwork.h"
  48. #include "util/Hex.h"
  49. #include "util/log/Log.h"
  50. #include "util/log/FileWriterLog.h"
  51. #include "util/SysInfo.h"
  52. #include "util/version/Version.h"
  53. #include "net/Benchmark.h"
  54. #include "crypto_scalarmult_curve25519.h"
  55. #include <stdint.h>
  56. #include <stdio.h>
  57. #include <unistd.h>
  58. #define DEFAULT_TUN_DEV "tun0"
  59. static int genAddress(uint8_t addressOut[40],
  60. uint8_t privateKeyHexOut[65],
  61. uint8_t publicKeyBase32Out[53],
  62. struct Random* rand)
  63. {
  64. struct Address address;
  65. uint8_t privateKey[32];
  66. for (;;) {
  67. Random_bytes(rand, privateKey, 32);
  68. crypto_scalarmult_curve25519_base(address.key, privateKey);
  69. // Brute force for keys until one matches FC00:/8
  70. if (AddressCalc_addressForPublicKey(address.ip6.bytes, address.key)) {
  71. Hex_encode(privateKeyHexOut, 65, privateKey, 32);
  72. Base32_encode(publicKeyBase32Out, 53, address.key, 32);
  73. Address_printShortIp(addressOut, &address);
  74. return 0;
  75. }
  76. }
  77. }
  78. static int genconf(struct Random* rand, bool eth)
  79. {
  80. uint8_t password[32];
  81. uint8_t password2[32];
  82. uint8_t password3[32];
  83. uint8_t password4[32];
  84. Random_base32(rand, password, 32);
  85. Random_base32(rand, password2, 32);
  86. Random_base32(rand, password3, 32);
  87. Random_base32(rand, password4, 32);
  88. uint16_t port = 0;
  89. while (port <= 1024) {
  90. port = Random_uint16(rand);
  91. }
  92. uint8_t publicKeyBase32[53];
  93. uint8_t address[40];
  94. uint8_t privateKeyHex[65];
  95. genAddress(address, privateKeyHex, publicKeyBase32, rand);
  96. printf("{\n");
  97. printf(" // Private key:\n"
  98. " // Your confidentiality and data integrity depend on this key, keep it secret!\n"
  99. " \"privateKey\": \"%s\",\n\n", privateKeyHex);
  100. printf(" // This key corresponds to the public key and ipv6 address:\n"
  101. " \"publicKey\": \"%s.k\",\n", publicKeyBase32);
  102. printf(" \"ipv6\": \"%s\",\n", address);
  103. printf("\n"
  104. " // Anyone connecting and offering these passwords on connection will be allowed.\n"
  105. " //\n"
  106. " // WARNING: If a \"login\" parameter is passed, someone sniffing on the wire can\n"
  107. " // sniff the packet and crack to find it. If the \"login\" is not passed\n"
  108. " // then the hash of the 'password' is effectively the login, therefore\n"
  109. " // that can be cracked.\n"
  110. " //\n"
  111. " \"authorizedPasswords\":\n"
  112. " [\n"
  113. " // A unique string which is known to the client and server.\n"
  114. " // Specify an optional user to identify the peer locally.\n"
  115. " // It is not used for authentication.\n"
  116. " {\"password\": \"%s\", \"user\": \"default-login\"}\n", password);
  117. printf("\n"
  118. " // More passwords should look like this.\n"
  119. " // {\"password\": \"%s\", \"user\": \"my-second-peer\"},\n", password2);
  120. printf(" // {\"password\": \"%s\", \"user\": \"my-third-peer\"},\n", password3);
  121. printf(" // {\"password\": \"%s\", \"user\": \"my-fourth-peer\"},\n", password4);
  122. printf("\n"
  123. " // Below is an example of your connection credentials\n"
  124. " // that you can give to other people so they can connect\n"
  125. " // to you using your default password (from above).\n"
  126. " // The login field here yourself to your peer and the peerName field\n"
  127. " // is the name the peer which will be displayed in peerStats\n"
  128. " // Adding a unique password for each peer is advisable\n"
  129. " // so that leaks can be isolated.\n"
  130. " /*\n"
  131. " \"your.external.ip.goes.here:%u\": {\n", port);
  132. printf(" \"login\": \"default-login\",\n"
  133. " \"password\":\"%s\",\n", password);
  134. printf(" \"publicKey\":\"%s.k\",\n", publicKeyBase32);
  135. printf(" \"peerName\":\"your-name-goes-here\"\n"
  136. " },\n"
  137. " */\n");
  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. " // ./tools/cexec\n"
  144. " // For a list of functions which can be called.\n"
  145. " // For example: ./tools/cexec 'memory()'\n"
  146. " // will call a function which gets the core's current memory consumption.\n"
  147. " // ./tools/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. " // This is a static password by default, so that tools like\n"
  156. " // ./tools/cexec can use the API without you creating a\n"
  157. " // config file at ~/.cjdnsadmin first. If you decide to\n"
  158. " // expose the admin API to the network, change the password!\n"
  159. " \"password\": \"NONE\"\n");
  160. printf(" },\n"
  161. "\n"
  162. " // Interfaces to connect to the switch core.\n"
  163. " \"interfaces\":\n"
  164. " {\n"
  165. " // The interface which connects over UDP/IP based VPN tunnel.\n"
  166. " \"UDPInterface\":\n"
  167. " [\n"
  168. " {\n"
  169. " // Bind to this port.\n"
  170. " \"bind\": \"0.0.0.0:%u\",\n", port);
  171. printf("\n"
  172. " // Nodes to connect to (IPv4 only).\n"
  173. " \"connectTo\":\n"
  174. " {\n"
  175. " // Add connection credentials here to join the network\n"
  176. " // If you have several, don't forget the separating commas\n"
  177. " // They should look like:\n"
  178. " // \"ipv4 address:port\": {\n"
  179. " // \"login\": \"(optional) name your peer has for you\"\n"
  180. " // \"password\": \"password to connect with\",\n"
  181. " // \"publicKey\": \"remote node key.k\",\n"
  182. " // \"peerName\": \"(optional) human-readable name for peer\"\n"
  183. " // },\n"
  184. " // Ask somebody who is already connected.\n"
  185. " }\n"
  186. " },\n"
  187. " {\n"
  188. " // Bind to this port.\n"
  189. " \"bind\": \"[::]:%u\",\n", port);
  190. printf("\n"
  191. " // Nodes to connect to (IPv6 only).\n"
  192. " \"connectTo\":\n"
  193. " {\n"
  194. " // Add connection credentials here to join the network\n"
  195. " // Ask somebody who is already connected.\n"
  196. " }\n"
  197. " }\n"
  198. " ]\n");
  199. #ifdef HAS_ETH_INTERFACE
  200. printf("\n");
  201. if (!eth) {
  202. printf(" /*\n");
  203. }
  204. printf(" \"ETHInterface\":\n"
  205. " [\n"
  206. " // Alternatively bind to just one device and either beacon and/or\n"
  207. " // connect to a specified MAC address\n"
  208. " {\n"
  209. " // Bind to this device (interface name, not MAC)\n"
  210. " // \"all\" is a pseudo-name which will try to connect to all devices.\n"
  211. " \"bind\": \"all\",\n"
  212. "\n"
  213. " // Auto-connect to other cjdns nodes on the same network.\n"
  214. " // Options:\n"
  215. " //\n"
  216. " // 0 -- Disabled.\n"
  217. " //\n"
  218. " // 1 -- Accept beacons, this will cause cjdns to accept incoming\n"
  219. " // beacon messages and try connecting to the sender.\n"
  220. " //\n"
  221. " // 2 -- Accept and send beacons, this will cause cjdns to broadcast\n"
  222. " // messages on the local network which contain a randomly\n"
  223. " // generated per-session password, other nodes which have this\n"
  224. " // set to 1 or 2 will hear the beacon messages and connect\n"
  225. " // automatically.\n"
  226. " //\n"
  227. " \"beacon\": 2,\n"
  228. "\n"
  229. " // Node(s) to connect to manually\n"
  230. " // Note: does not work with \"all\" pseudo-device-name\n"
  231. " \"connectTo\":\n"
  232. " {\n"
  233. " // Credentials for connecting look similar to UDP credientials\n"
  234. " // except they begin with the mac address, for example:\n"
  235. " // \"01:02:03:04:05:06\":{\"password\":\"a\",\"publicKey\":\"b\"}\n"
  236. " }\n"
  237. " }\n"
  238. " ]\n");
  239. if (!eth) {
  240. printf(" */\n");
  241. }
  242. printf("\n");
  243. #endif
  244. printf(" },\n"
  245. "\n"
  246. " // Configuration for the router.\n"
  247. " \"router\":\n"
  248. " {\n"
  249. " // The interface which is used for connecting to the cjdns network.\n"
  250. " \"interface\":\n"
  251. " {\n"
  252. " // The type of interface (only TUNInterface is supported for now)\n"
  253. " \"type\": \"TUNInterface\"\n"
  254. #ifndef __APPLE__
  255. "\n"
  256. " // The name of a persistent TUN device to use.\n"
  257. " // This for starting cjdroute as its own user.\n"
  258. " // *MOST USERS DON'T NEED THIS*\n"
  259. " //\"tunDevice\": \"" DEFAULT_TUN_DEV "\"\n"
  260. #endif
  261. " },\n"
  262. "\n"
  263. " // System for tunneling IPv4 and ICANN IPv6 through cjdns.\n"
  264. " // This is using the cjdns switch layer as a VPN carrier.\n"
  265. " \"ipTunnel\":\n"
  266. " {\n"
  267. " // Nodes allowed to connect to us.\n"
  268. " // When a node with the given public key connects, give them the\n"
  269. " // ip4 and/or ip6 addresses listed.\n"
  270. " \"allowedConnections\":\n"
  271. " [\n"
  272. " // Give the client an address on 192.168.1.0/24, and an address\n"
  273. " // it thinks has all of IPv6 behind it.\n"
  274. " // {\n"
  275. " // \"publicKey\": "
  276. "\"f64hfl7c4uxt6krmhPutTheRealAddressOfANodeHere7kfm5m0.k\",\n"
  277. " // \"ip4Address\": \"192.168.1.24\",\n"
  278. " // \"ip4Prefix\": 24,\n"
  279. " // \"ip6Address\": \"2001:123:ab::10\",\n"
  280. " // \"ip6Prefix\": 0\n"
  281. " // },\n"
  282. "\n"
  283. " // It's ok to only specify one address.\n"
  284. " // {\n"
  285. " // \"publicKey\": "
  286. "\"ydq8csdk8p8ThisIsJustAnExampleAddresstxuyqdf27hvn2z0.k\",\n"
  287. " // \"ip4Address\": \"192.168.1.25\",\n"
  288. " // \"ip4Prefix\": 24\n"
  289. " // }\n"
  290. " ],\n"
  291. "\n"
  292. " \"outgoingConnections\":\n"
  293. " [\n"
  294. " // Connect to one or more machines and ask them for IP addresses.\n"
  295. " // \"6743gf5tw80ExampleExampleExampleExamplevlyb23zfnuzv0.k\",\n"
  296. " // \"pw9tfmr8pcrExampleExampleExampleExample8rhg1pgwpwf80.k\",\n"
  297. " // \"g91lxyxhq0kExampleExampleExampleExample6t0mknuhw75l0.k\"\n"
  298. " ]\n"
  299. " }\n"
  300. " },\n"
  301. "\n");
  302. printf(" // Dropping permissions.\n"
  303. " // In the event of a serious security exploit in cjdns, leak of confidential\n"
  304. " // network traffic and/or keys is highly likely but the following rules are\n"
  305. " // designed to prevent the attack from spreading to the system on which cjdns\n"
  306. " // is running.\n"
  307. " // Counter-intuitively, cjdns is *more* secure if it is started as root because\n"
  308. " // non-root users do not have permission to use chroot or change usernames,\n"
  309. " // limiting the effectiveness of the mitigations herein.\n"
  310. " \"security\":\n"
  311. " [\n"
  312. " // Change the user id to sandbox the cjdns process after it starts.\n"
  313. " // If keepNetAdmin is set to 0, IPTunnel will be unable to set IP addresses\n"
  314. " // and ETHInterface will be unable to hot-add new interfaces\n"
  315. " // Use { \"setuser\": 0 } to disable.\n"
  316. " // Default: enabled with keepNetAdmin\n"
  317. " { \"setuser\": \"nobody\", \"keepNetAdmin\": 1 },\n"
  318. "\n"
  319. " // Chroot changes the filesystem root directory which cjdns sees, blocking it\n"
  320. " // from accessing files outside of the chroot sandbox, if the user does not\n"
  321. " // have permission to use chroot(), this will fail quietly.\n"
  322. " // Use { \"chroot\": 0 } to disable.\n");
  323. if (Defined(android)) {
  324. printf(" // Default: disabled\n"
  325. " { \"chroot\": 0 },\n");
  326. }
  327. else {
  328. printf(" // Default: enabled (using \"/var/run\")\n"
  329. " { \"chroot\": \"/var/run/\" },\n");
  330. }
  331. printf("\n"
  332. " // Nofiles is a deprecated security feature which prevents cjdns from opening\n"
  333. " // any files at all, using this will block setting of IP addresses and\n"
  334. " // hot-adding ETHInterface devices but for users who do not need this, it\n"
  335. " // provides a formidable sandbox.\n"
  336. " // Default: disabled\n"
  337. " { \"nofiles\": 0 },\n"
  338. "\n"
  339. " // Noforks will prevent cjdns from spawning any new processes or threads,\n"
  340. " // this prevents many types of exploits from attacking the wider system.\n"
  341. " // Default: enabled\n"
  342. " { \"noforks\": 1 },\n"
  343. "\n"
  344. " // Seccomp is the most advanced sandboxing feature in cjdns, it uses\n"
  345. " // SECCOMP_BPF to filter the system calls which cjdns is able to make on a\n"
  346. " // linux system, strictly limiting it's access to the outside world\n"
  347. " // This will fail quietly on any non-linux system\n");
  348. if (Defined(android)) {
  349. printf(" // Default: disabled\n"
  350. " { \"seccomp\": 0 },\n");
  351. }
  352. else {
  353. printf(" // Default: enabled\n"
  354. " { \"seccomp\": 1 },\n");
  355. }
  356. printf("\n"
  357. " // The client sets up the core using a sequence of RPC calls, the responses\n"
  358. " // to these calls are verified but in the event that the client crashes\n"
  359. " // setup of the core completes, it could leave the core in an insecure state\n"
  360. " // This call constitutes the client telling the core that the security rules\n"
  361. " // have been fully applied and the core may run. Without it, the core will\n"
  362. " // exit within a few seconds with return code 232.\n"
  363. " // Default: enabled\n"
  364. " { \"setupComplete\": 1 }\n"
  365. " ],\n"
  366. "\n"
  367. " // Logging\n"
  368. " \"logging\":\n"
  369. " {\n"
  370. " // Uncomment to have cjdns log to stdout rather than making logs available\n"
  371. " // via the admin socket.\n"
  372. " // \"logTo\":\"stdout\"\n"
  373. " },\n"
  374. "\n"
  375. " // If set to non-zero, cjdns will not fork to the background.\n"
  376. " // Recommended for use in conjunction with \"logTo\":\"stdout\".\n");
  377. if (Defined(win32)) {
  378. printf(" \"noBackground\":1,\n");
  379. }
  380. else {
  381. printf(" \"noBackground\":0,\n");
  382. }
  383. printf("}\n");
  384. return 0;
  385. }
  386. static int usage(struct Allocator* alloc, char* appName)
  387. {
  388. char* sysInfo = SysInfo_describe(SysInfo_detect(), alloc);
  389. printf("Cjdns %s %s\n"
  390. "Usage:\n"
  391. " cjdroute --help This information\n"
  392. " cjdroute --genconf [--no-eth] Generate a configuration file, write it to stdout\n"
  393. " if --no-eth is specified then eth beaconing will\n"
  394. " be disabled.\n"
  395. " cjdroute --bench Run some cryptography performance benchmarks.\n"
  396. " cjdroute --version Print the protocol version which this node speaks.\n"
  397. " cjdroute --cleanconf < conf Print a clean (valid json) version of the config.\n"
  398. " cjdroute --nobg Never fork to the background no matter the config.\n"
  399. "\n"
  400. "To get the router up and running.\n"
  401. "Step 1:\n"
  402. " Generate a new configuration file.\n"
  403. " cjdroute --genconf > cjdroute.conf\n"
  404. "\n"
  405. "Step 2:\n"
  406. " Find somebody to connect to.\n"
  407. " Check out the IRC channel or http://hyperboria.net/\n"
  408. " for information about how to meet new people and make connect to them.\n"
  409. " Read more here: https://github.com/cjdelisle/cjdns/#2-find-a-friend\n"
  410. "\n"
  411. "Step 3:\n"
  412. " Add that somebody's node to your cjdroute.conf file.\n"
  413. " https://github.com/cjdelisle/cjdns/#3-connect-your-node-to-your-friends-node\n"
  414. "\n"
  415. "Step 4:\n"
  416. " Fire it up!\n"
  417. " sudo cjdroute < cjdroute.conf\n"
  418. "\n"
  419. "For more information about other functions and non-standard setups, see README.md\n",
  420. ArchInfo_getArchStr(), sysInfo);
  421. return 0;
  422. }
  423. struct CheckRunningInstanceContext
  424. {
  425. struct EventBase* base;
  426. struct Allocator* alloc;
  427. struct AdminClient_Result* res;
  428. };
  429. static void checkRunningInstanceCallback(struct AdminClient_Promise* p,
  430. struct AdminClient_Result* res)
  431. {
  432. struct CheckRunningInstanceContext* ctx = p->userData;
  433. // Prevent this from freeing until after we drop out of the loop.
  434. Allocator_adopt(ctx->alloc, p->alloc);
  435. ctx->res = res;
  436. EventBase_endLoop(ctx->base);
  437. }
  438. static void checkRunningInstance(struct Allocator* allocator,
  439. struct EventBase* base,
  440. String* addr,
  441. String* password,
  442. struct Log* logger,
  443. struct Except* eh)
  444. {
  445. struct Allocator* alloc = Allocator_child(allocator);
  446. struct Sockaddr_storage pingAddrStorage;
  447. if (Sockaddr_parse(addr->bytes, &pingAddrStorage)) {
  448. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  449. addr->bytes);
  450. }
  451. struct UDPAddrIface* udp = UDPAddrIface_new(base, NULL, alloc, NULL, logger);
  452. struct AdminClient* adminClient =
  453. AdminClient_new(&udp->generic, &pingAddrStorage.addr, password, base, logger, alloc);
  454. // 100 milliseconds is plenty to wait for a process to respond on the same machine.
  455. adminClient->millisecondsToWait = 100;
  456. Dict* pingArgs = Dict_new(alloc);
  457. struct AdminClient_Promise* pingPromise =
  458. AdminClient_rpcCall(String_new("ping", alloc), pingArgs, adminClient, alloc);
  459. struct CheckRunningInstanceContext* ctx =
  460. Allocator_malloc(alloc, sizeof(struct CheckRunningInstanceContext));
  461. ctx->base = base;
  462. ctx->alloc = alloc;
  463. ctx->res = NULL;
  464. pingPromise->callback = checkRunningInstanceCallback;
  465. pingPromise->userData = ctx;
  466. EventBase_beginLoop(base);
  467. Assert_true(ctx->res);
  468. if (ctx->res->err != AdminClient_Error_TIMEOUT) {
  469. Except_throw(eh, "Startup failed: cjdroute is already running. [%d]", ctx->res->err);
  470. }
  471. Allocator_free(alloc);
  472. }
  473. static void onCoreExit(int64_t exit_status, int term_signal)
  474. {
  475. Assert_failure("Core exited with status [%d], signal [%d]\n", (int)exit_status, term_signal);
  476. }
  477. int main(int argc, char** argv)
  478. {
  479. #ifdef Log_KEYS
  480. fprintf(stderr, "Log_LEVEL = KEYS, EXPECT TO SEE PRIVATE KEYS IN YOUR LOGS!\n");
  481. #endif
  482. if (argc > 1 && (!CString_strcmp("angel", argv[1]) || !CString_strcmp("core", argv[1]))) {
  483. return Core_main(argc, argv);
  484. }
  485. Assert_ifParanoid(argc > 0);
  486. struct Except* eh = NULL;
  487. // Allow it to allocate 8MB
  488. struct Allocator* allocator = MallocAllocator_new(1<<23);
  489. struct Random* rand = Random_new(allocator, NULL, eh);
  490. struct EventBase* eventBase = EventBase_new(allocator);
  491. if (argc >= 2) {
  492. // one argument
  493. if ((CString_strcmp(argv[1], "--help") == 0) || (CString_strcmp(argv[1], "-h") == 0)) {
  494. return usage(allocator, argv[0]);
  495. } else if (CString_strcmp(argv[1], "--genconf") == 0) {
  496. bool eth = 1;
  497. for (int i = 1; i < argc; i++) {
  498. if (!CString_strcmp(argv[i], "--no-eth")) {
  499. eth = 0;
  500. }
  501. }
  502. return genconf(rand, eth);
  503. } else if (CString_strcmp(argv[1], "--pidfile") == 0) {
  504. // deprecated
  505. fprintf(stderr, "'--pidfile' option is deprecated.\n");
  506. return 0;
  507. } else if (CString_strcmp(argv[1], "--reconf") == 0) {
  508. // Performed after reading the configuration
  509. } else if (CString_strcmp(argv[1], "--bench") == 0) {
  510. Benchmark_runAll();
  511. return 0;
  512. } else if ((CString_strcmp(argv[1], "--version") == 0)
  513. || (CString_strcmp(argv[1], "-v") == 0))
  514. {
  515. printf("Cjdns version: %s\n", CJD_PACKAGE_VERSION);
  516. printf("Cjdns protocol version: %d\n", Version_CURRENT_PROTOCOL);
  517. return 0;
  518. } else if (CString_strcmp(argv[1], "--cleanconf") == 0) {
  519. // Performed after reading configuration
  520. } else if (CString_strcmp(argv[1], "--nobg") == 0) {
  521. // Performed while reading configuration
  522. } else {
  523. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[1]);
  524. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  525. return -1;
  526. }
  527. } else if (argc > 2) {
  528. // more than one argument?
  529. fprintf(stderr, "%s: too many arguments [%s]\n", argv[0], argv[1]);
  530. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  531. // because of '--pidfile $filename'?
  532. if (CString_strcmp(argv[1], "--pidfile") == 0)
  533. {
  534. fprintf(stderr, "\n'--pidfile' option is deprecated.\n");
  535. }
  536. return -1;
  537. }
  538. if (isatty(STDIN_FILENO)) {
  539. // We were started from a terminal
  540. // The chances an user wants to type in a configuration
  541. // bij hand are pretty slim so we show him the usage
  542. return usage(allocator, argv[0]);
  543. } else {
  544. // We assume stdin is a configuration file and that we should
  545. // start routing
  546. }
  547. struct Reader* stdinReader = FileReader_new(stdin, allocator);
  548. Dict config;
  549. if (JsonBencSerializer_get()->parseDictionary(stdinReader, allocator, &config)) {
  550. fprintf(stderr, "Failed to parse configuration.\n");
  551. return -1;
  552. }
  553. if (argc == 2 && CString_strcmp(argv[1], "--cleanconf") == 0) {
  554. struct Writer* stdoutWriter = FileWriter_new(stdout, allocator);
  555. JsonBencSerializer_get()->serializeDictionary(stdoutWriter, &config);
  556. printf("\n");
  557. return 0;
  558. }
  559. int forceNoBackground = 0;
  560. if (argc == 2 && CString_strcmp(argv[1], "--nobg") == 0) {
  561. forceNoBackground = 1;
  562. }
  563. struct Log* logger = FileWriterLog_new(stdout, allocator);
  564. // --------------------- Get Admin --------------------- //
  565. Dict* configAdmin = Dict_getDict(&config, String_CONST("admin"));
  566. String* adminPass = Dict_getString(configAdmin, String_CONST("password"));
  567. String* adminBind = Dict_getString(configAdmin, String_CONST("bind"));
  568. if (!adminPass) {
  569. adminPass = String_newBinary(NULL, 32, allocator);
  570. Random_base32(rand, (uint8_t*) adminPass->bytes, 32);
  571. adminPass->len = CString_strlen(adminPass->bytes);
  572. }
  573. if (!adminBind) {
  574. Except_throw(eh, "You must specify admin.bind in the cjdroute.conf file.");
  575. }
  576. // --------------------- Welcome to cjdns ---------------------- //
  577. char* sysInfo = SysInfo_describe(SysInfo_detect(), allocator);
  578. Log_info(logger, "Cjdns %s %s", ArchInfo_getArchStr(), sysInfo);
  579. // --------------------- Check for running instance --------------------- //
  580. Log_info(logger, "Checking for running instance...");
  581. checkRunningInstance(allocator, eventBase, adminBind, adminPass, logger, eh);
  582. // --------------------- Setup Pipes to Angel --------------------- //
  583. struct Allocator* corePipeAlloc = Allocator_child(allocator);
  584. char corePipeName[64] = "client-core-";
  585. Random_base32(rand, (uint8_t*)corePipeName+CString_strlen(corePipeName), 31);
  586. Assert_ifParanoid(EventBase_eventCount(eventBase) == 0);
  587. struct Pipe* corePipe = Pipe_named(corePipeName, eventBase, eh, corePipeAlloc);
  588. Assert_ifParanoid(EventBase_eventCount(eventBase) == 2);
  589. corePipe->logger = logger;
  590. char* args[] = { "core", corePipeName, NULL };
  591. // --------------------- Spawn Angel --------------------- //
  592. String* privateKey = Dict_getString(&config, String_CONST("privateKey"));
  593. char* corePath = Process_getPath(allocator);
  594. if (!corePath) {
  595. Except_throw(eh, "Can't find a usable cjdns core executable, "
  596. "make sure it is in the same directory as cjdroute");
  597. }
  598. if (!privateKey) {
  599. Except_throw(eh, "Need to specify privateKey.");
  600. }
  601. Process_spawn(corePath, args, eventBase, allocator, onCoreExit);
  602. // --------------------- Pre-Configure Core ------------------------- //
  603. Dict* preConf = Dict_new(allocator);
  604. Dict* adminPreConf = Dict_new(allocator);
  605. Dict_putDict(preConf, String_CONST("admin"), adminPreConf, allocator);
  606. Dict_putString(preConf, String_CONST("privateKey"), privateKey, allocator);
  607. Dict_putString(adminPreConf, String_CONST("bind"), adminBind, allocator);
  608. Dict_putString(adminPreConf, String_CONST("pass"), adminPass, allocator);
  609. Dict* logging = Dict_getDict(&config, String_CONST("logging"));
  610. if (logging) {
  611. Dict_putDict(preConf, String_CONST("logging"), logging, allocator);
  612. }
  613. struct Message* toCoreMsg = Message_new(0, 1024, allocator);
  614. BencMessageWriter_write(preConf, toCoreMsg, eh);
  615. Iface_CALL(corePipe->iface.send, toCoreMsg, &corePipe->iface);
  616. Log_debug(logger, "Sent [%d] bytes to core", toCoreMsg->length);
  617. // --------------------- Get Response from Core --------------------- //
  618. struct Message* fromCoreMsg =
  619. InterfaceWaiter_waitForData(&corePipe->iface, eventBase, allocator, eh);
  620. Dict* responseFromCore = BencMessageReader_read(fromCoreMsg, allocator, eh);
  621. // --------------------- Close the Core Pipe --------------------- //
  622. Allocator_free(corePipeAlloc);
  623. corePipe = NULL;
  624. // --------------------- Get Admin Addr/Port/Passwd --------------------- //
  625. Dict* responseFromCoreAdmin = Dict_getDict(responseFromCore, String_CONST("admin"));
  626. adminBind = Dict_getString(responseFromCoreAdmin, String_CONST("bind"));
  627. if (!adminBind) {
  628. Except_throw(eh, "didn't get address and port back from core");
  629. }
  630. struct Sockaddr_storage adminAddr;
  631. if (Sockaddr_parse(adminBind->bytes, &adminAddr)) {
  632. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  633. adminBind->bytes);
  634. }
  635. Assert_ifParanoid(EventBase_eventCount(eventBase) == 1);
  636. // --------------------- Configuration ------------------------- //
  637. Configurator_config(&config,
  638. &adminAddr.addr,
  639. adminPass,
  640. eventBase,
  641. logger,
  642. allocator);
  643. // --------------------- noBackground ------------------------ //
  644. int64_t* noBackground = Dict_getInt(&config, String_CONST("noBackground"));
  645. if (forceNoBackground || (noBackground && *noBackground)) {
  646. Log_debug(logger, "Keeping cjdns client alive because %s",
  647. (forceNoBackground) ? "--nobg was specified on the command line"
  648. : "noBackground was set in the configuration");
  649. EventBase_beginLoop(eventBase);
  650. }
  651. // Freeing this allocator here causes the core to be terminated in the epoll syscall.
  652. //Allocator_free(allocator);
  653. return 0;
  654. }