Utils.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdarg.h>
  31. #include <sys/stat.h>
  32. #include "Constants.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/stat.h>
  39. #include <sys/uio.h>
  40. #include <dirent.h>
  41. #endif
  42. #ifdef __WINDOWS__
  43. #include <wincrypt.h>
  44. #endif
  45. #include "Utils.hpp"
  46. #include "Mutex.hpp"
  47. namespace ZeroTier {
  48. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  49. #ifdef __UNIX_LIKE__
  50. bool Utils::redirectUnixOutputs(const char *stdoutPath,const char *stderrPath)
  51. throw()
  52. {
  53. int fdout = ::open(stdoutPath,O_WRONLY|O_CREAT);
  54. if (fdout > 0) {
  55. int fderr;
  56. if (stderrPath) {
  57. fderr = ::open(stderrPath,O_WRONLY|O_CREAT);
  58. if (fderr <= 0) {
  59. ::close(fdout);
  60. return false;
  61. }
  62. } else fderr = fdout;
  63. ::close(STDOUT_FILENO);
  64. ::close(STDERR_FILENO);
  65. ::dup2(fdout,STDOUT_FILENO);
  66. ::dup2(fderr,STDERR_FILENO);
  67. return true;
  68. }
  69. return false;
  70. }
  71. #endif // __UNIX_LIKE__
  72. std::map<std::string,bool> Utils::listDirectory(const char *path)
  73. {
  74. std::map<std::string,bool> r;
  75. #ifdef __WINDOWS__
  76. HANDLE hFind;
  77. WIN32_FIND_DATAA ffd;
  78. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  79. do {
  80. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,"..")))
  81. r[std::string(ffd.cFileName)] = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  82. } while (FindNextFileA(hFind,&ffd));
  83. FindClose(hFind);
  84. }
  85. #else
  86. struct dirent de;
  87. struct dirent *dptr;
  88. DIR *d = opendir(path);
  89. if (!d)
  90. return r;
  91. dptr = (struct dirent *)0;
  92. for(;;) {
  93. if (readdir_r(d,&de,&dptr))
  94. break;
  95. if (dptr) {
  96. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,"..")))
  97. r[std::string(dptr->d_name)] = (dptr->d_type == DT_DIR);
  98. } else break;
  99. }
  100. #endif
  101. return r;
  102. }
  103. std::string Utils::hex(const void *data,unsigned int len)
  104. {
  105. std::string r;
  106. r.reserve(len * 2);
  107. for(unsigned int i=0;i<len;++i) {
  108. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  109. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  110. }
  111. return r;
  112. }
  113. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  114. {
  115. int n = 1;
  116. unsigned char c,b = 0;
  117. const char *eof = hex + maxlen;
  118. std::string r;
  119. if (!maxlen)
  120. return r;
  121. while ((c = (unsigned char)*(hex++))) {
  122. if ((c >= 48)&&(c <= 57)) { // 0..9
  123. if ((n ^= 1))
  124. r.push_back((char)(b | (c - 48)));
  125. else b = (c - 48) << 4;
  126. } else if ((c >= 65)&&(c <= 70)) { // A..F
  127. if ((n ^= 1))
  128. r.push_back((char)(b | (c - (65 - 10))));
  129. else b = (c - (65 - 10)) << 4;
  130. } else if ((c >= 97)&&(c <= 102)) { // a..f
  131. if ((n ^= 1))
  132. r.push_back((char)(b | (c - (97 - 10))));
  133. else b = (c - (97 - 10)) << 4;
  134. }
  135. if (hex == eof)
  136. break;
  137. }
  138. return r;
  139. }
  140. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  141. {
  142. int n = 1;
  143. unsigned char c,b = 0;
  144. unsigned int l = 0;
  145. const char *eof = hex + maxlen;
  146. if (!maxlen)
  147. return 0;
  148. while ((c = (unsigned char)*(hex++))) {
  149. if ((c >= 48)&&(c <= 57)) { // 0..9
  150. if ((n ^= 1)) {
  151. if (l >= len) break;
  152. ((unsigned char *)buf)[l++] = (b | (c - 48));
  153. } else b = (c - 48) << 4;
  154. } else if ((c >= 65)&&(c <= 70)) { // A..F
  155. if ((n ^= 1)) {
  156. if (l >= len) break;
  157. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  158. } else b = (c - (65 - 10)) << 4;
  159. } else if ((c >= 97)&&(c <= 102)) { // a..f
  160. if ((n ^= 1)) {
  161. if (l >= len) break;
  162. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  163. } else b = (c - (97 - 10)) << 4;
  164. }
  165. if (hex == eof)
  166. break;
  167. }
  168. return l;
  169. }
  170. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  171. {
  172. #ifdef __WINDOWS__
  173. static HCRYPTPROV cryptProvider = NULL;
  174. static Mutex globalLock;
  175. Mutex::Lock _l(globalLock);
  176. if (cryptProvider == NULL) {
  177. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  178. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  179. exit(1);
  180. return;
  181. }
  182. }
  183. if (!CryptGenRandom(cryptProvider,(DWORD)bytes,(BYTE *)buf)) {
  184. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  185. exit(1);
  186. }
  187. #else // not __WINDOWS__
  188. #ifdef __UNIX_LIKE__
  189. static char randomBuf[65536];
  190. static unsigned int randomPtr = sizeof(randomBuf);
  191. static int devURandomFd = -1;
  192. static Mutex globalLock;
  193. Mutex::Lock _l(globalLock);
  194. if (devURandomFd <= 0) {
  195. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  196. if (devURandomFd <= 0) {
  197. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\r\n");
  198. exit(1);
  199. return;
  200. }
  201. }
  202. for(unsigned int i=0;i<bytes;++i) {
  203. if (randomPtr >= sizeof(randomBuf)) {
  204. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  205. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to read from /dev/urandom\r\n");
  206. exit(1);
  207. return;
  208. }
  209. randomPtr = 0;
  210. }
  211. ((char *)buf)[i] = randomBuf[randomPtr++];
  212. }
  213. #else // not __UNIX_LIKE__
  214. #error No getSecureRandom() implementation available.
  215. #endif // __UNIX_LIKE__
  216. #endif // __WINDOWS__
  217. }
  218. void Utils::lockDownFile(const char *path,bool isDir)
  219. {
  220. #ifdef __UNIX_LIKE__
  221. chmod(path,isDir ? 0700 : 0600);
  222. #else
  223. #ifdef __WINDOWS__
  224. {
  225. STARTUPINFOA startupInfo;
  226. startupInfo.cb = sizeof(startupInfo);
  227. PROCESS_INFORMATION processInfo;
  228. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  229. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  230. /*
  231. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\cacls.exe \"") + path + "\" /E /R Users").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  232. WaitForSingleObject(processInfo.hProcess,INFINITE);
  233. CloseHandle(processInfo.hProcess);
  234. CloseHandle(processInfo.hThread);
  235. }
  236. */
  237. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\icacls.exe \"") + path + "\" /inheritance:d /Q").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  238. WaitForSingleObject(processInfo.hProcess,INFINITE);
  239. CloseHandle(processInfo.hProcess);
  240. CloseHandle(processInfo.hThread);
  241. }
  242. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\icacls.exe \"") + path + "\" /remove *S-1-5-32-545 /Q").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  243. WaitForSingleObject(processInfo.hProcess,INFINITE);
  244. CloseHandle(processInfo.hProcess);
  245. CloseHandle(processInfo.hThread);
  246. }
  247. }
  248. #endif
  249. #endif
  250. }
  251. uint64_t Utils::getLastModified(const char *path)
  252. {
  253. struct stat s;
  254. if (stat(path,&s))
  255. return 0;
  256. return (((uint64_t)s.st_mtime) * 1000ULL);
  257. }
  258. bool Utils::fileExists(const char *path,bool followLinks)
  259. {
  260. struct stat s;
  261. #ifdef __UNIX_LIKE__
  262. if (!followLinks)
  263. return (lstat(path,&s) == 0);
  264. #endif
  265. return (stat(path,&s) == 0);
  266. }
  267. int64_t Utils::getFileSize(const char *path)
  268. {
  269. struct stat s;
  270. if (stat(path,&s))
  271. return -1;
  272. #ifdef __WINDOWS__
  273. return s.st_size;
  274. #else
  275. if (S_ISREG(s.st_mode))
  276. return s.st_size;
  277. #endif
  278. return -1;
  279. }
  280. bool Utils::readFile(const char *path,std::string &buf)
  281. {
  282. char tmp[4096];
  283. FILE *f = fopen(path,"rb");
  284. if (f) {
  285. for(;;) {
  286. long n = (long)fread(tmp,1,sizeof(tmp),f);
  287. if (n > 0)
  288. buf.append(tmp,n);
  289. else break;
  290. }
  291. fclose(f);
  292. return true;
  293. }
  294. return false;
  295. }
  296. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  297. {
  298. FILE *f = fopen(path,"wb");
  299. if (f) {
  300. if ((long)fwrite(buf,1,len,f) != (long)len) {
  301. fclose(f);
  302. return false;
  303. } else {
  304. fclose(f);
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  311. {
  312. std::vector<std::string> fields;
  313. std::string buf;
  314. if (!esc)
  315. esc = "";
  316. if (!quot)
  317. quot = "";
  318. bool escapeState = false;
  319. char quoteState = 0;
  320. while (*s) {
  321. if (escapeState) {
  322. escapeState = false;
  323. buf.push_back(*s);
  324. } else if (quoteState) {
  325. if (*s == quoteState) {
  326. quoteState = 0;
  327. fields.push_back(buf);
  328. buf.clear();
  329. } else buf.push_back(*s);
  330. } else {
  331. const char *quotTmp;
  332. if (strchr(esc,*s))
  333. escapeState = true;
  334. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  335. quoteState = *quotTmp;
  336. else if (strchr(sep,*s)) {
  337. if (buf.size() > 0) {
  338. fields.push_back(buf);
  339. buf.clear();
  340. } // else skip runs of seperators
  341. } else buf.push_back(*s);
  342. }
  343. ++s;
  344. }
  345. if (buf.size())
  346. fields.push_back(buf);
  347. return fields;
  348. }
  349. std::string Utils::trim(const std::string &s)
  350. {
  351. unsigned long end = (unsigned long)s.length();
  352. while (end) {
  353. char c = s[end - 1];
  354. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  355. --end;
  356. else break;
  357. }
  358. unsigned long start = 0;
  359. while (start < end) {
  360. char c = s[start];
  361. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  362. ++start;
  363. else break;
  364. }
  365. return s.substr(start,end - start);
  366. }
  367. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  368. throw(std::length_error)
  369. {
  370. va_list ap;
  371. va_start(ap,fmt);
  372. int n = (int)vsnprintf(buf,len,fmt,ap);
  373. va_end(ap);
  374. if ((n >= (int)len)||(n < 0)) {
  375. if (len)
  376. buf[len - 1] = (char)0;
  377. throw std::length_error("buf[] overflow in Utils::snprintf");
  378. }
  379. return (unsigned int)n;
  380. }
  381. } // namespace ZeroTier