]>
Commit | Line | Data |
---|---|---|
0a61b0df | 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. |
0a61b0df | 5 | |
35b8af92 | 6 | #if defined(HAVE_CONFIG_H) |
f3967bcc | 7 | #include "config/bitcoin-config.h" |
35b8af92 CF |
8 | #endif |
9 | ||
72b21929 | 10 | #include "main.h" |
40c2614e | 11 | #include "net.h" |
51ed9ec9 | 12 | |
5fee401f | 13 | #include "addrman.h" |
51ed9ec9 | 14 | #include "chainparams.h" |
71697f97 | 15 | #include "clientversion.h" |
d2270111 | 16 | #include "primitives/transaction.h" |
9a1dcea2 | 17 | #include "scheduler.h" |
ed6d0b5f | 18 | #include "ui_interface.h" |
dec84cae | 19 | #include "crypto/common.h" |
51ed9ec9 | 20 | |
9cb1ec9c | 21 | #ifdef _WIN32 |
013df1cc | 22 | #include <string.h> |
51ed9ec9 | 23 | #else |
98148a71 | 24 | #include <fcntl.h> |
25 | #endif | |
26 | ||
a486abd4 | 27 | #include <boost/filesystem.hpp> |
ad49c256 | 28 | #include <boost/thread.hpp> |
a486abd4 | 29 | |
c43da3f1 PW |
30 | // Dump addresses to peers.dat every 15 minutes (900s) |
31 | #define DUMP_ADDRESSES_INTERVAL 900 | |
51ed9ec9 BD |
32 | |
33 | #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) | |
35b8af92 CF |
34 | #define MSG_NOSIGNAL 0 |
35 | #endif | |
c43da3f1 | 36 | |
9e9ca2b6 PK |
37 | // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. |
38 | // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. | |
9cb1ec9c | 39 | #ifdef _WIN32 |
9e9ca2b6 PK |
40 | #ifndef PROTECTION_LEVEL_UNRESTRICTED |
41 | #define PROTECTION_LEVEL_UNRESTRICTED 10 | |
42 | #endif | |
43 | #ifndef IPV6_PROTECTION_LEVEL | |
44 | #define IPV6_PROTECTION_LEVEL 23 | |
45 | #endif | |
46 | #endif | |
47 | ||
611116d4 | 48 | using namespace std; |
223b6f1b | 49 | |
dc942e6f PW |
50 | namespace { |
51 | const int MAX_OUTBOUND_CONNECTIONS = 8; | |
52 | ||
53 | struct ListenSocket { | |
54 | SOCKET socket; | |
55 | bool whitelisted; | |
56 | ||
57 | ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} | |
58 | }; | |
59 | } | |
0a61b0df | 60 | |
0a61b0df | 61 | // |
62 | // Global state variables | |
63 | // | |
587f929c | 64 | bool fDiscover = true; |
53a08815 | 65 | bool fListen = true; |
70352e11 | 66 | uint64_t nLocalServices = NODE_NETWORK; |
d387b8ec WL |
67 | CCriticalSection cs_mapLocalHost; |
68 | map<CNetAddr, LocalServiceInfo> mapLocalHost; | |
457754d2 | 69 | static bool vfLimited[NET_MAX] = {}; |
99860de3 | 70 | static CNode* pnodeLocalHost = NULL; |
51ed9ec9 | 71 | uint64_t nLocalHostNonce = 0; |
dc942e6f | 72 | static std::vector<ListenSocket> vhListenSocket; |
5fee401f | 73 | CAddrMan addrman; |
8a5ae3c7 | 74 | int nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS; |
94064710 | 75 | bool fAddressesInitialized = false; |
0a61b0df | 76 | |
77 | vector<CNode*> vNodes; | |
78 | CCriticalSection cs_vNodes; | |
0a61b0df | 79 | map<CInv, CDataStream> mapRelay; |
51ed9ec9 | 80 | deque<pair<int64_t, CInv> > vRelayExpiration; |
0a61b0df | 81 | CCriticalSection cs_mapRelay; |
51ed9ec9 | 82 | limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); |
0a61b0df | 83 | |
478b01d9 PW |
84 | static deque<string> vOneShots; |
85 | CCriticalSection cs_vOneShots; | |
0a61b0df | 86 | |
b24e6e4d MC |
87 | set<CNetAddr> setservAddNodeAddresses; |
88 | CCriticalSection cs_setservAddNodeAddresses; | |
89 | ||
74088e86 MC |
90 | vector<std::string> vAddedNodes; |
91 | CCriticalSection cs_vAddedNodes; | |
92 | ||
b2864d2f PW |
93 | NodeId nLastNodeId = 0; |
94 | CCriticalSection cs_nLastNodeId; | |
95 | ||
c59abe25 | 96 | static CSemaphore *semOutbound = NULL; |
351593b9 | 97 | boost::condition_variable messageHandlerCondition; |
0a61b0df | 98 | |
501da250 EL |
99 | // Signals for message handling |
100 | static CNodeSignals g_signals; | |
101 | CNodeSignals& GetNodeSignals() { return g_signals; } | |
663224c2 | 102 | |
db954a65 | 103 | void AddOneShot(const std::string& strDest) |
478b01d9 PW |
104 | { |
105 | LOCK(cs_vOneShots); | |
106 | vOneShots.push_back(strDest); | |
107 | } | |
108 | ||
00bcfe0b GA |
109 | unsigned short GetListenPort() |
110 | { | |
3fca36b0 | 111 | //printf("Listenport.%u\n",Params().GetDefaultPort()); |
0e4b3175 | 112 | return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); |
00bcfe0b | 113 | } |
0a61b0df | 114 | |
39857190 | 115 | // find 'best' local address for a particular peer |
7fa4443f | 116 | bool GetLocal(CService& addr, const CNetAddr *paddrPeer) |
39857190 | 117 | { |
53a08815 | 118 | if (!fListen) |
39857190 | 119 | return false; |
0a61b0df | 120 | |
139d2f7c | 121 | int nBestScore = -1; |
39857190 PW |
122 | int nBestReachability = -1; |
123 | { | |
124 | LOCK(cs_mapLocalHost); | |
139d2f7c | 125 | for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) |
39857190 | 126 | { |
139d2f7c | 127 | int nScore = (*it).second.nScore; |
39857190 | 128 | int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); |
139d2f7c | 129 | if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) |
39857190 | 130 | { |
139d2f7c | 131 | addr = CService((*it).first, (*it).second.nPort); |
39857190 | 132 | nBestReachability = nReachability; |
139d2f7c | 133 | nBestScore = nScore; |
39857190 PW |
134 | } |
135 | } | |
136 | } | |
139d2f7c | 137 | return nBestScore >= 0; |
39857190 | 138 | } |
0a61b0df | 139 | |
739d6155 CF |
140 | //! Convert the pnSeeds6 array into usable address objects. |
141 | static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn) | |
142 | { | |
143 | // It'll only connect to one or two seed nodes because once it connects, | |
144 | // it'll get a pile of addresses with newer timestamps. | |
145 | // Seed nodes are given a random 'last seen time' of between one and two | |
146 | // weeks ago. | |
147 | const int64_t nOneWeek = 7*24*60*60; | |
148 | std::vector<CAddress> vSeedsOut; | |
149 | vSeedsOut.reserve(vSeedsIn.size()); | |
150 | for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i) | |
151 | { | |
152 | struct in6_addr ip; | |
153 | memcpy(&ip, i->addr, sizeof(ip)); | |
154 | CAddress addr(CService(ip, i->port)); | |
155 | addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; | |
156 | vSeedsOut.push_back(addr); | |
157 | } | |
158 | return vSeedsOut; | |
159 | } | |
160 | ||
39857190 | 161 | // get best local address for a particular peer as a CAddress |
845c86d1 GM |
162 | // Otherwise, return the unroutable 0.0.0.0 but filled in with |
163 | // the normal parameters, since the IP may be changed to a useful | |
164 | // one by discovery. | |
39857190 PW |
165 | CAddress GetLocalAddress(const CNetAddr *paddrPeer) |
166 | { | |
845c86d1 | 167 | CAddress ret(CService("0.0.0.0",GetListenPort()),0); |
7fa4443f | 168 | CService addr; |
39857190 PW |
169 | if (GetLocal(addr, paddrPeer)) |
170 | { | |
7fa4443f | 171 | ret = CAddress(addr); |
39857190 | 172 | } |
845c86d1 GM |
173 | ret.nServices = nLocalServices; |
174 | ret.nTime = GetAdjustedTime(); | |
39857190 PW |
175 | return ret; |
176 | } | |
0a61b0df | 177 | |
845c86d1 | 178 | int GetnScore(const CService& addr) |
39857190 | 179 | { |
845c86d1 GM |
180 | LOCK(cs_mapLocalHost); |
181 | if (mapLocalHost.count(addr) == LOCAL_NONE) | |
182 | return 0; | |
183 | return mapLocalHost[addr].nScore; | |
184 | } | |
185 | ||
186 | // Is our peer's addrLocal potentially useful as an external IP source? | |
187 | bool IsPeerAddrLocalGood(CNode *pnode) | |
188 | { | |
189 | return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && | |
190 | !IsLimited(pnode->addrLocal.GetNetwork()); | |
191 | } | |
192 | ||
193 | // pushes our own address to a peer | |
194 | void AdvertizeLocal(CNode *pnode) | |
195 | { | |
196 | if (fListen && pnode->fSuccessfullyConnected) | |
39857190 | 197 | { |
845c86d1 GM |
198 | CAddress addrLocal = GetLocalAddress(&pnode->addr); |
199 | // If discovery is enabled, sometimes give our peer the address it | |
200 | // tells us that it sees us as in case it has a better idea of our | |
201 | // address than we do. | |
202 | if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || | |
203 | GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) | |
39857190 | 204 | { |
845c86d1 GM |
205 | addrLocal.SetIP(pnode->addrLocal); |
206 | } | |
207 | if (addrLocal.IsRoutable()) | |
208 | { | |
eb5f63fe | 209 | LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString()); |
845c86d1 | 210 | pnode->PushAddress(addrLocal); |
39857190 PW |
211 | } |
212 | } | |
213 | } | |
214 | ||
215 | // learn a new local address | |
7fa4443f | 216 | bool AddLocal(const CService& addr, int nScore) |
39857190 PW |
217 | { |
218 | if (!addr.IsRoutable()) | |
219 | return false; | |
220 | ||
587f929c | 221 | if (!fDiscover && nScore < LOCAL_MANUAL) |
af4006b3 PW |
222 | return false; |
223 | ||
09b4e26a | 224 | if (IsLimited(addr)) |
1653f97c PW |
225 | return false; |
226 | ||
7d9d134b | 227 | LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); |
39857190 PW |
228 | |
229 | { | |
230 | LOCK(cs_mapLocalHost); | |
139d2f7c PW |
231 | bool fAlready = mapLocalHost.count(addr) > 0; |
232 | LocalServiceInfo &info = mapLocalHost[addr]; | |
233 | if (!fAlready || nScore >= info.nScore) { | |
af4da4be PW |
234 | info.nScore = nScore + (fAlready ? 1 : 0); |
235 | info.nPort = addr.GetPort(); | |
139d2f7c | 236 | } |
39857190 PW |
237 | } |
238 | ||
39857190 PW |
239 | return true; |
240 | } | |
241 | ||
5a3cb32e | 242 | bool AddLocal(const CNetAddr &addr, int nScore) |
7fa4443f | 243 | { |
5a3cb32e | 244 | return AddLocal(CService(addr, GetListenPort()), nScore); |
7fa4443f PW |
245 | } |
246 | ||
975dc649 WL |
247 | bool RemoveLocal(const CService& addr) |
248 | { | |
249 | LOCK(cs_mapLocalHost); | |
250 | LogPrintf("RemoveLocal(%s)\n", addr.ToString()); | |
251 | mapLocalHost.erase(addr); | |
252 | return true; | |
253 | } | |
254 | ||
457754d2 PW |
255 | /** Make a particular network entirely off-limits (no automatic connects to it) */ |
256 | void SetLimited(enum Network net, bool fLimited) | |
257 | { | |
0f1707de PW |
258 | if (net == NET_UNROUTABLE) |
259 | return; | |
457754d2 PW |
260 | LOCK(cs_mapLocalHost); |
261 | vfLimited[net] = fLimited; | |
262 | } | |
263 | ||
0f1707de | 264 | bool IsLimited(enum Network net) |
457754d2 PW |
265 | { |
266 | LOCK(cs_mapLocalHost); | |
0f1707de PW |
267 | return vfLimited[net]; |
268 | } | |
269 | ||
270 | bool IsLimited(const CNetAddr &addr) | |
271 | { | |
272 | return IsLimited(addr.GetNetwork()); | |
457754d2 PW |
273 | } |
274 | ||
275 | /** vote for a local address */ | |
7fa4443f | 276 | bool SeenLocal(const CService& addr) |
39857190 PW |
277 | { |
278 | { | |
279 | LOCK(cs_mapLocalHost); | |
280 | if (mapLocalHost.count(addr) == 0) | |
281 | return false; | |
139d2f7c | 282 | mapLocalHost[addr].nScore++; |
39857190 | 283 | } |
39857190 PW |
284 | return true; |
285 | } | |
286 | ||
845c86d1 | 287 | |
457754d2 | 288 | /** check whether a given address is potentially local */ |
7fa4443f | 289 | bool IsLocal(const CService& addr) |
39857190 PW |
290 | { |
291 | LOCK(cs_mapLocalHost); | |
292 | return mapLocalHost.count(addr) > 0; | |
293 | } | |
0a61b0df | 294 | |
c91a9471 WL |
295 | /** check whether a given network is one we can probably connect to */ |
296 | bool IsReachable(enum Network net) | |
297 | { | |
298 | LOCK(cs_mapLocalHost); | |
a05be280 | 299 | return !vfLimited[net]; |
c91a9471 WL |
300 | } |
301 | ||
457754d2 | 302 | /** check whether a given address is in a network we can probably connect to */ |
090e5b40 PW |
303 | bool IsReachable(const CNetAddr& addr) |
304 | { | |
457754d2 | 305 | enum Network net = addr.GetNetwork(); |
c91a9471 | 306 | return IsReachable(net); |
090e5b40 | 307 | } |
0a61b0df | 308 | |
67a42f92 | 309 | void AddressCurrentlyConnected(const CService& addr) |
0a61b0df | 310 | { |
5fee401f | 311 | addrman.Connected(addr); |
0a61b0df | 312 | } |
313 | ||
314 | ||
51ed9ec9 BD |
315 | uint64_t CNode::nTotalBytesRecv = 0; |
316 | uint64_t CNode::nTotalBytesSent = 0; | |
ce14345a SE |
317 | CCriticalSection CNode::cs_totalBytesRecv; |
318 | CCriticalSection CNode::cs_totalBytesSent; | |
0a61b0df | 319 | |
67a42f92 | 320 | CNode* FindNode(const CNetAddr& ip) |
0a61b0df | 321 | { |
b001c871 PK |
322 | LOCK(cs_vNodes); |
323 | BOOST_FOREACH(CNode* pnode, vNodes) | |
324 | if ((CNetAddr)pnode->addr == ip) | |
325 | return (pnode); | |
0a61b0df | 326 | return NULL; |
327 | } | |
328 | ||
e5219399 JS |
329 | CNode* FindNode(const CSubNet& subNet) |
330 | { | |
331 | LOCK(cs_vNodes); | |
332 | BOOST_FOREACH(CNode* pnode, vNodes) | |
333 | if (subNet.Match((CNetAddr)pnode->addr)) | |
334 | return (pnode); | |
335 | return NULL; | |
336 | } | |
337 | ||
0430c30a | 338 | CNode* FindNode(const std::string& addrName) |
9bab521d PW |
339 | { |
340 | LOCK(cs_vNodes); | |
341 | BOOST_FOREACH(CNode* pnode, vNodes) | |
342 | if (pnode->addrName == addrName) | |
343 | return (pnode); | |
344 | return NULL; | |
345 | } | |
346 | ||
67a42f92 | 347 | CNode* FindNode(const CService& addr) |
0a61b0df | 348 | { |
b001c871 PK |
349 | LOCK(cs_vNodes); |
350 | BOOST_FOREACH(CNode* pnode, vNodes) | |
351 | if ((CService)pnode->addr == addr) | |
352 | return (pnode); | |
0a61b0df | 353 | return NULL; |
354 | } | |
355 | ||
cedaa714 | 356 | CNode* ConnectNode(CAddress addrConnect, const char *pszDest) |
0a61b0df | 357 | { |
478b01d9 | 358 | if (pszDest == NULL) { |
39857190 | 359 | if (IsLocal(addrConnect)) |
9bab521d | 360 | return NULL; |
0a61b0df | 361 | |
9bab521d PW |
362 | // Look for an existing connection |
363 | CNode* pnode = FindNode((CService)addrConnect); | |
364 | if (pnode) | |
365 | { | |
cedaa714 | 366 | pnode->AddRef(); |
9bab521d PW |
367 | return pnode; |
368 | } | |
0a61b0df | 369 | } |
370 | ||
371 | /// debug print | |
881a85a2 | 372 | LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", |
7d9d134b | 373 | pszDest ? pszDest : addrConnect.ToString(), |
5bd6c31b | 374 | pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); |
0a61b0df | 375 | |
376 | // Connect | |
377 | SOCKET hSocket; | |
35e408f8 WL |
378 | bool proxyConnectionFailed = false; |
379 | if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : | |
380 | ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) | |
0a61b0df | 381 | { |
0095b9a1 PW |
382 | if (!IsSelectableSocket(hSocket)) { |
383 | LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); | |
384 | CloseSocket(hSocket); | |
385 | return NULL; | |
386 | } | |
387 | ||
9bab521d PW |
388 | addrman.Attempt(addrConnect); |
389 | ||
0a61b0df | 390 | // Add node |
9bab521d | 391 | CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); |
cedaa714 | 392 | pnode->AddRef(); |
9bab521d | 393 | |
f8dcd5ca PW |
394 | { |
395 | LOCK(cs_vNodes); | |
0a61b0df | 396 | vNodes.push_back(pnode); |
f8dcd5ca | 397 | } |
0a61b0df | 398 | |
399 | pnode->nTimeConnected = GetTime(); | |
2e36866f | 400 | |
0a61b0df | 401 | return pnode; |
35e408f8 WL |
402 | } else if (!proxyConnectionFailed) { |
403 | // If connecting to the node failed, and failure is not caused by a problem connecting to | |
404 | // the proxy, mark this as an attempt. | |
405 | addrman.Attempt(addrConnect); | |
0a61b0df | 406 | } |
5bd6c31b PK |
407 | |
408 | return NULL; | |
0a61b0df | 409 | } |
410 | ||
411 | void CNode::CloseSocketDisconnect() | |
412 | { | |
413 | fDisconnect = true; | |
414 | if (hSocket != INVALID_SOCKET) | |
415 | { | |
2e36866f | 416 | LogPrint("net", "disconnecting peer=%d\n", id); |
43f510d3 | 417 | CloseSocket(hSocket); |
0a61b0df | 418 | } |
6ed71b5e PW |
419 | |
420 | // in case this fails, we'll empty the recv buffer when the CNode is deleted | |
421 | TRY_LOCK(cs_vRecvMsg, lockRecv); | |
422 | if (lockRecv) | |
423 | vRecvMsg.clear(); | |
0a61b0df | 424 | } |
425 | ||
f8ded588 GA |
426 | void CNode::PushVersion() |
427 | { | |
4c6d41b8 PW |
428 | int nBestHeight = g_signals.GetHeight().get_value_or(0); |
429 | ||
51ed9ec9 | 430 | int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); |
587f929c | 431 | CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); |
39857190 | 432 | CAddress addrMe = GetLocalAddress(&addr); |
001a53d7 | 433 | GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); |
2e36866f B |
434 | if (fLogIPs) |
435 | LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); | |
436 | else | |
437 | LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); | |
f8ded588 | 438 | PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, |
c87f462b | 439 | nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true); |
f8ded588 GA |
440 | } |
441 | ||
442 | ||
443 | ||
444 | ||
445 | ||
e5219399 | 446 | std::map<CSubNet, int64_t> CNode::setBanned; |
15f3ad4d GA |
447 | CCriticalSection CNode::cs_setBanned; |
448 | ||
449 | void CNode::ClearBanned() | |
450 | { | |
0382246b | 451 | LOCK(cs_setBanned); |
15f3ad4d GA |
452 | setBanned.clear(); |
453 | } | |
454 | ||
67a42f92 | 455 | bool CNode::IsBanned(CNetAddr ip) |
15f3ad4d GA |
456 | { |
457 | bool fResult = false; | |
15f3ad4d | 458 | { |
f8dcd5ca | 459 | LOCK(cs_setBanned); |
e5219399 JS |
460 | for (std::map<CSubNet, int64_t>::iterator it = setBanned.begin(); it != setBanned.end(); it++) |
461 | { | |
462 | CSubNet subNet = (*it).first; | |
463 | int64_t t = (*it).second; | |
464 | ||
465 | if(subNet.Match(ip) && GetTime() < t) | |
466 | fResult = true; | |
467 | } | |
468 | } | |
469 | return fResult; | |
470 | } | |
471 | ||
472 | bool CNode::IsBanned(CSubNet subnet) | |
473 | { | |
474 | bool fResult = false; | |
475 | { | |
476 | LOCK(cs_setBanned); | |
477 | std::map<CSubNet, int64_t>::iterator i = setBanned.find(subnet); | |
15f3ad4d GA |
478 | if (i != setBanned.end()) |
479 | { | |
51ed9ec9 | 480 | int64_t t = (*i).second; |
15f3ad4d GA |
481 | if (GetTime() < t) |
482 | fResult = true; | |
483 | } | |
484 | } | |
485 | return fResult; | |
486 | } | |
487 | ||
fcc8920f | 488 | void CNode::Ban(const CNetAddr& addr, int64_t bantimeoffset, bool sinceUnixEpoch) { |
e5219399 | 489 | CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128")); |
fcc8920f | 490 | Ban(subNet, bantimeoffset, sinceUnixEpoch); |
e5219399 JS |
491 | } |
492 | ||
fcc8920f | 493 | void CNode::Ban(const CSubNet& subNet, int64_t bantimeoffset, bool sinceUnixEpoch) { |
b2864d2f | 494 | int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban |
99782971 | 495 | if (bantimeoffset > 0) |
fcc8920f | 496 | banTime = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset; |
99782971 JS |
497 | |
498 | LOCK(cs_setBanned); | |
e5219399 JS |
499 | if (setBanned[subNet] < banTime) |
500 | setBanned[subNet] = banTime; | |
15f3ad4d GA |
501 | } |
502 | ||
99782971 | 503 | bool CNode::Unban(const CNetAddr &addr) { |
e5219399 JS |
504 | CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128")); |
505 | return Unban(subNet); | |
506 | } | |
507 | ||
508 | bool CNode::Unban(const CSubNet &subNet) { | |
99782971 | 509 | LOCK(cs_setBanned); |
e5219399 | 510 | if (setBanned.erase(subNet)) |
99782971 JS |
511 | return true; |
512 | return false; | |
513 | } | |
514 | ||
e5219399 | 515 | void CNode::GetBanned(std::map<CSubNet, int64_t> &banMap) |
99782971 JS |
516 | { |
517 | LOCK(cs_setBanned); | |
518 | banMap = setBanned; //create a thread safe copy | |
15f3ad4d GA |
519 | } |
520 | ||
dc942e6f PW |
521 | |
522 | std::vector<CSubNet> CNode::vWhitelistedRange; | |
523 | CCriticalSection CNode::cs_vWhitelistedRange; | |
524 | ||
525 | bool CNode::IsWhitelistedRange(const CNetAddr &addr) { | |
526 | LOCK(cs_vWhitelistedRange); | |
527 | BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) { | |
528 | if (subnet.Match(addr)) | |
529 | return true; | |
530 | } | |
531 | return false; | |
532 | } | |
533 | ||
534 | void CNode::AddWhitelistedRange(const CSubNet &subnet) { | |
535 | LOCK(cs_vWhitelistedRange); | |
536 | vWhitelistedRange.push_back(subnet); | |
537 | } | |
538 | ||
1006f070 JG |
539 | void CNode::copyStats(CNodeStats &stats) |
540 | { | |
b2864d2f | 541 | stats.nodeid = this->GetId(); |
7e9d662e S |
542 | stats.nServices = nServices; |
543 | stats.nLastSend = nLastSend; | |
544 | stats.nLastRecv = nLastRecv; | |
545 | stats.nTimeConnected = nTimeConnected; | |
546 | stats.nTimeOffset = nTimeOffset; | |
547 | stats.addrName = addrName; | |
548 | stats.nVersion = nVersion; | |
549 | stats.cleanSubVer = cleanSubVer; | |
550 | stats.fInbound = fInbound; | |
551 | stats.nStartingHeight = nStartingHeight; | |
552 | stats.nSendBytes = nSendBytes; | |
553 | stats.nRecvBytes = nRecvBytes; | |
554 | stats.fWhitelisted = fWhitelisted; | |
fabba0e6 | 555 | |
971bb3e9 JL |
556 | // It is common for nodes with good ping times to suddenly become lagged, |
557 | // due to a new block arriving or other large transfer. | |
558 | // Merely reporting pingtime might fool the caller into thinking the node was still responsive, | |
559 | // since pingtime does not update until the ping is complete, which might take a while. | |
560 | // So, if a ping is taking an unusually long time in flight, | |
561 | // the caller can immediately detect that this is happening. | |
51ed9ec9 | 562 | int64_t nPingUsecWait = 0; |
971bb3e9 JL |
563 | if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { |
564 | nPingUsecWait = GetTimeMicros() - nPingUsecStart; | |
565 | } | |
fabba0e6 | 566 | |
971bb3e9 JL |
567 | // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) |
568 | stats.dPingTime = (((double)nPingUsecTime) / 1e6); | |
569 | stats.dPingWait = (((double)nPingUsecWait) / 1e6); | |
fabba0e6 | 570 | |
547c61f8 JL |
571 | // Leave string empty if addrLocal invalid (not filled in yet) |
572 | stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; | |
1006f070 | 573 | } |
0a61b0df | 574 | |
607dbfde JG |
575 | // requires LOCK(cs_vRecvMsg) |
576 | bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) | |
577 | { | |
578 | while (nBytes > 0) { | |
579 | ||
580 | // get current incomplete message, or create a new one | |
967f2459 | 581 | if (vRecvMsg.empty() || |
607dbfde | 582 | vRecvMsg.back().complete()) |
eec37136 | 583 | vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, nRecvVersion)); |
607dbfde JG |
584 | |
585 | CNetMessage& msg = vRecvMsg.back(); | |
586 | ||
587 | // absorb network data | |
588 | int handled; | |
589 | if (!msg.in_data) | |
590 | handled = msg.readHeader(pch, nBytes); | |
591 | else | |
592 | handled = msg.readData(pch, nBytes); | |
593 | ||
594 | if (handled < 0) | |
595 | return false; | |
596 | ||
ba04c4a7 | 597 | if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { |
e0020d4c | 598 | LogPrint("net", "Oversized message from peer=%i, disconnecting\n", GetId()); |
ba04c4a7 PW |
599 | return false; |
600 | } | |
601 | ||
607dbfde JG |
602 | pch += handled; |
603 | nBytes -= handled; | |
9f4da19b | 604 | |
351593b9 | 605 | if (msg.complete()) { |
9f4da19b | 606 | msg.nTime = GetTimeMicros(); |
351593b9 | 607 | messageHandlerCondition.notify_one(); |
608 | } | |
607dbfde JG |
609 | } |
610 | ||
611 | return true; | |
612 | } | |
613 | ||
614 | int CNetMessage::readHeader(const char *pch, unsigned int nBytes) | |
615 | { | |
616 | // copy data to temporary parsing buffer | |
617 | unsigned int nRemaining = 24 - nHdrPos; | |
618 | unsigned int nCopy = std::min(nRemaining, nBytes); | |
619 | ||
620 | memcpy(&hdrbuf[nHdrPos], pch, nCopy); | |
621 | nHdrPos += nCopy; | |
622 | ||
623 | // if header incomplete, exit | |
624 | if (nHdrPos < 24) | |
625 | return nCopy; | |
626 | ||
627 | // deserialize to CMessageHeader | |
628 | try { | |
629 | hdrbuf >> hdr; | |
630 | } | |
27df4123 | 631 | catch (const std::exception&) { |
607dbfde JG |
632 | return -1; |
633 | } | |
634 | ||
635 | // reject messages larger than MAX_SIZE | |
636 | if (hdr.nMessageSize > MAX_SIZE) | |
637 | return -1; | |
638 | ||
639 | // switch state to reading message data | |
640 | in_data = true; | |
607dbfde JG |
641 | |
642 | return nCopy; | |
643 | } | |
644 | ||
645 | int CNetMessage::readData(const char *pch, unsigned int nBytes) | |
646 | { | |
647 | unsigned int nRemaining = hdr.nMessageSize - nDataPos; | |
648 | unsigned int nCopy = std::min(nRemaining, nBytes); | |
649 | ||
806fd19e PW |
650 | if (vRecv.size() < nDataPos + nCopy) { |
651 | // Allocate up to 256 KiB ahead, but never more than the total message size. | |
652 | vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); | |
653 | } | |
654 | ||
607dbfde JG |
655 | memcpy(&vRecv[nDataPos], pch, nCopy); |
656 | nDataPos += nCopy; | |
657 | ||
658 | return nCopy; | |
659 | } | |
660 | ||
0a61b0df | 661 | |
662 | ||
663 | ||
664 | ||
665 | ||
666 | ||
667 | ||
668 | ||
bc2f5aa7 JG |
669 | // requires LOCK(cs_vSend) |
670 | void SocketSendData(CNode *pnode) | |
671 | { | |
41b052ad PW |
672 | std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); |
673 | ||
674 | while (it != pnode->vSendMsg.end()) { | |
675 | const CSerializeData &data = *it; | |
676 | assert(data.size() > pnode->nSendOffset); | |
677 | int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); | |
678 | if (nBytes > 0) { | |
679 | pnode->nLastSend = GetTime(); | |
86648a8d | 680 | pnode->nSendBytes += nBytes; |
41b052ad | 681 | pnode->nSendOffset += nBytes; |
ce14345a | 682 | pnode->RecordBytesSent(nBytes); |
41b052ad PW |
683 | if (pnode->nSendOffset == data.size()) { |
684 | pnode->nSendOffset = 0; | |
685 | pnode->nSendSize -= data.size(); | |
686 | it++; | |
687 | } else { | |
688 | // could not send full message; stop sending more | |
689 | break; | |
690 | } | |
691 | } else { | |
692 | if (nBytes < 0) { | |
693 | // error | |
694 | int nErr = WSAGetLastError(); | |
695 | if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) | |
696 | { | |
a60838d0 | 697 | LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); |
41b052ad PW |
698 | pnode->CloseSocketDisconnect(); |
699 | } | |
700 | } | |
701 | // couldn't send anything at all | |
702 | break; | |
bc2f5aa7 JG |
703 | } |
704 | } | |
41b052ad PW |
705 | |
706 | if (it == pnode->vSendMsg.end()) { | |
707 | assert(pnode->nSendOffset == 0); | |
708 | assert(pnode->nSendSize == 0); | |
709 | } | |
710 | pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); | |
bc2f5aa7 | 711 | } |
0a61b0df | 712 | |
3427517d PW |
713 | static list<CNode*> vNodesDisconnected; |
714 | ||
6e966f67 PS |
715 | class CNodeRef { |
716 | public: | |
f1e7e371 PS |
717 | CNodeRef(CNode *pnode) : _pnode(pnode) { |
718 | LOCK(cs_vNodes); | |
719 | _pnode->AddRef(); | |
720 | } | |
721 | ||
722 | ~CNodeRef() { | |
723 | LOCK(cs_vNodes); | |
724 | _pnode->Release(); | |
725 | } | |
6e966f67 PS |
726 | |
727 | CNode& operator *() const {return *_pnode;}; | |
728 | CNode* operator ->() const {return _pnode;}; | |
75c0598c PS |
729 | |
730 | CNodeRef& operator =(const CNodeRef& other) | |
731 | { | |
732 | if (this != &other) { | |
f1e7e371 PS |
733 | LOCK(cs_vNodes); |
734 | ||
75c0598c PS |
735 | _pnode->Release(); |
736 | _pnode = other._pnode; | |
737 | _pnode->AddRef(); | |
738 | } | |
739 | return *this; | |
740 | } | |
741 | ||
742 | CNodeRef(const CNodeRef& other): | |
743 | _pnode(other._pnode) | |
744 | { | |
f1e7e371 | 745 | LOCK(cs_vNodes); |
75c0598c PS |
746 | _pnode->AddRef(); |
747 | } | |
6e966f67 PS |
748 | private: |
749 | CNode *_pnode; | |
750 | }; | |
751 | ||
752 | static bool ReverseCompareNodeMinPingTime(const CNodeRef &a, const CNodeRef &b) | |
2fa41ff9 PS |
753 | { |
754 | return a->nMinPingUsecTime > b->nMinPingUsecTime; | |
755 | } | |
756 | ||
6e966f67 | 757 | static bool ReverseCompareNodeTimeConnected(const CNodeRef &a, const CNodeRef &b) |
2fa41ff9 PS |
758 | { |
759 | return a->nTimeConnected > b->nTimeConnected; | |
760 | } | |
761 | ||
762 | class CompareNetGroupKeyed | |
763 | { | |
764 | std::vector<unsigned char> vchSecretKey; | |
765 | public: | |
766 | CompareNetGroupKeyed() | |
767 | { | |
768 | vchSecretKey.resize(32, 0); | |
769 | GetRandBytes(vchSecretKey.data(), vchSecretKey.size()); | |
770 | } | |
771 | ||
6e966f67 | 772 | bool operator()(const CNodeRef &a, const CNodeRef &b) |
2fa41ff9 PS |
773 | { |
774 | std::vector<unsigned char> vchGroupA, vchGroupB; | |
775 | CSHA256 hashA, hashB; | |
776 | std::vector<unsigned char> vchA(32), vchB(32); | |
777 | ||
778 | vchGroupA = a->addr.GetGroup(); | |
779 | vchGroupB = b->addr.GetGroup(); | |
780 | ||
781 | hashA.Write(begin_ptr(vchGroupA), vchGroupA.size()); | |
782 | hashB.Write(begin_ptr(vchGroupB), vchGroupB.size()); | |
783 | ||
784 | hashA.Write(begin_ptr(vchSecretKey), vchSecretKey.size()); | |
785 | hashB.Write(begin_ptr(vchSecretKey), vchSecretKey.size()); | |
786 | ||
787 | hashA.Finalize(begin_ptr(vchA)); | |
788 | hashB.Finalize(begin_ptr(vchB)); | |
789 | ||
790 | return vchA < vchB; | |
791 | } | |
792 | }; | |
793 | ||
dd99be0f | 794 | static bool AttemptToEvictConnection(bool fPreferNewConnection) { |
6e966f67 | 795 | std::vector<CNodeRef> vEvictionCandidates; |
2fa41ff9 PS |
796 | { |
797 | LOCK(cs_vNodes); | |
798 | ||
799 | BOOST_FOREACH(CNode *node, vNodes) { | |
800 | if (node->fWhitelisted) | |
801 | continue; | |
802 | if (!node->fInbound) | |
803 | continue; | |
804 | if (node->fDisconnect) | |
805 | continue; | |
6e966f67 | 806 | vEvictionCandidates.push_back(CNodeRef(node)); |
2fa41ff9 PS |
807 | } |
808 | } | |
809 | ||
ce94413e PS |
810 | if (vEvictionCandidates.empty()) return false; |
811 | ||
2fa41ff9 | 812 | // Protect connections with certain characteristics |
396bd999 | 813 | |
72b21929 S |
814 | // Check version of eviction candidates and prioritize nodes which do not support network upgrade. |
815 | std::vector<CNodeRef> vTmpEvictionCandidates; | |
816 | int height; | |
817 | { | |
818 | LOCK(cs_main); | |
819 | height = chainActive.Height(); | |
820 | } | |
821 | ||
822 | const Consensus::Params& params = Params().GetConsensus(); | |
823 | int nActivationHeight = params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight; | |
824 | ||
825 | if (nActivationHeight > 0 && | |
826 | height < nActivationHeight && | |
827 | height >= nActivationHeight - NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD) | |
828 | { | |
829 | // Find any nodes which don't support Overwinter protocol version | |
830 | BOOST_FOREACH(const CNodeRef &node, vEvictionCandidates) { | |
831 | if (node->nVersion < params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion) { | |
832 | vTmpEvictionCandidates.push_back(node); | |
833 | } | |
834 | } | |
835 | ||
836 | // Prioritize these nodes by replacing eviction set with them | |
837 | if (vTmpEvictionCandidates.size() > 0) { | |
838 | vEvictionCandidates = vTmpEvictionCandidates; | |
839 | } | |
840 | } | |
841 | ||
396bd999 PS |
842 | // Deterministically select 4 peers to protect by netgroup. |
843 | // An attacker cannot predict which netgroups will be protected. | |
2fa41ff9 PS |
844 | static CompareNetGroupKeyed comparerNetGroupKeyed; |
845 | std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), comparerNetGroupKeyed); | |
846 | vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); | |
847 | ||
ce94413e PS |
848 | if (vEvictionCandidates.empty()) return false; |
849 | ||
396bd999 PS |
850 | // Protect the 8 nodes with the best ping times. |
851 | // An attacker cannot manipulate this metric without physically moving nodes closer to the target. | |
2fa41ff9 PS |
852 | std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime); |
853 | vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end()); | |
854 | ||
ce94413e PS |
855 | if (vEvictionCandidates.empty()) return false; |
856 | ||
b63e75ae | 857 | // Protect the half of the remaining nodes which have been connected the longest. |
396bd999 | 858 | // This replicates the existing implicit behavior. |
2fa41ff9 | 859 | std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected); |
ce94413e | 860 | vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end()); |
2fa41ff9 | 861 | |
ce94413e | 862 | if (vEvictionCandidates.empty()) return false; |
2fa41ff9 | 863 | |
f28a87b4 GM |
864 | // Identify the network group with the most connections and youngest member. |
865 | // (vEvictionCandidates is already sorted by reverse connect time) | |
85e84f5e | 866 | std::vector<unsigned char> naMostConnections; |
2fa41ff9 | 867 | unsigned int nMostConnections = 0; |
f28a87b4 | 868 | int64_t nMostConnectionsTime = 0; |
85e84f5e | 869 | std::map<std::vector<unsigned char>, std::vector<CNodeRef> > mapAddrCounts; |
6e966f67 | 870 | BOOST_FOREACH(const CNodeRef &node, vEvictionCandidates) { |
85e84f5e | 871 | mapAddrCounts[node->addr.GetGroup()].push_back(node); |
f28a87b4 GM |
872 | int64_t grouptime = mapAddrCounts[node->addr.GetGroup()][0]->nTimeConnected; |
873 | size_t groupsize = mapAddrCounts[node->addr.GetGroup()].size(); | |
2fa41ff9 | 874 | |
f28a87b4 GM |
875 | if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) { |
876 | nMostConnections = groupsize; | |
877 | nMostConnectionsTime = grouptime; | |
85e84f5e | 878 | naMostConnections = node->addr.GetGroup(); |
2fa41ff9 PS |
879 | } |
880 | } | |
881 | ||
85e84f5e | 882 | // Reduce to the network group with the most connections |
2fa41ff9 PS |
883 | vEvictionCandidates = mapAddrCounts[naMostConnections]; |
884 | ||
f28a87b4 | 885 | // Do not disconnect peers if there is only one unprotected connection from their network group. |
2fa41ff9 | 886 | if (vEvictionCandidates.size() <= 1) |
dd99be0f PS |
887 | // unless we prefer the new connection (for whitelisted peers) |
888 | if (!fPreferNewConnection) | |
889 | return false; | |
2fa41ff9 | 890 | |
f28a87b4 | 891 | // Disconnect from the network group with the most connections |
2fa41ff9 PS |
892 | vEvictionCandidates[0]->fDisconnect = true; |
893 | ||
894 | return true; | |
895 | } | |
896 | ||
057d6078 PS |
897 | static void AcceptConnection(const ListenSocket& hListenSocket) { |
898 | struct sockaddr_storage sockaddr; | |
899 | socklen_t len = sizeof(sockaddr); | |
900 | SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); | |
901 | CAddress addr; | |
902 | int nInbound = 0; | |
903 | int nMaxInbound = nMaxConnections - MAX_OUTBOUND_CONNECTIONS; | |
904 | ||
905 | if (hSocket != INVALID_SOCKET) | |
906 | if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) | |
907 | LogPrintf("Warning: Unknown socket family\n"); | |
908 | ||
909 | bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); | |
910 | { | |
911 | LOCK(cs_vNodes); | |
912 | BOOST_FOREACH(CNode* pnode, vNodes) | |
913 | if (pnode->fInbound) | |
914 | nInbound++; | |
915 | } | |
916 | ||
917 | if (hSocket == INVALID_SOCKET) | |
918 | { | |
919 | int nErr = WSAGetLastError(); | |
920 | if (nErr != WSAEWOULDBLOCK) | |
921 | LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); | |
12005016 | 922 | return; |
057d6078 | 923 | } |
12005016 PS |
924 | |
925 | if (!IsSelectableSocket(hSocket)) | |
057d6078 PS |
926 | { |
927 | LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); | |
928 | CloseSocket(hSocket); | |
12005016 | 929 | return; |
057d6078 | 930 | } |
12005016 | 931 | |
bd80ec0d | 932 | if (CNode::IsBanned(addr) && !whitelisted) |
057d6078 | 933 | { |
bd80ec0d | 934 | LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); |
057d6078 | 935 | CloseSocket(hSocket); |
12005016 | 936 | return; |
057d6078 | 937 | } |
12005016 | 938 | |
bd80ec0d | 939 | if (nInbound >= nMaxInbound) |
057d6078 | 940 | { |
dd99be0f | 941 | if (!AttemptToEvictConnection(whitelisted)) { |
2fa41ff9 PS |
942 | // No connection to evict, disconnect the new connection |
943 | LogPrint("net", "failed to find an eviction candidate - connection dropped (full)\n"); | |
944 | CloseSocket(hSocket); | |
945 | return; | |
946 | } | |
057d6078 | 947 | } |
12005016 PS |
948 | |
949 | // According to the internet TCP_NODELAY is not carried into accepted sockets | |
950 | // on all platforms. Set it again here just to be sure. | |
951 | int set = 1; | |
9cb1ec9c | 952 | #ifdef _WIN32 |
12005016 | 953 | setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int)); |
057d6078 | 954 | #else |
12005016 | 955 | setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int)); |
057d6078 PS |
956 | #endif |
957 | ||
12005016 PS |
958 | CNode* pnode = new CNode(hSocket, addr, "", true); |
959 | pnode->AddRef(); | |
960 | pnode->fWhitelisted = whitelisted; | |
057d6078 | 961 | |
12005016 | 962 | LogPrint("net", "connection from %s accepted\n", addr.ToString()); |
057d6078 | 963 | |
12005016 PS |
964 | { |
965 | LOCK(cs_vNodes); | |
966 | vNodes.push_back(pnode); | |
057d6078 PS |
967 | } |
968 | } | |
969 | ||
21eb5ada | 970 | void ThreadSocketHandler() |
0a61b0df | 971 | { |
735a6069 | 972 | unsigned int nPrevNodeCount = 0; |
050d2e95 | 973 | while (true) |
0a61b0df | 974 | { |
975 | // | |
976 | // Disconnect nodes | |
977 | // | |
0a61b0df | 978 | { |
f8dcd5ca | 979 | LOCK(cs_vNodes); |
0a61b0df | 980 | // Disconnect unused nodes |
981 | vector<CNode*> vNodesCopy = vNodes; | |
223b6f1b | 982 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 983 | { |
984 | if (pnode->fDisconnect || | |
41b052ad | 985 | (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) |
0a61b0df | 986 | { |
987 | // remove from vNodes | |
988 | vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); | |
989 | ||
c59abe25 PW |
990 | // release outbound grant (if any) |
991 | pnode->grantOutbound.Release(); | |
092631f0 | 992 | |
0a61b0df | 993 | // close socket and cleanup |
994 | pnode->CloseSocketDisconnect(); | |
0a61b0df | 995 | |
996 | // hold in disconnected pool until all refs are released | |
0a61b0df | 997 | if (pnode->fNetworkNode || pnode->fInbound) |
998 | pnode->Release(); | |
999 | vNodesDisconnected.push_back(pnode); | |
1000 | } | |
1001 | } | |
49d754d9 PW |
1002 | } |
1003 | { | |
0a61b0df | 1004 | // Delete disconnected nodes |
1005 | list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; | |
223b6f1b | 1006 | BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) |
0a61b0df | 1007 | { |
1008 | // wait until threads are done using it | |
1009 | if (pnode->GetRefCount() <= 0) | |
1010 | { | |
1011 | bool fDelete = false; | |
f8dcd5ca PW |
1012 | { |
1013 | TRY_LOCK(pnode->cs_vSend, lockSend); | |
1014 | if (lockSend) | |
1015 | { | |
607dbfde | 1016 | TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); |
f8dcd5ca PW |
1017 | if (lockRecv) |
1018 | { | |
529a4d48 WL |
1019 | TRY_LOCK(pnode->cs_inventory, lockInv); |
1020 | if (lockInv) | |
1021 | fDelete = true; | |
f8dcd5ca PW |
1022 | } |
1023 | } | |
1024 | } | |
0a61b0df | 1025 | if (fDelete) |
1026 | { | |
1027 | vNodesDisconnected.remove(pnode); | |
1028 | delete pnode; | |
1029 | } | |
1030 | } | |
1031 | } | |
1032 | } | |
ce14345a | 1033 | if(vNodes.size() != nPrevNodeCount) { |
0a61b0df | 1034 | nPrevNodeCount = vNodes.size(); |
ce14345a | 1035 | uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); |
0a61b0df | 1036 | } |
1037 | ||
0a61b0df | 1038 | // |
1039 | // Find which sockets have data to receive | |
1040 | // | |
1041 | struct timeval timeout; | |
1042 | timeout.tv_sec = 0; | |
1043 | timeout.tv_usec = 50000; // frequency to poll pnode->vSend | |
1044 | ||
1045 | fd_set fdsetRecv; | |
1046 | fd_set fdsetSend; | |
1047 | fd_set fdsetError; | |
1048 | FD_ZERO(&fdsetRecv); | |
1049 | FD_ZERO(&fdsetSend); | |
1050 | FD_ZERO(&fdsetError); | |
1051 | SOCKET hSocketMax = 0; | |
23879447 | 1052 | bool have_fds = false; |
5f88e888 | 1053 | |
dc942e6f PW |
1054 | BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) { |
1055 | FD_SET(hListenSocket.socket, &fdsetRecv); | |
1056 | hSocketMax = max(hSocketMax, hListenSocket.socket); | |
23879447 | 1057 | have_fds = true; |
8f10a288 | 1058 | } |
5d599212 | 1059 | |
0a61b0df | 1060 | { |
f8dcd5ca | 1061 | LOCK(cs_vNodes); |
223b6f1b | 1062 | BOOST_FOREACH(CNode* pnode, vNodes) |
0a61b0df | 1063 | { |
d7f1d200 | 1064 | if (pnode->hSocket == INVALID_SOCKET) |
0a61b0df | 1065 | continue; |
a9d9f0f5 PW |
1066 | FD_SET(pnode->hSocket, &fdsetError); |
1067 | hSocketMax = max(hSocketMax, pnode->hSocket); | |
1068 | have_fds = true; | |
1069 | ||
1070 | // Implement the following logic: | |
1071 | // * If there is data to send, select() for sending data. As this only | |
1072 | // happens when optimistic write failed, we choose to first drain the | |
1073 | // write buffer in this case before receiving more. This avoids | |
1074 | // needlessly queueing received data, if the remote peer is not themselves | |
c938fb1f | 1075 | // receiving data. This means properly utilizing TCP flow control signaling. |
a9d9f0f5 PW |
1076 | // * Otherwise, if there is no (complete) message in the receive buffer, |
1077 | // or there is space left in the buffer, select() for receiving data. | |
1078 | // * (if neither of the above applies, there is certainly one message | |
1079 | // in the receiver buffer ready to be processed). | |
1080 | // Together, that means that at least one of the following is always possible, | |
1081 | // so we don't deadlock: | |
1082 | // * We send some data. | |
1083 | // * We wait for data to be received (and disconnect after timeout). | |
1084 | // * We process a message in the buffer (message handler thread). | |
f8dcd5ca PW |
1085 | { |
1086 | TRY_LOCK(pnode->cs_vSend, lockSend); | |
a9d9f0f5 PW |
1087 | if (lockSend && !pnode->vSendMsg.empty()) { |
1088 | FD_SET(pnode->hSocket, &fdsetSend); | |
1089 | continue; | |
b9ff2970 | 1090 | } |
f8dcd5ca | 1091 | } |
a9d9f0f5 PW |
1092 | { |
1093 | TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); | |
1094 | if (lockRecv && ( | |
1095 | pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || | |
1096 | pnode->GetTotalRecvSize() <= ReceiveFloodSize())) | |
1097 | FD_SET(pnode->hSocket, &fdsetRecv); | |
1098 | } | |
0a61b0df | 1099 | } |
1100 | } | |
1101 | ||
23879447 JG |
1102 | int nSelect = select(have_fds ? hSocketMax + 1 : 0, |
1103 | &fdsetRecv, &fdsetSend, &fdsetError, &timeout); | |
21eb5ada GA |
1104 | boost::this_thread::interruption_point(); |
1105 | ||
0a61b0df | 1106 | if (nSelect == SOCKET_ERROR) |
1107 | { | |
23879447 | 1108 | if (have_fds) |
c6710c7a | 1109 | { |
23879447 | 1110 | int nErr = WSAGetLastError(); |
a60838d0 | 1111 | LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); |
c376ac35 | 1112 | for (unsigned int i = 0; i <= hSocketMax; i++) |
c6710c7a MC |
1113 | FD_SET(i, &fdsetRecv); |
1114 | } | |
0a61b0df | 1115 | FD_ZERO(&fdsetSend); |
1116 | FD_ZERO(&fdsetError); | |
1b43bf0d | 1117 | MilliSleep(timeout.tv_usec/1000); |
0a61b0df | 1118 | } |
1119 | ||
0a61b0df | 1120 | // |
1121 | // Accept new connections | |
1122 | // | |
dc942e6f | 1123 | BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) |
0a61b0df | 1124 | { |
dc942e6f | 1125 | if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) |
f8dcd5ca | 1126 | { |
057d6078 | 1127 | AcceptConnection(hListenSocket); |
0a61b0df | 1128 | } |
1129 | } | |
1130 | ||
0a61b0df | 1131 | // |
1132 | // Service each socket | |
1133 | // | |
1134 | vector<CNode*> vNodesCopy; | |
0a61b0df | 1135 | { |
f8dcd5ca | 1136 | LOCK(cs_vNodes); |
0a61b0df | 1137 | vNodesCopy = vNodes; |
223b6f1b | 1138 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 1139 | pnode->AddRef(); |
1140 | } | |
223b6f1b | 1141 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 1142 | { |
21eb5ada | 1143 | boost::this_thread::interruption_point(); |
0a61b0df | 1144 | |
1145 | // | |
1146 | // Receive | |
1147 | // | |
1148 | if (pnode->hSocket == INVALID_SOCKET) | |
1149 | continue; | |
1150 | if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) | |
1151 | { | |
607dbfde | 1152 | TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); |
f8dcd5ca | 1153 | if (lockRecv) |
0a61b0df | 1154 | { |
a9d9f0f5 | 1155 | { |
9cbae55a GA |
1156 | // typical socket buffer is 8K-64K |
1157 | char pchBuf[0x10000]; | |
1158 | int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); | |
1159 | if (nBytes > 0) | |
0a61b0df | 1160 | { |
607dbfde JG |
1161 | if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) |
1162 | pnode->CloseSocketDisconnect(); | |
9cbae55a | 1163 | pnode->nLastRecv = GetTime(); |
86648a8d | 1164 | pnode->nRecvBytes += nBytes; |
ce14345a | 1165 | pnode->RecordBytesRecv(nBytes); |
9cbae55a GA |
1166 | } |
1167 | else if (nBytes == 0) | |
1168 | { | |
1169 | // socket closed gracefully | |
0a61b0df | 1170 | if (!pnode->fDisconnect) |
881a85a2 | 1171 | LogPrint("net", "socket closed\n"); |
0a61b0df | 1172 | pnode->CloseSocketDisconnect(); |
1173 | } | |
9cbae55a GA |
1174 | else if (nBytes < 0) |
1175 | { | |
1176 | // error | |
1177 | int nErr = WSAGetLastError(); | |
1178 | if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) | |
1179 | { | |
1180 | if (!pnode->fDisconnect) | |
a60838d0 | 1181 | LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); |
9cbae55a GA |
1182 | pnode->CloseSocketDisconnect(); |
1183 | } | |
1184 | } | |
0a61b0df | 1185 | } |
1186 | } | |
1187 | } | |
1188 | ||
1189 | // | |
1190 | // Send | |
1191 | // | |
1192 | if (pnode->hSocket == INVALID_SOCKET) | |
1193 | continue; | |
1194 | if (FD_ISSET(pnode->hSocket, &fdsetSend)) | |
1195 | { | |
f8dcd5ca PW |
1196 | TRY_LOCK(pnode->cs_vSend, lockSend); |
1197 | if (lockSend) | |
bc2f5aa7 | 1198 | SocketSendData(pnode); |
0a61b0df | 1199 | } |
1200 | ||
1201 | // | |
1202 | // Inactivity checking | |
1203 | // | |
f1920e86 PW |
1204 | int64_t nTime = GetTime(); |
1205 | if (nTime - pnode->nTimeConnected > 60) | |
0a61b0df | 1206 | { |
1207 | if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) | |
1208 | { | |
2e36866f | 1209 | LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); |
0a61b0df | 1210 | pnode->fDisconnect = true; |
1211 | } | |
f1920e86 | 1212 | else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) |
0a61b0df | 1213 | { |
f1920e86 | 1214 | LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); |
0a61b0df | 1215 | pnode->fDisconnect = true; |
1216 | } | |
f1920e86 | 1217 | else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) |
0a61b0df | 1218 | { |
f1920e86 PW |
1219 | LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); |
1220 | pnode->fDisconnect = true; | |
1221 | } | |
1222 | else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) | |
1223 | { | |
1224 | LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); | |
0a61b0df | 1225 | pnode->fDisconnect = true; |
1226 | } | |
1227 | } | |
1228 | } | |
0a61b0df | 1229 | { |
f8dcd5ca | 1230 | LOCK(cs_vNodes); |
223b6f1b | 1231 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 1232 | pnode->Release(); |
1233 | } | |
0a61b0df | 1234 | } |
1235 | } | |
1236 | ||
1237 | ||
21eb5ada | 1238 | void ThreadDNSAddressSeed() |
2bc6cece | 1239 | { |
2e7009d6 JG |
1240 | // goal: only query DNS seeds if address need is acute |
1241 | if ((addrman.size() > 0) && | |
1242 | (!GetBoolArg("-forcednsseed", false))) { | |
1243 | MilliSleep(11 * 1000); | |
1244 | ||
1245 | LOCK(cs_vNodes); | |
1246 | if (vNodes.size() >= 2) { | |
1247 | LogPrintf("P2P peers available. Skipped DNS seeding.\n"); | |
1248 | return; | |
1249 | } | |
1250 | } | |
1251 | ||
0e4b3175 | 1252 | const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds(); |
f684aec4 JG |
1253 | int found = 0; |
1254 | ||
881a85a2 | 1255 | LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); |
af899882 | 1256 | |
0e4b3175 | 1257 | BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) { |
af899882 | 1258 | if (HaveNameProxy()) { |
0e4b3175 | 1259 | AddOneShot(seed.host); |
af899882 | 1260 | } else { |
0e4b3175 | 1261 | vector<CNetAddr> vIPs; |
af899882 | 1262 | vector<CAddress> vAdd; |
0e4b3175 | 1263 | if (LookupHost(seed.host.c_str(), vIPs)) |
af899882 | 1264 | { |
db954a65 | 1265 | BOOST_FOREACH(const CNetAddr& ip, vIPs) |
a6a5bb7c | 1266 | { |
af899882 | 1267 | int nOneDay = 24*3600; |
0e4b3175 | 1268 | CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); |
af899882 PT |
1269 | addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old |
1270 | vAdd.push_back(addr); | |
1271 | found++; | |
a6a5bb7c | 1272 | } |
f684aec4 | 1273 | } |
0e4b3175 | 1274 | addrman.Add(vAdd, CNetAddr(seed.name, true)); |
f684aec4 JG |
1275 | } |
1276 | } | |
1277 | ||
881a85a2 | 1278 | LogPrintf("%d addresses found from DNS seeds\n", found); |
f684aec4 | 1279 | } |
0a61b0df | 1280 | |
1281 | ||
1282 | ||
2bc6cece MC |
1283 | |
1284 | ||
1285 | ||
1286 | ||
1287 | ||
1288 | ||
1289 | ||
1290 | ||
1291 | ||
5fee401f PW |
1292 | void DumpAddresses() |
1293 | { | |
51ed9ec9 | 1294 | int64_t nStart = GetTimeMillis(); |
928d3a01 | 1295 | |
5fee401f | 1296 | CAddrDB adb; |
928d3a01 JG |
1297 | adb.Write(addrman); |
1298 | ||
f48742c2 | 1299 | LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", |
928d3a01 | 1300 | addrman.size(), GetTimeMillis() - nStart); |
5fee401f | 1301 | } |
0a61b0df | 1302 | |
478b01d9 PW |
1303 | void static ProcessOneShot() |
1304 | { | |
1305 | string strDest; | |
1306 | { | |
1307 | LOCK(cs_vOneShots); | |
1308 | if (vOneShots.empty()) | |
1309 | return; | |
1310 | strDest = vOneShots.front(); | |
1311 | vOneShots.pop_front(); | |
1312 | } | |
1313 | CAddress addr; | |
c59abe25 PW |
1314 | CSemaphoreGrant grant(*semOutbound, true); |
1315 | if (grant) { | |
1316 | if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) | |
1317 | AddOneShot(strDest); | |
1318 | } | |
478b01d9 PW |
1319 | } |
1320 | ||
21eb5ada | 1321 | void ThreadOpenConnections() |
0a61b0df | 1322 | { |
0a61b0df | 1323 | // Connect to specific addresses |
f161a2c2 | 1324 | if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) |
0a61b0df | 1325 | { |
51ed9ec9 | 1326 | for (int64_t nLoop = 0;; nLoop++) |
0a61b0df | 1327 | { |
478b01d9 | 1328 | ProcessOneShot(); |
db954a65 | 1329 | BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-connect"]) |
0a61b0df | 1330 | { |
478b01d9 | 1331 | CAddress addr; |
c59abe25 | 1332 | OpenNetworkConnection(addr, NULL, strAddr.c_str()); |
0a61b0df | 1333 | for (int i = 0; i < 10 && i < nLoop; i++) |
1334 | { | |
1b43bf0d | 1335 | MilliSleep(500); |
0a61b0df | 1336 | } |
1337 | } | |
1b43bf0d | 1338 | MilliSleep(500); |
0a61b0df | 1339 | } |
1340 | } | |
1341 | ||
0a61b0df | 1342 | // Initiate network connections |
51ed9ec9 | 1343 | int64_t nStart = GetTime(); |
050d2e95 | 1344 | while (true) |
0a61b0df | 1345 | { |
478b01d9 PW |
1346 | ProcessOneShot(); |
1347 | ||
1b43bf0d | 1348 | MilliSleep(500); |
cc201e01 | 1349 | |
c59abe25 | 1350 | CSemaphoreGrant grant(*semOutbound); |
21eb5ada | 1351 | boost::this_thread::interruption_point(); |
0a61b0df | 1352 | |
0e4b3175 MH |
1353 | // Add seed nodes if DNS seeds are all down (an infrastructure attack?). |
1354 | if (addrman.size() == 0 && (GetTime() - nStart > 60)) { | |
1355 | static bool done = false; | |
1356 | if (!done) { | |
881a85a2 | 1357 | LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); |
739d6155 | 1358 | addrman.Add(convertSeed6(Params().FixedSeeds()), CNetAddr("127.0.0.1")); |
0e4b3175 | 1359 | done = true; |
0a61b0df | 1360 | } |
1361 | } | |
1362 | ||
0a61b0df | 1363 | // |
1364 | // Choose an address to connect to based on most recently seen | |
1365 | // | |
1366 | CAddress addrConnect; | |
0a61b0df | 1367 | |
19521acf | 1368 | // Only connect out to one peer per network group (/16 for IPv4). |
0a61b0df | 1369 | // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. |
c59abe25 | 1370 | int nOutbound = 0; |
67a42f92 | 1371 | set<vector<unsigned char> > setConnected; |
f8dcd5ca PW |
1372 | { |
1373 | LOCK(cs_vNodes); | |
c59abe25 | 1374 | BOOST_FOREACH(CNode* pnode, vNodes) { |
19521acf GM |
1375 | if (!pnode->fInbound) { |
1376 | setConnected.insert(pnode->addr.GetGroup()); | |
c59abe25 | 1377 | nOutbound++; |
19521acf | 1378 | } |
c59abe25 | 1379 | } |
f8dcd5ca | 1380 | } |
0a61b0df | 1381 | |
51ed9ec9 | 1382 | int64_t nANow = GetAdjustedTime(); |
a4e6ae10 | 1383 | |
5fee401f | 1384 | int nTries = 0; |
050d2e95 | 1385 | while (true) |
0a61b0df | 1386 | { |
1d5b47a9 | 1387 | CAddrInfo addr = addrman.Select(); |
0a61b0df | 1388 | |
5fee401f | 1389 | // if we selected an invalid address, restart |
23aa78c4 | 1390 | if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) |
5fee401f | 1391 | break; |
0a61b0df | 1392 | |
f161a2c2 PW |
1393 | // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, |
1394 | // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates | |
1395 | // already-connected network ranges, ...) before trying new addrman addresses. | |
5fee401f | 1396 | nTries++; |
f161a2c2 PW |
1397 | if (nTries > 100) |
1398 | break; | |
0a61b0df | 1399 | |
457754d2 PW |
1400 | if (IsLimited(addr)) |
1401 | continue; | |
1402 | ||
5fee401f PW |
1403 | // only consider very recently tried nodes after 30 failed attempts |
1404 | if (nANow - addr.nLastTry < 600 && nTries < 30) | |
1405 | continue; | |
1406 | ||
1407 | // do not allow non-default ports, unless after 50 invalid addresses selected already | |
0e4b3175 | 1408 | if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) |
5fee401f PW |
1409 | continue; |
1410 | ||
1411 | addrConnect = addr; | |
1412 | break; | |
0a61b0df | 1413 | } |
1414 | ||
1415 | if (addrConnect.IsValid()) | |
c59abe25 | 1416 | OpenNetworkConnection(addrConnect, &grant); |
0a61b0df | 1417 | } |
1418 | } | |
1419 | ||
21eb5ada | 1420 | void ThreadOpenAddedConnections() |
b24e6e4d | 1421 | { |
74088e86 MC |
1422 | { |
1423 | LOCK(cs_vAddedNodes); | |
1424 | vAddedNodes = mapMultiArgs["-addnode"]; | |
1425 | } | |
b24e6e4d | 1426 | |
81bbef26 | 1427 | if (HaveNameProxy()) { |
21eb5ada | 1428 | while(true) { |
74088e86 MC |
1429 | list<string> lAddresses(0); |
1430 | { | |
1431 | LOCK(cs_vAddedNodes); | |
db954a65 | 1432 | BOOST_FOREACH(const std::string& strAddNode, vAddedNodes) |
74088e86 MC |
1433 | lAddresses.push_back(strAddNode); |
1434 | } | |
db954a65 | 1435 | BOOST_FOREACH(const std::string& strAddNode, lAddresses) { |
9bab521d | 1436 | CAddress addr; |
c59abe25 PW |
1437 | CSemaphoreGrant grant(*semOutbound); |
1438 | OpenNetworkConnection(addr, &grant, strAddNode.c_str()); | |
1b43bf0d | 1439 | MilliSleep(500); |
9bab521d | 1440 | } |
1b43bf0d | 1441 | MilliSleep(120000); // Retry every 2 minutes |
9bab521d | 1442 | } |
9bab521d PW |
1443 | } |
1444 | ||
f2bd6c28 | 1445 | for (unsigned int i = 0; true; i++) |
b24e6e4d | 1446 | { |
74088e86 MC |
1447 | list<string> lAddresses(0); |
1448 | { | |
1449 | LOCK(cs_vAddedNodes); | |
db954a65 | 1450 | BOOST_FOREACH(const std::string& strAddNode, vAddedNodes) |
74088e86 MC |
1451 | lAddresses.push_back(strAddNode); |
1452 | } | |
1453 | ||
1454 | list<vector<CService> > lservAddressesToAdd(0); | |
db954a65 | 1455 | BOOST_FOREACH(const std::string& strAddNode, lAddresses) { |
74088e86 | 1456 | vector<CService> vservNode(0); |
0e4b3175 | 1457 | if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) |
f8dcd5ca | 1458 | { |
74088e86 MC |
1459 | lservAddressesToAdd.push_back(vservNode); |
1460 | { | |
1461 | LOCK(cs_setservAddNodeAddresses); | |
db954a65 | 1462 | BOOST_FOREACH(const CService& serv, vservNode) |
74088e86 MC |
1463 | setservAddNodeAddresses.insert(serv); |
1464 | } | |
f8dcd5ca | 1465 | } |
b24e6e4d | 1466 | } |
b24e6e4d | 1467 | // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry |
9bab521d | 1468 | // (keeping in mind that addnode entries can have many IPs if fNameLookup) |
f8dcd5ca PW |
1469 | { |
1470 | LOCK(cs_vNodes); | |
b24e6e4d | 1471 | BOOST_FOREACH(CNode* pnode, vNodes) |
74088e86 | 1472 | for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) |
db954a65 | 1473 | BOOST_FOREACH(const CService& addrNode, *(it)) |
b24e6e4d MC |
1474 | if (pnode->addr == addrNode) |
1475 | { | |
74088e86 | 1476 | it = lservAddressesToAdd.erase(it); |
b24e6e4d MC |
1477 | it--; |
1478 | break; | |
1479 | } | |
f8dcd5ca | 1480 | } |
74088e86 | 1481 | BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) |
b24e6e4d | 1482 | { |
c59abe25 | 1483 | CSemaphoreGrant grant(*semOutbound); |
f2bd6c28 | 1484 | OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); |
1b43bf0d | 1485 | MilliSleep(500); |
b24e6e4d | 1486 | } |
1b43bf0d | 1487 | MilliSleep(120000); // Retry every 2 minutes |
b24e6e4d MC |
1488 | } |
1489 | } | |
1490 | ||
814efd6f | 1491 | // if successful, this moves the passed grant to the constructed node |
5bd6c31b | 1492 | bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot) |
0a61b0df | 1493 | { |
1494 | // | |
1495 | // Initiate outbound network connection | |
1496 | // | |
21eb5ada | 1497 | boost::this_thread::interruption_point(); |
5bd6c31b | 1498 | if (!pszDest) { |
39857190 PW |
1499 | if (IsLocal(addrConnect) || |
1500 | FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || | |
f469f79f | 1501 | FindNode(addrConnect.ToStringIPPort())) |
9bab521d | 1502 | return false; |
49b22928 | 1503 | } else if (FindNode(std::string(pszDest))) |
0a61b0df | 1504 | return false; |
1505 | ||
5bd6c31b | 1506 | CNode* pnode = ConnectNode(addrConnect, pszDest); |
21eb5ada GA |
1507 | boost::this_thread::interruption_point(); |
1508 | ||
0a61b0df | 1509 | if (!pnode) |
1510 | return false; | |
c59abe25 PW |
1511 | if (grantOutbound) |
1512 | grantOutbound->MoveTo(pnode->grantOutbound); | |
0a61b0df | 1513 | pnode->fNetworkNode = true; |
478b01d9 PW |
1514 | if (fOneShot) |
1515 | pnode->fOneShot = true; | |
0a61b0df | 1516 | |
0a61b0df | 1517 | return true; |
1518 | } | |
1519 | ||
1520 | ||
21eb5ada | 1521 | void ThreadMessageHandler() |
0a61b0df | 1522 | { |
351593b9 | 1523 | boost::mutex condition_mutex; |
1524 | boost::unique_lock<boost::mutex> lock(condition_mutex); | |
49b22928 | 1525 | |
0a61b0df | 1526 | SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); |
21eb5ada | 1527 | while (true) |
0a61b0df | 1528 | { |
1529 | vector<CNode*> vNodesCopy; | |
0a61b0df | 1530 | { |
f8dcd5ca | 1531 | LOCK(cs_vNodes); |
0a61b0df | 1532 | vNodesCopy = vNodes; |
6ed71b5e | 1533 | BOOST_FOREACH(CNode* pnode, vNodesCopy) { |
0a61b0df | 1534 | pnode->AddRef(); |
6ed71b5e | 1535 | } |
0a61b0df | 1536 | } |
1537 | ||
1538 | // Poll the connected nodes for messages | |
1539 | CNode* pnodeTrickle = NULL; | |
1540 | if (!vNodesCopy.empty()) | |
1541 | pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; | |
fabba0e6 | 1542 | |
75ef87dd | 1543 | bool fSleep = true; |
fabba0e6 | 1544 | |
223b6f1b | 1545 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 1546 | { |
967f2459 PW |
1547 | if (pnode->fDisconnect) |
1548 | continue; | |
1549 | ||
0a61b0df | 1550 | // Receive messages |
f8dcd5ca | 1551 | { |
607dbfde | 1552 | TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); |
f8dcd5ca | 1553 | if (lockRecv) |
75ef87dd | 1554 | { |
501da250 | 1555 | if (!g_signals.ProcessMessages(pnode)) |
607dbfde | 1556 | pnode->CloseSocketDisconnect(); |
fabba0e6 | 1557 | |
75ef87dd PS |
1558 | if (pnode->nSendSize < SendBufferSize()) |
1559 | { | |
1560 | if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) | |
1561 | { | |
1562 | fSleep = false; | |
1563 | } | |
1564 | } | |
1565 | } | |
f8dcd5ca | 1566 | } |
21eb5ada | 1567 | boost::this_thread::interruption_point(); |
0a61b0df | 1568 | |
1569 | // Send messages | |
f8dcd5ca PW |
1570 | { |
1571 | TRY_LOCK(pnode->cs_vSend, lockSend); | |
501da250 | 1572 | if (lockSend) |
fc720207 | 1573 | g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted); |
f8dcd5ca | 1574 | } |
21eb5ada | 1575 | boost::this_thread::interruption_point(); |
0a61b0df | 1576 | } |
1577 | ||
0a61b0df | 1578 | { |
f8dcd5ca | 1579 | LOCK(cs_vNodes); |
223b6f1b | 1580 | BOOST_FOREACH(CNode* pnode, vNodesCopy) |
0a61b0df | 1581 | pnode->Release(); |
1582 | } | |
fabba0e6 | 1583 | |
75ef87dd | 1584 | if (fSleep) |
351593b9 | 1585 | messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); |
0a61b0df | 1586 | } |
1587 | } | |
1588 | ||
1589 | ||
1590 | ||
1591 | ||
1592 | ||
1593 | ||
dc942e6f | 1594 | bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted) |
0a61b0df | 1595 | { |
1596 | strError = ""; | |
1597 | int nOne = 1; | |
1598 | ||
0a61b0df | 1599 | // Create socket for listening for incoming connections |
8f10a288 | 1600 | struct sockaddr_storage sockaddr; |
8f10a288 PW |
1601 | socklen_t len = sizeof(sockaddr); |
1602 | if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) | |
1603 | { | |
5bd6c31b | 1604 | strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); |
7d9d134b | 1605 | LogPrintf("%s\n", strError); |
8f10a288 PW |
1606 | return false; |
1607 | } | |
1608 | ||
1609 | SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); | |
0a61b0df | 1610 | if (hListenSocket == INVALID_SOCKET) |
1611 | { | |
a60838d0 | 1612 | strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); |
7d9d134b | 1613 | LogPrintf("%s\n", strError); |
0a61b0df | 1614 | return false; |
1615 | } | |
0095b9a1 PW |
1616 | if (!IsSelectableSocket(hListenSocket)) |
1617 | { | |
1618 | strError = "Error: Couldn't create a listenable socket for incoming connections"; | |
1619 | LogPrintf("%s\n", strError); | |
1620 | return false; | |
1621 | } | |
1622 | ||
0a61b0df | 1623 | |
9cb1ec9c | 1624 | #ifndef _WIN32 |
ec93a0e2 | 1625 | #ifdef SO_NOSIGPIPE |
0a61b0df | 1626 | // Different way of disabling SIGPIPE on BSD |
1627 | setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); | |
1628 | #endif | |
0a61b0df | 1629 | // Allow binding if the port is still in TIME_WAIT state after |
ccc4ad6c | 1630 | // the program was closed and restarted. |
0a61b0df | 1631 | setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); |
95a50390 GM |
1632 | // Disable Nagle's algorithm |
1633 | setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int)); | |
ccc4ad6c CF |
1634 | #else |
1635 | setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int)); | |
95a50390 | 1636 | setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int)); |
0a61b0df | 1637 | #endif |
1638 | ||
814efd6f | 1639 | // Set to non-blocking, incoming connections will also inherit this |
eaedb59e PK |
1640 | if (!SetSocketNonBlocking(hListenSocket, true)) { |
1641 | strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); | |
7d9d134b | 1642 | LogPrintf("%s\n", strError); |
0a61b0df | 1643 | return false; |
1644 | } | |
1645 | ||
8f10a288 PW |
1646 | // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option |
1647 | // and enable it by default or not. Try to enable it, if possible. | |
1648 | if (addrBind.IsIPv6()) { | |
1649 | #ifdef IPV6_V6ONLY | |
9cb1ec9c | 1650 | #ifdef _WIN32 |
b3e0aaf3 PK |
1651 | setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); |
1652 | #else | |
8f10a288 | 1653 | setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); |
23aa78c4 | 1654 | #endif |
b3e0aaf3 | 1655 | #endif |
9cb1ec9c | 1656 | #ifdef _WIN32 |
9e9ca2b6 PK |
1657 | int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; |
1658 | setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); | |
8f10a288 PW |
1659 | #endif |
1660 | } | |
8f10a288 PW |
1661 | |
1662 | if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) | |
0a61b0df | 1663 | { |
1664 | int nErr = WSAGetLastError(); | |
1665 | if (nErr == WSAEADDRINUSE) | |
b30900a5 | 1666 | strError = strprintf(_("Unable to bind to %s on this computer. Zcash is probably already running."), addrBind.ToString()); |
0a61b0df | 1667 | else |
a60838d0 | 1668 | strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); |
7d9d134b | 1669 | LogPrintf("%s\n", strError); |
c994d2e7 | 1670 | CloseSocket(hListenSocket); |
0a61b0df | 1671 | return false; |
1672 | } | |
7d9d134b | 1673 | LogPrintf("Bound to %s\n", addrBind.ToString()); |
0a61b0df | 1674 | |
1675 | // Listen for incoming connections | |
1676 | if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) | |
1677 | { | |
a60838d0 | 1678 | strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); |
7d9d134b | 1679 | LogPrintf("%s\n", strError); |
c994d2e7 | 1680 | CloseSocket(hListenSocket); |
0a61b0df | 1681 | return false; |
1682 | } | |
1683 | ||
dc942e6f | 1684 | vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); |
8f10a288 | 1685 | |
dc942e6f | 1686 | if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) |
8f10a288 PW |
1687 | AddLocal(addrBind, LOCAL_BIND); |
1688 | ||
0a61b0df | 1689 | return true; |
1690 | } | |
1691 | ||
80ecf670 | 1692 | void static Discover(boost::thread_group& threadGroup) |
0a61b0df | 1693 | { |
587f929c | 1694 | if (!fDiscover) |
19b6958c | 1695 | return; |
0a61b0df | 1696 | |
9cb1ec9c | 1697 | #ifdef _WIN32 |
814efd6f | 1698 | // Get local host IP |
cd4d3f19 | 1699 | char pszHostName[256] = ""; |
0a61b0df | 1700 | if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) |
1701 | { | |
67a42f92 PW |
1702 | vector<CNetAddr> vaddr; |
1703 | if (LookupHost(pszHostName, vaddr)) | |
f8e4d43b | 1704 | { |
67a42f92 | 1705 | BOOST_FOREACH (const CNetAddr &addr, vaddr) |
f8e4d43b | 1706 | { |
8fa0494e PK |
1707 | if (AddLocal(addr, LOCAL_IF)) |
1708 | LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); | |
f8e4d43b PK |
1709 | } |
1710 | } | |
0a61b0df | 1711 | } |
1712 | #else | |
1713 | // Get local host ip | |
1714 | struct ifaddrs* myaddrs; | |
1715 | if (getifaddrs(&myaddrs) == 0) | |
1716 | { | |
1717 | for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) | |
1718 | { | |
1719 | if (ifa->ifa_addr == NULL) continue; | |
1720 | if ((ifa->ifa_flags & IFF_UP) == 0) continue; | |
1721 | if (strcmp(ifa->ifa_name, "lo") == 0) continue; | |
1722 | if (strcmp(ifa->ifa_name, "lo0") == 0) continue; | |
0a61b0df | 1723 | if (ifa->ifa_addr->sa_family == AF_INET) |
1724 | { | |
1725 | struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); | |
39857190 | 1726 | CNetAddr addr(s4->sin_addr); |
23aa78c4 | 1727 | if (AddLocal(addr, LOCAL_IF)) |
8fa0494e | 1728 | LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); |
0a61b0df | 1729 | } |
1730 | else if (ifa->ifa_addr->sa_family == AF_INET6) | |
1731 | { | |
1732 | struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); | |
39857190 | 1733 | CNetAddr addr(s6->sin6_addr); |
23aa78c4 | 1734 | if (AddLocal(addr, LOCAL_IF)) |
8fa0494e | 1735 | LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); |
0a61b0df | 1736 | } |
1737 | } | |
1738 | freeifaddrs(myaddrs); | |
1739 | } | |
1740 | #endif | |
19b6958c PW |
1741 | } |
1742 | ||
9a1dcea2 | 1743 | void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler) |
19b6958c | 1744 | { |
94064710 WL |
1745 | uiInterface.InitMessage(_("Loading addresses...")); |
1746 | // Load addresses for peers.dat | |
1747 | int64_t nStart = GetTimeMillis(); | |
1748 | { | |
1749 | CAddrDB adb; | |
1750 | if (!adb.Read(addrman)) | |
1751 | LogPrintf("Invalid or missing peers.dat; recreating\n"); | |
1752 | } | |
1753 | LogPrintf("Loaded %i addresses from peers.dat %dms\n", | |
1754 | addrman.size(), GetTimeMillis() - nStart); | |
1755 | fAddressesInitialized = true; | |
1756 | ||
c59abe25 PW |
1757 | if (semOutbound == NULL) { |
1758 | // initialize semaphore | |
ba29a559 | 1759 | int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); |
c59abe25 PW |
1760 | semOutbound = new CSemaphore(nMaxOutbound); |
1761 | } | |
1762 | ||
19b6958c PW |
1763 | if (pnodeLocalHost == NULL) |
1764 | pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); | |
1765 | ||
80ecf670 | 1766 | Discover(threadGroup); |
0a61b0df | 1767 | |
1768 | // | |
1769 | // Start threads | |
1770 | // | |
1771 | ||
9d952d17 | 1772 | if (!GetBoolArg("-dnsseed", true)) |
881a85a2 | 1773 | LogPrintf("DNS seeding disabled\n"); |
2bc6cece | 1774 | else |
53e71135 | 1775 | threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); |
2bc6cece | 1776 | |
0a61b0df | 1777 | // Send and receive from sockets, accept connections |
b31499ec | 1778 | threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); |
0a61b0df | 1779 | |
b24e6e4d | 1780 | // Initiate outbound connections from -addnode |
b31499ec | 1781 | threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); |
b24e6e4d | 1782 | |
0a61b0df | 1783 | // Initiate outbound connections |
b31499ec | 1784 | threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); |
0a61b0df | 1785 | |
1786 | // Process messages | |
b31499ec | 1787 | threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); |
0a61b0df | 1788 | |
5fee401f | 1789 | // Dump network addresses |
9a1dcea2 | 1790 | scheduler.scheduleEvery(&DumpAddresses, DUMP_ADDRESSES_INTERVAL); |
0a61b0df | 1791 | } |
1792 | ||
1793 | bool StopNode() | |
1794 | { | |
881a85a2 | 1795 | LogPrintf("StopNode()\n"); |
89b5616d PW |
1796 | if (semOutbound) |
1797 | for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) | |
1798 | semOutbound->post(); | |
94064710 WL |
1799 | |
1800 | if (fAddressesInitialized) | |
1801 | { | |
1802 | DumpAddresses(); | |
1803 | fAddressesInitialized = false; | |
1804 | } | |
3427517d | 1805 | |
0a61b0df | 1806 | return true; |
1807 | } | |
1808 | ||
1809 | class CNetCleanup | |
1810 | { | |
1811 | public: | |
5bd6c31b PK |
1812 | CNetCleanup() {} |
1813 | ||
0a61b0df | 1814 | ~CNetCleanup() |
1815 | { | |
1816 | // Close sockets | |
223b6f1b | 1817 | BOOST_FOREACH(CNode* pnode, vNodes) |
0a61b0df | 1818 | if (pnode->hSocket != INVALID_SOCKET) |
43f510d3 | 1819 | CloseSocket(pnode->hSocket); |
dc942e6f PW |
1820 | BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket) |
1821 | if (hListenSocket.socket != INVALID_SOCKET) | |
43f510d3 WL |
1822 | if (!CloseSocket(hListenSocket.socket)) |
1823 | LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); | |
0a61b0df | 1824 | |
3427517d PW |
1825 | // clean up some globals (to help leak detection) |
1826 | BOOST_FOREACH(CNode *pnode, vNodes) | |
1827 | delete pnode; | |
1828 | BOOST_FOREACH(CNode *pnode, vNodesDisconnected) | |
1829 | delete pnode; | |
1830 | vNodes.clear(); | |
1831 | vNodesDisconnected.clear(); | |
3dc1464f | 1832 | vhListenSocket.clear(); |
3427517d PW |
1833 | delete semOutbound; |
1834 | semOutbound = NULL; | |
1835 | delete pnodeLocalHost; | |
1836 | pnodeLocalHost = NULL; | |
1837 | ||
9cb1ec9c | 1838 | #ifdef _WIN32 |
0a61b0df | 1839 | // Shutdown Windows Sockets |
1840 | WSACleanup(); | |
1841 | #endif | |
1842 | } | |
1843 | } | |
1844 | instance_of_cnetcleanup; | |
269d9c64 MC |
1845 | |
1846 | ||
1847 | ||
1848 | ||
1849 | ||
1850 | ||
1851 | ||
d38da59b | 1852 | void RelayTransaction(const CTransaction& tx) |
269d9c64 MC |
1853 | { |
1854 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
1855 | ss.reserve(10000); | |
1856 | ss << tx; | |
d38da59b | 1857 | RelayTransaction(tx, ss); |
269d9c64 MC |
1858 | } |
1859 | ||
d38da59b | 1860 | void RelayTransaction(const CTransaction& tx, const CDataStream& ss) |
269d9c64 | 1861 | { |
805344dc | 1862 | CInv inv(MSG_TX, tx.GetHash()); |
269d9c64 MC |
1863 | { |
1864 | LOCK(cs_mapRelay); | |
1865 | // Expire old relay messages | |
1866 | while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) | |
1867 | { | |
1868 | mapRelay.erase(vRelayExpiration.front().second); | |
1869 | vRelayExpiration.pop_front(); | |
1870 | } | |
1871 | ||
1872 | // Save original serialized message so newer versions are preserved | |
1873 | mapRelay.insert(std::make_pair(inv, ss)); | |
1874 | vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); | |
1875 | } | |
1876 | LOCK(cs_vNodes); | |
1877 | BOOST_FOREACH(CNode* pnode, vNodes) | |
1878 | { | |
4c8fc1a5 MC |
1879 | if(!pnode->fRelayTxes) |
1880 | continue; | |
269d9c64 MC |
1881 | LOCK(pnode->cs_filter); |
1882 | if (pnode->pfilter) | |
1883 | { | |
d38da59b | 1884 | if (pnode->pfilter->IsRelevantAndUpdate(tx)) |
269d9c64 MC |
1885 | pnode->PushInventory(inv); |
1886 | } else | |
1887 | pnode->PushInventory(inv); | |
1888 | } | |
1889 | } | |
ce14345a | 1890 | |
51ed9ec9 | 1891 | void CNode::RecordBytesRecv(uint64_t bytes) |
ce14345a SE |
1892 | { |
1893 | LOCK(cs_totalBytesRecv); | |
1894 | nTotalBytesRecv += bytes; | |
1895 | } | |
1896 | ||
51ed9ec9 | 1897 | void CNode::RecordBytesSent(uint64_t bytes) |
ce14345a SE |
1898 | { |
1899 | LOCK(cs_totalBytesSent); | |
1900 | nTotalBytesSent += bytes; | |
1901 | } | |
1902 | ||
51ed9ec9 | 1903 | uint64_t CNode::GetTotalBytesRecv() |
ce14345a SE |
1904 | { |
1905 | LOCK(cs_totalBytesRecv); | |
1906 | return nTotalBytesRecv; | |
1907 | } | |
1908 | ||
51ed9ec9 | 1909 | uint64_t CNode::GetTotalBytesSent() |
ce14345a SE |
1910 | { |
1911 | LOCK(cs_totalBytesSent); | |
1912 | return nTotalBytesSent; | |
1913 | } | |
9038b18f GA |
1914 | |
1915 | void CNode::Fuzz(int nChance) | |
1916 | { | |
1917 | if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake | |
1918 | if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages | |
1919 | ||
1920 | switch (GetRand(3)) | |
1921 | { | |
1922 | case 0: | |
1923 | // xor a random byte with a random value: | |
1924 | if (!ssSend.empty()) { | |
1925 | CDataStream::size_type pos = GetRand(ssSend.size()); | |
1926 | ssSend[pos] ^= (unsigned char)(GetRand(256)); | |
1927 | } | |
1928 | break; | |
1929 | case 1: | |
1930 | // delete a random byte: | |
1931 | if (!ssSend.empty()) { | |
1932 | CDataStream::size_type pos = GetRand(ssSend.size()); | |
1933 | ssSend.erase(ssSend.begin()+pos); | |
1934 | } | |
1935 | break; | |
1936 | case 2: | |
1937 | // insert a random byte at a random position | |
1938 | { | |
1939 | CDataStream::size_type pos = GetRand(ssSend.size()); | |
1940 | char ch = (char)GetRand(256); | |
1941 | ssSend.insert(ssSend.begin()+pos, ch); | |
1942 | } | |
1943 | break; | |
1944 | } | |
1945 | // Chance of more than one change half the time: | |
1946 | // (more changes exponentially less likely): | |
1947 | Fuzz(2); | |
1948 | } | |
d004d727 WL |
1949 | |
1950 | // | |
1951 | // CAddrDB | |
1952 | // | |
1953 | ||
1954 | CAddrDB::CAddrDB() | |
1955 | { | |
1956 | pathAddr = GetDataDir() / "peers.dat"; | |
1957 | } | |
1958 | ||
1959 | bool CAddrDB::Write(const CAddrMan& addr) | |
1960 | { | |
1961 | // Generate random temporary filename | |
1962 | unsigned short randv = 0; | |
001a53d7 | 1963 | GetRandBytes((unsigned char*)&randv, sizeof(randv)); |
d004d727 WL |
1964 | std::string tmpfn = strprintf("peers.dat.%04x", randv); |
1965 | ||
1966 | // serialize addresses, checksum data up to that point, then append csum | |
1967 | CDataStream ssPeers(SER_DISK, CLIENT_VERSION); | |
1968 | ssPeers << FLATDATA(Params().MessageStart()); | |
1969 | ssPeers << addr; | |
1970 | uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); | |
1971 | ssPeers << hash; | |
1972 | ||
1973 | // open temp output file, and associate with CAutoFile | |
1974 | boost::filesystem::path pathTmp = GetDataDir() / tmpfn; | |
1975 | FILE *file = fopen(pathTmp.string().c_str(), "wb"); | |
eee030f6 | 1976 | CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); |
fef24cab | 1977 | if (fileout.IsNull()) |
5262fde0 | 1978 | return error("%s: Failed to open file %s", __func__, pathTmp.string()); |
d004d727 WL |
1979 | |
1980 | // Write and commit header, data | |
1981 | try { | |
1982 | fileout << ssPeers; | |
1983 | } | |
27df4123 | 1984 | catch (const std::exception& e) { |
5262fde0 | 1985 | return error("%s: Serialize or I/O error - %s", __func__, e.what()); |
d004d727 | 1986 | } |
a8738238 | 1987 | FileCommit(fileout.Get()); |
d004d727 WL |
1988 | fileout.fclose(); |
1989 | ||
1990 | // replace existing peers.dat, if any, with new peers.dat.XXXX | |
1991 | if (!RenameOver(pathTmp, pathAddr)) | |
5262fde0 | 1992 | return error("%s: Rename-into-place failed", __func__); |
d004d727 WL |
1993 | |
1994 | return true; | |
1995 | } | |
1996 | ||
1997 | bool CAddrDB::Read(CAddrMan& addr) | |
1998 | { | |
1999 | // open input file, and associate with CAutoFile | |
2000 | FILE *file = fopen(pathAddr.string().c_str(), "rb"); | |
eee030f6 | 2001 | CAutoFile filein(file, SER_DISK, CLIENT_VERSION); |
fef24cab | 2002 | if (filein.IsNull()) |
5262fde0 | 2003 | return error("%s: Failed to open file %s", __func__, pathAddr.string()); |
d004d727 WL |
2004 | |
2005 | // use file size to size memory buffer | |
a486abd4 | 2006 | int fileSize = boost::filesystem::file_size(pathAddr); |
d004d727 | 2007 | int dataSize = fileSize - sizeof(uint256); |
a486abd4 | 2008 | // Don't try to resize to a negative number if file is small |
2fdd4c79 PK |
2009 | if (dataSize < 0) |
2010 | dataSize = 0; | |
d004d727 WL |
2011 | vector<unsigned char> vchData; |
2012 | vchData.resize(dataSize); | |
2013 | uint256 hashIn; | |
2014 | ||
2015 | // read data and checksum from file | |
2016 | try { | |
2017 | filein.read((char *)&vchData[0], dataSize); | |
2018 | filein >> hashIn; | |
2019 | } | |
27df4123 | 2020 | catch (const std::exception& e) { |
5262fde0 | 2021 | return error("%s: Deserialize or I/O error - %s", __func__, e.what()); |
d004d727 WL |
2022 | } |
2023 | filein.fclose(); | |
2024 | ||
2025 | CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); | |
2026 | ||
2027 | // verify stored checksum matches input data | |
2028 | uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); | |
2029 | if (hashIn != hashTmp) | |
5262fde0 | 2030 | return error("%s: Checksum mismatch, data corrupted", __func__); |
d004d727 WL |
2031 | |
2032 | unsigned char pchMsgTmp[4]; | |
2033 | try { | |
2034 | // de-serialize file header (network specific magic number) and .. | |
2035 | ssPeers >> FLATDATA(pchMsgTmp); | |
2036 | ||
2037 | // ... verify the network matches ours | |
2038 | if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) | |
5262fde0 | 2039 | return error("%s: Invalid network magic number", __func__); |
d004d727 WL |
2040 | |
2041 | // de-serialize address data into one CAddrMan object | |
2042 | ssPeers >> addr; | |
2043 | } | |
27df4123 | 2044 | catch (const std::exception& e) { |
5262fde0 | 2045 | return error("%s: Deserialize or I/O error - %s", __func__, e.what()); |
d004d727 WL |
2046 | } |
2047 | ||
2048 | return true; | |
2049 | } | |
651480c8 WL |
2050 | |
2051 | unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); } | |
2052 | unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); } | |
2053 | ||
db954a65 | 2054 | CNode::CNode(SOCKET hSocketIn, const CAddress& addrIn, const std::string& addrNameIn, bool fInboundIn) : |
d4d5022c | 2055 | ssSend(SER_NETWORK, INIT_PROTO_VERSION), |
83671efe | 2056 | addrKnown(5000, 0.001), |
d4d5022c | 2057 | setInventoryKnown(SendBufferSize() / 1000) |
651480c8 WL |
2058 | { |
2059 | nServices = 0; | |
2060 | hSocket = hSocketIn; | |
2061 | nRecvVersion = INIT_PROTO_VERSION; | |
2062 | nLastSend = 0; | |
2063 | nLastRecv = 0; | |
2064 | nSendBytes = 0; | |
2065 | nRecvBytes = 0; | |
2066 | nTimeConnected = GetTime(); | |
26a6bae7 | 2067 | nTimeOffset = 0; |
651480c8 WL |
2068 | addr = addrIn; |
2069 | addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; | |
2070 | nVersion = 0; | |
2071 | strSubVer = ""; | |
2072 | fWhitelisted = false; | |
2073 | fOneShot = false; | |
2074 | fClient = false; // set by version message | |
2075 | fInbound = fInboundIn; | |
2076 | fNetworkNode = false; | |
2077 | fSuccessfullyConnected = false; | |
2078 | fDisconnect = false; | |
2079 | nRefCount = 0; | |
2080 | nSendSize = 0; | |
2081 | nSendOffset = 0; | |
4f152496 | 2082 | hashContinue = uint256(); |
651480c8 | 2083 | nStartingHeight = -1; |
651480c8 WL |
2084 | fGetAddr = false; |
2085 | fRelayTxes = false; | |
a514cb29 | 2086 | fSentAddr = false; |
651480c8 WL |
2087 | pfilter = new CBloomFilter(); |
2088 | nPingNonceSent = 0; | |
2089 | nPingUsecStart = 0; | |
2090 | nPingUsecTime = 0; | |
2091 | fPingQueued = false; | |
9dcea38a | 2092 | nMinPingUsecTime = std::numeric_limits<int64_t>::max(); |
651480c8 WL |
2093 | |
2094 | { | |
2095 | LOCK(cs_nLastNodeId); | |
2096 | id = nLastNodeId++; | |
2097 | } | |
2098 | ||
2099 | if (fLogIPs) | |
2100 | LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); | |
2101 | else | |
2102 | LogPrint("net", "Added connection peer=%d\n", id); | |
2103 | ||
2104 | // Be shy and don't send version until we hear | |
2105 | if (hSocket != INVALID_SOCKET && !fInbound) | |
2106 | PushVersion(); | |
2107 | ||
2108 | GetNodeSignals().InitializeNode(GetId(), this); | |
2109 | } | |
2110 | ||
2111 | CNode::~CNode() | |
2112 | { | |
2113 | CloseSocket(hSocket); | |
2114 | ||
2115 | if (pfilter) | |
2116 | delete pfilter; | |
2117 | ||
2118 | GetNodeSignals().FinalizeNode(GetId()); | |
2119 | } | |
2120 | ||
2121 | void CNode::AskFor(const CInv& inv) | |
2122 | { | |
e2190f80 | 2123 | if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ) |
d4168c82 | 2124 | return; |
e2190f80 | 2125 | // a peer may not have multiple non-responded queue positions for a single inv item |
56f165bd | 2126 | if (!setAskFor.insert(inv.hash).second) |
2127 | return; | |
2128 | ||
651480c8 WL |
2129 | // We're using mapAskFor as a priority queue, |
2130 | // the key is the earliest time the request can be sent | |
2131 | int64_t nRequestTime; | |
2132 | limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); | |
2133 | if (it != mapAlreadyAskedFor.end()) | |
2134 | nRequestTime = it->second; | |
2135 | else | |
2136 | nRequestTime = 0; | |
2c2cc5da | 2137 | LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id); |
651480c8 WL |
2138 | |
2139 | // Make sure not to reuse time indexes to keep things in the same order | |
2140 | int64_t nNow = GetTimeMicros() - 1000000; | |
2141 | static int64_t nLastTime; | |
2142 | ++nLastTime; | |
2143 | nNow = std::max(nNow, nLastTime); | |
2144 | nLastTime = nNow; | |
2145 | ||
2146 | // Each retry is 2 minutes after the last | |
2147 | nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); | |
2148 | if (it != mapAlreadyAskedFor.end()) | |
2149 | mapAlreadyAskedFor.update(it, nRequestTime); | |
2150 | else | |
2151 | mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); | |
2152 | mapAskFor.insert(std::make_pair(nRequestTime, inv)); | |
2153 | } | |
2154 | ||
2155 | void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) | |
2156 | { | |
2157 | ENTER_CRITICAL_SECTION(cs_vSend); | |
2158 | assert(ssSend.size() == 0); | |
eec37136 | 2159 | ssSend << CMessageHeader(Params().MessageStart(), pszCommand, 0); |
28d4cff0 | 2160 | LogPrint("net", "sending: %s ", SanitizeString(pszCommand)); |
651480c8 WL |
2161 | } |
2162 | ||
2163 | void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) | |
2164 | { | |
2165 | ssSend.clear(); | |
2166 | ||
2167 | LEAVE_CRITICAL_SECTION(cs_vSend); | |
2168 | ||
2169 | LogPrint("net", "(aborted)\n"); | |
2170 | } | |
2171 | ||
2172 | void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) | |
2173 | { | |
2174 | // The -*messagestest options are intentionally not documented in the help message, | |
2175 | // since they are only used during development to debug the networking code and are | |
2176 | // not intended for end-users. | |
2177 | if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) | |
2178 | { | |
2179 | LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); | |
2180 | AbortMessage(); | |
2181 | return; | |
2182 | } | |
2183 | if (mapArgs.count("-fuzzmessagestest")) | |
2184 | Fuzz(GetArg("-fuzzmessagestest", 10)); | |
2185 | ||
2186 | if (ssSend.size() == 0) | |
60457d3c CF |
2187 | { |
2188 | LEAVE_CRITICAL_SECTION(cs_vSend); | |
651480c8 | 2189 | return; |
60457d3c | 2190 | } |
651480c8 WL |
2191 | // Set the size |
2192 | unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; | |
dec84cae | 2193 | WriteLE32((uint8_t*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], nSize); |
651480c8 WL |
2194 | |
2195 | // Set the checksum | |
2196 | uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); | |
2197 | unsigned int nChecksum = 0; | |
2198 | memcpy(&nChecksum, &hash, sizeof(nChecksum)); | |
2199 | assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); | |
2200 | memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); | |
2201 | ||
2202 | LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); | |
2203 | ||
2204 | std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); | |
2205 | ssSend.GetAndClear(*it); | |
2206 | nSendSize += (*it).size(); | |
2207 | ||
2208 | // If write queue empty, attempt "optimistic write" | |
2209 | if (it == vSendMsg.begin()) | |
2210 | SocketSendData(this); | |
2211 | ||
2212 | LEAVE_CRITICAL_SECTION(cs_vSend); | |
2213 | } |