2
0

main.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. // Uncomment on Windows to assume -C and run in console instead of service
  28. // Useful for Visual Studio debugging (launch VS as Administrator to run)
  29. //#define ZT_WIN_RUN_IN_CONSOLE
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <time.h>
  34. #include <errno.h>
  35. #include <string>
  36. #include <stdexcept>
  37. #include "node/Constants.hpp"
  38. #ifdef __WINDOWS__
  39. #include <WinSock2.h>
  40. #include <Windows.h>
  41. #include <tchar.h>
  42. #include <wchar.h>
  43. #include <lmcons.h>
  44. #include <newdev.h>
  45. #include <atlbase.h>
  46. #include "windows/ZeroTierOne/ServiceInstaller.h"
  47. #include "windows/ZeroTierOne/ServiceBase.h"
  48. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  49. #else
  50. #include <unistd.h>
  51. #include <pwd.h>
  52. #include <fcntl.h>
  53. #include <sys/types.h>
  54. #include <sys/stat.h>
  55. #include <signal.h>
  56. #endif
  57. #include "node/Constants.hpp"
  58. #include "node/Defaults.hpp"
  59. #include "node/Utils.hpp"
  60. #include "node/Node.hpp"
  61. #include "node/C25519.hpp"
  62. #include "node/Identity.hpp"
  63. #include "node/Thread.hpp"
  64. #include "node/CertificateOfMembership.hpp"
  65. #include "node/EthernetTapFactory.hpp"
  66. #include "node/RoutingTable.hpp"
  67. #include "node/SocketManager.hpp"
  68. #include "control/NodeControlClient.hpp"
  69. #include "control/NodeControlService.hpp"
  70. #include "osnet/NativeSocketManager.hpp"
  71. #ifdef ZT_ENABLE_NETCONF_MASTER
  72. #include "netconf/SqliteNetworkConfigMaster.hpp"
  73. #endif // ZT_ENABLE_NETCONF_MASTER
  74. #ifdef __WINDOWS__
  75. #include "osnet/WindowsEthernetTapFactory.hpp"
  76. #include "osnet/WindowsRoutingTable.hpp"
  77. #define ZTCreatePlatformEthernetTapFactory (new WindowsEthernetTapFactory(homeDir))
  78. #define ZTCreatePlatformRoutingTable (new WindowsRoutingTable())
  79. #endif // __WINDOWS__
  80. #ifdef __LINUX__
  81. #include "osnet/LinuxEthernetTapFactory.hpp"
  82. #include "osnet/LinuxRoutingTable.hpp"
  83. #define ZTCreatePlatformEthernetTapFactory (new LinuxEthernetTapFactory())
  84. #define ZTCreatePlatformRoutingTable (new LinuxRoutingTable())
  85. #endif // __LINUX__
  86. #ifdef __APPLE__
  87. #include "osnet/OSXEthernetTapFactory.hpp"
  88. #include "osnet/BSDRoutingTable.hpp"
  89. #define ZTCreatePlatformEthernetTapFactory (new OSXEthernetTapFactory(homeDir,"tap.kext"))
  90. #define ZTCreatePlatformRoutingTable (new BSDRoutingTable())
  91. #endif // __APPLE__
  92. #ifndef ZTCreatePlatformEthernetTapFactory
  93. #ifdef __BSD__
  94. #include "osnet/BSDEthernetTapFactory.hpp"
  95. #include "osnet/BSDRoutingTable.hpp"
  96. #define ZTCreatePlatformEthernetTapFactory (new BSDEthernetTapFactory())
  97. #define ZTCreatePlatformRoutingTable (new BSDRoutingTable())
  98. #else
  99. #error Sorry, this platform has no osnet/ implementation yet. Fork me on GitHub and add one?
  100. #endif // __BSD__
  101. #endif // ZTCreatePlatformEthernetTapFactory
  102. using namespace ZeroTier;
  103. static Node *node = (Node *)0;
  104. namespace ZeroTierCLI { // ---------------------------------------------------
  105. static void printHelp(FILE *out,const char *cn)
  106. {
  107. fprintf(out,"Usage: %s <command> (use 'help' for help)"ZT_EOL_S,cn);
  108. }
  109. static void _CBresultHandler(void *arg,const char *line)
  110. {
  111. if (line) {
  112. if ((line[0] == '.')&&(line[1] == (char)0)) {
  113. fflush(stdout);
  114. ::exit(0); // terminate CLI on end of message
  115. } else {
  116. fprintf(stdout,"%s"ZT_EOL_S,line);
  117. }
  118. }
  119. }
  120. #ifdef __WINDOWS__
  121. static int main(const char *homeDir,int argc,_TCHAR* argv[])
  122. #else
  123. static int main(const char *homeDir,int argc,char **argv)
  124. #endif
  125. {
  126. if (argc < 2) {
  127. printHelp(stdout,argv[0]);
  128. return 1;
  129. }
  130. std::string query;
  131. for(int i=1;i<argc;++i) {
  132. if (argv[i][0] == '-') {
  133. switch(argv[i][1]) {
  134. case 'q': // ignore -q since it's used to invoke this
  135. break;
  136. case 'h':
  137. default:
  138. printHelp(stdout,argv[0]);
  139. return 1;
  140. }
  141. } else if ((!homeDir)||(strcmp(homeDir,argv[i]))) {
  142. if (query.length())
  143. query.push_back(' ');
  144. query.append(argv[i]);
  145. }
  146. }
  147. if (!query.length()) {
  148. printHelp(stdout,argv[0]);
  149. return 1;
  150. }
  151. if (!homeDir)
  152. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  153. try {
  154. std::string buf;
  155. if (!Utils::readFile((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),buf)) {
  156. fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
  157. return 1;
  158. }
  159. Identity id;
  160. if (!id.fromString(buf)) {
  161. fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
  162. return 1;
  163. }
  164. std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),false));
  165. if (!authToken.length())
  166. authToken = NodeControlClient::getAuthToken(NodeControlClient::authTokenDefaultUserPath(),false);
  167. if (!authToken.length()) {
  168. fprintf(stderr,"%s: fatal error: unable to read authentication token from home path or user home"ZT_EOL_S,argv[0]);
  169. return 1;
  170. }
  171. NodeControlClient client((std::string(ZT_IPC_ENDPOINT_BASE) + id.address().toString()).c_str(),authToken.c_str(),&_CBresultHandler,(void *)0);
  172. const char *err = client.error();
  173. if (err) {
  174. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],err);
  175. return 1;
  176. }
  177. client.send(query.c_str());
  178. for(;;) { Thread::sleep(60000); } // exit() is called at end of message from handler
  179. } catch (std::exception &exc) {
  180. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],exc.what());
  181. return 1;
  182. } catch ( ... ) {
  183. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (unknown exception)"ZT_EOL_S,argv[0]);
  184. return 1;
  185. }
  186. return 0;
  187. }
  188. } // namespace ZeroTierCLI ---------------------------------------------------
  189. namespace ZeroTierIdTool { // ------------------------------------------------
  190. static void printHelp(FILE *out,const char *pn)
  191. {
  192. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  193. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  194. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  195. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  196. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  197. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  198. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  199. }
  200. static Identity getIdFromArg(char *arg)
  201. {
  202. Identity id;
  203. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  204. if (id.fromString(arg))
  205. return id;
  206. } else { // identity is to be read from a file
  207. std::string idser;
  208. if (Utils::readFile(arg,idser)) {
  209. if (id.fromString(idser))
  210. return id;
  211. }
  212. }
  213. return Identity();
  214. }
  215. #ifdef __WINDOWS__
  216. static int main(int argc,_TCHAR* argv[])
  217. #else
  218. static int main(int argc,char **argv)
  219. #endif
  220. {
  221. if (argc < 2) {
  222. printHelp(stdout,argv[0]);
  223. return 1;
  224. }
  225. if (!strcmp(argv[1],"generate")) {
  226. Identity id;
  227. id.generate();
  228. std::string idser = id.toString(true);
  229. if (argc >= 3) {
  230. if (!Utils::writeFile(argv[2],idser)) {
  231. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  232. return 1;
  233. } else printf("%s written"ZT_EOL_S,argv[2]);
  234. if (argc >= 4) {
  235. idser = id.toString(false);
  236. if (!Utils::writeFile(argv[3],idser)) {
  237. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  238. return 1;
  239. } else printf("%s written"ZT_EOL_S,argv[3]);
  240. }
  241. } else printf("%s",idser.c_str());
  242. } else if (!strcmp(argv[1],"validate")) {
  243. if (argc < 3) {
  244. printHelp(stdout,argv[0]);
  245. return 1;
  246. }
  247. Identity id = getIdFromArg(argv[2]);
  248. if (!id) {
  249. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  250. return 1;
  251. }
  252. if (!id.locallyValidate()) {
  253. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  254. return 1;
  255. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  256. } else if (!strcmp(argv[1],"getpublic")) {
  257. if (argc < 3) {
  258. printHelp(stdout,argv[0]);
  259. return 1;
  260. }
  261. Identity id = getIdFromArg(argv[2]);
  262. if (!id) {
  263. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  264. return 1;
  265. }
  266. printf("%s",id.toString(false).c_str());
  267. } else if (!strcmp(argv[1],"sign")) {
  268. if (argc < 4) {
  269. printHelp(stdout,argv[0]);
  270. return 1;
  271. }
  272. Identity id = getIdFromArg(argv[2]);
  273. if (!id) {
  274. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  275. return 1;
  276. }
  277. if (!id.hasPrivate()) {
  278. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  279. return 1;
  280. }
  281. std::string inf;
  282. if (!Utils::readFile(argv[3],inf)) {
  283. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  284. return 1;
  285. }
  286. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  287. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  288. } else if (!strcmp(argv[1],"verify")) {
  289. if (argc < 4) {
  290. printHelp(stdout,argv[0]);
  291. return 1;
  292. }
  293. Identity id = getIdFromArg(argv[2]);
  294. if (!id) {
  295. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  296. return 1;
  297. }
  298. std::string inf;
  299. if (!Utils::readFile(argv[3],inf)) {
  300. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  301. return 1;
  302. }
  303. std::string signature(Utils::unhex(argv[4]));
  304. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  305. printf("%s signature valid"ZT_EOL_S,argv[3]);
  306. } else {
  307. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  308. return 1;
  309. }
  310. } else if (!strcmp(argv[1],"mkcom")) {
  311. if (argc < 3) {
  312. printHelp(stdout,argv[0]);
  313. return 1;
  314. }
  315. Identity id = getIdFromArg(argv[2]);
  316. if ((!id)||(!id.hasPrivate())) {
  317. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  318. return 1;
  319. }
  320. CertificateOfMembership com;
  321. for(int a=3;a<argc;++a) {
  322. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  323. if (params.size() == 3) {
  324. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  325. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  326. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  327. com.setQualifier(qId,qValue,qMaxDelta);
  328. }
  329. }
  330. if (!com.sign(id)) {
  331. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  332. return 1;
  333. }
  334. printf("%s",com.toString().c_str());
  335. } else {
  336. printHelp(stdout,argv[0]);
  337. return 1;
  338. }
  339. return 0;
  340. }
  341. } // namespace ZeroTierIdTool ------------------------------------------------
  342. #ifdef __UNIX_LIKE__
  343. static void sighandlerHup(int sig)
  344. {
  345. Node *n = node;
  346. if (n)
  347. n->resync();
  348. }
  349. static void sighandlerQuit(int sig)
  350. {
  351. Node *n = node;
  352. if (n)
  353. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  354. else exit(0);
  355. }
  356. #endif
  357. #ifdef __WINDOWS__
  358. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  359. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  360. {
  361. switch(dwCtrlType) {
  362. case CTRL_C_EVENT:
  363. case CTRL_BREAK_EVENT:
  364. case CTRL_CLOSE_EVENT:
  365. case CTRL_SHUTDOWN_EVENT:
  366. Node *n = node;
  367. if (n)
  368. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  369. return TRUE;
  370. }
  371. return FALSE;
  372. }
  373. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  374. static void _winPokeAHole()
  375. {
  376. char myPath[MAX_PATH];
  377. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  378. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  379. STARTUPINFOA startupInfo;
  380. PROCESS_INFORMATION processInfo;
  381. startupInfo.cb = sizeof(startupInfo);
  382. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  383. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  384. 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)) {
  385. WaitForSingleObject(processInfo.hProcess,INFINITE);
  386. CloseHandle(processInfo.hProcess);
  387. CloseHandle(processInfo.hThread);
  388. }
  389. startupInfo.cb = sizeof(startupInfo);
  390. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  391. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  392. 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)) {
  393. WaitForSingleObject(processInfo.hProcess,INFINITE);
  394. CloseHandle(processInfo.hProcess);
  395. CloseHandle(processInfo.hThread);
  396. }
  397. startupInfo.cb = sizeof(startupInfo);
  398. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  399. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  400. 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)) {
  401. WaitForSingleObject(processInfo.hProcess,INFINITE);
  402. CloseHandle(processInfo.hProcess);
  403. CloseHandle(processInfo.hThread);
  404. }
  405. }
  406. }
  407. // Returns true if this is running as the local administrator
  408. static BOOL IsCurrentUserLocalAdministrator(void)
  409. {
  410. BOOL fReturn = FALSE;
  411. DWORD dwStatus;
  412. DWORD dwAccessMask;
  413. DWORD dwAccessDesired;
  414. DWORD dwACLSize;
  415. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  416. PACL pACL = NULL;
  417. PSID psidAdmin = NULL;
  418. HANDLE hToken = NULL;
  419. HANDLE hImpersonationToken = NULL;
  420. PRIVILEGE_SET ps;
  421. GENERIC_MAPPING GenericMapping;
  422. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  423. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  424. const DWORD ACCESS_READ = 1;
  425. const DWORD ACCESS_WRITE = 2;
  426. __try
  427. {
  428. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  429. {
  430. if (GetLastError() != ERROR_NO_TOKEN)
  431. __leave;
  432. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  433. __leave;
  434. }
  435. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  436. __leave;
  437. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  438. SECURITY_BUILTIN_DOMAIN_RID,
  439. DOMAIN_ALIAS_RID_ADMINS,
  440. 0, 0, 0, 0, 0, 0, &psidAdmin))
  441. __leave;
  442. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  443. if (psdAdmin == NULL)
  444. __leave;
  445. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  446. __leave;
  447. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  448. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  449. if (pACL == NULL)
  450. __leave;
  451. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  452. __leave;
  453. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  454. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  455. __leave;
  456. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  457. __leave;
  458. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  459. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  460. if (!IsValidSecurityDescriptor(psdAdmin))
  461. __leave;
  462. dwAccessDesired = ACCESS_READ;
  463. GenericMapping.GenericRead = ACCESS_READ;
  464. GenericMapping.GenericWrite = ACCESS_WRITE;
  465. GenericMapping.GenericExecute = 0;
  466. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  467. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  468. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  469. &fReturn))
  470. {
  471. fReturn = FALSE;
  472. __leave;
  473. }
  474. }
  475. __finally
  476. {
  477. // Clean up.
  478. if (pACL) LocalFree(pACL);
  479. if (psdAdmin) LocalFree(psdAdmin);
  480. if (psidAdmin) FreeSid(psidAdmin);
  481. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  482. if (hToken) CloseHandle (hToken);
  483. }
  484. return fReturn;
  485. }
  486. #endif // __WINDOWS__
  487. // ---------------------------------------------------------------------------
  488. static void printHelp(const char *cn,FILE *out)
  489. {
  490. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2014 ZeroTier Networks LLC"ZT_EOL_S,Node::versionMajor(),Node::versionMinor(),Node::versionRevision());
  491. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  492. #ifdef ZT_AUTO_UPDATE
  493. fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
  494. fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  495. fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
  496. int no = 0;
  497. for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
  498. if (no == 0)
  499. fprintf(out," %s",sa->first.toString().c_str());
  500. else fprintf(out,", %s",sa->first.toString().c_str());
  501. if (++no == 6) {
  502. fprintf(out,ZT_EOL_S);
  503. no = 0;
  504. }
  505. }
  506. fprintf(out,ZT_EOL_S""ZT_EOL_S);
  507. #else
  508. fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
  509. #endif
  510. fprintf(out,"Usage: %s [-switches] [home directory] [-q <query>]"ZT_EOL_S""ZT_EOL_S,cn);
  511. fprintf(out,"Available switches:"ZT_EOL_S);
  512. fprintf(out," -h - Display this help"ZT_EOL_S);
  513. fprintf(out," -v - Show version"ZT_EOL_S);
  514. fprintf(out," -p<port> - Port for UDP (default: 9993)"ZT_EOL_S);
  515. fprintf(out," -t<port> - Port for TCP (default: disabled)"ZT_EOL_S);
  516. //fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
  517. #ifdef __UNIX_LIKE__
  518. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  519. #endif
  520. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  521. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  522. #ifdef __WINDOWS__
  523. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  524. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  525. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  526. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  527. #endif
  528. }
  529. #ifdef __WINDOWS__
  530. int _tmain(int argc, _TCHAR* argv[])
  531. #else
  532. int main(int argc,char **argv)
  533. #endif
  534. {
  535. #ifdef __UNIX_LIKE__
  536. signal(SIGHUP,&sighandlerHup);
  537. signal(SIGPIPE,SIG_IGN);
  538. signal(SIGUSR1,SIG_IGN);
  539. signal(SIGUSR2,SIG_IGN);
  540. signal(SIGALRM,SIG_IGN);
  541. signal(SIGINT,&sighandlerQuit);
  542. signal(SIGTERM,&sighandlerQuit);
  543. signal(SIGQUIT,&sighandlerQuit);
  544. /* Ensure that there are no inherited file descriptors open from a previous
  545. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  546. * of it do not return, and should not do anything otherwise bad. */
  547. {
  548. int mfd = STDIN_FILENO;
  549. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  550. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  551. for(int f=mfd+1;f<1024;++f)
  552. ::close(f);
  553. }
  554. #endif
  555. #ifdef __WINDOWS__
  556. WSADATA wsaData;
  557. WSAStartup(MAKEWORD(2,2),&wsaData);
  558. #endif
  559. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  560. return ZeroTierCLI::main((const char *)0,argc,argv);
  561. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  562. return ZeroTierIdTool::main(argc,argv);
  563. const char *homeDir = (const char *)0;
  564. unsigned int udpPort = ZT_DEFAULT_UDP_PORT;
  565. unsigned int tcpPort = 0;
  566. std::string overrideRootTopology;
  567. #ifdef __UNIX_LIKE__
  568. bool runAsDaemon = false;
  569. #endif
  570. #ifdef __WINDOWS__
  571. #ifdef ZT_WIN_RUN_IN_CONSOLE
  572. bool winRunFromCommandLine = true;
  573. #else
  574. bool winRunFromCommandLine = false;
  575. #endif
  576. #endif // __WINDOWS__
  577. for(int i=1;i<argc;++i) {
  578. if (argv[i][0] == '-') {
  579. switch(argv[i][1]) {
  580. case 'p':
  581. udpPort = Utils::strToUInt(argv[i] + 2);
  582. if (udpPort > 65535) {
  583. printHelp(argv[0],stdout);
  584. return 1;
  585. }
  586. break;
  587. case 't':
  588. tcpPort = Utils::strToUInt(argv[i] + 2);
  589. if (tcpPort > 65535) {
  590. printHelp(argv[0],stdout);
  591. return 1;
  592. }
  593. break;
  594. #ifdef __UNIX_LIKE__
  595. case 'd':
  596. runAsDaemon = true;
  597. break;
  598. #endif
  599. case 'T':
  600. if (argv[i][2]) {
  601. if (!Utils::readFile(argv[i] + 2,overrideRootTopology)) {
  602. fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
  603. return 1;
  604. }
  605. } else {
  606. printHelp(argv[0],stdout);
  607. return 1;
  608. }
  609. break;
  610. case 'v':
  611. printf("%s"ZT_EOL_S,Node::versionString());
  612. return 0;
  613. case 'q':
  614. if (argv[i][2]) {
  615. printHelp(argv[0],stdout);
  616. return 0;
  617. } else return ZeroTierCLI::main(homeDir,argc,argv);
  618. case 'i':
  619. if (argv[i][2]) {
  620. printHelp(argv[0],stdout);
  621. return 0;
  622. } else return ZeroTierIdTool::main(argc,argv);
  623. #ifdef __WINDOWS__
  624. case 'C':
  625. winRunFromCommandLine = true;
  626. break;
  627. case 'I': { // install self as service
  628. if (IsCurrentUserLocalAdministrator() != TRUE) {
  629. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  630. return 1;
  631. }
  632. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  633. if (ret.length()) {
  634. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  635. return 3;
  636. }
  637. return 0;
  638. } break;
  639. case 'R': { // uninstall self as service
  640. if (IsCurrentUserLocalAdministrator() != TRUE) {
  641. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  642. return 1;
  643. }
  644. std::string ret(UninstallService(ZT_SERVICE_NAME));
  645. if (ret.length()) {
  646. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  647. return 3;
  648. }
  649. return 0;
  650. } break;
  651. case 'D': { // install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  652. std::string pathToInf;
  653. #ifdef _WIN64
  654. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  655. #else
  656. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  657. #endif
  658. 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);
  659. BOOL needReboot = FALSE;
  660. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  661. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  662. return 0;
  663. } else {
  664. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  665. return 3;
  666. }
  667. } break;
  668. #endif // __WINDOWS__
  669. case 'h':
  670. case '?':
  671. default:
  672. printHelp(argv[0],stdout);
  673. return 0;
  674. }
  675. } else {
  676. if (homeDir) {
  677. printHelp(argv[0],stdout);
  678. return 0;
  679. } else homeDir = argv[i];
  680. }
  681. }
  682. if ((!homeDir)||(strlen(homeDir) == 0))
  683. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  684. #ifdef __UNIX_LIKE__
  685. if (getuid() != 0) {
  686. fprintf(stderr,"%s: must be run as root (uid 0)\n",argv[0]);
  687. return 1;
  688. }
  689. if (runAsDaemon) {
  690. long p = (long)fork();
  691. if (p < 0) {
  692. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  693. return 1;
  694. } else if (p > 0)
  695. return 0; // forked
  696. // else p == 0, so we are daemonized
  697. }
  698. mkdir(homeDir,0755); // will fail if it already exists, but that's fine
  699. {
  700. // Write .pid file to home folder
  701. char pidpath[4096];
  702. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  703. FILE *pf = fopen(pidpath,"w");
  704. if (pf) {
  705. fprintf(pf,"%ld",(long)getpid());
  706. fclose(pf);
  707. }
  708. }
  709. #endif // __UNIX_LIKE__
  710. #ifdef __WINDOWS__
  711. if (winRunFromCommandLine) {
  712. // Running in "interactive" mode (mostly for debugging)
  713. if (IsCurrentUserLocalAdministrator() != TRUE) {
  714. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  715. return 1;
  716. }
  717. _winPokeAHole();
  718. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  719. // continues on to ordinary command line execution code below...
  720. } else {
  721. // Running from service manager
  722. _winPokeAHole();
  723. ZeroTierOneService zt1Service;
  724. if (CServiceBase::Run(zt1Service) == TRUE) {
  725. return 0;
  726. } else {
  727. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  728. return 1;
  729. }
  730. }
  731. #endif // __WINDOWS__
  732. int exitCode = 0;
  733. bool needsReset = false;
  734. EthernetTapFactory *tapFactory = (EthernetTapFactory *)0;
  735. RoutingTable *routingTable = (RoutingTable *)0;
  736. SocketManager *socketManager = (SocketManager *)0;
  737. NodeControlService *controlService = (NodeControlService *)0;
  738. NetworkConfigMaster *netconfMaster = (NetworkConfigMaster *)0;
  739. try {
  740. // Get or create authtoken.secret -- note that if this fails, authentication
  741. // will always fail since an empty auth token won't work. This should always
  742. // succeed unless something is wrong with the filesystem.
  743. std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),true));
  744. tapFactory = ZTCreatePlatformEthernetTapFactory;
  745. routingTable = ZTCreatePlatformRoutingTable;
  746. try {
  747. socketManager = new NativeSocketManager(udpPort,tcpPort);
  748. } catch ( ... ) {
  749. fprintf(stderr,"%s: unable to bind to port: %u/UDP, %u/TCP (0 == disabled)"ZT_EOL_S,argv[0],udpPort,tcpPort);
  750. throw;
  751. }
  752. node = new Node(homeDir,tapFactory,routingTable,socketManager,netconfMaster,needsReset,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
  753. controlService = new NodeControlService(node,authToken.c_str());
  754. switch(node->run()) {
  755. #ifdef __WINDOWS__
  756. case Node::NODE_RESTART_FOR_UPGRADE: {
  757. const char *upgPath = node->terminationMessage();
  758. if (upgPath) {
  759. if (!ZeroTierOneService::doStartUpgrade(std::string(upgPath))) {
  760. exitCode = 3;
  761. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (doStartUpgrade failed)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  762. }
  763. } else {
  764. exitCode = 3;
  765. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (no upgrade path provided)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  766. }
  767. } break;
  768. #else // __UNIX_LIKE__
  769. case Node::NODE_RESTART_FOR_UPGRADE: {
  770. const char *upgPath = node->terminationMessage();
  771. // On Unix-type OSes we exec() right into the upgrade. This in turn will
  772. // end with us being re-launched either via the upgrade itself or something
  773. // like OSX's launchd.
  774. if (upgPath) {
  775. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  776. std::string updateLogPath(homeDir);
  777. updateLogPath.append("/autoupdate.log");
  778. Utils::rm(updateLogPath.c_str());
  779. Utils::redirectUnixOutputs(updateLogPath.c_str(),(const char *)0);
  780. ::execl(upgPath,upgPath,(char *)0);
  781. }
  782. exitCode = 3;
  783. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  784. } break;
  785. #endif // __WINDOWS__ / __UNIX_LIKE__
  786. case Node::NODE_UNRECOVERABLE_ERROR: {
  787. exitCode = 3;
  788. const char *termReason = node->terminationMessage();
  789. fprintf(stderr,"%s: abnormal termination: %s"ZT_EOL_S,argv[0],(termReason) ? termReason : "(unknown reason)");
  790. } break;
  791. default:
  792. break;
  793. }
  794. } catch ( std::exception &exc ) {
  795. fprintf(stderr,"%s: unexpected exception: %s"ZT_EOL_S,argv[0],exc.what());
  796. exitCode = 3;
  797. } catch ( ... ) {
  798. fprintf(stderr,"%s: unexpected exception: unknown exception"ZT_EOL_S,argv[0]);
  799. exitCode = 3;
  800. }
  801. delete controlService;
  802. delete node; node = (Node *)0;
  803. delete socketManager;
  804. delete routingTable;
  805. delete tapFactory;
  806. #ifdef __UNIX_LIKE__
  807. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  808. #endif
  809. return exitCode;
  810. }