Utils.cpp 7.0 KB

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