netbase.cpp 35.3 KB
Newer Older
Pieter Wuille's avatar
Pieter Wuille committed
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-2014 The Bitcoin developers
Pieter Wuille's avatar
Pieter Wuille committed
3
// Distributed under the MIT/X11 software license, see the accompanying
Fordy's avatar
Fordy committed
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
Pieter Wuille's avatar
Pieter Wuille committed
5
6

#include "netbase.h"
7

Pieter Wuille's avatar
Pieter Wuille committed
8
#include "hash.h"
9
10
11
12
#include "sync.h"
#include "uint256.h"
#include "util.h"

Pieter Wuille's avatar
Pieter Wuille committed
13
#ifndef WIN32
14
#include <fcntl.h>
Pieter Wuille's avatar
Pieter Wuille committed
15
16
#endif

17
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
18
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
Pieter Wuille's avatar
Pieter Wuille committed
19

20
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
21
22
23
#define MSG_NOSIGNAL 0
#endif

Pieter Wuille's avatar
Pieter Wuille committed
24
25
26
using namespace std;

// Settings
Pieter Wuille's avatar
Pieter Wuille committed
27
28
static proxyType proxyInfo[NET_MAX];
static proxyType nameproxyInfo;
29
static CCriticalSection cs_proxyInfos;
Pieter Wuille's avatar
Pieter Wuille committed
30
int nConnectTimeout = 5000;
Pieter Wuille's avatar
Pieter Wuille committed
31
bool fNameLookup = false;
Pieter Wuille's avatar
Pieter Wuille committed
32
33
34

static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };

35
enum Network ParseNetwork(std::string net) {
36
    boost::to_lower(net);
37
38
39
40
41
42
    if (net == "ipv4") return NET_IPV4;
    if (net == "ipv6") return NET_IPV6;
    if (net == "tor")  return NET_TOR;
    return NET_UNROUTABLE;
}

43
44
45
46
47
48
49
void SplitHostPort(std::string in, int &portOut, std::string &hostOut) {
    size_t colon = in.find_last_of(':');
    // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
    bool fHaveColon = colon != in.npos;
    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
    bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos);
    if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
50
51
        int32_t n;
        if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
52
            in = in.substr(0, colon);
53
            portOut = n;
54
55
56
57
58
59
60
61
        }
    }
    if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']')
        hostOut = in.substr(1, in.size()-2);
    else
        hostOut = in;
}

62
bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Pieter Wuille's avatar
Pieter Wuille committed
63
64
{
    vIP.clear();
65
66
67
68
69
70
71
72
73

    {
        CNetAddr addr;
        if (addr.SetSpecial(std::string(pszName))) {
            vIP.push_back(addr);
            return true;
        }
    }

74
75
76
    struct addrinfo aiHint;
    memset(&aiHint, 0, sizeof(struct addrinfo));

Pieter Wuille's avatar
Pieter Wuille committed
77
78
79
    aiHint.ai_socktype = SOCK_STREAM;
    aiHint.ai_protocol = IPPROTO_TCP;
    aiHint.ai_family = AF_UNSPEC;
80
#ifdef WIN32
Pieter Wuille's avatar
Pieter Wuille committed
81
    aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
Pieter Wuille's avatar
Pieter Wuille committed
82
#else
Pieter Wuille's avatar
Pieter Wuille committed
83
    aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
Pieter Wuille's avatar
Pieter Wuille committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#endif
    struct addrinfo *aiRes = NULL;
    int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
    if (nErr)
        return false;

    struct addrinfo *aiTrav = aiRes;
    while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
    {
        if (aiTrav->ai_family == AF_INET)
        {
            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
            vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
        }

        if (aiTrav->ai_family == AF_INET6)
        {
            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
            vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
        }

        aiTrav = aiTrav->ai_next;
    }

    freeaddrinfo(aiRes);

    return (vIP.size() > 0);
}

113
bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Pieter Wuille's avatar
Pieter Wuille committed
114
{
115
116
    std::string strHost(pszName);
    if (strHost.empty())
Pieter Wuille's avatar
Pieter Wuille committed
117
        return false;
118
    if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]"))
Pieter Wuille's avatar
Pieter Wuille committed
119
    {
120
        strHost = strHost.substr(1, strHost.size() - 2);
Pieter Wuille's avatar
Pieter Wuille committed
121
122
    }

123
    return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
Pieter Wuille's avatar
Pieter Wuille committed
124
125
}

126
bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions)
Pieter Wuille's avatar
Pieter Wuille committed
127
128
129
130
{
    return LookupHost(pszName, vIP, nMaxSolutions, false);
}

