Utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. 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. std::string Utils::toRfc1123(uint64_t t64)
  239. {
  240. struct tm t;
  241. char buf[128];
  242. time_t utc = (time_t)(t64 / 1000ULL);
  243. #ifdef __WINDOWS__
  244. gmtime_s(&t,&utc);
  245. #else
  246. gmtime_r(&utc,&t);
  247. #endif
  248. 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);
  249. return std::string(buf);
  250. }
  251. #ifdef __WINDOWS__
  252. static int is_leap(unsigned y) {
  253. y += 1900;
  254. return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
  255. }
  256. static time_t timegm(struct tm *tm) {
  257. static const unsigned ndays[2][12] = {
  258. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  259. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  260. };
  261. time_t res = 0;
  262. int i;
  263. for (i = 70; i < tm->tm_year; ++i)
  264. res += is_leap(i) ? 366 : 365;
  265. for (i = 0; i < tm->tm_mon; ++i)
  266. res += ndays[is_leap(tm->tm_year)][i];
  267. res += tm->tm_mday - 1;
  268. res *= 24;
  269. res += tm->tm_hour;
  270. res *= 60;
  271. res += tm->tm_min;
  272. res *= 60;
  273. res += tm->tm_sec;
  274. return res;
  275. }
  276. #endif
  277. uint64_t Utils::fromRfc1123(const char *tstr)
  278. {
  279. struct tm t;
  280. char wdays[128],mons[128];
  281. int l = (int)strlen(tstr);
  282. if ((l < 29)||(l > 64))
  283. return 0;
  284. 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);
  285. if (assigned != 7)
  286. return 0;
  287. wdays[3] = '\0';
  288. for(t.tm_wday=0;t.tm_wday<7;++t.tm_wday) {
  289. #ifdef __WINDOWS__
  290. if (!_stricmp(DAY_NAMES[t.tm_wday],wdays))
  291. break;
  292. #else
  293. if (!strcasecmp(DAY_NAMES[t.tm_wday],wdays))
  294. break;
  295. #endif
  296. }
  297. if (t.tm_wday == 7)
  298. return 0;
  299. mons[3] = '\0';
  300. for(t.tm_mon=0;t.tm_mon<12;++t.tm_mon) {
  301. #ifdef __WINDOWS__
  302. if (!_stricmp(MONTH_NAMES[t.tm_mday],mons))
  303. break;
  304. #else
  305. if (!strcasecmp(MONTH_NAMES[t.tm_mday],mons))
  306. break;
  307. #endif
  308. }
  309. if (t.tm_mon == 12)
  310. return 0;
  311. t.tm_wday = 0; // ignored by timegm
  312. t.tm_yday = 0; // ignored by timegm
  313. t.tm_isdst = 0; // ignored by timegm
  314. time_t utc = timegm(&t);
  315. return ((utc > 0) ? (1000ULL * (uint64_t)utc) : 0ULL);
  316. }
  317. bool Utils::readFile(const char *path,std::string &buf)
  318. {
  319. char tmp[4096];
  320. FILE *f = fopen(path,"rb");
  321. if (f) {
  322. for(;;) {
  323. long n = (long)fread(tmp,1,sizeof(tmp),f);
  324. if (n > 0)
  325. buf.append(tmp,n);
  326. else break;
  327. }
  328. fclose(f);
  329. return true;
  330. }
  331. return false;
  332. }
  333. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  334. {
  335. FILE *f = fopen(path,"wb");
  336. if (f) {
  337. if ((long)fwrite(buf,1,len,f) != (long)len) {
  338. fclose(f);
  339. return false;
  340. } else {
  341. fclose(f);
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  348. {
  349. std::vector<std::string> fields;
  350. std::string buf;
  351. if (!esc)
  352. esc = "";
  353. if (!quot)
  354. quot = "";
  355. bool escapeState = false;
  356. char quoteState = 0;
  357. while (*s) {
  358. if (escapeState) {
  359. escapeState = false;
  360. buf.push_back(*s);
  361. } else if (quoteState) {
  362. if (*s == quoteState) {
  363. quoteState = 0;
  364. fields.push_back(buf);
  365. buf.clear();
  366. } else buf.push_back(*s);
  367. } else {
  368. const char *quotTmp;
  369. if (strchr(esc,*s))
  370. escapeState = true;
  371. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  372. quoteState = *quotTmp;
  373. else if (strchr(sep,*s)) {
  374. if (buf.size() > 0) {
  375. fields.push_back(buf);
  376. buf.clear();
  377. } // else skip runs of seperators
  378. } else buf.push_back(*s);
  379. }
  380. ++s;
  381. }
  382. if (buf.size())
  383. fields.push_back(buf);
  384. return fields;
  385. }
  386. std::string Utils::trim(const std::string &s)
  387. {
  388. unsigned long end = (unsigned long)s.length();
  389. while (end) {
  390. char c = s[end - 1];
  391. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  392. --end;
  393. else break;
  394. }
  395. unsigned long start = 0;
  396. while (start < end) {
  397. char c = s[start];
  398. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  399. ++start;
  400. else break;
  401. }
  402. return s.substr(start,end - start);
  403. }
  404. void Utils::stdsprintf(std::string &s,const char *fmt,...)
  405. throw(std::bad_alloc,std::length_error)
  406. {
  407. char buf[65536];
  408. va_list ap;
  409. va_start(ap,fmt);
  410. int n = vsnprintf(buf,sizeof(buf),fmt,ap);
  411. va_end(ap);
  412. if ((n >= (int)sizeof(buf))||(n < 0))
  413. throw std::length_error("printf result too large");
  414. s.append(buf);
  415. }
  416. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  417. throw(std::length_error)
  418. {
  419. va_list ap;
  420. va_start(ap,fmt);
  421. int n = (int)vsnprintf(buf,len,fmt,ap);
  422. va_end(ap);
  423. if ((n >= (int)len)||(n < 0)) {
  424. if (len)
  425. buf[len - 1] = (char)0;
  426. throw std::length_error("buf[] overflow in Utils::snprintf");
  427. }
  428. return (unsigned int)n;
  429. }
  430. } // namespace ZeroTier