Utils.cpp 10 KB

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