131
bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Pieter Wuille's avatar
Pieter Wuille committed
132
133
134
135
{
    if (pszName[0] == 0)
        return false;
    int port = portDefault;
136
137
    std::string hostname = "";
    SplitHostPort(std::string(pszName), port, hostname);
Pieter Wuille's avatar
Pieter Wuille committed
138
139

    std::vector<CNetAddr> vIP;
140
    bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
141
142
143
    if (!fRet)
        return false;
    vAddr.resize(vIP.size());
144
    for (unsigned int i = 0; i < vIP.size(); i++)
145
146
147
148
149
150
151
152
        vAddr[i] = CService(vIP[i], port);
    return true;
}

bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
{
    std::vector<CService> vService;
    bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
Pieter Wuille's avatar
Pieter Wuille committed
153
154
    if (!fRet)
        return false;
155
    addr = vService[0];
Pieter Wuille's avatar
Pieter Wuille committed
156
157
158
159
160
161
162
163
    return true;
}

bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
    return Lookup(pszName, addr, portDefault, false);
}

Pieter Wuille's avatar
Pieter Wuille committed
164
165
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
166
    LogPrintf("SOCKS4 connecting %s\n", addrDest.ToString());
Pieter Wuille's avatar
Pieter Wuille committed
167
168
169
170
171
172
173
    if (!addrDest.IsIPv4())
    {
        closesocket(hSocket);
        return error("Proxy destination is not IPv4");
    }
    char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
    struct sockaddr_in addr;
174
175
176
177
178
179
    socklen_t len = sizeof(addr);
    if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
    {
        closesocket(hSocket);
        return error("Cannot get proxy destination address");
    }
Pieter Wuille's avatar
Pieter Wuille committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
    memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
    char* pszSocks4 = pszSocks4IP;
    int nSize = sizeof(pszSocks4IP);

    int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
    if (ret != nSize)
    {
        closesocket(hSocket);
        return error("Error sending to proxy");
    }
    char pchRet[8];
    if (recv(hSocket, pchRet, 8, 0) != 8)
    {
        closesocket(hSocket);
        return error("Error reading proxy response");
    }
    if (pchRet[1] != 0x5a)
    {
        closesocket(hSocket);
        if (pchRet[1] != 0x5b)
201
            LogPrintf("ERROR: Proxy returned error %d\n", pchRet[1]);
Pieter Wuille's avatar
Pieter Wuille committed
202
203
        return false;
    }
204
    LogPrintf("SOCKS4 connected %s\n", addrDest.ToString());
Pieter Wuille's avatar
Pieter Wuille committed
205
206
207
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
208
bool static Socks5(string strDest, int port, SOCKET& hSocket)
Pieter Wuille's avatar
Pieter Wuille committed
209
{
210
    LogPrintf("SOCKS5 connecting %s\n", strDest);
Pieter Wuille's avatar
Pieter Wuille committed
211
212
213
214
215
    if (strDest.size() > 255)
    {
        closesocket(hSocket);
        return error("Hostname too long");
    }
Pieter Wuille's avatar
Pieter Wuille committed
216
    char pszSocks5Init[] = "\5\1\0";
217
    ssize_t nSize = sizeof(pszSocks5Init) - 1;
Pieter Wuille's avatar
Pieter Wuille committed
218

219
    ssize_t ret = send(hSocket, pszSocks5Init, nSize, MSG_NOSIGNAL);
Pieter Wuille's avatar
Pieter Wuille committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    if (ret != nSize)
    {
        closesocket(hSocket);
        return error("Error sending to proxy");
    }
    char pchRet1[2];
    if (recv(hSocket, pchRet1, 2, 0) != 2)
    {
        closesocket(hSocket);
        return error("Error reading proxy response");
    }
    if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00)
    {
        closesocket(hSocket);
        return error("Proxy failed to initialize");
    }
Pieter Wuille's avatar
Pieter Wuille committed
236
237
238
    string strSocks5("\5\1");
    strSocks5 += '\000'; strSocks5 += '\003';
    strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
239
    strSocks5 += strDest;
Pieter Wuille's avatar
Pieter Wuille committed
240
241
    strSocks5 += static_cast<char>((port >> 8) & 0xFF);
    strSocks5 += static_cast<char>((port >> 0) & 0xFF);
Pieter Wuille's avatar
Pieter Wuille committed
242
    ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL);
Pieter Wuille's avatar
Pieter Wuille committed
243
    if (ret != (ssize_t)strSocks5.size())
