main.cpp 13 KB

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