main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  62. fprintf(out,"Available switches:"ZT_EOL_S);
  63. fprintf(out," -h - Display this help"ZT_EOL_S);
  64. fprintf(out," -v - Show version"ZT_EOL_S);
  65. fprintf(out," -p<port> - Bind to this port for network I/O"ZT_EOL_S);
  66. fprintf(out," -c<port> - Bind to this port for local control packets"ZT_EOL_S);
  67. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  68. fprintf(out," -i - Run idtool command (zerotier-idtool)"ZT_EOL_S);
  69. }
  70. namespace ZeroTierCLI { // ---------------------------------------------------
  71. static void printHelp(FILE *out,const char *exename)
  72. {
  73. fprintf(out,"Usage: %s [-switches] <command>"ZT_EOL_S,exename);
  74. fprintf(out,ZT_EOL_S);
  75. fprintf(out,"Available switches:"ZT_EOL_S);
  76. fprintf(out," -c<port> - Communicate with daemon over this local port"ZT_EOL_S);
  77. fprintf(out," -t<token> - Specify token on command line"ZT_EOL_S);
  78. fprintf(out," -T<file> - Read token from file"ZT_EOL_S);
  79. fprintf(out,ZT_EOL_S);
  80. fprintf(out,"Use the 'help' command to get help from ZeroTier One itself."ZT_EOL_S);
  81. }
  82. static volatile unsigned int numResults = 0;
  83. static Condition doneCondition;
  84. static void resultHandler(void *arg,unsigned long id,const char *line)
  85. {
  86. ++numResults;
  87. if (strlen(line))
  88. fprintf(stdout,"%s"ZT_EOL_S,line);
  89. else doneCondition.signal();
  90. }
  91. // Runs instead of rest of main() if process is called zerotier-cli or if
  92. // -q is specified as an option.
  93. #ifdef __WINDOWS__
  94. static int main(int argc,_TCHAR* argv[])
  95. #else
  96. static int main(int argc,char **argv)
  97. #endif
  98. {
  99. if (argc <= 1) {
  100. printHelp(stdout,argv[0]);
  101. return -1;
  102. }
  103. std::string authToken;
  104. std::string command;
  105. bool pastSwitches = false;
  106. unsigned int controlPort = 0;
  107. for(int i=1;i<argc;++i) {
  108. if ((argv[i][0] == '-')&&(!pastSwitches)) {
  109. if (strlen(argv[i]) <= 1) {
  110. printHelp(stdout,argv[0]);
  111. return -1;
  112. }
  113. switch(argv[i][1]) {
  114. case 'q': // does nothing, for invocation without binary path name aliasing
  115. if (argv[i][2]) {
  116. printHelp(argv[0],stderr);
  117. return 0;
  118. }
  119. break;
  120. case 'c':
  121. controlPort = Utils::strToUInt(argv[i] + 2);
  122. break;
  123. case 't':
  124. authToken.assign(argv[i] + 2);
  125. break;
  126. case 'T':
  127. if (!Utils::readFile(argv[i] + 2,authToken)) {
  128. fprintf(stdout,"FATAL ERROR: unable to read token from '%s'"ZT_EOL_S,argv[i] + 2);
  129. return -2;
  130. }
  131. break;
  132. default:
  133. return -1;
  134. }
  135. } else {
  136. pastSwitches = true;
  137. if (command.length())
  138. command.push_back(' ');
  139. command.append(argv[i]);
  140. }
  141. }
  142. if (!command.length()) {
  143. printHelp(stdout,argv[0]);
  144. return -1;
  145. }
  146. if (!authToken.length()) {
  147. const char *home = getenv("HOME");
  148. if (home) {
  149. std::string dotZeroTierAuthToken(home);
  150. dotZeroTierAuthToken.push_back(ZT_PATH_SEPARATOR);
  151. dotZeroTierAuthToken.append(".zerotierOneAuthToken");
  152. if (!Utils::readFile(dotZeroTierAuthToken.c_str(),authToken)) {
  153. #ifndef __WINDOWS__
  154. #ifdef __APPLE__
  155. const char *systemAuthTokenPath = "/Library/Application Support/ZeroTier/One/authtoken.secret";
  156. #else
  157. const char *systemAuthTokenPath = "/var/lib/zerotier-one/authtoken.secret";
  158. #endif
  159. if (!Utils::readFile(systemAuthTokenPath,authToken)) {
  160. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s' or '%s'"ZT_EOL_S,dotZeroTierAuthToken.c_str(),systemAuthTokenPath);
  161. return -2;
  162. }
  163. #else // __WINDOWS__
  164. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s'"ZT_EOL_S,dotZeroTierAuthToken.c_str());
  165. return -2;
  166. #endif // __WINDOWS__
  167. }
  168. }
  169. }
  170. if (!authToken.length()) {
  171. fprintf(stdout,"FATAL ERROR: could not find auth token"ZT_EOL_S);
  172. return -2;
  173. }
  174. Node::LocalClient client(authToken.c_str(),controlPort,&resultHandler,(void *)0);
  175. client.send(command.c_str());
  176. doneCondition.wait(1000);
  177. if (!numResults) {
  178. fprintf(stdout,"ERROR: no results received. Is ZeroTier One running?"ZT_EOL_S);
  179. return -1;
  180. }
  181. return 0;
  182. }
  183. } // namespace ZeroTierCLI ---------------------------------------------------
  184. namespace ZeroTierIdTool { // ------------------------------------------------
  185. static void printHelp(FILE *out,const char *pn)
  186. {
  187. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  188. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  189. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  190. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  191. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  192. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  193. }
  194. static Identity getIdFromArg(char *arg)
  195. {
  196. Identity id;
  197. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  198. if (id.fromString(arg))
  199. return id;
  200. } else { // identity is to be read from a file
  201. std::string idser;
  202. if (Utils::readFile(arg,idser)) {
  203. if (id.fromString(idser))
  204. return id;
  205. }
  206. }
  207. return Identity();
  208. }
  209. // Runs instead of rest of main() if process is called zerotier-idtool or if
  210. // -i is specified as an option.
  211. #ifdef __WINDOWS__
  212. static int main(int argc,_TCHAR* argv[])
  213. #else
  214. static int main(int argc,char **argv)
  215. #endif
  216. {
  217. if (argc < 2) {
  218. printHelp(stderr,argv[0]);
  219. return -1;
  220. }
  221. if (!strcmp(argv[1],"generate")) {
  222. Identity id;
  223. id.generate();
  224. std::string idser = id.toString(true);
  225. if (argc >= 3) {
  226. if (!Utils::writeFile(argv[2],idser)) {
  227. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  228. return -1;
  229. } else printf("%s written"ZT_EOL_S,argv[2]);
  230. if (argc >= 4) {
  231. idser = id.toString(false);
  232. if (!Utils::writeFile(argv[3],idser)) {
  233. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  234. return -1;
  235. } else printf("%s written"ZT_EOL_S,argv[3]);
  236. }
  237. } else printf("%s",idser.c_str());
  238. } else if (!strcmp(argv[1],"validate")) {
  239. if (argc < 3) {
  240. printHelp(stderr,argv[0]);
  241. return -1;
  242. }
  243. Identity id = getIdFromArg(argv[2]);
  244. if (!id) {
  245. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  246. return -1;
  247. }
  248. if (!id.locallyValidate()) {
  249. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  250. return -1;
  251. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  252. } else if (!strcmp(argv[1],"getpublic")) {
  253. if (argc < 3) {
  254. printHelp(stderr,argv[0]);
  255. return -1;
  256. }
  257. Identity id = getIdFromArg(argv[2]);
  258. if (!id) {
  259. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  260. return -1;
  261. }
  262. printf("%s",id.toString(false).c_str());
  263. } else if (!strcmp(argv[1],"sign")) {
  264. if (argc < 4) {
  265. printHelp(stderr,argv[0]);
  266. return -1;
  267. }
  268. Identity id = getIdFromArg(argv[2]);
  269. if (!id) {
  270. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  271. return -1;
  272. }
  273. if (!id.hasPrivate()) {
  274. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  275. return -1;
  276. }
  277. std::string inf;
  278. if (!Utils::readFile(argv[3],inf)) {
  279. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  280. return -1;
  281. }
  282. C25519::Signature signature = id.sign(inf.data(),inf.length());
  283. printf("%s",Utils::hex(signature.data,signature.size()).c_str());
  284. } else if (!strcmp(argv[1],"verify")) {
  285. if (argc < 4) {
  286. printHelp(stderr,argv[0]);
  287. return -1;
  288. }
  289. Identity id = getIdFromArg(argv[2]);
  290. if (!id) {
  291. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  292. return -1;
  293. }
  294. std::string inf;
  295. if (!Utils::readFile(argv[3],inf)) {
  296. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  297. return -1;
  298. }
  299. std::string signature(Utils::unhex(argv[4]));
  300. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),inf.length(),signature.data(),signature.length()))) {
  301. printf("%s signature valid"ZT_EOL_S,argv[3]);
  302. } else {
  303. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  304. return -1;
  305. }
  306. } else {
  307. printHelp(stderr,argv[0]);
  308. return -1;
  309. }
  310. return 0;
  311. }
  312. } // namespace ZeroTierIdTool ------------------------------------------------
  313. #ifdef __UNIX_LIKE__
  314. static void sighandlerQuit(int sig)
  315. {
  316. Node *n = node;
  317. if (n)
  318. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  319. else exit(0);
  320. }
  321. #endif
  322. #ifdef __WINDOWS__
  323. static BOOL WINAPI _handlerRoutine(DWORD dwCtrlType)
  324. {
  325. switch(dwCtrlType) {
  326. case CTRL_C_EVENT:
  327. case CTRL_BREAK_EVENT:
  328. case CTRL_CLOSE_EVENT:
  329. case CTRL_SHUTDOWN_EVENT:
  330. Node *n = node;
  331. if (n)
  332. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  333. return TRUE;
  334. }
  335. return FALSE;
  336. }
  337. #endif
  338. #ifdef __WINDOWS__
  339. int _tmain(int argc, _TCHAR* argv[])
  340. #else
  341. int main(int argc,char **argv)
  342. #endif
  343. {
  344. #ifdef __UNIX_LIKE__
  345. signal(SIGHUP,SIG_IGN);
  346. signal(SIGPIPE,SIG_IGN);
  347. signal(SIGUSR1,SIG_IGN);
  348. signal(SIGUSR2,SIG_IGN);
  349. signal(SIGALRM,SIG_IGN);
  350. signal(SIGINT,&sighandlerQuit);
  351. signal(SIGTERM,&sighandlerQuit);
  352. signal(SIGQUIT,&sighandlerQuit);
  353. #endif
  354. #ifdef __WINDOWS__
  355. WSADATA wsaData;
  356. WSAStartup(MAKEWORD(2,2),&wsaData);
  357. SetConsoleCtrlHandler(&_handlerRoutine,TRUE);
  358. #endif
  359. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  360. return ZeroTierCLI::main(argc,argv);
  361. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  362. return ZeroTierIdTool::main(argc,argv);
  363. const char *homeDir = (const char *)0;
  364. unsigned int port = 0;
  365. unsigned int controlPort = 0;
  366. for(int i=1;i<argc;++i) {
  367. if (argv[i][0] == '-') {
  368. switch(argv[i][1]) {
  369. case 'p':
  370. port = Utils::strToUInt(argv[i] + 2);
  371. if (port > 65535) {
  372. printHelp(argv[0],stderr);
  373. return -1;
  374. }
  375. break;
  376. case 'v':
  377. printf("%s"ZT_EOL_S,Node::versionString());
  378. return 0;
  379. case 'c':
  380. controlPort = Utils::strToUInt(argv[i] + 2);
  381. if (controlPort > 65535) {
  382. printHelp(argv[0],stderr);
  383. return -1;
  384. }
  385. break;
  386. case 'q':
  387. if (argv[i][2]) {
  388. printHelp(argv[0],stderr);
  389. return 0;
  390. } else return ZeroTierCLI::main(argc,argv);
  391. case 'i':
  392. if (argv[i][2]) {
  393. printHelp(argv[0],stderr);
  394. return 0;
  395. } else return ZeroTierIdTool::main(argc,argv);
  396. case 'h':
  397. case '?':
  398. default:
  399. printHelp(argv[0],stderr);
  400. return 0;
  401. }
  402. } else {
  403. if (homeDir) {
  404. printHelp(argv[0],stderr);
  405. return 0;
  406. }
  407. homeDir = argv[i];
  408. break;
  409. }
  410. }
  411. if ((!homeDir)||(strlen(homeDir) == 0))
  412. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  413. #ifdef __UNIX_LIKE__
  414. mkdir(homeDir,0755); // will fail if it already exists
  415. {
  416. char pidpath[4096];
  417. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  418. FILE *pf = fopen(pidpath,"w");
  419. if (pf) {
  420. fprintf(pf,"%ld",(long)getpid());
  421. fclose(pf);
  422. }
  423. }
  424. #endif
  425. int exitCode = 0;
  426. try {
  427. node = new Node(homeDir,port,controlPort);
  428. switch(node->run()) {
  429. case Node::NODE_NODE_RESTART_FOR_UPGRADE: {
  430. #ifdef __UNIX_LIKE__
  431. const char *upgPath = node->reasonForTermination();
  432. if (upgPath)
  433. execl(upgPath,upgPath,"-s",(char *)0); // -s = (re)start after install/upgrade
  434. exitCode = -1;
  435. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s",argv[0],(upgPath) ? upgPath : "(unknown path)");
  436. #endif
  437. } break;
  438. case Node::NODE_UNRECOVERABLE_ERROR: {
  439. exitCode = -1;
  440. const char *termReason = node->reasonForTermination();
  441. fprintf(stderr,"%s: abnormal termination: %s\n",argv[0],(termReason) ? termReason : "(unknown reason)");
  442. } break;
  443. default:
  444. break;
  445. }
  446. delete node;
  447. node = (Node *)0;
  448. } catch ( ... ) {}
  449. #ifdef __UNIX_LIKE__
  450. {
  451. char pidpath[4096];
  452. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  453. Utils::rm(pidpath);
  454. }
  455. #endif
  456. return exitCode;
  457. }