cjdroute2.c 39 KB

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