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

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