Pieter Wuille's avatar
Pieter Wuille committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
    {
        closesocket(hSocket);
        return error("Error sending to proxy");
    }
    char pchRet2[4];
    if (recv(hSocket, pchRet2, 4, 0) != 4)
    {
        closesocket(hSocket);
        return error("Error reading proxy response");
    }
    if (pchRet2[0] != 0x05)
    {
        closesocket(hSocket);
        return error("Proxy failed to accept request");
    }
    if (pchRet2[1] != 0x00)
    {
        closesocket(hSocket);
        switch (pchRet2[1])
        {
            case 0x01: return error("Proxy error: general failure");
            case 0x02: return error("Proxy error: connection not allowed");
            case 0x03: return error("Proxy error: network unreachable");
            case 0x04: return error("Proxy error: host unreachable");
            case 0x05: return error("Proxy error: connection refused");
            case 0x06: return error("Proxy error: TTL expired");
            case 0x07: return error("Proxy error: protocol error");
            case 0x08: return error("Proxy error: address type not supported");
            default:   return error("Proxy error: unknown");
        }
    }
    if (pchRet2[2] != 0x00)
    {
        closesocket(hSocket);
        return error("Error: malformed proxy response");
    }
    char pchRet3[256];
    switch (pchRet2[3])
    {
        case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break;
        case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break;
        case 0x03:
        {
            ret = recv(hSocket, pchRet3, 1, 0) != 1;
288
289
            if (ret) {
                closesocket(hSocket);
Pieter Wuille's avatar
Pieter Wuille committed
290
                return error("Error reading from proxy");
291
            }
Pieter Wuille's avatar
Pieter Wuille committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
            int nRecv = pchRet3[0];
            ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv;
            break;
        }
        default: closesocket(hSocket); return error("Error: malformed proxy response");
    }
    if (ret)
    {
        closesocket(hSocket);
        return error("Error reading from proxy");
    }
    if (recv(hSocket, pchRet3, 2, 0) != 2)
    {
        closesocket(hSocket);
        return error("Error reading from proxy");
    }
308
    LogPrintf("SOCKS5 connected %s\n", strDest);
Pieter Wuille's avatar
Pieter Wuille committed
309
310
311
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
312
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
Pieter Wuille's avatar
Pieter Wuille committed
313
314
315
{
    hSocketRet = INVALID_SOCKET;

316
317
318
    struct sockaddr_storage sockaddr;
    socklen_t len = sizeof(sockaddr);
    if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
319
        LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
Pieter Wuille's avatar
Pieter Wuille committed
320
321
322
        return false;
    }

323
    SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
Pieter Wuille's avatar
Pieter Wuille committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
    if (hSocket == INVALID_SOCKET)
        return false;
#ifdef SO_NOSIGPIPE
    int set = 1;
    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif

#ifdef WIN32
    u_long fNonblock = 1;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    int fFlags = fcntl(hSocket, F_GETFL, 0);
    if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
    {
        closesocket(hSocket);
        return false;
    }

343
    if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
Pieter Wuille's avatar
Pieter Wuille committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    {
        // WSAEINVAL is here because some legacy version of winsock uses it
        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
        {
            struct timeval timeout;
            timeout.tv_sec  = nTimeout / 1000;
            timeout.tv_usec = (nTimeout % 1000) * 1000;

            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0)
            {
358
                LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
Pieter Wuille's avatar
Pieter Wuille committed
359
360
361
362
363
                closesocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR)
            {
364
                LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
Pieter Wuille's avatar
Pieter Wuille committed
365
366
367
368
369
370
371
372
373
374
                closesocket(hSocket);
                return false;
            }
            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
375
                LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
Pieter Wuille's avatar
Pieter Wuille committed
376
377
378
379
380
                closesocket(hSocket);
                return false;
            }
            if (nRet != 0)
            {
381
                LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
Pieter Wuille's avatar
Pieter Wuille committed
382
383
384
385
386
387
388
389
390
391
                closesocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
392
            LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
Pieter Wuille's avatar
Pieter Wuille committed
393
394
395
396
397
398
399
400
401
402
403
404
405
            closesocket(hSocket);
            return false;
        }
    }

    // this isn't even strictly necessary
    // CNode::ConnectNode immediately turns the socket back to non-blocking
    // but we'll turn it back to blocking just in case
#ifdef WIN32
    fNonblock = 0;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    fFlags = fcntl(hSocket, F_GETFL, 0);
406
    if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
Pieter Wuille's avatar
Pieter Wuille committed
407
408
409
410
411
412
#endif
    {
        closesocket(hSocket);
        return false;
    }

Pieter Wuille's avatar
Pieter Wuille committed
413
414
415
416
    hSocketRet = hSocket;
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
417
418
419
420
421
422
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
    assert(net >= 0 && net < NET_MAX);
    if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
        return false;
    if (nSocksVersion != 0 && !addrProxy.IsValid())
        return false;
