OSUtils.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <stdarg.h>
  22. #include <sys/stat.h>
  23. #include "../node/Constants.hpp"
  24. #include "../node/Utils.hpp"
  25. #ifdef __UNIX_LIKE__
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <sys/stat.h>
  32. #include <sys/uio.h>
  33. #include <dirent.h>
  34. #include <netdb.h>
  35. #endif
  36. #ifdef __WINDOWS__
  37. #include <windows.h>
  38. #include <wincrypt.h>
  39. #include <ShlObj.h>
  40. #include <netioapi.h>
  41. #include <iphlpapi.h>
  42. #endif
  43. #include "OSUtils.hpp"
  44. namespace ZeroTier {
  45. #ifdef __UNIX_LIKE__
  46. bool OSUtils::redirectUnixOutputs(const char *stdoutPath,const char *stderrPath)
  47. throw()
  48. {
  49. int fdout = ::open(stdoutPath,O_WRONLY|O_CREAT,0600);
  50. if (fdout > 0) {
  51. int fderr;
  52. if (stderrPath) {
  53. fderr = ::open(stderrPath,O_WRONLY|O_CREAT,0600);
  54. if (fderr <= 0) {
  55. ::close(fdout);
  56. return false;
  57. }
  58. } else fderr = fdout;
  59. ::close(STDOUT_FILENO);
  60. ::close(STDERR_FILENO);
  61. ::dup2(fdout,STDOUT_FILENO);
  62. ::dup2(fderr,STDERR_FILENO);
  63. return true;
  64. }
  65. return false;
  66. }
  67. #endif // __UNIX_LIKE__
  68. std::vector<std::string> OSUtils::listDirectory(const char *path)
  69. {
  70. std::vector<std::string> r;
  71. #ifdef __WINDOWS__
  72. HANDLE hFind;
  73. WIN32_FIND_DATAA ffd;
  74. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  75. do {
  76. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,".."))&&((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0))
  77. r.push_back(std::string(ffd.cFileName));
  78. } while (FindNextFileA(hFind,&ffd));
  79. FindClose(hFind);
  80. }
  81. #else
  82. struct dirent de;
  83. struct dirent *dptr;
  84. DIR *d = opendir(path);
  85. if (!d)
  86. return r;
  87. dptr = (struct dirent *)0;
  88. for(;;) {
  89. if (readdir_r(d,&de,&dptr))
  90. break;
  91. if (dptr) {
  92. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))&&(dptr->d_type != DT_DIR))
  93. r.push_back(std::string(dptr->d_name));
  94. } else break;
  95. }
  96. closedir(d);
  97. #endif
  98. return r;
  99. }
  100. std::map<std::string,char> OSUtils::listDirectoryFull(const char *path)
  101. {
  102. std::map<std::string,char> r;
  103. #ifdef __WINDOWS__
  104. HANDLE hFind;
  105. WIN32_FIND_DATAA ffd;
  106. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  107. do {
  108. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,".."))) {
  109. r[ffd.cFileName] = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) ? 'd' : 'f';
  110. }
  111. } while (FindNextFileA(hFind,&ffd));
  112. FindClose(hFind);
  113. }
  114. #else
  115. struct dirent de;
  116. struct dirent *dptr;
  117. DIR *d = opendir(path);
  118. if (!d)
  119. return r;
  120. dptr = (struct dirent *)0;
  121. for(;;) {
  122. if (readdir_r(d,&de,&dptr))
  123. break;
  124. if (dptr) {
  125. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))) {
  126. r[dptr->d_name] = (dptr->d_type == DT_DIR) ? 'd' : 'f';
  127. }
  128. } else break;
  129. }
  130. closedir(d);
  131. #endif
  132. return r;
  133. }
  134. long OSUtils::cleanDirectory(const char *path,const uint64_t olderThan)
  135. {
  136. long cleaned = 0;
  137. #ifdef __WINDOWS__
  138. HANDLE hFind;
  139. WIN32_FIND_DATAA ffd;
  140. LARGE_INTEGER date,adjust;
  141. adjust.QuadPart = 11644473600000 * 10000;
  142. char tmp[4096];
  143. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  144. do {
  145. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,".."))&&((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)) {
  146. date.HighPart = ffd.ftLastWriteTime.dwHighDateTime;
  147. date.LowPart = ffd.ftLastWriteTime.dwLowDateTime;
  148. if (date.QuadPart > 0) {
  149. date.QuadPart -= adjust.QuadPart;
  150. if (((date.QuadPart / 10000000) * 1000) < olderThan) {
  151. Utils::snprintf(tmp, sizeof(tmp), "%s\\%s", path, ffd.cFileName);
  152. if (DeleteFileA(tmp))
  153. ++cleaned;
  154. }
  155. }
  156. }
  157. } while (FindNextFileA(hFind,&ffd));
  158. FindClose(hFind);
  159. }
  160. #else
  161. struct dirent de;
  162. struct dirent *dptr;
  163. struct stat st;
  164. char tmp[4096];
  165. DIR *d = opendir(path);
  166. if (!d)
  167. return -1;
  168. dptr = (struct dirent *)0;
  169. for(;;) {
  170. if (readdir_r(d,&de,&dptr))
  171. break;
  172. if (dptr) {
  173. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,".."))&&(dptr->d_type == DT_REG)) {
  174. Utils::snprintf(tmp,sizeof(tmp),"%s/%s",path,dptr->d_name);
  175. if (stat(tmp,&st) == 0) {
  176. uint64_t mt = (uint64_t)(st.st_mtime);
  177. if ((mt > 0)&&((mt * 1000) < olderThan)) {
  178. if (unlink(tmp) == 0)
  179. ++cleaned;
  180. }
  181. }
  182. }
  183. } else break;
  184. }
  185. closedir(d);
  186. #endif
  187. return cleaned;
  188. }
  189. bool OSUtils::rmDashRf(const char *path)
  190. {
  191. #ifdef __WINDOWS__
  192. HANDLE hFind;
  193. WIN32_FIND_DATAA ffd;
  194. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  195. do {
  196. if ((strcmp(ffd.cFileName,".") != 0)&&(strcmp(ffd.cFileName,"..") != 0)) {
  197. if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  198. if (DeleteFileA((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()) == FALSE)
  199. return false;
  200. } else {
  201. if (!rmDashRf((std::string(path) + ZT_PATH_SEPARATOR_S + ffd.cFileName).c_str()))
  202. return false;
  203. }
  204. }
  205. } while (FindNextFileA(hFind,&ffd));
  206. FindClose(hFind);
  207. }
  208. return (RemoveDirectoryA(path) != FALSE);
  209. #else
  210. struct dirent de;
  211. struct dirent *dptr;
  212. DIR *d = opendir(path);
  213. if (!d)
  214. return true;
  215. dptr = (struct dirent *)0;
  216. for(;;) {
  217. if (readdir_r(d,&de,&dptr) != 0)
  218. break;
  219. if (!dptr)
  220. break;
  221. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  222. std::string p(path);
  223. p.push_back(ZT_PATH_SEPARATOR);
  224. p.append(dptr->d_name);
  225. if (unlink(p.c_str()) != 0) { // unlink first will remove symlinks instead of recursing them
  226. if (!rmDashRf(p.c_str()))
  227. return false;
  228. }
  229. }
  230. }
  231. closedir(d);
  232. return (rmdir(path) == 0);
  233. #endif
  234. }
  235. void OSUtils::lockDownFile(const char *path,bool isDir)
  236. {
  237. #ifdef __UNIX_LIKE__
  238. chmod(path,isDir ? 0700 : 0600);
  239. #else
  240. #ifdef __WINDOWS__
  241. {
  242. STARTUPINFOA startupInfo;
  243. PROCESS_INFORMATION processInfo;
  244. startupInfo.cb = sizeof(startupInfo);
  245. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  246. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  247. 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)) {
  248. WaitForSingleObject(processInfo.hProcess,INFINITE);
  249. CloseHandle(processInfo.hProcess);
  250. CloseHandle(processInfo.hThread);
  251. }
  252. startupInfo.cb = sizeof(startupInfo);
  253. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  254. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  255. 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)) {
  256. WaitForSingleObject(processInfo.hProcess,INFINITE);
  257. CloseHandle(processInfo.hProcess);
  258. CloseHandle(processInfo.hThread);
  259. }
  260. }
  261. #endif
  262. #endif
  263. }
  264. uint64_t OSUtils::getLastModified(const char *path)
  265. {
  266. struct stat s;
  267. if (stat(path,&s))
  268. return 0;
  269. return (((uint64_t)s.st_mtime) * 1000ULL);
  270. }
  271. bool OSUtils::fileExists(const char *path,bool followLinks)
  272. {
  273. struct stat s;
  274. #ifdef __UNIX_LIKE__
  275. if (!followLinks)
  276. return (lstat(path,&s) == 0);
  277. #endif
  278. return (stat(path,&s) == 0);
  279. }
  280. int64_t OSUtils::getFileSize(const char *path)
  281. {
  282. struct stat s;
  283. if (stat(path,&s))
  284. return -1;
  285. #ifdef __WINDOWS__
  286. return s.st_size;
  287. #else
  288. if (S_ISREG(s.st_mode))
  289. return s.st_size;
  290. #endif
  291. return -1;
  292. }
  293. bool OSUtils::readFile(const char *path,std::string &buf)
  294. {
  295. char tmp[1024];
  296. FILE *f = fopen(path,"rb");
  297. if (f) {
  298. for(;;) {
  299. long n = (long)fread(tmp,1,sizeof(tmp),f);
  300. if (n > 0)
  301. buf.append(tmp,n);
  302. else break;
  303. }
  304. fclose(f);
  305. return true;
  306. }
  307. return false;
  308. }
  309. bool OSUtils::writeFile(const char *path,const void *buf,unsigned int len)
  310. {
  311. FILE *f = fopen(path,"wb");
  312. if (f) {
  313. if ((long)fwrite(buf,1,len,f) != (long)len) {
  314. fclose(f);
  315. return false;
  316. } else {
  317. fclose(f);
  318. return true;
  319. }
  320. }
  321. return false;
  322. }
  323. std::vector<std::string> OSUtils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  324. {
  325. std::vector<std::string> fields;
  326. std::string buf;
  327. if (!esc)
  328. esc = "";
  329. if (!quot)
  330. quot = "";
  331. bool escapeState = false;
  332. char quoteState = 0;
  333. while (*s) {
  334. if (escapeState) {
  335. escapeState = false;
  336. buf.push_back(*s);
  337. } else if (quoteState) {
  338. if (*s == quoteState) {
  339. quoteState = 0;
  340. fields.push_back(buf);
  341. buf.clear();
  342. } else buf.push_back(*s);
  343. } else {
  344. const char *quotTmp;
  345. if (strchr(esc,*s))
  346. escapeState = true;
  347. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  348. quoteState = *quotTmp;
  349. else if (strchr(sep,*s)) {
  350. if (buf.size() > 0) {
  351. fields.push_back(buf);
  352. buf.clear();
  353. } // else skip runs of seperators
  354. } else buf.push_back(*s);
  355. }
  356. ++s;
  357. }
  358. if (buf.size())
  359. fields.push_back(buf);
  360. return fields;
  361. }
  362. std::string OSUtils::platformDefaultHomePath()
  363. {
  364. #ifdef __UNIX_LIKE__
  365. #ifdef __APPLE__
  366. // /Library/... on Apple
  367. return std::string("/Library/Application Support/ZeroTier/One");
  368. #else
  369. #ifdef __BSD__
  370. // BSD likes /var/db instead of /var/lib
  371. return std::string("/var/db/zerotier-one");
  372. #else
  373. // Use /var/lib for Linux and other *nix
  374. return std::string("/var/lib/zerotier-one");
  375. #endif
  376. #endif
  377. #else // not __UNIX_LIKE__
  378. #ifdef __WINDOWS__
  379. // Look up app data folder on Windows, e.g. C:\ProgramData\...
  380. char buf[16384];
  381. if (SUCCEEDED(SHGetFolderPathA(NULL,CSIDL_COMMON_APPDATA,NULL,0,buf)))
  382. return (std::string(buf) + "\\ZeroTier\\One");
  383. else return std::string("C:\\ZeroTier\\One");
  384. #else
  385. return (std::string(ZT_PATH_SEPARATOR_S) + "ZeroTier" + ZT_PATH_SEPARATOR_S + "One"); // UNKNOWN PLATFORM
  386. #endif
  387. #endif // __UNIX_LIKE__ or not...
  388. }
  389. // Inline these massive JSON operations in one place only to reduce binary footprint and compile time
  390. nlohmann::json OSUtils::jsonParse(const std::string &buf) { return nlohmann::json::parse(buf.c_str()); }
  391. std::string OSUtils::jsonDump(const nlohmann::json &j) { return j.dump(1); }
  392. uint64_t OSUtils::jsonInt(const nlohmann::json &jv,const uint64_t dfl)
  393. {
  394. try {
  395. if (jv.is_number()) {
  396. return (uint64_t)jv;
  397. } else if (jv.is_string()) {
  398. std::string s = jv;
  399. return Utils::strToU64(s.c_str());
  400. } else if (jv.is_boolean()) {
  401. return ((bool)jv ? 1ULL : 0ULL);
  402. }
  403. } catch ( ... ) {}
  404. return dfl;
  405. }
  406. bool OSUtils::jsonBool(const nlohmann::json &jv,const bool dfl)
  407. {
  408. try {
  409. if (jv.is_boolean()) {
  410. return (bool)jv;
  411. } else if (jv.is_number()) {
  412. return ((uint64_t)jv > 0ULL);
  413. } else if (jv.is_string()) {
  414. std::string s = jv;
  415. if (s.length() > 0) {
  416. switch(s[0]) {
  417. case 't':
  418. case 'T':
  419. case '1':
  420. return true;
  421. }
  422. }
  423. return false;
  424. }
  425. } catch ( ... ) {}
  426. return dfl;
  427. }
  428. std::string OSUtils::jsonString(const nlohmann::json &jv,const char *dfl)
  429. {
  430. try {
  431. if (jv.is_string()) {
  432. return jv;
  433. } else if (jv.is_number()) {
  434. char tmp[64];
  435. Utils::snprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  436. return tmp;
  437. } else if (jv.is_boolean()) {
  438. return ((bool)jv ? std::string("1") : std::string("0"));
  439. }
  440. } catch ( ... ) {}
  441. return std::string((dfl) ? dfl : "");
  442. }
  443. std::string OSUtils::jsonBinFromHex(const nlohmann::json &jv)
  444. {
  445. std::string s(jsonString(jv,""));
  446. if (s.length() > 0) {
  447. char *buf = new char[(s.length() / 2) + 1];
  448. try {
  449. unsigned int l = Utils::unhex(s,buf,(unsigned int)s.length());
  450. std::string b(buf,l);
  451. delete [] buf;
  452. return b;
  453. } catch ( ... ) {
  454. delete [] buf;
  455. }
  456. }
  457. return std::string();
  458. }
  459. // Used to convert HTTP header names to ASCII lower case
  460. 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 };
  461. } // namespace ZeroTier