Utils.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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/stat.h>
  39. #include <sys/uio.h>
  40. #include <dirent.h>
  41. #endif
  42. #ifdef __WINDOWS__
  43. #include <wincrypt.h>
  44. #endif
  45. #include "Utils.hpp"
  46. #include "Mutex.hpp"
  47. namespace ZeroTier {
  48. const char Utils::HEXCHARS[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  49. static void _Utils_doBurn(char *ptr,unsigned int len)
  50. {
  51. for(unsigned int i=0;i<len;++i)
  52. ptr[i] = (char)0;
  53. }
  54. void (*volatile _Utils_doBurn_ptr)(char *,unsigned int) = _Utils_doBurn;
  55. void Utils::burn(void *ptr,unsigned int len)
  56. throw()
  57. {
  58. // Ridiculous hack: call _doBurn() via a volatile function pointer to
  59. // hold down compiler optimizers and beat them mercilessly until they
  60. // cry and mumble something about never eliding secure memory zeroing
  61. // again.
  62. (_Utils_doBurn_ptr)((char *)ptr,len);
  63. }
  64. std::string Utils::hex(const void *data,unsigned int len)
  65. {
  66. std::string r;
  67. r.reserve(len * 2);
  68. for(unsigned int i=0;i<len;++i) {
  69. r.push_back(HEXCHARS[(((const unsigned char *)data)[i] & 0xf0) >> 4]);
  70. r.push_back(HEXCHARS[((const unsigned char *)data)[i] & 0x0f]);
  71. }
  72. return r;
  73. }
  74. std::string Utils::unhex(const char *hex,unsigned int maxlen)
  75. {
  76. int n = 1;
  77. unsigned char c,b = 0;
  78. const char *eof = hex + maxlen;
  79. std::string r;
  80. if (!maxlen)
  81. return r;
  82. while ((c = (unsigned char)*(hex++))) {
  83. if ((c >= 48)&&(c <= 57)) { // 0..9
  84. if ((n ^= 1))
  85. r.push_back((char)(b | (c - 48)));
  86. else b = (c - 48) << 4;
  87. } else if ((c >= 65)&&(c <= 70)) { // A..F
  88. if ((n ^= 1))
  89. r.push_back((char)(b | (c - (65 - 10))));
  90. else b = (c - (65 - 10)) << 4;
  91. } else if ((c >= 97)&&(c <= 102)) { // a..f
  92. if ((n ^= 1))
  93. r.push_back((char)(b | (c - (97 - 10))));
  94. else b = (c - (97 - 10)) << 4;
  95. }
  96. if (hex == eof)
  97. break;
  98. }
  99. return r;
  100. }
  101. unsigned int Utils::unhex(const char *hex,unsigned int maxlen,void *buf,unsigned int len)
  102. {
  103. int n = 1;
  104. unsigned char c,b = 0;
  105. unsigned int l = 0;
  106. const char *eof = hex + maxlen;
  107. if (!maxlen)
  108. return 0;
  109. while ((c = (unsigned char)*(hex++))) {
  110. if ((c >= 48)&&(c <= 57)) { // 0..9
  111. if ((n ^= 1)) {
  112. if (l >= len) break;
  113. ((unsigned char *)buf)[l++] = (b | (c - 48));
  114. } else b = (c - 48) << 4;
  115. } else if ((c >= 65)&&(c <= 70)) { // A..F
  116. if ((n ^= 1)) {
  117. if (l >= len) break;
  118. ((unsigned char *)buf)[l++] = (b | (c - (65 - 10)));
  119. } else b = (c - (65 - 10)) << 4;
  120. } else if ((c >= 97)&&(c <= 102)) { // a..f
  121. if ((n ^= 1)) {
  122. if (l >= len) break;
  123. ((unsigned char *)buf)[l++] = (b | (c - (97 - 10)));
  124. } else b = (c - (97 - 10)) << 4;
  125. }
  126. if (hex == eof)
  127. break;
  128. }
  129. return l;
  130. }
  131. void Utils::getSecureRandom(void *buf,unsigned int bytes)
  132. {
  133. #ifdef __WINDOWS__
  134. static HCRYPTPROV cryptProvider = NULL;
  135. static Mutex globalLock;
  136. Mutex::Lock _l(globalLock);
  137. if (cryptProvider == NULL) {
  138. if (!CryptAcquireContextA(&cryptProvider,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT|CRYPT_SILENT)) {
  139. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to obtain WinCrypt context!\r\n");
  140. exit(1);
  141. return;
  142. }
  143. }
  144. if (!CryptGenRandom(cryptProvider,(DWORD)bytes,(BYTE *)buf)) {
  145. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() CryptGenRandom failed!\r\n");
  146. exit(1);
  147. }
  148. #else // not __WINDOWS__
  149. #ifdef __UNIX_LIKE__
  150. static char randomBuf[65536];
  151. static unsigned int randomPtr = sizeof(randomBuf);
  152. static int devURandomFd = -1;
  153. static Mutex globalLock;
  154. Mutex::Lock _l(globalLock);
  155. if (devURandomFd <= 0) {
  156. devURandomFd = ::open("/dev/urandom",O_RDONLY);
  157. if (devURandomFd <= 0) {
  158. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to open /dev/urandom\r\n");
  159. exit(1);
  160. return;
  161. }
  162. }
  163. for(unsigned int i=0;i<bytes;++i) {
  164. if (randomPtr >= sizeof(randomBuf)) {
  165. if ((int)::read(devURandomFd,randomBuf,sizeof(randomBuf)) != (int)sizeof(randomBuf)) {
  166. fprintf(stderr,"FATAL ERROR: Utils::getSecureRandom() unable to read from /dev/urandom\r\n");
  167. exit(1);
  168. return;
  169. }
  170. randomPtr = 0;
  171. }
  172. ((char *)buf)[i] = randomBuf[randomPtr++];
  173. }
  174. #else // not __UNIX_LIKE__
  175. #error No getSecureRandom() implementation available.
  176. #endif // __UNIX_LIKE__
  177. #endif // __WINDOWS__
  178. }
  179. std::vector<std::string> Utils::split(const char *s,const char *const sep,const char *esc,const char *quot)
  180. {
  181. std::vector<std::string> fields;
  182. std::string buf;
  183. if (!esc)
  184. esc = "";
  185. if (!quot)
  186. quot = "";
  187. bool escapeState = false;
  188. char quoteState = 0;
  189. while (*s) {
  190. if (escapeState) {
  191. escapeState = false;
  192. buf.push_back(*s);
  193. } else if (quoteState) {
  194. if (*s == quoteState) {
  195. quoteState = 0;
  196. fields.push_back(buf);
  197. buf.clear();
  198. } else buf.push_back(*s);
  199. } else {
  200. const char *quotTmp;
  201. if (strchr(esc,*s))
  202. escapeState = true;
  203. else if ((buf.size() <= 0)&&((quotTmp = strchr(quot,*s))))
  204. quoteState = *quotTmp;
  205. else if (strchr(sep,*s)) {
  206. if (buf.size() > 0) {
  207. fields.push_back(buf);
  208. buf.clear();
  209. } // else skip runs of seperators
  210. } else buf.push_back(*s);
  211. }
  212. ++s;
  213. }
  214. if (buf.size())
  215. fields.push_back(buf);
  216. return fields;
  217. }
  218. std::string Utils::trim(const std::string &s)
  219. {
  220. unsigned long end = (unsigned long)s.length();
  221. while (end) {
  222. char c = s[end - 1];
  223. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  224. --end;
  225. else break;
  226. }
  227. unsigned long start = 0;
  228. while (start < end) {
  229. char c = s[start];
  230. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  231. ++start;
  232. else break;
  233. }
  234. return s.substr(start,end - start);
  235. }
  236. unsigned int Utils::snprintf(char *buf,unsigned int len,const char *fmt,...)
  237. throw(std::length_error)
  238. {
  239. va_list ap;
  240. va_start(ap,fmt);
  241. int n = (int)vsnprintf(buf,len,fmt,ap);
  242. va_end(ap);
  243. if ((n >= (int)len)||(n < 0)) {
  244. if (len)
  245. buf[len - 1] = (char)0;
  246. throw std::length_error("buf[] overflow in Utils::snprintf");
  247. }
  248. return (unsigned int)n;
  249. }
  250. } // namespace ZeroTier