Utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. static const char *DAY_NAMES[7] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
  47. static const char *MONTH_NAMES[12] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
  48. std::map<std::string,bool> Utils::listDirectory(const char *path)
  49. {
  50. std::map<std::string,bool> r;
  51. #ifdef __WINDOWS__
  52. HANDLE hFind;
  53. WIN32_FIND_DATAA ffd;
  54. if ((hFind = FindFirstFileA((std::string(path) + "\\*").c_str(),&ffd)) != INVALID_HANDLE_VALUE) {
  55. do {
  56. r[std::string(ffd.cFileName)] = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  57. } while (FindNextFileA(hFind,&ffd));
  58. FindClose(hFind);
  59. }
  60. #else
  61. struct dirent de;
  62. struct dirent *dptr;
  63. DIR *d = opendir(path);
  64. if (!d)
  65. return r;
  66. dptr = (struct dirent *)0;
  67. for(;;) {
  68. if (readdir_r(d,&de,&dptr))
  69. break;
  70. if (dptr) {
  71. if ((strcmp(dptr->d_name,"."))&&(strcmp(dptr->d_name,"..")))
  72. r[std::string(dptr->d_name)] = (dptr->d_type == DT_DIR);
  73. } else break;
  74. }
  75. #endif
  76. return r;
  77. }
  78. std::string Utils::hex(const void *data,unsigned int len)
  79. {
  80. std::string r;
  81. r.reserve(len * 2);
  82. for(unsigned int i=0;i<len;++i) {
  83. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  84. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  85. }
  86. return r;
  87. }
  88. std::string Utils::unhex(const char *hex)
  89. {
  90. int n = 1;
  91. unsigned char c,b = 0;
  92. std::string r;
  93. while ((c = (unsigned char)*(hex++))) {
  94. if ((c >= 48)&&(c <= 57)) { // 0..9
  95. if ((n ^= 1))
  96. r.push_back((char)(b | (c - 48)));
  97. else b = (c - 48) << 4;
  98. } else if ((c >= 65)&&(c <= 70)) { // A..F
  99. if ((n ^= 1))
  100. r.push_back((char)(b | (c - (65 - 10))));
  101. else b = (c - (65 - 10)) << 4;
  102. } else if ((c >= 97)&&(c <= 102)) { // a..f
  103. if ((n ^= 1))
  104. r.push_back((char)(b | (c - (97 - 10))));
  105. else b = (c - (97 - 10)) << 4;
  106. }
  107. }
  108. return r;
  109. }
  110. unsigned int Utils::unhex(const char *hex,void *buf,unsigned int len)
  111. {
  112. int n = 1;
  113. unsigned char c,b = 0;
  114. unsigned int l = 0;
  115. while ((c = (unsigned char)*(hex++))) {
  116. if ((c >= 48)&&(c <= 57)) { // 0..9
  117. if ((n ^= 1)) {
  118. if (l >= len) break;
  119. ((unsigned char *)buf)[l++] = (b | (c - 48));
  120. } else b = (c - 48) << 4;
  121. } else if ((c >= 65)&&(c <= 70)) { // A..F
  122. if ((n ^= 1)) {
  123. if (l >= len) break;
  124. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  125. } else b = (c - (65 - 10)) << 4;
  126. } else if ((c >= 97)&&(c <= 102)) { // a..f
  127. if ((n ^= 1)) {
  128. if (l >= len) break;
  129. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  130. } else b = (c - (97 - 10)) << 4;
  131. }
  132. }
  133. return l;
  134. }
  135. unsigned int Utils::unhex(const char *hex,unsigned int hexlen,void *buf,unsigned int len)
  136. throw()
  137. {
  138. int n = 1;
  139. unsigned char c,b = 0;
  140. unsigned int l = 0;
  141. const char *const end = hex + hexlen;
  142. while (hex != end) {
  143. c = (unsigned char)*(hex++);
  144. if ((c >= 48)&&(c <= 57)) { // 0..9
  145. if ((n ^= 1)) {
  146. if (l >= len) break;
  147. ((unsigned char *)buf)[l++] = (b | (c - 48));
  148. } else b = (c - 48) << 4;
  149. } else if ((c >= 65)&&(c <= 70)) { // A..F
  150. if ((n ^= 1)) {
  151. if (l >= len) break;
  152. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  153. } else b = (c - (65 - 10)) << 4;
  154. } else if ((c >= 97)&&(c <= 102)) { // a..f
  155. if ((n ^= 1)) {
  156. if (l >= len) break;
  157. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  158. } else b = (c - (97 - 10)) << 4;
  159. }
  160. }
  161. return l;
  162. }
  163. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  164. {
  165. static Mutex randomLock;
  166. static char randbuf[16384];
  167. static unsigned int randptr = sizeof(randbuf);
  168. static Salsa20 s20;
  169. static bool randInitialized = false;
  170. Mutex::Lock _l(randomLock);
  171. // A Salsa20 instance is used to mangle whatever our base
  172. // random source happens to be.
  173. if (!randInitialized) {
  174. randInitialized = true;
  175. memset(randbuf,0,sizeof(randbuf));
  176. char s20key[33];
  177. uint64_t s20iv = now();
  178. Utils::snprintf(s20key,sizeof(s20key),"%.16llx%.16llx",(unsigned long long)now(),(unsigned long long)((void *)&s20iv));
  179. s20.init(s20key,256,&s20iv,8);
  180. }
  181. for(unsigned int i=0;i<bytes;++i) {
  182. if (randptr >= sizeof(randbuf)) {
  183. #ifdef __UNIX_LIKE__
  184. {
  185. int fd = ::open("/dev/urandom",O_RDONLY);
  186. if (fd < 0) {
  187. fprintf(stderr,"FATAL ERROR: unable to open /dev/urandom: %s"ZT_EOL_S,strerror(errno));
  188. exit(-1);
  189. }
  190. if ((int)::read(fd,randbuf,sizeof(randbuf)) != (int)sizeof(randbuf)) {
  191. fprintf(stderr,"FATAL ERROR: unable to read from /dev/urandom"ZT_EOL_S);
  192. exit(-1);
  193. }
  194. ::close(fd);
  195. }
  196. #else
  197. #ifdef __WINDOWS__
  198. {
  199. char ktmp[32];
  200. char ivtmp[8];
  201. for(int i=0;i<32;++i) ktmp[i] = (char)rand();
  202. for(int i=0;i<8;++i) ivtmp[i] = (char)rand();
  203. double now = Utils::nowf();
  204. memcpy(ktmp,&now,sizeof(now));
  205. DWORD tmp = GetCurrentProcessId();
  206. memcpy(ktmp + sizeof(now),&tmp,sizeof(tmp));
  207. tmp = GetTickCount();
  208. memcpy(ktmp + sizeof(now) + sizeof(DWORD),&tmp,sizeof(tmp));
  209. Salsa20 s20tmp(ktmp,256,ivtmp,8);
  210. s20tmp.encrypt(randbuf,randbuf,sizeof(randbuf));
  211. }
  212. #else
  213. no getSecureRandom() implementation;
  214. #endif
  215. #endif
  216. s20.encrypt(randbuf,randbuf,sizeof(randbuf));
  217. randptr = 0;
  218. }
  219. ((char *)buf)[i] = randbuf[randptr++];
  220. }
  221. }
  222. void Utils::lockDownFile(const char *path,bool isDir)
  223. {
  224. #if defined(__APPLE__) || defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  225. chmod(path,isDir ? 0700 : 0600);
  226. #else
  227. #ifdef _WIN32
  228. // TODO: windows ACL hell...
  229. #endif
  230. #endif
  231. }
  232. uint64_t Utils::getLastModified(const char *path)
  233. {
  234. struct stat s;
  235. if (stat(path,&s))
  236. return 0;
  237. return (((uint64_t)s.st_mtime) * 1000ULL);
  238. }
  239. std::string Utils::toRfc1123(uint64_t t64)
  240. {
  241. struct tm t;
  242. char buf[128];
  243. time_t utc = (time_t)(t64 / 1000ULL);
  244. #ifdef __WINDOWS__
  245. gmtime_s(&t,&utc);
  246. #else
  247. gmtime_r(&utc,&t);
  248. #endif
  249. Utils::snprintf(buf,sizeof(buf),"%3s, %02d %3s %4d %02d:%02d:%02d GMT",DAY_NAMES[t.tm_wday],t.tm_mday,MONTH_NAMES[t.tm_mon],t.tm_year + 1900,t.tm_hour,t.tm_min,t.tm_sec);
  250. return std::string(buf);
  251. }
  252. #ifdef __WINDOWS__
  253. static int is_leap(unsigned y) {
  254. y += 1900;
  255. return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
  256. }
  257. static time_t timegm(struct tm *tm) {
  258. static const unsigned ndays[2][12] = {
  259. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  260. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  261. };
  262. time_t res = 0;
  263. int i;
  264. for (i = 70; i < tm->tm_year; ++i)
  265. res += is_leap(i) ? 366 : 365;
  266. for (i = 0; i < tm->tm_mon; ++i)
  267. res += ndays[is_leap(tm->tm_year)][i];
  268. res += tm->tm_mday - 1;
  269. res *= 24;
  270. res += tm->tm_hour;
  271. res *= 60;
  272. res += tm->tm_min;
  273. res *= 60;
  274. res += tm->tm_sec;
  275. return res;
  276. }
  277. #endif
  278. uint64_t Utils::fromRfc1123(const char *tstr)
  279. {
  280. struct tm t;
  281. char wdays[128],mons[128];
  282. int l = (int)strlen(tstr);
  283. if ((l < 29)||(l > 64))
  284. return 0;
  285. int assigned = sscanf(tstr,"%3s, %02d %3s %4d %02d:%02d:%02d GMT",wdays,&t.tm_mday,mons,&t.tm_year,&t.tm_hour,&t.tm_min,&t.tm_sec);
  286. if (assigned != 7)
  287. return 0;
  288. wdays[3] = '\0';
  289. for(t.tm_wday=0;t.tm_wday<7;++t.tm_wday) {
  290. #ifdef __WINDOWS__
  291. if (!_stricmp(DAY_NAMES[t.tm_wday],wdays))
  292. break;
  293. #else
  294. if (!strcasecmp(DAY_NAMES[t.tm_wday],wdays))
  295. break;
  296. #endif
  297. }
  298. if (t.tm_wday == 7)
  299. return 0;
  300. mons[3] = '\0';
  301. for(t.tm_mon=0;t.tm_mon<12;++t.tm_mon) {
  302. #ifdef __WINDOWS__
  303. if (!_stricmp(MONTH_NAMES[t.tm_mday],mons))
  304. break;
  305. #else
  306. if (!strcasecmp(MONTH_NAMES[t.tm_mday],mons))
  307. break;
  308. #endif
  309. }
  310. if (t.tm_mon == 12)
  311. return 0;
  312. t.tm_wday = 0; // ignored by timegm
  313. t.tm_yday = 0; // ignored by timegm
  314. t.tm_isdst = 0; // ignored by timegm
  315. time_t utc = timegm(&t);
  316. return ((utc > 0) ? (1000ULL * (uint64_t)utc) : 0ULL);
  317. }
  318. bool Utils::readFile(const char *path,std::string &buf)
  319. {
  320. char tmp[4096];
  321. FILE *f = fopen(path,"rb");
  322. if (f) {
  323. for(;;) {
  324. long n = (long)fread(tmp,1,sizeof(tmp),f);
  325. if (n > 0)
  326. buf.append(tmp,n);
  327. else break;
  328. }
  329. fclose(f);
  330. return true;
  331. }
  332. return false;
  333. }
  334. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  335. {
  336. FILE *f = fopen(path,"wb");
  337. if (f) {
  338. if ((long)fwrite(buf,1,len,f) != (long)len) {
  339. fclose(f);
  340. return false;
  341. } else {
  342. fclose(f);
  343. return true;
  344. }
  345. }
  346. return false;
  347. }
  348. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  349. {
  350. std::vector<std::string> fields;
  351. std::string buf;
  352. if (!esc)
  353. esc = "";
  354. if (!quot)
  355. quot = "";
  356. bool escapeState = false;
  357. char quoteState = 0;
  358. while (*s) {
  359. if (escapeState) {
  360. escapeState = false;
  361. buf.push_back(*s);
  362. } else if (quoteState) {
  363. if (*s == quoteState) {
  364. quoteState = 0;
  365. fields.push_back(buf);
  366. buf.clear();
  367. } else buf.push_back(*s);
  368. } else {
  369. const char *quotTmp;
  370. if (strchr(esc,*s))
  371. escapeState = true;
  372. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  373. quoteState = *quotTmp;
  374. else if (strchr(sep,*s)) {
  375. if (buf.size() > 0) {
  376. fields.push_back(buf);
  377. buf.clear();
  378. } // else skip runs of seperators
  379. } else buf.push_back(*s);
  380. }
  381. ++s;
  382. }
  383. if (buf.size())
  384. fields.push_back(buf);
  385. return fields;
  386. }
  387. std::string Utils::trim(const std::string &s)
  388. {
  389. unsigned long end = (unsigned long)s.length();
  390. while (end) {
  391. char c = s[end - 1];
  392. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  393. --end;
  394. else break;
  395. }
  396. unsigned long start = 0;
  397. while (start < end) {
  398. char c = s[start];
  399. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  400. ++start;
  401. else break;
  402. }
  403. return s.substr(start,end - start);
  404. }
  405. void Utils::stdsprintf(std::string &s,const char *fmt,...)
  406. throw(std::bad_alloc,std::length_error)
  407. {
  408. char buf[65536];
  409. va_list ap;
  410. va_start(ap,fmt);
  411. int n = vsnprintf(buf,sizeof(buf),fmt,ap);
  412. va_end(ap);
  413. if ((n >= (int)sizeof(buf))||(n < 0))
  414. throw std::length_error("printf result too large");
  415. s.append(buf);
  416. }
  417. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  418. throw(std::length_error)
  419. {
  420. va_list ap;
  421. va_start(ap,fmt);
  422. int n = (int)vsnprintf(buf,len,fmt,ap);
  423. va_end(ap);
  424. if ((n >= (int)len)||(n < 0)) {
  425. if (len)
  426. buf[len - 1] = (char)0;
  427. throw std::length_error("buf[] overflow in Utils::snprintf");
  428. }
  429. return (unsigned int)n;
  430. }
  431. } // namespace ZeroTier