Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

netbase.cpp 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2015 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifdef HAVE_CONFIG_H
  6. #include "config/bitcoin-config.h"
  7. #endif
  8. #include "netbase.h"
  9. #include "hash.h"
  10. #include "sync.h"
  11. #include "uint256.h"
  12. #include "random.h"
  13. #include "util.h"
  14. #include "utilstrencodings.h"
  15. #ifdef HAVE_GETADDRINFO_A
  16. #include <netdb.h>
  17. #endif
  18. #ifndef WIN32
  19. #if HAVE_INET_PTON
  20. #include <arpa/inet.h>
  21. #endif
  22. #include <fcntl.h>
  23. #endif
  24. #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
  25. #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
  26. #include <boost/thread.hpp>
  27. #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
  28. #define MSG_NOSIGNAL 0
  29. #endif
  30. // Settings
  31. static proxyType proxyInfo[NET_MAX];
  32. static proxyType nameProxy;
  33. static CCriticalSection cs_proxyInfos;
  34. int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
  35. bool fNameLookup = DEFAULT_NAME_LOOKUP;
  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. struct timeval MillisToTimeval(int64_t nTimeout)
  198. {
  199. struct timeval timeout;
  200. timeout.tv_sec = nTimeout / 1000;
  201. timeout.tv_usec = (nTimeout % 1000) * 1000;
  202. return timeout;
  203. }
  204. /**
  205. * Read bytes from socket. This will either read the full number of bytes requested
  206. * or return False on error or timeout.
  207. * This function can be interrupted by boost thread interrupt.
  208. *
  209. * @param data Buffer to receive into
  210. * @param len Length of data to receive
  211. * @param timeout Timeout in milliseconds for receive operation
  212. *
  213. * @note This function requires that hSocket is in non-blocking mode.
  214. */
  215. bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
  216. {
  217. int64_t curTime = GetTimeMillis();
  218. int64_t endTime = curTime + timeout;
  219. // Maximum time to wait in one select call. It will take up until this time (in millis)
  220. // to break off in case of an interruption.
  221. const int64_t maxWait = 1000;
  222. while (len > 0 && curTime < endTime) {
  223. ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
  224. if (ret > 0) {
  225. len -= ret;
  226. data += ret;
  227. } else if (ret == 0) { // Unexpected disconnection
  228. return false;
  229. } else { // Other error or blocking
  230. int nErr = WSAGetLastError();
  231. if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
  232. if (!IsSelectableSocket(hSocket)) {
  233. return false;
  234. }
  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. struct ProxyCredentials
  253. {
  254. std::string username;
  255. std::string password;
  256. };
  257. /** Connect using SOCKS5 (as described in RFC1928) */
  258. static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
  259. {
  260. LogPrintf("SOCKS5 connecting %s\n", strDest);
  261. if (strDest.size() > 255) {
  262. CloseSocket(hSocket);
  263. return error("Hostname too long");
  264. }
  265. // Accepted authentication methods
  266. std::vector<uint8_t> vSocks5Init;
  267. vSocks5Init.push_back(0x05);
  268. if (auth) {
  269. vSocks5Init.push_back(0x02); // # METHODS
  270. vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
  271. vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
  272. } else {
  273. vSocks5Init.push_back(0x01); // # METHODS
  274. vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
  275. }
  276. ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL);
  277. if (ret != (ssize_t)vSocks5Init.size()) {
  278. CloseSocket(hSocket);
  279. return error("Error sending to proxy");
  280. }
  281. char pchRet1[2];
  282. if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
  283. CloseSocket(hSocket);
  284. return error("Error reading proxy response");
  285. }
  286. if (pchRet1[0] != 0x05) {
  287. CloseSocket(hSocket);
  288. return error("Proxy failed to initialize");
  289. }
  290. if (pchRet1[1] == 0x02 && auth) {
  291. // Perform username/password authentication (as described in RFC1929)
  292. std::vector<uint8_t> vAuth;
  293. vAuth.push_back(0x01);
  294. if (auth->username.size() > 255 || auth->password.size() > 255)
  295. return error("Proxy username or password too long");
  296. vAuth.push_back(auth->username.size());
  297. vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
  298. vAuth.push_back(auth->password.size());
  299. vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
  300. ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL);
  301. if (ret != (ssize_t)vAuth.size()) {
  302. CloseSocket(hSocket);
  303. return error("Error sending authentication to proxy");
  304. }
  305. LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
  306. char pchRetA[2];
  307. if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
  308. CloseSocket(hSocket);
  309. return error("Error reading proxy authentication response");
  310. }
  311. if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
  312. CloseSocket(hSocket);
  313. return error("Proxy authentication unsuccessful");
  314. }
  315. } else if (pchRet1[1] == 0x00) {
  316. // Perform no authentication
  317. } else {
  318. CloseSocket(hSocket);
  319. return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
  320. }
  321. std::vector<uint8_t> vSocks5;
  322. vSocks5.push_back(0x05); // VER protocol version
  323. vSocks5.push_back(0x01); // CMD CONNECT
  324. vSocks5.push_back(0x00); // RSV Reserved
  325. vSocks5.push_back(0x03); // ATYP DOMAINNAME
  326. vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
  327. vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
  328. vSocks5.push_back((port >> 8) & 0xFF);
  329. vSocks5.push_back((port >> 0) & 0xFF);
  330. ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL);
  331. if (ret != (ssize_t)vSocks5.size()) {
  332. CloseSocket(hSocket);
  333. return error("Error sending to proxy");
  334. }
  335. char pchRet2[4];
  336. if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
  337. CloseSocket(hSocket);
  338. return error("Error reading proxy response");
  339. }
  340. if (pchRet2[0] != 0x05) {
  341. CloseSocket(hSocket);
  342. return error("Proxy failed to accept request");
  343. }
  344. if (pchRet2[1] != 0x00) {
  345. CloseSocket(hSocket);
  346. switch (pchRet2[1])
  347. {
  348. case 0x01: return error("Proxy error: general failure");
  349. case 0x02: return error("Proxy error: connection not allowed");
  350. case 0x03: return error("Proxy error: network unreachable");
  351. case 0x04: return error("Proxy error: host unreachable");
  352. case 0x05: return error("Proxy error: connection refused");
  353. case 0x06: return error("Proxy error: TTL expired");
  354. case 0x07: return error("Proxy error: protocol error");
  355. case 0x08: return error("Proxy error: address type not supported");
  356. default: return error("Proxy error: unknown");
  357. }
  358. }
  359. if (pchRet2[2] != 0x00) {
  360. CloseSocket(hSocket);
  361. return error("Error: malformed proxy response");
  362. }
  363. char pchRet3[256];
  364. switch (pchRet2[3])
  365. {
  366. case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break;
  367. case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break;
  368. case 0x03:
  369. {
  370. ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
  371. if (!ret) {
  372. CloseSocket(hSocket);
  373. return error("Error reading from proxy");
  374. }
  375. int nRecv = pchRet3[0];
  376. ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
  377. break;
  378. }
  379. default: CloseSocket(hSocket); return error("Error: malformed proxy response");
  380. }
  381. if (!ret) {
  382. CloseSocket(hSocket);
  383. return error("Error reading from proxy");
  384. }
  385. if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
  386. CloseSocket(hSocket);
  387. return error("Error reading from proxy");
  388. }
  389. LogPrintf("SOCKS5 connected %s\n", strDest);
  390. return true;
  391. }
  392. bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
  393. {
  394. hSocketRet = INVALID_SOCKET;
  395. struct sockaddr_storage sockaddr;
  396. socklen_t len = sizeof(sockaddr);
  397. if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
  398. LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
  399. return false;
  400. }
  401. SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  402. if (hSocket == INVALID_SOCKET)
  403. return false;
  404. int set = 1;
  405. #ifdef SO_NOSIGPIPE
  406. // Different way of disabling SIGPIPE on BSD
  407. setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
  408. #endif
  409. //Disable Nagle's algorithm
  410. #ifdef WIN32
  411. setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
  412. #else
  413. setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
  414. #endif
  415. // Set to non-blocking
  416. if (!SetSocketNonBlocking(hSocket, true))
  417. return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
  418. if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  419. {
  420. int nErr = WSAGetLastError();
  421. // WSAEINVAL is here because some legacy version of winsock uses it
  422. if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
  423. {
  424. struct timeval timeout = MillisToTimeval(nTimeout);
  425. fd_set fdset;
  426. FD_ZERO(&fdset);
  427. FD_SET(hSocket, &fdset);
  428. int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
  429. if (nRet == 0)
  430. {
  431. LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
  432. CloseSocket(hSocket);
  433. return false;
  434. }
  435. if (nRet == SOCKET_ERROR)
  436. {
  437. LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  438. CloseSocket(hSocket);
  439. return false;
  440. }
  441. socklen_t nRetSize = sizeof(nRet);
  442. #ifdef WIN32
  443. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
  444. #else
  445. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
  446. #endif
  447. {
  448. LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  449. CloseSocket(hSocket);
  450. return false;
  451. }
  452. if (nRet != 0)
  453. {
  454. LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
  455. CloseSocket(hSocket);
  456. return false;
  457. }
  458. }
  459. #ifdef WIN32
  460. else if (WSAGetLastError() != WSAEISCONN)
  461. #else
  462. else
  463. #endif
  464. {
  465. LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
  466. CloseSocket(hSocket);
  467. return false;
  468. }
  469. }
  470. hSocketRet = hSocket;
  471. return true;
  472. }
  473. bool SetProxy(enum Network net, const proxyType &addrProxy) {
  474. assert(net >= 0 && net < NET_MAX);
  475. if (!addrProxy.IsValid())
  476. return false;
  477. LOCK(cs_proxyInfos);
  478. proxyInfo[net] = addrProxy;
  479. return true;
  480. }
  481. bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
  482. assert(net >= 0 && net < NET_MAX);
  483. LOCK(cs_proxyInfos);
  484. if (!proxyInfo[net].IsValid())
  485. return false;
  486. proxyInfoOut = proxyInfo[net];
  487. return true;
  488. }
  489. bool SetNameProxy(const proxyType &addrProxy) {
  490. if (!addrProxy.IsValid())
  491. return false;
  492. LOCK(cs_proxyInfos);
  493. nameProxy = addrProxy;
  494. return true;
  495. }
  496. bool GetNameProxy(proxyType &nameProxyOut) {
  497. LOCK(cs_proxyInfos);
  498. if(!nameProxy.IsValid())
  499. return false;
  500. nameProxyOut = nameProxy;
  501. return true;
  502. }
  503. bool HaveNameProxy() {
  504. LOCK(cs_proxyInfos);
  505. return nameProxy.IsValid();
  506. }
  507. bool IsProxy(const CNetAddr &addr) {
  508. LOCK(cs_proxyInfos);
  509. for (int i = 0; i < NET_MAX; i++) {
  510. if (addr == (CNetAddr)proxyInfo[i].proxy)
  511. return true;
  512. }
  513. return false;
  514. }
  515. static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
  516. {
  517. SOCKET hSocket = INVALID_SOCKET;
  518. // first connect to proxy server
  519. if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
  520. if (outProxyConnectionFailed)
  521. *outProxyConnectionFailed = true;
  522. return false;
  523. }
  524. // do socks negotiation
  525. if (proxy.randomize_credentials) {
  526. ProxyCredentials random_auth;
  527. random_auth.username = strprintf("%i", insecure_rand());
  528. random_auth.password = strprintf("%i", insecure_rand());
  529. if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
  530. return false;
  531. } else {
  532. if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
  533. return false;
  534. }
  535. hSocketRet = hSocket;
  536. return true;
  537. }
  538. bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
  539. {
  540. proxyType proxy;
  541. if (outProxyConnectionFailed)
  542. *outProxyConnectionFailed = false;
  543. if (GetProxy(addrDest.GetNetwork(), proxy))
  544. return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
  545. else // no proxy needed (none set for target network)
  546. return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
  547. }
  548. bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed)
  549. {
  550. std::string strDest;
  551. int port = portDefault;
  552. if (outProxyConnectionFailed)
  553. *outProxyConnectionFailed = false;
  554. SplitHostPort(std::string(pszDest), port, strDest);
  555. proxyType nameProxy;
  556. GetNameProxy(nameProxy);
  557. CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
  558. if (addrResolved.IsValid()) {
  559. addr = addrResolved;
  560. return ConnectSocket(addr, hSocketRet, nTimeout);
  561. }
  562. addr = CService("0.0.0.0:0");
  563. if (!HaveNameProxy())
  564. return false;
  565. return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
  566. }
  567. void CNetAddr::Init()
  568. {
  569. memset(ip, 0, sizeof(ip));
  570. }
  571. void CNetAddr::SetIP(const CNetAddr& ipIn)
  572. {
  573. memcpy(ip, ipIn.ip, sizeof(ip));
  574. }
  575. void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
  576. {
  577. switch(network)
  578. {
  579. case NET_IPV4:
  580. memcpy(ip, pchIPv4, 12);
  581. memcpy(ip+12, ip_in, 4);
  582. break;
  583. case NET_IPV6:
  584. memcpy(ip, ip_in, 16);
  585. break;
  586. default:
  587. assert(!"invalid network");
  588. }
  589. }
  590. static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
  591. bool CNetAddr::SetSpecial(const std::string &strName)
  592. {
  593. if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
  594. std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
  595. if (vchAddr.size() != 16-sizeof(pchOnionCat))
  596. return false;
  597. memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
  598. for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
  599. ip[i + sizeof(pchOnionCat)] = vchAddr[i];
  600. return true;
  601. }
  602. return false;
  603. }
  604. CNetAddr::CNetAddr()
  605. {
  606. Init();
  607. }
  608. CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
  609. {
  610. SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
  611. }
  612. CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
  613. {
  614. SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
  615. }
  616. CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
  617. {
  618. Init();
  619. std::vector<CNetAddr> vIP;
  620. if (LookupHost(pszIp, vIP, 1, fAllowLookup))
  621. *this = vIP[0];
  622. }
  623. CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
  624. {
  625. Init();
  626. std::vector<CNetAddr> vIP;
  627. if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
  628. *this = vIP[0];
  629. }
  630. unsigned int CNetAddr::GetByte(int n) const
  631. {
  632. return ip[15-n];
  633. }
  634. bool CNetAddr::IsIPv4() const
  635. {
  636. return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
  637. }
  638. bool CNetAddr::IsIPv6() const
  639. {
  640. return (!IsIPv4() && !IsTor());
  641. }
  642. bool CNetAddr::IsRFC1918() const
  643. {
  644. return IsIPv4() && (
  645. GetByte(3) == 10 ||
  646. (GetByte(3) == 192 && GetByte(2) == 168) ||
  647. (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
  648. }
  649. bool CNetAddr::IsRFC2544() const
  650. {
  651. return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
  652. }
  653. bool CNetAddr::IsRFC3927() const
  654. {
  655. return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
  656. }
  657. bool CNetAddr::IsRFC6598() const
  658. {
  659. return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
  660. }
  661. bool CNetAddr::IsRFC5737() const
  662. {
  663. return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
  664. (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
  665. (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
  666. }
  667. bool CNetAddr::IsRFC3849() const
  668. {
  669. return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
  670. }
  671. bool CNetAddr::IsRFC3964() const
  672. {
  673. return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
  674. }
  675. bool CNetAddr::IsRFC6052() const
  676. {
  677. static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
  678. return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
  679. }
  680. bool CNetAddr::IsRFC4380() const
  681. {
  682. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
  683. }
  684. bool CNetAddr::IsRFC4862() const
  685. {
  686. static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
  687. return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
  688. }
  689. bool CNetAddr::IsRFC4193() const
  690. {
  691. return ((GetByte(15) & 0xFE) == 0xFC);
  692. }
  693. bool CNetAddr::IsRFC6145() const
  694. {
  695. static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
  696. return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
  697. }
  698. bool CNetAddr::IsRFC4843() const
  699. {
  700. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
  701. }
  702. bool CNetAddr::IsTor() const
  703. {
  704. return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
  705. }
  706. bool CNetAddr::IsLocal() const
  707. {
  708. // IPv4 loopback
  709. if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
  710. return true;
  711. // IPv6 loopback (::1/128)
  712. static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
  713. if (memcmp(ip, pchLocal, 16) == 0)
  714. return true;
  715. return false;
  716. }
  717. bool CNetAddr::IsMulticast() const
  718. {
  719. return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
  720. || (GetByte(15) == 0xFF);
  721. }
  722. bool CNetAddr::IsValid() const
  723. {
  724. // Cleanup 3-byte shifted addresses caused by garbage in size field
  725. // of addr messages from versions before 0.2.9 checksum.
  726. // Two consecutive addr messages look like this:
  727. // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
  728. // so if the first length field is garbled, it reads the second batch
  729. // of addr misaligned by 3 bytes.
  730. if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
  731. return false;
  732. // unspecified IPv6 address (::/128)
  733. unsigned char ipNone[16] = {};
  734. if (memcmp(ip, ipNone, 16) == 0)
  735. return false;
  736. // documentation IPv6 address
  737. if (IsRFC3849())
  738. return false;
  739. if (IsIPv4())
  740. {
  741. // INADDR_NONE
  742. uint32_t ipNone = INADDR_NONE;
  743. if (memcmp(ip+12, &ipNone, 4) == 0)
  744. return false;
  745. // 0
  746. ipNone = 0;
  747. if (memcmp(ip+12, &ipNone, 4) == 0)
  748. return false;
  749. }
  750. return true;
  751. }
  752. bool CNetAddr::IsRoutable() const
  753. {
  754. return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
  755. }
  756. enum Network CNetAddr::GetNetwork() const
  757. {
  758. if (!IsRoutable())
  759. return NET_UNROUTABLE;
  760. if (IsIPv4())
  761. return NET_IPV4;
  762. if (IsTor())
  763. return NET_TOR;
  764. return NET_IPV6;
  765. }
  766. std::string CNetAddr::ToStringIP() const
  767. {
  768. if (IsTor())
  769. return EncodeBase32(&ip[6], 10) + ".onion";
  770. CService serv(*this, 0);
  771. struct sockaddr_storage sockaddr;
  772. socklen_t socklen = sizeof(sockaddr);
  773. if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
  774. char name[1025] = "";
  775. if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
  776. return std::string(name);
  777. }
  778. if (IsIPv4())
  779. return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
  780. else
  781. return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  782. GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
  783. GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
  784. GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
  785. GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
  786. }
  787. std::string CNetAddr::ToString() const
  788. {
  789. return ToStringIP();
  790. }
  791. bool operator==(const CNetAddr& a, const CNetAddr& b)
  792. {
  793. return (memcmp(a.ip, b.ip, 16) == 0);
  794. }
  795. bool operator!=(const CNetAddr& a, const CNetAddr& b)
  796. {
  797. return (memcmp(a.ip, b.ip, 16) != 0);
  798. }
  799. bool operator<(const CNetAddr& a, const CNetAddr& b)
  800. {
  801. return (memcmp(a.ip, b.ip, 16) < 0);
  802. }
  803. bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
  804. {
  805. if (!IsIPv4())
  806. return false;
  807. memcpy(pipv4Addr, ip+12, 4);
  808. return true;
  809. }
  810. bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
  811. {
  812. memcpy(pipv6Addr, ip, 16);
  813. return true;
  814. }
  815. // get canonical identifier of an address' group
  816. // no two connections will be attempted to addresses with the same group
  817. std::vector<unsigned char> CNetAddr::GetGroup() const
  818. {
  819. std::vector<unsigned char> vchRet;
  820. int nClass = NET_IPV6;
  821. int nStartByte = 0;
  822. int nBits = 16;
  823. // all local addresses belong to the same group
  824. if (IsLocal())
  825. {
  826. nClass = 255;
  827. nBits = 0;
  828. }
  829. // all unroutable addresses belong to the same group
  830. if (!IsRoutable())
  831. {
  832. nClass = NET_UNROUTABLE;
  833. nBits = 0;
  834. }
  835. // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
  836. // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
  837. else if (IsIPv4() || IsRFC6145() || IsRFC6052())
  838. {
  839. nClass = NET_IPV4;
  840. nStartByte = 12;
  841. }
  842. // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
  843. else if (IsRFC3964())
  844. {
  845. nClass = NET_IPV4;
  846. nStartByte = 2;
  847. }
  848. // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
  849. else if (IsRFC4380())
  850. {
  851. vchRet.push_back(NET_IPV4);
  852. vchRet.push_back(GetByte(3) ^ 0xFF);
  853. vchRet.push_back(GetByte(2) ^ 0xFF);
  854. return vchRet;
  855. }
  856. else if (IsTor())
  857. {
  858. nClass = NET_TOR;
  859. nStartByte = 6;
  860. nBits = 4;
  861. }
  862. // for he.net, use /36 groups
  863. else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
  864. nBits = 36;
  865. // for the rest of the IPv6 network, use /32 groups
  866. else
  867. nBits = 32;
  868. vchRet.push_back(nClass);
  869. while (nBits >= 8)
  870. {
  871. vchRet.push_back(GetByte(15 - nStartByte));
  872. nStartByte++;
  873. nBits -= 8;
  874. }
  875. if (nBits > 0)
  876. vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
  877. return vchRet;
  878. }
  879. uint64_t CNetAddr::GetHash() const
  880. {
  881. uint256 hash = Hash(&ip[0], &ip[16]);
  882. uint64_t nRet;
  883. memcpy(&nRet, &hash, sizeof(nRet));
  884. return nRet;
  885. }
  886. // private extensions to enum Network, only returned by GetExtNetwork,
  887. // and only used in GetReachabilityFrom
  888. static const int NET_UNKNOWN = NET_MAX + 0;
  889. static const int NET_TEREDO = NET_MAX + 1;
  890. int static GetExtNetwork(const CNetAddr *addr)
  891. {
  892. if (addr == NULL)
  893. return NET_UNKNOWN;
  894. if (addr->IsRFC4380())
  895. return NET_TEREDO;
  896. return addr->GetNetwork();
  897. }
  898. /** Calculates a metric for how reachable (*this) is from a given partner */
  899. int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
  900. {
  901. enum Reachability {
  902. REACH_UNREACHABLE,
  903. REACH_DEFAULT,
  904. REACH_TEREDO,
  905. REACH_IPV6_WEAK,
  906. REACH_IPV4,
  907. REACH_IPV6_STRONG,
  908. REACH_PRIVATE
  909. };
  910. if (!IsRoutable())
  911. return REACH_UNREACHABLE;
  912. int ourNet = GetExtNetwork(this);
  913. int theirNet = GetExtNetwork(paddrPartner);
  914. bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
  915. switch(theirNet) {
  916. case NET_IPV4:
  917. switch(ourNet) {
  918. default: return REACH_DEFAULT;
  919. case NET_IPV4: return REACH_IPV4;
  920. }
  921. case NET_IPV6:
  922. switch(ourNet) {
  923. default: return REACH_DEFAULT;
  924. case NET_TEREDO: return REACH_TEREDO;
  925. case NET_IPV4: return REACH_IPV4;
  926. case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
  927. }
  928. case NET_TOR:
  929. switch(ourNet) {
  930. default: return REACH_DEFAULT;
  931. case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
  932. case NET_TOR: return REACH_PRIVATE;
  933. }
  934. case NET_TEREDO:
  935. switch(ourNet) {
  936. default: return REACH_DEFAULT;
  937. case NET_TEREDO: return REACH_TEREDO;
  938. case NET_IPV6: return REACH_IPV6_WEAK;
  939. case NET_IPV4: return REACH_IPV4;
  940. }
  941. case NET_UNKNOWN:
  942. case NET_UNROUTABLE:
  943. default:
  944. switch(ourNet) {
  945. default: return REACH_DEFAULT;
  946. case NET_TEREDO: return REACH_TEREDO;
  947. case NET_IPV6: return REACH_IPV6_WEAK;
  948. case NET_IPV4: return REACH_IPV4;
  949. case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
  950. }
  951. }
  952. }
  953. void CService::Init()
  954. {
  955. port = 0;
  956. }
  957. CService::CService()
  958. {
  959. Init();
  960. }
  961. CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
  962. {
  963. }
  964. CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
  965. {
  966. }
  967. CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
  968. {
  969. }
  970. CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
  971. {
  972. assert(addr.sin_family == AF_INET);
  973. }
  974. CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
  975. {
  976. assert(addr.sin6_family == AF_INET6);
  977. }
  978. bool CService::SetSockAddr(const struct sockaddr *paddr)
  979. {
  980. switch (paddr->sa_family) {
  981. case AF_INET:
  982. *this = CService(*(const struct sockaddr_in*)paddr);
  983. return true;
  984. case AF_INET6:
  985. *this = CService(*(const struct sockaddr_in6*)paddr);
  986. return true;
  987. default:
  988. return false;
  989. }
  990. }
  991. CService::CService(const char *pszIpPort, bool fAllowLookup)
  992. {
  993. Init();
  994. CService ip;
  995. if (Lookup(pszIpPort, ip, 0, fAllowLookup))
  996. *this = ip;
  997. }
  998. CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
  999. {
  1000. Init();
  1001. CService ip;
  1002. if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
  1003. *this = ip;
  1004. }
  1005. CService::CService(const std::string &strIpPort, bool fAllowLookup)
  1006. {
  1007. Init();
  1008. CService ip;
  1009. if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
  1010. *this = ip;
  1011. }
  1012. CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
  1013. {
  1014. Init();
  1015. CService ip;
  1016. if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
  1017. *this = ip;
  1018. }
  1019. unsigned short CService::GetPort() const
  1020. {
  1021. return port;
  1022. }
  1023. bool operator==(const CService& a, const CService& b)
  1024. {
  1025. return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
  1026. }
  1027. bool operator!=(const CService& a, const CService& b)
  1028. {
  1029. return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
  1030. }
  1031. bool operator<(const CService& a, const CService& b)
  1032. {
  1033. return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
  1034. }
  1035. bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
  1036. {
  1037. if (IsIPv4()) {
  1038. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
  1039. return false;
  1040. *addrlen = sizeof(struct sockaddr_in);
  1041. struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
  1042. memset(paddrin, 0, *addrlen);
  1043. if (!GetInAddr(&paddrin->sin_addr))
  1044. return false;
  1045. paddrin->sin_family = AF_INET;
  1046. paddrin->sin_port = htons(port);
  1047. return true;
  1048. }
  1049. if (IsIPv6()) {
  1050. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
  1051. return false;
  1052. *addrlen = sizeof(struct sockaddr_in6);
  1053. struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
  1054. memset(paddrin6, 0, *addrlen);
  1055. if (!GetIn6Addr(&paddrin6->sin6_addr))
  1056. return false;
  1057. paddrin6->sin6_family = AF_INET6;
  1058. paddrin6->sin6_port = htons(port);
  1059. return true;
  1060. }
  1061. return false;
  1062. }
  1063. std::vector<unsigned char> CService::GetKey() const
  1064. {
  1065. std::vector<unsigned char> vKey;
  1066. vKey.resize(18);
  1067. memcpy(&vKey[0], ip, 16);
  1068. vKey[16] = port / 0x100;
  1069. vKey[17] = port & 0x0FF;
  1070. return vKey;
  1071. }
  1072. std::string CService::ToStringPort() const
  1073. {
  1074. return strprintf("%u", port);
  1075. }
  1076. std::string CService::ToStringIPPort() const
  1077. {
  1078. if (IsIPv4() || IsTor()) {
  1079. return ToStringIP() + ":" + ToStringPort();
  1080. } else {
  1081. return "[" + ToStringIP() + "]:" + ToStringPort();
  1082. }
  1083. }
  1084. std::string CService::ToString() const
  1085. {
  1086. return ToStringIPPort();
  1087. }
  1088. void CService::SetPort(unsigned short portIn)
  1089. {
  1090. port = portIn;
  1091. }
  1092. CSubNet::CSubNet():
  1093. valid(false)
  1094. {
  1095. memset(netmask, 0, sizeof(netmask));
  1096. }
  1097. CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
  1098. {
  1099. size_t slash = strSubnet.find_last_of('/');
  1100. std::vector<CNetAddr> vIP;
  1101. valid = true;
  1102. // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
  1103. memset(netmask, 255, sizeof(netmask));
  1104. std::string strAddress = strSubnet.substr(0, slash);
  1105. if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
  1106. {
  1107. network = vIP[0];
  1108. if (slash != strSubnet.npos)
  1109. {
  1110. std::string strNetmask = strSubnet.substr(slash + 1);
  1111. int32_t n;
  1112. // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
  1113. const int astartofs = network.IsIPv4() ? 12 : 0;
  1114. if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
  1115. {
  1116. if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
  1117. {
  1118. n += astartofs*8;
  1119. // Clear bits [n..127]
  1120. for (; n < 128; ++n)
  1121. netmask[n>>3] &= ~(1<<(7-(n&7)));
  1122. }
  1123. else
  1124. {
  1125. valid = false;
  1126. }
  1127. }
  1128. else // If not a valid number, try full netmask syntax
  1129. {
  1130. if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
  1131. {
  1132. // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
  1133. // we don't want pchIPv4 to be part of the mask.
  1134. for(int x=astartofs; x<16; ++x)
  1135. netmask[x] = vIP[0].ip[x];
  1136. }
  1137. else
  1138. {
  1139. valid = false;
  1140. }
  1141. }
  1142. }
  1143. }
  1144. else
  1145. {
  1146. valid = false;
  1147. }
  1148. // Normalize network according to netmask
  1149. for(int x=0; x<16; ++x)
  1150. network.ip[x] &= netmask[x];
  1151. }
  1152. CSubNet::CSubNet(const CNetAddr &addr):
  1153. valid(addr.IsValid())
  1154. {
  1155. memset(netmask, 255, sizeof(netmask));
  1156. network = addr;
  1157. }
  1158. bool CSubNet::Match(const CNetAddr &addr) const
  1159. {
  1160. if (!valid || !addr.IsValid())
  1161. return false;
  1162. for(int x=0; x<16; ++x)
  1163. if ((addr.ip[x] & netmask[x]) != network.ip[x])
  1164. return false;
  1165. return true;
  1166. }
  1167. static inline int NetmaskBits(uint8_t x)
  1168. {
  1169. switch(x) {
  1170. case 0x00: return 0; break;
  1171. case 0x80: return 1; break;
  1172. case 0xc0: return 2; break;
  1173. case 0xe0: return 3; break;
  1174. case 0xf0: return 4; break;
  1175. case 0xf8: return 5; break;
  1176. case 0xfc: return 6; break;
  1177. case 0xfe: return 7; break;
  1178. case 0xff: return 8; break;
  1179. default: return -1; break;
  1180. }
  1181. }
  1182. std::string CSubNet::ToString() const
  1183. {
  1184. /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
  1185. int cidr = 0;
  1186. bool valid_cidr = true;
  1187. int n = network.IsIPv4() ? 12 : 0;
  1188. for (; n < 16 && netmask[n] == 0xff; ++n)
  1189. cidr += 8;
  1190. if (n < 16) {
  1191. int bits = NetmaskBits(netmask[n]);
  1192. if (bits < 0)
  1193. valid_cidr = false;
  1194. else
  1195. cidr += bits;
  1196. ++n;
  1197. }
  1198. for (; n < 16 && valid_cidr; ++n)
  1199. if (netmask[n] != 0x00)
  1200. valid_cidr = false;
  1201. /* Format output */
  1202. std::string strNetmask;
  1203. if (valid_cidr) {
  1204. strNetmask = strprintf("%u", cidr);
  1205. } else {
  1206. if (network.IsIPv4())
  1207. strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
  1208. else
  1209. strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  1210. netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
  1211. netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
  1212. netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
  1213. netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
  1214. }
  1215. return network.ToString() + "/" + strNetmask;
  1216. }
  1217. bool CSubNet::IsValid() const
  1218. {
  1219. return valid;
  1220. }
  1221. bool operator==(const CSubNet& a, const CSubNet& b)
  1222. {
  1223. return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
  1224. }
  1225. bool operator!=(const CSubNet& a, const CSubNet& b)
  1226. {
  1227. return !(a==b);
  1228. }
  1229. bool operator<(const CSubNet& a, const CSubNet& b)
  1230. {
  1231. return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
  1232. }
  1233. #ifdef WIN32
  1234. std::string NetworkErrorString(int err)
  1235. {
  1236. char buf[256];
  1237. buf[0] = 0;
  1238. if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
  1239. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1240. buf, sizeof(buf), NULL))
  1241. {
  1242. return strprintf("%s (%d)", buf, err);
  1243. }
  1244. else
  1245. {
  1246. return strprintf("Unknown error (%d)", err);
  1247. }
  1248. }
  1249. #else
  1250. std::string NetworkErrorString(int err)
  1251. {
  1252. char buf[256];
  1253. const char *s = buf;
  1254. buf[0] = 0;
  1255. /* Too bad there are two incompatible implementations of the
  1256. * thread-safe strerror. */
  1257. #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
  1258. s = strerror_r(err, buf, sizeof(buf));
  1259. #else /* POSIX variant always returns message in buffer */
  1260. if (strerror_r(err, buf, sizeof(buf)))
  1261. buf[0] = 0;
  1262. #endif
  1263. return strprintf("%s (%d)", s, err);
  1264. }
  1265. #endif
  1266. bool CloseSocket(SOCKET& hSocket)
  1267. {
  1268. if (hSocket == INVALID_SOCKET)
  1269. return false;
  1270. #ifdef WIN32
  1271. int ret = closesocket(hSocket);
  1272. #else
  1273. int ret = close(hSocket);
  1274. #endif
  1275. hSocket = INVALID_SOCKET;
  1276. return ret != SOCKET_ERROR;
  1277. }
  1278. bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
  1279. {
  1280. if (fNonBlocking) {
  1281. #ifdef WIN32
  1282. u_long nOne = 1;
  1283. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
  1284. #else
  1285. int fFlags = fcntl(hSocket, F_GETFL, 0);
  1286. if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
  1287. #endif
  1288. CloseSocket(hSocket);
  1289. return false;
  1290. }
  1291. } else {
  1292. #ifdef WIN32
  1293. u_long nZero = 0;
  1294. if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
  1295. #else
  1296. int fFlags = fcntl(hSocket, F_GETFL, 0);
  1297. if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
  1298. #endif
  1299. CloseSocket(hSocket);
  1300. return false;
  1301. }
  1302. }
  1303. return true;
  1304. }