You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.cpp 62KB

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