one.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <stdint.h>
  30. #include <time.h>
  31. #include <errno.h>
  32. #include "node/Constants.hpp"
  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 "osdep/WindowsEthernetTap.hpp"
  42. #include "windows/ZeroTierOne/ServiceInstaller.h"
  43. #include "windows/ZeroTierOne/ServiceBase.h"
  44. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  45. #else
  46. #include <unistd.h>
  47. #include <pwd.h>
  48. #include <fcntl.h>
  49. #include <sys/types.h>
  50. #include <sys/stat.h>
  51. #include <sys/uio.h>
  52. #include <dirent.h>
  53. #include <signal.h>
  54. #ifdef __LINUX__
  55. #include <sys/prctl.h>
  56. #include <sys/syscall.h>
  57. #include <sys/wait.h>
  58. #include <linux/capability.h>
  59. #include <linux/securebits.h>
  60. #endif
  61. #endif
  62. #include <string>
  63. #include <stdexcept>
  64. #include <iostream>
  65. #include <sstream>
  66. #include "version.h"
  67. #include "include/ZeroTierOne.h"
  68. #include "node/Identity.hpp"
  69. #include "node/CertificateOfMembership.hpp"
  70. #include "node/Utils.hpp"
  71. #include "node/NetworkController.hpp"
  72. #include "node/Buffer.hpp"
  73. #include "node/World.hpp"
  74. #include "osdep/OSUtils.hpp"
  75. #include "osdep/Http.hpp"
  76. #include "osdep/Thread.hpp"
  77. #include "service/OneService.hpp"
  78. #include "ext/json/json.hpp"
  79. #define ZT_PID_PATH "zerotier-one.pid"
  80. using namespace ZeroTier;
  81. static OneService *volatile zt1Service = (OneService *)0;
  82. #define PROGRAM_NAME "ZeroTier One"
  83. #define COPYRIGHT_NOTICE "Copyright (c) 2011-2018 ZeroTier, Inc."
  84. #define LICENSE_GRANT \
  85. "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
  86. "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
  87. "later as published by the Free Software Foundation." ZT_EOL_S \
  88. "No warranty expressed or implied." ZT_EOL_S
  89. /****************************************************************************/
  90. /* zerotier-cli personality */
  91. /****************************************************************************/
  92. // This is getting deprecated soon in favor of the stuff in cli/
  93. static void cliPrintHelp(const char *pn,FILE *out)
  94. {
  95. fprintf(out,
  96. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  97. PROGRAM_NAME,
  98. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  99. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  100. fprintf(out,
  101. COPYRIGHT_NOTICE ZT_EOL_S
  102. LICENSE_GRANT ZT_EOL_S);
  103. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  104. fprintf(out,"Available switches:" ZT_EOL_S);
  105. fprintf(out," -h - Display this help" ZT_EOL_S);
  106. fprintf(out," -v - Show version" ZT_EOL_S);
  107. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  108. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  109. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  110. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  111. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  112. fprintf(out," info - Display status info" ZT_EOL_S);
  113. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  114. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  115. fprintf(out," join <network> - Join a network" ZT_EOL_S);
  116. fprintf(out," leave <network> - Leave a network" ZT_EOL_S);
  117. fprintf(out," set <network> <setting> - Set a network setting" ZT_EOL_S);
  118. fprintf(out," get <network> <setting> - Get a network setting" ZT_EOL_S);
  119. fprintf(out," listmoons - List moons (federated root sets)" ZT_EOL_S);
  120. fprintf(out," orbit <world ID> <seed> - Join a moon via any member root" ZT_EOL_S);
  121. fprintf(out," deorbit <world ID> - Leave a moon" ZT_EOL_S);
  122. }
  123. static std::string cliFixJsonCRs(const std::string &s)
  124. {
  125. std::string r;
  126. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  127. if (*c == '\n')
  128. r.append(ZT_EOL_S);
  129. else r.push_back(*c);
  130. }
  131. return r;
  132. }
  133. #ifdef __WINDOWS__
  134. static int cli(int argc, _TCHAR* argv[])
  135. #else
  136. static int cli(int argc,char **argv)
  137. #endif
  138. {
  139. unsigned int port = 0;
  140. std::string homeDir,command,arg1,arg2,authToken;
  141. std::string ip("127.0.0.1");
  142. bool json = false;
  143. for(int i=1;i<argc;++i) {
  144. if (argv[i][0] == '-') {
  145. switch(argv[i][1]) {
  146. case 'q': // ignore -q used to invoke this personality
  147. if (argv[i][2]) {
  148. cliPrintHelp(argv[0],stdout);
  149. return 1;
  150. }
  151. break;
  152. case 'j':
  153. if (argv[i][2]) {
  154. cliPrintHelp(argv[0],stdout);
  155. return 1;
  156. }
  157. json = true;
  158. break;
  159. case 'p':
  160. port = Utils::strToUInt(argv[i] + 2);
  161. if ((port > 0xffff)||(port == 0)) {
  162. cliPrintHelp(argv[0],stdout);
  163. return 1;
  164. }
  165. break;
  166. case 'D':
  167. if (argv[i][2]) {
  168. homeDir = argv[i] + 2;
  169. } else {
  170. cliPrintHelp(argv[0],stdout);
  171. return 1;
  172. }
  173. break;
  174. case 'H':
  175. if (argv[i][2]) {
  176. ip = argv[i] + 2;
  177. } else {
  178. cliPrintHelp(argv[0],stdout);
  179. return 1;
  180. }
  181. break;
  182. case 'T':
  183. if (argv[i][2]) {
  184. authToken = argv[i] + 2;
  185. } else {
  186. cliPrintHelp(argv[0],stdout);
  187. return 1;
  188. }
  189. break;
  190. case 'v':
  191. if (argv[i][2]) {
  192. cliPrintHelp(argv[0],stdout);
  193. return 1;
  194. }
  195. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  196. return 0;
  197. case 'h':
  198. case '?':
  199. default:
  200. cliPrintHelp(argv[0],stdout);
  201. return 0;
  202. }
  203. } else {
  204. if (arg1.length())
  205. arg2 = argv[i];
  206. else if (command.length())
  207. arg1 = argv[i];
  208. else command = argv[i];
  209. }
  210. }
  211. if (!homeDir.length())
  212. homeDir = OneService::platformDefaultHomePath();
  213. if ((!port)||(!authToken.length())) {
  214. if (!homeDir.length()) {
  215. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  216. return 2;
  217. }
  218. if (!port) {
  219. std::string portStr;
  220. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  221. port = Utils::strToUInt(portStr.c_str());
  222. if ((port == 0)||(port > 0xffff)) {
  223. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  224. return 2;
  225. }
  226. }
  227. if (!authToken.length()) {
  228. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  229. #ifdef __UNIX_LIKE__
  230. if (!authToken.length()) {
  231. const char *hd = getenv("HOME");
  232. if (hd) {
  233. char p[4096];
  234. #ifdef __APPLE__
  235. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  236. #else
  237. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  238. #endif
  239. OSUtils::readFile(p,authToken);
  240. }
  241. }
  242. #endif
  243. if (!authToken.length()) {
  244. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  245. return 2;
  246. }
  247. }
  248. }
  249. InetAddress addr;
  250. {
  251. char addrtmp[256];
  252. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  253. addr = InetAddress(addrtmp);
  254. }
  255. std::map<std::string,std::string> requestHeaders;
  256. std::map<std::string,std::string> responseHeaders;
  257. std::string responseBody;
  258. requestHeaders["X-ZT1-Auth"] = authToken;
  259. if ((command.length() > 0)&&(command[0] == '/')) {
  260. unsigned int scode = Http::GET(
  261. 1024 * 1024 * 16,
  262. 60000,
  263. (const struct sockaddr *)&addr,
  264. command.c_str(),
  265. requestHeaders,
  266. responseHeaders,
  267. responseBody);
  268. if (scode == 200) {
  269. printf("%s", cliFixJsonCRs(responseBody).c_str());
  270. return 0;
  271. } else {
  272. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  273. return 1;
  274. }
  275. } else if ((command == "info")||(command == "status")) {
  276. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  277. if (scode == 0) {
  278. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  279. return 1;
  280. }
  281. nlohmann::json j;
  282. try {
  283. j = OSUtils::jsonParse(responseBody);
  284. } catch (std::exception &exc) {
  285. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  286. return 1;
  287. } catch ( ... ) {
  288. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  289. return 1;
  290. }
  291. if (scode == 200) {
  292. if (json) {
  293. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  294. } else {
  295. if (j.is_object()) {
  296. printf("200 info %s %s %s" ZT_EOL_S,
  297. OSUtils::jsonString(j["address"],"-").c_str(),
  298. OSUtils::jsonString(j["version"],"-").c_str(),
  299. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  300. }
  301. }
  302. return 0;
  303. } else {
  304. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  305. return 1;
  306. }
  307. } else if (command == "listpeers") {
  308. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  309. if (scode == 0) {
  310. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  311. return 1;
  312. }
  313. nlohmann::json j;
  314. try {
  315. j = OSUtils::jsonParse(responseBody);
  316. } catch (std::exception &exc) {
  317. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  318. return 1;
  319. } catch ( ... ) {
  320. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  321. return 1;
  322. }
  323. if (scode == 200) {
  324. if (json) {
  325. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  326. } else {
  327. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  328. if (j.is_array()) {
  329. for(unsigned long k=0;k<j.size();++k) {
  330. nlohmann::json &p = j[k];
  331. std::string bestPath;
  332. nlohmann::json &paths = p["paths"];
  333. if (paths.is_array()) {
  334. for(unsigned long i=0;i<paths.size();++i) {
  335. nlohmann::json &path = paths[i];
  336. if (path["preferred"]) {
  337. char tmp[256];
  338. std::string addr = path["address"];
  339. const int64_t now = OSUtils::now();
  340. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  341. bestPath = tmp;
  342. break;
  343. }
  344. }
  345. }
  346. if (bestPath.length() == 0) bestPath = "-";
  347. char ver[128];
  348. int64_t vmaj = p["versionMajor"];
  349. int64_t vmin = p["versionMinor"];
  350. int64_t vrev = p["versionRev"];
  351. if (vmaj >= 0) {
  352. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  353. } else {
  354. ver[0] = '-';
  355. ver[1] = (char)0;
  356. }
  357. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  358. OSUtils::jsonString(p["address"],"-").c_str(),
  359. bestPath.c_str(),
  360. (int)OSUtils::jsonInt(p["latency"],0),
  361. ver,
  362. OSUtils::jsonString(p["role"],"-").c_str());
  363. }
  364. }
  365. }
  366. return 0;
  367. } else {
  368. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  369. return 1;
  370. }
  371. } else if (command == "listnetworks") {
  372. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  373. if (scode == 0) {
  374. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  375. return 1;
  376. }
  377. nlohmann::json j;
  378. try {
  379. j = OSUtils::jsonParse(responseBody);
  380. } catch (std::exception &exc) {
  381. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  382. return 1;
  383. } catch ( ... ) {
  384. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  385. return 1;
  386. }
  387. if (scode == 200) {
  388. if (json) {
  389. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  390. } else {
  391. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  392. if (j.is_array()) {
  393. for(unsigned long i=0;i<j.size();++i) {
  394. nlohmann::json &n = j[i];
  395. if (n.is_object()) {
  396. std::string aa;
  397. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  398. if (assignedAddresses.is_array()) {
  399. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  400. nlohmann::json &addr = assignedAddresses[j];
  401. if (addr.is_string()) {
  402. if (aa.length() > 0) aa.push_back(',');
  403. aa.append(addr.get<std::string>());
  404. }
  405. }
  406. }
  407. if (aa.length() == 0) aa = "-";
  408. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  409. OSUtils::jsonString(n["nwid"],"-").c_str(),
  410. OSUtils::jsonString(n["name"],"-").c_str(),
  411. OSUtils::jsonString(n["mac"],"-").c_str(),
  412. OSUtils::jsonString(n["status"],"-").c_str(),
  413. OSUtils::jsonString(n["type"],"-").c_str(),
  414. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  415. aa.c_str());
  416. }
  417. }
  418. }
  419. }
  420. return 0;
  421. } else {
  422. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  423. return 1;
  424. }
  425. } else if (command == "join") {
  426. if (arg1.length() != 16) {
  427. printf("invalid network id" ZT_EOL_S);
  428. return 2;
  429. }
  430. requestHeaders["Content-Type"] = "application/json";
  431. requestHeaders["Content-Length"] = "2";
  432. unsigned int scode = Http::POST(
  433. 1024 * 1024 * 16,
  434. 60000,
  435. (const struct sockaddr *)&addr,
  436. (std::string("/network/") + arg1).c_str(),
  437. requestHeaders,
  438. "{}",
  439. 2,
  440. responseHeaders,
  441. responseBody);
  442. if (scode == 200) {
  443. if (json) {
  444. printf("%s",cliFixJsonCRs(responseBody).c_str());
  445. } else {
  446. printf("200 join OK" ZT_EOL_S);
  447. }
  448. return 0;
  449. } else {
  450. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  451. return 1;
  452. }
  453. } else if (command == "leave") {
  454. if (arg1.length() != 16) {
  455. printf("invalid network id" ZT_EOL_S);
  456. return 2;
  457. }
  458. unsigned int scode = Http::DEL(
  459. 1024 * 1024 * 16,
  460. 60000,
  461. (const struct sockaddr *)&addr,
  462. (std::string("/network/") + arg1).c_str(),
  463. requestHeaders,
  464. responseHeaders,
  465. responseBody);
  466. if (scode == 200) {
  467. if (json) {
  468. printf("%s",cliFixJsonCRs(responseBody).c_str());
  469. } else {
  470. printf("200 leave OK" ZT_EOL_S);
  471. }
  472. return 0;
  473. } else {
  474. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  475. return 1;
  476. }
  477. } else if (command == "listmoons") {
  478. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/moon",requestHeaders,responseHeaders,responseBody);
  479. if (scode == 0) {
  480. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  481. return 1;
  482. }
  483. nlohmann::json j;
  484. try {
  485. j = OSUtils::jsonParse(responseBody);
  486. } catch (std::exception &exc) {
  487. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  488. return 1;
  489. } catch ( ... ) {
  490. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  491. return 1;
  492. }
  493. if (scode == 200) {
  494. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  495. return 0;
  496. } else {
  497. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  498. return 1;
  499. }
  500. } else if (command == "orbit") {
  501. const uint64_t worldId = Utils::hexStrToU64(arg1.c_str());
  502. const uint64_t seed = Utils::hexStrToU64(arg2.c_str());
  503. if ((worldId)&&(seed)) {
  504. char jsons[1024];
  505. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  506. char cl[128];
  507. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  508. requestHeaders["Content-Type"] = "application/json";
  509. requestHeaders["Content-Length"] = cl;
  510. unsigned int scode = Http::POST(
  511. 1024 * 1024 * 16,
  512. 60000,
  513. (const struct sockaddr *)&addr,
  514. (std::string("/moon/") + arg1).c_str(),
  515. requestHeaders,
  516. jsons,
  517. (unsigned long)strlen(jsons),
  518. responseHeaders,
  519. responseBody);
  520. if (scode == 200) {
  521. printf("200 orbit OK" ZT_EOL_S);
  522. return 0;
  523. } else {
  524. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  525. return 1;
  526. }
  527. }
  528. } else if (command == "deorbit") {
  529. unsigned int scode = Http::DEL(
  530. 1024 * 1024 * 16,
  531. 60000,
  532. (const struct sockaddr *)&addr,
  533. (std::string("/moon/") + arg1).c_str(),
  534. requestHeaders,
  535. responseHeaders,
  536. responseBody);
  537. if (scode == 200) {
  538. if (json) {
  539. printf("%s",cliFixJsonCRs(responseBody).c_str());
  540. } else {
  541. printf("200 deorbit OK" ZT_EOL_S);
  542. }
  543. return 0;
  544. } else {
  545. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  546. return 1;
  547. }
  548. } else if (command == "set") {
  549. if (arg1.length() != 16) {
  550. printf("invalid network id" ZT_EOL_S);
  551. return 2;
  552. }
  553. std::size_t eqidx = arg2.find('=');
  554. if (eqidx != std::string::npos) {
  555. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  556. char jsons[1024];
  557. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  558. arg2.substr(0,eqidx).c_str(),
  559. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  560. char cl[128];
  561. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  562. requestHeaders["Content-Type"] = "application/json";
  563. requestHeaders["Content-Length"] = cl;
  564. unsigned int scode = Http::POST(
  565. 1024 * 1024 * 16,
  566. 60000,
  567. (const struct sockaddr *)&addr,
  568. (std::string("/network/") + arg1).c_str(),
  569. requestHeaders,
  570. jsons,
  571. (unsigned long)strlen(jsons),
  572. responseHeaders,
  573. responseBody);
  574. if (scode == 200) {
  575. printf("%s",cliFixJsonCRs(responseBody).c_str());
  576. return 0;
  577. } else {
  578. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  579. return 1;
  580. }
  581. }
  582. } else {
  583. cliPrintHelp(argv[0],stderr);
  584. return 2;
  585. }
  586. } else if (command == "get") {
  587. if (arg1.length() != 16) {
  588. fprintf(stderr,"invalid network ID format, must be a 16-digit hexidecimal number\n");
  589. return 2;
  590. }
  591. char jsons[1024], cl[128];
  592. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  593. requestHeaders["Content-Type"] = "application/json";
  594. requestHeaders["Content-Length"] = cl;
  595. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  596. if (scode == 0) {
  597. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  598. return 1;
  599. }
  600. nlohmann::json j;
  601. try {
  602. j = OSUtils::jsonParse(responseBody);
  603. } catch (std::exception &exc) {
  604. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  605. return 1;
  606. } catch ( ... ) {
  607. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  608. return 1;
  609. }
  610. bool bNetworkFound = false;
  611. if (j.is_array()) {
  612. for(unsigned long i=0;i<j.size();++i) {
  613. nlohmann::json &n = j[i];
  614. if (n.is_object()) {
  615. if (n["id"] == arg1) {
  616. printf("%s\n", OSUtils::jsonString(n[arg2],"-").c_str());
  617. bNetworkFound = true;
  618. }
  619. }
  620. }
  621. }
  622. if (!bNetworkFound) {
  623. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  624. }
  625. if (scode == 200) {
  626. return 0;
  627. } else {
  628. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  629. return 1;
  630. }
  631. } else {
  632. cliPrintHelp(argv[0],stderr);
  633. return 0;
  634. }
  635. return 0;
  636. }
  637. /****************************************************************************/
  638. /* zerotier-idtool personality */
  639. /****************************************************************************/
  640. static void idtoolPrintHelp(FILE *out,const char *pn)
  641. {
  642. fprintf(out,
  643. "%s version %d.%d.%d" ZT_EOL_S,
  644. PROGRAM_NAME,
  645. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  646. fprintf(out,
  647. COPYRIGHT_NOTICE ZT_EOL_S
  648. LICENSE_GRANT ZT_EOL_S);
  649. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  650. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  651. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  652. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  653. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  654. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  655. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  656. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  657. }
  658. static Identity getIdFromArg(char *arg)
  659. {
  660. Identity id;
  661. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  662. if (id.fromString(arg))
  663. return id;
  664. } else { // identity is to be read from a file
  665. std::string idser;
  666. if (OSUtils::readFile(arg,idser)) {
  667. if (id.fromString(idser.c_str()))
  668. return id;
  669. }
  670. }
  671. return Identity();
  672. }
  673. #ifdef __WINDOWS__
  674. static int idtool(int argc, _TCHAR* argv[])
  675. #else
  676. static int idtool(int argc,char **argv)
  677. #endif
  678. {
  679. if (argc < 2) {
  680. idtoolPrintHelp(stdout,argv[0]);
  681. return 1;
  682. }
  683. if (!strcmp(argv[1],"generate")) {
  684. uint64_t vanity = 0;
  685. int vanityBits = 0;
  686. if (argc >= 5) {
  687. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  688. vanityBits = 4 * (int)strlen(argv[4]);
  689. if (vanityBits > 40)
  690. vanityBits = 40;
  691. }
  692. Identity id;
  693. for(;;) {
  694. id.generate();
  695. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  696. if (vanityBits > 0) {
  697. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  698. }
  699. break;
  700. } else {
  701. fprintf(stderr,"vanity address: tried %.10llx looking for first %d bits of %.10llx\n",(unsigned long long)id.address().toInt(),vanityBits,(unsigned long long)(vanity << (40 - vanityBits)));
  702. }
  703. }
  704. char idtmp[1024];
  705. std::string idser = id.toString(true,idtmp);
  706. if (argc >= 3) {
  707. if (!OSUtils::writeFile(argv[2],idser)) {
  708. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  709. return 1;
  710. } else printf("%s written" ZT_EOL_S,argv[2]);
  711. if (argc >= 4) {
  712. idser = id.toString(false,idtmp);
  713. if (!OSUtils::writeFile(argv[3],idser)) {
  714. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  715. return 1;
  716. } else printf("%s written" ZT_EOL_S,argv[3]);
  717. }
  718. } else printf("%s",idser.c_str());
  719. } else if (!strcmp(argv[1],"validate")) {
  720. if (argc < 3) {
  721. idtoolPrintHelp(stdout,argv[0]);
  722. return 1;
  723. }
  724. Identity id = getIdFromArg(argv[2]);
  725. if (!id) {
  726. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  727. return 1;
  728. }
  729. if (!id.locallyValidate()) {
  730. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  731. return 1;
  732. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  733. } else if (!strcmp(argv[1],"getpublic")) {
  734. if (argc < 3) {
  735. idtoolPrintHelp(stdout,argv[0]);
  736. return 1;
  737. }
  738. Identity id = getIdFromArg(argv[2]);
  739. if (!id) {
  740. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  741. return 1;
  742. }
  743. char idtmp[1024];
  744. printf("%s",id.toString(false,idtmp));
  745. } else if (!strcmp(argv[1],"sign")) {
  746. if (argc < 4) {
  747. idtoolPrintHelp(stdout,argv[0]);
  748. return 1;
  749. }
  750. Identity id = getIdFromArg(argv[2]);
  751. if (!id) {
  752. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  753. return 1;
  754. }
  755. if (!id.hasPrivate()) {
  756. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  757. return 1;
  758. }
  759. std::string inf;
  760. if (!OSUtils::readFile(argv[3],inf)) {
  761. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  762. return 1;
  763. }
  764. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  765. char hexbuf[1024];
  766. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  767. } else if (!strcmp(argv[1],"verify")) {
  768. if (argc < 5) {
  769. idtoolPrintHelp(stdout,argv[0]);
  770. return 1;
  771. }
  772. Identity id = getIdFromArg(argv[2]);
  773. if (!id) {
  774. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  775. return 1;
  776. }
  777. std::string inf;
  778. if (!OSUtils::readFile(argv[3],inf)) {
  779. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  780. return 1;
  781. }
  782. char buf[4096];
  783. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  784. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  785. printf("%s signature valid" ZT_EOL_S,argv[3]);
  786. } else {
  787. signature.clear();
  788. if (OSUtils::readFile(argv[4],signature)) {
  789. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  790. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  791. printf("%s signature valid" ZT_EOL_S,argv[3]);
  792. } else {
  793. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  794. return 1;
  795. }
  796. } else {
  797. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  798. return 1;
  799. }
  800. }
  801. } else if (!strcmp(argv[1],"initmoon")) {
  802. if (argc < 3) {
  803. idtoolPrintHelp(stdout,argv[0]);
  804. } else {
  805. const Identity id = getIdFromArg(argv[2]);
  806. if (!id) {
  807. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  808. return 1;
  809. }
  810. C25519::Pair kp(C25519::generate());
  811. char idtmp[4096];
  812. nlohmann::json mj;
  813. mj["objtype"] = "world";
  814. mj["worldType"] = "moon";
  815. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  816. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  817. mj["id"] = id.address().toString(idtmp);
  818. nlohmann::json seedj;
  819. seedj["identity"] = id.toString(false,idtmp);
  820. seedj["stableEndpoints"] = nlohmann::json::array();
  821. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  822. std::string mjd(OSUtils::jsonDump(mj));
  823. printf("%s" ZT_EOL_S,mjd.c_str());
  824. }
  825. } else if (!strcmp(argv[1],"genmoon")) {
  826. if (argc < 3) {
  827. idtoolPrintHelp(stdout,argv[0]);
  828. } else {
  829. std::string buf;
  830. if (!OSUtils::readFile(argv[2],buf)) {
  831. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  832. return 1;
  833. }
  834. nlohmann::json mj(OSUtils::jsonParse(buf));
  835. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  836. if (!id) {
  837. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  838. return 1;
  839. }
  840. World::Type t;
  841. if (mj["worldType"] == "moon") {
  842. t = World::TYPE_MOON;
  843. } else if (mj["worldType"] == "planet") {
  844. t = World::TYPE_PLANET;
  845. } else {
  846. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  847. return 1;
  848. }
  849. C25519::Pair signingKey;
  850. C25519::Public updatesMustBeSignedBy;
  851. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  852. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  853. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  854. std::vector<World::Root> roots;
  855. nlohmann::json &rootsj = mj["roots"];
  856. if (rootsj.is_array()) {
  857. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  858. nlohmann::json &r = rootsj[i];
  859. if (r.is_object()) {
  860. roots.push_back(World::Root());
  861. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  862. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  863. if (stableEndpointsj.is_array()) {
  864. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  865. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  866. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  867. }
  868. }
  869. }
  870. }
  871. std::sort(roots.begin(),roots.end());
  872. const int64_t now = OSUtils::now();
  873. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  874. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  875. w.serialize(wbuf);
  876. char fn[128];
  877. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  878. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  879. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  880. }
  881. } else {
  882. idtoolPrintHelp(stdout,argv[0]);
  883. return 1;
  884. }
  885. return 0;
  886. }
  887. /****************************************************************************/
  888. /* Unix helper functions and signal handlers */
  889. /****************************************************************************/
  890. #ifdef __UNIX_LIKE__
  891. static void _sighandlerHup(int sig)
  892. {
  893. }
  894. static void _sighandlerQuit(int sig)
  895. {
  896. OneService *s = zt1Service;
  897. if (s)
  898. s->terminate();
  899. else exit(0);
  900. }
  901. #endif
  902. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  903. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  904. #ifndef PR_CAP_AMBIENT
  905. #define PR_CAP_AMBIENT 47
  906. #define PR_CAP_AMBIENT_IS_SET 1
  907. #define PR_CAP_AMBIENT_RAISE 2
  908. #define PR_CAP_AMBIENT_LOWER 3
  909. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  910. #endif
  911. #define ZT_LINUX_USER "zerotier-one"
  912. #define ZT_HAVE_DROP_PRIVILEGES 1
  913. namespace {
  914. // libc doesn't export capset, it is instead located in libcap
  915. // We ignore libcap and call it manually.
  916. struct cap_header_struct {
  917. __u32 version;
  918. int pid;
  919. };
  920. struct cap_data_struct {
  921. __u32 effective;
  922. __u32 permitted;
  923. __u32 inheritable;
  924. };
  925. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  926. static void _notDropping(const char *procName,const std::string &homeDir)
  927. {
  928. struct stat buf;
  929. if (lstat(homeDir.c_str(),&buf) < 0) {
  930. if (buf.st_uid != 0 || buf.st_gid != 0) {
  931. fprintf(stderr, "%s: FATAL: failed to drop privileges and can't run as root since privileges were previously dropped (home directory not owned by root)" ZT_EOL_S,procName);
  932. exit(1);
  933. }
  934. }
  935. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  936. }
  937. static int _setCapabilities(int flags)
  938. {
  939. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  940. cap_data_struct capdata;
  941. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  942. return _zt_capset(&capheader, &capdata);
  943. }
  944. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  945. {
  946. struct dirent de;
  947. struct dirent *dptr;
  948. lchown(path,uid,gid);
  949. DIR *d = opendir(path);
  950. if (!d)
  951. return;
  952. dptr = (struct dirent *)0;
  953. for(;;) {
  954. if (readdir_r(d,&de,&dptr) != 0)
  955. break;
  956. if (!dptr)
  957. break;
  958. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  959. std::string p(path);
  960. p.push_back(ZT_PATH_SEPARATOR);
  961. p.append(dptr->d_name);
  962. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  963. }
  964. }
  965. closedir(d);
  966. }
  967. static void dropPrivileges(const char *procName,const std::string &homeDir)
  968. {
  969. if (getuid() != 0)
  970. return;
  971. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  972. // and CAP_NET_RAW capabilities.
  973. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  974. if (!targetUser)
  975. return;
  976. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  977. // Kernel has no support for ambient capabilities.
  978. _notDropping(procName,homeDir);
  979. return;
  980. }
  981. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  982. _notDropping(procName,homeDir);
  983. return;
  984. }
  985. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  986. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  987. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  988. _notDropping(procName,homeDir);
  989. return;
  990. }
  991. int oldDumpable = prctl(PR_GET_DUMPABLE);
  992. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  993. // Disable ptracing. Otherwise there is a small window when previous
  994. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  995. // (this is mitigated anyway on most distros by ptrace_scope=1)
  996. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  997. exit(1);
  998. }
  999. // Relinquish root
  1000. if (setgid(targetUser->pw_gid) < 0) {
  1001. perror("setgid");
  1002. exit(1);
  1003. }
  1004. if (setuid(targetUser->pw_uid) < 0) {
  1005. perror("setuid");
  1006. exit(1);
  1007. }
  1008. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1009. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1010. exit(1);
  1011. }
  1012. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1013. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1014. exit(1);
  1015. }
  1016. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1017. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_ADMIN) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1018. exit(1);
  1019. }
  1020. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1021. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_RAW) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1022. exit(1);
  1023. }
  1024. }
  1025. } // anonymous namespace
  1026. #endif // __LINUX__
  1027. /****************************************************************************/
  1028. /* Windows helper functions and signal handlers */
  1029. /****************************************************************************/
  1030. #ifdef __WINDOWS__
  1031. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1032. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1033. {
  1034. switch(dwCtrlType) {
  1035. case CTRL_C_EVENT:
  1036. case CTRL_BREAK_EVENT:
  1037. case CTRL_CLOSE_EVENT:
  1038. case CTRL_SHUTDOWN_EVENT:
  1039. OneService *s = zt1Service;
  1040. if (s)
  1041. s->terminate();
  1042. return TRUE;
  1043. }
  1044. return FALSE;
  1045. }
  1046. static void _winPokeAHole()
  1047. {
  1048. char myPath[MAX_PATH];
  1049. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1050. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1051. STARTUPINFOA startupInfo;
  1052. PROCESS_INFORMATION processInfo;
  1053. startupInfo.cb = sizeof(startupInfo);
  1054. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1055. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1056. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1057. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1058. CloseHandle(processInfo.hProcess);
  1059. CloseHandle(processInfo.hThread);
  1060. }
  1061. startupInfo.cb = sizeof(startupInfo);
  1062. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1063. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1064. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1065. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1066. CloseHandle(processInfo.hProcess);
  1067. CloseHandle(processInfo.hThread);
  1068. }
  1069. startupInfo.cb = sizeof(startupInfo);
  1070. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1071. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1072. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1073. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1074. CloseHandle(processInfo.hProcess);
  1075. CloseHandle(processInfo.hThread);
  1076. }
  1077. }
  1078. }
  1079. // Returns true if this is running as the local administrator
  1080. static BOOL IsCurrentUserLocalAdministrator(void)
  1081. {
  1082. BOOL fReturn = FALSE;
  1083. DWORD dwStatus;
  1084. DWORD dwAccessMask;
  1085. DWORD dwAccessDesired;
  1086. DWORD dwACLSize;
  1087. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1088. PACL pACL = NULL;
  1089. PSID psidAdmin = NULL;
  1090. HANDLE hToken = NULL;
  1091. HANDLE hImpersonationToken = NULL;
  1092. PRIVILEGE_SET ps;
  1093. GENERIC_MAPPING GenericMapping;
  1094. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1095. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1096. const DWORD ACCESS_READ = 1;
  1097. const DWORD ACCESS_WRITE = 2;
  1098. __try
  1099. {
  1100. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1101. {
  1102. if (GetLastError() != ERROR_NO_TOKEN)
  1103. __leave;
  1104. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1105. __leave;
  1106. }
  1107. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1108. __leave;
  1109. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1110. SECURITY_BUILTIN_DOMAIN_RID,
  1111. DOMAIN_ALIAS_RID_ADMINS,
  1112. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1113. __leave;
  1114. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1115. if (psdAdmin == NULL)
  1116. __leave;
  1117. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1118. __leave;
  1119. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1120. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1121. if (pACL == NULL)
  1122. __leave;
  1123. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1124. __leave;
  1125. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1126. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1127. __leave;
  1128. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1129. __leave;
  1130. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1131. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1132. if (!IsValidSecurityDescriptor(psdAdmin))
  1133. __leave;
  1134. dwAccessDesired = ACCESS_READ;
  1135. GenericMapping.GenericRead = ACCESS_READ;
  1136. GenericMapping.GenericWrite = ACCESS_WRITE;
  1137. GenericMapping.GenericExecute = 0;
  1138. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1139. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1140. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1141. &fReturn))
  1142. {
  1143. fReturn = FALSE;
  1144. __leave;
  1145. }
  1146. }
  1147. __finally
  1148. {
  1149. // Clean up.
  1150. if (pACL) LocalFree(pACL);
  1151. if (psdAdmin) LocalFree(psdAdmin);
  1152. if (psidAdmin) FreeSid(psidAdmin);
  1153. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1154. if (hToken) CloseHandle (hToken);
  1155. }
  1156. return fReturn;
  1157. }
  1158. #endif // __WINDOWS__
  1159. /****************************************************************************/
  1160. /* main() and friends */
  1161. /****************************************************************************/
  1162. static void printHelp(const char *cn,FILE *out)
  1163. {
  1164. fprintf(out,
  1165. "%s version %d.%d.%d" ZT_EOL_S,
  1166. PROGRAM_NAME,
  1167. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1168. fprintf(out,
  1169. COPYRIGHT_NOTICE ZT_EOL_S
  1170. LICENSE_GRANT ZT_EOL_S);
  1171. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1172. fprintf(out,"Available switches:" ZT_EOL_S);
  1173. fprintf(out," -h - Display this help" ZT_EOL_S);
  1174. fprintf(out," -v - Show version" ZT_EOL_S);
  1175. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1176. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1177. #ifdef __UNIX_LIKE__
  1178. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1179. #endif // __UNIX_LIKE__
  1180. #ifdef __WINDOWS__
  1181. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1182. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1183. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1184. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1185. #endif // __WINDOWS__
  1186. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1187. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1188. }
  1189. class _OneServiceRunner
  1190. {
  1191. public:
  1192. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1193. void threadMain()
  1194. throw()
  1195. {
  1196. try {
  1197. for(;;) {
  1198. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1199. switch(zt1Service->run()) {
  1200. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1201. case OneService::ONE_NORMAL_TERMINATION:
  1202. break;
  1203. case OneService::ONE_UNRECOVERABLE_ERROR:
  1204. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1205. returnValue = 1;
  1206. break;
  1207. case OneService::ONE_IDENTITY_COLLISION: {
  1208. delete zt1Service;
  1209. zt1Service = (OneService *)0;
  1210. std::string oldid;
  1211. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1212. if (oldid.length()) {
  1213. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1214. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1215. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1216. }
  1217. } continue; // restart!
  1218. }
  1219. break; // terminate loop -- normally we don't keep restarting
  1220. }
  1221. delete zt1Service;
  1222. zt1Service = (OneService *)0;
  1223. } catch ( ... ) {
  1224. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1225. returnValue = 1;
  1226. }
  1227. }
  1228. const char *progname;
  1229. unsigned int returnValue;
  1230. unsigned int port;
  1231. const std::string &homeDir;
  1232. };
  1233. #ifdef __WINDOWS__
  1234. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1235. #else
  1236. int main(int argc,char **argv)
  1237. #endif
  1238. {
  1239. #ifdef __UNIX_LIKE__
  1240. signal(SIGHUP,&_sighandlerHup);
  1241. signal(SIGPIPE,SIG_IGN);
  1242. signal(SIGUSR1,SIG_IGN);
  1243. signal(SIGUSR2,SIG_IGN);
  1244. signal(SIGALRM,SIG_IGN);
  1245. signal(SIGINT,&_sighandlerQuit);
  1246. signal(SIGTERM,&_sighandlerQuit);
  1247. signal(SIGQUIT,&_sighandlerQuit);
  1248. /* Ensure that there are no inherited file descriptors open from a previous
  1249. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1250. * of it do not return, and should not do anything otherwise bad. */
  1251. {
  1252. int mfd = STDIN_FILENO;
  1253. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1254. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1255. for(int f=mfd+1;f<1024;++f)
  1256. ::close(f);
  1257. }
  1258. bool runAsDaemon = false;
  1259. #endif // __UNIX_LIKE__
  1260. #ifdef __WINDOWS__
  1261. {
  1262. WSADATA wsaData;
  1263. WSAStartup(MAKEWORD(2,2),&wsaData);
  1264. }
  1265. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1266. bool winRunFromCommandLine = true;
  1267. #else
  1268. bool winRunFromCommandLine = false;
  1269. #endif
  1270. #endif // __WINDOWS__
  1271. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1272. return idtool(argc,argv);
  1273. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1274. return cli(argc,argv);
  1275. std::string homeDir;
  1276. unsigned int port = ZT_DEFAULT_PORT;
  1277. bool skipRootCheck = false;
  1278. for(int i=1;i<argc;++i) {
  1279. if (argv[i][0] == '-') {
  1280. switch(argv[i][1]) {
  1281. case 'p': // port -- for both UDP and TCP, packets and control plane
  1282. port = Utils::strToUInt(argv[i] + 2);
  1283. if (port > 0xffff) {
  1284. printHelp(argv[0],stdout);
  1285. return 1;
  1286. }
  1287. break;
  1288. #ifdef __UNIX_LIKE__
  1289. case 'd': // Run in background as daemon
  1290. runAsDaemon = true;
  1291. break;
  1292. #endif // __UNIX_LIKE__
  1293. case 'U':
  1294. skipRootCheck = true;
  1295. break;
  1296. case 'v': // Display version
  1297. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1298. return 0;
  1299. case 'i': // Invoke idtool personality
  1300. if (argv[i][2]) {
  1301. printHelp(argv[0],stdout);
  1302. return 0;
  1303. } else return idtool(argc-1,argv+1);
  1304. case 'q': // Invoke cli personality
  1305. if (argv[i][2]) {
  1306. printHelp(argv[0],stdout);
  1307. return 0;
  1308. } else return cli(argc,argv);
  1309. #ifdef __WINDOWS__
  1310. case 'C': // Run from command line instead of as Windows service
  1311. winRunFromCommandLine = true;
  1312. break;
  1313. case 'I': { // Install this binary as a Windows service
  1314. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1315. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1316. return 1;
  1317. }
  1318. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1319. if (ret.length()) {
  1320. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1321. return 3;
  1322. }
  1323. return 0;
  1324. } break;
  1325. case 'R': { // Uninstall this binary as Windows service
  1326. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1327. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1328. return 1;
  1329. }
  1330. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1331. if (ret.length()) {
  1332. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1333. return 3;
  1334. }
  1335. return 0;
  1336. } break;
  1337. case 'D': {
  1338. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1339. if (err.length() > 0) {
  1340. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1341. return 3;
  1342. }
  1343. return 0;
  1344. } break;
  1345. #endif // __WINDOWS__
  1346. case 'h':
  1347. case '?':
  1348. default:
  1349. printHelp(argv[0],stdout);
  1350. return 0;
  1351. }
  1352. } else {
  1353. if (homeDir.length()) {
  1354. printHelp(argv[0],stdout);
  1355. return 0;
  1356. } else {
  1357. homeDir = argv[i];
  1358. }
  1359. }
  1360. }
  1361. if (!homeDir.length())
  1362. homeDir = OneService::platformDefaultHomePath();
  1363. if (!homeDir.length()) {
  1364. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1365. return 1;
  1366. } else {
  1367. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1368. std::string ptmp;
  1369. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1370. ptmp.push_back(ZT_PATH_SEPARATOR);
  1371. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1372. if (ptmp.length() > 0)
  1373. ptmp.push_back(ZT_PATH_SEPARATOR);
  1374. ptmp.append(*pi);
  1375. if ((*pi != ".")&&(*pi != "..")) {
  1376. if (!OSUtils::mkdir(ptmp))
  1377. throw std::runtime_error("home path does not exist, and could not create");
  1378. }
  1379. }
  1380. }
  1381. // This can be removed once the new controller code has been around for many versions
  1382. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1383. fprintf(stderr,"%s: FATAL: an old controller.db exists in %s -- see instructions in controller/README.md for how to migrate!" ZT_EOL_S,argv[0],homeDir.c_str());
  1384. return 1;
  1385. }
  1386. #ifdef __UNIX_LIKE__
  1387. #ifndef ZT_ONE_NO_ROOT_CHECK
  1388. if ((!skipRootCheck)&&(getuid() != 0)) {
  1389. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1390. return 1;
  1391. }
  1392. #endif // !ZT_ONE_NO_ROOT_CHECK
  1393. if (runAsDaemon) {
  1394. long p = (long)fork();
  1395. if (p < 0) {
  1396. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1397. return 1;
  1398. } else if (p > 0)
  1399. return 0; // forked
  1400. // else p == 0, so we are daemonized
  1401. }
  1402. #endif // __UNIX_LIKE__
  1403. #ifdef __WINDOWS__
  1404. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1405. // when tap instances are created.
  1406. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1407. if (winRunFromCommandLine) {
  1408. // Running in "interactive" mode (mostly for debugging)
  1409. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1410. if (!skipRootCheck) {
  1411. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1412. return 1;
  1413. }
  1414. } else {
  1415. _winPokeAHole();
  1416. }
  1417. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1418. // continues on to ordinary command line execution code below...
  1419. } else {
  1420. // Running from service manager
  1421. _winPokeAHole();
  1422. ZeroTierOneService zt1WindowsService;
  1423. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1424. return 0;
  1425. } else {
  1426. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1427. return 1;
  1428. }
  1429. }
  1430. #endif // __WINDOWS__
  1431. #ifdef __UNIX_LIKE__
  1432. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1433. if (!skipRootCheck)
  1434. dropPrivileges(argv[0],homeDir);
  1435. #endif
  1436. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1437. {
  1438. // Write .pid file to home folder
  1439. FILE *pf = fopen(pidPath.c_str(),"w");
  1440. if (pf) {
  1441. fprintf(pf,"%ld",(long)getpid());
  1442. fclose(pf);
  1443. }
  1444. }
  1445. #endif // __UNIX_LIKE__
  1446. _OneServiceRunner thr(argv[0],homeDir,port);
  1447. thr.threadMain();
  1448. //Thread::join(Thread::start(&thr));
  1449. #ifdef __UNIX_LIKE__
  1450. OSUtils::rm(pidPath.c_str());
  1451. #endif
  1452. return thr.returnValue;
  1453. }