cjdroute2.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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/CryptoAuth.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 "net/Benchmark.h"
  59. #include <stdint.h>
  60. #include <stdio.h>
  61. #include <unistd.h>
  62. #include <errno.h>
  63. #include <string.h>
  64. #include <time.h>
  65. #include <stdlib.h>
  66. #define DEFAULT_TUN_DEV "tun0"
  67. #ifndef CJD_PACKAGE_VERSION
  68. #define CJD_PACKAGE_VERSION "unknown"
  69. #endif
  70. static int genconf(struct Allocator* alloc, struct Random* rand, bool eth, bool seed)
  71. {
  72. if (seed) {
  73. uint8_t seedbuf[64];
  74. Bits_memset(seedbuf, 0, 64);
  75. Assert_true(64 == read(STDIN_FILENO, seedbuf, 64));
  76. struct RandomSeed* rs = DeterminentRandomSeed_new(alloc, seedbuf);
  77. rand = Random_newWithSeed(alloc, NULL, rs, NULL);
  78. }
  79. uint8_t password[32];
  80. uint8_t password2[32];
  81. uint8_t password3[32];
  82. uint8_t password4[32];
  83. Random_base32(rand, password, 32);
  84. Random_base32(rand, password2, 32);
  85. Random_base32(rand, password3, 32);
  86. Random_base32(rand, password4, 32);
  87. uint16_t port = 0;
  88. while (port <= 1024) {
  89. port = Random_uint16(rand);
  90. }
  91. uint8_t publicKey[32];
  92. uint8_t publicKeyBase32[53];
  93. uint8_t ip[16];
  94. uint8_t address[40];
  95. uint8_t privateKey[32];
  96. uint8_t privateKeyHex[65];
  97. Key_gen(ip, publicKey, privateKey, rand);
  98. Base32_encode(publicKeyBase32, 53, publicKey, 32);
  99. Hex_encode(privateKeyHex, 65, privateKey, 32);
  100. AddrTools_printIp(address, ip);
  101. printf("{\n");
  102. printf(" // Private key:\n"
  103. " // Your confidentiality and data integrity depend on this key, keep it secret!\n"
  104. " \"privateKey\": \"%s\",\n\n", privateKeyHex);
  105. printf(" // This key corresponds to the public key and ipv6 address:\n"
  106. " \"publicKey\": \"%s.k\",\n", publicKeyBase32);
  107. printf(" \"ipv6\": \"%s\",\n", address);
  108. printf("\n"
  109. " // Anyone connecting and offering these passwords on connection will be allowed.\n"
  110. " //\n"
  111. " // WARNING: If a \"login\" parameter is passed, someone sniffing on the wire can\n"
  112. " // sniff the packet and crack to find it. If the \"login\" is not passed\n"
  113. " // then the hash of the 'password' is effectively the login, therefore\n"
  114. " // that can be cracked.\n"
  115. " //\n"
  116. " \"authorizedPasswords\": [\n"
  117. " // Password is a unique string which is known to the client and server.\n"
  118. " // User is an optional login name and will also be used to display the peer.\n"
  119. " { \"password\": \"%s\", \"user\": \"default-login\" }\n", password);
  120. printf("\n"
  121. " // More passwords should look like this.\n"
  122. " // { \"password\": \"%s\", \"user\": \"my-second-peer\" },\n", password2);
  123. printf(" // { \"password\": \"%s\", \"user\": \"my-third-peer\" },\n", password3);
  124. printf(" // { \"password\": \"%s\", \"user\": \"my-fourth-peer\" },\n", password4);
  125. printf("\n"
  126. " // Below is an example of your connection credentials\n"
  127. " // that you can give to other people so they can connect\n"
  128. " // to you using your default password (from above).\n"
  129. " // The login field here yourself to your peer and the peerName field\n"
  130. " // is the name the peer which will be displayed in peerStats\n"
  131. " // Adding a unique password for each peer is advisable\n"
  132. " // so that leaks can be isolated.\n"
  133. " /*\n"
  134. " \"your.external.ip.goes.here:%u\": {\n", port);
  135. printf(" \"login\": \"default-login\",\n"
  136. " \"password\": \"%s\",\n", password);
  137. printf(" \"publicKey\": \"%s.k\",\n", publicKeyBase32);
  138. printf(" \"peerName\": \"your-name-goes-here\"\n"
  139. " },\n"
  140. " */\n");
  141. printf(" ],\n"
  142. "\n"
  143. " // Settings for administering and extracting information from your router.\n"
  144. " // This interface provides functions which can be called through a UDP socket.\n"
  145. " // See admin/Readme.md for more information about the API and try:\n"
  146. " // ./tools/cexec\n"
  147. " // For a list of functions which can be called.\n"
  148. " // For example: ./tools/cexec 'memory()'\n"
  149. " // will call a function which gets the core's current memory consumption.\n"
  150. " // ./tools/cjdnslog\n"
  151. " // is a tool which uses this admin interface to get logs from cjdns.\n"
  152. " \"admin\": {\n"
  153. " // Port to bind the admin RPC server to.\n"
  154. " \"bind\": \"127.0.0.1:11234\",\n"
  155. "\n"
  156. " // Password for admin RPC server.\n"
  157. " // This is a static password by default, so that tools like\n"
  158. " // ./tools/cexec can use the API without you creating a\n"
  159. " // config file at ~/.cjdnsadmin first. If you decide to\n"
  160. " // expose the admin API to the network, change the password!\n"
  161. " \"password\": \"NONE\"\n");
  162. printf(" },\n"
  163. "\n"
  164. " // Interfaces to connect to the switch core.\n"
  165. " \"interfaces\": {\n"
  166. " // The interface which connects over UDP/IP based VPN tunnel.\n"
  167. " \"UDPInterface\": [\n"
  168. " {\n"
  169. " // Bind to this port.\n"
  170. " \"bind\": \"0.0.0.0:%u\",\n", port);
  171. printf(" // Set the DSCP value for Qos. Default is 0.\n"
  172. " // \"dscp\": 46,\n"
  173. "\n"
  174. " // Automatically connect to other nodes on the same LAN\n"
  175. " // This works by binding a second port and sending beacons\n"
  176. " // containing the main data port.\n"
  177. " // beacon is a number between 0 and 2:\n"
  178. " // 0 -> do not beacon nor connect to other nodes who beacon\n"
  179. " // 1 -> quiet mode, accept beacons from other nodes only\n"
  180. " // 2 -> send and accept beacons\n"
  181. " // beaconDevices is a list which can contain names of devices such\n"
  182. " // as eth0, as well as broadcast addresses to send to, such as\n"
  183. " // 192.168.101.255, or the pseudo-name \"all\".\n"
  184. " // in order to auto-peer, all cjdns nodes must use the same\n"
  185. " // beaconPort.\n"
  186. " \"beacon\": 2,\n"
  187. " \"beaconDevices\": [ \"all\" ],\n"
  188. " \"beaconPort\": 64512,\n");
  189. printf("\n"
  190. " // Nodes to connect to (IPv4 only).\n"
  191. " \"connectTo\": {\n"
  192. " // Add connection credentials here to join the network\n"
  193. " // If you have several, don't forget the separating commas\n"
  194. " // They should look like:\n"
  195. " // \"ipv4 address:port\": {\n"
  196. " // \"login\": \"(optional) name your peer has for you\"\n"
  197. " // \"password\": \"password to connect with\",\n"
  198. " // \"publicKey\": \"remote node key.k\",\n"
  199. " // \"peerName\": \"(optional) human-readable name for peer\"\n"
  200. " // },\n"
  201. " // Ask somebody who is already connected.\n"
  202. " }\n"
  203. " },\n"
  204. " {\n"
  205. " // Bind to this port.\n"
  206. " \"bind\": \"[::]:%u\",\n", port);
  207. printf(" // Set the DSCP value for Qos. Default is 0.\n"
  208. " // \"dscp\": 46,\n");
  209. printf("\n"
  210. " // Nodes to connect to (IPv6 only).\n"
  211. " \"connectTo\": {\n"
  212. " // Add connection credentials here to join the network\n"
  213. " // Ask somebody who is already connected.\n"
  214. " }\n"
  215. " }\n"
  216. " ],\n\n");
  217. #ifdef HAS_ETH_INTERFACE
  218. printf(" // The interface which allows peering using layer-2 ethernet frames\n"
  219. " \"%sETHInterface\": [\n"
  220. " // Alternatively bind to just one device and either beacon and/or\n"
  221. " // connect to a specified MAC address\n"
  222. " {\n"
  223. " // Bind to this device (interface name, not MAC)\n"
  224. " // \"all\" is a pseudo-name which will try to connect to all devices.\n"
  225. " \"bind\": \"all\",\n"
  226. "\n"
  227. " // Auto-connect to other cjdns nodes on the same network.\n"
  228. " // Options:\n"
  229. " //\n"
  230. " // 0 -- Disabled.\n"
  231. " //\n"
  232. " // 1 -- Accept beacons, this will cause cjdns to accept incoming\n"
  233. " // beacon messages and try connecting to the sender.\n"
  234. " //\n"
  235. " // 2 -- Accept and send beacons, this will cause cjdns to broadcast\n"
  236. " // messages on the local network which contain a randomly\n"
  237. " // generated per-session password, other nodes which have this\n"
  238. " // set to 1 or 2 will hear the beacon messages and connect\n"
  239. " // automatically.\n"
  240. " //\n"
  241. " \"beacon\": 2,\n"
  242. "\n"
  243. " // Node(s) to connect to manually\n"
  244. " // Note: does not work with \"all\" pseudo-device-name\n"
  245. " \"connectTo\": {\n"
  246. " // Credentials for connecting look similar to UDP credentials\n"
  247. " // except they begin with the mac address, for example:\n"
  248. " // \"01:02:03:04:05:06\":{\"password\":\"a\",\"publicKey\":\"b\"}\n"
  249. " }\n"
  250. " }\n"
  251. " ]\n\n", (eth) ? "" : "_disabled_");
  252. #else
  253. printf(" ]\n");
  254. #endif
  255. printf(" },\n"
  256. "\n"
  257. " // Configuration for the router.\n"
  258. " \"router\": {\n"
  259. " // supernodes, if none are specified they'll be taken from your peers\n"
  260. " \"supernodes\": [\n"
  261. " //\"6743gf5tw80ExampleExampleExampleExamplevlyb23zfnuzv0.k\",\n"
  262. " ],\n"
  263. "\n"
  264. " // The interface which is used for connecting to the cjdns network.\n"
  265. " \"interface\": {\n"
  266. " // The type of interface (only TUNInterface is supported for now)\n"
  267. " \"type\": \"TUNInterface\"\n");
  268. #ifndef __APPLE__
  269. printf("\n"
  270. " // The name of a persistent TUN device to use.\n"
  271. " // This for starting cjdroute as its own user.\n"
  272. " // *MOST USERS DON'T NEED THIS*\n"
  273. " //\"tunDevice\": \"" DEFAULT_TUN_DEV "\"\n");
  274. #endif
  275. printf(" },\n"
  276. "\n"
  277. " // As an alternative to the TUN interface, you can create a socket interface\n"
  278. " // which will create a UNIX socket which emits packets that would otherwise\n"
  279. " // be sent through the TUN device.\n"
  280. " // To enable this interface, change the name of the above TUN interface to\n"
  281. " // \"_disabled_interface\" and change the name of this interface to\n"
  282. " // simply \"interface\"\n"
  283. " \"_disabled_interface\": {\n"
  284. " \"type\": \"SocketInterface\",\n"
  285. "\n"
  286. " // The filesystem path to the socket to create or connect to.\n"
  287. " \"socketFullPath\": \"/var/run/cjdns.sock\"\n"
  288. " },\n"
  289. "\n");
  290. printf(" // System for tunneling IPv4 and ICANN IPv6 through cjdns.\n"
  291. " // This is using the cjdns switch layer as a VPN carrier.\n"
  292. " \"ipTunnel\": {\n"
  293. " // Nodes allowed to connect to us.\n"
  294. " // When a node with the given public key connects, give them the\n"
  295. " // ip4 and/or ip6 addresses listed.\n"
  296. " \"allowedConnections\": [\n");
  297. printf(" // Give the client an address on 192.168.1.0/24, and an address\n"
  298. " // it thinks has all of IPv6 behind it.\n"
  299. " // ip4Prefix is the set of addresses which are routable from the tun\n"
  300. " // for example, if you're advertizing a VPN into a company network\n"
  301. " // which exists in 10.123.45.0/24 space, ip4Prefix should be 24\n"
  302. " // default is 32 for ipv4 and 128 for ipv6\n"
  303. " // so by default it will not install a route\n"
  304. " // ip4Alloc is the block of addresses which are allocated to the\n"
  305. " // for example if you want to issue 4 addresses to the client, those\n"
  306. " // being 192.168.123.0 to 192.168.123.3, you would set this to 30\n"
  307. " // default is 32 for ipv4 and 128 for ipv6 (1 address)\n"
  308. " // {\n"
  309. " // \"publicKey\": "
  310. "\"f64hfl7c4uxt6krmhPutTheRealAddressOfANodeHere7kfm5m0.k\",\n"
  311. " // \"ip4Address\": \"192.168.1.24\",\n"
  312. " // \"ip4Prefix\": 0,\n"
  313. " // \"ip4Alloc\": 32,\n"
  314. " // \"ip6Address\": \"2001:123:ab::10\",\n"
  315. " // \"ip6Prefix\": 0\n"
  316. " // \"ip6Alloc\": 64,\n"
  317. " // },\n"
  318. "\n"
  319. " // It's ok to only specify one address and prefix/alloc are optional.\n"
  320. " // {\n"
  321. " // \"publicKey\": "
  322. "\"ydq8csdk8p8ThisIsJustAnExampleAddresstxuyqdf27hvn2z0.k\",\n"
  323. " // \"ip4Address\": \"192.168.1.25\",\n"
  324. " // \"ip4Prefix\": 0,\n"
  325. " // }\n"
  326. " ],\n"
  327. "\n"
  328. " \"outgoingConnections\": [\n"
  329. " // Connect to one or more machines and ask them for IP addresses.\n"
  330. " // \"6743gf5tw80ExampleExampleExampleExamplevlyb23zfnuzv0.k\",\n"
  331. " // \"pw9tfmr8pcrExampleExampleExampleExample8rhg1pgwpwf80.k\",\n"
  332. " // \"g91lxyxhq0kExampleExampleExampleExample6t0mknuhw75l0.k\"\n"
  333. " ]\n"
  334. " }\n"
  335. " },\n"
  336. "\n");
  337. printf(" // Dropping permissions.\n"
  338. " // In the event of a serious security exploit in cjdns, leak of confidential\n"
  339. " // network traffic and/or keys is highly likely but the following rules are\n"
  340. " // designed to prevent the attack from spreading to the system on which cjdns\n"
  341. " // is running.\n"
  342. " // Counter-intuitively, cjdns is *more* secure if it is started as root because\n"
  343. " // non-root users do not have permission to use chroot or change usernames,\n"
  344. " // limiting the effectiveness of the mitigations herein.\n"
  345. " \"security\": [\n"
  346. " // Change the user id to sandbox the cjdns process after it starts.\n"
  347. " // If keepNetAdmin is set to 0, IPTunnel will be unable to set IP addresses\n"
  348. " // and ETHInterface will be unable to hot-add new interfaces\n"
  349. " // Use { \"setuser\": 0 } to disable.\n"
  350. " // Default: enabled with keepNetAdmin\n");
  351. if (Defined(android) || Defined(darwin)) {
  352. printf(" { \"setuser\": 0 },\n");
  353. } else {
  354. printf(" { \"setuser\": \"nobody\", \"keepNetAdmin\": 1 },\n");
  355. }
  356. printf("\n"
  357. " // Chroot changes the filesystem root directory which cjdns sees, blocking it\n"
  358. " // from accessing files outside of the chroot sandbox, if the user does not\n"
  359. " // have permission to use chroot(), this will fail quietly.\n"
  360. " // Use { \"chroot\": 0 } to disable.\n");
  361. if (Defined(android)) {
  362. printf(" // Default: disabled\n"
  363. " { \"chroot\": 0 },\n");
  364. }
  365. else {
  366. printf(" // Default: enabled (using \"/var/run\")\n"
  367. " { \"chroot\": \"/var/run/\" },\n");
  368. }
  369. printf("\n"
  370. " // Nofiles is a deprecated security feature which prevents cjdns from opening\n"
  371. " // any files at all, using this will block setting of IP addresses and\n"
  372. " // hot-adding ETHInterface devices but for users who do not need this, it\n"
  373. " // provides a formidable sandbox.\n"
  374. " // Default: disabled\n"
  375. " { \"nofiles\": 0 },\n"
  376. "\n"
  377. " // Noforks will prevent cjdns from spawning any new processes or threads,\n"
  378. " // this prevents many types of exploits from attacking the wider system.\n"
  379. " // Default: enabled\n"
  380. " { \"noforks\": 1 },\n"
  381. "\n"
  382. " // Seccomp is the most advanced sandboxing feature in cjdns, it uses\n"
  383. " // SECCOMP_BPF to filter the system calls which cjdns is able to make on a\n"
  384. " // linux system, strictly limiting it's access to the outside world\n"
  385. " // This will fail quietly on any non-linux system\n");
  386. if (Defined(android)) {
  387. printf(" // Default: disabled\n"
  388. " { \"seccomp\": 0 },\n");
  389. }
  390. else {
  391. printf(" // Default: enabled\n"
  392. " { \"seccomp\": 1 },\n");
  393. }
  394. printf("\n"
  395. " // The client sets up the core using a sequence of RPC calls, the responses\n"
  396. " // to these calls are verified but in the event that the client crashes\n"
  397. " // setup of the core completes, it could leave the core in an insecure state\n"
  398. " // This call constitutes the client telling the core that the security rules\n"
  399. " // have been fully applied and the core may run. Without it, the core will\n"
  400. " // exit within a few seconds with return code 232.\n"
  401. " // Default: enabled\n"
  402. " { \"setupComplete\": 1 }\n"
  403. " ],\n"
  404. "\n"
  405. " // Logging\n"
  406. " \"logging\": {\n"
  407. " // Uncomment to have cjdns log to stdout rather than making logs available\n"
  408. " // via the admin socket.\n"
  409. " // \"logTo\": \"stdout\"\n"
  410. " },\n"
  411. "\n"
  412. " // If set to non-zero, cjdns will not fork to the background.\n"
  413. " // Recommended for use in conjunction with \"logTo\":\"stdout\".\n");
  414. printf(" \"noBackground\": %d,\n", Defined(win32) ? 1 : 0);
  415. printf("\n"
  416. " // Path for admin control pipe:\n"
  417. " // If you pass only a filename then cjdns will guess the full path\n"
  418. " // On unix the default path is /tmp/\n"
  419. " // On windows: \\\\.\\pipe\\\n"
  420. " \"pipe\": \"cjdroute.sock\",\n");
  421. printf("\n"
  422. " // This is to make the configuration be parsed in strict mode, which allows\n"
  423. " // it to be edited externally using cjdnsconf.\n"
  424. " \"version\": 2\n");
  425. printf("}\n");
  426. return 0;
  427. }
  428. static int usage(struct Allocator* alloc, char* appName)
  429. {
  430. char* sysInfo = SysInfo_describe(SysInfo_detect(), alloc);
  431. printf("Cjdns %s %s\n"
  432. "Usage:\n"
  433. " cjdroute --help This information\n"
  434. " cjdroute --genconf [--eth] Generate a configuration file, write it to stdout\n"
  435. " if --eth is specified then eth beaconing will\n"
  436. " be enabled. Caution it can interfere with UDP\n"
  437. " beaconing\n"
  438. " cjdroute --genconf-seed [--eth] Generate a configuration file from a 64 byte seed\n"
  439. " which is read in from stdin."
  440. " cjdroute --bench Run some cryptography performance benchmarks.\n"
  441. " cjdroute --version Print the protocol version which this node speaks.\n"
  442. " cjdroute --cleanconf < conf Print a clean (valid json) version of the config.\n"
  443. " cjdroute --nobg Never fork to the background no matter the config.\n"
  444. "\n"
  445. "To get the router up and running.\n"
  446. "Step 1:\n"
  447. " Generate a new configuration file.\n"
  448. " cjdroute --genconf > cjdroute.conf\n"
  449. "\n"
  450. "Step 2:\n"
  451. " Find somebody to connect to.\n"
  452. " Check out the IRC channel #cjdns on Efnet and Freenode\n"
  453. " for information about how to meet new people and make connect to them.\n"
  454. " Read more here: https://github.com/cjdelisle/cjdns/#2-find-a-friend\n"
  455. "\n"
  456. "Step 3:\n"
  457. " Add that somebody's node to your cjdroute.conf file.\n"
  458. " https://github.com/cjdelisle/cjdns/#3-connect-your-node-to-your-friends-node\n"
  459. "\n"
  460. "Step 4:\n"
  461. " Fire it up!\n"
  462. " sudo cjdroute < cjdroute.conf\n"
  463. "\n"
  464. "For more information about other functions and non-standard setups, see README.md\n",
  465. ArchInfo_getArchStr(), sysInfo);
  466. return 0;
  467. }
  468. struct CheckRunningInstanceContext
  469. {
  470. struct EventBase* base;
  471. struct Allocator* alloc;
  472. struct AdminClient_Result* res;
  473. };
  474. static void checkRunningInstanceCallback(struct AdminClient_Promise* p,
  475. struct AdminClient_Result* res)
  476. {
  477. struct CheckRunningInstanceContext* ctx = p->userData;
  478. // Prevent this from freeing until after we drop out of the loop.
  479. Allocator_adopt(ctx->alloc, p->alloc);
  480. ctx->res = res;
  481. EventBase_endLoop(ctx->base);
  482. }
  483. static void checkRunningInstance(struct Allocator* allocator,
  484. struct EventBase* base,
  485. String* addr,
  486. String* password,
  487. struct Log* logger,
  488. struct Except* eh)
  489. {
  490. struct Allocator* alloc = Allocator_child(allocator);
  491. struct Sockaddr_storage pingAddrStorage;
  492. if (Sockaddr_parse(addr->bytes, &pingAddrStorage)) {
  493. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  494. addr->bytes);
  495. }
  496. struct UDPAddrIface* udp = Except_er(eh, UDPAddrIface_new(base, NULL, alloc, logger));
  497. struct AdminClient* adminClient =
  498. AdminClient_new(&udp->generic, &pingAddrStorage.addr, password, base, logger, alloc);
  499. // 100 milliseconds is plenty to wait for a process to respond on the same machine.
  500. adminClient->millisecondsToWait = 100;
  501. Dict* pingArgs = Dict_new(alloc);
  502. struct AdminClient_Promise* pingPromise =
  503. AdminClient_rpcCall(String_new("ping", alloc), pingArgs, adminClient, alloc);
  504. struct CheckRunningInstanceContext* ctx =
  505. Allocator_malloc(alloc, sizeof(struct CheckRunningInstanceContext));
  506. ctx->base = base;
  507. ctx->alloc = alloc;
  508. ctx->res = NULL;
  509. pingPromise->callback = checkRunningInstanceCallback;
  510. pingPromise->userData = ctx;
  511. EventBase_beginLoop(base);
  512. Assert_true(ctx->res);
  513. if (ctx->res->err != AdminClient_Error_TIMEOUT) {
  514. Except_throw(eh, "Startup failed: cjdroute is already running. [%d]", ctx->res->err);
  515. }
  516. Allocator_free(alloc);
  517. }
  518. static void onCoreExit(int64_t exit_status, int term_signal)
  519. {
  520. Assert_failure("Core exited with status [%d], signal [%d]\n", (int)exit_status, term_signal);
  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(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. int 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], "--bench") == 0) {
  594. Benchmark_runAll();
  595. return 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->bytes, confMsg->length, 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. char* args[] = { "core", pipePath->bytes, NULL };
  719. // --------------------- Spawn Core --------------------- //
  720. String* privateKey = Dict_getStringC(config, "privateKey");
  721. 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", toCoreMsg->length);
  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. }