main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. case 'h':
  151. printHelp(stdout,argv[0]);
  152. return 0;
  153. default:
  154. return -1;
  155. }
  156. } else {
  157. pastSwitches = true;
  158. if (command.length())
  159. command.push_back(' ');
  160. command.append(argv[i]);
  161. }
  162. }
  163. if (!command.length()) {
  164. printHelp(stdout,argv[0]);
  165. return -1;
  166. }
  167. if (!authToken.length()) {
  168. if (!Utils::readFile(Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  169. if (!Utils::readFile(Node::LocalClient::authTokenDefaultSystemPath().c_str(),authToken)) {
  170. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s' or '%s'"ZT_EOL_S,Node::LocalClient::authTokenDefaultSystemPath().c_str(),Node::LocalClient::authTokenDefaultUserPath().c_str());
  171. return -2;
  172. }
  173. }
  174. }
  175. if (!authToken.length()) {
  176. fprintf(stdout,"FATAL ERROR: could not find auth token"ZT_EOL_S);
  177. return -2;
  178. }
  179. Node::LocalClient client(authToken.c_str(),controlPort,&resultHandler,(void *)0);
  180. client.send(command.c_str());
  181. doneCondition.wait(1000);
  182. if (!numResults) {
  183. fprintf(stdout,"ERROR: no results received. Is ZeroTier One running?"ZT_EOL_S);
  184. return -1;
  185. }
  186. return 0;
  187. }
  188. } // namespace ZeroTierCLI ---------------------------------------------------
  189. namespace ZeroTierIdTool { // ------------------------------------------------
  190. static void printHelp(FILE *out,const char *pn)
  191. {
  192. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  193. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  194. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  195. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  196. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  197. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  198. }
  199. static Identity getIdFromArg(char *arg)
  200. {
  201. Identity id;
  202. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  203. if (id.fromString(arg))
  204. return id;
  205. } else { // identity is to be read from a file
  206. std::string idser;
  207. if (Utils::readFile(arg,idser)) {
  208. if (id.fromString(idser))
  209. return id;
  210. }
  211. }
  212. return Identity();
  213. }
  214. // Runs instead of rest of main() if process is called zerotier-idtool or if
  215. // -i is specified as an option.
  216. #ifdef __WINDOWS__
  217. static int main(int argc,_TCHAR* argv[])
  218. #else
  219. static int main(int argc,char **argv)
  220. #endif
  221. {
  222. if (argc < 2) {
  223. printHelp(stderr,argv[0]);
  224. return -1;
  225. }
  226. if (!strcmp(argv[1],"generate")) {
  227. Identity id;
  228. id.generate();
  229. std::string idser = id.toString(true);
  230. if (argc >= 3) {
  231. if (!Utils::writeFile(argv[2],idser)) {
  232. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  233. return -1;
  234. } else printf("%s written"ZT_EOL_S,argv[2]);
  235. if (argc >= 4) {
  236. idser = id.toString(false);
  237. if (!Utils::writeFile(argv[3],idser)) {
  238. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  239. return -1;
  240. } else printf("%s written"ZT_EOL_S,argv[3]);
  241. }
  242. } else printf("%s",idser.c_str());
  243. } else if (!strcmp(argv[1],"validate")) {
  244. if (argc < 3) {
  245. printHelp(stderr,argv[0]);
  246. return -1;
  247. }
  248. Identity id = getIdFromArg(argv[2]);
  249. if (!id) {
  250. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  251. return -1;
  252. }
  253. if (!id.locallyValidate()) {
  254. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  255. return -1;
  256. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  257. } else if (!strcmp(argv[1],"getpublic")) {
  258. if (argc < 3) {
  259. printHelp(stderr,argv[0]);
  260. return -1;
  261. }
  262. Identity id = getIdFromArg(argv[2]);
  263. if (!id) {
  264. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  265. return -1;
  266. }
  267. printf("%s",id.toString(false).c_str());
  268. } else if (!strcmp(argv[1],"sign")) {
  269. if (argc < 4) {
  270. printHelp(stderr,argv[0]);
  271. return -1;
  272. }
  273. Identity id = getIdFromArg(argv[2]);
  274. if (!id) {
  275. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  276. return -1;
  277. }
  278. if (!id.hasPrivate()) {
  279. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  280. return -1;
  281. }
  282. std::string inf;
  283. if (!Utils::readFile(argv[3],inf)) {
  284. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  285. return -1;
  286. }
  287. C25519::Signature signature = id.sign(inf.data(),inf.length());
  288. printf("%s",Utils::hex(signature.data,signature.size()).c_str());
  289. } else if (!strcmp(argv[1],"verify")) {
  290. if (argc < 4) {
  291. printHelp(stderr,argv[0]);
  292. return -1;
  293. }
  294. Identity id = getIdFromArg(argv[2]);
  295. if (!id) {
  296. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  297. return -1;
  298. }
  299. std::string inf;
  300. if (!Utils::readFile(argv[3],inf)) {
  301. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  302. return -1;
  303. }
  304. std::string signature(Utils::unhex(argv[4]));
  305. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),inf.length(),signature.data(),signature.length()))) {
  306. printf("%s signature valid"ZT_EOL_S,argv[3]);
  307. } else {
  308. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  309. return -1;
  310. }
  311. } else {
  312. printHelp(stderr,argv[0]);
  313. return -1;
  314. }
  315. return 0;
  316. }
  317. } // namespace ZeroTierIdTool ------------------------------------------------
  318. #ifdef __UNIX_LIKE__
  319. static void sighandlerQuit(int sig)
  320. {
  321. Node *n = node;
  322. if (n)
  323. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  324. else exit(0);
  325. }
  326. #endif
  327. #ifdef __WINDOWS__
  328. static BOOL WINAPI _handlerRoutine(DWORD dwCtrlType)
  329. {
  330. switch(dwCtrlType) {
  331. case CTRL_C_EVENT:
  332. case CTRL_BREAK_EVENT:
  333. case CTRL_CLOSE_EVENT:
  334. case CTRL_SHUTDOWN_EVENT:
  335. Node *n = node;
  336. if (n)
  337. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  338. return TRUE;
  339. }
  340. return FALSE;
  341. }
  342. #endif
  343. #ifdef __WINDOWS__
  344. int _tmain(int argc, _TCHAR* argv[])
  345. #else
  346. int main(int argc,char **argv)
  347. #endif
  348. {
  349. #ifdef __UNIX_LIKE__
  350. signal(SIGHUP,SIG_IGN);
  351. signal(SIGPIPE,SIG_IGN);
  352. signal(SIGUSR1,SIG_IGN);
  353. signal(SIGUSR2,SIG_IGN);
  354. signal(SIGALRM,SIG_IGN);
  355. signal(SIGINT,&sighandlerQuit);
  356. signal(SIGTERM,&sighandlerQuit);
  357. signal(SIGQUIT,&sighandlerQuit);
  358. #endif
  359. #ifdef __WINDOWS__
  360. WSADATA wsaData;
  361. WSAStartup(MAKEWORD(2,2),&wsaData);
  362. SetConsoleCtrlHandler(&_handlerRoutine,TRUE);
  363. #endif
  364. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  365. return ZeroTierCLI::main(argc,argv);
  366. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  367. return ZeroTierIdTool::main(argc,argv);
  368. const char *homeDir = (const char *)0;
  369. unsigned int port = 0;
  370. unsigned int controlPort = 0;
  371. for(int i=1;i<argc;++i) {
  372. if (argv[i][0] == '-') {
  373. switch(argv[i][1]) {
  374. case 'p':
  375. port = Utils::strToUInt(argv[i] + 2);
  376. if (port > 65535) {
  377. printHelp(argv[0],stderr);
  378. return 1;
  379. }
  380. break;
  381. case 'v':
  382. printf("%s"ZT_EOL_S,Node::versionString());
  383. return 0;
  384. case 'c':
  385. controlPort = Utils::strToUInt(argv[i] + 2);
  386. if (controlPort > 65535) {
  387. printHelp(argv[0],stderr);
  388. return 1;
  389. }
  390. break;
  391. case 'q':
  392. if (argv[i][2]) {
  393. printHelp(argv[0],stderr);
  394. return 0;
  395. } else return ZeroTierCLI::main(argc,argv);
  396. case 'i':
  397. if (argv[i][2]) {
  398. printHelp(argv[0],stderr);
  399. return 0;
  400. } else return ZeroTierIdTool::main(argc,argv);
  401. case 'h':
  402. case '?':
  403. default:
  404. printHelp(argv[0],stderr);
  405. return 0;
  406. }
  407. } else {
  408. if (homeDir) {
  409. printHelp(argv[0],stderr);
  410. return 0;
  411. }
  412. homeDir = argv[i];
  413. break;
  414. }
  415. }
  416. if ((!homeDir)||(strlen(homeDir) == 0))
  417. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  418. #ifdef __UNIX_LIKE__
  419. if (getuid()) {
  420. fprintf(stderr,"%s: must be run as root (uid==0)\n",argv[0]);
  421. return 1;
  422. }
  423. mkdir(homeDir,0755); // will fail if it already exists
  424. {
  425. char pidpath[4096];
  426. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  427. FILE *pf = fopen(pidpath,"w");
  428. if (pf) {
  429. fprintf(pf,"%ld",(long)getpid());
  430. fclose(pf);
  431. }
  432. }
  433. #endif
  434. int exitCode = 0;
  435. try {
  436. node = new Node(homeDir,port,controlPort);
  437. switch(node->run()) {
  438. case Node::NODE_RESTART_FOR_UPGRADE: {
  439. #ifdef __UNIX_LIKE__
  440. const char *upgPath = node->reasonForTermination();
  441. if (upgPath) {
  442. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  443. execl(upgPath,upgPath,(char *)0);
  444. }
  445. exitCode = 2;
  446. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  447. #endif
  448. } break;
  449. case Node::NODE_UNRECOVERABLE_ERROR: {
  450. exitCode = 3;
  451. const char *termReason = node->reasonForTermination();
  452. fprintf(stderr,"%s: abnormal termination: %s\n",argv[0],(termReason) ? termReason : "(unknown reason)");
  453. } break;
  454. default:
  455. break;
  456. }
  457. delete node;
  458. node = (Node *)0;
  459. } catch ( ... ) {}
  460. #ifdef __UNIX_LIKE__
  461. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  462. #endif
  463. return exitCode;
  464. }