one.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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 <stdint.h>
  31. #include <time.h>
  32. #include <errno.h>
  33. #ifdef __WINDOWS__
  34. #include <WinSock2.h>
  35. #include <Windows.h>
  36. #include <tchar.h>
  37. #include <wchar.h>
  38. #include <lmcons.h>
  39. #include <newdev.h>
  40. #include <atlbase.h>
  41. #include "windows/ZeroTierOne/ServiceInstaller.h"
  42. #include "windows/ZeroTierOne/ServiceBase.h"
  43. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  44. #else
  45. #include <unistd.h>
  46. #include <pwd.h>
  47. #include <fcntl.h>
  48. #include <sys/types.h>
  49. #include <sys/stat.h>
  50. #include <signal.h>
  51. #endif
  52. #include <string>
  53. #include <stdexcept>
  54. #include "version.h"
  55. #include "include/ZeroTierOne.h"
  56. #include "ext/json-parser/json.h"
  57. #include "node/Constants.hpp"
  58. #include "node/Identity.hpp"
  59. #include "node/CertificateOfMembership.hpp"
  60. #include "node/Utils.hpp"
  61. #include "node/NetworkController.hpp"
  62. #include "osdep/OSUtils.hpp"
  63. #include "osdep/Http.hpp"
  64. #include "service/OneService.hpp"
  65. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  66. #include "controller/SqliteNetworkController.hpp"
  67. #endif
  68. #define ZT1_PID_PATH "zerotier-one.pid"
  69. #define ZT1_CONTROLLER_DB_PATH "controller.db"
  70. using namespace ZeroTier;
  71. static OneService *volatile zt1Service = (OneService *)0;
  72. /****************************************************************************/
  73. /* zerotier-cli personality */
  74. /****************************************************************************/
  75. static void cliPrintHelp(const char *pn,FILE *out)
  76. {
  77. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  78. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  79. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]"ZT_EOL_S""ZT_EOL_S,pn);
  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," -j - Display full raw JSON output"ZT_EOL_S);
  84. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect"ZT_EOL_S);
  85. fprintf(out," -p<port> - HTTP port (default: auto)"ZT_EOL_S);
  86. fprintf(out," -T<token> - Authentication token (default: auto)"ZT_EOL_S);
  87. //fprintf(out," -H<ip> - HTTP IP address (default: 127.0.0.1)"ZT_EOL_S""ZT_EOL_S);
  88. fprintf(out,"Available commands:"ZT_EOL_S);
  89. fprintf(out," info - Display status info"ZT_EOL_S);
  90. fprintf(out," listpeers - List all peers"ZT_EOL_S);
  91. fprintf(out," listnetworks - List all networks"ZT_EOL_S);
  92. fprintf(out," join <network> - Join a network"ZT_EOL_S);
  93. fprintf(out," leave <network> - Leave a network"ZT_EOL_S);
  94. }
  95. static std::string cliFixJsonCRs(const std::string &s)
  96. {
  97. std::string r;
  98. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  99. if (*c == '\n')
  100. r.append(ZT_EOL_S);
  101. else r.push_back(*c);
  102. }
  103. return r;
  104. }
  105. #ifdef __WINDOWS__
  106. static int cli(int argc, _TCHAR* argv[])
  107. #else
  108. static int cli(int argc,char **argv)
  109. #endif
  110. {
  111. unsigned int port = 0;
  112. std::string homeDir;
  113. std::string command;
  114. std::string arg1;
  115. std::string authToken;
  116. std::string ip("127.0.0.1");
  117. bool json = false;
  118. for(int i=1;i<argc;++i) {
  119. if (argv[i][0] == '-') {
  120. switch(argv[i][1]) {
  121. case 'q': // ignore -q used to invoke this personality
  122. if (argv[i][2]) {
  123. cliPrintHelp(argv[0],stdout);
  124. return 1;
  125. }
  126. break;
  127. case 'j':
  128. if (argv[i][2]) {
  129. cliPrintHelp(argv[0],stdout);
  130. return 1;
  131. }
  132. json = true;
  133. break;
  134. case 'p': // port for HTTP
  135. port = Utils::strToUInt(argv[i] + 2);
  136. if ((port > 0xffff)||(port == 0)) {
  137. cliPrintHelp(argv[0],stdout);
  138. return 1;
  139. }
  140. break;
  141. case 'D': // Home path
  142. if (argv[i][2]) {
  143. homeDir = argv[i] + 2;
  144. } else {
  145. cliPrintHelp(argv[0],stdout);
  146. return 1;
  147. }
  148. break;
  149. case 'H': // HTTP IP
  150. if (argv[i][2]) {
  151. ip = argv[i] + 2;
  152. } else {
  153. cliPrintHelp(argv[0],stdout);
  154. return 1;
  155. }
  156. break;
  157. case 'T': // Override root topology
  158. if (argv[i][2]) {
  159. authToken = argv[i] + 2;
  160. } else {
  161. cliPrintHelp(argv[0],stdout);
  162. return 1;
  163. }
  164. break;
  165. case 'v': // Display version
  166. if (argv[i][2]) {
  167. cliPrintHelp(argv[0],stdout);
  168. return 1;
  169. }
  170. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  171. return 0;
  172. case 'h':
  173. case '?':
  174. default:
  175. cliPrintHelp(argv[0],stdout);
  176. return 0;
  177. }
  178. } else {
  179. if (command.length())
  180. arg1 = argv[i];
  181. else command = argv[i];
  182. }
  183. }
  184. if (!homeDir.length())
  185. homeDir = OneService::platformDefaultHomePath();
  186. if ((!port)||(!authToken.length())) {
  187. if (!homeDir.length()) {
  188. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect"ZT_EOL_S,argv[0]);
  189. return 2;
  190. }
  191. if (!port) {
  192. std::string portStr;
  193. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  194. port = Utils::strToUInt(portStr.c_str());
  195. if ((port == 0)||(port > 0xffff)) {
  196. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s"ZT_EOL_S,argv[0],homeDir.c_str());
  197. return 2;
  198. }
  199. }
  200. if (!authToken.length()) {
  201. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  202. if (!authToken.length()) {
  203. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s"ZT_EOL_S,argv[0],homeDir.c_str());
  204. return 2;
  205. }
  206. }
  207. }
  208. InetAddress addr;
  209. {
  210. char addrtmp[256];
  211. Utils::snprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  212. addr = InetAddress(addrtmp);
  213. }
  214. std::map<std::string,std::string> requestHeaders;
  215. std::map<std::string,std::string> responseHeaders;
  216. std::string responseBody;
  217. requestHeaders["X-ZT1-Auth"] = authToken;
  218. if ((command == "info")||(command == "status")) {
  219. unsigned int scode = Http::GET(
  220. 1024 * 1024 * 16,
  221. 60000,
  222. (const struct sockaddr *)&addr,
  223. "/status",
  224. requestHeaders,
  225. responseHeaders,
  226. responseBody);
  227. if (scode == 200) {
  228. if (json) {
  229. printf("%s",cliFixJsonCRs(responseBody).c_str());
  230. return 0;
  231. } else {
  232. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  233. bool good = false;
  234. if (j) {
  235. if (j->type == json_object) {
  236. const char *address = (const char *)0;
  237. bool online = false;
  238. const char *version = (const char *)0;
  239. for(unsigned int k=0;k<j->u.object.length;++k) {
  240. if ((!strcmp(j->u.object.values[k].name,"address"))&&(j->u.object.values[k].value->type == json_string))
  241. address = j->u.object.values[k].value->u.string.ptr;
  242. else if ((!strcmp(j->u.object.values[k].name,"version"))&&(j->u.object.values[k].value->type == json_string))
  243. version = j->u.object.values[k].value->u.string.ptr;
  244. else if ((!strcmp(j->u.object.values[k].name,"online"))&&(j->u.object.values[k].value->type == json_boolean))
  245. online = (j->u.object.values[k].value->u.boolean != 0);
  246. }
  247. if ((address)&&(version)) {
  248. printf("200 info %s %s %s"ZT_EOL_S,address,(online ? "ONLINE" : "OFFLINE"),version);
  249. good = true;
  250. }
  251. }
  252. json_value_free(j);
  253. }
  254. if (good) {
  255. return 0;
  256. } else {
  257. printf("%u %s invalid JSON response"ZT_EOL_S,scode,command.c_str());
  258. return 1;
  259. }
  260. }
  261. } else {
  262. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  263. return 1;
  264. }
  265. } else if (command == "listpeers") {
  266. unsigned int scode = Http::GET(
  267. 1024 * 1024 * 16,
  268. 60000,
  269. (const struct sockaddr *)&addr,
  270. "/peer",
  271. requestHeaders,
  272. responseHeaders,
  273. responseBody);
  274. if (scode == 200) {
  275. if (json) {
  276. printf("%s",cliFixJsonCRs(responseBody).c_str());
  277. return 0;
  278. } else {
  279. printf("200 listpeers <ztaddr> <paths> <latency> <version> <role>"ZT_EOL_S);
  280. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  281. if (j) {
  282. if (j->type == json_array) {
  283. for(unsigned int p=0;p<j->u.array.length;++p) {
  284. json_value *jp = j->u.array.values[p];
  285. if (jp->type == json_object) {
  286. const char *address = (const char *)0;
  287. std::string paths;
  288. int64_t latency = 0;
  289. int64_t versionMajor = -1,versionMinor = -1,versionRev = -1;
  290. const char *role = (const char *)0;
  291. for(unsigned int k=0;k<jp->u.object.length;++k) {
  292. if ((!strcmp(jp->u.object.values[k].name,"address"))&&(jp->u.object.values[k].value->type == json_string))
  293. address = jp->u.object.values[k].value->u.string.ptr;
  294. else if ((!strcmp(jp->u.object.values[k].name,"versionMajor"))&&(jp->u.object.values[k].value->type == json_integer))
  295. versionMajor = jp->u.object.values[k].value->u.integer;
  296. else if ((!strcmp(jp->u.object.values[k].name,"versionMinor"))&&(jp->u.object.values[k].value->type == json_integer))
  297. versionMinor = jp->u.object.values[k].value->u.integer;
  298. else if ((!strcmp(jp->u.object.values[k].name,"versionRev"))&&(jp->u.object.values[k].value->type == json_integer))
  299. versionRev = jp->u.object.values[k].value->u.integer;
  300. else if ((!strcmp(jp->u.object.values[k].name,"role"))&&(jp->u.object.values[k].value->type == json_string))
  301. role = jp->u.object.values[k].value->u.string.ptr;
  302. else if ((!strcmp(jp->u.object.values[k].name,"latency"))&&(jp->u.object.values[k].value->type == json_integer))
  303. latency = jp->u.object.values[k].value->u.integer;
  304. else if ((!strcmp(jp->u.object.values[k].name,"paths"))&&(jp->u.object.values[k].value->type == json_array)) {
  305. for(unsigned int pp=0;pp<jp->u.object.values[k].value->u.array.length;++pp) {
  306. json_value *jpath = jp->u.object.values[k].value->u.array.values[pp];
  307. if (jpath->type == json_object) {
  308. const char *paddr = (const char *)0;
  309. int64_t lastSend = 0;
  310. int64_t lastReceive = 0;
  311. bool fixed = false;
  312. bool active = false; // fixed/active/inactive
  313. for(unsigned int kk=0;kk<jpath->u.object.length;++kk) {
  314. if ((!strcmp(jpath->u.object.values[kk].name,"address"))&&(jpath->u.object.values[kk].value->type == json_string))
  315. paddr = jpath->u.object.values[kk].value->u.string.ptr;
  316. else if ((!strcmp(jpath->u.object.values[kk].name,"lastSend"))&&(jpath->u.object.values[kk].value->type == json_integer))
  317. lastSend = jpath->u.object.values[kk].value->u.integer;
  318. else if ((!strcmp(jpath->u.object.values[kk].name,"lastReceive"))&&(jpath->u.object.values[kk].value->type == json_integer))
  319. lastReceive = jpath->u.object.values[kk].value->u.integer;
  320. else if ((!strcmp(jpath->u.object.values[kk].name,"fixed"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  321. fixed = (jpath->u.object.values[kk].value->u.boolean != 0);
  322. else if ((!strcmp(jpath->u.object.values[kk].name,"active"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  323. active = (jpath->u.object.values[kk].value->u.boolean != 0);
  324. }
  325. if (paddr) {
  326. int64_t now = (int64_t)OSUtils::now();
  327. if (lastSend > 0)
  328. lastSend = now - lastSend;
  329. if (lastReceive > 0)
  330. lastReceive = now - lastReceive;
  331. char pathtmp[256];
  332. Utils::snprintf(pathtmp,sizeof(pathtmp),"%s;%lld;%lld;%s",
  333. paddr,
  334. lastSend,
  335. lastReceive,
  336. (fixed ? "fixed" : (active ? "active" : "inactive")));
  337. if (paths.length())
  338. paths.push_back(',');
  339. paths.append(pathtmp);
  340. }
  341. }
  342. }
  343. }
  344. }
  345. if ((address)&&(role)) {
  346. char verstr[64];
  347. if ((versionMajor >= 0)&&(versionMinor >= 0)&&(versionRev >= 0))
  348. Utils::snprintf(verstr,sizeof(verstr),"%lld.%lld.%lld",versionMajor,versionMinor,versionRev);
  349. else {
  350. verstr[0] = '-';
  351. verstr[1] = (char)0;
  352. }
  353. printf("200 listpeers %s %s %lld %s %s"ZT_EOL_S,address,(paths.length()) ? paths.c_str() : "-",latency,verstr,role);
  354. }
  355. }
  356. }
  357. }
  358. json_value_free(j);
  359. }
  360. return 0;
  361. }
  362. } else {
  363. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  364. return 1;
  365. }
  366. } else if (command == "listnetworks") {
  367. unsigned int scode = Http::GET(
  368. 1024 * 1024 * 16,
  369. 60000,
  370. (const struct sockaddr *)&addr,
  371. "/network",
  372. requestHeaders,
  373. responseHeaders,
  374. responseBody);
  375. if (scode == 200) {
  376. if (json) {
  377. printf("%s",cliFixJsonCRs(responseBody).c_str());
  378. return 0;
  379. } else {
  380. }
  381. } else {
  382. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  383. return 1;
  384. }
  385. } else if (command == "join") {
  386. if (arg1.length() != 16) {
  387. cliPrintHelp(argv[0],stderr);
  388. return 2;
  389. }
  390. unsigned int scode = Http::POST(
  391. 1024 * 1024 * 16,
  392. 60000,
  393. (const struct sockaddr *)&addr,
  394. (std::string("/network/") + arg1).c_str(),
  395. requestHeaders,
  396. "",
  397. 0,
  398. responseHeaders,
  399. responseBody);
  400. if (scode == 200) {
  401. if (json) {
  402. printf("%s",cliFixJsonCRs(responseBody).c_str());
  403. } else {
  404. }
  405. return 0;
  406. } else {
  407. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  408. return 1;
  409. }
  410. } else if (command == "leave") {
  411. if (arg1.length() != 16) {
  412. cliPrintHelp(argv[0],stderr);
  413. return 2;
  414. }
  415. unsigned int scode = Http::DELETE(
  416. 1024 * 1024 * 16,
  417. 60000,
  418. (const struct sockaddr *)&addr,
  419. (std::string("/network/") + arg1).c_str(),
  420. requestHeaders,
  421. responseHeaders,
  422. responseBody);
  423. if (scode == 200) {
  424. if (json) {
  425. printf("%s",cliFixJsonCRs(responseBody).c_str());
  426. } else {
  427. printf("200 leave OK"ZT_EOL_S);
  428. }
  429. return 0;
  430. } else {
  431. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  432. return 1;
  433. }
  434. } else {
  435. cliPrintHelp(argv[0],stderr);
  436. return 0;
  437. }
  438. }
  439. /****************************************************************************/
  440. /* zerotier-idtool personality */
  441. /****************************************************************************/
  442. static void idtoolPrintHelp(FILE *out,const char *pn)
  443. {
  444. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  445. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  446. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  447. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  448. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  449. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  450. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  451. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  452. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  453. }
  454. static Identity getIdFromArg(char *arg)
  455. {
  456. Identity id;
  457. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  458. if (id.fromString(arg))
  459. return id;
  460. } else { // identity is to be read from a file
  461. std::string idser;
  462. if (OSUtils::readFile(arg,idser)) {
  463. if (id.fromString(idser))
  464. return id;
  465. }
  466. }
  467. return Identity();
  468. }
  469. #ifdef __WINDOWS__
  470. static int idtool(int argc, _TCHAR* argv[])
  471. #else
  472. static int idtool(int argc,char **argv)
  473. #endif
  474. {
  475. if (argc < 2) {
  476. idtoolPrintHelp(stdout,argv[0]);
  477. return 1;
  478. }
  479. if (!strcmp(argv[1],"generate")) {
  480. Identity id;
  481. id.generate();
  482. std::string idser = id.toString(true);
  483. if (argc >= 3) {
  484. if (!OSUtils::writeFile(argv[2],idser)) {
  485. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  486. return 1;
  487. } else printf("%s written"ZT_EOL_S,argv[2]);
  488. if (argc >= 4) {
  489. idser = id.toString(false);
  490. if (!OSUtils::writeFile(argv[3],idser)) {
  491. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  492. return 1;
  493. } else printf("%s written"ZT_EOL_S,argv[3]);
  494. }
  495. } else printf("%s",idser.c_str());
  496. } else if (!strcmp(argv[1],"validate")) {
  497. if (argc < 3) {
  498. idtoolPrintHelp(stdout,argv[0]);
  499. return 1;
  500. }
  501. Identity id = getIdFromArg(argv[2]);
  502. if (!id) {
  503. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  504. return 1;
  505. }
  506. if (!id.locallyValidate()) {
  507. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  508. return 1;
  509. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  510. } else if (!strcmp(argv[1],"getpublic")) {
  511. if (argc < 3) {
  512. idtoolPrintHelp(stdout,argv[0]);
  513. return 1;
  514. }
  515. Identity id = getIdFromArg(argv[2]);
  516. if (!id) {
  517. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  518. return 1;
  519. }
  520. printf("%s",id.toString(false).c_str());
  521. } else if (!strcmp(argv[1],"sign")) {
  522. if (argc < 4) {
  523. idtoolPrintHelp(stdout,argv[0]);
  524. return 1;
  525. }
  526. Identity id = getIdFromArg(argv[2]);
  527. if (!id) {
  528. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  529. return 1;
  530. }
  531. if (!id.hasPrivate()) {
  532. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  533. return 1;
  534. }
  535. std::string inf;
  536. if (!OSUtils::readFile(argv[3],inf)) {
  537. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  538. return 1;
  539. }
  540. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  541. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  542. } else if (!strcmp(argv[1],"verify")) {
  543. if (argc < 4) {
  544. idtoolPrintHelp(stdout,argv[0]);
  545. return 1;
  546. }
  547. Identity id = getIdFromArg(argv[2]);
  548. if (!id) {
  549. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  550. return 1;
  551. }
  552. std::string inf;
  553. if (!OSUtils::readFile(argv[3],inf)) {
  554. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  555. return 1;
  556. }
  557. std::string signature(Utils::unhex(argv[4]));
  558. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  559. printf("%s signature valid"ZT_EOL_S,argv[3]);
  560. } else {
  561. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  562. return 1;
  563. }
  564. } else if (!strcmp(argv[1],"mkcom")) {
  565. if (argc < 3) {
  566. idtoolPrintHelp(stdout,argv[0]);
  567. return 1;
  568. }
  569. Identity id = getIdFromArg(argv[2]);
  570. if ((!id)||(!id.hasPrivate())) {
  571. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  572. return 1;
  573. }
  574. CertificateOfMembership com;
  575. for(int a=3;a<argc;++a) {
  576. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  577. if (params.size() == 3) {
  578. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  579. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  580. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  581. com.setQualifier(qId,qValue,qMaxDelta);
  582. }
  583. }
  584. if (!com.sign(id)) {
  585. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  586. return 1;
  587. }
  588. printf("%s",com.toString().c_str());
  589. } else {
  590. idtoolPrintHelp(stdout,argv[0]);
  591. return 1;
  592. }
  593. return 0;
  594. }
  595. /****************************************************************************/
  596. /* Unix helper functions and signal handlers */
  597. /****************************************************************************/
  598. #ifdef __UNIX_LIKE__
  599. static void _sighandlerHup(int sig)
  600. {
  601. }
  602. static void _sighandlerQuit(int sig)
  603. {
  604. OneService *s = zt1Service;
  605. if (s)
  606. s->terminate();
  607. else exit(0);
  608. }
  609. #endif
  610. /****************************************************************************/
  611. /* Windows helper functions and signal handlers */
  612. /****************************************************************************/
  613. #ifdef __WINDOWS__
  614. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  615. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  616. {
  617. switch(dwCtrlType) {
  618. case CTRL_C_EVENT:
  619. case CTRL_BREAK_EVENT:
  620. case CTRL_CLOSE_EVENT:
  621. case CTRL_SHUTDOWN_EVENT:
  622. Node *n = node;
  623. if (n)
  624. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  625. return TRUE;
  626. }
  627. return FALSE;
  628. }
  629. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  630. static void _winPokeAHole()
  631. {
  632. char myPath[MAX_PATH];
  633. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  634. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  635. STARTUPINFOA startupInfo;
  636. PROCESS_INFORMATION processInfo;
  637. startupInfo.cb = sizeof(startupInfo);
  638. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  639. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  640. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall delete rule name=\"ZeroTier One\" program=\"") + myPath + "\"").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  641. WaitForSingleObject(processInfo.hProcess,INFINITE);
  642. CloseHandle(processInfo.hProcess);
  643. CloseHandle(processInfo.hThread);
  644. }
  645. startupInfo.cb = sizeof(startupInfo);
  646. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  647. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  648. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=in action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  649. WaitForSingleObject(processInfo.hProcess,INFINITE);
  650. CloseHandle(processInfo.hProcess);
  651. CloseHandle(processInfo.hThread);
  652. }
  653. startupInfo.cb = sizeof(startupInfo);
  654. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  655. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  656. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=out action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  657. WaitForSingleObject(processInfo.hProcess,INFINITE);
  658. CloseHandle(processInfo.hProcess);
  659. CloseHandle(processInfo.hThread);
  660. }
  661. }
  662. }
  663. // Returns true if this is running as the local administrator
  664. static BOOL IsCurrentUserLocalAdministrator(void)
  665. {
  666. BOOL fReturn = FALSE;
  667. DWORD dwStatus;
  668. DWORD dwAccessMask;
  669. DWORD dwAccessDesired;
  670. DWORD dwACLSize;
  671. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  672. PACL pACL = NULL;
  673. PSID psidAdmin = NULL;
  674. HANDLE hToken = NULL;
  675. HANDLE hImpersonationToken = NULL;
  676. PRIVILEGE_SET ps;
  677. GENERIC_MAPPING GenericMapping;
  678. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  679. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  680. const DWORD ACCESS_READ = 1;
  681. const DWORD ACCESS_WRITE = 2;
  682. __try
  683. {
  684. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  685. {
  686. if (GetLastError() != ERROR_NO_TOKEN)
  687. __leave;
  688. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  689. __leave;
  690. }
  691. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  692. __leave;
  693. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  694. SECURITY_BUILTIN_DOMAIN_RID,
  695. DOMAIN_ALIAS_RID_ADMINS,
  696. 0, 0, 0, 0, 0, 0, &psidAdmin))
  697. __leave;
  698. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  699. if (psdAdmin == NULL)
  700. __leave;
  701. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  702. __leave;
  703. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  704. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  705. if (pACL == NULL)
  706. __leave;
  707. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  708. __leave;
  709. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  710. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  711. __leave;
  712. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  713. __leave;
  714. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  715. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  716. if (!IsValidSecurityDescriptor(psdAdmin))
  717. __leave;
  718. dwAccessDesired = ACCESS_READ;
  719. GenericMapping.GenericRead = ACCESS_READ;
  720. GenericMapping.GenericWrite = ACCESS_WRITE;
  721. GenericMapping.GenericExecute = 0;
  722. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  723. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  724. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  725. &fReturn))
  726. {
  727. fReturn = FALSE;
  728. __leave;
  729. }
  730. }
  731. __finally
  732. {
  733. // Clean up.
  734. if (pACL) LocalFree(pACL);
  735. if (psdAdmin) LocalFree(psdAdmin);
  736. if (psidAdmin) FreeSid(psidAdmin);
  737. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  738. if (hToken) CloseHandle (hToken);
  739. }
  740. return fReturn;
  741. }
  742. #endif // __WINDOWS__
  743. /****************************************************************************/
  744. /* main() and friends */
  745. /****************************************************************************/
  746. static void printHelp(const char *cn,FILE *out)
  747. {
  748. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  749. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  750. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  751. fprintf(out,"Available switches:"ZT_EOL_S);
  752. fprintf(out," -h - Display this help"ZT_EOL_S);
  753. fprintf(out," -v - Show version"ZT_EOL_S);
  754. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993)"ZT_EOL_S);
  755. //fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
  756. #ifdef __UNIX_LIKE__
  757. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  758. #endif // __UNIX_LIKE__
  759. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  760. fprintf(out," -q - Query API (zerotier-cli)"ZT_EOL_S);
  761. #ifdef __WINDOWS__
  762. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  763. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  764. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  765. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  766. #endif // __WINDOWS__
  767. }
  768. #ifdef __WINDOWS__
  769. int _tmain(int argc, _TCHAR* argv[])
  770. #else
  771. int main(int argc,char **argv)
  772. #endif
  773. {
  774. #ifdef __UNIX_LIKE__
  775. signal(SIGHUP,&_sighandlerHup);
  776. signal(SIGPIPE,SIG_IGN);
  777. signal(SIGUSR1,SIG_IGN);
  778. signal(SIGUSR2,SIG_IGN);
  779. signal(SIGALRM,SIG_IGN);
  780. signal(SIGINT,&_sighandlerQuit);
  781. signal(SIGTERM,&_sighandlerQuit);
  782. signal(SIGQUIT,&_sighandlerQuit);
  783. /* Ensure that there are no inherited file descriptors open from a previous
  784. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  785. * of it do not return, and should not do anything otherwise bad. */
  786. {
  787. int mfd = STDIN_FILENO;
  788. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  789. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  790. for(int f=mfd+1;f<1024;++f)
  791. ::close(f);
  792. }
  793. bool runAsDaemon = false;
  794. #endif // __UNIX_LIKE__
  795. #ifdef __WINDOWS__
  796. WSADATA wsaData;
  797. WSAStartup(MAKEWORD(2,2),&wsaData);
  798. #ifdef ZT_WIN_RUN_IN_CONSOLE
  799. bool winRunFromCommandLine = true;
  800. #else
  801. bool winRunFromCommandLine = false;
  802. #endif
  803. #endif // __WINDOWS__
  804. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  805. return idtool(argc,argv);
  806. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  807. return cli(argc,argv);
  808. std::string overrideRootTopology;
  809. std::string homeDir;
  810. unsigned int port = ZT1_DEFAULT_PORT;
  811. for(int i=1;i<argc;++i) {
  812. if (argv[i][0] == '-') {
  813. switch(argv[i][1]) {
  814. case 'p': // port -- for both UDP and TCP, packets and control plane
  815. port = Utils::strToUInt(argv[i] + 2);
  816. if ((port > 0xffff)||(port == 0)) {
  817. printHelp(argv[0],stdout);
  818. return 1;
  819. }
  820. break;
  821. #ifdef __UNIX_LIKE__
  822. case 'd': // Run in background as daemon
  823. runAsDaemon = true;
  824. break;
  825. #endif // __UNIX_LIKE__
  826. case 'T': // Override root topology
  827. if (argv[i][2]) {
  828. if (!OSUtils::readFile(argv[i] + 2,overrideRootTopology)) {
  829. fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
  830. return 1;
  831. }
  832. } else {
  833. printHelp(argv[0],stdout);
  834. return 1;
  835. }
  836. break;
  837. case 'v': // Display version
  838. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  839. return 0;
  840. case 'i': // Invoke idtool personality
  841. if (argv[i][2]) {
  842. printHelp(argv[0],stdout);
  843. return 0;
  844. } else return idtool(argc,argv);
  845. case 'q': // Invoke cli personality
  846. if (argv[i][2]) {
  847. printHelp(argv[0],stdout);
  848. return 0;
  849. } else return cli(argc,argv);
  850. #ifdef __WINDOWS__
  851. case 'C': // Run from command line instead of as Windows service
  852. winRunFromCommandLine = true;
  853. break;
  854. case 'I': { // Install this binary as a Windows service
  855. if (IsCurrentUserLocalAdministrator() != TRUE) {
  856. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  857. return 1;
  858. }
  859. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  860. if (ret.length()) {
  861. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  862. return 3;
  863. }
  864. return 0;
  865. } break;
  866. case 'R': { // Uninstall this binary as Windows service
  867. if (IsCurrentUserLocalAdministrator() != TRUE) {
  868. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  869. return 1;
  870. }
  871. std::string ret(UninstallService(ZT_SERVICE_NAME));
  872. if (ret.length()) {
  873. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  874. return 3;
  875. }
  876. return 0;
  877. } break;
  878. #if 0
  879. case 'D': { // Install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  880. std::string pathToInf;
  881. #ifdef _WIN64
  882. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  883. #else
  884. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  885. #endif
  886. printf("Installing ZeroTier One virtual Ethernet port driver."ZT_EOL_S""ZT_EOL_S"NOTE: If you don't see a confirmation window to allow driver installation,"ZT_EOL_S"check to make sure it didn't appear under the installer."ZT_EOL_S);
  887. BOOL needReboot = FALSE;
  888. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  889. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  890. return 0;
  891. } else {
  892. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  893. return 3;
  894. }
  895. } break;
  896. #endif // __WINDOWS__
  897. #endif
  898. case 'h':
  899. case '?':
  900. default:
  901. printHelp(argv[0],stdout);
  902. return 0;
  903. }
  904. } else {
  905. if (homeDir.length()) {
  906. printHelp(argv[0],stdout);
  907. return 0;
  908. } else {
  909. homeDir = argv[i];
  910. }
  911. }
  912. }
  913. if (!homeDir.length())
  914. homeDir = OneService::platformDefaultHomePath();
  915. if (!homeDir.length()) {
  916. fprintf(stderr,"%s: no home path specified and no platform default available"ZT_EOL_S,argv[0]);
  917. return 1;
  918. } else {
  919. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  920. std::string ptmp;
  921. if (homeDir[0] == ZT_PATH_SEPARATOR)
  922. ptmp.push_back(ZT_PATH_SEPARATOR);
  923. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  924. if (ptmp.length() > 0)
  925. ptmp.push_back(ZT_PATH_SEPARATOR);
  926. ptmp.append(*pi);
  927. if ((*pi != ".")&&(*pi != "..")) {
  928. if (!OSUtils::mkdir(ptmp))
  929. throw std::runtime_error("home path does not exist, and could not create");
  930. }
  931. }
  932. }
  933. #ifdef __UNIX_LIKE__
  934. if (getuid() != 0) {
  935. fprintf(stderr,"%s: must be run as root (uid 0)"ZT_EOL_S,argv[0]);
  936. return 1;
  937. }
  938. if (runAsDaemon) {
  939. long p = (long)fork();
  940. if (p < 0) {
  941. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  942. return 1;
  943. } else if (p > 0)
  944. return 0; // forked
  945. // else p == 0, so we are daemonized
  946. }
  947. #endif // __UNIX_LIKE__
  948. #ifdef __WINDOWS__
  949. if (winRunFromCommandLine) {
  950. // Running in "interactive" mode (mostly for debugging)
  951. if (IsCurrentUserLocalAdministrator() != TRUE) {
  952. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  953. return 1;
  954. }
  955. _winPokeAHole();
  956. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  957. // continues on to ordinary command line execution code below...
  958. } else {
  959. // Running from service manager
  960. _winPokeAHole();
  961. ZeroTierOneService zt1Service;
  962. if (CServiceBase::Run(zt1Service) == TRUE) {
  963. return 0;
  964. } else {
  965. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  966. return 1;
  967. }
  968. }
  969. #endif // __WINDOWS__
  970. NetworkController *controller = (NetworkController *)0;
  971. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  972. try {
  973. controller = new SqliteNetworkController((homeDir + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str());
  974. } catch (std::exception &exc) {
  975. fprintf(stderr,"%s: failure initializing SqliteNetworkController: %s"ZT_EOL_S,argv[0],exc.what());
  976. return 1;
  977. } catch ( ... ) {
  978. fprintf(stderr,"%s: failure initializing SqliteNetworkController: unknown exception"ZT_EOL_S,argv[0]);
  979. return 1;
  980. }
  981. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  982. #ifdef __UNIX_LIKE__
  983. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT1_PID_PATH);
  984. {
  985. // Write .pid file to home folder
  986. FILE *pf = fopen(pidPath.c_str(),"w");
  987. if (pf) {
  988. fprintf(pf,"%ld",(long)getpid());
  989. fclose(pf);
  990. }
  991. }
  992. #endif // __UNIX_LIKE__
  993. unsigned int returnValue = 0;
  994. try {
  995. for(;;) {
  996. zt1Service = OneService::newInstance(homeDir.c_str(),port,controller,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
  997. switch(zt1Service->run()) {
  998. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  999. case OneService::ONE_NORMAL_TERMINATION:
  1000. break;
  1001. case OneService::ONE_UNRECOVERABLE_ERROR:
  1002. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1003. returnValue = 1;
  1004. break;
  1005. case OneService::ONE_IDENTITY_COLLISION: {
  1006. delete zt1Service;
  1007. zt1Service = (OneService *)0;
  1008. std::string oldid;
  1009. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1010. if (oldid.length()) {
  1011. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1012. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1013. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1014. }
  1015. } continue; // restart!
  1016. }
  1017. break; // terminate loop -- normally we don't keep restarting
  1018. }
  1019. } catch (std::exception &exc) {
  1020. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],exc.what());
  1021. returnValue = 1;
  1022. } catch ( ... ) {
  1023. fprintf(stderr,"%s: fatal error: unknown exception"ZT_EOL_S,argv[0]);
  1024. returnValue = 1;
  1025. }
  1026. delete zt1Service;
  1027. zt1Service = (OneService *)0;
  1028. delete controller;
  1029. #ifdef __UNIX_LIKE__
  1030. OSUtils::rm(pidPath.c_str());
  1031. #endif
  1032. return returnValue;
  1033. }