Utils.cpp 9.7 KB

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