Utils.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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/uio.h>
  39. #include <dirent.h>
  40. #endif
  41. #include "Utils.hpp"
  42. #include "Mutex.hpp"
  43. #include "Salsa20.hpp"
  44. namespace ZeroTier {
  45. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  46. std::map<std::string,bool> Utils::listDirectory(const char *path)
  47. {
  48. std::map<std::string,bool> r;
  49. #ifdef __WINDOWS__
  50. HANDLE hFind;
  51. WIN32_FIND_DATAA ffd;
  52. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  53. do {
  54. if ((strcmp(ffd.cFileName,"."))&&(strcmp(ffd.cFileName,"..")))
  55. r[std::string(ffd.cFileName)] = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  56. } while (FindNextFileA(hFind,&ffd));
  57. FindClose(hFind);
  58. }
  59. #else
  60. struct dirent de;
  61. struct dirent *dptr;
  62. DIR *d = opendir(path);
  63. if (!d)
  64. return r;
  65. dptr = (struct dirent *)0;
  66. for(;;) {
  67. if (readdir_r(d,&de,&dptr))
  68. break;
  69. if (dptr) {
  70. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,"..")))
  71. r[std::string(dptr->d_name)] = (dptr->d_type == DT_DIR);
  72. } else break;
  73. }
  74. #endif
  75. return r;
  76. }
  77. std::string Utils::hex(const void *data,unsigned int len)
  78. {
  79. std::string r;
  80. r.reserve(len * 2);
  81. for(unsigned int i=0;i<len;++i) {
  82. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  83. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  84. }
  85. return r;
  86. }
  87. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  88. {
  89. int n = 1;
  90. unsigned char c,b = 0;
  91. const char *eof = hex + maxlen;
  92. std::string r;
  93. if (!maxlen)
  94. return r;
  95. while ((c = (unsigned char)*(hex++))) {
  96. if ((c >= 48)&&(c <= 57)) { // 0..9
  97. if ((n ^= 1))
  98. r.push_back((char)(b | (c - 48)));
  99. else b = (c - 48) << 4;
  100. } else if ((c >= 65)&&(c <= 70)) { // A..F
  101. if ((n ^= 1))
  102. r.push_back((char)(b | (c - (65 - 10))));
  103. else b = (c - (65 - 10)) << 4;
  104. } else if ((c >= 97)&&(c <= 102)) { // a..f
  105. if ((n ^= 1))
  106. r.push_back((char)(b | (c - (97 - 10))));
  107. else b = (c - (97 - 10)) << 4;
  108. }
  109. if (hex == eof)
  110. break;
  111. }
  112. return r;
  113. }
  114. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  115. {
  116. int n = 1;
  117. unsigned char c,b = 0;
  118. unsigned int l = 0;
  119. const char *eof = hex + maxlen;
  120. if (!maxlen)
  121. return 0;
  122. while ((c = (unsigned char)*(hex++))) {
  123. if ((c >= 48)&&(c <= 57)) { // 0..9
  124. if ((n ^= 1)) {
  125. if (l >= len) break;
  126. ((unsigned char *)buf)[l++] = (b | (c - 48));
  127. } else b = (c - 48) << 4;
  128. } else if ((c >= 65)&&(c <= 70)) { // A..F
  129. if ((n ^= 1)) {
  130. if (l >= len) break;
  131. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  132. } else b = (c - (65 - 10)) << 4;
  133. } else if ((c >= 97)&&(c <= 102)) { // a..f
  134. if ((n ^= 1)) {
  135. if (l >= len) break;
  136. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  137. } else b = (c - (97 - 10)) << 4;
  138. }
  139. if (hex == eof)
  140. break;
  141. }
  142. return l;
  143. }
  144. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  145. {
  146. static Mutex randomLock;
  147. static char randbuf[16384];
  148. static unsigned int randptr = sizeof(randbuf);
  149. static Salsa20 s20;
  150. static bool randInitialized = false;
  151. Mutex::Lock _l(randomLock);
  152. // A Salsa20/8 instance is used to further mangle whatever our base
  153. // random source happens to be.
  154. if (!randInitialized) {
  155. randInitialized = true;
  156. memset(randbuf,0,sizeof(randbuf));
  157. char s20key[33];
  158. uint64_t s20iv = now();
  159. Utils::snprintf(s20key,sizeof(s20key),"%.16llx%.16llx",(unsigned long long)now(),(unsigned long long)((void *)&s20iv));
  160. s20.init(s20key,256,&s20iv,8);
  161. }
  162. for(unsigned int i=0;i<bytes;++i) {
  163. if (randptr >= sizeof(randbuf)) {
  164. #ifdef __UNIX_LIKE__
  165. {
  166. int fd = ::open("/dev/urandom",O_RDONLY);
  167. if (fd < 0) {
  168. fprintf(stderr,"FATAL ERROR: unable to open /dev/urandom (%d)"ZT_EOL_S,errno);
  169. exit(-1);
  170. }
  171. if ((int)::read(fd,randbuf,sizeof(randbuf)) != (int)sizeof(randbuf)) {
  172. fprintf(stderr,"FATAL ERROR: unable to read from /dev/urandom"ZT_EOL_S);
  173. exit(-1);
  174. }
  175. ::close(fd);
  176. }
  177. #else
  178. #ifdef __WINDOWS__
  179. {
  180. struct {
  181. double nowf;
  182. DWORD processId;
  183. DWORD tickCount;
  184. uint64_t nowi;
  185. char padding[32];
  186. } keyMaterial;
  187. keyMaterial.nowf = Utils::nowf();
  188. keyMaterial.processId = GetCurrentProcessId();
  189. keyMaterial.tickCount = GetTickCount();
  190. keyMaterial.nowi = Utils::now();
  191. for(int i=0;i<sizeof(keyMaterial.padding);++i)
  192. keyMaterial.padding[i] = (char)rand();
  193. Salsa20 s20tmp(&keyMaterial,256,&(keyMaterial.nowi),8);
  194. s20tmp.encrypt(randbuf,randbuf,sizeof(randbuf));
  195. }
  196. #else
  197. no getSecureRandom() implementation;
  198. #endif
  199. #endif
  200. s20.encrypt(randbuf,randbuf,sizeof(randbuf));
  201. randptr = 0;
  202. }
  203. ((char *)buf)[i] = randbuf[randptr++];
  204. }
  205. }
  206. void Utils::lockDownFile(const char *path,bool isDir)
  207. {
  208. #ifdef __UNIX_LIKE__
  209. chmod(path,isDir ? 0700 : 0600);
  210. #else
  211. #ifdef __WINDOWS__
  212. {
  213. STARTUPINFOA startupInfo;
  214. startupInfo.cb = sizeof(startupInfo);
  215. PROCESS_INFORMATION processInfo;
  216. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  217. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  218. /*
  219. 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)) {
  220. WaitForSingleObject(processInfo.hProcess,INFINITE);
  221. CloseHandle(processInfo.hProcess);
  222. CloseHandle(processInfo.hThread);
  223. }
  224. */
  225. 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)) {
  226. WaitForSingleObject(processInfo.hProcess,INFINITE);
  227. CloseHandle(processInfo.hProcess);
  228. CloseHandle(processInfo.hThread);
  229. }
  230. 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)) {
  231. WaitForSingleObject(processInfo.hProcess,INFINITE);
  232. CloseHandle(processInfo.hProcess);
  233. CloseHandle(processInfo.hThread);
  234. }
  235. }
  236. #endif
  237. #endif
  238. }
  239. uint64_t Utils::getLastModified(const char *path)
  240. {
  241. struct stat s;
  242. if (stat(path,&s))
  243. return 0;
  244. return (((uint64_t)s.st_mtime) * 1000ULL);
  245. }
  246. bool Utils::fileExists(const char *path,bool followLinks)
  247. {
  248. struct stat s;
  249. #ifdef __UNIX_LIKE__
  250. if (!followLinks)
  251. return (lstat(path,&s) == 0);
  252. #endif
  253. return (stat(path,&s) == 0);
  254. }
  255. int64_t Utils::getFileSize(const char *path)
  256. {
  257. struct stat s;
  258. if (stat(path,&s))
  259. return -1;
  260. #ifdef __WINDOWS__
  261. return s.st_size;
  262. #else
  263. if (S_ISREG(s.st_mode))
  264. return s.st_size;
  265. #endif
  266. return -1;
  267. }
  268. bool Utils::readFile(const char *path,std::string &buf)
  269. {
  270. char tmp[4096];
  271. FILE *f = fopen(path,"rb");
  272. if (f) {
  273. for(;;) {
  274. long n = (long)fread(tmp,1,sizeof(tmp),f);
  275. if (n > 0)
  276. buf.append(tmp,n);
  277. else break;
  278. }
  279. fclose(f);
  280. return true;
  281. }
  282. return false;
  283. }
  284. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  285. {
  286. FILE *f = fopen(path,"wb");
  287. if (f) {
  288. if ((long)fwrite(buf,1,len,f) != (long)len) {
  289. fclose(f);
  290. return false;
  291. } else {
  292. fclose(f);
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  299. {
  300. std::vector<std::string> fields;
  301. std::string buf;
  302. if (!esc)
  303. esc = "";
  304. if (!quot)
  305. quot = "";
  306. bool escapeState = false;
  307. char quoteState = 0;
  308. while (*s) {
  309. if (escapeState) {
  310. escapeState = false;
  311. buf.push_back(*s);
  312. } else if (quoteState) {
  313. if (*s == quoteState) {
  314. quoteState = 0;
  315. fields.push_back(buf);
  316. buf.clear();
  317. } else buf.push_back(*s);
  318. } else {
  319. const char *quotTmp;
  320. if (strchr(esc,*s))
  321. escapeState = true;
  322. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  323. quoteState = *quotTmp;
  324. else if (strchr(sep,*s)) {
  325. if (buf.size() > 0) {
  326. fields.push_back(buf);
  327. buf.clear();
  328. } // else skip runs of seperators
  329. } else buf.push_back(*s);
  330. }
  331. ++s;
  332. }
  333. if (buf.size())
  334. fields.push_back(buf);
  335. return fields;
  336. }
  337. std::string Utils::trim(const std::string &s)
  338. {
  339. unsigned long end = (unsigned long)s.length();
  340. while (end) {
  341. char c = s[end - 1];
  342. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  343. --end;
  344. else break;
  345. }
  346. unsigned long start = 0;
  347. while (start < end) {
  348. char c = s[start];
  349. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  350. ++start;
  351. else break;
  352. }
  353. return s.substr(start,end - start);
  354. }
  355. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  356. throw(std::length_error)
  357. {
  358. va_list ap;
  359. va_start(ap,fmt);
  360. int n = (int)vsnprintf(buf,len,fmt,ap);
  361. va_end(ap);
  362. if ((n >= (int)len)||(n < 0)) {
  363. if (len)
  364. buf[len - 1] = (char)0;
  365. throw std::length_error("buf[] overflow in Utils::snprintf");
  366. }
  367. return (unsigned int)n;
  368. }
  369. } // namespace ZeroTier