423
    LOCK(cs_proxyInfos);
Pieter Wuille's avatar
Pieter Wuille committed
424
425
426
427
    proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
    return true;
}

428
bool GetProxy(enum Network net, proxyType &proxyInfoOut) {
Pieter Wuille's avatar
Pieter Wuille committed
429
    assert(net >= 0 && net < NET_MAX);
430
    LOCK(cs_proxyInfos);
Pieter Wuille's avatar
Pieter Wuille committed
431
432
    if (!proxyInfo[net].second)
        return false;
433
    proxyInfoOut = proxyInfo[net];
Pieter Wuille's avatar
Pieter Wuille committed
434
435
436
437
438
439
440
441
    return true;
}

bool SetNameProxy(CService addrProxy, int nSocksVersion) {
    if (nSocksVersion != 0 && nSocksVersion != 5)
        return false;
    if (nSocksVersion != 0 && !addrProxy.IsValid())
        return false;
442
    LOCK(cs_proxyInfos);
Pieter Wuille's avatar
Pieter Wuille committed
443
444
445
446
    nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
    return true;
}

447
448
449
450
451
452
453
454
455
456
bool GetNameProxy(proxyType &nameproxyInfoOut) {
    LOCK(cs_proxyInfos);
    if (!nameproxyInfo.second)
        return false;
    nameproxyInfoOut = nameproxyInfo;
    return true;
}

bool HaveNameProxy() {
    LOCK(cs_proxyInfos);
Pieter Wuille's avatar
Pieter Wuille committed
457
458
459
460
    return nameproxyInfo.second != 0;
}

bool IsProxy(const CNetAddr &addr) {
461
462
    LOCK(cs_proxyInfos);
    for (int i = 0; i < NET_MAX; i++) {
Pieter Wuille's avatar
Pieter Wuille committed
463
464
465
466
467
468
        if (proxyInfo[i].second && (addr == (CNetAddr)proxyInfo[i].first))
            return true;
    }
    return false;
}

Pieter Wuille's avatar
Pieter Wuille committed
469
470
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
471
    proxyType proxy;
Pieter Wuille's avatar
Pieter Wuille committed
472
473

    // no proxy needed
474
    if (!GetProxy(addrDest.GetNetwork(), proxy))
Pieter Wuille's avatar
Pieter Wuille committed
475
476
        return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);

Pieter Wuille's avatar
Pieter Wuille committed
477
478
    SOCKET hSocket = INVALID_SOCKET;

Pieter Wuille's avatar
Pieter Wuille committed
479
480
481
    // first connect to proxy server
    if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
        return false;
482

Pieter Wuille's avatar
Pieter Wuille committed
483
484
485
486
487
488
489
490
491
492
493
    // do socks negotiation
    switch (proxy.second) {
    case 4:
        if (!Socks4(addrDest, hSocket))
            return false;
        break;
    case 5:
        if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
            return false;
        break;
    default:
494
        closesocket(hSocket);
Pieter Wuille's avatar
Pieter Wuille committed
495
        return false;
Pieter Wuille's avatar
Pieter Wuille committed
496
497
498
499
500
501
    }

    hSocketRet = hSocket;
    return true;
}

502
503
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
{
504
    string strDest;
505
    int port = portDefault;
506
    SplitHostPort(string(pszDest), port, strDest);
507
508

    SOCKET hSocket = INVALID_SOCKET;
509
510
511
512
513

    proxyType nameproxy;
    GetNameProxy(nameproxy);

    CService addrResolved(CNetAddr(strDest, fNameLookup && !nameproxy.second), port);
514
515
516
517
518
    if (addrResolved.IsValid()) {
        addr = addrResolved;
        return ConnectSocket(addr, hSocketRet, nTimeout);
    }
    addr = CService("0.0.0.0:0");
519
    if (!nameproxy.second)
520
        return false;
521
    if (!ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout))
522
523
        return false;

524
    switch(nameproxy.second) {
Pieter Wuille's avatar
Pieter Wuille committed
525
        default:
526
527
528
        case 4:
            closesocket(hSocket);
            return false;
Pieter Wuille's avatar
Pieter Wuille committed
529
530
531
532
533
        case 5:
            if (!Socks5(strDest, port, hSocket))
                return false;
            break;
    }
534
535
536
537
538

    hSocketRet = hSocket;
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
539
540
void CNetAddr::Init()
{
541
    memset(ip, 0, sizeof(ip));
Pieter Wuille's avatar
Pieter Wuille committed
542
543
544
545
546
547
548
}

