cjdroute2.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/events/Socket.h"
  16. #define _POSIX_C_SOURCE 200112L
  17. #include "client/AdminClient.h"
  18. #include "admin/angel/Core.h"
  19. #include "admin/angel/InterfaceWaiter.h"
  20. #include "client/Configurator.h"
  21. #include "crypto/Key.h"
  22. #include "benc/Dict.h"
  23. #include "benc/Int.h"
  24. #include "benc/List.h"
  25. #include "benc/serialization/BencSerializer.h"
  26. #include "benc/serialization/json/JsonBencSerializer.h"
  27. #include "benc/serialization/json/JsonBencMessageReader.h"
  28. #include "benc/serialization/standard/BencMessageReader.h"
  29. #include "benc/serialization/standard/BencMessageWriter.h"
  30. #include "crypto/random/test/DeterminentRandomSeed.h"
  31. #include "crypto/AddressCalc.h"
  32. #include "crypto/Ca.h"
  33. #include "dht/Address.h"
  34. #include "exception/Except.h"
  35. #include "interface/Iface.h"
  36. #include "io/ArrayReader.h"
  37. #include "io/FileWriter.h"
  38. #include "io/Reader.h"
  39. #include "io/Writer.h"
  40. #include "memory/Allocator.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/libuv/Glock.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. printf("\n"
  381. " // The client sets up the core using a sequence of RPC calls, the responses\n"
  382. " // to these calls are verified but in the event that the client crashes\n"
  383. " // setup of the core completes, it could leave the core in an insecure state\n"
  384. " // This call constitutes the client telling the core that the security rules\n"
  385. " // have been fully applied and the core may run. Without it, the core will\n"
  386. " // exit within a few seconds with return code 232.\n"
  387. " // Default: enabled\n"
  388. " { \"setupComplete\": 1 }\n"
  389. " ],\n"
  390. "\n"
  391. " // Logging\n"
  392. " \"logging\": {\n"
  393. " // Uncomment to have cjdns log to stdout rather than making logs available\n"
  394. " // via the admin socket.\n"
  395. " // \"logTo\": \"stdout\"\n"
  396. " },\n"
  397. "\n"
  398. " // If set to non-zero, cjdns will not fork to the background.\n"
  399. " // Recommended for use in conjunction with \"logTo\":\"stdout\".\n");
  400. printf(" \"noBackground\": %d,\n", Defined(win32) ? 1 : 0);
  401. printf("\n"
  402. " // Path for admin control pipe:\n"
  403. " // If you pass only a filename then cjdns will guess the full path\n"
  404. " // On unix the default path is /tmp/\n"
  405. " // On windows: \\\\.\\pipe\\\n"
  406. " \"pipe\": \"cjdroute.sock\",\n");
  407. printf("\n"
  408. " // This is to make the configuration be parsed in strict mode, which allows\n"
  409. " // it to be edited externally using cjdnsconf.\n"
  410. " \"version\": 2\n");
  411. printf("}\n");
  412. return 0;
  413. }
  414. static int usage(struct Allocator* alloc, char* appName)
  415. {
  416. char* sysInfo = SysInfo_describe(SysInfo_detect(), alloc);
  417. printf("Cjdns %s %s\n"
  418. "Usage:\n"
  419. " cjdroute --help This information\n"
  420. " cjdroute --genconf [--eth] Generate a configuration file, write it to stdout\n"
  421. " if --eth is specified then eth beaconing will\n"
  422. " be enabled. Caution it can interfere with UDP\n"
  423. " beaconing\n"
  424. " cjdroute --genconf-seed [--eth] Generate a configuration file from a 64 byte seed\n"
  425. " which is read in from stdin."
  426. " cjdroute --version Print the protocol version which this node speaks.\n"
  427. " cjdroute --cleanconf < conf Print a clean (valid json) version of the config.\n"
  428. " cjdroute --nobg Never fork to the background no matter the config.\n"
  429. "\n"
  430. "To get the router up and running.\n"
  431. "Step 1:\n"
  432. " Generate a new configuration file.\n"
  433. " cjdroute --genconf > cjdroute.conf\n"
  434. "\n"
  435. "Step 2:\n"
  436. " Find somebody to connect to.\n"
  437. " Check out the IRC channel #cjdns on Efnet and Freenode\n"
  438. " for information about how to meet new people and make connect to them.\n"
  439. " Read more here: https://github.com/cjdelisle/cjdns/#2-find-a-friend\n"
  440. "\n"
  441. "Step 3:\n"
  442. " Add that somebody's node to your cjdroute.conf file.\n"
  443. " https://github.com/cjdelisle/cjdns/#3-connect-your-node-to-your-friends-node\n"
  444. "\n"
  445. "Step 4:\n"
  446. " Fire it up!\n"
  447. " sudo cjdroute < cjdroute.conf\n"
  448. "\n"
  449. "For more information about other functions and non-standard setups, see README.md\n",
  450. ArchInfo_getArchStr(), sysInfo);
  451. return 0;
  452. }
  453. struct CheckRunningInstanceContext
  454. {
  455. EventBase_t* base;
  456. struct Allocator* alloc;
  457. struct AdminClient_Result* res;
  458. };
  459. static void checkRunningInstanceCallback(struct AdminClient_Promise* p,
  460. struct AdminClient_Result* res)
  461. {
  462. struct CheckRunningInstanceContext* ctx = p->userData;
  463. // Prevent this from freeing until after we drop out of the loop.
  464. Allocator_adopt(ctx->alloc, p->alloc);
  465. ctx->res = res;
  466. EventBase_endLoop(ctx->base);
  467. }
  468. static void checkRunningInstance(struct Allocator* allocator,
  469. EventBase_t* base,
  470. String* addr,
  471. String* password,
  472. struct Log* logger,
  473. struct Except* eh)
  474. {
  475. struct Allocator* alloc = Allocator_child(allocator);
  476. struct Sockaddr_storage pingAddrStorage;
  477. if (Sockaddr_parse(addr->bytes, &pingAddrStorage)) {
  478. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  479. addr->bytes);
  480. }
  481. struct UDPAddrIface* udp = Except_er(eh, UDPAddrIface_new(base, NULL, alloc, logger));
  482. struct AdminClient* adminClient =
  483. AdminClient_new(&udp->generic, &pingAddrStorage.addr, password, base, logger, alloc);
  484. // 100 milliseconds is plenty to wait for a process to respond on the same machine.
  485. adminClient->millisecondsToWait = 100;
  486. Dict* pingArgs = Dict_new(alloc);
  487. // Indirection is needed otherwise adopt doesn't work
  488. struct Allocator* alloc1 = Allocator_child(alloc);
  489. struct AdminClient_Promise* pingPromise =
  490. AdminClient_rpcCall(String_new("ping", alloc), pingArgs, adminClient, alloc1);
  491. struct CheckRunningInstanceContext* ctx =
  492. Allocator_malloc(alloc, sizeof(struct CheckRunningInstanceContext));
  493. ctx->base = base;
  494. ctx->alloc = alloc;
  495. ctx->res = NULL;
  496. pingPromise->callback = checkRunningInstanceCallback;
  497. pingPromise->userData = ctx;
  498. EventBase_beginLoop(base);
  499. Assert_true(ctx->res);
  500. if (ctx->res->err != AdminClient_Error_TIMEOUT) {
  501. Except_throw(eh, "Startup failed: cjdroute is already running. [%d]", ctx->res->err);
  502. }
  503. Allocator_free(alloc);
  504. }
  505. static void onCoreExit(int64_t exit_status, int term_signal)
  506. {
  507. printf("Core exited with status [%d], signal [%d]\n", (int)exit_status, term_signal);
  508. exit(exit_status);
  509. }
  510. #define Chunk_MAX_LEN 4000
  511. struct Chunk {
  512. uint32_t length;
  513. struct Chunk* next;
  514. uint8_t buf[Chunk_MAX_LEN];
  515. };
  516. static Message_t* readToMsg(FILE* f, struct Allocator* alloc)
  517. {
  518. struct Allocator* child = Allocator_child(alloc);
  519. struct Chunk* c = NULL;
  520. uint32_t totalLength = 0;
  521. do {
  522. struct Chunk* cc = Allocator_calloc(child, sizeof(struct Chunk), 1);
  523. cc->length = fread(cc->buf, 1, Chunk_MAX_LEN, f);
  524. totalLength += cc->length;
  525. cc->next = c;
  526. c = cc;
  527. } while (c->length == Chunk_MAX_LEN);
  528. Message_t* out = Message_new(0, totalLength, alloc);
  529. while (c) {
  530. Er_assert(Message_epush(out, c->buf, c->length));
  531. c = c->next;
  532. }
  533. Allocator_free(child);
  534. return out;
  535. }
  536. static String* getPipePath(Dict* config, struct Allocator* alloc)
  537. {
  538. String* pipePath = Dict_getStringC(config, "pipe");
  539. char* pp = (pipePath) ? pipePath->bytes : "cjdroute.sock";
  540. if (pp[0] == Pipe_PATH_SEP[0]) {
  541. return pipePath;
  542. }
  543. char* path = Pipe_PATH;
  544. if (Defined(Cjdns_android)) {
  545. char* t = getenv("TMPDIR");
  546. if (!t) {
  547. t = getenv("HOME");
  548. }
  549. if (t) {
  550. path = t;
  551. }
  552. }
  553. String* out = String_newBinary(NULL,
  554. strlen(pp) + strlen(Pipe_PATH_SEP) + strlen(path) + 2, alloc);
  555. snprintf(out->bytes, out->len, "%s%s%s", path, Pipe_PATH_SEP, pp);
  556. out->len = strlen(out->bytes);
  557. return out;
  558. }
  559. // This is invoked from cjdroute.rs
  560. int cjdroute2_main(int argc, char** argv);
  561. int cjdroute2_main(int argc, char** argv)
  562. {
  563. Glock_init();
  564. #ifdef Log_KEYS
  565. fprintf(stderr, "Log_LEVEL = KEYS, EXPECT TO SEE PRIVATE KEYS IN YOUR LOGS!\n");
  566. #endif
  567. if (argc > 1 && (!CString_strcmp("angel", argv[1]) || !CString_strcmp("core", argv[1]))) {
  568. return Core_main(argc, argv);
  569. }
  570. Assert_ifParanoid(argc > 0);
  571. struct Except* eh = NULL;
  572. // Allow it to allocate 8MB
  573. struct Allocator* allocator = Allocator_new(1<<23);
  574. struct Random* rand = Random_new(allocator, NULL, eh);
  575. EventBase_t* eventBase = EventBase_new(allocator);
  576. if (argc == 2) {
  577. // one argument
  578. if ((CString_strcmp(argv[1], "--help") == 0) || (CString_strcmp(argv[1], "-h") == 0)) {
  579. return usage(allocator, argv[0]);
  580. } else if (CString_strcmp(argv[1], "--genconf-seed") == 0) {
  581. return genconf(allocator, rand, 0, 1);
  582. } else if (CString_strcmp(argv[1], "--genconf") == 0) {
  583. return genconf(allocator, rand, 0, 0);
  584. } else if ((CString_strcmp(argv[1], "--version") == 0)
  585. || (CString_strcmp(argv[1], "-v") == 0))
  586. {
  587. printf("Cjdns version: %s\n", CJD_PACKAGE_VERSION);
  588. printf("Cjdns protocol version: %d\n", Version_CURRENT_PROTOCOL);
  589. return 0;
  590. } else if (CString_strcmp(argv[1], "--cleanconf") == 0) {
  591. // Performed after reading configuration
  592. } else if (CString_strcmp(argv[1], "--nobg") == 0) {
  593. // Performed while reading configuration
  594. } else {
  595. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[1]);
  596. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  597. return -1;
  598. }
  599. } else if (argc > 2) {
  600. // more than one argument?
  601. // because of '--pidfile $filename'?
  602. if (CString_strcmp(argv[1], "--pidfile") == 0) {
  603. fprintf(stderr, "\n'--pidfile' option is deprecated.\n");
  604. } else if (CString_strcmp(argv[1], "--genconf") == 0 ||
  605. CString_strcmp(argv[1], "--genconf-seed") == 0)
  606. {
  607. bool eth = 0;
  608. for (int i = 2; i < argc; i++) {
  609. if (!CString_strcmp(argv[i], "--eth")) {
  610. eth = 1;
  611. } else {
  612. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[i]);
  613. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  614. return -1;
  615. }
  616. }
  617. return genconf(allocator, rand, eth, CString_strcmp(argv[1], "--genconf-seed") == 0);
  618. } else {
  619. fprintf(stderr, "%s: too many arguments [%s]\n", argv[0], argv[1]);
  620. fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
  621. }
  622. return -1;
  623. }
  624. if (isatty(STDIN_FILENO)) {
  625. // We were started from a terminal
  626. // The chances an user wants to type in a configuration
  627. // bij hand are pretty slim so we show him the usage
  628. return usage(allocator, argv[0]);
  629. } else {
  630. // We assume stdin is a configuration file and that we should
  631. // start routing
  632. }
  633. // First try reading the conf with the new parser, then try the old parser
  634. // and if the old parser fails or the parsed content contains "version": 2,
  635. // fail to launch
  636. Message_t* confMsg = readToMsg(stdin, allocator);
  637. struct Reader* confReader = ArrayReader_new(Message_bytes(confMsg), Message_getLength(confMsg), allocator);
  638. Dict _config;
  639. Dict* config = &_config;
  640. const char* err = JsonBencMessageReader_readNoExcept(confMsg, allocator, &config, false);
  641. if (!err) {
  642. // If old version is specified, always use old parser so there is no possible error
  643. int64_t* v = Dict_getIntC(config, "version");
  644. if (!v || *v < 2) { err = "using old parser"; }
  645. }
  646. if (err) {
  647. if (JsonBencSerializer_get()->parseDictionary(confReader, allocator, &_config)) {
  648. fprintf(stderr, "Failed to parse configuration.\n%s\n", err);
  649. return -1;
  650. }
  651. uint64_t* version = Dict_getIntC(config, "version");
  652. if (version && *version >= 2) {
  653. fprintf(stderr, "Invalid cjdroute.conf\n%s\n", err);
  654. return -1;
  655. }
  656. }
  657. if (argc == 2 && CString_strcmp(argv[1], "--cleanconf") == 0) {
  658. // Slip a v2 in there because at this point, the conf file is definitely v2 valid
  659. Dict_putIntC(config, "version", 2, allocator);
  660. struct Writer* stdoutWriter = FileWriter_new(stdout, allocator);
  661. JsonBencSerializer_get()->serializeDictionary(stdoutWriter, config);
  662. printf("\n");
  663. return 0;
  664. }
  665. int forceNoBackground = 0;
  666. if (argc == 2 && CString_strcmp(argv[1], "--nobg") == 0) {
  667. forceNoBackground = 1;
  668. }
  669. struct Log* logger = FileWriterLog_new(stdout, allocator);
  670. Rffi_setLogger(logger);
  671. // --------------------- Get Admin --------------------- //
  672. Dict* configAdmin = Dict_getDictC(config, "admin");
  673. String* adminPass = Dict_getStringC(configAdmin, "password");
  674. String* adminBind = Dict_getStringC(configAdmin, "bind");
  675. if (!adminPass) {
  676. adminPass = String_newBinary(NULL, 32, allocator);
  677. Random_base32(rand, (uint8_t*) adminPass->bytes, 32);
  678. adminPass->len = CString_strlen(adminPass->bytes);
  679. }
  680. if (!adminBind) {
  681. Except_throw(eh, "You must specify admin.bind in the cjdroute.conf file.");
  682. }
  683. // --------------------- Welcome to cjdns ---------------------- //
  684. char* sysInfo = SysInfo_describe(SysInfo_detect(), allocator);
  685. Log_info(logger, "%s %s %s", CJD_PACKAGE_VERSION, ArchInfo_getArchStr(), sysInfo);
  686. // --------------------- Check for running instance --------------------- //
  687. Log_info(logger, "Checking for running instance...");
  688. checkRunningInstance(allocator, eventBase, adminBind, adminPass, logger, eh);
  689. // --------------------- Setup Pipes to Angel --------------------- //
  690. struct Allocator* corePipeAlloc = Allocator_child(allocator);
  691. String* pipePath = getPipePath(config, corePipeAlloc);
  692. if (!Defined(win32)) {
  693. // win32 sockets are not files
  694. char* lastsep = strrchr(pipePath->bytes, '/');
  695. Assert_true(lastsep);
  696. *lastsep = '\0';
  697. int ret = access(pipePath->bytes, W_OK);
  698. *lastsep = '/';
  699. if (ret) {
  700. Except_throw(eh, "Pipe directory not writable: [%s]", pipePath->bytes);
  701. }
  702. if (unlink(pipePath->bytes) && (errno != ENOENT)) {
  703. Except_throw(eh, "Unable to delete existing pipe at path [%s] err [%s]",
  704. pipePath->bytes, strerror(errno));
  705. }
  706. }
  707. const char* args[] = { "core", pipePath->bytes, NULL };
  708. // --------------------- Spawn Core --------------------- //
  709. String* privateKey = Dict_getStringC(config, "privateKey");
  710. const char* corePath = Process_getPath(allocator);
  711. if (!corePath) {
  712. Except_throw(eh, "Can't find a usable cjdns core executable, "
  713. "make sure it is in the same directory as cjdroute");
  714. }
  715. if (!privateKey) {
  716. Except_throw(eh, "Need to specify privateKey.");
  717. }
  718. Process_spawn(corePath, args, allocator, onCoreExit);
  719. // --------------------- Wait for socket ------------------------- //
  720. // cycle for up to 1 minute
  721. int exists = 0;
  722. for (int i = 0; i < 2 * 10 * 60; i++) {
  723. if (Except_er(eh, Socket_fileExists(pipePath->bytes, allocator))) {
  724. exists = 1;
  725. break;
  726. }
  727. // sleep 50ms
  728. Rffi_sleep_ms_sync(50);
  729. }
  730. if (!exists) {
  731. Except_throw(eh, "Core did not setup pipe file [%s] within 60 seconds",
  732. pipePath->bytes);
  733. }
  734. // --------------------- Connect to socket ------------------------- //
  735. Iface_t* corePipe = Except_er(eh, Socket_connect(pipePath->bytes, allocator));
  736. // --------------------- Pre-Configure Core ------------------------- //
  737. Dict* preConf = Dict_new(allocator);
  738. Dict* adminPreConf = Dict_new(allocator);
  739. Dict_putDictC(preConf, "admin", adminPreConf, allocator);
  740. Dict_putStringC(preConf, "privateKey", privateKey, allocator);
  741. Dict_putStringC(adminPreConf, "bind", adminBind, allocator);
  742. Dict_putStringC(adminPreConf, "pass", adminPass, allocator);
  743. Dict* logging = Dict_getDictC(config, "logging");
  744. if (logging) {
  745. Dict_putDictC(preConf, "logging", logging, allocator);
  746. }
  747. Message_t* toCoreMsg = Message_new(0, 1024, allocator);
  748. Er_assert(BencMessageWriter_write(preConf, toCoreMsg));
  749. Iface_CALL(corePipe->send, toCoreMsg, corePipe);
  750. Log_debug(logger, "Sent [%d] bytes to core", Message_getLength(toCoreMsg));
  751. // --------------------- Get Response from Core --------------------- //
  752. Message_t* fromCoreMsg =
  753. InterfaceWaiter_waitForData(corePipe, eventBase, allocator, eh);
  754. Dict* responseFromCore = Except_er(eh, BencMessageReader_read(fromCoreMsg, allocator));
  755. // --------------------- Close the Core Pipe --------------------- //
  756. Allocator_free(corePipeAlloc);
  757. corePipe = NULL;
  758. // --------------------- Get Admin Addr/Port/Passwd --------------------- //
  759. Dict* responseFromCoreAdmin = Dict_getDictC(responseFromCore, "admin");
  760. adminBind = Dict_getStringC(responseFromCoreAdmin, "bind");
  761. if (!adminBind) {
  762. Except_throw(eh, "didn't get address and port back from core");
  763. }
  764. struct Sockaddr_storage adminAddr;
  765. if (Sockaddr_parse(adminBind->bytes, &adminAddr)) {
  766. Except_throw(eh, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
  767. adminBind->bytes);
  768. }
  769. //Assert_ifParanoid(EventBase_eventCount(eventBase) == 1);
  770. // --------------------- Configuration ------------------------- //
  771. Configurator_config(config,
  772. &adminAddr.addr,
  773. adminPass,
  774. eventBase,
  775. logger,
  776. allocator);
  777. // --------------------- noBackground ------------------------ //
  778. int64_t* noBackground = Dict_getIntC(config, "noBackground");
  779. if (forceNoBackground || (noBackground && *noBackground)) {
  780. Log_debug(logger, "Keeping cjdns client alive because %s",
  781. (forceNoBackground) ? "--nobg was specified on the command line"
  782. : "noBackground was set in the configuration");
  783. EventBase_beginLoop(eventBase);
  784. }
  785. // Freeing this allocator here causes the core to be terminated in the epoll syscall.
  786. //Allocator_free(allocator);
  787. return 0;
  788. }