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

net.cpp 85KB

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