void CNetAddr::SetIP(const CNetAddr& ipIn)
{
    memcpy(ip, ipIn.ip, sizeof(ip));
}

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
{
    switch(network)
    {
        case NET_IPV4:
            memcpy(ip, pchIPv4, 12);
            memcpy(ip+12, ip_in, 4);
            break;
        case NET_IPV6:
            memcpy(ip, ip_in, 16);
            break;
        default:
            assert(!"invalid network");
    }
}

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};

bool CNetAddr::SetSpecial(const std::string &strName)
{
    if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
        std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
        if (vchAddr.size() != 16-sizeof(pchOnionCat))
            return false;
        memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
        for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
            ip[i + sizeof(pchOnionCat)] = vchAddr[i];
        return true;
    }
    return false;
}

Pieter Wuille's avatar
Pieter Wuille committed
581
582
583
584
585
586
587
CNetAddr::CNetAddr()
{
    Init();
}

CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
588
    SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
Pieter Wuille's avatar
Pieter Wuille committed
589
590
591
592
}

CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
593
    SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
Pieter Wuille's avatar
Pieter Wuille committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
}

CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
    Init();
    std::vector<CNetAddr> vIP;
    if (LookupHost(pszIp, vIP, 1, fAllowLookup))
        *this = vIP[0];
}

CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
    Init();
    std::vector<CNetAddr> vIP;
    if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
        *this = vIP[0];
}

612
unsigned int CNetAddr::GetByte(int n) const
Pieter Wuille's avatar
Pieter Wuille committed
613
614
615
616
617
618
619
620
621
{
    return ip[15-n];
}

bool CNetAddr::IsIPv4() const
{
    return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}

Pieter Wuille's avatar
Pieter Wuille committed
622
623
bool CNetAddr::IsIPv6() const
{
624
    return (!IsIPv4() && !IsTor());
Pieter Wuille's avatar
Pieter Wuille committed
625
626
}

Pieter Wuille's avatar
Pieter Wuille committed
627
628
629
bool CNetAddr::IsRFC1918() const
{
    return IsIPv4() && (
630
631
        GetByte(3) == 10 ||
        (GetByte(3) == 192 && GetByte(2) == 168) ||
Pieter Wuille's avatar
Pieter Wuille committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
        (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}

bool CNetAddr::IsRFC3927() const
{
    return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}

bool CNetAddr::IsRFC3849() const
{
    return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}

bool CNetAddr::IsRFC3964() const
{
    return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}

bool CNetAddr::IsRFC6052() const
{
    static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
    return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}

bool CNetAddr::IsRFC4380() const
{
    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}

bool CNetAddr::IsRFC4862() const
{
    static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
    return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}

bool CNetAddr::IsRFC4193() const
{
    return ((GetByte(15) & 0xFE) == 0xFC);
}

bool CNetAddr::IsRFC6145() const
{
    static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
    return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}

bool CNetAddr::IsRFC4843() const
{
680
    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
Pieter Wuille's avatar
Pieter Wuille committed
681
682
}

683
bool CNetAddr::IsTor() const
684
685
686
687
{
    return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}

Pieter Wuille's avatar
Pieter Wuille committed
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
bool CNetAddr::IsLocal() const
{
    // IPv4 loopback
   if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
       return true;

   // IPv6 loopback (::1/128)
   static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
   if (memcmp(ip, pchLocal, 16) == 0)
       return true;

   return false;
}

bool CNetAddr::IsMulticast() const
{
    return    (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
           || (GetByte(15) == 0xFF);
}

bool CNetAddr::IsValid() const
{
710
    // Cleanup 3-byte shifted addresses caused by garbage in size field
Pieter Wuille's avatar
Pieter Wuille committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    // of addr messages from versions before 0.2.9 checksum.
    // Two consecutive addr messages look like this:
    // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
    // so if the first length field is garbled, it reads the second batch
    // of addr misaligned by 3 bytes.
    if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
        return false;

    // unspecified IPv6 address (::/128)
    unsigned char ipNone[16] = {};
    if (memcmp(ip, ipNone, 16) == 0)
        return false;

    // documentation IPv6 address
    if (IsRFC3849())
        return false;

    if (IsIPv4())
    {
        // INADDR_NONE
        uint32_t ipNone = INADDR_NONE;
        if (memcmp(ip+12, &ipNone, 4) == 0)
            return false;

        // 0
        ipNone = 0;
        if (memcmp(ip+12, &ipNone, 4) == 0)
            return false;
    }

    return true;
}

bool CNetAddr::IsRoutable() const
{
746
    return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
Pieter Wuille's avatar
Pieter Wuille committed
747
748
}

749
750
751
752
753
754
755
756
enum Network CNetAddr::GetNetwork() const
{
    if (!IsRoutable())
        return NET_UNROUTABLE;

    if (IsIPv4())
        return NET_IPV4;

757
    if (IsTor())
758
759
760
761
762
        return NET_TOR;

    return NET_IPV6;
}

Pieter Wuille's avatar
Pieter Wuille committed
763
764
std::string CNetAddr::ToStringIP() const
{
765
766
    if (IsTor())
        return EncodeBase32(&ip[6], 10) + ".onion";
767
768
769
770
771
772
773
774
    CService serv(*this, 0);
    struct sockaddr_storage sockaddr;
    socklen_t socklen = sizeof(sockaddr);
    if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
        char name[1025] = "";
        if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
            return std::string(name);
    }
775
    if (IsIPv4())
Pieter Wuille's avatar
Pieter Wuille committed
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
        return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
    else
        return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
                         GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
                         GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
                         GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
                         GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}

std::string CNetAddr::ToString() const
{
    return ToStringIP();
}

bool operator==(const CNetAddr& a, const CNetAddr& b)
{
    return (memcmp(a.ip, b.ip, 16) == 0);
}

bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
    return (memcmp(a.ip, b.ip, 16) != 0);
}

bool operator<(const CNetAddr& a, const CNetAddr& b)
{
    return (memcmp(a.ip, b.ip, 16) < 0);
}

bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
    if (!IsIPv4())
        return false;
    memcpy(pipv4Addr, ip+12, 4);
    return true;
}

bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
    memcpy(pipv6Addr, ip, 16);
    return true;
}

// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
    std::vector<unsigned char> vchRet;
824
    int nClass = NET_IPV6;
Pieter Wuille's avatar
Pieter Wuille committed
825
826
827
    int nStartByte = 0;
    int nBits = 16;

828
829
830
    // all local addresses belong to the same group
    if (IsLocal())
    {
831
        nClass = 255;
832
833
834
835
        nBits = 0;
    }

    // all unroutable addresses belong to the same group
Pieter Wuille's avatar
Pieter Wuille committed
836
837
    if (!IsRoutable())
    {
838
        nClass = NET_UNROUTABLE;
839
        nBits = 0;
Pieter Wuille's avatar
Pieter Wuille committed
840
841
842
843
844
    }
    // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
    // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
    else if (IsIPv4() || IsRFC6145() || IsRFC6052())
    {
845
        nClass = NET_IPV4;
Pieter Wuille's avatar
Pieter Wuille committed
846
847
        nStartByte = 12;
    }
848
    // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
Pieter Wuille's avatar
Pieter Wuille committed
849
850
    else if (IsRFC3964())
    {
851
        nClass = NET_IPV4;
Pieter Wuille's avatar
Pieter Wuille committed
852
853
        nStartByte = 2;
    }
854
    // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
Pieter Wuille's avatar
Pieter Wuille committed
855
856
    else if (IsRFC4380())
    {
857
        vchRet.push_back(NET_IPV4);
Pieter Wuille's avatar
Pieter Wuille committed
858
859
860
861
        vchRet.push_back(GetByte(3) ^ 0xFF);
        vchRet.push_back(GetByte(2) ^ 0xFF);
        return vchRet;
    }
862
863
864
865
866
867
    else if (IsTor())
    {
        nClass = NET_TOR;
        nStartByte = 6;
        nBits = 4;
    }
Pieter Wuille's avatar
Pieter Wuille committed
868
    // for he.net, use /36 groups
869
    else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
Pieter Wuille's avatar
Pieter Wuille committed
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
        nBits = 36;
    // for the rest of the IPv6 network, use /32 groups
    else
        nBits = 32;

    vchRet.push_back(nClass);
    while (nBits >= 8)
    {
        vchRet.push_back(GetByte(15 - nStartByte));
        nStartByte++;
        nBits -= 8;
    }
    if (nBits > 0)
        vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));

    return vchRet;
}

888
uint64_t CNetAddr::GetHash() const
Pieter Wuille's avatar
Pieter Wuille committed
889
890
{
    uint256 hash = Hash(&ip[0], &ip[16]);
891
    uint64_t nRet;
Pieter Wuille's avatar
Pieter Wuille committed
892
893
894
895
896
897
    memcpy(&nRet, &hash, sizeof(nRet));
    return nRet;
}

void CNetAddr::print() const
{
898
    LogPrintf("CNetAddr(%s)\n", ToString());
Pieter Wuille's avatar
Pieter Wuille committed
899
900
}

