Utils.cpp 10 KB

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