main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <time.h>
  31. #include <errno.h>
  32. #include <string>
  33. #include <stdexcept>
  34. #include "node/Constants.hpp"
  35. #ifdef __WINDOWS__
  36. #include <WinSock2.h>
  37. #include <Windows.h>
  38. #include <tchar.h>
  39. #include <wchar.h>
  40. #else
  41. #include <unistd.h>
  42. #include <pwd.h>
  43. #include <fcntl.h>
  44. #include <sys/types.h>
  45. #include <sys/stat.h>
  46. #include <signal.h>
  47. #endif
  48. #include "node/Constants.hpp"
  49. #include "node/Defaults.hpp"
  50. #include "node/Utils.hpp"
  51. #include "node/Node.hpp"
  52. #include "node/Condition.hpp"
  53. #include "node/C25519.hpp"
  54. #include "node/Identity.hpp"
  55. using namespace ZeroTier;
  56. static Node *node = (Node *)0;
  57. static void printHelp(const char *cn,FILE *out)
  58. {
  59. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2012-2013 ZeroTier Networks LLC"ZT_EOL_S,Node::versionMajor(),Node::versionMinor(),Node::versionRevision());
  60. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  61. #ifdef ZT_AUTO_UPDATE
  62. fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
  63. fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  64. fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
  65. int no = 0;
  66. for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
  67. if (no == 0)
  68. fprintf(out," %s",sa->first.toString().c_str());
  69. else fprintf(out,", %s",sa->first.toString().c_str());
  70. if (++no == 6) {
  71. fprintf(out,ZT_EOL_S);
  72. no = 0;
  73. }
  74. }
  75. fprintf(out,ZT_EOL_S""ZT_EOL_S);
  76. #else
  77. fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
  78. #endif
  79. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  80. fprintf(out,"Available switches:"ZT_EOL_S);
  81. fprintf(out," -h - Display this help"ZT_EOL_S);
  82. fprintf(out," -v - Show version"ZT_EOL_S);
  83. fprintf(out," -p<port> - Bind to this port for network I/O"ZT_EOL_S);
  84. fprintf(out," -c<port> - Bind to this port for local control packets"ZT_EOL_S);
  85. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  86. fprintf(out," -i - Run idtool command (zerotier-idtool)"ZT_EOL_S);
  87. }
  88. namespace ZeroTierCLI { // ---------------------------------------------------
  89. static void printHelp(FILE *out,const char *exename)
  90. {
  91. fprintf(out,"Usage: %s [-switches] <command>"ZT_EOL_S,exename);
  92. fprintf(out,ZT_EOL_S);
  93. fprintf(out,"Available switches:"ZT_EOL_S);
  94. fprintf(out," -c<port> - Communicate with daemon over this local port"ZT_EOL_S);
  95. fprintf(out," -t<token> - Specify token on command line"ZT_EOL_S);
  96. fprintf(out," -T<file> - Read token from file"ZT_EOL_S);
  97. fprintf(out,ZT_EOL_S);
  98. fprintf(out,"Use the 'help' command to get help from ZeroTier One itself."ZT_EOL_S);
  99. }
  100. static volatile unsigned int numResults = 0;
  101. static Condition doneCondition;
  102. static void resultHandler(void *arg,unsigned long id,const char *line)
  103. {
  104. ++numResults;
  105. if (strlen(line))
  106. fprintf(stdout,"%s"ZT_EOL_S,line);
  107. else doneCondition.signal();
  108. }
  109. // Runs instead of rest of main() if process is called zerotier-cli or if
  110. // -q is specified as an option.
  111. #ifdef __WINDOWS__
  112. static int main(int argc,_TCHAR* argv[])
  113. #else
  114. static int main(int argc,char **argv)
  115. #endif
  116. {
  117. if (argc <= 1) {
  118. printHelp(stdout,argv[0]);
  119. return -1;
  120. }
  121. std::string authToken;
  122. std::string command;
  123. bool pastSwitches = false;
  124. unsigned int controlPort = 0;
  125. for(int i=1;i<argc;++i) {
  126. if ((argv[i][0] == '-')&&(!pastSwitches)) {
  127. if (strlen(argv[i]) <= 1) {
  128. printHelp(stdout,argv[0]);
  129. return -1;
  130. }
  131. switch(argv[i][1]) {
  132. case 'q': // does nothing, for invocation without binary path name aliasing
  133. if (argv[i][2]) {
  134. printHelp(argv[0],stderr);
  135. return 0;
  136. }
  137. break;
  138. case 'c':
  139. controlPort = Utils::strToUInt(argv[i] + 2);
  140. break;
  141. case 't':
  142. authToken.assign(argv[i] + 2);
  143. break;
  144. case 'T':
  145. if (!Utils::readFile(argv[i] + 2,authToken)) {
  146. fprintf(stdout,"FATAL ERROR: unable to read token from '%s'"ZT_EOL_S,argv[i] + 2);
  147. return -2;
  148. }
  149. break;
  150. default:
  151. return -1;
  152. }
  153. } else {
  154. pastSwitches = true;
  155. if (command.length())
  156. command.push_back(' ');
  157. command.append(argv[i]);
  158. }
  159. }
  160. if (!command.length()) {
  161. printHelp(stdout,argv[0]);
  162. return -1;
  163. }
  164. if (!authToken.length()) {
  165. const char *home = getenv("HOME");
  166. if (home) {
  167. std::string dotZeroTierAuthToken(home);
  168. dotZeroTierAuthToken.push_back(ZT_PATH_SEPARATOR);
  169. dotZeroTierAuthToken.append(".zerotierOneAuthToken");
  170. if (!Utils::readFile(dotZeroTierAuthToken.c_str(),authToken)) {
  171. #ifndef __WINDOWS__
  172. #ifdef __APPLE__
  173. const char *systemAuthTokenPath = "/Library/Application Support/ZeroTier/One/authtoken.secret";
  174. #else
  175. const char *systemAuthTokenPath = "/var/lib/zerotier-one/authtoken.secret";
  176. #endif
  177. if (!Utils::readFile(systemAuthTokenPath,authToken)) {
  178. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s' or '%s'"ZT_EOL_S,dotZeroTierAuthToken.c_str(),systemAuthTokenPath);
  179. return -2;
  180. }
  181. #else // __WINDOWS__
  182. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s'"ZT_EOL_S,dotZeroTierAuthToken.c_str());
  183. return -2;
  184. #endif // __WINDOWS__
  185. }
  186. }
  187. }
  188. if (!authToken.length()) {
  189. fprintf(stdout,"FATAL ERROR: could not find auth token"ZT_EOL_S);
  190. return -2;
  191. }
  192. Node::LocalClient client(authToken.c_str(),controlPort,&resultHandler,(void *)0);
  193. client.send(command.c_str());
  194. doneCondition.wait(1000);
  195. if (!numResults) {
  196. fprintf(stdout,"ERROR: no results received. Is ZeroTier One running?"ZT_EOL_S);
  197. return -1;
  198. }
  199. return 0;
  200. }
  201. } // namespace ZeroTierCLI ---------------------------------------------------
  202. namespace ZeroTierIdTool { // ------------------------------------------------
  203. static void printHelp(FILE *out,const char *pn)
  204. {
  205. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  206. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  207. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  208. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  209. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  210. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  211. }
  212. static Identity getIdFromArg(char *arg)
  213. {
  214. Identity id;
  215. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  216. if (id.fromString(arg))
  217. return id;
  218. } else { // identity is to be read from a file
  219. std::string idser;
  220. if (Utils::readFile(arg,idser)) {
  221. if (id.fromString(idser))
  222. return id;
  223. }
  224. }
  225. return Identity();
  226. }
  227. // Runs instead of rest of main() if process is called zerotier-idtool or if
  228. // -i is specified as an option.
  229. #ifdef __WINDOWS__
  230. static int main(int argc,_TCHAR* argv[])
  231. #else
  232. static int main(int argc,char **argv)
  233. #endif
  234. {
  235. if (argc < 2) {
  236. printHelp(stderr,argv[0]);
  237. return -1;
  238. }
  239. if (!strcmp(argv[1],"generate")) {
  240. Identity id;
  241. id.generate();
  242. std::string idser = id.toString(true);
  243. if (argc >= 3) {
  244. if (!Utils::writeFile(argv[2],idser)) {
  245. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  246. return -1;
  247. } else printf("%s written"ZT_EOL_S,argv[2]);
  248. if (argc >= 4) {
  249. idser = id.toString(false);
  250. if (!Utils::writeFile(argv[3],idser)) {
  251. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  252. return -1;
  253. } else printf("%s written"ZT_EOL_S,argv[3]);
  254. }
  255. } else printf("%s",idser.c_str());
  256. } else if (!strcmp(argv[1],"validate")) {
  257. if (argc < 3) {
  258. printHelp(stderr,argv[0]);
  259. return -1;
  260. }
  261. Identity id = getIdFromArg(argv[2]);
  262. if (!id) {
  263. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  264. return -1;
  265. }
  266. if (!id.locallyValidate()) {
  267. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  268. return -1;
  269. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  270. } else if (!strcmp(argv[1],"getpublic")) {
  271. if (argc < 3) {
  272. printHelp(stderr,argv[0]);
  273. return -1;
  274. }
  275. Identity id = getIdFromArg(argv[2]);
  276. if (!id) {
  277. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  278. return -1;
  279. }
  280. printf("%s",id.toString(false).c_str());
  281. } else if (!strcmp(argv[1],"sign")) {
  282. if (argc < 4) {
  283. printHelp(stderr,argv[0]);
  284. return -1;
  285. }
  286. Identity id = getIdFromArg(argv[2]);
  287. if (!id) {
  288. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  289. return -1;
  290. }
  291. if (!id.hasPrivate()) {
  292. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  293. return -1;
  294. }
  295. std::string inf;
  296. if (!Utils::readFile(argv[3],inf)) {
  297. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  298. return -1;
  299. }
  300. C25519::Signature signature = id.sign(inf.data(),inf.length());
  301. printf("%s",Utils::hex(signature.data,signature.size()).c_str());
  302. } else if (!strcmp(argv[1],"verify")) {
  303. if (argc < 4) {
  304. printHelp(stderr,argv[0]);
  305. return -1;
  306. }
  307. Identity id = getIdFromArg(argv[2]);
  308. if (!id) {
  309. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  310. return -1;
  311. }
  312. std::string inf;
  313. if (!Utils::readFile(argv[3],inf)) {
  314. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  315. return -1;
  316. }
  317. std::string signature(Utils::unhex(argv[4]));
  318. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),inf.length(),signature.data(),signature.length()))) {
  319. printf("%s signature valid"ZT_EOL_S,argv[3]);
  320. } else {
  321. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  322. return -1;
  323. }
  324. } else {
  325. printHelp(stderr,argv[0]);
  326. return -1;
  327. }
  328. return 0;
  329. }
  330. } // namespace ZeroTierIdTool ------------------------------------------------
  331. #ifdef __UNIX_LIKE__
  332. static void sighandlerQuit(int sig)
  333. {
  334. Node *n = node;
  335. if (n)
  336. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  337. else exit(0);
  338. }
  339. #endif
  340. #ifdef __WINDOWS__
  341. static BOOL WINAPI _handlerRoutine(DWORD dwCtrlType)
  342. {
  343. switch(dwCtrlType) {
  344. case CTRL_C_EVENT:
  345. case CTRL_BREAK_EVENT:
  346. case CTRL_CLOSE_EVENT:
  347. case CTRL_SHUTDOWN_EVENT:
  348. Node *n = node;
  349. if (n)
  350. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  351. return TRUE;
  352. }
  353. return FALSE;
  354. }
  355. #endif
  356. #ifdef __WINDOWS__
  357. int _tmain(int argc, _TCHAR* argv[])
  358. #else
  359. int main(int argc,char **argv)
  360. #endif
  361. {
  362. #ifdef __UNIX_LIKE__
  363. signal(SIGHUP,SIG_IGN);
  364. signal(SIGPIPE,SIG_IGN);
  365. signal(SIGUSR1,SIG_IGN);
  366. signal(SIGUSR2,SIG_IGN);
  367. signal(SIGALRM,SIG_IGN);
  368. signal(SIGINT,&sighandlerQuit);
  369. signal(SIGTERM,&sighandlerQuit);
  370. signal(SIGQUIT,&sighandlerQuit);
  371. #endif
  372. #ifdef __WINDOWS__
  373. WSADATA wsaData;
  374. WSAStartup(MAKEWORD(2,2),&wsaData);
  375. SetConsoleCtrlHandler(&_handlerRoutine,TRUE);
  376. #endif
  377. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  378. return ZeroTierCLI::main(argc,argv);
  379. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  380. return ZeroTierIdTool::main(argc,argv);
  381. const char *homeDir = (const char *)0;
  382. unsigned int port = 0;
  383. unsigned int controlPort = 0;
  384. for(int i=1;i<argc;++i) {
  385. if (argv[i][0] == '-') {
  386. switch(argv[i][1]) {
  387. case 'p':
  388. port = Utils::strToUInt(argv[i] + 2);
  389. if (port > 65535) {
  390. printHelp(argv[0],stderr);
  391. return 1;
  392. }
  393. break;
  394. case 'v':
  395. printf("%s"ZT_EOL_S,Node::versionString());
  396. return 0;
  397. case 'c':
  398. controlPort = Utils::strToUInt(argv[i] + 2);
  399. if (controlPort > 65535) {
  400. printHelp(argv[0],stderr);
  401. return 1;
  402. }
  403. break;
  404. case 'q':
  405. if (argv[i][2]) {
  406. printHelp(argv[0],stderr);
  407. return 0;
  408. } else return ZeroTierCLI::main(argc,argv);
  409. case 'i':
  410. if (argv[i][2]) {
  411. printHelp(argv[0],stderr);
  412. return 0;
  413. } else return ZeroTierIdTool::main(argc,argv);
  414. case 'h':
  415. case '?':
  416. default:
  417. printHelp(argv[0],stderr);
  418. return 0;
  419. }
  420. } else {
  421. if (homeDir) {
  422. printHelp(argv[0],stderr);
  423. return 0;
  424. }
  425. homeDir = argv[i];
  426. break;
  427. }
  428. }
  429. if ((!homeDir)||(strlen(homeDir) == 0))
  430. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  431. #ifdef __UNIX_LIKE__
  432. if (getuid()) {
  433. fprintf(stderr,"%s: must be run as root (uid==0)\n",argv[0]);
  434. return 1;
  435. }
  436. mkdir(homeDir,0755); // will fail if it already exists
  437. {
  438. char pidpath[4096];
  439. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  440. FILE *pf = fopen(pidpath,"w");
  441. if (pf) {
  442. fprintf(pf,"%ld",(long)getpid());
  443. fclose(pf);
  444. }
  445. }
  446. #endif
  447. int exitCode = 0;
  448. try {
  449. node = new Node(homeDir,port,controlPort);
  450. switch(node->run()) {
  451. case Node::NODE_RESTART_FOR_UPGRADE: {
  452. #ifdef __UNIX_LIKE__
  453. const char *upgPath = node->reasonForTermination();
  454. if (upgPath)
  455. execl(upgPath,upgPath,"-s",(char *)0); // -s = (re)start after install/upgrade
  456. exitCode = 2;
  457. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  458. #endif
  459. } break;
  460. case Node::NODE_UNRECOVERABLE_ERROR: {
  461. exitCode = 3;
  462. const char *termReason = node->reasonForTermination();
  463. fprintf(stderr,"%s: abnormal termination: %s\n",argv[0],(termReason) ? termReason : "(unknown reason)");
  464. } break;
  465. default:
  466. break;
  467. }
  468. delete node;
  469. node = (Node *)0;
  470. } catch ( ... ) {}
  471. #ifdef __UNIX_LIKE__
  472. {
  473. char pidpath[4096];
  474. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  475. Utils::rm(pidpath);
  476. }
  477. #endif
  478. return exitCode;
  479. }