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