Utils.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. PROCESS_INFORMATION processInfo;
  227. startupInfo.cb = sizeof(startupInfo);
  228. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  229. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  230. 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)) {
  231. WaitForSingleObject(processInfo.hProcess,INFINITE);
  232. CloseHandle(processInfo.hProcess);
  233. CloseHandle(processInfo.hThread);
  234. }
  235. startupInfo.cb = sizeof(startupInfo);
  236. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  237. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  238. 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)) {
  239. WaitForSingleObject(processInfo.hProcess,INFINITE);
  240. CloseHandle(processInfo.hProcess);
  241. CloseHandle(processInfo.hThread);
  242. }
  243. }
  244. #endif
  245. #endif
  246. }
  247. uint64_t Utils::getLastModified(const char *path)
  248. {
  249. struct stat s;
  250. if (stat(path,&s))
  251. return 0;
  252. return (((uint64_t)s.st_mtime) * 1000ULL);
  253. }
  254. bool Utils::fileExists(const char *path,bool followLinks)
  255. {
  256. struct stat s;
  257. #ifdef __UNIX_LIKE__
  258. if (!followLinks)
  259. return (lstat(path,&s) == 0);
  260. #endif
  261. return (stat(path,&s) == 0);
  262. }
  263. int64_t Utils::getFileSize(const char *path)
  264. {
  265. struct stat s;
  266. if (stat(path,&s))
  267. return -1;
  268. #ifdef __WINDOWS__
  269. return s.st_size;
  270. #else
  271. if (S_ISREG(s.st_mode))
  272. return s.st_size;
  273. #endif
  274. return -1;
  275. }
  276. bool Utils::readFile(const char *path,std::string &buf)
  277. {
  278. char tmp[4096];
  279. FILE *f = fopen(path,"rb");
  280. if (f) {
  281. for(;;) {
  282. long n = (long)fread(tmp,1,sizeof(tmp),f);
  283. if (n > 0)
  284. buf.append(tmp,n);
  285. else break;
  286. }
  287. fclose(f);
  288. return true;
  289. }
  290. return false;
  291. }
  292. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  293. {
  294. FILE *f = fopen(path,"wb");
  295. if (f) {
  296. if ((long)fwrite(buf,1,len,f) != (long)len) {
  297. fclose(f);
  298. return false;
  299. } else {
  300. fclose(f);
  301. return true;
  302. }
  303. }
  304. return false;
  305. }
  306. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  307. {
  308. std::vector<std::string> fields;
  309. std::string buf;
  310. if (!esc)
  311. esc = "";
  312. if (!quot)
  313. quot = "";
  314. bool escapeState = false;
  315. char quoteState = 0;
  316. while (*s) {
  317. if (escapeState) {
  318. escapeState = false;
  319. buf.push_back(*s);
  320. } else if (quoteState) {
  321. if (*s == quoteState) {
  322. quoteState = 0;
  323. fields.push_back(buf);
  324. buf.clear();
  325. } else buf.push_back(*s);
  326. } else {
  327. const char *quotTmp;
  328. if (strchr(esc,*s))
  329. escapeState = true;
  330. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  331. quoteState = *quotTmp;
  332. else if (strchr(sep,*s)) {
  333. if (buf.size() > 0) {
  334. fields.push_back(buf);
  335. buf.clear();
  336. } // else skip runs of seperators
  337. } else buf.push_back(*s);
  338. }
  339. ++s;
  340. }
  341. if (buf.size())
  342. fields.push_back(buf);
  343. return fields;
  344. }
  345. std::string Utils::trim(const std::string &s)
  346. {
  347. unsigned long end = (unsigned long)s.length();
  348. while (end) {
  349. char c = s[end - 1];
  350. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  351. --end;
  352. else break;
  353. }
  354. unsigned long start = 0;
  355. while (start < end) {
  356. char c = s[start];
  357. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  358. ++start;
  359. else break;
  360. }
  361. return s.substr(start,end - start);
  362. }
  363. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  364. throw(std::length_error)
  365. {
  366. va_list ap;
  367. va_start(ap,fmt);
  368. int n = (int)vsnprintf(buf,len,fmt,ap);
  369. va_end(ap);
  370. if ((n >= (int)len)||(n < 0)) {
  371. if (len)
  372. buf[len - 1] = (char)0;
  373. throw std::length_error("buf[] overflow in Utils::snprintf");
  374. }
  375. return (unsigned int)n;
  376. }
  377. } // namespace ZeroTier