901
902
903
904
905
906
907
908
909
910
911
912
913
914
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO  = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr *addr)
{
    if (addr == NULL)
        return NET_UNKNOWN;
    if (addr->IsRFC4380())
        return NET_TEREDO;
    return addr->GetNetwork();
}

/** Calculates a metric for how reachable (*this) is from a given partner */
915
916
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
    enum Reachability {
        REACH_UNREACHABLE,
        REACH_DEFAULT,
        REACH_TEREDO,
        REACH_IPV6_WEAK,
        REACH_IPV4,
        REACH_IPV6_STRONG,
        REACH_PRIVATE
    };

    if (!IsRoutable())
        return REACH_UNREACHABLE;

    int ourNet = GetExtNetwork(this);
    int theirNet = GetExtNetwork(paddrPartner);
    bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();

    switch(theirNet) {
    case NET_IPV4:
        switch(ourNet) {
        default:       return REACH_DEFAULT;
        case NET_IPV4: return REACH_IPV4;
        }
    case NET_IPV6:
        switch(ourNet) {
        default:         return REACH_DEFAULT;
        case NET_TEREDO: return REACH_TEREDO;
        case NET_IPV4:   return REACH_IPV4;
945
        case NET_IPV6:   return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
        }
    case NET_TOR:
        switch(ourNet) {
        default:         return REACH_DEFAULT;
        case NET_IPV4:   return REACH_IPV4; // Tor users can connect to IPv4 as well
        case NET_TOR:    return REACH_PRIVATE;
        }
    case NET_TEREDO:
        switch(ourNet) {
        default:          return REACH_DEFAULT;
        case NET_TEREDO:  return REACH_TEREDO;
        case NET_IPV6:    return REACH_IPV6_WEAK;
        case NET_IPV4:    return REACH_IPV4;
        }
    case NET_UNKNOWN:
    case NET_UNROUTABLE:
    default:
        switch(ourNet) {
        default:          return REACH_DEFAULT;
        case NET_TEREDO:  return REACH_TEREDO;
        case NET_IPV6:    return REACH_IPV6_WEAK;
        case NET_IPV4:    return REACH_IPV4;
968
        case NET_TOR:     return REACH_PRIVATE; // either from Tor, or don't care about our address
969
970
        }
    }
971
972
}

Pieter Wuille's avatar
Pieter Wuille committed
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
void CService::Init()
{
    port = 0;
}

CService::CService()
{
    Init();
}

CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}

CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}

CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}

CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
    assert(addr.sin_family == AF_INET);
}

CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
   assert(addr.sin6_family == AF_INET6);
}

1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
bool CService::SetSockAddr(const struct sockaddr *paddr)
{
    switch (paddr->sa_family) {
    case AF_INET:
        *this = CService(*(const struct sockaddr_in*)paddr);
        return true;
    case AF_INET6:
        *this = CService(*(const struct sockaddr_in6*)paddr);
        return true;
    default:
        return false;
    }
}

Pieter Wuille's avatar
Pieter Wuille committed
1019
1020
1021
1022
1023
1024
1025
1026
CService::CService(const char *pszIpPort, bool fAllowLookup)
{
    Init();
    CService ip;
    if (Lookup(pszIpPort, ip, 0, fAllowLookup))
        *this = ip;
}

Pieter Wuille's avatar
Pieter Wuille committed
1027
CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup)
Pieter Wuille's avatar
Pieter Wuille committed
1028
{
Pieter Wuille's avatar
Pieter Wuille committed
1029
1030
1031
1032
    Init();
    CService ip;
    if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
        *this = ip;
Pieter Wuille's avatar
Pieter Wuille committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
}

CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
    Init();
    CService ip;
    if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
        *this = ip;
}

Pieter Wuille's avatar
Pieter Wuille committed
1043
CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup)
Pieter Wuille's avatar
Pieter Wuille committed
1044
{
Pieter Wuille's avatar
Pieter Wuille committed
1045
1046
1047
1048
    Init();
    CService ip;
    if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
        *this = ip;
Pieter Wuille's avatar
Pieter Wuille committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
}

unsigned short CService::GetPort() const
{
    return port;
}

bool operator==(const CService& a, const CService& b)
{
    return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}

bool operator!=(const CService& a, const CService& b)
{
    return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}

bool operator<(const CService& a, const CService& b)
{
    return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}

