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 89KB

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