OSUtils.cpp 13 KB

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