Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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