OSUtils.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <stdarg.h>
  17. #include <sys/stat.h>
  18. #include <stdlib.h>
  19. #include "../node/Constants.hpp"
  20. #include "../node/Utils.hpp"
  21. #ifdef __UNIX_LIKE__
  22. #include <unistd.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <sys/types.h>
  26. #include <sys/socket.h>
  27. #include <sys/stat.h>
  28. #include <sys/uio.h>
  29. #include <dirent.h>
  30. #include <netdb.h>
  31. #endif
  32. #ifdef __WINDOWS__
  33. #include <windows.h>
  34. #include <wincrypt.h>
  35. #include <shlobj.h>
  36. #include <netioapi.h>
  37. #include <iphlpapi.h>
  38. #endif
  39. #include "OSUtils.hpp"
  40. #ifdef __GCC__
  41. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  42. #endif
  43. namespace ZeroTier {
  44. unsigned int OSUtils::ztsnprintf(char *buf,unsigned int len,const char *fmt,...)
  45. {
  46. va_list ap;
  47. va_start(ap,fmt);
  48. int n = (int)vsnprintf(buf,len,fmt,ap);
  49. va_end(ap);
  50. if ((n >= (int)len)||(n < 0)) {
  51. if (len)
  52. buf[len - 1] = (char)0;
  53. throw std::length_error("buf[] overflow");
  54. }
  55. return (unsigned int)n;
  56. }
  57. #ifdef __UNIX_LIKE__
  58. bool OSUtils::redirectUnixOutputs(const char *stdoutPath,const char *stderrPath)
  59. throw()
  60. {
  61. int fdout = ::open(stdoutPath,O_WRONLY|O_CREAT,0600);
  62. if (fdout > 0) {
  63. int fderr;
  64. if (stderrPath) {
  65. fderr = ::open(stderrPath,O_WRONLY|O_CREAT,0600);
  66. if (fderr <= 0) {
  67. ::close(fdout);
  68. return false;
  69. }
  70. } else fderr = fdout;
  71. ::close(STDOUT_FILENO);
  72. ::close(STDERR_FILENO);
  73. ::dup2(fdout,STDOUT_FILENO);
  74. ::dup2(fderr,STDERR_FILENO);
  75. return true;
  76. }
  77. return false;
  78. }
  79. #endif // __UNIX_LIKE__
  80. std::vector<std::string> OSUtils::listDirectory(const char *path,bool includeDirectories)
  81. {
  82. std::vector<std::string> r;
  83. #ifdef __WINDOWS__
  84. HANDLE hFind;
  85. WIN32_FIND_DATAA ffd;
  86. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  87. do {
  88. if ( (strcmp(ffd.cFileName,".")) && (strcmp(ffd.cFileName,"..")) && (((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)||(((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)&&(includeDirectories))) )
  89. r.push_back(std::string(ffd.cFileName));
  90. } while (FindNextFileA(hFind,&ffd));
  91. FindClose(hFind);
  92. }
  93. #else
  94. struct dirent de;
  95. struct dirent *dptr;
  96. DIR *d = opendir(path);
  97. if (!d)
  98. return r;
  99. dptr = (struct dirent *)0;
  100. for(;;) {
  101. if (readdir_r(d,&de,&dptr))
  102. break;
  103. if (dptr) {
  104. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))&&((dptr->d_type != DT_DIR)||(includeDirectories)))
  105. r.push_back(std::string(dptr->d_name));
  106. } else break;
  107. }
  108. closedir(d);
  109. #endif
  110. return r;
  111. }
  112. long OSUtils::cleanDirectory(const char *path,const int64_t olderThan)
  113. {
  114. long cleaned = 0;
  115. #ifdef __WINDOWS__
  116. HANDLE hFind;
  117. WIN32_FIND_DATAA ffd;
  118. LARGE_INTEGER date,adjust;
  119. adjust.QuadPart = 11644473600000 * 10000;
  120. char tmp[4096];
  121. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  122. do {
  123. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,".."))&&((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {
  124. date.HighPart = ffd.ftLastWriteTime.dwHighDateTime;
  125. date.LowPart = ffd.ftLastWriteTime.dwLowDateTime;
  126. if (date.QuadPart > 0) {
  127. date.QuadPart -= adjust.QuadPart;
  128. if ((int64_t)((date.QuadPart / 10000000) * 1000) < olderThan) {
  129. ztsnprintf(tmp, sizeof(tmp), "%s\\%s", path, ffd.cFileName);
  130. if (DeleteFileA(tmp))
  131. ++cleaned;
  132. }
  133. }
  134. }
  135. } while (FindNextFileA(hFind,&ffd));
  136. FindClose(hFind);
  137. }
  138. #else
  139. struct dirent de;
  140. struct dirent *dptr;
  141. struct stat st;
  142. char tmp[4096];
  143. DIR *d = opendir(path);
  144. if (!d)
  145. return -1;
  146. dptr = (struct dirent *)0;
  147. for(;;) {
  148. if (readdir_r(d,&de,&dptr))
  149. break;
  150. if (dptr) {
  151. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))&&(dptr->d_type == DT_REG)) {
  152. ztsnprintf(tmp,sizeof(tmp),"%s/%s",path,dptr->d_name);
  153. if (stat(tmp,&st) == 0) {
  154. int64_t mt = (int64_t)(st.st_mtime);
  155. if ((mt > 0)&&((mt * 1000) < olderThan)) {
  156. if (unlink(tmp) == 0)
  157. ++cleaned;
  158. }
  159. }
  160. }
  161. } else break;
  162. }
  163. closedir(d);
  164. #endif
  165. return cleaned;
  166. }
  167. bool OSUtils::rmDashRf(const char *path)
  168. {
  169. #ifdef __WINDOWS__
  170. HANDLE hFind;
  171. WIN32_FIND_DATAA ffd;
  172. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  173. do {
  174. if ((strcmp(ffd.cFileName,".") != 0)&&(strcmp(ffd.cFileName,"..") != 0)) {
  175. if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  176. if (DeleteFileA((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()) == FALSE)
  177. return false;
  178. } else {
  179. if (!rmDashRf((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()))
  180. return false;
  181. }
  182. }
  183. } while (FindNextFileA(hFind,&ffd));
  184. FindClose(hFind);
  185. }
  186. return (RemoveDirectoryA(path) != FALSE);
  187. #else
  188. struct dirent de;
  189. struct dirent *dptr;
  190. DIR *d = opendir(path);
  191. if (!d)
  192. return true;
  193. dptr = (struct dirent *)0;
  194. for(;;) {
  195. if (readdir_r(d,&de,&dptr) != 0)
  196. break;
  197. if (!dptr)
  198. break;
  199. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  200. std::string p(path);
  201. p.push_back(ZT_PATH_SEPARATOR);
  202. p.append(dptr->d_name);
  203. if (unlink(p.c_str()) != 0) { // unlink first will remove symlinks instead of recursing them
  204. if (!rmDashRf(p.c_str()))
  205. return false;
  206. }
  207. }
  208. }
  209. closedir(d);
  210. return (rmdir(path) == 0);
  211. #endif
  212. }
  213. void OSUtils::lockDownFile(const char *path,bool isDir)
  214. {
  215. #ifdef __UNIX_LIKE__
  216. chmod(path,isDir ? 0700 : 0600);
  217. #else
  218. #ifdef __WINDOWS__
  219. {
  220. STARTUPINFOA startupInfo;
  221. PROCESS_INFORMATION processInfo;
  222. startupInfo.cb = sizeof(startupInfo);
  223. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  224. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  225. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\icacls.exe \"") + path + "\" /inheritance:d /Q").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  226. WaitForSingleObject(processInfo.hProcess,INFINITE);
  227. CloseHandle(processInfo.hProcess);
  228. CloseHandle(processInfo.hThread);
  229. }
  230. startupInfo.cb = sizeof(startupInfo);
  231. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  232. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  233. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\icacls.exe \"") + path + "\" /remove *S-1-5-32-545 /Q").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  234. WaitForSingleObject(processInfo.hProcess,INFINITE);
  235. CloseHandle(processInfo.hProcess);
  236. CloseHandle(processInfo.hThread);
  237. }
  238. }
  239. #endif
  240. #endif
  241. }
  242. uint64_t OSUtils::getLastModified(const char *path)
  243. {
  244. struct stat s;
  245. if (stat(path,&s))
  246. return 0;
  247. return (((uint64_t)s.st_mtime) * 1000ULL);
  248. }
  249. bool OSUtils::fileExists(const char *path,bool followLinks)
  250. {
  251. struct stat s;
  252. #ifdef __UNIX_LIKE__
  253. if (!followLinks)
  254. return (lstat(path,&s) == 0);
  255. #endif
  256. return (stat(path,&s) == 0);
  257. }
  258. int64_t OSUtils::getFileSize(const char *path)
  259. {
  260. struct stat s;
  261. if (stat(path,&s))
  262. return -1;
  263. #ifdef __WINDOWS__
  264. return s.st_size;
  265. #else
  266. if (S_ISREG(s.st_mode))
  267. return s.st_size;
  268. #endif
  269. return -1;
  270. }
  271. bool OSUtils::readFile(const char *path,std::string &buf)
  272. {
  273. char tmp[16384];
  274. FILE *f = fopen(path,"rb");
  275. if (f) {
  276. for(;;) {
  277. long n = (long)fread(tmp,1,sizeof(tmp),f);
  278. if (n > 0)
  279. buf.append(tmp,n);
  280. else break;
  281. }
  282. fclose(f);
  283. return true;
  284. }
  285. return false;
  286. }
  287. bool OSUtils::writeFile(const char *path,const void *buf,unsigned int len)
  288. {
  289. FILE *f = fopen(path,"wb");
  290. if (f) {
  291. if ((long)fwrite(buf,1,len,f) != (long)len) {
  292. fclose(f);
  293. return false;
  294. } else {
  295. fclose(f);
  296. return true;
  297. }
  298. }
  299. return false;
  300. }
  301. std::vector<std::string> OSUtils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  302. {
  303. std::vector<std::string> fields;
  304. std::string buf;
  305. if (!esc)
  306. esc = "";
  307. if (!quot)
  308. quot = "";
  309. bool escapeState = false;
  310. char quoteState = 0;
  311. while (*s) {
  312. if (escapeState) {
  313. escapeState = false;
  314. buf.push_back(*s);
  315. } else if (quoteState) {
  316. if (*s == quoteState) {
  317. quoteState = 0;
  318. fields.push_back(buf);
  319. buf.clear();
  320. } else buf.push_back(*s);
  321. } else {
  322. const char *quotTmp;
  323. if (strchr(esc,*s))
  324. escapeState = true;
  325. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  326. quoteState = *quotTmp;
  327. else if (strchr(sep,*s)) {
  328. if (!buf.empty()) {
  329. fields.push_back(buf);
  330. buf.clear();
  331. } // else skip runs of separators
  332. } else buf.push_back(*s);
  333. }
  334. ++s;
  335. }
  336. if (buf.size())
  337. fields.push_back(buf);
  338. return fields;
  339. }
  340. std::string OSUtils::platformDefaultHomePath()
  341. {
  342. #ifdef __QNAP__
  343. char *cmd = "/sbin/getcfg zerotier Install_Path -f /etc/config/qpkg.conf";
  344. char buf[128];
  345. FILE *fp;
  346. if ((fp = popen(cmd, "r")) == NULL) {
  347. printf("Error opening pipe!\n");
  348. return NULL;
  349. }
  350. while (fgets(buf, 128, fp) != NULL) { }
  351. if(pclose(fp)) {
  352. printf("Command not found or exited with error status\n");
  353. return NULL;
  354. }
  355. std::string homeDir = std::string(buf);
  356. homeDir.erase(std::remove(homeDir.begin(), homeDir.end(), '\n'), homeDir.end());
  357. return homeDir;
  358. #endif
  359. #ifdef __UBIQUITI__
  360. // Only persistent location after firmware upgrades
  361. return std::string("/config/zerotier-one");
  362. #endif
  363. // Check for user-defined environment variable before using defaults
  364. #ifdef __WINDOWS__
  365. DWORD bufferSize = 65535;
  366. std::string userDefinedPath;
  367. bufferSize = GetEnvironmentVariable("ZEROTIER_HOME", &userDefinedPath[0], bufferSize);
  368. if (bufferSize) {
  369. return userDefinedPath;
  370. }
  371. #else
  372. if(const char* userDefinedPath = getenv("ZEROTIER_HOME")) {
  373. return std::string(userDefinedPath);
  374. }
  375. #endif
  376. // Finally, resort to using default paths if no user-defined path was provided
  377. #ifdef __UNIX_LIKE__
  378. #ifdef __APPLE__
  379. // /Library/... on Apple
  380. return std::string("/Library/Application Support/ZeroTier/One");
  381. #else
  382. #ifdef __BSD__
  383. // BSD likes /var/db instead of /var/lib
  384. return std::string("/var/db/zerotier-one");
  385. #else
  386. // Use /var/lib for Linux and other *nix
  387. return std::string("/var/lib/zerotier-one");
  388. #endif
  389. #endif
  390. #else // not __UNIX_LIKE__
  391. #ifdef __WINDOWS__
  392. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  393. char buf[16384];
  394. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  395. return (std::string(buf) + "\\ZeroTier\\One");
  396. else return std::string("C:\\ZeroTier\\One");
  397. #else
  398. return (std::string(ZT_PATH_SEPARATOR_S) + "ZeroTier" + ZT_PATH_SEPARATOR_S + "One"); // UNKNOWN PLATFORM
  399. #endif
  400. #endif // __UNIX_LIKE__ or not...
  401. }
  402. #ifndef OMIT_JSON_SUPPORT
  403. // Inline these massive JSON operations in one place only to reduce binary footprint and compile time
  404. nlohmann::json OSUtils::jsonParse(const std::string &buf) { return nlohmann::json::parse(buf.c_str()); }
  405. std::string OSUtils::jsonDump(const nlohmann::json &j,int indentation) { return j.dump(indentation); }
  406. uint64_t OSUtils::jsonInt(const nlohmann::json &jv,const uint64_t dfl)
  407. {
  408. try {
  409. if (jv.is_number()) {
  410. return (uint64_t)jv;
  411. } else if (jv.is_string()) {
  412. std::string s = jv;
  413. return Utils::strToU64(s.c_str());
  414. } else if (jv.is_boolean()) {
  415. return ((bool)jv ? 1ULL : 0ULL);
  416. }
  417. } catch ( ... ) {}
  418. return dfl;
  419. }
  420. double OSUtils::jsonDouble(const nlohmann::json &jv,const double dfl)
  421. {
  422. try {
  423. if (jv.is_number()) {
  424. return (double)jv;
  425. }
  426. else if (jv.is_string()) {
  427. std::string s = jv;
  428. return Utils::strToDouble(s.c_str());
  429. } else if (jv.is_boolean()) {
  430. return (double)jv;
  431. }
  432. } catch ( ... ) {}
  433. return dfl;
  434. }
  435. uint64_t OSUtils::jsonIntHex(const nlohmann::json &jv,const uint64_t dfl)
  436. {
  437. try {
  438. if (jv.is_number()) {
  439. return (uint64_t)jv;
  440. } else if (jv.is_string()) {
  441. std::string s = jv;
  442. return Utils::hexStrToU64(s.c_str());
  443. } else if (jv.is_boolean()) {
  444. return ((bool)jv ? 1ULL : 0ULL);
  445. }
  446. } catch ( ... ) {}
  447. return dfl;
  448. }
  449. bool OSUtils::jsonBool(const nlohmann::json &jv,const bool dfl)
  450. {
  451. try {
  452. if (jv.is_boolean()) {
  453. return (bool)jv;
  454. } else if (jv.is_number()) {
  455. return ((uint64_t)jv > 0ULL);
  456. } else if (jv.is_string()) {
  457. std::string s = jv;
  458. if (s.length() > 0) {
  459. switch(s[0]) {
  460. case 't':
  461. case 'T':
  462. case '1':
  463. return true;
  464. }
  465. }
  466. return false;
  467. }
  468. } catch ( ... ) {}
  469. return dfl;
  470. }
  471. std::string OSUtils::jsonString(const nlohmann::json &jv,const char *dfl)
  472. {
  473. try {
  474. if (jv.is_string()) {
  475. return jv;
  476. } else if (jv.is_number()) {
  477. char tmp[64];
  478. ztsnprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  479. return tmp;
  480. } else if (jv.is_boolean()) {
  481. return ((bool)jv ? std::string("1") : std::string("0"));
  482. }
  483. } catch ( ... ) {}
  484. return std::string((dfl) ? dfl : "");
  485. }
  486. std::string OSUtils::jsonBinFromHex(const nlohmann::json &jv)
  487. {
  488. std::string s(jsonString(jv,""));
  489. if (s.length() > 0) {
  490. unsigned int buflen = (unsigned int)((s.length() / 2) + 1);
  491. char *buf = new char[buflen];
  492. try {
  493. unsigned int l = Utils::unhex(s.c_str(),buf,buflen);
  494. std::string b(buf,l);
  495. delete [] buf;
  496. return b;
  497. } catch ( ... ) {
  498. delete [] buf;
  499. }
  500. }
  501. return std::string();
  502. }
  503. #endif // OMIT_JSON_SUPPORT
  504. // Used to convert HTTP header names to ASCII lower case
  505. const unsigned char OSUtils::TOLOWER_TABLE[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, ' ', '!', '"', '#', '$', '%', '&', 0x27, '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
  506. } // namespace ZeroTier