Utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2015 ZeroTier Networks
  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,0600);
  54. if (fdout > 0) {
  55. int fderr;
  56. if (stderrPath) {
  57. fderr = ::open(stderrPath,O_WRONLY|O_CREAT,0600);
  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. static void _Utils_doBurn(char *ptr,unsigned int len)
  73. {
  74. for(unsigned int i=0;i<len;++i)
  75. ptr[i] = (char)0;
  76. }
  77. void (*volatile _Utils_doBurn_ptr)(char *,unsigned int) = _Utils_doBurn;
  78. void Utils::burn(void *ptr,unsigned int len)
  79. throw()
  80. {
  81. // Ridiculous hack: call _doBurn() via a volatile function pointer to
  82. // hold down compiler optimizers and beat them mercilessly until they
  83. // cry and mumble something about never eliding secure memory zeroing
  84. // again.
  85. (_Utils_doBurn_ptr)((char *)ptr,len);
  86. }
  87. std::map<std::string,bool> Utils::listDirectory(const char *path)
  88. {
  89. std::map<std::string,bool> r;
  90. #ifdef __WINDOWS__
  91. HANDLE hFind;
  92. WIN32_FIND_DATAA ffd;
  93. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  94. do {
  95. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,"..")))
  96. r[std::string(ffd.cFileName)] = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  97. } while (FindNextFileA(hFind,&ffd));
  98. FindClose(hFind);
  99. }
  100. #else
  101. struct dirent de;
  102. struct dirent *dptr;
  103. DIR *d = opendir(path);
  104. if (!d)
  105. return r;
  106. dptr = (struct dirent *)0;
  107. for(;;) {
  108. if (readdir_r(d,&de,&dptr))
  109. break;
  110. if (dptr) {
  111. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,"..")))
  112. r[std::string(dptr->d_name)] = (dptr->d_type == DT_DIR);
  113. } else break;
  114. }
  115. #endif
  116. return r;
  117. }
  118. std::string Utils::hex(const void *data,unsigned int len)
  119. {
  120. std::string r;
  121. r.reserve(len * 2);
  122. for(unsigned int i=0;i<len;++i) {
  123. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  124. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  125. }
  126. return r;
  127. }
  128. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  129. {
  130. int n = 1;
  131. unsigned char c,b = 0;
  132. const char *eof = hex + maxlen;
  133. std::string r;
  134. if (!maxlen)
  135. return r;
  136. while ((c = (unsigned char)*(hex++))) {
  137. if ((c >= 48)&&(c <= 57)) { // 0..9
  138. if ((n ^= 1))
  139. r.push_back((char)(b | (c - 48)));
  140. else b = (c - 48) << 4;
  141. } else if ((c >= 65)&&(c <= 70)) { // A..F
  142. if ((n ^= 1))
  143. r.push_back((char)(b | (c - (65 - 10))));
  144. else b = (c - (65 - 10)) << 4;
  145. } else if ((c >= 97)&&(c <= 102)) { // a..f
  146. if ((n ^= 1))
  147. r.push_back((char)(b | (c - (97 - 10))));
  148. else b = (c - (97 - 10)) << 4;
  149. }
  150. if (hex == eof)
  151. break;
  152. }
  153. return r;
  154. }
  155. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  156. {
  157. int n = 1;
  158. unsigned char c,b = 0;
  159. unsigned int l = 0;
  160. const char *eof = hex + maxlen;
  161. if (!maxlen)
  162. return 0;
  163. while ((c = (unsigned char)*(hex++))) {
  164. if ((c >= 48)&&(c <= 57)) { // 0..9
  165. if ((n ^= 1)) {
  166. if (l >= len) break;
  167. ((unsigned char *)buf)[l++] = (b | (c - 48));
  168. } else b = (c - 48) << 4;
  169. } else if ((c >= 65)&&(c <= 70)) { // A..F
  170. if ((n ^= 1)) {
  171. if (l >= len) break;
  172. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  173. } else b = (c - (65 - 10)) << 4;
  174. } else if ((c >= 97)&&(c <= 102)) { // a..f
  175. if ((n ^= 1)) {
  176. if (l >= len) break;
  177. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  178. } else b = (c - (97 - 10)) << 4;
  179. }
  180. if (hex == eof)
  181. break;
  182. }
  183. return l;
  184. }
  185. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  186. {
  187. #ifdef __WINDOWS__
  188. static HCRYPTPROV cryptProvider = NULL;
  189. static Mutex globalLock;
  190. Mutex::Lock _l(globalLock);
  191. if (cryptProvider == NULL) {
  192. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  193. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  194. exit(1);
  195. return;
  196. }
  197. }
  198. if (!CryptGenRandom(cryptProvider,(DWORD)bytes,(BYTE *)buf)) {
  199. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  200. exit(1);
  201. }
  202. #else // not __WINDOWS__
  203. #ifdef __UNIX_LIKE__
  204. static char randomBuf[65536];
  205. static unsigned int randomPtr = sizeof(randomBuf);
  206. static int devURandomFd = -1;
  207. static Mutex globalLock;
  208. Mutex::Lock _l(globalLock);
  209. if (devURandomFd <= 0) {
  210. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  211. if (devURandomFd <= 0) {
  212. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\r\n");
  213. exit(1);
  214. return;
  215. }
  216. }
  217. for(unsigned int i=0;i<bytes;++i) {
  218. if (randomPtr >= sizeof(randomBuf)) {
  219. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  220. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to read from /dev/urandom\r\n");
  221. exit(1);
  222. return;
  223. }
  224. randomPtr = 0;
  225. }
  226. ((char *)buf)[i] = randomBuf[randomPtr++];
  227. }
  228. #else // not __UNIX_LIKE__
  229. #error No getSecureRandom() implementation available.
  230. #endif // __UNIX_LIKE__
  231. #endif // __WINDOWS__
  232. }
  233. void Utils::lockDownFile(const char *path,bool isDir)
  234. {
  235. #ifdef __UNIX_LIKE__
  236. chmod(path,isDir ? 0700 : 0600);
  237. #else
  238. #ifdef __WINDOWS__
  239. {
  240. STARTUPINFOA startupInfo;
  241. PROCESS_INFORMATION processInfo;
  242. startupInfo.cb = sizeof(startupInfo);
  243. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  244. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  245. 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)) {
  246. WaitForSingleObject(processInfo.hProcess,INFINITE);
  247. CloseHandle(processInfo.hProcess);
  248. CloseHandle(processInfo.hThread);
  249. }
  250. startupInfo.cb = sizeof(startupInfo);
  251. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  252. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  253. 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)) {
  254. WaitForSingleObject(processInfo.hProcess,INFINITE);
  255. CloseHandle(processInfo.hProcess);
  256. CloseHandle(processInfo.hThread);
  257. }
  258. }
  259. #endif
  260. #endif
  261. }
  262. uint64_t Utils::getLastModified(const char *path)
  263. {
  264. struct stat s;
  265. if (stat(path,&s))
  266. return 0;
  267. return (((uint64_t)s.st_mtime) * 1000ULL);
  268. }
  269. bool Utils::fileExists(const char *path,bool followLinks)
  270. {
  271. struct stat s;
  272. #ifdef __UNIX_LIKE__
  273. if (!followLinks)
  274. return (lstat(path,&s) == 0);
  275. #endif
  276. return (stat(path,&s) == 0);
  277. }
  278. int64_t Utils::getFileSize(const char *path)
  279. {
  280. struct stat s;
  281. if (stat(path,&s))
  282. return -1;
  283. #ifdef __WINDOWS__
  284. return s.st_size;
  285. #else
  286. if (S_ISREG(s.st_mode))
  287. return s.st_size;
  288. #endif
  289. return -1;
  290. }
  291. bool Utils::readFile(const char *path,std::string &buf)
  292. {
  293. char tmp[4096];
  294. FILE *f = fopen(path,"rb");
  295. if (f) {
  296. for(;;) {
  297. long n = (long)fread(tmp,1,sizeof(tmp),f);
  298. if (n > 0)
  299. buf.append(tmp,n);
  300. else break;
  301. }
  302. fclose(f);
  303. return true;
  304. }
  305. return false;
  306. }
  307. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  308. {
  309. FILE *f = fopen(path,"wb");
  310. if (f) {
  311. if ((long)fwrite(buf,1,len,f) != (long)len) {
  312. fclose(f);
  313. return false;
  314. } else {
  315. fclose(f);
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  322. {
  323. std::vector<std::string> fields;
  324. std::string buf;
  325. if (!esc)
  326. esc = "";
  327. if (!quot)
  328. quot = "";
  329. bool escapeState = false;
  330. char quoteState = 0;
  331. while (*s) {
  332. if (escapeState) {
  333. escapeState = false;
  334. buf.push_back(*s);
  335. } else if (quoteState) {
  336. if (*s == quoteState) {
  337. quoteState = 0;
  338. fields.push_back(buf);
  339. buf.clear();
  340. } else buf.push_back(*s);
  341. } else {
  342. const char *quotTmp;
  343. if (strchr(esc,*s))
  344. escapeState = true;
  345. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  346. quoteState = *quotTmp;
  347. else if (strchr(sep,*s)) {
  348. if (buf.size() > 0) {
  349. fields.push_back(buf);
  350. buf.clear();
  351. } // else skip runs of seperators
  352. } else buf.push_back(*s);
  353. }
  354. ++s;
  355. }
  356. if (buf.size())
  357. fields.push_back(buf);
  358. return fields;
  359. }
  360. std::string Utils::trim(const std::string &s)
  361. {
  362. unsigned long end = (unsigned long)s.length();
  363. while (end) {
  364. char c = s[end - 1];
  365. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  366. --end;
  367. else break;
  368. }
  369. unsigned long start = 0;
  370. while (start < end) {
  371. char c = s[start];
  372. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  373. ++start;
  374. else break;
  375. }
  376. return s.substr(start,end - start);
  377. }
  378. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  379. throw(std::length_error)
  380. {
  381. va_list ap;
  382. va_start(ap,fmt);
  383. int n = (int)vsnprintf(buf,len,fmt,ap);
  384. va_end(ap);
  385. if ((n >= (int)len)||(n < 0)) {
  386. if (len)
  387. buf[len - 1] = (char)0;
  388. throw std::length_error("buf[] overflow in Utils::snprintf");
  389. }
  390. return (unsigned int)n;
  391. }
  392. } // namespace ZeroTier