選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

net.cpp 66KB

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