1071
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
Pieter Wuille's avatar
Pieter Wuille committed
1072
{
1073
    if (IsIPv4()) {
1074
        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
            return false;
        *addrlen = sizeof(struct sockaddr_in);
        struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
        memset(paddrin, 0, *addrlen);
        if (!GetInAddr(&paddrin->sin_addr))
            return false;
        paddrin->sin_family = AF_INET;
        paddrin->sin_port = htons(port);
        return true;
    }
    if (IsIPv6()) {
1086
        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
            return false;
        *addrlen = sizeof(struct sockaddr_in6);
        struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
        memset(paddrin6, 0, *addrlen);
        if (!GetIn6Addr(&paddrin6->sin6_addr))
            return false;
        paddrin6->sin6_family = AF_INET6;
        paddrin6->sin6_port = htons(port);
        return true;
    }
    return false;
}
Pieter Wuille's avatar
Pieter Wuille committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111

std::vector<unsigned char> CService::GetKey() const
{
     std::vector<unsigned char> vKey;
     vKey.resize(18);
     memcpy(&vKey[0], ip, 16);
     vKey[16] = port / 0x100;
     vKey[17] = port & 0x0FF;
     return vKey;
}

std::string CService::ToStringPort() const
{
1112
    return strprintf("%u", port);
Pieter Wuille's avatar
Pieter Wuille committed
1113
1114
1115
1116
}

std::string CService::ToStringIPPort() const
{
1117
    if (IsIPv4() || IsTor()) {
Pieter Wuille's avatar
Pieter Wuille committed
1118
1119
1120
1121
        return ToStringIP() + ":" + ToStringPort();
    } else {
        return "[" + ToStringIP() + "]:" + ToStringPort();
    }
Pieter Wuille's avatar
Pieter Wuille committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
}

std::string CService::ToString() const
{
    return ToStringIPPort();
}

void CService::print() const
{
1131
    LogPrintf("CService(%s)\n", ToString());
Pieter Wuille's avatar
Pieter Wuille committed
1132
1133
1134
1135
1136
1137
}

void CService::SetPort(unsigned short portIn)
{
    port = portIn;
}
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239

CSubNet::CSubNet():
    valid(false)
{
    memset(netmask, 0, sizeof(netmask));
}

CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup)
{
    size_t slash = strSubnet.find_last_of('/');
    std::vector<CNetAddr> vIP;

    valid = true;
    // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
    memset(netmask, 255, sizeof(netmask));

    std::string strAddress = strSubnet.substr(0, slash);
    if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup))
    {
        network = vIP[0];
        if (slash != strSubnet.npos)
        {
            std::string strNetmask = strSubnet.substr(slash + 1);
            int32_t n;
            // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
            int noffset = network.IsIPv4() ? (12 * 8) : 0;
            if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
            {
                if(n >= 0 && n <= (128 - noffset)) // Only valid if in range of bits of address
                {
                    n += noffset;
                    // Clear bits [n..127]
                    for (; n < 128; ++n)
                        netmask[n>>3] &= ~(1<<(n&7));
                }
                else
                {
                    valid = false;
                }
            }
            else // If not a valid number, try full netmask syntax
            {
                if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
                {
                    // Remember: GetByte returns bytes in reversed order
                    // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
                    // we don't want pchIPv4 to be part of the mask.
                    int asize = network.IsIPv4() ? 4 : 16;
                    for(int x=0; x<asize; ++x)
                        netmask[15-x] = vIP[0].GetByte(x);
                }
                else
                {
                    valid = false;
                }
            }
        }
    }
    else
    {
        valid = false;
    }
}

bool CSubNet::Match(const CNetAddr &addr) const
{
    if (!valid || !addr.IsValid())
        return false;
    for(int x=0; x<16; ++x)
        if ((addr.GetByte(x) & netmask[15-x]) != network.GetByte(x))
            return false;
    return true;
}

std::string CSubNet::ToString() const
{
    std::string strNetmask;
    if (network.IsIPv4())
        strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
    else
        strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
                         netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
                         netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
                         netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
                         netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
    return network.ToString() + "/" + strNetmask;
}

bool CSubNet::IsValid() const
{
    return valid;
}

bool operator==(const CSubNet& a, const CSubNet& b)
{
    return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
}

bool operator!=(const CSubNet& a, const CSubNet& b)
{
    return !(a==b);
}
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272

#ifdef WIN32
std::string NetworkErrorString(int err)
{
    char buf[256];
    buf[0] = 0;
    if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
            NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            buf, sizeof(buf), NULL))
    {
        return strprintf("%s (%d)", buf, err);
    }
    else
    {
        return strprintf("Unknown error (%d)", err);
    }
}
#else
std::string NetworkErrorString(int err)
{
    char buf[256];
    const char *s = buf;
    buf[0] = 0;
    /* Too bad there are two incompatible implementations of the
     * thread-safe strerror. */
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    (void) strerror_r(err, buf, sizeof(buf));
#endif
    return strprintf("%s (%d)", s, err);
}
#endif