OSUtils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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: 2024-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 <cstdio>
  14. #include <cstring>
  15. #include <cstdlib>
  16. #include <cstdarg>
  17. #include <sys/stat.h>
  18. #include "../node/Constants.hpp"
  19. #include "../node/Utils.hpp"
  20. #ifdef __UNIX_LIKE__
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <sys/uio.h>
  24. #include <dirent.h>
  25. #endif
  26. #ifdef __GCC__
  27. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  28. #endif
  29. #ifdef __WINDOWS__
  30. #include <windows.h>
  31. #include <wincrypt.h>
  32. #include <ShlObj.h>
  33. #include <netioapi.h>
  34. #include <iphlpapi.h>
  35. #endif
  36. #include "OSUtils.hpp"
  37. namespace ZeroTier {
  38. unsigned int OSUtils::ztsnprintf(char *buf,unsigned int len,const char *fmt,...)
  39. {
  40. va_list ap;
  41. va_start(ap,fmt);
  42. int n = (int)vsnprintf(buf,len,fmt,ap);
  43. va_end(ap);
  44. if ((n >= (int)len)||(n < 0)) {
  45. if (len)
  46. buf[len - 1] = (char)0;
  47. throw std::length_error("buf[] overflow");
  48. }
  49. return (unsigned int)n;
  50. }
  51. #ifdef __UNIX_LIKE__
  52. bool OSUtils::redirectUnixOutputs(const char *stdoutPath,const char *stderrPath)
  53. throw()
  54. {
  55. int fdout = ::open(stdoutPath,O_WRONLY|O_CREAT,0600);
  56. if (fdout > 0) {
  57. int fderr;
  58. if (stderrPath) {
  59. fderr = ::open(stderrPath,O_WRONLY|O_CREAT,0600);
  60. if (fderr <= 0) {
  61. ::close(fdout);
  62. return false;
  63. }
  64. } else fderr = fdout;
  65. ::close(STDOUT_FILENO);
  66. ::close(STDERR_FILENO);
  67. ::dup2(fdout,STDOUT_FILENO);
  68. ::dup2(fderr,STDERR_FILENO);
  69. return true;
  70. }
  71. return false;
  72. }
  73. #endif // __UNIX_LIKE__
  74. std::vector<std::string> OSUtils::listDirectory(const char *path,bool includeDirectories)
  75. {
  76. std::vector<std::string> r;
  77. #ifdef __WINDOWS__
  78. HANDLE hFind;
  79. WIN32_FIND_DATAA ffd;
  80. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  81. do {
  82. if ( (strcmp(ffd.cFileName,".")) && (strcmp(ffd.cFileName,"..")) && (((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)||(((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)&&(includeDirectories))) )
  83. r.push_back(std::string(ffd.cFileName));
  84. } while (FindNextFileA(hFind,&ffd));
  85. FindClose(hFind);
  86. }
  87. #else
  88. struct dirent de;
  89. struct dirent *dptr;
  90. DIR *d = opendir(path);
  91. if (!d)
  92. return r;
  93. dptr = (struct dirent *)0;
  94. for(;;) {
  95. if (readdir_r(d,&de,&dptr))
  96. break;
  97. if (dptr) {
  98. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))&&((dptr->d_type != DT_DIR)||(includeDirectories)))
  99. r.push_back(std::string(dptr->d_name));
  100. } else break;
  101. }
  102. closedir(d);
  103. #endif
  104. return r;
  105. }
  106. bool OSUtils::rmDashRf(const char *path)
  107. {
  108. #ifdef __WINDOWS__
  109. HANDLE hFind;
  110. WIN32_FIND_DATAA ffd;
  111. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  112. do {
  113. if ((strcmp(ffd.cFileName,".") != 0)&&(strcmp(ffd.cFileName,"..") != 0)) {
  114. if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  115. if (DeleteFileA((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()) == FALSE)
  116. return false;
  117. } else {
  118. if (!rmDashRf((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()))
  119. return false;
  120. }
  121. }
  122. } while (FindNextFileA(hFind,&ffd));
  123. FindClose(hFind);
  124. }
  125. return (RemoveDirectoryA(path) != FALSE);
  126. #else
  127. struct dirent de;
  128. struct dirent *dptr;
  129. DIR *d = opendir(path);
  130. if (!d)
  131. return true;
  132. dptr = (struct dirent *)0;
  133. for(;;) {
  134. if (readdir_r(d,&de,&dptr) != 0)
  135. break;
  136. if (!dptr)
  137. break;
  138. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  139. std::string p(path);
  140. p.push_back(ZT_PATH_SEPARATOR);
  141. p.append(dptr->d_name);
  142. if (unlink(p.c_str()) != 0) { // unlink first will remove symlinks instead of recursing them
  143. if (!rmDashRf(p.c_str()))
  144. return false;
  145. }
  146. }
  147. }
  148. closedir(d);
  149. return (rmdir(path) == 0);
  150. #endif
  151. }
  152. void OSUtils::lockDownFile(const char *path,bool isDir)
  153. {
  154. #ifdef __UNIX_LIKE__
  155. chmod(path,isDir ? 0700 : 0600);
  156. #else
  157. #ifdef __WINDOWS__
  158. {
  159. STARTUPINFOA startupInfo;
  160. PROCESS_INFORMATION processInfo;
  161. startupInfo.cb = sizeof(startupInfo);
  162. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  163. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  164. 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)) {
  165. WaitForSingleObject(processInfo.hProcess,INFINITE);
  166. CloseHandle(processInfo.hProcess);
  167. CloseHandle(processInfo.hThread);
  168. }
  169. startupInfo.cb = sizeof(startupInfo);
  170. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  171. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  172. 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)) {
  173. WaitForSingleObject(processInfo.hProcess,INFINITE);
  174. CloseHandle(processInfo.hProcess);
  175. CloseHandle(processInfo.hThread);
  176. }
  177. }
  178. #endif
  179. #endif
  180. }
  181. uint64_t OSUtils::getLastModified(const char *path)
  182. {
  183. struct stat s;
  184. if (stat(path,&s))
  185. return 0;
  186. return (((uint64_t)s.st_mtime) * 1000ULL);
  187. }
  188. bool OSUtils::fileExists(const char *path,bool followLinks)
  189. {
  190. struct stat s;
  191. #ifdef __UNIX_LIKE__
  192. if (!followLinks)
  193. return (lstat(path,&s) == 0);
  194. #endif
  195. return (stat(path,&s) == 0);
  196. }
  197. int64_t OSUtils::getFileSize(const char *path)
  198. {
  199. struct stat s;
  200. if (stat(path,&s))
  201. return -1;
  202. #ifdef __WINDOWS__
  203. return s.st_size;
  204. #else
  205. if (S_ISREG(s.st_mode))
  206. return s.st_size;
  207. #endif
  208. return -1;
  209. }
  210. bool OSUtils::readFile(const char *path,std::string &buf)
  211. {
  212. char tmp[16384];
  213. FILE *f = fopen(path,"rb");
  214. if (f) {
  215. for(;;) {
  216. long n = (long)fread(tmp,1,sizeof(tmp),f);
  217. if (n > 0)
  218. buf.append(tmp,n);
  219. else break;
  220. }
  221. fclose(f);
  222. return true;
  223. }
  224. return false;
  225. }
  226. bool OSUtils::writeFile(const char *path,const void *buf,unsigned int len)
  227. {
  228. FILE *f = fopen(path,"wb");
  229. if (f) {
  230. if ((long)fwrite(buf,1,len,f) != (long)len) {
  231. fclose(f);
  232. return false;
  233. } else {
  234. fclose(f);
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. std::vector<std::string> OSUtils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  241. {
  242. std::vector<std::string> fields;
  243. std::string buf;
  244. if (!esc)
  245. esc = "";
  246. if (!quot)
  247. quot = "";
  248. bool escapeState = false;
  249. char quoteState = 0;
  250. while (*s) {
  251. if (escapeState) {
  252. escapeState = false;
  253. buf.push_back(*s);
  254. } else if (quoteState) {
  255. if (*s == quoteState) {
  256. quoteState = 0;
  257. fields.push_back(buf);
  258. buf.clear();
  259. } else buf.push_back(*s);
  260. } else {
  261. const char *quotTmp;
  262. if (strchr(esc,*s))
  263. escapeState = true;
  264. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  265. quoteState = *quotTmp;
  266. else if (strchr(sep,*s)) {
  267. if (buf.size() > 0) {
  268. fields.push_back(buf);
  269. buf.clear();
  270. } // else skip runs of separators
  271. } else buf.push_back(*s);
  272. }
  273. ++s;
  274. }
  275. if (buf.size())
  276. fields.push_back(buf);
  277. return fields;
  278. }
  279. std::string OSUtils::platformDefaultHomePath()
  280. {
  281. #ifdef __QNAP__
  282. char *cmd = "/sbin/getcfg zerotier Install_Path -f /etc/config/qpkg.conf";
  283. char buf[128];
  284. FILE *fp;
  285. if ((fp = popen(cmd, "r")) == NULL) {
  286. printf("Error opening pipe!\n");
  287. return NULL;
  288. }
  289. while (fgets(buf, 128, fp) != NULL) { }
  290. if(pclose(fp)) {
  291. printf("Command not found or exited with error status\n");
  292. return NULL;
  293. }
  294. std::string homeDir = std::string(buf);
  295. homeDir.erase(std::remove(homeDir.begin(), homeDir.end(), '\n'), homeDir.end());
  296. return homeDir;
  297. #endif
  298. // Check for user-defined environment variable before using defaults
  299. #ifdef __WINDOWS__
  300. DWORD bufferSize = 65535;
  301. std::string userDefinedPath;
  302. bufferSize = GetEnvironmentVariable("ZEROTIER_HOME", &userDefinedPath[0], bufferSize);
  303. if (bufferSize) {
  304. return userDefinedPath;
  305. }
  306. #else
  307. if(const char* userDefinedPath = getenv("ZEROTIER_HOME")) {
  308. return std::string(userDefinedPath);
  309. }
  310. #endif
  311. // Finally, resort to using default paths if no user-defined path was provided
  312. #ifdef __UNIX_LIKE__
  313. #ifdef __APPLE__
  314. // /Library/... on Apple
  315. return std::string("/Library/Application Support/ZeroTier");
  316. #else
  317. #ifdef __BSD__
  318. // BSD likes /var/db instead of /var/lib
  319. return std::string("/var/db/zerotier");
  320. #else
  321. // Use /var/lib for Linux and other *nix
  322. return std::string("/var/lib/zerotier");
  323. #endif
  324. #endif
  325. #else // not __UNIX_LIKE__
  326. #ifdef __WINDOWS__
  327. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  328. char buf[16384];
  329. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  330. return (std::string(buf) + "\\ZeroTier");
  331. else return std::string("C:\\ZeroTier");
  332. #else
  333. return (std::string(ZT_PATH_SEPARATOR_S) + "ZeroTier"); // UNKNOWN PLATFORM
  334. #endif
  335. #endif // __UNIX_LIKE__ or not...
  336. }
  337. #ifndef OMIT_JSON_SUPPORT
  338. // Inline these massive JSON operations in one place only to reduce binary footprint and compile time
  339. nlohmann::json OSUtils::jsonParse(const std::string &buf) { return nlohmann::json::parse(buf.c_str()); }
  340. std::string OSUtils::jsonDump(const nlohmann::json &j,int indentation) { return j.dump(indentation); }
  341. uint64_t OSUtils::jsonInt(const nlohmann::json &jv,const uint64_t dfl)
  342. {
  343. try {
  344. if (jv.is_number()) {
  345. return (uint64_t)jv;
  346. } else if (jv.is_string()) {
  347. std::string s = jv;
  348. return Utils::strToU64(s.c_str());
  349. } else if (jv.is_boolean()) {
  350. return ((bool)jv ? 1ULL : 0ULL);
  351. }
  352. } catch ( ... ) {}
  353. return dfl;
  354. }
  355. uint64_t OSUtils::jsonIntHex(const nlohmann::json &jv,const uint64_t dfl)
  356. {
  357. try {
  358. if (jv.is_number()) {
  359. return (uint64_t)jv;
  360. } else if (jv.is_string()) {
  361. std::string s = jv;
  362. return Utils::hexStrToU64(s.c_str());
  363. } else if (jv.is_boolean()) {
  364. return ((bool)jv ? 1ULL : 0ULL);
  365. }
  366. } catch ( ... ) {}
  367. return dfl;
  368. }
  369. bool OSUtils::jsonBool(const nlohmann::json &jv,const bool dfl)
  370. {
  371. try {
  372. if (jv.is_boolean()) {
  373. return (bool)jv;
  374. } else if (jv.is_number()) {
  375. return ((uint64_t)jv > 0ULL);
  376. } else if (jv.is_string()) {
  377. std::string s = jv;
  378. if (s.length() > 0) {
  379. switch(s[0]) {
  380. case 't':
  381. case 'T':
  382. case '1':
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. } catch ( ... ) {}
  389. return dfl;
  390. }
  391. std::string OSUtils::jsonString(const nlohmann::json &jv,const char *dfl)
  392. {
  393. try {
  394. if (jv.is_string()) {
  395. return jv;
  396. } else if (jv.is_number()) {
  397. char tmp[64];
  398. ztsnprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  399. return tmp;
  400. } else if (jv.is_boolean()) {
  401. return ((bool)jv ? std::string("1") : std::string("0"));
  402. }
  403. } catch ( ... ) {}
  404. return std::string((dfl) ? dfl : "");
  405. }
  406. #endif // OMIT_JSON_SUPPORT
  407. // Used to convert HTTP header names to ASCII lower case
  408. 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 };
  409. } // namespace ZeroTier