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

net.cpp 88KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 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 "consensus/consensus.h"
  13. #include "crypto/common.h"
  14. #include "crypto/sha256.h"
  15. #include "hash.h"
  16. #include "primitives/transaction.h"
  17. #include "netbase.h"
  18. #include "scheduler.h"
  19. #include "ui_interface.h"
  20. #include "utilstrencodings.h"
  21. #ifdef WIN32
  22. #include <string.h>
  23. #else
  24. #include <fcntl.h>
  25. #endif
  26. #ifdef USE_UPNP
  27. #include <miniupnpc/miniupnpc.h>
  28. #include <miniupnpc/miniwget.h>
  29. #include <miniupnpc/upnpcommands.h>
  30. #include <miniupnpc/upnperrors.h>
  31. #endif
  32. #include <math.h>
  33. // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
  34. #define DUMP_ADDRESSES_INTERVAL 900
  35. // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
  36. #define FEELER_SLEEP_WINDOW 1
  37. #if !defined(HAVE_MSG_NOSIGNAL)
  38. #define MSG_NOSIGNAL 0
  39. #endif
  40. // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
  41. #if !defined(HAVE_MSG_DONTWAIT)
  42. #define MSG_DONTWAIT 0
  43. #endif
  44. // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
  45. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
  46. #ifdef WIN32
  47. #ifndef PROTECTION_LEVEL_UNRESTRICTED
  48. #define PROTECTION_LEVEL_UNRESTRICTED 10
  49. #endif
  50. #ifndef IPV6_PROTECTION_LEVEL
  51. #define IPV6_PROTECTION_LEVEL 23
  52. #endif
  53. #endif
  54. const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
  55. static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
  56. static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
  57. //
  58. // Global state variables
  59. //
  60. bool fDiscover = true;
  61. bool fListen = true;
  62. bool fRelayTxes = true;
  63. CCriticalSection cs_mapLocalHost;
  64. std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
  65. static bool vfLimited[NET_MAX] = {};
  66. std::string strSubVersion;
  67. limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
  68. // Signals for message handling
  69. static CNodeSignals g_signals;
  70. CNodeSignals& GetNodeSignals() { return g_signals; }
  71. void CConnman::AddOneShot(const std::string& strDest)
  72. {
  73. LOCK(cs_vOneShots);
  74. vOneShots.push_back(strDest);
  75. }
  76. unsigned short GetListenPort()
  77. {
  78. return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
  79. }
  80. // find 'best' local address for a particular peer
  81. bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
  82. {
  83. if (!fListen)
  84. return false;
  85. int nBestScore = -1;
  86. int nBestReachability = -1;
  87. {
  88. LOCK(cs_mapLocalHost);
  89. for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
  90. {
  91. int nScore = (*it).second.nScore;
  92. int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
  93. if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
  94. {
  95. addr = CService((*it).first, (*it).second.nPort);
  96. nBestReachability = nReachability;
  97. nBestScore = nScore;
  98. }
  99. }
  100. }
  101. return nBestScore >= 0;
  102. }
  103. //! Convert the pnSeeds6 array into usable address objects.
  104. static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
  105. {
  106. // It'll only connect to one or two seed nodes because once it connects,
  107. // it'll get a pile of addresses with newer timestamps.
  108. // Seed nodes are given a random 'last seen time' of between one and two
  109. // weeks ago.
  110. const int64_t nOneWeek = 7*24*60*60;
  111. std::vector<CAddress> vSeedsOut;
  112. vSeedsOut.reserve(vSeedsIn.size());
  113. for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
  114. {
  115. struct in6_addr ip;
  116. memcpy(&ip, i->addr, sizeof(ip));
  117. CAddress addr(CService(ip, i->port), NODE_NETWORK);
  118. addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
  119. vSeedsOut.push_back(addr);
  120. }
  121. return vSeedsOut;
  122. }
  123. // get best local address for a particular peer as a CAddress
  124. // Otherwise, return the unroutable 0.0.0.0 but filled in with
  125. // the normal parameters, since the IP may be changed to a useful
  126. // one by discovery.
  127. CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
  128. {
  129. CAddress ret(CService(CNetAddr(),GetListenPort()), NODE_NONE);
  130. CService addr;
  131. if (GetLocal(addr, paddrPeer))
  132. {
  133. ret = CAddress(addr, nLocalServices);
  134. }
  135. ret.nTime = GetAdjustedTime();
  136. return ret;
  137. }
  138. int GetnScore(const CService& addr)
  139. {
  140. LOCK(cs_mapLocalHost);
  141. if (mapLocalHost.count(addr) == LOCAL_NONE)
  142. return 0;
  143. return mapLocalHost[addr].nScore;
  144. }
  145. // Is our peer's addrLocal potentially useful as an external IP source?
  146. bool IsPeerAddrLocalGood(CNode *pnode)
  147. {
  148. CService addrLocal = pnode->GetAddrLocal();
  149. return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
  150. !IsLimited(addrLocal.GetNetwork());
  151. }
  152. // pushes our own address to a peer
  153. void AdvertiseLocal(CNode *pnode)
  154. {
  155. if (fListen && pnode->fSuccessfullyConnected)
  156. {
  157. CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
  158. // If discovery is enabled, sometimes give our peer the address it
  159. // tells us that it sees us as in case it has a better idea of our
  160. // address than we do.
  161. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
  162. GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
  163. {
  164. addrLocal.SetIP(pnode->GetAddrLocal());
  165. }
  166. if (addrLocal.IsRoutable())
  167. {
  168. LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
  169. FastRandomContext insecure_rand;
  170. pnode->PushAddress(addrLocal, insecure_rand);
  171. }
  172. }
  173. }
  174. // learn a new local address
  175. bool AddLocal(const CService& addr, int nScore)
  176. {
  177. if (!addr.IsRoutable())
  178. return false;
  179. if (!fDiscover && nScore < LOCAL_MANUAL)
  180. return false;
  181. if (IsLimited(addr))
  182. return false;
  183. LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
  184. {
  185. LOCK(cs_mapLocalHost);
  186. bool fAlready = mapLocalHost.count(addr) > 0;
  187. LocalServiceInfo &info = mapLocalHost[addr];
  188. if (!fAlready || nScore >= info.nScore) {
  189. info.nScore = nScore + (fAlready ? 1 : 0);
  190. info.nPort = addr.GetPort();
  191. }
  192. }
  193. return true;
  194. }
  195. bool AddLocal(const CNetAddr &addr, int nScore)
  196. {
  197. return AddLocal(CService(addr, GetListenPort()), nScore);
  198. }
  199. bool RemoveLocal(const CService& addr)
  200. {
  201. LOCK(cs_mapLocalHost);
  202. LogPrintf("RemoveLocal(%s)\n", addr.ToString());
  203. mapLocalHost.erase(addr);
  204. return true;
  205. }
  206. /** Make a particular network entirely off-limits (no automatic connects to it) */
  207. void SetLimited(enum Network net, bool fLimited)
  208. {
  209. if (net == NET_UNROUTABLE)
  210. return;
  211. LOCK(cs_mapLocalHost);
  212. vfLimited[net] = fLimited;
  213. }
  214. bool IsLimited(enum Network net)
  215. {
  216. LOCK(cs_mapLocalHost);
  217. return vfLimited[net];
  218. }
  219. bool IsLimited(const CNetAddr &addr)
  220. {
  221. return IsLimited(addr.GetNetwork());
  222. }
  223. /** vote for a local address */
  224. bool SeenLocal(const CService& addr)
  225. {
  226. {
  227. LOCK(cs_mapLocalHost);
  228. if (mapLocalHost.count(addr) == 0)
  229. return false;
  230. mapLocalHost[addr].nScore++;
  231. }
  232. return true;
  233. }
  234. /** check whether a given address is potentially local */
  235. bool IsLocal(const CService& addr)
  236. {
  237. LOCK(cs_mapLocalHost);
  238. return mapLocalHost.count(addr) > 0;
  239. }
  240. /** check whether a given network is one we can probably connect to */
  241. bool IsReachable(enum Network net)
  242. {
  243. LOCK(cs_mapLocalHost);
  244. return !vfLimited[net];
  245. }
  246. /** check whether a given address is in a network we can probably connect to */
  247. bool IsReachable(const CNetAddr& addr)
  248. {
  249. enum Network net = addr.GetNetwork();
  250. return IsReachable(net);
  251. }
  252. CNode* CConnman::FindNode(const CNetAddr& ip)
  253. {
  254. LOCK(cs_vNodes);
  255. BOOST_FOREACH(CNode* pnode, vNodes)
  256. if ((CNetAddr)pnode->addr == ip)
  257. return (pnode);
  258. return NULL;
  259. }
  260. CNode* CConnman::FindNode(const CSubNet& subNet)
  261. {
  262. LOCK(cs_vNodes);
  263. BOOST_FOREACH(CNode* pnode, vNodes)
  264. if (subNet.Match((CNetAddr)pnode->addr))
  265. return (pnode);
  266. return NULL;
  267. }
  268. CNode* CConnman::FindNode(const std::string& addrName)
  269. {
  270. LOCK(cs_vNodes);
  271. BOOST_FOREACH(CNode* pnode, vNodes) {
  272. if (pnode->GetAddrName() == addrName) {
  273. return (pnode);
  274. }
  275. }
  276. return NULL;
  277. }
  278. CNode* CConnman::FindNode(const CService& addr)
  279. {
  280. LOCK(cs_vNodes);
  281. BOOST_FOREACH(CNode* pnode, vNodes)
  282. if ((CService)pnode->addr == addr)
  283. return (pnode);
  284. return NULL;
  285. }
  286. bool CConnman::CheckIncomingNonce(uint64_t nonce)
  287. {
  288. LOCK(cs_vNodes);
  289. BOOST_FOREACH(CNode* pnode, vNodes) {
  290. if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
  291. return false;
  292. }
  293. return true;
  294. }
  295. CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
  296. {
  297. if (pszDest == NULL) {
  298. if (IsLocal(addrConnect))
  299. return NULL;
  300. // Look for an existing connection
  301. CNode* pnode = FindNode((CService)addrConnect);
  302. if (pnode)
  303. {
  304. LogPrintf("Failed to open new connection, already connected\n");
  305. return NULL;
  306. }
  307. }
  308. /// debug print
  309. LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
  310. pszDest ? pszDest : addrConnect.ToString(),
  311. pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
  312. // Connect
  313. SOCKET hSocket;
  314. bool proxyConnectionFailed = false;
  315. if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
  316. ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
  317. {
  318. if (!IsSelectableSocket(hSocket)) {
  319. LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
  320. CloseSocket(hSocket);
  321. return NULL;
  322. }
  323. if (pszDest && addrConnect.IsValid()) {
  324. // It is possible that we already have a connection to the IP/port pszDest resolved to.
  325. // In that case, drop the connection that was just created, and return the existing CNode instead.
  326. // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
  327. // name catch this early.
  328. LOCK(cs_vNodes);
  329. CNode* pnode = FindNode((CService)addrConnect);
  330. if (pnode)
  331. {
  332. pnode->MaybeSetAddrName(std::string(pszDest));
  333. CloseSocket(hSocket);
  334. LogPrintf("Failed to open new connection, already connected\n");
  335. return NULL;
  336. }
  337. }
  338. addrman.Attempt(addrConnect, fCountFailure);
  339. // Add node
  340. NodeId id = GetNewNodeId();
  341. uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
  342. CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, pszDest ? pszDest : "", false);
  343. pnode->nServicesExpected = ServiceFlags(addrConnect.nServices & nRelevantServices);
  344. pnode->AddRef();
  345. return pnode;
  346. } else if (!proxyConnectionFailed) {
  347. // If connecting to the node failed, and failure is not caused by a problem connecting to
  348. // the proxy, mark this as an attempt.
  349. addrman.Attempt(addrConnect, fCountFailure);
  350. }
  351. return NULL;
  352. }
  353. void CConnman::DumpBanlist()
  354. {
  355. SweepBanned(); // clean unused entries (if bantime has expired)
  356. if (!BannedSetIsDirty())
  357. return;
  358. int64_t nStart = GetTimeMillis();
  359. CBanDB bandb;
  360. banmap_t banmap;
  361. GetBanned(banmap);
  362. if (bandb.Write(banmap)) {
  363. SetBannedSetDirty(false);
  364. }
  365. LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
  366. banmap.size(), GetTimeMillis() - nStart);
  367. }
  368. void CNode::CloseSocketDisconnect()
  369. {
  370. fDisconnect = true;
  371. LOCK(cs_hSocket);
  372. if (hSocket != INVALID_SOCKET)
  373. {
  374. LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
  375. CloseSocket(hSocket);
  376. }
  377. }
  378. void CConnman::ClearBanned()
  379. {
  380. {
  381. LOCK(cs_setBanned);
  382. setBanned.clear();
  383. setBannedIsDirty = true;
  384. }
  385. DumpBanlist(); //store banlist to disk
  386. if(clientInterface)
  387. clientInterface->BannedListChanged();
  388. }
  389. bool CConnman::IsBanned(CNetAddr ip)
  390. {
  391. bool fResult = false;
  392. {
  393. LOCK(cs_setBanned);
  394. for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
  395. {
  396. CSubNet subNet = (*it).first;
  397. CBanEntry banEntry = (*it).second;
  398. if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
  399. fResult = true;
  400. }
  401. }
  402. return fResult;
  403. }
  404. bool CConnman::IsBanned(CSubNet subnet)
  405. {
  406. bool fResult = false;
  407. {
  408. LOCK(cs_setBanned);
  409. banmap_t::iterator i = setBanned.find(subnet);
  410. if (i != setBanned.end())
  411. {
  412. CBanEntry banEntry = (*i).second;
  413. if (GetTime() < banEntry.nBanUntil)
  414. fResult = true;
  415. }
  416. }
  417. return fResult;
  418. }
  419. void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
  420. CSubNet subNet(addr);
  421. Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
  422. }
  423. void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
  424. CBanEntry banEntry(GetTime());
  425. banEntry.banReason = banReason;
  426. if (bantimeoffset <= 0)
  427. {
  428. bantimeoffset = GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
  429. sinceUnixEpoch = false;
  430. }
  431. banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
  432. {
  433. LOCK(cs_setBanned);
  434. if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
  435. setBanned[subNet] = banEntry;
  436. setBannedIsDirty = true;
  437. }
  438. else
  439. return;
  440. }
  441. if(clientInterface)
  442. clientInterface->BannedListChanged();
  443. {
  444. LOCK(cs_vNodes);
  445. BOOST_FOREACH(CNode* pnode, vNodes) {
  446. if (subNet.Match((CNetAddr)pnode->addr))
  447. pnode->fDisconnect = true;
  448. }
  449. }
  450. if(banReason == BanReasonManuallyAdded)
  451. DumpBanlist(); //store banlist to disk immediately if user requested ban
  452. }
  453. bool CConnman::Unban(const CNetAddr &addr) {
  454. CSubNet subNet(addr);
  455. return Unban(subNet);
  456. }
  457. bool CConnman::Unban(const CSubNet &subNet) {
  458. {
  459. LOCK(cs_setBanned);
  460. if (!setBanned.erase(subNet))
  461. return false;
  462. setBannedIsDirty = true;
  463. }
  464. if(clientInterface)
  465. clientInterface->BannedListChanged();
  466. DumpBanlist(); //store banlist to disk immediately
  467. return true;
  468. }
  469. void CConnman::GetBanned(banmap_t &banMap)
  470. {
  471. LOCK(cs_setBanned);
  472. // Sweep the banlist so expired bans are not returned
  473. SweepBanned();
  474. banMap = setBanned; //create a thread safe copy
  475. }
  476. void CConnman::SetBanned(const banmap_t &banMap)
  477. {
  478. LOCK(cs_setBanned);
  479. setBanned = banMap;
  480. setBannedIsDirty = true;
  481. }
  482. void CConnman::SweepBanned()
  483. {
  484. int64_t now = GetTime();
  485. LOCK(cs_setBanned);
  486. banmap_t::iterator it = setBanned.begin();
  487. while(it != setBanned.end())
  488. {
  489. CSubNet subNet = (*it).first;
  490. CBanEntry banEntry = (*it).second;
  491. if(now > banEntry.nBanUntil)
  492. {
  493. setBanned.erase(it++);
  494. setBannedIsDirty = true;
  495. LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
  496. }
  497. else
  498. ++it;
  499. }
  500. }
  501. bool CConnman::BannedSetIsDirty()
  502. {
  503. LOCK(cs_setBanned);
  504. return setBannedIsDirty;
  505. }
  506. void CConnman::SetBannedSetDirty(bool dirty)
  507. {
  508. LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
  509. setBannedIsDirty = dirty;
  510. }
  511. bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
  512. LOCK(cs_vWhitelistedRange);
  513. BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
  514. if (subnet.Match(addr))
  515. return true;
  516. }
  517. return false;
  518. }
  519. void CConnman::AddWhitelistedRange(const CSubNet &subnet) {
  520. LOCK(cs_vWhitelistedRange);
  521. vWhitelistedRange.push_back(subnet);
  522. }
  523. std::string CNode::GetAddrName() const {
  524. LOCK(cs_addrName);
  525. return addrName;
  526. }
  527. void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
  528. LOCK(cs_addrName);
  529. if (addrName.empty()) {
  530. addrName = addrNameIn;
  531. }
  532. }
  533. CService CNode::GetAddrLocal() const {
  534. LOCK(cs_addrLocal);
  535. return addrLocal;
  536. }
  537. void CNode::SetAddrLocal(const CService& addrLocalIn) {
  538. LOCK(cs_addrLocal);
  539. if (addrLocal.IsValid()) {
  540. error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
  541. } else {
  542. addrLocal = addrLocalIn;
  543. }
  544. }
  545. #undef X
  546. #define X(name) stats.name = name
  547. void CNode::copyStats(CNodeStats &stats)
  548. {
  549. stats.nodeid = this->GetId();
  550. X(nServices);
  551. X(addr);
  552. {
  553. LOCK(cs_filter);
  554. X(fRelayTxes);
  555. }
  556. X(nLastSend);
  557. X(nLastRecv);
  558. X(nTimeConnected);
  559. X(nTimeOffset);
  560. stats.addrName = GetAddrName();
  561. X(nVersion);
  562. {
  563. LOCK(cs_SubVer);
  564. X(cleanSubVer);
  565. }
  566. X(fInbound);
  567. X(fAddnode);
  568. X(nStartingHeight);
  569. {
  570. LOCK(cs_vSend);
  571. X(mapSendBytesPerMsgCmd);
  572. X(nSendBytes);
  573. }
  574. {
  575. LOCK(cs_vRecv);
  576. X(mapRecvBytesPerMsgCmd);
  577. X(nRecvBytes);
  578. }
  579. X(fWhitelisted);
  580. // It is common for nodes with good ping times to suddenly become lagged,
  581. // due to a new block arriving or other large transfer.
  582. // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
  583. // since pingtime does not update until the ping is complete, which might take a while.
  584. // So, if a ping is taking an unusually long time in flight,
  585. // the caller can immediately detect that this is happening.
  586. int64_t nPingUsecWait = 0;
  587. if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
  588. nPingUsecWait = GetTimeMicros() - nPingUsecStart;
  589. }
  590. // 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 :)
  591. stats.dPingTime = (((double)nPingUsecTime) / 1e6);
  592. stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
  593. stats.dPingWait = (((double)nPingUsecWait) / 1e6);
  594. // Leave string empty if addrLocal invalid (not filled in yet)
  595. CService addrLocalUnlocked = GetAddrLocal();
  596. stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
  597. }
  598. #undef X
  599. bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
  600. {
  601. complete = false;
  602. int64_t nTimeMicros = GetTimeMicros();
  603. LOCK(cs_vRecv);
  604. nLastRecv = nTimeMicros / 1000000;
  605. nRecvBytes += nBytes;
  606. while (nBytes > 0) {
  607. // get current incomplete message, or create a new one
  608. if (vRecvMsg.empty() ||
  609. vRecvMsg.back().complete())
  610. vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
  611. CNetMessage& msg = vRecvMsg.back();
  612. // absorb network data
  613. int handled;
  614. if (!msg.in_data)
  615. handled = msg.readHeader(pch, nBytes);
  616. else
  617. handled = msg.readData(pch, nBytes);
  618. if (handled < 0)
  619. return false;
  620. if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
  621. LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
  622. return false;
  623. }
  624. pch += handled;
  625. nBytes -= handled;
  626. if (msg.complete()) {
  627. //store received bytes per message command
  628. //to prevent a memory DOS, only allow valid commands
  629. mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
  630. if (i == mapRecvBytesPerMsgCmd.end())
  631. i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
  632. assert(i != mapRecvBytesPerMsgCmd.end());
  633. i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
  634. msg.nTime = nTimeMicros;
  635. complete = true;
  636. }
  637. }
  638. return true;
  639. }
  640. void CNode::SetSendVersion(int nVersionIn)
  641. {
  642. // Send version may only be changed in the version message, and
  643. // only one version message is allowed per session. We can therefore
  644. // treat this value as const and even atomic as long as it's only used
  645. // once a version message has been successfully processed. Any attempt to
  646. // set this twice is an error.
  647. if (nSendVersion != 0) {
  648. error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
  649. } else {
  650. nSendVersion = nVersionIn;
  651. }
  652. }
  653. int CNode::GetSendVersion() const
  654. {
  655. // The send version should always be explicitly set to
  656. // INIT_PROTO_VERSION rather than using this value until SetSendVersion
  657. // has been called.
  658. if (nSendVersion == 0) {
  659. error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
  660. return INIT_PROTO_VERSION;
  661. }
  662. return nSendVersion;
  663. }
  664. int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
  665. {
  666. // copy data to temporary parsing buffer
  667. unsigned int nRemaining = 24 - nHdrPos;
  668. unsigned int nCopy = std::min(nRemaining, nBytes);
  669. memcpy(&hdrbuf[nHdrPos], pch, nCopy);
  670. nHdrPos += nCopy;
  671. // if header incomplete, exit
  672. if (nHdrPos < 24)
  673. return nCopy;
  674. // deserialize to CMessageHeader
  675. try {
  676. hdrbuf >> hdr;
  677. }
  678. catch (const std::exception&) {
  679. return -1;
  680. }
  681. // reject messages larger than MAX_SIZE
  682. if (hdr.nMessageSize > MAX_SIZE)
  683. return -1;
  684. // switch state to reading message data
  685. in_data = true;
  686. return nCopy;
  687. }
  688. int CNetMessage::readData(const char *pch, unsigned int nBytes)
  689. {
  690. unsigned int nRemaining = hdr.nMessageSize - nDataPos;
  691. unsigned int nCopy = std::min(nRemaining, nBytes);
  692. if (vRecv.size() < nDataPos + nCopy) {
  693. // Allocate up to 256 KiB ahead, but never more than the total message size.
  694. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
  695. }
  696. hasher.Write((const unsigned char*)pch, nCopy);
  697. memcpy(&vRecv[nDataPos], pch, nCopy);
  698. nDataPos += nCopy;
  699. return nCopy;
  700. }
  701. const uint256& CNetMessage::GetMessageHash() const
  702. {
  703. assert(complete());
  704. if (data_hash.IsNull())
  705. hasher.Finalize(data_hash.begin());
  706. return data_hash;
  707. }
  708. // requires LOCK(cs_vSend)
  709. size_t CConnman::SocketSendData(CNode *pnode) const
  710. {
  711. auto it = pnode->vSendMsg.begin();
  712. size_t nSentSize = 0;
  713. while (it != pnode->vSendMsg.end()) {
  714. const auto &data = *it;
  715. assert(data.size() > pnode->nSendOffset);
  716. int nBytes = 0;
  717. {
  718. LOCK(pnode->cs_hSocket);
  719. if (pnode->hSocket == INVALID_SOCKET)
  720. break;
  721. nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
  722. }
  723. if (nBytes > 0) {
  724. pnode->nLastSend = GetSystemTimeInSeconds();
  725. pnode->nSendBytes += nBytes;
  726. pnode->nSendOffset += nBytes;
  727. nSentSize += nBytes;
  728. if (pnode->nSendOffset == data.size()) {
  729. pnode->nSendOffset = 0;
  730. pnode->nSendSize -= data.size();
  731. pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
  732. it++;
  733. } else {
  734. // could not send full message; stop sending more
  735. break;
  736. }
  737. } else {
  738. if (nBytes < 0) {
  739. // error
  740. int nErr = WSAGetLastError();
  741. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  742. {
  743. LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
  744. pnode->CloseSocketDisconnect();
  745. }
  746. }
  747. // couldn't send anything at all
  748. break;
  749. }
  750. }
  751. if (it == pnode->vSendMsg.end()) {
  752. assert(pnode->nSendOffset == 0);
  753. assert(pnode->nSendSize == 0);
  754. }
  755. pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
  756. return nSentSize;
  757. }
  758. struct NodeEvictionCandidate
  759. {
  760. NodeId id;
  761. int64_t nTimeConnected;
  762. int64_t nMinPingUsecTime;
  763. int64_t nLastBlockTime;
  764. int64_t nLastTXTime;
  765. bool fRelevantServices;
  766. bool fRelayTxes;
  767. bool fBloomFilter;
  768. CAddress addr;
  769. uint64_t nKeyedNetGroup;
  770. };
  771. static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
  772. {
  773. return a.nMinPingUsecTime > b.nMinPingUsecTime;
  774. }
  775. static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
  776. {
  777. return a.nTimeConnected > b.nTimeConnected;
  778. }
  779. static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
  780. return a.nKeyedNetGroup < b.nKeyedNetGroup;
  781. }
  782. static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
  783. {
  784. // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
  785. if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime;
  786. if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
  787. return a.nTimeConnected > b.nTimeConnected;
  788. }
  789. static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
  790. {
  791. // There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn.
  792. if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
  793. if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
  794. if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
  795. return a.nTimeConnected > b.nTimeConnected;
  796. }
  797. /** Try to find a connection to evict when the node is full.
  798. * Extreme care must be taken to avoid opening the node to attacker
  799. * triggered network partitioning.
  800. * The strategy used here is to protect a small number of peers
  801. * for each of several distinct characteristics which are difficult
  802. * to forge. In order to partition a node the attacker must be
  803. * simultaneously better at all of them than honest peers.
  804. */
  805. bool CConnman::AttemptToEvictConnection()
  806. {
  807. std::vector<NodeEvictionCandidate> vEvictionCandidates;
  808. {
  809. LOCK(cs_vNodes);
  810. BOOST_FOREACH(CNode *node, vNodes) {
  811. if (node->fWhitelisted)
  812. continue;
  813. if (!node->fInbound)
  814. continue;
  815. if (node->fDisconnect)
  816. continue;
  817. NodeEvictionCandidate candidate = {node->id, node->nTimeConnected, node->nMinPingUsecTime,
  818. node->nLastBlockTime, node->nLastTXTime,
  819. (node->nServices & nRelevantServices) == nRelevantServices,
  820. node->fRelayTxes, node->pfilter != NULL, node->addr, node->nKeyedNetGroup};
  821. vEvictionCandidates.push_back(candidate);
  822. }
  823. }
  824. if (vEvictionCandidates.empty()) return false;
  825. // Protect connections with certain characteristics
  826. // Deterministically select 4 peers to protect by netgroup.
  827. // An attacker cannot predict which netgroups will be protected
  828. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed);
  829. vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
  830. if (vEvictionCandidates.empty()) return false;
  831. // Protect the 8 nodes with the lowest minimum ping time.
  832. // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
  833. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
  834. vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
  835. if (vEvictionCandidates.empty()) return false;
  836. // Protect 4 nodes that most recently sent us transactions.
  837. // An attacker cannot manipulate this metric without performing useful work.
  838. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeTXTime);
  839. vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
  840. if (vEvictionCandidates.empty()) return false;
  841. // Protect 4 nodes that most recently sent us blocks.
  842. // An attacker cannot manipulate this metric without performing useful work.
  843. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockTime);
  844. vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
  845. if (vEvictionCandidates.empty()) return false;
  846. // Protect the half of the remaining nodes which have been connected the longest.
  847. // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
  848. std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
  849. vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
  850. if (vEvictionCandidates.empty()) return false;
  851. // Identify the network group with the most connections and youngest member.
  852. // (vEvictionCandidates is already sorted by reverse connect time)
  853. uint64_t naMostConnections;
  854. unsigned int nMostConnections = 0;
  855. int64_t nMostConnectionsTime = 0;
  856. std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
  857. BOOST_FOREACH(const NodeEvictionCandidate &node, vEvictionCandidates) {
  858. mapNetGroupNodes[node.nKeyedNetGroup].push_back(node);
  859. int64_t grouptime = mapNetGroupNodes[node.nKeyedNetGroup][0].nTimeConnected;
  860. size_t groupsize = mapNetGroupNodes[node.nKeyedNetGroup].size();
  861. if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
  862. nMostConnections = groupsize;
  863. nMostConnectionsTime = grouptime;
  864. naMostConnections = node.nKeyedNetGroup;
  865. }
  866. }
  867. // Reduce to the network group with the most connections
  868. vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
  869. // Disconnect from the network group with the most connections
  870. NodeId evicted = vEvictionCandidates.front().id;
  871. LOCK(cs_vNodes);
  872. for(std::vector<CNode*>::const_iterator it(vNodes.begin()); it != vNodes.end(); ++it) {
  873. if ((*it)->GetId() == evicted) {
  874. (*it)->fDisconnect = true;
  875. return true;
  876. }
  877. }
  878. return false;
  879. }
  880. void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
  881. struct sockaddr_storage sockaddr;
  882. socklen_t len = sizeof(sockaddr);
  883. SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
  884. CAddress addr;
  885. int nInbound = 0;
  886. int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
  887. if (hSocket != INVALID_SOCKET)
  888. if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
  889. LogPrintf("Warning: Unknown socket family\n");
  890. bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
  891. {
  892. LOCK(cs_vNodes);
  893. BOOST_FOREACH(CNode* pnode, vNodes)
  894. if (pnode->fInbound)
  895. nInbound++;
  896. }
  897. if (hSocket == INVALID_SOCKET)
  898. {
  899. int nErr = WSAGetLastError();
  900. if (nErr != WSAEWOULDBLOCK)
  901. LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
  902. return;
  903. }
  904. if (!fNetworkActive) {
  905. LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
  906. CloseSocket(hSocket);
  907. return;
  908. }
  909. if (!IsSelectableSocket(hSocket))
  910. {
  911. LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
  912. CloseSocket(hSocket);
  913. return;
  914. }
  915. // According to the internet TCP_NODELAY is not carried into accepted sockets
  916. // on all platforms. Set it again here just to be sure.
  917. int set = 1;
  918. #ifdef WIN32
  919. setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
  920. #else
  921. setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
  922. #endif
  923. if (IsBanned(addr) && !whitelisted)
  924. {
  925. LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
  926. CloseSocket(hSocket);
  927. return;
  928. }
  929. if (nInbound >= nMaxInbound)
  930. {
  931. if (!AttemptToEvictConnection()) {
  932. // No connection to evict, disconnect the new connection
  933. LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
  934. CloseSocket(hSocket);
  935. return;
  936. }
  937. }
  938. NodeId id = GetNewNodeId();
  939. uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
  940. CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, "", true);
  941. pnode->AddRef();
  942. pnode->fWhitelisted = whitelisted;
  943. GetNodeSignals().InitializeNode(pnode, *this);
  944. LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
  945. {
  946. LOCK(cs_vNodes);
  947. vNodes.push_back(pnode);
  948. }
  949. }
  950. void CConnman::ThreadSocketHandler()
  951. {
  952. unsigned int nPrevNodeCount = 0;
  953. while (!interruptNet)
  954. {
  955. //
  956. // Disconnect nodes
  957. //
  958. {
  959. LOCK(cs_vNodes);
  960. // Disconnect unused nodes
  961. std::vector<CNode*> vNodesCopy = vNodes;
  962. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  963. {
  964. if (pnode->fDisconnect)
  965. {
  966. // remove from vNodes
  967. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  968. // release outbound grant (if any)
  969. pnode->grantOutbound.Release();
  970. // close socket and cleanup
  971. pnode->CloseSocketDisconnect();
  972. // hold in disconnected pool until all refs are released
  973. pnode->Release();
  974. vNodesDisconnected.push_back(pnode);
  975. }
  976. }
  977. }
  978. {
  979. // Delete disconnected nodes
  980. std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  981. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  982. {
  983. // wait until threads are done using it
  984. if (pnode->GetRefCount() <= 0) {
  985. bool fDelete = false;
  986. {
  987. TRY_LOCK(pnode->cs_inventory, lockInv);
  988. if (lockInv) {
  989. TRY_LOCK(pnode->cs_vSend, lockSend);
  990. if (lockSend) {
  991. fDelete = true;
  992. }
  993. }
  994. }
  995. if (fDelete) {
  996. vNodesDisconnected.remove(pnode);
  997. DeleteNode(pnode);
  998. }
  999. }
  1000. }
  1001. }
  1002. size_t vNodesSize;
  1003. {
  1004. LOCK(cs_vNodes);
  1005. vNodesSize = vNodes.size();
  1006. }
  1007. if(vNodesSize != nPrevNodeCount) {
  1008. nPrevNodeCount = vNodesSize;
  1009. if(clientInterface)
  1010. clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount);
  1011. }
  1012. //
  1013. // Find which sockets have data to receive
  1014. //
  1015. struct timeval timeout;
  1016. timeout.tv_sec = 0;
  1017. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  1018. fd_set fdsetRecv;
  1019. fd_set fdsetSend;
  1020. fd_set fdsetError;
  1021. FD_ZERO(&fdsetRecv);
  1022. FD_ZERO(&fdsetSend);
  1023. FD_ZERO(&fdsetError);
  1024. SOCKET hSocketMax = 0;
  1025. bool have_fds = false;
  1026. BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
  1027. FD_SET(hListenSocket.socket, &fdsetRecv);
  1028. hSocketMax = std::max(hSocketMax, hListenSocket.socket);
  1029. have_fds = true;
  1030. }
  1031. {
  1032. LOCK(cs_vNodes);
  1033. BOOST_FOREACH(CNode* pnode, vNodes)
  1034. {
  1035. // Implement the following logic:
  1036. // * If there is data to send, select() for sending data. As this only
  1037. // happens when optimistic write failed, we choose to first drain the
  1038. // write buffer in this case before receiving more. This avoids
  1039. // needlessly queueing received data, if the remote peer is not themselves
  1040. // receiving data. This means properly utilizing TCP flow control signalling.
  1041. // * Otherwise, if there is space left in the receive buffer, select() for
  1042. // receiving data.
  1043. // * Hand off all complete messages to the processor, to be handled without
  1044. // blocking here.
  1045. bool select_recv = !pnode->fPauseRecv;
  1046. bool select_send;
  1047. {
  1048. LOCK(pnode->cs_vSend);
  1049. select_send = !pnode->vSendMsg.empty();
  1050. }
  1051. LOCK(pnode->cs_hSocket);
  1052. if (pnode->hSocket == INVALID_SOCKET)
  1053. continue;
  1054. FD_SET(pnode->hSocket, &fdsetError);
  1055. hSocketMax = std::max(hSocketMax, pnode->hSocket);
  1056. have_fds = true;
  1057. if (select_send) {
  1058. FD_SET(pnode->hSocket, &fdsetSend);
  1059. continue;
  1060. }
  1061. if (select_recv) {
  1062. FD_SET(pnode->hSocket, &fdsetRecv);
  1063. }
  1064. }
  1065. }
  1066. int nSelect = select(have_fds ? hSocketMax + 1 : 0,
  1067. &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  1068. if (interruptNet)
  1069. return;
  1070. if (nSelect == SOCKET_ERROR)
  1071. {
  1072. if (have_fds)
  1073. {
  1074. int nErr = WSAGetLastError();
  1075. LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
  1076. for (unsigned int i = 0; i <= hSocketMax; i++)
  1077. FD_SET(i, &fdsetRecv);
  1078. }
  1079. FD_ZERO(&fdsetSend);
  1080. FD_ZERO(&fdsetError);
  1081. if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000)))
  1082. return;
  1083. }
  1084. //
  1085. // Accept new connections
  1086. //
  1087. BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
  1088. {
  1089. if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
  1090. {
  1091. AcceptConnection(hListenSocket);
  1092. }
  1093. }
  1094. //
  1095. // Service each socket
  1096. //
  1097. std::vector<CNode*> vNodesCopy;
  1098. {
  1099. LOCK(cs_vNodes);
  1100. vNodesCopy = vNodes;
  1101. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1102. pnode->AddRef();
  1103. }
  1104. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1105. {
  1106. if (interruptNet)
  1107. return;
  1108. //
  1109. // Receive
  1110. //
  1111. bool recvSet = false;
  1112. bool sendSet = false;
  1113. bool errorSet = false;
  1114. {
  1115. LOCK(pnode->cs_hSocket);
  1116. if (pnode->hSocket == INVALID_SOCKET)
  1117. continue;
  1118. recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv);
  1119. sendSet = FD_ISSET(pnode->hSocket, &fdsetSend);
  1120. errorSet = FD_ISSET(pnode->hSocket, &fdsetError);
  1121. }
  1122. if (recvSet || errorSet)
  1123. {
  1124. // typical socket buffer is 8K-64K
  1125. char pchBuf[0x10000];
  1126. int nBytes = 0;
  1127. {
  1128. LOCK(pnode->cs_hSocket);
  1129. if (pnode->hSocket == INVALID_SOCKET)
  1130. continue;
  1131. nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  1132. }
  1133. if (nBytes > 0)
  1134. {
  1135. bool notify = false;
  1136. if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
  1137. pnode->CloseSocketDisconnect();
  1138. RecordBytesRecv(nBytes);
  1139. if (notify) {
  1140. size_t nSizeAdded = 0;
  1141. auto it(pnode->vRecvMsg.begin());
  1142. for (; it != pnode->vRecvMsg.end(); ++it) {
  1143. if (!it->complete())
  1144. break;
  1145. nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
  1146. }
  1147. {
  1148. LOCK(pnode->cs_vProcessMsg);
  1149. pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
  1150. pnode->nProcessQueueSize += nSizeAdded;
  1151. pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
  1152. }
  1153. WakeMessageHandler();
  1154. }
  1155. }
  1156. else if (nBytes == 0)
  1157. {
  1158. // socket closed gracefully
  1159. if (!pnode->fDisconnect) {
  1160. LogPrint(BCLog::NET, "socket closed\n");
  1161. }
  1162. pnode->CloseSocketDisconnect();
  1163. }
  1164. else if (nBytes < 0)
  1165. {
  1166. // error
  1167. int nErr = WSAGetLastError();
  1168. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  1169. {
  1170. if (!pnode->fDisconnect)
  1171. LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
  1172. pnode->CloseSocketDisconnect();
  1173. }
  1174. }
  1175. }
  1176. //
  1177. // Send
  1178. //
  1179. if (sendSet)
  1180. {
  1181. LOCK(pnode->cs_vSend);
  1182. size_t nBytes = SocketSendData(pnode);
  1183. if (nBytes) {
  1184. RecordBytesSent(nBytes);
  1185. }
  1186. }
  1187. //
  1188. // Inactivity checking
  1189. //
  1190. int64_t nTime = GetSystemTimeInSeconds();
  1191. if (nTime - pnode->nTimeConnected > 60)
  1192. {
  1193. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  1194. {
  1195. LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
  1196. pnode->fDisconnect = true;
  1197. }
  1198. else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
  1199. {
  1200. LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
  1201. pnode->fDisconnect = true;
  1202. }
  1203. else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
  1204. {
  1205. LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
  1206. pnode->fDisconnect = true;
  1207. }
  1208. else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
  1209. {
  1210. LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
  1211. pnode->fDisconnect = true;
  1212. }
  1213. else if (!pnode->fSuccessfullyConnected)
  1214. {
  1215. LogPrintf("version handshake timeout from %d\n", pnode->id);
  1216. pnode->fDisconnect = true;
  1217. }
  1218. }
  1219. }
  1220. {
  1221. LOCK(cs_vNodes);
  1222. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1223. pnode->Release();
  1224. }
  1225. }
  1226. }
  1227. void CConnman::WakeMessageHandler()
  1228. {
  1229. {
  1230. std::lock_guard<std::mutex> lock(mutexMsgProc);
  1231. fMsgProcWake = true;
  1232. }
  1233. condMsgProc.notify_one();
  1234. }
  1235. #ifdef USE_UPNP
  1236. void ThreadMapPort()
  1237. {
  1238. std::string port = strprintf("%u", GetListenPort());
  1239. const char * multicastif = 0;
  1240. const char * minissdpdpath = 0;
  1241. struct UPNPDev * devlist = 0;
  1242. char lanaddr[64];
  1243. #ifndef UPNPDISCOVER_SUCCESS
  1244. /* miniupnpc 1.5 */
  1245. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
  1246. #elif MINIUPNPC_API_VERSION < 14
  1247. /* miniupnpc 1.6 */
  1248. int error = 0;
  1249. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
  1250. #else
  1251. /* miniupnpc 1.9.20150730 */
  1252. int error = 0;
  1253. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
  1254. #endif
  1255. struct UPNPUrls urls;
  1256. struct IGDdatas data;
  1257. int r;
  1258. r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
  1259. if (r == 1)
  1260. {
  1261. if (fDiscover) {
  1262. char externalIPAddress[40];
  1263. r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
  1264. if(r != UPNPCOMMAND_SUCCESS)
  1265. LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
  1266. else
  1267. {
  1268. if(externalIPAddress[0])
  1269. {
  1270. CNetAddr resolved;
  1271. if(LookupHost(externalIPAddress, resolved, false)) {
  1272. LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
  1273. AddLocal(resolved, LOCAL_UPNP);
  1274. }
  1275. }
  1276. else
  1277. LogPrintf("UPnP: GetExternalIPAddress failed.\n");
  1278. }
  1279. }
  1280. std::string strDesc = "Bitcoin " + FormatFullVersion();
  1281. try {
  1282. while (true) {
  1283. #ifndef UPNPDISCOVER_SUCCESS
  1284. /* miniupnpc 1.5 */
  1285. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  1286. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
  1287. #else
  1288. /* miniupnpc 1.6 */
  1289. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  1290. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
  1291. #endif
  1292. if(r!=UPNPCOMMAND_SUCCESS)
  1293. LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  1294. port, port, lanaddr, r, strupnperror(r));
  1295. else
  1296. LogPrintf("UPnP Port Mapping successful.\n");
  1297. MilliSleep(20*60*1000); // Refresh every 20 minutes
  1298. }
  1299. }
  1300. catch (const boost::thread_interrupted&)
  1301. {
  1302. r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
  1303. LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
  1304. freeUPNPDevlist(devlist); devlist = 0;
  1305. FreeUPNPUrls(&urls);
  1306. throw;
  1307. }
  1308. } else {
  1309. LogPrintf("No valid UPnP IGDs found\n");
  1310. freeUPNPDevlist(devlist); devlist = 0;
  1311. if (r != 0)
  1312. FreeUPNPUrls(&urls);
  1313. }
  1314. }
  1315. void MapPort(bool fUseUPnP)
  1316. {
  1317. static boost::thread* upnp_thread = NULL;
  1318. if (fUseUPnP)
  1319. {
  1320. if (upnp_thread) {
  1321. upnp_thread->interrupt();
  1322. upnp_thread->join();
  1323. delete upnp_thread;
  1324. }
  1325. upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
  1326. }
  1327. else if (upnp_thread) {
  1328. upnp_thread->interrupt();
  1329. upnp_thread->join();
  1330. delete upnp_thread;
  1331. upnp_thread = NULL;
  1332. }
  1333. }
  1334. #else
  1335. void MapPort(bool)
  1336. {
  1337. // Intentionally left blank.
  1338. }
  1339. #endif
  1340. static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
  1341. {
  1342. //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
  1343. if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
  1344. *requiredServiceBits = NODE_NETWORK;
  1345. return data.host;
  1346. }
  1347. // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
  1348. return strprintf("x%x.%s", *requiredServiceBits, data.host);
  1349. }
  1350. void CConnman::ThreadDNSAddressSeed()
  1351. {
  1352. // goal: only query DNS seeds if address need is acute
  1353. // Avoiding DNS seeds when we don't need them improves user privacy by
  1354. // creating fewer identifying DNS requests, reduces trust by giving seeds
  1355. // less influence on the network topology, and reduces traffic to the seeds.
  1356. if ((addrman.size() > 0) &&
  1357. (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
  1358. if (!interruptNet.sleep_for(std::chrono::seconds(11)))
  1359. return;
  1360. LOCK(cs_vNodes);
  1361. int nRelevant = 0;
  1362. for (auto pnode : vNodes) {
  1363. nRelevant += pnode->fSuccessfullyConnected && ((pnode->nServices & nRelevantServices) == nRelevantServices);
  1364. }
  1365. if (nRelevant >= 2) {
  1366. LogPrintf("P2P peers available. Skipped DNS seeding.\n");
  1367. return;
  1368. }
  1369. }
  1370. const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
  1371. int found = 0;
  1372. LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
  1373. BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
  1374. if (interruptNet) {
  1375. return;
  1376. }
  1377. if (HaveNameProxy()) {
  1378. AddOneShot(seed.host);
  1379. } else {
  1380. std::vector<CNetAddr> vIPs;
  1381. std::vector<CAddress> vAdd;
  1382. ServiceFlags requiredServiceBits = nRelevantServices;
  1383. if (LookupHost(GetDNSHost(seed, &requiredServiceBits).c_str(), vIPs, 0, true))
  1384. {
  1385. BOOST_FOREACH(const CNetAddr& ip, vIPs)
  1386. {
  1387. int nOneDay = 24*3600;
  1388. CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
  1389. addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
  1390. vAdd.push_back(addr);
  1391. found++;
  1392. }
  1393. }
  1394. if (interruptNet) {
  1395. return;
  1396. }
  1397. // TODO: The seed name resolve may fail, yielding an IP of [::], which results in
  1398. // addrman assigning the same source to results from different seeds.
  1399. // This should switch to a hard-coded stable dummy IP for each seed name, so that the
  1400. // resolve is not required at all.
  1401. if (!vIPs.empty()) {
  1402. CService seedSource;
  1403. Lookup(seed.name.c_str(), seedSource, 0, true);
  1404. addrman.Add(vAdd, seedSource);
  1405. }
  1406. }
  1407. }
  1408. LogPrintf("%d addresses found from DNS seeds\n", found);
  1409. }
  1410. void CConnman::DumpAddresses()
  1411. {
  1412. int64_t nStart = GetTimeMillis();
  1413. CAddrDB adb;
  1414. adb.Write(addrman);
  1415. LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
  1416. addrman.size(), GetTimeMillis() - nStart);
  1417. }
  1418. void CConnman::DumpData()
  1419. {
  1420. DumpAddresses();
  1421. DumpBanlist();
  1422. }
  1423. void CConnman::ProcessOneShot()
  1424. {
  1425. std::string strDest;
  1426. {
  1427. LOCK(cs_vOneShots);
  1428. if (vOneShots.empty())
  1429. return;
  1430. strDest = vOneShots.front();
  1431. vOneShots.pop_front();
  1432. }
  1433. CAddress addr;
  1434. CSemaphoreGrant grant(*semOutbound, true);
  1435. if (grant) {
  1436. if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true))
  1437. AddOneShot(strDest);
  1438. }
  1439. }
  1440. void CConnman::ThreadOpenConnections()
  1441. {
  1442. // Connect to specific addresses
  1443. if (gArgs.IsArgSet("-connect") && gArgs.GetArgs("-connect").size() > 0)
  1444. {
  1445. for (int64_t nLoop = 0;; nLoop++)
  1446. {
  1447. ProcessOneShot();
  1448. BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-connect"))
  1449. {
  1450. CAddress addr(CService(), NODE_NONE);
  1451. OpenNetworkConnection(addr, false, NULL, strAddr.c_str());
  1452. for (int i = 0; i < 10 && i < nLoop; i++)
  1453. {
  1454. if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
  1455. return;
  1456. }
  1457. }
  1458. if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
  1459. return;
  1460. }
  1461. }
  1462. // Initiate network connections
  1463. int64_t nStart = GetTime();
  1464. // Minimum time before next feeler connection (in microseconds).
  1465. int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
  1466. while (!interruptNet)
  1467. {
  1468. ProcessOneShot();
  1469. if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
  1470. return;
  1471. CSemaphoreGrant grant(*semOutbound);
  1472. if (interruptNet)
  1473. return;
  1474. // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
  1475. if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
  1476. static bool done = false;
  1477. if (!done) {
  1478. LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
  1479. CNetAddr local;
  1480. LookupHost("127.0.0.1", local, false);
  1481. addrman.Add(convertSeed6(Params().FixedSeeds()), local);
  1482. done = true;
  1483. }
  1484. }
  1485. //
  1486. // Choose an address to connect to based on most recently seen
  1487. //
  1488. CAddress addrConnect;
  1489. // Only connect out to one peer per network group (/16 for IPv4).
  1490. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
  1491. int nOutbound = 0;
  1492. std::set<std::vector<unsigned char> > setConnected;
  1493. {
  1494. LOCK(cs_vNodes);
  1495. BOOST_FOREACH(CNode* pnode, vNodes) {
  1496. if (!pnode->fInbound && !pnode->fAddnode) {
  1497. // Netgroups for inbound and addnode peers are not excluded because our goal here
  1498. // is to not use multiple of our limited outbound slots on a single netgroup
  1499. // but inbound and addnode peers do not use our outbound slots. Inbound peers
  1500. // also have the added issue that they're attacker controlled and could be used
  1501. // to prevent us from connecting to particular hosts if we used them here.
  1502. setConnected.insert(pnode->addr.GetGroup());
  1503. nOutbound++;
  1504. }
  1505. }
  1506. }
  1507. // Feeler Connections
  1508. //
  1509. // Design goals:
  1510. // * Increase the number of connectable addresses in the tried table.
  1511. //
  1512. // Method:
  1513. // * Choose a random address from new and attempt to connect to it if we can connect
  1514. // successfully it is added to tried.
  1515. // * Start attempting feeler connections only after node finishes making outbound
  1516. // connections.
  1517. // * Only make a feeler connection once every few minutes.
  1518. //
  1519. bool fFeeler = false;
  1520. if (nOutbound >= nMaxOutbound) {
  1521. int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
  1522. if (nTime > nNextFeeler) {
  1523. nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
  1524. fFeeler = true;
  1525. } else {
  1526. continue;
  1527. }
  1528. }
  1529. int64_t nANow = GetAdjustedTime();
  1530. int nTries = 0;
  1531. while (!interruptNet)
  1532. {
  1533. CAddrInfo addr = addrman.Select(fFeeler);
  1534. // if we selected an invalid address, restart
  1535. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1536. break;
  1537. // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
  1538. // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
  1539. // already-connected network ranges, ...) before trying new addrman addresses.
  1540. nTries++;
  1541. if (nTries > 100)
  1542. break;
  1543. if (IsLimited(addr))
  1544. continue;
  1545. // only connect to full nodes
  1546. if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
  1547. continue;
  1548. // only consider very recently tried nodes after 30 failed attempts
  1549. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1550. continue;
  1551. // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
  1552. if ((addr.nServices & nRelevantServices) != nRelevantServices && (nTries < 40 || nOutbound >= (nMaxOutbound >> 1)))
  1553. continue;
  1554. // do not allow non-default ports, unless after 50 invalid addresses selected already
  1555. if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
  1556. continue;
  1557. addrConnect = addr;
  1558. break;
  1559. }
  1560. if (addrConnect.IsValid()) {
  1561. if (fFeeler) {
  1562. // Add small amount of random noise before connection to avoid synchronization.
  1563. int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
  1564. if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
  1565. return;
  1566. LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
  1567. }
  1568. OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, NULL, false, fFeeler);
  1569. }
  1570. }
  1571. }
  1572. std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
  1573. {
  1574. std::vector<AddedNodeInfo> ret;
  1575. std::list<std::string> lAddresses(0);
  1576. {
  1577. LOCK(cs_vAddedNodes);
  1578. ret.reserve(vAddedNodes.size());
  1579. BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
  1580. lAddresses.push_back(strAddNode);
  1581. }
  1582. // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
  1583. std::map<CService, bool> mapConnected;
  1584. std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
  1585. {
  1586. LOCK(cs_vNodes);
  1587. for (const CNode* pnode : vNodes) {
  1588. if (pnode->addr.IsValid()) {
  1589. mapConnected[pnode->addr] = pnode->fInbound;
  1590. }
  1591. std::string addrName = pnode->GetAddrName();
  1592. if (!addrName.empty()) {
  1593. mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
  1594. }
  1595. }
  1596. }
  1597. BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
  1598. CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
  1599. if (service.IsValid()) {
  1600. // strAddNode is an IP:port
  1601. auto it = mapConnected.find(service);
  1602. if (it != mapConnected.end()) {
  1603. ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second});
  1604. } else {
  1605. ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
  1606. }
  1607. } else {
  1608. // strAddNode is a name
  1609. auto it = mapConnectedByName.find(strAddNode);
  1610. if (it != mapConnectedByName.end()) {
  1611. ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first});
  1612. } else {
  1613. ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
  1614. }
  1615. }
  1616. }
  1617. return ret;
  1618. }
  1619. void CConnman::ThreadOpenAddedConnections()
  1620. {
  1621. {
  1622. LOCK(cs_vAddedNodes);
  1623. if (gArgs.IsArgSet("-addnode"))
  1624. vAddedNodes = gArgs.GetArgs("-addnode");
  1625. }
  1626. while (true)
  1627. {
  1628. CSemaphoreGrant grant(*semAddnode);
  1629. std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
  1630. bool tried = false;
  1631. for (const AddedNodeInfo& info : vInfo) {
  1632. if (!info.fConnected) {
  1633. if (!grant.TryAcquire()) {
  1634. // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
  1635. // the addednodeinfo state might change.
  1636. break;
  1637. }
  1638. // If strAddedNode is an IP/port, decode it immediately, so
  1639. // OpenNetworkConnection can detect existing connections to that IP/port.
  1640. tried = true;
  1641. CService service(LookupNumeric(info.strAddedNode.c_str(), Params().GetDefaultPort()));
  1642. OpenNetworkConnection(CAddress(service, NODE_NONE), false, &grant, info.strAddedNode.c_str(), false, false, true);
  1643. if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
  1644. return;
  1645. }
  1646. }
  1647. // Retry every 60 seconds if a connection was attempted, otherwise two seconds
  1648. if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
  1649. return;
  1650. }
  1651. }
  1652. // if successful, this moves the passed grant to the constructed node
  1653. bool CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool fAddnode)
  1654. {
  1655. //
  1656. // Initiate outbound network connection
  1657. //
  1658. if (interruptNet) {
  1659. return false;
  1660. }
  1661. if (!fNetworkActive) {
  1662. return false;
  1663. }
  1664. if (!pszDest) {
  1665. if (IsLocal(addrConnect) ||
  1666. FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) ||
  1667. FindNode(addrConnect.ToStringIPPort()))
  1668. return false;
  1669. } else if (FindNode(std::string(pszDest)))
  1670. return false;
  1671. CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
  1672. if (!pnode)
  1673. return false;
  1674. if (grantOutbound)
  1675. grantOutbound->MoveTo(pnode->grantOutbound);
  1676. if (fOneShot)
  1677. pnode->fOneShot = true;
  1678. if (fFeeler)
  1679. pnode->fFeeler = true;
  1680. if (fAddnode)
  1681. pnode->fAddnode = true;
  1682. GetNodeSignals().InitializeNode(pnode, *this);
  1683. {
  1684. LOCK(cs_vNodes);
  1685. vNodes.push_back(pnode);
  1686. }
  1687. return true;
  1688. }
  1689. void CConnman::ThreadMessageHandler()
  1690. {
  1691. while (!flagInterruptMsgProc)
  1692. {
  1693. std::vector<CNode*> vNodesCopy;
  1694. {
  1695. LOCK(cs_vNodes);
  1696. vNodesCopy = vNodes;
  1697. BOOST_FOREACH(CNode* pnode, vNodesCopy) {
  1698. pnode->AddRef();
  1699. }
  1700. }
  1701. bool fMoreWork = false;
  1702. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1703. {
  1704. if (pnode->fDisconnect)
  1705. continue;
  1706. // Receive messages
  1707. bool fMoreNodeWork = GetNodeSignals().ProcessMessages(pnode, *this, flagInterruptMsgProc);
  1708. fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
  1709. if (flagInterruptMsgProc)
  1710. return;
  1711. // Send messages
  1712. {
  1713. LOCK(pnode->cs_sendProcessing);
  1714. GetNodeSignals().SendMessages(pnode, *this, flagInterruptMsgProc);
  1715. }
  1716. if (flagInterruptMsgProc)
  1717. return;
  1718. }
  1719. {
  1720. LOCK(cs_vNodes);
  1721. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1722. pnode->Release();
  1723. }
  1724. std::unique_lock<std::mutex> lock(mutexMsgProc);
  1725. if (!fMoreWork) {
  1726. condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
  1727. }
  1728. fMsgProcWake = false;
  1729. }
  1730. }
  1731. bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
  1732. {
  1733. strError = "";
  1734. int nOne = 1;
  1735. // Create socket for listening for incoming connections
  1736. struct sockaddr_storage sockaddr;
  1737. socklen_t len = sizeof(sockaddr);
  1738. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1739. {
  1740. strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
  1741. LogPrintf("%s\n", strError);
  1742. return false;
  1743. }
  1744. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1745. if (hListenSocket == INVALID_SOCKET)
  1746. {
  1747. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
  1748. LogPrintf("%s\n", strError);
  1749. return false;
  1750. }
  1751. if (!IsSelectableSocket(hListenSocket))
  1752. {
  1753. strError = "Error: Couldn't create a listenable socket for incoming connections";
  1754. LogPrintf("%s\n", strError);
  1755. return false;
  1756. }
  1757. #ifndef WIN32
  1758. #ifdef SO_NOSIGPIPE
  1759. // Different way of disabling SIGPIPE on BSD
  1760. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1761. #endif
  1762. // Allow binding if the port is still in TIME_WAIT state after
  1763. // the program was closed and restarted.
  1764. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1765. // Disable Nagle's algorithm
  1766. setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
  1767. #else
  1768. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
  1769. setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
  1770. #endif
  1771. // Set to non-blocking, incoming connections will also inherit this
  1772. if (!SetSocketNonBlocking(hListenSocket, true)) {
  1773. strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
  1774. LogPrintf("%s\n", strError);
  1775. return false;
  1776. }
  1777. // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
  1778. // and enable it by default or not. Try to enable it, if possible.
  1779. if (addrBind.IsIPv6()) {
  1780. #ifdef IPV6_V6ONLY
  1781. #ifdef WIN32
  1782. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
  1783. #else
  1784. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1785. #endif
  1786. #endif
  1787. #ifdef WIN32
  1788. int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
  1789. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
  1790. #endif
  1791. }
  1792. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1793. {
  1794. int nErr = WSAGetLastError();
  1795. if (nErr == WSAEADDRINUSE)
  1796. strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
  1797. else
  1798. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
  1799. LogPrintf("%s\n", strError);
  1800. CloseSocket(hListenSocket);
  1801. return false;
  1802. }
  1803. LogPrintf("Bound to %s\n", addrBind.ToString());
  1804. // Listen for incoming connections
  1805. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1806. {
  1807. strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
  1808. LogPrintf("%s\n", strError);
  1809. CloseSocket(hListenSocket);
  1810. return false;
  1811. }
  1812. vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
  1813. if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
  1814. AddLocal(addrBind, LOCAL_BIND);
  1815. return true;
  1816. }
  1817. void Discover(boost::thread_group& threadGroup)
  1818. {
  1819. if (!fDiscover)
  1820. return;
  1821. #ifdef WIN32
  1822. // Get local host IP
  1823. char pszHostName[256] = "";
  1824. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1825. {
  1826. std::vector<CNetAddr> vaddr;
  1827. if (LookupHost(pszHostName, vaddr, 0, true))
  1828. {
  1829. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1830. {
  1831. if (AddLocal(addr, LOCAL_IF))
  1832. LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
  1833. }
  1834. }
  1835. }
  1836. #else
  1837. // Get local host ip
  1838. struct ifaddrs* myaddrs;
  1839. if (getifaddrs(&myaddrs) == 0)
  1840. {
  1841. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1842. {
  1843. if (ifa->ifa_addr == NULL) continue;
  1844. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1845. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1846. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1847. if (ifa->ifa_addr->sa_family == AF_INET)
  1848. {
  1849. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1850. CNetAddr addr(s4->sin_addr);
  1851. if (AddLocal(addr, LOCAL_IF))
  1852. LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
  1853. }
  1854. else if (ifa->ifa_addr->sa_family == AF_INET6)
  1855. {
  1856. struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
  1857. CNetAddr addr(s6->sin6_addr);
  1858. if (AddLocal(addr, LOCAL_IF))
  1859. LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
  1860. }
  1861. }
  1862. freeifaddrs(myaddrs);
  1863. }
  1864. #endif
  1865. }
  1866. void CConnman::SetNetworkActive(bool active)
  1867. {
  1868. LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
  1869. if (!active) {
  1870. fNetworkActive = false;
  1871. LOCK(cs_vNodes);
  1872. // Close sockets to all nodes
  1873. BOOST_FOREACH(CNode* pnode, vNodes) {
  1874. pnode->CloseSocketDisconnect();
  1875. }
  1876. } else {
  1877. fNetworkActive = true;
  1878. }
  1879. uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
  1880. }
  1881. CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
  1882. {
  1883. fNetworkActive = true;
  1884. setBannedIsDirty = false;
  1885. fAddressesInitialized = false;
  1886. nLastNodeId = 0;
  1887. nSendBufferMaxSize = 0;
  1888. nReceiveFloodSize = 0;
  1889. semOutbound = NULL;
  1890. semAddnode = NULL;
  1891. nMaxConnections = 0;
  1892. nMaxOutbound = 0;
  1893. nMaxAddnode = 0;
  1894. nBestHeight = 0;
  1895. clientInterface = NULL;
  1896. flagInterruptMsgProc = false;
  1897. }
  1898. NodeId CConnman::GetNewNodeId()
  1899. {
  1900. return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
  1901. }
  1902. bool CConnman::Start(CScheduler& scheduler, std::string& strNodeError, Options connOptions)
  1903. {
  1904. nTotalBytesRecv = 0;
  1905. nTotalBytesSent = 0;
  1906. nMaxOutboundTotalBytesSentInCycle = 0;
  1907. nMaxOutboundCycleStartTime = 0;
  1908. nRelevantServices = connOptions.nRelevantServices;
  1909. nLocalServices = connOptions.nLocalServices;
  1910. nMaxConnections = connOptions.nMaxConnections;
  1911. nMaxOutbound = std::min((connOptions.nMaxOutbound), nMaxConnections);
  1912. nMaxAddnode = connOptions.nMaxAddnode;
  1913. nMaxFeeler = connOptions.nMaxFeeler;
  1914. nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
  1915. nReceiveFloodSize = connOptions.nReceiveFloodSize;
  1916. nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
  1917. nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
  1918. SetBestHeight(connOptions.nBestHeight);
  1919. clientInterface = connOptions.uiInterface;
  1920. if (clientInterface) {
  1921. clientInterface->InitMessage(_("Loading P2P addresses..."));
  1922. }
  1923. // Load addresses from peers.dat
  1924. int64_t nStart = GetTimeMillis();
  1925. {
  1926. CAddrDB adb;
  1927. if (adb.Read(addrman))
  1928. LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
  1929. else {
  1930. addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
  1931. LogPrintf("Invalid or missing peers.dat; recreating\n");
  1932. DumpAddresses();
  1933. }
  1934. }
  1935. if (clientInterface)
  1936. clientInterface->InitMessage(_("Loading banlist..."));
  1937. // Load addresses from banlist.dat
  1938. nStart = GetTimeMillis();
  1939. CBanDB bandb;
  1940. banmap_t banmap;
  1941. if (bandb.Read(banmap)) {
  1942. SetBanned(banmap); // thread save setter
  1943. SetBannedSetDirty(false); // no need to write down, just read data
  1944. SweepBanned(); // sweep out unused entries
  1945. LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
  1946. banmap.size(), GetTimeMillis() - nStart);
  1947. } else {
  1948. LogPrintf("Invalid or missing banlist.dat; recreating\n");
  1949. SetBannedSetDirty(true); // force write
  1950. DumpBanlist();
  1951. }
  1952. uiInterface.InitMessage(_("Starting network threads..."));
  1953. fAddressesInitialized = true;
  1954. if (semOutbound == NULL) {
  1955. // initialize semaphore
  1956. semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
  1957. }
  1958. if (semAddnode == NULL) {
  1959. // initialize semaphore
  1960. semAddnode = new CSemaphore(nMaxAddnode);
  1961. }
  1962. //
  1963. // Start threads
  1964. //
  1965. InterruptSocks5(false);
  1966. interruptNet.reset();
  1967. flagInterruptMsgProc = false;
  1968. {
  1969. std::unique_lock<std::mutex> lock(mutexMsgProc);
  1970. fMsgProcWake = false;
  1971. }
  1972. // Send and receive from sockets, accept connections
  1973. threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
  1974. if (!GetBoolArg("-dnsseed", true))
  1975. LogPrintf("DNS seeding disabled\n");
  1976. else
  1977. threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
  1978. // Initiate outbound connections from -addnode
  1979. threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
  1980. // Initiate outbound connections unless connect=0
  1981. if (!gArgs.IsArgSet("-connect") || gArgs.GetArgs("-connect").size() != 1 || gArgs.GetArgs("-connect")[0] != "0")
  1982. threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this)));
  1983. // Process messages
  1984. threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
  1985. // Dump network addresses
  1986. scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
  1987. return true;
  1988. }
  1989. class CNetCleanup
  1990. {
  1991. public:
  1992. CNetCleanup() {}
  1993. ~CNetCleanup()
  1994. {
  1995. #ifdef WIN32
  1996. // Shutdown Windows Sockets
  1997. WSACleanup();
  1998. #endif
  1999. }
  2000. }
  2001. instance_of_cnetcleanup;
  2002. void CConnman::Interrupt()
  2003. {
  2004. {
  2005. std::lock_guard<std::mutex> lock(mutexMsgProc);
  2006. flagInterruptMsgProc = true;
  2007. }
  2008. condMsgProc.notify_all();
  2009. interruptNet();
  2010. InterruptSocks5(true);
  2011. if (semOutbound) {
  2012. for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
  2013. semOutbound->post();
  2014. }
  2015. }
  2016. if (semAddnode) {
  2017. for (int i=0; i<nMaxAddnode; i++) {
  2018. semAddnode->post();
  2019. }
  2020. }
  2021. }
  2022. void CConnman::Stop()
  2023. {
  2024. if (threadMessageHandler.joinable())
  2025. threadMessageHandler.join();
  2026. if (threadOpenConnections.joinable())
  2027. threadOpenConnections.join();
  2028. if (threadOpenAddedConnections.joinable())
  2029. threadOpenAddedConnections.join();
  2030. if (threadDNSAddressSeed.joinable())
  2031. threadDNSAddressSeed.join();
  2032. if (threadSocketHandler.joinable())
  2033. threadSocketHandler.join();
  2034. if (fAddressesInitialized)
  2035. {
  2036. DumpData();
  2037. fAddressesInitialized = false;
  2038. }
  2039. // Close sockets
  2040. BOOST_FOREACH(CNode* pnode, vNodes)
  2041. pnode->CloseSocketDisconnect();
  2042. BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
  2043. if (hListenSocket.socket != INVALID_SOCKET)
  2044. if (!CloseSocket(hListenSocket.socket))
  2045. LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
  2046. // clean up some globals (to help leak detection)
  2047. BOOST_FOREACH(CNode *pnode, vNodes) {
  2048. DeleteNode(pnode);
  2049. }
  2050. BOOST_FOREACH(CNode *pnode, vNodesDisconnected) {
  2051. DeleteNode(pnode);
  2052. }
  2053. vNodes.clear();
  2054. vNodesDisconnected.clear();
  2055. vhListenSocket.clear();
  2056. delete semOutbound;
  2057. semOutbound = NULL;
  2058. delete semAddnode;
  2059. semAddnode = NULL;
  2060. }
  2061. void CConnman::DeleteNode(CNode* pnode)
  2062. {
  2063. assert(pnode);
  2064. bool fUpdateConnectionTime = false;
  2065. GetNodeSignals().FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
  2066. if(fUpdateConnectionTime)
  2067. addrman.Connected(pnode->addr);
  2068. delete pnode;
  2069. }
  2070. CConnman::~CConnman()
  2071. {
  2072. Interrupt();
  2073. Stop();
  2074. }
  2075. size_t CConnman::GetAddressCount() const
  2076. {
  2077. return addrman.size();
  2078. }
  2079. void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
  2080. {
  2081. addrman.SetServices(addr, nServices);
  2082. }
  2083. void CConnman::MarkAddressGood(const CAddress& addr)
  2084. {
  2085. addrman.Good(addr);
  2086. }
  2087. void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
  2088. {
  2089. addrman.Add(vAddr, addrFrom, nTimePenalty);
  2090. }
  2091. std::vector<CAddress> CConnman::GetAddresses()
  2092. {
  2093. return addrman.GetAddr();
  2094. }
  2095. bool CConnman::AddNode(const std::string& strNode)
  2096. {
  2097. LOCK(cs_vAddedNodes);
  2098. for(std::vector<std::string>::const_iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
  2099. if (strNode == *it)
  2100. return false;
  2101. }
  2102. vAddedNodes.push_back(strNode);
  2103. return true;
  2104. }
  2105. bool CConnman::RemoveAddedNode(const std::string& strNode)
  2106. {
  2107. LOCK(cs_vAddedNodes);
  2108. for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
  2109. if (strNode == *it) {
  2110. vAddedNodes.erase(it);
  2111. return true;
  2112. }
  2113. }
  2114. return false;
  2115. }
  2116. size_t CConnman::GetNodeCount(NumConnections flags)
  2117. {
  2118. LOCK(cs_vNodes);
  2119. if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
  2120. return vNodes.size();
  2121. int nNum = 0;
  2122. for(std::vector<CNode*>::const_iterator it = vNodes.begin(); it != vNodes.end(); ++it)
  2123. if (flags & ((*it)->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
  2124. nNum++;
  2125. return nNum;
  2126. }
  2127. void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
  2128. {
  2129. vstats.clear();
  2130. LOCK(cs_vNodes);
  2131. vstats.reserve(vNodes.size());
  2132. for(std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) {
  2133. CNode* pnode = *it;
  2134. vstats.emplace_back();
  2135. pnode->copyStats(vstats.back());
  2136. }
  2137. }
  2138. bool CConnman::DisconnectNode(const std::string& strNode)
  2139. {
  2140. LOCK(cs_vNodes);
  2141. if (CNode* pnode = FindNode(strNode)) {
  2142. pnode->fDisconnect = true;
  2143. return true;
  2144. }
  2145. return false;
  2146. }
  2147. bool CConnman::DisconnectNode(NodeId id)
  2148. {
  2149. LOCK(cs_vNodes);
  2150. for(CNode* pnode : vNodes) {
  2151. if (id == pnode->id) {
  2152. pnode->fDisconnect = true;
  2153. return true;
  2154. }
  2155. }
  2156. return false;
  2157. }
  2158. void CConnman::RecordBytesRecv(uint64_t bytes)
  2159. {
  2160. LOCK(cs_totalBytesRecv);
  2161. nTotalBytesRecv += bytes;
  2162. }
  2163. void CConnman::RecordBytesSent(uint64_t bytes)
  2164. {
  2165. LOCK(cs_totalBytesSent);
  2166. nTotalBytesSent += bytes;
  2167. uint64_t now = GetTime();
  2168. if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
  2169. {
  2170. // timeframe expired, reset cycle
  2171. nMaxOutboundCycleStartTime = now;
  2172. nMaxOutboundTotalBytesSentInCycle = 0;
  2173. }
  2174. // TODO, exclude whitebind peers
  2175. nMaxOutboundTotalBytesSentInCycle += bytes;
  2176. }
  2177. void CConnman::SetMaxOutboundTarget(uint64_t limit)
  2178. {
  2179. LOCK(cs_totalBytesSent);
  2180. nMaxOutboundLimit = limit;
  2181. }
  2182. uint64_t CConnman::GetMaxOutboundTarget()
  2183. {
  2184. LOCK(cs_totalBytesSent);
  2185. return nMaxOutboundLimit;
  2186. }
  2187. uint64_t CConnman::GetMaxOutboundTimeframe()
  2188. {
  2189. LOCK(cs_totalBytesSent);
  2190. return nMaxOutboundTimeframe;
  2191. }
  2192. uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
  2193. {
  2194. LOCK(cs_totalBytesSent);
  2195. if (nMaxOutboundLimit == 0)
  2196. return 0;
  2197. if (nMaxOutboundCycleStartTime == 0)
  2198. return nMaxOutboundTimeframe;
  2199. uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
  2200. uint64_t now = GetTime();
  2201. return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
  2202. }
  2203. void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
  2204. {
  2205. LOCK(cs_totalBytesSent);
  2206. if (nMaxOutboundTimeframe != timeframe)
  2207. {
  2208. // reset measure-cycle in case of changing
  2209. // the timeframe
  2210. nMaxOutboundCycleStartTime = GetTime();
  2211. }
  2212. nMaxOutboundTimeframe = timeframe;
  2213. }
  2214. bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
  2215. {
  2216. LOCK(cs_totalBytesSent);
  2217. if (nMaxOutboundLimit == 0)
  2218. return false;
  2219. if (historicalBlockServingLimit)
  2220. {
  2221. // keep a large enough buffer to at least relay each block once
  2222. uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
  2223. uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE;
  2224. if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
  2225. return true;
  2226. }
  2227. else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
  2228. return true;
  2229. return false;
  2230. }
  2231. uint64_t CConnman::GetOutboundTargetBytesLeft()
  2232. {
  2233. LOCK(cs_totalBytesSent);
  2234. if (nMaxOutboundLimit == 0)
  2235. return 0;
  2236. return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
  2237. }
  2238. uint64_t CConnman::GetTotalBytesRecv()
  2239. {
  2240. LOCK(cs_totalBytesRecv);
  2241. return nTotalBytesRecv;
  2242. }
  2243. uint64_t CConnman::GetTotalBytesSent()
  2244. {
  2245. LOCK(cs_totalBytesSent);
  2246. return nTotalBytesSent;
  2247. }
  2248. ServiceFlags CConnman::GetLocalServices() const
  2249. {
  2250. return nLocalServices;
  2251. }
  2252. void CConnman::SetBestHeight(int height)
  2253. {
  2254. nBestHeight.store(height, std::memory_order_release);
  2255. }
  2256. int CConnman::GetBestHeight() const
  2257. {
  2258. return nBestHeight.load(std::memory_order_acquire);
  2259. }
  2260. unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
  2261. unsigned int CConnman::GetSendBufferSize() const{ return nSendBufferMaxSize; }
  2262. CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string& addrNameIn, bool fInboundIn) :
  2263. nTimeConnected(GetSystemTimeInSeconds()),
  2264. addr(addrIn),
  2265. fInbound(fInboundIn),
  2266. id(idIn),
  2267. nKeyedNetGroup(nKeyedNetGroupIn),
  2268. addrKnown(5000, 0.001),
  2269. filterInventoryKnown(50000, 0.000001),
  2270. nLocalHostNonce(nLocalHostNonceIn),
  2271. nLocalServices(nLocalServicesIn),
  2272. nMyStartingHeight(nMyStartingHeightIn),
  2273. nSendVersion(0)
  2274. {
  2275. nServices = NODE_NONE;
  2276. nServicesExpected = NODE_NONE;
  2277. hSocket = hSocketIn;
  2278. nRecvVersion = INIT_PROTO_VERSION;
  2279. nLastSend = 0;
  2280. nLastRecv = 0;
  2281. nSendBytes = 0;
  2282. nRecvBytes = 0;
  2283. nTimeOffset = 0;
  2284. addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
  2285. nVersion = 0;
  2286. strSubVer = "";
  2287. fWhitelisted = false;
  2288. fOneShot = false;
  2289. fAddnode = false;
  2290. fClient = false; // set by version message
  2291. fFeeler = false;
  2292. fSuccessfullyConnected = false;
  2293. fDisconnect = false;
  2294. nRefCount = 0;
  2295. nSendSize = 0;
  2296. nSendOffset = 0;
  2297. hashContinue = uint256();
  2298. nStartingHeight = -1;
  2299. filterInventoryKnown.reset();
  2300. fSendMempool = false;
  2301. fGetAddr = false;
  2302. nNextLocalAddrSend = 0;
  2303. nNextAddrSend = 0;
  2304. nNextInvSend = 0;
  2305. fRelayTxes = false;
  2306. fSentAddr = false;
  2307. pfilter = new CBloomFilter();
  2308. timeLastMempoolReq = 0;
  2309. nLastBlockTime = 0;
  2310. nLastTXTime = 0;
  2311. nPingNonceSent = 0;
  2312. nPingUsecStart = 0;
  2313. nPingUsecTime = 0;
  2314. fPingQueued = false;
  2315. nMinPingUsecTime = std::numeric_limits<int64_t>::max();
  2316. minFeeFilter = 0;
  2317. lastSentFeeFilter = 0;
  2318. nextSendTimeFeeFilter = 0;
  2319. fPauseRecv = false;
  2320. fPauseSend = false;
  2321. nProcessQueueSize = 0;
  2322. BOOST_FOREACH(const std::string &msg, getAllNetMessageTypes())
  2323. mapRecvBytesPerMsgCmd[msg] = 0;
  2324. mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
  2325. if (fLogIPs) {
  2326. LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
  2327. } else {
  2328. LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
  2329. }
  2330. }
  2331. CNode::~CNode()
  2332. {
  2333. CloseSocket(hSocket);
  2334. if (pfilter)
  2335. delete pfilter;
  2336. }
  2337. void CNode::AskFor(const CInv& inv)
  2338. {
  2339. if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
  2340. return;
  2341. // a peer may not have multiple non-responded queue positions for a single inv item
  2342. if (!setAskFor.insert(inv.hash).second)
  2343. return;
  2344. // We're using mapAskFor as a priority queue,
  2345. // the key is the earliest time the request can be sent
  2346. int64_t nRequestTime;
  2347. limitedmap<uint256, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv.hash);
  2348. if (it != mapAlreadyAskedFor.end())
  2349. nRequestTime = it->second;
  2350. else
  2351. nRequestTime = 0;
  2352. LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
  2353. // Make sure not to reuse time indexes to keep things in the same order
  2354. int64_t nNow = GetTimeMicros() - 1000000;
  2355. static int64_t nLastTime;
  2356. ++nLastTime;
  2357. nNow = std::max(nNow, nLastTime);
  2358. nLastTime = nNow;
  2359. // Each retry is 2 minutes after the last
  2360. nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
  2361. if (it != mapAlreadyAskedFor.end())
  2362. mapAlreadyAskedFor.update(it, nRequestTime);
  2363. else
  2364. mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime));
  2365. mapAskFor.insert(std::make_pair(nRequestTime, inv));
  2366. }
  2367. bool CConnman::NodeFullyConnected(const CNode* pnode)
  2368. {
  2369. return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
  2370. }
  2371. void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
  2372. {
  2373. size_t nMessageSize = msg.data.size();
  2374. size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
  2375. LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->id);
  2376. std::vector<unsigned char> serializedHeader;
  2377. serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
  2378. uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
  2379. CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
  2380. memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
  2381. CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
  2382. size_t nBytesSent = 0;
  2383. {
  2384. LOCK(pnode->cs_vSend);
  2385. bool optimisticSend(pnode->vSendMsg.empty());
  2386. //log total amount of bytes per command
  2387. pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
  2388. pnode->nSendSize += nTotalSize;
  2389. if (pnode->nSendSize > nSendBufferMaxSize)
  2390. pnode->fPauseSend = true;
  2391. pnode->vSendMsg.push_back(std::move(serializedHeader));
  2392. if (nMessageSize)
  2393. pnode->vSendMsg.push_back(std::move(msg.data));
  2394. // If write queue empty, attempt "optimistic write"
  2395. if (optimisticSend == true)
  2396. nBytesSent = SocketSendData(pnode);
  2397. }
  2398. if (nBytesSent)
  2399. RecordBytesSent(nBytesSent);
  2400. }
  2401. bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
  2402. {
  2403. CNode* found = nullptr;
  2404. LOCK(cs_vNodes);
  2405. for (auto&& pnode : vNodes) {
  2406. if(pnode->id == id) {
  2407. found = pnode;
  2408. break;
  2409. }
  2410. }
  2411. return found != nullptr && NodeFullyConnected(found) && func(found);
  2412. }
  2413. int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
  2414. return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
  2415. }
  2416. CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
  2417. {
  2418. return CSipHasher(nSeed0, nSeed1).Write(id);
  2419. }
  2420. uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const
  2421. {
  2422. std::vector<unsigned char> vchNetGroup(ad.GetGroup());
  2423. return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(&vchNetGroup[0], vchNetGroup.size()).Finalize();
  2424. }