You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

netbase.cpp 38KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifdef HAVE_CONFIG_H
  6. #include "bitcoin-config.h"
  7. #endif
  8. #include "netbase.h"
  9. #include "hash.h"
  10. #include "sync.h"
  11. #include "uint256.h"
  12. #include "util.h"
  13. #include "utilstrencodings.h"
  14. #ifdef HAVE_GETADDRINFO_A
  15. #include <netdb.h>
  16. #endif
  17. #ifndef WIN32
  18. #if HAVE_INET_PTON
  19. #include <arpa/inet.h>
  20. #endif
  21. #include <fcntl.h>
  22. #endif
  23. #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
  24. #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
  25. #include <boost/thread.hpp>
  26. #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
  27. #define MSG_NOSIGNAL 0
  28. #endif
  29. using namespace std;
  30. // Settings
  31. static proxyType proxyInfo[NET_MAX];
  32. static CService nameProxy;
  33. static CCriticalSection cs_proxyInfos;
  34. int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  35. bool fNameLookup = false;
  36. static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
  37. // Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
  38. static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
  39. enum Network ParseNetwork(std::string net) {
  40. boost::to_lower(net);
  41. if (net == "ipv4") return NET_IPV4;
  42. if (net == "ipv6") return NET_IPV6;
  43. if (net == "tor" || net == "onion") return NET_TOR;
  44. return NET_UNROUTABLE;
  45. }
  46. std::string GetNetworkName(enum Network net) {
  47. switch(net)
  48. {
  49. case NET_IPV4: return "ipv4";
  50. case NET_IPV6: return "ipv6";
  51. case NET_TOR: return "onion";
  52. default: return "";
  53. }
  54. }
  55. void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
  56. size_t colon = in.find_last_of(':');
  57. // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
  58. bool fHaveColon = colon != in.npos;
  59. bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
  60. bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
  61. if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
  62. int32_t n;
  63. if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
  64. in = in.substr(0, colon);
  65. portOut = n;
  66. }
  67. }
  68. if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
  69. hostOut = in.substr(1, in.size()-2);
  70. else
  71. hostOut = in;
  72. }
  73. bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
  74. {
  75. vIP.clear();
  76. {
  77. CNetAddr addr;
  78. if (addr.SetSpecial(std::string(pszName))) {
  79. vIP.push_back(addr);
  80. return true;
  81. }
  82. }
  83. #ifdef HAVE_GETADDRINFO_A
  84. struct in_addr ipv4_addr;
  85. #ifdef HAVE_INET_PTON
  86. if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
  87. vIP.push_back(CNetAddr(ipv4_addr));
  88. return true;
  89. }
  90. struct in6_addr ipv6_addr;
  91. if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
  92. vIP.push_back(CNetAddr(ipv6_addr));
  93. return true;
  94. }
  95. #else
  96. ipv4_addr.s_addr = inet_addr(pszName);
  97. if (ipv4_addr.s_addr != INADDR_NONE) {
  98. vIP.push_back(CNetAddr(ipv4_addr));
  99. return true;
  100. }
  101. #endif
  102. #endif
  103. struct addrinfo aiHint;
  104. memset(&aiHint, 0, sizeof(struct addrinfo));
  105. aiHint.ai_socktype = SOCK_STREAM;
  106. aiHint.ai_protocol = IPPROTO_TCP;
  107. aiHint.ai_family = AF_UNSPEC;
  108. #ifdef WIN32
  109. aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
  110. #else
  111. aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
  112. #endif
  113. struct addrinfo *aiRes = NULL;
  114. #ifdef HAVE_GETADDRINFO_A
  115. struct gaicb gcb, *query = &gcb;
  116. memset(query, 0, sizeof(struct gaicb));
  117. gcb.ar_name = pszName;
  118. gcb.ar_request = &aiHint;
  119. int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
  120. if (nErr)
  121. return false;
  122. do {
  123. // Should set the timeout limit to a resonable value to avoid
  124. // generating unnecessary checking call during the polling loop,
  125. // while it can still response to stop request quick enough.
  126. // 2 seconds looks fine in our situation.
  127. struct timespec ts = { 2, 0 };
  128. gai_suspend(&query, 1, &ts);
  129. boost::this_thread::interruption_point();
  130. nErr = gai_error(query);
  131. if (0 == nErr)
  132. aiRes = query->ar_result;
  133. } while (nErr == EAI_INPROGRESS);
  134. #else
  135. int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
  136. #endif
  137. if (nErr)
  138. return false;
  139. struct addrinfo *aiTrav = aiRes;
  140. while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
  141. {
  142. if (aiTrav->ai_family == AF_INET)
  143. {
  144. assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
  145. vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
  146. }
  147. if (aiTrav->ai_family == AF_INET6)
  148. {
  149. assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
  150. vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
  151. }
  152. aiTrav = aiTrav->ai_next;
  153. }
  154. freeaddrinfo(aiRes);
  155. return (vIP.size() > 0);
  156. }
  157. bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
  158. {
  159. std::string strHost(pszName);
  160. if (strHost.empty())
  161. return false;
  162. if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
  163. {
  164. strHost = strHost.substr(1, strHost.size() - 2);
  165. }
  166. return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
  167. }
  168. bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
  169. {
  170. if (pszName[0] == 0)
  171. return false;
  172. int port = portDefault;
  173. std::string hostname = "";
  174. SplitHostPort(std::string(pszName), port, hostname);
  175. std::vector<CNetAddr> vIP;
  176. bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
  177. if (!fRet)
  178. return false;
  179. vAddr.resize(vIP.size());
  180. for (unsigned int i = 0; i < vIP.size(); i++)
  181. vAddr[i] = CService(vIP[i], port);
  182. return true;
  183. }
  184. bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
  185. {
  186. std::vector<CService> vService;
  187. bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
  188. if (!fRet)
  189. return false;
  190. addr = vService[0];
  191. return true;
  192. }
  193. bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
  194. {
  195. return Lookup(pszName, addr, portDefault, false);
  196. }
  197. /**
  198. * Convert milliseconds to a struct timeval for select.
  199. */
  200. struct timeval static MillisToTimeval(int64_t nTimeout)
  201. {
  202. struct timeval timeout;
  203. timeout.tv_sec = nTimeout / 1000;
  204. timeout.tv_usec = (nTimeout % 1000) * 1000;
  205. return timeout;
  206. }
  207. /**
  208. * Read bytes from socket. This will either read the full number of bytes requested
  209. * or return False on error or timeout.
  210. * This function can be interrupted by boost thread interrupt.
  211. *
  212. * @param data Buffer to receive into
  213. * @param len Length of data to receive
  214. * @param timeout Timeout in milliseconds for receive operation
  215. *
  216. * @note This function requires that hSocket is in non-blocking mode.
  217. */
  218. bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
  219. {
  220. int64_t curTime = GetTimeMillis();
  221. int64_t endTime = curTime + timeout;
  222. // Maximum time to wait in one select call. It will take up until this time (in millis)
  223. // to break off in case of an interruption.
  224. const int64_t maxWait = 1000;
  225. while (len > 0 && curTime < endTime) {
  226. ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
  227. if (ret > 0) {
  228. len -= ret;
  229. data += ret;
  230. } else if (ret == 0) { // Unexpected disconnection
  231. return false;
  232. } else { // Other error or blocking
  233. int nErr = WSAGetLastError();
  234. if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
  235. struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
  236. fd_set fdset;
  237. FD_ZERO(&fdset);
  238. FD_SET(hSocket, &fdset);
  239. int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
  240. if (nRet == SOCKET_ERROR) {
  241. return false;
  242. }
  243. } else {
  244. return false;
  245. }
  246. }
  247. boost::this_thread::interruption_point();
  248. curTime = GetTimeMillis();
  249. }
  250. return len == 0;
  251. }
  252. bool static Socks5(string strDest, int port, SOCKET& hSocket)
  253. {
  254. LogPrintf("SOCKS5 connecting %s\n", strDest);
  255. if (strDest.size() > 255)
  256. {
  257. CloseSocket(hSocket);
  258. return error("Hostname too long");
  259. }
  260. char pszSocks5Init[] = "\5\1\0";
  261. ssize_t nSize = sizeof(pszSocks5Init) - 1;
  262. ssize_t ret = send(hSocket, pszSocks5Init, nSize, MSG_NOSIGNAL);
  263. if (ret != nSize)
  264. {
  265. CloseSocket(hSocket);
  266. return error("Error sending to proxy");
  267. }
  268. char pchRet1[2];
  269. if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket))
  270. {
  271. CloseSocket(hSocket);
  272. return error("Error reading proxy response");
  273. }
  274. if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
  275. {
  276. CloseSocket(hSocket);
  277. return error("Proxy failed to initialize");
  278. }
  279. string strSocks5("\5\1");
  280. strSocks5 += '\000'; strSocks5 += '\003';
  281. strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
  282. strSocks5 += strDest;
  283. strSocks5 += static_cast<char>((port >> 8) & 0xFF);
  284. strSocks5 += static_cast<char>((port >> 0) & 0xFF);
  285. ret = send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
  286. if (ret != (ssize_t)strSocks5.size())
  287. {
  288. CloseSocket(hSocket);
  289. return error("Error sending to proxy");
  290. }
  291. char pchRet2[4];
  292. if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket))
  293. {
  294. CloseSocket(hSocket);
  295. return error("Error reading proxy response");
  296. }
  297. if (pchRet2[0] != 0x05)
  298. {
  299. CloseSocket(hSocket);
  300. return error("Proxy failed to accept request");
  301. }
  302. if (pchRet2[1] != 0x00)
  303. {
  304. CloseSocket(hSocket);
  305. switch (pchRet2[1])
  306. {
  307. case 0x01: return error("Proxy error: general failure");
  308. case 0x02: return error("Proxy error: connection not allowed");
  309. case 0x03: return error("Proxy error: network unreachable");
  310. case 0x04: return error("Proxy error: host unreachable");
  311. case 0x05: return error("Proxy error: connection refused");
  312. case 0x06: return error("Proxy error: TTL expired");
  313. case 0x07: return error("Proxy error: protocol error");
  314. case 0x08: return error("Proxy error: address type not supported");
  315. default: return error("Proxy error: unknown");
  316. }
  317. }
  318. if (pchRet2[2] != 0x00)
  319. {
  320. CloseSocket(hSocket);
  321. return error("Error: malformed proxy response");
  322. }
  323. char pchRet3[256];
  324. switch (pchRet2[3])
  325. {
  326. case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
  327. case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
  328. case 0x03:
  329. {
  330. ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
  331. if (!ret) {
  332. CloseSocket(hSocket);
  333. return error("Error reading from proxy");
  334. }
  335. int nRecv = pchRet3[0];
  336. ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
  337. break;
  338. }
  339. default: CloseSocket(hSocket); return error("Error: malformed proxy response");
  340. }
  341. if (!ret)
  342. {
  343. CloseSocket(hSocket);
  344. return error("Error reading from proxy");
  345. }
  346. if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket))
  347. {
  348. CloseSocket(hSocket);
  349. return error("Error reading from proxy");
  350. }
  351. LogPrintf("SOCKS5 connected %s\n", strDest);
  352. return true;
  353. }
  354. bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
  355. {
  356. hSocketRet = INVALID_SOCKET;
  357. struct sockaddr_storage sockaddr;
  358. socklen_t len = sizeof(sockaddr);
  359. if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
  360. LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
  361. return false;
  362. }
  363. SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  364. if (hSocket == INVALID_SOCKET)
  365. return false;
  366. #ifdef SO_NOSIGPIPE
  367. int set = 1;
  368. // Different way of disabling SIGPIPE on BSD
  369. setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
  370. #endif
  371. // Set to non-blocking
  372. if (!SetSocketNonBlocking(hSocket, true))
  373. return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
  374. if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  375. {
  376. int nErr = WSAGetLastError();
  377. // WSAEINVAL is here because some legacy version of winsock uses it
  378. if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
  379. {
  380. struct timeval timeout = MillisToTimeval(nTimeout);
  381. fd_set fdset;
  382. FD_ZERO(&fdset);
  383. FD_SET(hSocket, &fdset);
  384. int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
  385. if (nRet == 0)
  386. {
  387. LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
  388. CloseSocket(hSocket);
  389. return false;
  390. }
  391. if (nRet == SOCKET_ERROR)
  392. {
  393. LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  394. CloseSocket(hSocket);
  395. return false;
  396. }
  397. socklen_t nRetSize = sizeof(nRet);
  398. #ifdef WIN32
  399. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
  400. #else
  401. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
  402. #endif
  403. {
  404. LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  405. CloseSocket(hSocket);
  406. return false;
  407. }
  408. if (nRet != 0)
  409. {
  410. LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
  411. CloseSocket(hSocket);
  412. return false;
  413. }
  414. }
  415. #ifdef WIN32
  416. else if (WSAGetLastError() != WSAEISCONN)
  417. #else
  418. else
  419. #endif
  420. {
  421. LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  422. CloseSocket(hSocket);
  423. return false;
  424. }
  425. }
  426. hSocketRet = hSocket;
  427. return true;
  428. }
  429. bool SetProxy(enum Network net, CService addrProxy) {
  430. assert(net >= 0 && net < NET_MAX);
  431. if (!addrProxy.IsValid())
  432. return false;
  433. LOCK(cs_proxyInfos);
  434. proxyInfo[net] = addrProxy;
  435. return true;
  436. }
  437. bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
  438. assert(net >= 0 && net < NET_MAX);
  439. LOCK(cs_proxyInfos);
  440. if (!proxyInfo[net].IsValid())
  441. return false;
  442. proxyInfoOut = proxyInfo[net];
  443. return true;
  444. }
  445. bool SetNameProxy(CService addrProxy) {
  446. if (!addrProxy.IsValid())
  447. return false;
  448. LOCK(cs_proxyInfos);
  449. nameProxy = addrProxy;
  450. return true;
  451. }
  452. bool GetNameProxy(CService &nameProxyOut) {
  453. LOCK(cs_proxyInfos);
  454. if(!nameProxy.IsValid())
  455. return false;
  456. nameProxyOut = nameProxy;
  457. return true;
  458. }
  459. bool HaveNameProxy() {
  460. LOCK(cs_proxyInfos);
  461. return nameProxy.IsValid();
  462. }
  463. bool IsProxy(const CNetAddr &addr) {
  464. LOCK(cs_proxyInfos);
  465. for (int i = 0; i < NET_MAX; i++) {
  466. if (addr == (CNetAddr)proxyInfo[i])
  467. return true;
  468. }
  469. return false;
  470. }
  471. bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
  472. {
  473. proxyType proxy;
  474. // no proxy needed (none set for target network)
  475. if (!GetProxy(addrDest.GetNetwork(), proxy))
  476. return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
  477. SOCKET hSocket = INVALID_SOCKET;
  478. // first connect to proxy server
  479. if (!ConnectSocketDirectly(proxy, hSocket, nTimeout))
  480. return false;
  481. // do socks negotiation
  482. if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
  483. return false;
  484. hSocketRet = hSocket;
  485. return true;
  486. }
  487. bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
  488. {
  489. string strDest;
  490. int port = portDefault;
  491. SplitHostPort(string(pszDest), port, strDest);
  492. SOCKET hSocket = INVALID_SOCKET;
  493. CService nameProxy;
  494. GetNameProxy(nameProxy);
  495. CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
  496. if (addrResolved.IsValid()) {
  497. addr = addrResolved;
  498. return ConnectSocket(addr, hSocketRet, nTimeout);
  499. }
  500. addr = CService("0.0.0.0:0");
  501. if (!HaveNameProxy())
  502. return false;
  503. // first connect to name proxy server
  504. if (!ConnectSocketDirectly(nameProxy, hSocket, nTimeout))
  505. return false;
  506. // do socks negotiation
  507. if (!Socks5(strDest, (unsigned short)port, hSocket))
  508. return false;
  509. hSocketRet = hSocket;
  510. return true;
  511. }
  512. void CNetAddr::Init()
  513. {
  514. memset(ip, 0, sizeof(ip));
  515. }
  516. void CNetAddr::SetIP(const CNetAddr& ipIn)
  517. {
  518. memcpy(ip, ipIn.ip, sizeof(ip));
  519. }
  520. void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
  521. {
  522. switch(network)
  523. {
  524. case NET_IPV4:
  525. memcpy(ip, pchIPv4, 12);
  526. memcpy(ip+12, ip_in, 4);
  527. break;
  528. case NET_IPV6:
  529. memcpy(ip, ip_in, 16);
  530. break;
  531. default:
  532. assert(!"invalid network");
  533. }
  534. }
  535. static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
  536. bool CNetAddr::SetSpecial(const std::string &strName)
  537. {
  538. if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
  539. std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
  540. if (vchAddr.size() != 16-sizeof(pchOnionCat))
  541. return false;
  542. memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
  543. for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
  544. ip[i + sizeof(pchOnionCat)] = vchAddr[i];
  545. return true;
  546. }
  547. return false;
  548. }
  549. CNetAddr::CNetAddr()
  550. {
  551. Init();
  552. }
  553. CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
  554. {
  555. SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
  556. }
  557. CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
  558. {
  559. SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
  560. }
  561. CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
  562. {
  563. Init();
  564. std::vector<CNetAddr> vIP;
  565. if (LookupHost(pszIp, vIP, 1, fAllowLookup))
  566. *this = vIP[0];
  567. }
  568. CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
  569. {
  570. Init();
  571. std::vector<CNetAddr> vIP;
  572. if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
  573. *this = vIP[0];
  574. }
  575. unsigned int CNetAddr::GetByte(int n) const
  576. {
  577. return ip[15-n];
  578. }
  579. bool CNetAddr::IsIPv4() const
  580. {
  581. return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
  582. }
  583. bool CNetAddr::IsIPv6() const
  584. {
  585. return (!IsIPv4() && !IsTor());
  586. }
  587. bool CNetAddr::IsRFC1918() const
  588. {
  589. return IsIPv4() && (
  590. GetByte(3) == 10 ||
  591. (GetByte(3) == 192 && GetByte(2) == 168) ||
  592. (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
  593. }
  594. bool CNetAddr::IsRFC3927() const
  595. {
  596. return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
  597. }
  598. bool CNetAddr::IsRFC3849() const
  599. {
  600. return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
  601. }
  602. bool CNetAddr::IsRFC3964() const
  603. {
  604. return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
  605. }
  606. bool CNetAddr::IsRFC6052() const
  607. {
  608. static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
  609. return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
  610. }
  611. bool CNetAddr::IsRFC4380() const
  612. {
  613. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
  614. }
  615. bool CNetAddr::IsRFC4862() const
  616. {
  617. static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
  618. return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
  619. }
  620. bool CNetAddr::IsRFC4193() const
  621. {
  622. return ((GetByte(15) & 0xFE) == 0xFC);
  623. }
  624. bool CNetAddr::IsRFC6145() const
  625. {
  626. static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
  627. return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
  628. }
  629. bool CNetAddr::IsRFC4843() const
  630. {
  631. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
  632. }
  633. bool CNetAddr::IsTor() const
  634. {
  635. return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
  636. }
  637. bool CNetAddr::IsLocal() const
  638. {
  639. // IPv4 loopback
  640. if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
  641. return true;
  642. // IPv6 loopback (::1/128)
  643. static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
  644. if (memcmp(ip, pchLocal, 16) == 0)
  645. return true;
  646. return false;
  647. }
  648. bool CNetAddr::IsMulticast() const
  649. {
  650. return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
  651. || (GetByte(15) == 0xFF);
  652. }
  653. bool CNetAddr::IsValid() const
  654. {
  655. // Cleanup 3-byte shifted addresses caused by garbage in size field
  656. // of addr messages from versions before 0.2.9 checksum.
  657. // Two consecutive addr messages look like this:
  658. // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
  659. // so if the first length field is garbled, it reads the second batch
  660. // of addr misaligned by 3 bytes.
  661. if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
  662. return false;
  663. // unspecified IPv6 address (::/128)
  664. unsigned char ipNone[16] = {};
  665. if (memcmp(ip, ipNone, 16) == 0)
  666. return false;
  667. // documentation IPv6 address
  668. if (IsRFC3849())
  669. return false;
  670. if (IsIPv4())
  671. {
  672. // INADDR_NONE
  673. uint32_t ipNone = INADDR_NONE;
  674. if (memcmp(ip+12, &ipNone, 4) == 0)
  675. return false;
  676. // 0
  677. ipNone = 0;
  678. if (memcmp(ip+12, &ipNone, 4) == 0)
  679. return false;
  680. }
  681. return true;
  682. }
  683. bool CNetAddr::IsRoutable() const
  684. {
  685. return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
  686. }
  687. enum Network CNetAddr::GetNetwork() const
  688. {
  689. if (!IsRoutable())
  690. return NET_UNROUTABLE;
  691. if (IsIPv4())
  692. return NET_IPV4;
  693. if (IsTor())
  694. return NET_TOR;
  695. return NET_IPV6;
  696. }
  697. std::string CNetAddr::ToStringIP() const
  698. {
  699. if (IsTor())
  700. return EncodeBase32(&ip[6], 10) + ".onion";
  701. CService serv(*this, 0);
  702. struct sockaddr_storage sockaddr;
  703. socklen_t socklen = sizeof(sockaddr);
  704. if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
  705. char name[1025] = "";
  706. if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
  707. return std::string(name);
  708. }
  709. if (IsIPv4())
  710. return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
  711. else
  712. return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  713. GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
  714. GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
  715. GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
  716. GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
  717. }
  718. std::string CNetAddr::ToString() const
  719. {
  720. return ToStringIP();
  721. }
  722. bool operator==(const CNetAddr& a, const CNetAddr& b)
  723. {
  724. return (memcmp(a.ip, b.ip, 16) == 0);
  725. }
  726. bool operator!=(const CNetAddr& a, const CNetAddr& b)
  727. {
  728. return (memcmp(a.ip, b.ip, 16) != 0);
  729. }
  730. bool operator<(const CNetAddr& a, const CNetAddr& b)
  731. {
  732. return (memcmp(a.ip, b.ip, 16) < 0);
  733. }
  734. bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
  735. {
  736. if (!IsIPv4())
  737. return false;
  738. memcpy(pipv4Addr, ip+12, 4);
  739. return true;
  740. }
  741. bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
  742. {
  743. memcpy(pipv6Addr, ip, 16);
  744. return true;
  745. }
  746. // get canonical identifier of an address' group
  747. // no two connections will be attempted to addresses with the same group
  748. std::vector<unsigned char> CNetAddr::GetGroup() const
  749. {
  750. std::vector<unsigned char> vchRet;
  751. int nClass = NET_IPV6;
  752. int nStartByte = 0;
  753. int nBits = 16;
  754. // all local addresses belong to the same group
  755. if (IsLocal())
  756. {
  757. nClass = 255;
  758. nBits = 0;
  759. }
  760. // all unroutable addresses belong to the same group
  761. if (!IsRoutable())
  762. {
  763. nClass = NET_UNROUTABLE;
  764. nBits = 0;
  765. }
  766. // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
  767. // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
  768. else if (IsIPv4() || IsRFC6145() || IsRFC6052())
  769. {
  770. nClass = NET_IPV4;
  771. nStartByte = 12;
  772. }
  773. // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
  774. else if (IsRFC3964())
  775. {
  776. nClass = NET_IPV4;
  777. nStartByte = 2;
  778. }
  779. // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
  780. else if (IsRFC4380())
  781. {
  782. vchRet.push_back(NET_IPV4);
  783. vchRet.push_back(GetByte(3) ^ 0xFF);
  784. vchRet.push_back(GetByte(2) ^ 0xFF);
  785. return vchRet;
  786. }
  787. else if (IsTor())
  788. {
  789. nClass = NET_TOR;
  790. nStartByte = 6;
  791. nBits = 4;
  792. }
  793. // for he.net, use /36 groups
  794. else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
  795. nBits = 36;
  796. // for the rest of the IPv6 network, use /32 groups
  797. else
  798. nBits = 32;
  799. vchRet.push_back(nClass);
  800. while (nBits >= 8)
  801. {
  802. vchRet.push_back(GetByte(15 - nStartByte));
  803. nStartByte++;
  804. nBits -= 8;
  805. }
  806. if (nBits > 0)
  807. vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
  808. return vchRet;
  809. }
  810. uint64_t CNetAddr::GetHash() const
  811. {
  812. uint256 hash = Hash(&ip[0], &ip[16]);
  813. uint64_t nRet;
  814. memcpy(&nRet, &hash, sizeof(nRet));
  815. return nRet;
  816. }
  817. // private extensions to enum Network, only returned by GetExtNetwork,
  818. // and only used in GetReachabilityFrom
  819. static const int NET_UNKNOWN = NET_MAX + 0;
  820. static const int NET_TEREDO = NET_MAX + 1;
  821. int static GetExtNetwork(const CNetAddr *addr)
  822. {
  823. if (addr == NULL)
  824. return NET_UNKNOWN;
  825. if (addr->IsRFC4380())
  826. return NET_TEREDO;
  827. return addr->GetNetwork();
  828. }
  829. /** Calculates a metric for how reachable (*this) is from a given partner */
  830. int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
  831. {
  832. enum Reachability {
  833. REACH_UNREACHABLE,
  834. REACH_DEFAULT,
  835. REACH_TEREDO,
  836. REACH_IPV6_WEAK,
  837. REACH_IPV4,
  838. REACH_IPV6_STRONG,
  839. REACH_PRIVATE
  840. };
  841. if (!IsRoutable())
  842. return REACH_UNREACHABLE;
  843. int ourNet = GetExtNetwork(this);
  844. int theirNet = GetExtNetwork(paddrPartner);
  845. bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
  846. switch(theirNet) {
  847. case NET_IPV4:
  848. switch(ourNet) {
  849. default: return REACH_DEFAULT;
  850. case NET_IPV4: return REACH_IPV4;
  851. }
  852. case NET_IPV6:
  853. switch(ourNet) {
  854. default: return REACH_DEFAULT;
  855. case NET_TEREDO: return REACH_TEREDO;
  856. case NET_IPV4: return REACH_IPV4;
  857. case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
  858. }
  859. case NET_TOR:
  860. switch(ourNet) {
  861. default: return REACH_DEFAULT;
  862. case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
  863. case NET_TOR: return REACH_PRIVATE;
  864. }
  865. case NET_TEREDO:
  866. switch(ourNet) {
  867. default: return REACH_DEFAULT;
  868. case NET_TEREDO: return REACH_TEREDO;
  869. case NET_IPV6: return REACH_IPV6_WEAK;
  870. case NET_IPV4: return REACH_IPV4;
  871. }
  872. case NET_UNKNOWN:
  873. case NET_UNROUTABLE:
  874. default:
  875. switch(ourNet) {
  876. default: return REACH_DEFAULT;
  877. case NET_TEREDO: return REACH_TEREDO;
  878. case NET_IPV6: return REACH_IPV6_WEAK;
  879. case NET_IPV4: return REACH_IPV4;
  880. case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
  881. }
  882. }
  883. }
  884. void CService::Init()
  885. {
  886. port = 0;
  887. }
  888. CService::CService()
  889. {
  890. Init();
  891. }
  892. CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
  893. {
  894. }
  895. CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
  896. {
  897. }
  898. CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
  899. {
  900. }
  901. CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
  902. {
  903. assert(addr.sin_family == AF_INET);
  904. }
  905. CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
  906. {
  907. assert(addr.sin6_family == AF_INET6);
  908. }
  909. bool CService::SetSockAddr(const struct sockaddr *paddr)
  910. {
  911. switch (paddr->sa_family) {
  912. case AF_INET:
  913. *this = CService(*(const struct sockaddr_in*)paddr);
  914. return true;
  915. case AF_INET6:
  916. *this = CService(*(const struct sockaddr_in6*)paddr);
  917. return true;
  918. default:
  919. return false;
  920. }
  921. }
  922. CService::CService(const char *pszIpPort, bool fAllowLookup)
  923. {
  924. Init();
  925. CService ip;
  926. if (Lookup(pszIpPort, ip, 0, fAllowLookup))
  927. *this = ip;
  928. }
  929. CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
  930. {
  931. Init();
  932. CService ip;
  933. if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
  934. *this = ip;
  935. }
  936. CService::CService(const std::string &strIpPort, bool fAllowLookup)
  937. {
  938. Init();
  939. CService ip;
  940. if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
  941. *this = ip;
  942. }
  943. CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
  944. {
  945. Init();
  946. CService ip;
  947. if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
  948. *this = ip;
  949. }
  950. unsigned short CService::GetPort() const
  951. {
  952. return port;
  953. }
  954. bool operator==(const CService& a, const CService& b)
  955. {
  956. return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
  957. }
  958. bool operator!=(const CService& a, const CService& b)
  959. {
  960. return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
  961. }
  962. bool operator<(const CService& a, const CService& b)
  963. {
  964. return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
  965. }
  966. bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
  967. {
  968. if (IsIPv4()) {
  969. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
  970. return false;
  971. *addrlen = sizeof(struct sockaddr_in);
  972. struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
  973. memset(paddrin, 0, *addrlen);
  974. if (!GetInAddr(&paddrin->sin_addr))
  975. return false;
  976. paddrin->sin_family = AF_INET;
  977. paddrin->sin_port = htons(port);
  978. return true;
  979. }
  980. if (IsIPv6()) {
  981. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
  982. return false;
  983. *addrlen = sizeof(struct sockaddr_in6);
  984. struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
  985. memset(paddrin6, 0, *addrlen);
  986. if (!GetIn6Addr(&paddrin6->sin6_addr))
  987. return false;
  988. paddrin6->sin6_family = AF_INET6;
  989. paddrin6->sin6_port = htons(port);
  990. return true;
  991. }
  992. return false;
  993. }
  994. std::vector<unsigned char> CService::GetKey() const
  995. {
  996. std::vector<unsigned char> vKey;
  997. vKey.resize(18);
  998. memcpy(&vKey[0], ip, 16);
  999. vKey[16] = port / 0x100;
  1000. vKey[17] = port & 0x0FF;
  1001. return vKey;
  1002. }
  1003. std::string CService::ToStringPort() const
  1004. {
  1005. return strprintf("%u", port);
  1006. }
  1007. std::string CService::ToStringIPPort() const
  1008. {
  1009. if (IsIPv4() || IsTor()) {
  1010. return ToStringIP() + ":" + ToStringPort();
  1011. } else {
  1012. return "[" + ToStringIP() + "]:" + ToStringPort();
  1013. }
  1014. }
  1015. std::string CService::ToString() const
  1016. {
  1017. return ToStringIPPort();
  1018. }
  1019. void CService::SetPort(unsigned short portIn)
  1020. {
  1021. port = portIn;
  1022. }
  1023. CSubNet::CSubNet():
  1024. valid(false)
  1025. {
  1026. memset(netmask, 0, sizeof(netmask));
  1027. }
  1028. CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
  1029. {
  1030. size_t slash = strSubnet.find_last_of('/');
  1031. std::vector<CNetAddr> vIP;
  1032. valid = true;
  1033. // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
  1034. memset(netmask, 255, sizeof(netmask));
  1035. std::string strAddress = strSubnet.substr(0, slash);
  1036. if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
  1037. {
  1038. network = vIP[0];
  1039. if (slash != strSubnet.npos)
  1040. {
  1041. std::string strNetmask = strSubnet.substr(slash + 1);
  1042. int32_t n;
  1043. // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
  1044. int noffset = network.IsIPv4() ? (12 * 8) : 0;
  1045. if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
  1046. {
  1047. if(n >= 0 && n <= (128 - noffset)) // Only valid if in range of bits of address
  1048. {
  1049. n += noffset;
  1050. // Clear bits [n..127]
  1051. for (; n < 128; ++n)
  1052. netmask[n>>3] &= ~(1<<(n&7));
  1053. }
  1054. else
  1055. {
  1056. valid = false;
  1057. }
  1058. }
  1059. else // If not a valid number, try full netmask syntax
  1060. {
  1061. if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
  1062. {
  1063. // Remember: GetByte returns bytes in reversed order
  1064. // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
  1065. // we don't want pchIPv4 to be part of the mask.
  1066. int asize = network.IsIPv4() ? 4 : 16;
  1067. for(int x=0; x<asize; ++x)
  1068. netmask[15-x] = vIP[0].GetByte(x);
  1069. }
  1070. else
  1071. {
  1072. valid = false;
  1073. }
  1074. }
  1075. }
  1076. }
  1077. else
  1078. {
  1079. valid = false;
  1080. }
  1081. }
  1082. bool CSubNet::Match(const CNetAddr &addr) const
  1083. {
  1084. if (!valid || !addr.IsValid())
  1085. return false;
  1086. for(int x=0; x<16; ++x)
  1087. if ((addr.GetByte(x) & netmask[15-x]) != network.GetByte(x))
  1088. return false;
  1089. return true;
  1090. }
  1091. std::string CSubNet::ToString() const
  1092. {
  1093. std::string strNetmask;
  1094. if (network.IsIPv4())
  1095. strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
  1096. else
  1097. strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  1098. netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
  1099. netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
  1100. netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
  1101. netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
  1102. return network.ToString() + "/" + strNetmask;
  1103. }
  1104. bool CSubNet::IsValid() const
  1105. {
  1106. return valid;
  1107. }
  1108. bool operator==(const CSubNet& a, const CSubNet& b)
  1109. {
  1110. return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
  1111. }
  1112. bool operator!=(const CSubNet& a, const CSubNet& b)
  1113. {
  1114. return !(a==b);
  1115. }
  1116. #ifdef WIN32
  1117. std::string NetworkErrorString(int err)
  1118. {
  1119. char buf[256];
  1120. buf[0] = 0;
  1121. if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
  1122. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1123. buf, sizeof(buf), NULL))
  1124. {
  1125. return strprintf("%s (%d)", buf, err);
  1126. }
  1127. else
  1128. {
  1129. return strprintf("Unknown error (%d)", err);
  1130. }
  1131. }
  1132. #else
  1133. std::string NetworkErrorString(int err)
  1134. {
  1135. char buf[256];
  1136. const char *s = buf;
  1137. buf[0] = 0;
  1138. /* Too bad there are two incompatible implementations of the
  1139. * thread-safe strerror. */
  1140. #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
  1141. s = strerror_r(err, buf, sizeof(buf));
  1142. #else /* POSIX variant always returns message in buffer */
  1143. if (strerror_r(err, buf, sizeof(buf)))
  1144. buf[0] = 0;
  1145. #endif
  1146. return strprintf("%s (%d)", s, err);
  1147. }
  1148. #endif
  1149. bool CloseSocket(SOCKET& hSocket)
  1150. {
  1151. if (hSocket == INVALID_SOCKET)
  1152. return false;
  1153. #ifdef WIN32
  1154. int ret = closesocket(hSocket);
  1155. #else
  1156. int ret = close(hSocket);
  1157. #endif
  1158. hSocket = INVALID_SOCKET;
  1159. return ret != SOCKET_ERROR;
  1160. }
  1161. bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
  1162. {
  1163. if (fNonBlocking) {
  1164. #ifdef WIN32
  1165. u_long nOne = 1;
  1166. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
  1167. #else
  1168. int fFlags = fcntl(hSocket, F_GETFL, 0);
  1169. if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
  1170. #endif
  1171. CloseSocket(hSocket);
  1172. return false;
  1173. }
  1174. } else {
  1175. #ifdef WIN32
  1176. u_long nZero = 0;
  1177. if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
  1178. #else
  1179. int fFlags = fcntl(hSocket, F_GETFL, 0);
  1180. if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
  1181. #endif
  1182. CloseSocket(hSocket);
  1183. return false;
  1184. }
  1185. }
  1186. return true;
  1187. }