net.cpp 69 KB

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