Utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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[32768];
  167. static unsigned int randptr = sizeof(randbuf);
  168. #ifdef __WINDOWS__
  169. static Salsa20 s20;
  170. volatile bool s20Initialized = false;
  171. #endif
  172. Mutex::Lock _l(randomLock);
  173. for(unsigned int i=0;i<bytes;++i) {
  174. if (randptr >= sizeof(randbuf)) {
  175. #ifdef __UNIX_LIKE__
  176. int fd = ::open("/dev/urandom",O_RDONLY);
  177. if (fd < 0) {
  178. fprintf(stderr,"FATAL ERROR: unable to open /dev/urandom: %s"ZT_EOL_S,strerror(errno));
  179. exit(-1);
  180. }
  181. if ((int)::read(fd,randbuf,sizeof(randbuf)) != (int)sizeof(randbuf)) {
  182. fprintf(stderr,"FATAL ERROR: unable to read from /dev/urandom"ZT_EOL_S);
  183. exit(-1);
  184. }
  185. ::close(fd);
  186. #else
  187. #ifdef __WINDOWS__
  188. if (!s20Initialized) {
  189. s20Initialized = true;
  190. char ktmp[32];
  191. char ivtmp[8];
  192. for(int i=0;i<32;++i) ktmp[i] = (char)rand();
  193. for(int i=0;i<8;++i) ivtmp[i] = (char)rand();
  194. double now = Utils::nowf();
  195. memcpy(ktmp,&now,sizeof(now));
  196. DWORD tmp = GetCurrentProcessId();
  197. memcpy(ktmp + sizeof(double),&tmp,sizeof(tmp));
  198. tmp = GetTickCount();
  199. memcpy(ktmp + sizeof(double) + sizeof(DWORD),&tmp,sizeof(tmp));
  200. s20.init(ktmp,256,ivtmp);
  201. for(int i=0;i<sizeof(randbuf);++i) randbuf[i] = (char)rand();
  202. }
  203. s20.encrypt(randbuf,randbuf,sizeof(randbuf));
  204. #else
  205. no getSecureRandom() implementation;
  206. #endif
  207. #endif
  208. randptr = 0;
  209. }
  210. ((char *)buf)[i] = randbuf[randptr++];
  211. }
  212. }
  213. void Utils::lockDownFile(const char *path,bool isDir)
  214. {
  215. #if defined(__APPLE__) || defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  216. chmod(path,isDir ? 0700 : 0600);
  217. #else
  218. #ifdef _WIN32
  219. // TODO: windows ACL hell...
  220. #endif
  221. #endif
  222. }
  223. uint64_t Utils::getLastModified(const char *path)
  224. {
  225. struct stat s;
  226. if (stat(path,&s))
  227. return 0;
  228. return (((uint64_t)s.st_mtime) * 1000ULL);
  229. }
  230. std::string Utils::toRfc1123(uint64_t t64)
  231. {
  232. struct tm t;
  233. char buf[128];
  234. time_t utc = (time_t)(t64 / 1000ULL);
  235. #ifdef __WINDOWS__
  236. gmtime_s(&t,&utc);
  237. #else
  238. gmtime_r(&utc,&t);
  239. #endif
  240. 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);
  241. return std::string(buf);
  242. }
  243. #ifdef __WINDOWS__
  244. static int is_leap(unsigned y) {
  245. y += 1900;
  246. return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
  247. }
  248. static time_t timegm(struct tm *tm) {
  249. static const unsigned ndays[2][12] = {
  250. {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  251. {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  252. };
  253. time_t res = 0;
  254. int i;
  255. for (i = 70; i < tm->tm_year; ++i)
  256. res += is_leap(i) ? 366 : 365;
  257. for (i = 0; i < tm->tm_mon; ++i)
  258. res += ndays[is_leap(tm->tm_year)][i];
  259. res += tm->tm_mday - 1;
  260. res *= 24;
  261. res += tm->tm_hour;
  262. res *= 60;
  263. res += tm->tm_min;
  264. res *= 60;
  265. res += tm->tm_sec;
  266. return res;
  267. }
  268. #endif
  269. uint64_t Utils::fromRfc1123(const char *tstr)
  270. {
  271. struct tm t;
  272. char wdays[128],mons[128];
  273. int l = (int)strlen(tstr);
  274. if ((l < 29)||(l > 64))
  275. return 0;
  276. 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);
  277. if (assigned != 7)
  278. return 0;
  279. wdays[3] = '\0';
  280. for(t.tm_wday=0;t.tm_wday<7;++t.tm_wday) {
  281. #ifdef __WINDOWS__
  282. if (!_stricmp(DAY_NAMES[t.tm_wday],wdays))
  283. break;
  284. #else
  285. if (!strcasecmp(DAY_NAMES[t.tm_wday],wdays))
  286. break;
  287. #endif
  288. }
  289. if (t.tm_wday == 7)
  290. return 0;
  291. mons[3] = '\0';
  292. for(t.tm_mon=0;t.tm_mon<12;++t.tm_mon) {
  293. #ifdef __WINDOWS__
  294. if (!_stricmp(MONTH_NAMES[t.tm_mday],mons))
  295. break;
  296. #else
  297. if (!strcasecmp(MONTH_NAMES[t.tm_mday],mons))
  298. break;
  299. #endif
  300. }
  301. if (t.tm_mon == 12)
  302. return 0;
  303. t.tm_wday = 0; // ignored by timegm
  304. t.tm_yday = 0; // ignored by timegm
  305. t.tm_isdst = 0; // ignored by timegm
  306. time_t utc = timegm(&t);
  307. return ((utc > 0) ? (1000ULL * (uint64_t)utc) : 0ULL);
  308. }
  309. bool Utils::readFile(const char *path,std::string &buf)
  310. {
  311. char tmp[4096];
  312. FILE *f = fopen(path,"rb");
  313. if (f) {
  314. for(;;) {
  315. long n = (long)fread(tmp,1,sizeof(tmp),f);
  316. if (n > 0)
  317. buf.append(tmp,n);
  318. else break;
  319. }
  320. fclose(f);
  321. return true;
  322. }
  323. return false;
  324. }
  325. bool Utils::writeFile(const char *path,const void *buf,unsigned int len)
  326. {
  327. FILE *f = fopen(path,"wb");
  328. if (f) {
  329. if ((long)fwrite(buf,1,len,f) != (long)len) {
  330. fclose(f);
  331. return false;
  332. } else {
  333. fclose(f);
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  340. {
  341. std::vector<std::string> fields;
  342. std::string buf;
  343. if (!esc)
  344. esc = "";
  345. if (!quot)
  346. quot = "";
  347. bool escapeState = false;
  348. char quoteState = 0;
  349. while (*s) {
  350. if (escapeState) {
  351. escapeState = false;
  352. buf.push_back(*s);
  353. } else if (quoteState) {
  354. if (*s == quoteState) {
  355. quoteState = 0;
  356. fields.push_back(buf);
  357. buf.clear();
  358. } else buf.push_back(*s);
  359. } else {
  360. const char *quotTmp;
  361. if (strchr(esc,*s))
  362. escapeState = true;
  363. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  364. quoteState = *quotTmp;
  365. else if (strchr(sep,*s)) {
  366. if (buf.size() > 0) {
  367. fields.push_back(buf);
  368. buf.clear();
  369. } // else skip runs of seperators
  370. } else buf.push_back(*s);
  371. }
  372. ++s;
  373. }
  374. if (buf.size())
  375. fields.push_back(buf);
  376. return fields;
  377. }
  378. std::string Utils::trim(const std::string &s)
  379. {
  380. unsigned long end = (unsigned long)s.length();
  381. while (end) {
  382. char c = s[end - 1];
  383. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  384. --end;
  385. else break;
  386. }
  387. unsigned long start = 0;
  388. while (start < end) {
  389. char c = s[start];
  390. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  391. ++start;
  392. else break;
  393. }
  394. return s.substr(start,end - start);
  395. }
  396. void Utils::stdsprintf(std::string &s,const char *fmt,...)
  397. throw(std::bad_alloc,std::length_error)
  398. {
  399. char buf[65536];
  400. va_list ap;
  401. va_start(ap,fmt);
  402. int n = vsnprintf(buf,sizeof(buf),fmt,ap);
  403. va_end(ap);
  404. if ((n >= (int)sizeof(buf))||(n < 0))
  405. throw std::length_error("printf result too large");
  406. s.append(buf);
  407. }
  408. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  409. throw(std::length_error)
  410. {
  411. va_list ap;
  412. va_start(ap,fmt);
  413. int n = (int)vsnprintf(buf,len,fmt,ap);
  414. va_end(ap);
  415. if ((n >= (int)len)||(n < 0)) {
  416. if (len)
  417. buf[len - 1] = (char)0;
  418. throw std::length_error("buf[] overflow in Utils::snprintf");
  419. }
  420. return (unsigned int)n;
  421. }
  422. } // namespace ZeroTier