cjdroute2.c 36 KB

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