Utils.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. throw()
  136. {
  137. int n = 1;
  138. unsigned char c,b = 0;
  139. unsigned int l = 0;
  140. const char *const end = hex + hexlen;
  141. while (hex != end) {
  142. c = (unsigned char)*(hex++);
  143. if ((c >= 48)&&(c <= 57)) { // 0..9
  144. if ((n ^= 1)) {
  145. if (l >= len) break;
  146. ((unsigned char *)buf)[l++] = (b | (c - 48));
  147. } else b = (c - 48) << 4;
  148. } else if ((c >= 65)&&(c <= 70)) { // A..F
  149. if ((n ^= 1)) {
  150. if (l >= len) break;
  151. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  152. } else b = (c - (65 - 10)) << 4;
  153. } else if ((c >= 97)&&(c <= 102)) { // a..f
  154. if ((n ^= 1)) {
  155. if (l >= len) break;
  156. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  157. } else b = (c - (97 - 10)) << 4;
  158. }
  159. }
  160. return l;
  161. }
  162. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  163. {
  164. static Mutex randomLock;
  165. static char randbuf[16384];
  166. static unsigned int randptr = sizeof(randbuf);
  167. static Salsa20 s20;
  168. static bool randInitialized = false;
  169. Mutex::Lock _l(randomLock);
  170. // A Salsa20 instance is used to mangle whatever our base
  171. // random source happens to be.
  172. if (!randInitialized) {
  173. randInitialized = true;
  174. memset(randbuf,0,sizeof(randbuf));
  175. char s20key[33];
  176. uint64_t s20iv = now();
  177. Utils::snprintf(s20key,sizeof(s20key),"%.16llx%.16llx",(unsigned long long)now(),(unsigned long long)((void *)&s20iv));
  178. s20.init(s20key,256,&s20iv,8);
  179. }
  180. for(unsigned int i=0;i<bytes;++i) {
  181. if (randptr >= sizeof(randbuf)) {
  182. #ifdef __UNIX_LIKE__
  183. {
  184. int fd = ::open("/dev/urandom",O_RDONLY);
  185. if (fd < 0) {
  186. fprintf(stderr,"FATAL ERROR: unable to open /dev/urandom: %s"ZT_EOL_S,strerror(errno));
  187. exit(-1);
  188. }
  189. if ((int)::read(fd,randbuf,sizeof(randbuf)) != (int)sizeof(randbuf)) {
  190. fprintf(stderr,"FATAL ERROR: unable to read from /dev/urandom"ZT_EOL_S);
  191. exit(-1);
  192. }
  193. ::close(fd);
  194. }
  195. #else
  196. #ifdef __WINDOWS__
  197. {
  198. char ktmp[32];
  199. char ivtmp[8];
  200. for(int i=0;i<32;++i) ktmp[i] = (char)rand();
  201. for(int i=0;i<8;++i) ivtmp[i] = (char)rand();
  202. double now = Utils::nowf();
  203. memcpy(ktmp,&now,sizeof(now));
  204. DWORD tmp = GetCurrentProcessId();
  205. memcpy(ktmp + sizeof(now),&tmp,sizeof(tmp));
  206. tmp = GetTickCount();
  207. memcpy(ktmp + sizeof(now) + sizeof(DWORD),&tmp,sizeof(tmp));
  208. Salsa20 s20tmp(ktmp,256,ivtmp,8);
  209. s20tmp.encrypt(randbuf,randbuf,sizeof(randbuf));
  210. }
  211. #else
  212. no getSecureRandom() implementation;
  213. #endif
  214. #endif
  215. s20.encrypt(randbuf,randbuf,sizeof(randbuf));
  216. randptr = 0;
  217. }
  218. ((char *)buf)[i] = randbuf[randptr++];
  219. }
  220. }
  221. void Utils::lockDownFile(const char *path,bool isDir)
  222. {
  223. #if defined(__APPLE__) || defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  224. chmod(path,isDir ? 0700 : 0600);
  225. #else
  226. #ifdef _WIN32
  227. // TODO: windows ACL hell...
  228. #endif
  229. #endif
  230. }
  231. uint64_t Utils::getLastModified(const char *path)
  232. {
  233. struct stat s;
  234. if (stat(path,&s))
  235. return 0;
  236. return (((uint64_t)s.st_mtime) * 1000ULL);
  237. }
  238. int64_t Utils::getFileSize(const char *path)
  239. {
  240. struct stat s;
  241. if (stat(path,&s))
  242. return -1;
  243. if (S_ISREG(s.st_mode))
  244. return s.st_size;
  245. return -1;
  246. }
  247. bool Utils::readFile(const char *path,std::string &buf)
  248. {
  249. char tmp[4096];
  250. FILE *f = fopen(path,"rb");
  251. if (f) {
  252. for(;;) {
  253. long n = (long)fread(tmp,1,sizeof(tmp),f);
  254. if (n > 0)
  255. buf.append(tmp,n);
  256. else break;
  257. }
  258. fclose(f);
  259. return true;
  260. }
  261. return false;
  262. }
  263. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  264. {
  265. FILE *f = fopen(path,"wb");
  266. if (f) {
  267. if ((long)fwrite(buf,1,len,f) != (long)len) {
  268. fclose(f);
  269. return false;
  270. } else {
  271. fclose(f);
  272. return true;
  273. }
  274. }
  275. return false;
  276. }
  277. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  278. {
  279. std::vector<std::string> fields;
  280. std::string buf;
  281. if (!esc)
  282. esc = "";
  283. if (!quot)
  284. quot = "";
  285. bool escapeState = false;
  286. char quoteState = 0;
  287. while (*s) {
  288. if (escapeState) {
  289. escapeState = false;
  290. buf.push_back(*s);
  291. } else if (quoteState) {
  292. if (*s == quoteState) {
  293. quoteState = 0;
  294. fields.push_back(buf);
  295. buf.clear();
  296. } else buf.push_back(*s);
  297. } else {
  298. const char *quotTmp;
  299. if (strchr(esc,*s))
  300. escapeState = true;
  301. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  302. quoteState = *quotTmp;
  303. else if (strchr(sep,*s)) {
  304. if (buf.size() > 0) {
  305. fields.push_back(buf);
  306. buf.clear();
  307. } // else skip runs of seperators
  308. } else buf.push_back(*s);
  309. }
  310. ++s;
  311. }
  312. if (buf.size())
  313. fields.push_back(buf);
  314. return fields;
  315. }
  316. std::string Utils::trim(const std::string &s)
  317. {
  318. unsigned long end = (unsigned long)s.length();
  319. while (end) {
  320. char c = s[end - 1];
  321. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  322. --end;
  323. else break;
  324. }
  325. unsigned long start = 0;
  326. while (start < end) {
  327. char c = s[start];
  328. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  329. ++start;
  330. else break;
  331. }
  332. return s.substr(start,end - start);
  333. }
  334. void Utils::stdsprintf(std::string &s,const char *fmt,...)
  335. throw(std::bad_alloc,std::length_error)
  336. {
  337. char buf[65536];
  338. va_list ap;
  339. va_start(ap,fmt);
  340. int n = vsnprintf(buf,sizeof(buf),fmt,ap);
  341. va_end(ap);
  342. if ((n >= (int)sizeof(buf))||(n < 0))
  343. throw std::length_error("printf result too large");
  344. s.append(buf);
  345. }
  346. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  347. throw(std::length_error)
  348. {
  349. va_list ap;
  350. va_start(ap,fmt);
  351. int n = (int)vsnprintf(buf,len,fmt,ap);
  352. va_end(ap);
  353. if ((n >= (int)len)||(n < 0)) {
  354. if (len)
  355. buf[len - 1] = (char)0;
  356. throw std::length_error("buf[] overflow in Utils::snprintf");
  357. }
  358. return (unsigned int)n;
  359. }
  360. } // namespace ZeroTier