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