cjdroute2.c 39 KB

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