main.cpp 13 KB

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