Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

net.cpp 64KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 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 "core.h"
  12. #include "ui_interface.h"
  13. #ifdef WIN32
  14. #include <string.h>
  15. #else
  16. #include <fcntl.h>
  17. #endif
  18. #ifdef USE_UPNP
  19. #include <miniupnpc/miniupnpc.h>
  20. #include <miniupnpc/miniwget.h>
  21. #include <miniupnpc/upnpcommands.h>
  22. #include <miniupnpc/upnperrors.h>
  23. #endif
  24. #include <boost/filesystem.hpp>
  25. #include <boost/thread.hpp>
  26. // Dump addresses to peers.dat every 15 minutes (900s)
  27. #define DUMP_ADDRESSES_INTERVAL 900
  28. #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
  29. #define MSG_NOSIGNAL 0
  30. #endif
  31. // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
  32. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
  33. #ifdef WIN32
  34. #ifndef PROTECTION_LEVEL_UNRESTRICTED
  35. #define PROTECTION_LEVEL_UNRESTRICTED 10
  36. #endif
  37. #ifndef IPV6_PROTECTION_LEVEL
  38. #define IPV6_PROTECTION_LEVEL 23
  39. #endif
  40. #endif
  41. using namespace boost;
  42. using namespace std;
  43. namespace {
  44. const int MAX_OUTBOUND_CONNECTIONS = 8;
  45. struct ListenSocket {
  46. SOCKET socket;
  47. bool whitelisted;
  48. ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
  49. };
  50. }
  51. //
  52. // Global state variables
  53. //
  54. bool fDiscover = true;
  55. bool fListen = true;
  56. uint64_t nLocalServices = NODE_NETWORK;
  57. CCriticalSection cs_mapLocalHost;
  58. map<CNetAddr, LocalServiceInfo> mapLocalHost;
  59. static bool vfReachable[NET_MAX] = {};
  60. static bool vfLimited[NET_MAX] = {};
  61. static CNode* pnodeLocalHost = NULL;
  62. uint64_t nLocalHostNonce = 0;
  63. static std::vector<ListenSocket> vhListenSocket;
  64. CAddrMan addrman;
  65. int nMaxConnections = 125;
  66. bool fAddressesInitialized = false;
  67. vector<CNode*> vNodes;
  68. CCriticalSection cs_vNodes;
  69. map<CInv, CDataStream> mapRelay;
  70. deque<pair<int64_t, CInv> > vRelayExpiration;
  71. CCriticalSection cs_mapRelay;
  72. limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
  73. static deque<string> vOneShots;
  74. CCriticalSection cs_vOneShots;
  75. set<CNetAddr> setservAddNodeAddresses;
  76. CCriticalSection cs_setservAddNodeAddresses;
  77. vector<std::string> vAddedNodes;
  78. CCriticalSection cs_vAddedNodes;
  79. NodeId nLastNodeId = 0;
  80. CCriticalSection cs_nLastNodeId;
  81. static CSemaphore *semOutbound = NULL;
  82. // Signals for message handling
  83. static CNodeSignals g_signals;
  84. CNodeSignals& GetNodeSignals() { return g_signals; }
  85. void AddOneShot(string strDest)
  86. {
  87. LOCK(cs_vOneShots);
  88. vOneShots.push_back(strDest);
  89. }
  90. unsigned short GetListenPort()
  91. {
  92. return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
  93. }
  94. // find 'best' local address for a particular peer
  95. bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
  96. {
  97. if (!fListen)
  98. return false;
  99. int nBestScore = -1;
  100. int nBestReachability = -1;
  101. {
  102. LOCK(cs_mapLocalHost);
  103. for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
  104. {
  105. int nScore = (*it).second.nScore;
  106. int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
  107. if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
  108. {
  109. addr = CService((*it).first, (*it).second.nPort);
  110. nBestReachability = nReachability;
  111. nBestScore = nScore;
  112. }
  113. }
  114. }
  115. return nBestScore >= 0;
  116. }
  117. // get best local address for a particular peer as a CAddress
  118. CAddress GetLocalAddress(const CNetAddr *paddrPeer)
  119. {
  120. CAddress ret(CService("0.0.0.0",0),0);
  121. CService addr;
  122. if (GetLocal(addr, paddrPeer))
  123. {
  124. ret = CAddress(addr);
  125. ret.nServices = nLocalServices;
  126. ret.nTime = GetAdjustedTime();
  127. }
  128. return ret;
  129. }
  130. bool RecvLine(SOCKET hSocket, string& strLine)
  131. {
  132. strLine = "";
  133. while (true)
  134. {
  135. char c;
  136. int nBytes = recv(hSocket, &c, 1, 0);
  137. if (nBytes > 0)
  138. {
  139. if (c == '\n')
  140. continue;
  141. if (c == '\r')
  142. return true;
  143. strLine += c;
  144. if (strLine.size() >= 9000)
  145. return true;
  146. }
  147. else if (nBytes <= 0)
  148. {
  149. boost::this_thread::interruption_point();
  150. if (nBytes < 0)
  151. {
  152. int nErr = WSAGetLastError();
  153. if (nErr == WSAEMSGSIZE)
  154. continue;
  155. if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
  156. {
  157. MilliSleep(10);
  158. continue;
  159. }
  160. }
  161. if (!strLine.empty())
  162. return true;
  163. if (nBytes == 0)
  164. {
  165. // socket closed
  166. LogPrint("net", "socket closed\n");
  167. return false;
  168. }
  169. else
  170. {
  171. // socket error
  172. int nErr = WSAGetLastError();
  173. LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
  174. return false;
  175. }
  176. }
  177. }
  178. }
  179. // used when scores of local addresses may have changed
  180. // pushes better local address to peers
  181. void static AdvertizeLocal()
  182. {
  183. LOCK(cs_vNodes);
  184. BOOST_FOREACH(CNode* pnode, vNodes)
  185. {
  186. if (pnode->fSuccessfullyConnected)
  187. {
  188. CAddress addrLocal = GetLocalAddress(&pnode->addr);
  189. if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
  190. {
  191. pnode->PushAddress(addrLocal);
  192. pnode->addrLocal = addrLocal;
  193. }
  194. }
  195. }
  196. }
  197. void SetReachable(enum Network net, bool fFlag)
  198. {
  199. LOCK(cs_mapLocalHost);
  200. vfReachable[net] = fFlag;
  201. if (net == NET_IPV6 && fFlag)
  202. vfReachable[NET_IPV4] = true;
  203. }
  204. // learn a new local address
  205. bool AddLocal(const CService& addr, int nScore)
  206. {
  207. if (!addr.IsRoutable())
  208. return false;
  209. if (!fDiscover && nScore < LOCAL_MANUAL)
  210. return false;
  211. if (IsLimited(addr))
  212. return false;
  213. LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
  214. {
  215. LOCK(cs_mapLocalHost);
  216. bool fAlready = mapLocalHost.count(addr) > 0;
  217. LocalServiceInfo &info = mapLocalHost[addr];
  218. if (!fAlready || nScore >= info.nScore) {
  219. info.nScore = nScore + (fAlready ? 1 : 0);
  220. info.nPort = addr.GetPort();
  221. }
  222. SetReachable(addr.GetNetwork());
  223. }
  224. AdvertizeLocal();
  225. return true;
  226. }
  227. bool AddLocal(const CNetAddr &addr, int nScore)
  228. {
  229. return AddLocal(CService(addr, GetListenPort()), nScore);
  230. }
  231. /** Make a particular network entirely off-limits (no automatic connects to it) */
  232. void SetLimited(enum Network net, bool fLimited)
  233. {
  234. if (net == NET_UNROUTABLE)
  235. return;
  236. LOCK(cs_mapLocalHost);
  237. vfLimited[net] = fLimited;
  238. }
  239. bool IsLimited(enum Network net)
  240. {
  241. LOCK(cs_mapLocalHost);
  242. return vfLimited[net];
  243. }
  244. bool IsLimited(const CNetAddr &addr)
  245. {
  246. return IsLimited(addr.GetNetwork());
  247. }
  248. /** vote for a local address */
  249. bool SeenLocal(const CService& addr)
  250. {
  251. {
  252. LOCK(cs_mapLocalHost);
  253. if (mapLocalHost.count(addr) == 0)
  254. return false;
  255. mapLocalHost[addr].nScore++;
  256. }
  257. AdvertizeLocal();
  258. return true;
  259. }
  260. /** check whether a given address is potentially local */
  261. bool IsLocal(const CService& addr)
  262. {
  263. LOCK(cs_mapLocalHost);
  264. return mapLocalHost.count(addr) > 0;
  265. }
  266. /** check whether a given network is one we can probably connect to */
  267. bool IsReachable(enum Network net)
  268. {
  269. LOCK(cs_mapLocalHost);
  270. return vfReachable[net] && !vfLimited[net];
  271. }
  272. /** check whether a given address is in a network we can probably connect to */
  273. bool IsReachable(const CNetAddr& addr)
  274. {
  275. enum Network net = addr.GetNetwork();
  276. return IsReachable(net);
  277. }
  278. bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
  279. {
  280. SOCKET hSocket;
  281. if (!ConnectSocket(addrConnect, hSocket))
  282. return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString());
  283. send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
  284. string strLine;
  285. while (RecvLine(hSocket, strLine))
  286. {
  287. if (strLine.empty()) // HTTP response is separated from headers by blank line
  288. {
  289. while (true)
  290. {
  291. if (!RecvLine(hSocket, strLine))
  292. {
  293. CloseSocket(hSocket);
  294. return false;
  295. }
  296. if (pszKeyword == NULL)
  297. break;
  298. if (strLine.find(pszKeyword) != string::npos)
  299. {
  300. strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
  301. break;
  302. }
  303. }
  304. CloseSocket(hSocket);
  305. if (strLine.find("<") != string::npos)
  306. strLine = strLine.substr(0, strLine.find("<"));
  307. strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
  308. while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
  309. strLine.resize(strLine.size()-1);
  310. CService addr(strLine,0,true);
  311. LogPrintf("GetMyExternalIP() received [%s] %s\n", strLine, addr.ToString());
  312. if (!addr.IsValid() || !addr.IsRoutable())
  313. return false;
  314. ipRet.SetIP(addr);
  315. return true;
  316. }
  317. }
  318. CloseSocket(hSocket);
  319. return error("GetMyExternalIP() : connection closed");
  320. }
  321. bool GetMyExternalIP(CNetAddr& ipRet)
  322. {
  323. CService addrConnect;
  324. const char* pszGet;
  325. const char* pszKeyword;
  326. for (int nLookup = 0; nLookup <= 1; nLookup++)
  327. for (int nHost = 1; nHost <= 1; nHost++)
  328. {
  329. // We should be phasing out our use of sites like these. If we need
  330. // replacements, we should ask for volunteers to put this simple
  331. // php file on their web server that prints the client IP:
  332. // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
  333. if (nHost == 1)
  334. {
  335. addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
  336. if (nLookup == 1)
  337. {
  338. CService addrIP("checkip.dyndns.org", 80, true);
  339. if (addrIP.IsValid())
  340. addrConnect = addrIP;
  341. }
  342. pszGet = "GET / HTTP/1.1\r\n"
  343. "Host: checkip.dyndns.org\r\n"
  344. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  345. "Connection: close\r\n"
  346. "\r\n";
  347. pszKeyword = "Address:";
  348. }
  349. if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
  350. return true;
  351. }
  352. return false;
  353. }
  354. void ThreadGetMyExternalIP()
  355. {
  356. CNetAddr addrLocalHost;
  357. if (GetMyExternalIP(addrLocalHost))
  358. {
  359. LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP());
  360. AddLocal(addrLocalHost, LOCAL_HTTP);
  361. }
  362. }
  363. void AddressCurrentlyConnected(const CService& addr)
  364. {
  365. addrman.Connected(addr);
  366. }
  367. uint64_t CNode::nTotalBytesRecv = 0;
  368. uint64_t CNode::nTotalBytesSent = 0;
  369. CCriticalSection CNode::cs_totalBytesRecv;
  370. CCriticalSection CNode::cs_totalBytesSent;
  371. CNode* FindNode(const CNetAddr& ip)
  372. {
  373. LOCK(cs_vNodes);
  374. BOOST_FOREACH(CNode* pnode, vNodes)
  375. if ((CNetAddr)pnode->addr == ip)
  376. return (pnode);
  377. return NULL;
  378. }
  379. CNode* FindNode(const std::string& addrName)
  380. {
  381. LOCK(cs_vNodes);
  382. BOOST_FOREACH(CNode* pnode, vNodes)
  383. if (pnode->addrName == addrName)
  384. return (pnode);
  385. return NULL;
  386. }
  387. CNode* FindNode(const CService& addr)
  388. {
  389. LOCK(cs_vNodes);
  390. BOOST_FOREACH(CNode* pnode, vNodes)
  391. if ((CService)pnode->addr == addr)
  392. return (pnode);
  393. return NULL;
  394. }
  395. CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
  396. {
  397. if (pszDest == NULL) {
  398. if (IsLocal(addrConnect))
  399. return NULL;
  400. // Look for an existing connection
  401. CNode* pnode = FindNode((CService)addrConnect);
  402. if (pnode)
  403. {
  404. pnode->AddRef();
  405. return pnode;
  406. }
  407. }
  408. /// debug print
  409. LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
  410. pszDest ? pszDest : addrConnect.ToString(),
  411. pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
  412. // Connect
  413. SOCKET hSocket;
  414. if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
  415. {
  416. addrman.Attempt(addrConnect);
  417. // Add node
  418. CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
  419. pnode->AddRef();
  420. {
  421. LOCK(cs_vNodes);
  422. vNodes.push_back(pnode);
  423. }
  424. pnode->nTimeConnected = GetTime();
  425. return pnode;
  426. }
  427. return NULL;
  428. }
  429. void CNode::CloseSocketDisconnect()
  430. {
  431. fDisconnect = true;
  432. if (hSocket != INVALID_SOCKET)
  433. {
  434. LogPrint("net", "disconnecting peer=%d\n", id);
  435. CloseSocket(hSocket);
  436. }
  437. // in case this fails, we'll empty the recv buffer when the CNode is deleted
  438. TRY_LOCK(cs_vRecvMsg, lockRecv);
  439. if (lockRecv)
  440. vRecvMsg.clear();
  441. }
  442. void CNode::PushVersion()
  443. {
  444. int nBestHeight = g_signals.GetHeight().get_value_or(0);
  445. /// when NTP implemented, change to just nTime = GetAdjustedTime()
  446. int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
  447. CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
  448. CAddress addrMe = GetLocalAddress(&addr);
  449. GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
  450. if (fLogIPs)
  451. LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
  452. else
  453. LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
  454. PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
  455. nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
  456. }
  457. std::map<CNetAddr, int64_t> CNode::setBanned;
  458. CCriticalSection CNode::cs_setBanned;
  459. void CNode::ClearBanned()
  460. {
  461. setBanned.clear();
  462. }
  463. bool CNode::IsBanned(CNetAddr ip)
  464. {
  465. bool fResult = false;
  466. {
  467. LOCK(cs_setBanned);
  468. std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
  469. if (i != setBanned.end())
  470. {
  471. int64_t t = (*i).second;
  472. if (GetTime() < t)
  473. fResult = true;
  474. }
  475. }
  476. return fResult;
  477. }
  478. bool CNode::Ban(const CNetAddr &addr) {
  479. int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
  480. {
  481. LOCK(cs_setBanned);
  482. if (setBanned[addr] < banTime)
  483. setBanned[addr] = banTime;
  484. }
  485. return true;
  486. }
  487. std::vector<CSubNet> CNode::vWhitelistedRange;
  488. CCriticalSection CNode::cs_vWhitelistedRange;
  489. bool CNode::IsWhitelistedRange(const CNetAddr &addr) {
  490. LOCK(cs_vWhitelistedRange);
  491. BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
  492. if (subnet.Match(addr))
  493. return true;
  494. }
  495. return false;
  496. }
  497. void CNode::AddWhitelistedRange(const CSubNet &subnet) {
  498. LOCK(cs_vWhitelistedRange);
  499. vWhitelistedRange.push_back(subnet);
  500. }
  501. #undef X
  502. #define X(name) stats.name = name
  503. void CNode::copyStats(CNodeStats &stats)
  504. {
  505. stats.nodeid = this->GetId();
  506. X(nServices);
  507. X(nLastSend);
  508. X(nLastRecv);
  509. X(nTimeConnected);
  510. X(addrName);
  511. X(nVersion);
  512. X(cleanSubVer);
  513. X(fInbound);
  514. X(nStartingHeight);
  515. X(nSendBytes);
  516. X(nRecvBytes);
  517. X(fWhitelisted);
  518. // It is common for nodes with good ping times to suddenly become lagged,
  519. // due to a new block arriving or other large transfer.
  520. // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
  521. // since pingtime does not update until the ping is complete, which might take a while.
  522. // So, if a ping is taking an unusually long time in flight,
  523. // the caller can immediately detect that this is happening.
  524. int64_t nPingUsecWait = 0;
  525. if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
  526. nPingUsecWait = GetTimeMicros() - nPingUsecStart;
  527. }
  528. // 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 :)
  529. stats.dPingTime = (((double)nPingUsecTime) / 1e6);
  530. stats.dPingWait = (((double)nPingUsecWait) / 1e6);
  531. // Leave string empty if addrLocal invalid (not filled in yet)
  532. stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
  533. }
  534. #undef X
  535. // requires LOCK(cs_vRecvMsg)
  536. bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
  537. {
  538. while (nBytes > 0) {
  539. // get current incomplete message, or create a new one
  540. if (vRecvMsg.empty() ||
  541. vRecvMsg.back().complete())
  542. vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
  543. CNetMessage& msg = vRecvMsg.back();
  544. // absorb network data
  545. int handled;
  546. if (!msg.in_data)
  547. handled = msg.readHeader(pch, nBytes);
  548. else
  549. handled = msg.readData(pch, nBytes);
  550. if (handled < 0)
  551. return false;
  552. pch += handled;
  553. nBytes -= handled;
  554. if (msg.complete())
  555. msg.nTime = GetTimeMicros();
  556. }
  557. return true;
  558. }
  559. int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
  560. {
  561. // copy data to temporary parsing buffer
  562. unsigned int nRemaining = 24 - nHdrPos;
  563. unsigned int nCopy = std::min(nRemaining, nBytes);
  564. memcpy(&hdrbuf[nHdrPos], pch, nCopy);
  565. nHdrPos += nCopy;
  566. // if header incomplete, exit
  567. if (nHdrPos < 24)
  568. return nCopy;
  569. // deserialize to CMessageHeader
  570. try {
  571. hdrbuf >> hdr;
  572. }
  573. catch (const std::exception &) {
  574. return -1;
  575. }
  576. // reject messages larger than MAX_SIZE
  577. if (hdr.nMessageSize > MAX_SIZE)
  578. return -1;
  579. // switch state to reading message data
  580. in_data = true;
  581. return nCopy;
  582. }
  583. int CNetMessage::readData(const char *pch, unsigned int nBytes)
  584. {
  585. unsigned int nRemaining = hdr.nMessageSize - nDataPos;
  586. unsigned int nCopy = std::min(nRemaining, nBytes);
  587. if (vRecv.size() < nDataPos + nCopy) {
  588. // Allocate up to 256 KiB ahead, but never more than the total message size.
  589. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
  590. }
  591. memcpy(&vRecv[nDataPos], pch, nCopy);
  592. nDataPos += nCopy;
  593. return nCopy;
  594. }
  595. // requires LOCK(cs_vSend)
  596. void SocketSendData(CNode *pnode)
  597. {
  598. std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
  599. while (it != pnode->vSendMsg.end()) {
  600. const CSerializeData &data = *it;
  601. assert(data.size() > pnode->nSendOffset);
  602. int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
  603. if (nBytes > 0) {
  604. pnode->nLastSend = GetTime();
  605. pnode->nSendBytes += nBytes;
  606. pnode->nSendOffset += nBytes;
  607. pnode->RecordBytesSent(nBytes);
  608. if (pnode->nSendOffset == data.size()) {
  609. pnode->nSendOffset = 0;
  610. pnode->nSendSize -= data.size();
  611. it++;
  612. } else {
  613. // could not send full message; stop sending more
  614. break;
  615. }
  616. } else {
  617. if (nBytes < 0) {
  618. // error
  619. int nErr = WSAGetLastError();
  620. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  621. {
  622. LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
  623. pnode->CloseSocketDisconnect();
  624. }
  625. }
  626. // couldn't send anything at all
  627. break;
  628. }
  629. }
  630. if (it == pnode->vSendMsg.end()) {
  631. assert(pnode->nSendOffset == 0);
  632. assert(pnode->nSendSize == 0);
  633. }
  634. pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
  635. }
  636. static list<CNode*> vNodesDisconnected;
  637. void ThreadSocketHandler()
  638. {
  639. unsigned int nPrevNodeCount = 0;
  640. while (true)
  641. {
  642. //
  643. // Disconnect nodes
  644. //
  645. {
  646. LOCK(cs_vNodes);
  647. // Disconnect unused nodes
  648. vector<CNode*> vNodesCopy = vNodes;
  649. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  650. {
  651. if (pnode->fDisconnect ||
  652. (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
  653. {
  654. // remove from vNodes
  655. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  656. // release outbound grant (if any)
  657. pnode->grantOutbound.Release();
  658. // close socket and cleanup
  659. pnode->CloseSocketDisconnect();
  660. // hold in disconnected pool until all refs are released
  661. if (pnode->fNetworkNode || pnode->fInbound)
  662. pnode->Release();
  663. vNodesDisconnected.push_back(pnode);
  664. }
  665. }
  666. }
  667. {
  668. // Delete disconnected nodes
  669. list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  670. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  671. {
  672. // wait until threads are done using it
  673. if (pnode->GetRefCount() <= 0)
  674. {
  675. bool fDelete = false;
  676. {
  677. TRY_LOCK(pnode->cs_vSend, lockSend);
  678. if (lockSend)
  679. {
  680. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  681. if (lockRecv)
  682. {
  683. TRY_LOCK(pnode->cs_inventory, lockInv);
  684. if (lockInv)
  685. fDelete = true;
  686. }
  687. }
  688. }
  689. if (fDelete)
  690. {
  691. vNodesDisconnected.remove(pnode);
  692. delete pnode;
  693. }
  694. }
  695. }
  696. }
  697. if(vNodes.size() != nPrevNodeCount) {
  698. nPrevNodeCount = vNodes.size();
  699. uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
  700. }
  701. //
  702. // Find which sockets have data to receive
  703. //
  704. struct timeval timeout;
  705. timeout.tv_sec = 0;
  706. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  707. fd_set fdsetRecv;
  708. fd_set fdsetSend;
  709. fd_set fdsetError;
  710. FD_ZERO(&fdsetRecv);
  711. FD_ZERO(&fdsetSend);
  712. FD_ZERO(&fdsetError);
  713. SOCKET hSocketMax = 0;
  714. bool have_fds = false;
  715. BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
  716. FD_SET(hListenSocket.socket, &fdsetRecv);
  717. hSocketMax = max(hSocketMax, hListenSocket.socket);
  718. have_fds = true;
  719. }
  720. {
  721. LOCK(cs_vNodes);
  722. BOOST_FOREACH(CNode* pnode, vNodes)
  723. {
  724. if (pnode->hSocket == INVALID_SOCKET)
  725. continue;
  726. FD_SET(pnode->hSocket, &fdsetError);
  727. hSocketMax = max(hSocketMax, pnode->hSocket);
  728. have_fds = true;
  729. // Implement the following logic:
  730. // * If there is data to send, select() for sending data. As this only
  731. // happens when optimistic write failed, we choose to first drain the
  732. // write buffer in this case before receiving more. This avoids
  733. // needlessly queueing received data, if the remote peer is not themselves
  734. // receiving data. This means properly utilizing TCP flow control signalling.
  735. // * Otherwise, if there is no (complete) message in the receive buffer,
  736. // or there is space left in the buffer, select() for receiving data.
  737. // * (if neither of the above applies, there is certainly one message
  738. // in the receiver buffer ready to be processed).
  739. // Together, that means that at least one of the following is always possible,
  740. // so we don't deadlock:
  741. // * We send some data.
  742. // * We wait for data to be received (and disconnect after timeout).
  743. // * We process a message in the buffer (message handler thread).
  744. {
  745. TRY_LOCK(pnode->cs_vSend, lockSend);
  746. if (lockSend && !pnode->vSendMsg.empty()) {
  747. FD_SET(pnode->hSocket, &fdsetSend);
  748. continue;
  749. }
  750. }
  751. {
  752. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  753. if (lockRecv && (
  754. pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
  755. pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
  756. FD_SET(pnode->hSocket, &fdsetRecv);
  757. }
  758. }
  759. }
  760. int nSelect = select(have_fds ? hSocketMax + 1 : 0,
  761. &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  762. boost::this_thread::interruption_point();
  763. if (nSelect == SOCKET_ERROR)
  764. {
  765. if (have_fds)
  766. {
  767. int nErr = WSAGetLastError();
  768. LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
  769. for (unsigned int i = 0; i <= hSocketMax; i++)
  770. FD_SET(i, &fdsetRecv);
  771. }
  772. FD_ZERO(&fdsetSend);
  773. FD_ZERO(&fdsetError);
  774. MilliSleep(timeout.tv_usec/1000);
  775. }
  776. //
  777. // Accept new connections
  778. //
  779. BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
  780. {
  781. if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
  782. {
  783. struct sockaddr_storage sockaddr;
  784. socklen_t len = sizeof(sockaddr);
  785. SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
  786. CAddress addr;
  787. int nInbound = 0;
  788. if (hSocket != INVALID_SOCKET)
  789. if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
  790. LogPrintf("Warning: Unknown socket family\n");
  791. bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
  792. {
  793. LOCK(cs_vNodes);
  794. BOOST_FOREACH(CNode* pnode, vNodes)
  795. if (pnode->fInbound)
  796. nInbound++;
  797. }
  798. if (hSocket == INVALID_SOCKET)
  799. {
  800. int nErr = WSAGetLastError();
  801. if (nErr != WSAEWOULDBLOCK)
  802. LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
  803. }
  804. else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
  805. {
  806. CloseSocket(hSocket);
  807. }
  808. else if (CNode::IsBanned(addr) && !whitelisted)
  809. {
  810. LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
  811. CloseSocket(hSocket);
  812. }
  813. else
  814. {
  815. CNode* pnode = new CNode(hSocket, addr, "", true);
  816. pnode->AddRef();
  817. pnode->fWhitelisted = whitelisted;
  818. {
  819. LOCK(cs_vNodes);
  820. vNodes.push_back(pnode);
  821. }
  822. }
  823. }
  824. }
  825. //
  826. // Service each socket
  827. //
  828. vector<CNode*> vNodesCopy;
  829. {
  830. LOCK(cs_vNodes);
  831. vNodesCopy = vNodes;
  832. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  833. pnode->AddRef();
  834. }
  835. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  836. {
  837. boost::this_thread::interruption_point();
  838. //
  839. // Receive
  840. //
  841. if (pnode->hSocket == INVALID_SOCKET)
  842. continue;
  843. if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
  844. {
  845. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  846. if (lockRecv)
  847. {
  848. {
  849. // typical socket buffer is 8K-64K
  850. char pchBuf[0x10000];
  851. int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  852. if (nBytes > 0)
  853. {
  854. if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
  855. pnode->CloseSocketDisconnect();
  856. pnode->nLastRecv = GetTime();
  857. pnode->nRecvBytes += nBytes;
  858. pnode->RecordBytesRecv(nBytes);
  859. }
  860. else if (nBytes == 0)
  861. {
  862. // socket closed gracefully
  863. if (!pnode->fDisconnect)
  864. LogPrint("net", "socket closed\n");
  865. pnode->CloseSocketDisconnect();
  866. }
  867. else if (nBytes < 0)
  868. {
  869. // error
  870. int nErr = WSAGetLastError();
  871. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  872. {
  873. if (!pnode->fDisconnect)
  874. LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
  875. pnode->CloseSocketDisconnect();
  876. }
  877. }
  878. }
  879. }
  880. }
  881. //
  882. // Send
  883. //
  884. if (pnode->hSocket == INVALID_SOCKET)
  885. continue;
  886. if (FD_ISSET(pnode->hSocket, &fdsetSend))
  887. {
  888. TRY_LOCK(pnode->cs_vSend, lockSend);
  889. if (lockSend)
  890. SocketSendData(pnode);
  891. }
  892. //
  893. // Inactivity checking
  894. //
  895. int64_t nTime = GetTime();
  896. if (nTime - pnode->nTimeConnected > 60)
  897. {
  898. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  899. {
  900. LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
  901. pnode->fDisconnect = true;
  902. }
  903. else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
  904. {
  905. LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
  906. pnode->fDisconnect = true;
  907. }
  908. else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
  909. {
  910. LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
  911. pnode->fDisconnect = true;
  912. }
  913. else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
  914. {
  915. LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
  916. pnode->fDisconnect = true;
  917. }
  918. }
  919. }
  920. {
  921. LOCK(cs_vNodes);
  922. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  923. pnode->Release();
  924. }
  925. }
  926. }
  927. #ifdef USE_UPNP
  928. void ThreadMapPort()
  929. {
  930. std::string port = strprintf("%u", GetListenPort());
  931. const char * multicastif = 0;
  932. const char * minissdpdpath = 0;
  933. struct UPNPDev * devlist = 0;
  934. char lanaddr[64];
  935. #ifndef UPNPDISCOVER_SUCCESS
  936. /* miniupnpc 1.5 */
  937. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
  938. #else
  939. /* miniupnpc 1.6 */
  940. int error = 0;
  941. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
  942. #endif
  943. struct UPNPUrls urls;
  944. struct IGDdatas data;
  945. int r;
  946. r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
  947. if (r == 1)
  948. {
  949. if (fDiscover) {
  950. char externalIPAddress[40];
  951. r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
  952. if(r != UPNPCOMMAND_SUCCESS)
  953. LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
  954. else
  955. {
  956. if(externalIPAddress[0])
  957. {
  958. LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
  959. AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
  960. }
  961. else
  962. LogPrintf("UPnP: GetExternalIPAddress failed.\n");
  963. }
  964. }
  965. string strDesc = "Bitcoin " + FormatFullVersion();
  966. try {
  967. while (true) {
  968. #ifndef UPNPDISCOVER_SUCCESS
  969. /* miniupnpc 1.5 */
  970. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  971. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
  972. #else
  973. /* miniupnpc 1.6 */
  974. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  975. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
  976. #endif
  977. if(r!=UPNPCOMMAND_SUCCESS)
  978. LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  979. port, port, lanaddr, r, strupnperror(r));
  980. else
  981. LogPrintf("UPnP Port Mapping successful.\n");;
  982. MilliSleep(20*60*1000); // Refresh every 20 minutes
  983. }
  984. }
  985. catch (boost::thread_interrupted)
  986. {
  987. r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
  988. LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
  989. freeUPNPDevlist(devlist); devlist = 0;
  990. FreeUPNPUrls(&urls);
  991. throw;
  992. }
  993. } else {
  994. LogPrintf("No valid UPnP IGDs found\n");
  995. freeUPNPDevlist(devlist); devlist = 0;
  996. if (r != 0)
  997. FreeUPNPUrls(&urls);
  998. }
  999. }
  1000. void MapPort(bool fUseUPnP)
  1001. {
  1002. static boost::thread* upnp_thread = NULL;
  1003. if (fUseUPnP)
  1004. {
  1005. if (upnp_thread) {
  1006. upnp_thread->interrupt();
  1007. upnp_thread->join();
  1008. delete upnp_thread;
  1009. }
  1010. upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
  1011. }
  1012. else if (upnp_thread) {
  1013. upnp_thread->interrupt();
  1014. upnp_thread->join();
  1015. delete upnp_thread;
  1016. upnp_thread = NULL;
  1017. }
  1018. }
  1019. #else
  1020. void MapPort(bool)
  1021. {
  1022. // Intentionally left blank.
  1023. }
  1024. #endif
  1025. void ThreadDNSAddressSeed()
  1026. {
  1027. // goal: only query DNS seeds if address need is acute
  1028. if ((addrman.size() > 0) &&
  1029. (!GetBoolArg("-forcednsseed", false))) {
  1030. MilliSleep(11 * 1000);
  1031. LOCK(cs_vNodes);
  1032. if (vNodes.size() >= 2) {
  1033. LogPrintf("P2P peers available. Skipped DNS seeding.\n");
  1034. return;
  1035. }
  1036. }
  1037. const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
  1038. int found = 0;
  1039. LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
  1040. BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
  1041. if (HaveNameProxy()) {
  1042. AddOneShot(seed.host);
  1043. } else {
  1044. vector<CNetAddr> vIPs;
  1045. vector<CAddress> vAdd;
  1046. if (LookupHost(seed.host.c_str(), vIPs))
  1047. {
  1048. BOOST_FOREACH(CNetAddr& ip, vIPs)
  1049. {
  1050. int nOneDay = 24*3600;
  1051. CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
  1052. addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
  1053. vAdd.push_back(addr);
  1054. found++;
  1055. }
  1056. }
  1057. addrman.Add(vAdd, CNetAddr(seed.name, true));
  1058. }
  1059. }
  1060. LogPrintf("%d addresses found from DNS seeds\n", found);
  1061. }
  1062. void DumpAddresses()
  1063. {
  1064. int64_t nStart = GetTimeMillis();
  1065. CAddrDB adb;
  1066. adb.Write(addrman);
  1067. LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
  1068. addrman.size(), GetTimeMillis() - nStart);
  1069. }
  1070. void static ProcessOneShot()
  1071. {
  1072. string strDest;
  1073. {
  1074. LOCK(cs_vOneShots);
  1075. if (vOneShots.empty())
  1076. return;
  1077. strDest = vOneShots.front();
  1078. vOneShots.pop_front();
  1079. }
  1080. CAddress addr;
  1081. CSemaphoreGrant grant(*semOutbound, true);
  1082. if (grant) {
  1083. if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
  1084. AddOneShot(strDest);
  1085. }
  1086. }
  1087. void ThreadOpenConnections()
  1088. {
  1089. // Connect to specific addresses
  1090. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
  1091. {
  1092. for (int64_t nLoop = 0;; nLoop++)
  1093. {
  1094. ProcessOneShot();
  1095. BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
  1096. {
  1097. CAddress addr;
  1098. OpenNetworkConnection(addr, NULL, strAddr.c_str());
  1099. for (int i = 0; i < 10 && i < nLoop; i++)
  1100. {
  1101. MilliSleep(500);
  1102. }
  1103. }
  1104. MilliSleep(500);
  1105. }
  1106. }
  1107. // Initiate network connections
  1108. int64_t nStart = GetTime();
  1109. while (true)
  1110. {
  1111. ProcessOneShot();
  1112. MilliSleep(500);
  1113. CSemaphoreGrant grant(*semOutbound);
  1114. boost::this_thread::interruption_point();
  1115. // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
  1116. if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
  1117. static bool done = false;
  1118. if (!done) {
  1119. LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
  1120. addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
  1121. done = true;
  1122. }
  1123. }
  1124. //
  1125. // Choose an address to connect to based on most recently seen
  1126. //
  1127. CAddress addrConnect;
  1128. // Only connect out to one peer per network group (/16 for IPv4).
  1129. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
  1130. int nOutbound = 0;
  1131. set<vector<unsigned char> > setConnected;
  1132. {
  1133. LOCK(cs_vNodes);
  1134. BOOST_FOREACH(CNode* pnode, vNodes) {
  1135. if (!pnode->fInbound) {
  1136. setConnected.insert(pnode->addr.GetGroup());
  1137. nOutbound++;
  1138. }
  1139. }
  1140. }
  1141. int64_t nANow = GetAdjustedTime();
  1142. int nTries = 0;
  1143. while (true)
  1144. {
  1145. // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
  1146. CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
  1147. // if we selected an invalid address, restart
  1148. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1149. break;
  1150. // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
  1151. // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
  1152. // already-connected network ranges, ...) before trying new addrman addresses.
  1153. nTries++;
  1154. if (nTries > 100)
  1155. break;
  1156. if (IsLimited(addr))
  1157. continue;
  1158. // only consider very recently tried nodes after 30 failed attempts
  1159. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1160. continue;
  1161. // do not allow non-default ports, unless after 50 invalid addresses selected already
  1162. if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
  1163. continue;
  1164. addrConnect = addr;
  1165. break;
  1166. }
  1167. if (addrConnect.IsValid())
  1168. OpenNetworkConnection(addrConnect, &grant);
  1169. }
  1170. }
  1171. void ThreadOpenAddedConnections()
  1172. {
  1173. {
  1174. LOCK(cs_vAddedNodes);
  1175. vAddedNodes = mapMultiArgs["-addnode"];
  1176. }
  1177. if (HaveNameProxy()) {
  1178. while(true) {
  1179. list<string> lAddresses(0);
  1180. {
  1181. LOCK(cs_vAddedNodes);
  1182. BOOST_FOREACH(string& strAddNode, vAddedNodes)
  1183. lAddresses.push_back(strAddNode);
  1184. }
  1185. BOOST_FOREACH(string& strAddNode, lAddresses) {
  1186. CAddress addr;
  1187. CSemaphoreGrant grant(*semOutbound);
  1188. OpenNetworkConnection(addr, &grant, strAddNode.c_str());
  1189. MilliSleep(500);
  1190. }
  1191. MilliSleep(120000); // Retry every 2 minutes
  1192. }
  1193. }
  1194. for (unsigned int i = 0; true; i++)
  1195. {
  1196. list<string> lAddresses(0);
  1197. {
  1198. LOCK(cs_vAddedNodes);
  1199. BOOST_FOREACH(string& strAddNode, vAddedNodes)
  1200. lAddresses.push_back(strAddNode);
  1201. }
  1202. list<vector<CService> > lservAddressesToAdd(0);
  1203. BOOST_FOREACH(string& strAddNode, lAddresses)
  1204. {
  1205. vector<CService> vservNode(0);
  1206. if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
  1207. {
  1208. lservAddressesToAdd.push_back(vservNode);
  1209. {
  1210. LOCK(cs_setservAddNodeAddresses);
  1211. BOOST_FOREACH(CService& serv, vservNode)
  1212. setservAddNodeAddresses.insert(serv);
  1213. }
  1214. }
  1215. }
  1216. // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
  1217. // (keeping in mind that addnode entries can have many IPs if fNameLookup)
  1218. {
  1219. LOCK(cs_vNodes);
  1220. BOOST_FOREACH(CNode* pnode, vNodes)
  1221. for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
  1222. BOOST_FOREACH(CService& addrNode, *(it))
  1223. if (pnode->addr == addrNode)
  1224. {
  1225. it = lservAddressesToAdd.erase(it);
  1226. it--;
  1227. break;
  1228. }
  1229. }
  1230. BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
  1231. {
  1232. CSemaphoreGrant grant(*semOutbound);
  1233. OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
  1234. MilliSleep(500);
  1235. }
  1236. MilliSleep(120000); // Retry every 2 minutes
  1237. }
  1238. }
  1239. // if successful, this moves the passed grant to the constructed node
  1240. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot)
  1241. {
  1242. //
  1243. // Initiate outbound network connection
  1244. //
  1245. boost::this_thread::interruption_point();
  1246. if (!pszDest) {
  1247. if (IsLocal(addrConnect) ||
  1248. FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
  1249. FindNode(addrConnect.ToStringIPPort()))
  1250. return false;
  1251. } else if (FindNode(pszDest))
  1252. return false;
  1253. CNode* pnode = ConnectNode(addrConnect, pszDest);
  1254. boost::this_thread::interruption_point();
  1255. if (!pnode)
  1256. return false;
  1257. if (grantOutbound)
  1258. grantOutbound->MoveTo(pnode->grantOutbound);
  1259. pnode->fNetworkNode = true;
  1260. if (fOneShot)
  1261. pnode->fOneShot = true;
  1262. return true;
  1263. }
  1264. void ThreadMessageHandler()
  1265. {
  1266. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1267. while (true)
  1268. {
  1269. vector<CNode*> vNodesCopy;
  1270. {
  1271. LOCK(cs_vNodes);
  1272. vNodesCopy = vNodes;
  1273. BOOST_FOREACH(CNode* pnode, vNodesCopy) {
  1274. pnode->AddRef();
  1275. }
  1276. }
  1277. // Poll the connected nodes for messages
  1278. CNode* pnodeTrickle = NULL;
  1279. if (!vNodesCopy.empty())
  1280. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1281. bool fSleep = true;
  1282. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1283. {
  1284. if (pnode->fDisconnect)
  1285. continue;
  1286. // Receive messages
  1287. {
  1288. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  1289. if (lockRecv)
  1290. {
  1291. if (!g_signals.ProcessMessages(pnode))
  1292. pnode->CloseSocketDisconnect();
  1293. if (pnode->nSendSize < SendBufferSize())
  1294. {
  1295. if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
  1296. {
  1297. fSleep = false;
  1298. }
  1299. }
  1300. }
  1301. }
  1302. boost::this_thread::interruption_point();
  1303. // Send messages
  1304. {
  1305. TRY_LOCK(pnode->cs_vSend, lockSend);
  1306. if (lockSend)
  1307. g_signals.SendMessages(pnode, pnode == pnodeTrickle);
  1308. }
  1309. boost::this_thread::interruption_point();
  1310. }
  1311. {
  1312. LOCK(cs_vNodes);
  1313. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1314. pnode->Release();
  1315. }
  1316. if (fSleep)
  1317. MilliSleep(100);
  1318. }
  1319. }
  1320. bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted)
  1321. {
  1322. strError = "";
  1323. int nOne = 1;
  1324. // Create socket for listening for incoming connections
  1325. struct sockaddr_storage sockaddr;
  1326. socklen_t len = sizeof(sockaddr);
  1327. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1328. {
  1329. strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
  1330. LogPrintf("%s\n", strError);
  1331. return false;
  1332. }
  1333. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1334. if (hListenSocket == INVALID_SOCKET)
  1335. {
  1336. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
  1337. LogPrintf("%s\n", strError);
  1338. return false;
  1339. }
  1340. #ifndef WIN32
  1341. #ifdef SO_NOSIGPIPE
  1342. // Different way of disabling SIGPIPE on BSD
  1343. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1344. #endif
  1345. // Allow binding if the port is still in TIME_WAIT state after
  1346. // the program was closed and restarted. Not an issue on windows!
  1347. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1348. #endif
  1349. // Set to non-blocking, incoming connections will also inherit this
  1350. if (!SetSocketNonBlocking(hListenSocket, true)) {
  1351. strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
  1352. LogPrintf("%s\n", strError);
  1353. return false;
  1354. }
  1355. // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
  1356. // and enable it by default or not. Try to enable it, if possible.
  1357. if (addrBind.IsIPv6()) {
  1358. #ifdef IPV6_V6ONLY
  1359. #ifdef WIN32
  1360. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
  1361. #else
  1362. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1363. #endif
  1364. #endif
  1365. #ifdef WIN32
  1366. int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
  1367. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
  1368. #endif
  1369. }
  1370. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1371. {
  1372. int nErr = WSAGetLastError();
  1373. if (nErr == WSAEADDRINUSE)
  1374. strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin Core is probably already running."), addrBind.ToString());
  1375. else
  1376. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
  1377. LogPrintf("%s\n", strError);
  1378. CloseSocket(hListenSocket);
  1379. return false;
  1380. }
  1381. LogPrintf("Bound to %s\n", addrBind.ToString());
  1382. // Listen for incoming connections
  1383. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1384. {
  1385. strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
  1386. LogPrintf("%s\n", strError);
  1387. CloseSocket(hListenSocket);
  1388. return false;
  1389. }
  1390. vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
  1391. if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
  1392. AddLocal(addrBind, LOCAL_BIND);
  1393. return true;
  1394. }
  1395. void static Discover(boost::thread_group& threadGroup)
  1396. {
  1397. if (!fDiscover)
  1398. return;
  1399. #ifdef WIN32
  1400. // Get local host IP
  1401. char pszHostName[1000] = "";
  1402. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1403. {
  1404. vector<CNetAddr> vaddr;
  1405. if (LookupHost(pszHostName, vaddr))
  1406. {
  1407. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1408. {
  1409. AddLocal(addr, LOCAL_IF);
  1410. }
  1411. }
  1412. }
  1413. #else
  1414. // Get local host ip
  1415. struct ifaddrs* myaddrs;
  1416. if (getifaddrs(&myaddrs) == 0)
  1417. {
  1418. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1419. {
  1420. if (ifa->ifa_addr == NULL) continue;
  1421. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1422. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1423. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1424. if (ifa->ifa_addr->sa_family == AF_INET)
  1425. {
  1426. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1427. CNetAddr addr(s4->sin_addr);
  1428. if (AddLocal(addr, LOCAL_IF))
  1429. LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString());
  1430. }
  1431. else if (ifa->ifa_addr->sa_family == AF_INET6)
  1432. {
  1433. struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
  1434. CNetAddr addr(s6->sin6_addr);
  1435. if (AddLocal(addr, LOCAL_IF))
  1436. LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString());
  1437. }
  1438. }
  1439. freeifaddrs(myaddrs);
  1440. }
  1441. #endif
  1442. // Don't use external IPv4 discovery, when -onlynet="IPv6"
  1443. if (!IsLimited(NET_IPV4))
  1444. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "ext-ip", &ThreadGetMyExternalIP));
  1445. }
  1446. void StartNode(boost::thread_group& threadGroup)
  1447. {
  1448. uiInterface.InitMessage(_("Loading addresses..."));
  1449. // Load addresses for peers.dat
  1450. int64_t nStart = GetTimeMillis();
  1451. {
  1452. CAddrDB adb;
  1453. if (!adb.Read(addrman))
  1454. LogPrintf("Invalid or missing peers.dat; recreating\n");
  1455. }
  1456. LogPrintf("Loaded %i addresses from peers.dat %dms\n",
  1457. addrman.size(), GetTimeMillis() - nStart);
  1458. fAddressesInitialized = true;
  1459. if (semOutbound == NULL) {
  1460. // initialize semaphore
  1461. int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
  1462. semOutbound = new CSemaphore(nMaxOutbound);
  1463. }
  1464. if (pnodeLocalHost == NULL)
  1465. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
  1466. Discover(threadGroup);
  1467. //
  1468. // Start threads
  1469. //
  1470. if (!GetBoolArg("-dnsseed", true))
  1471. LogPrintf("DNS seeding disabled\n");
  1472. else
  1473. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
  1474. // Map ports with UPnP
  1475. MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
  1476. // Send and receive from sockets, accept connections
  1477. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
  1478. // Initiate outbound connections from -addnode
  1479. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
  1480. // Initiate outbound connections
  1481. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
  1482. // Process messages
  1483. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
  1484. // Dump network addresses
  1485. threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
  1486. }
  1487. bool StopNode()
  1488. {
  1489. LogPrintf("StopNode()\n");
  1490. MapPort(false);
  1491. if (semOutbound)
  1492. for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
  1493. semOutbound->post();
  1494. if (fAddressesInitialized)
  1495. {
  1496. DumpAddresses();
  1497. fAddressesInitialized = false;
  1498. }
  1499. return true;
  1500. }
  1501. class CNetCleanup
  1502. {
  1503. public:
  1504. CNetCleanup() {}
  1505. ~CNetCleanup()
  1506. {
  1507. // Close sockets
  1508. BOOST_FOREACH(CNode* pnode, vNodes)
  1509. if (pnode->hSocket != INVALID_SOCKET)
  1510. CloseSocket(pnode->hSocket);
  1511. BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
  1512. if (hListenSocket.socket != INVALID_SOCKET)
  1513. if (!CloseSocket(hListenSocket.socket))
  1514. LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
  1515. // clean up some globals (to help leak detection)
  1516. BOOST_FOREACH(CNode *pnode, vNodes)
  1517. delete pnode;
  1518. BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
  1519. delete pnode;
  1520. vNodes.clear();
  1521. vNodesDisconnected.clear();
  1522. vhListenSocket.clear();
  1523. delete semOutbound;
  1524. semOutbound = NULL;
  1525. delete pnodeLocalHost;
  1526. pnodeLocalHost = NULL;
  1527. #ifdef WIN32
  1528. // Shutdown Windows Sockets
  1529. WSACleanup();
  1530. #endif
  1531. }
  1532. }
  1533. instance_of_cnetcleanup;
  1534. void RelayTransaction(const CTransaction& tx)
  1535. {
  1536. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  1537. ss.reserve(10000);
  1538. ss << tx;
  1539. RelayTransaction(tx, ss);
  1540. }
  1541. void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
  1542. {
  1543. CInv inv(MSG_TX, tx.GetHash());
  1544. {
  1545. LOCK(cs_mapRelay);
  1546. // Expire old relay messages
  1547. while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
  1548. {
  1549. mapRelay.erase(vRelayExpiration.front().second);
  1550. vRelayExpiration.pop_front();
  1551. }
  1552. // Save original serialized message so newer versions are preserved
  1553. mapRelay.insert(std::make_pair(inv, ss));
  1554. vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
  1555. }
  1556. LOCK(cs_vNodes);
  1557. BOOST_FOREACH(CNode* pnode, vNodes)
  1558. {
  1559. if(!pnode->fRelayTxes)
  1560. continue;
  1561. LOCK(pnode->cs_filter);
  1562. if (pnode->pfilter)
  1563. {
  1564. if (pnode->pfilter->IsRelevantAndUpdate(tx))
  1565. pnode->PushInventory(inv);
  1566. } else
  1567. pnode->PushInventory(inv);
  1568. }
  1569. }
  1570. void CNode::RecordBytesRecv(uint64_t bytes)
  1571. {
  1572. LOCK(cs_totalBytesRecv);
  1573. nTotalBytesRecv += bytes;
  1574. }
  1575. void CNode::RecordBytesSent(uint64_t bytes)
  1576. {
  1577. LOCK(cs_totalBytesSent);
  1578. nTotalBytesSent += bytes;
  1579. }
  1580. uint64_t CNode::GetTotalBytesRecv()
  1581. {
  1582. LOCK(cs_totalBytesRecv);
  1583. return nTotalBytesRecv;
  1584. }
  1585. uint64_t CNode::GetTotalBytesSent()
  1586. {
  1587. LOCK(cs_totalBytesSent);
  1588. return nTotalBytesSent;
  1589. }
  1590. void CNode::Fuzz(int nChance)
  1591. {
  1592. if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
  1593. if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
  1594. switch (GetRand(3))
  1595. {
  1596. case 0:
  1597. // xor a random byte with a random value:
  1598. if (!ssSend.empty()) {
  1599. CDataStream::size_type pos = GetRand(ssSend.size());
  1600. ssSend[pos] ^= (unsigned char)(GetRand(256));
  1601. }
  1602. break;
  1603. case 1:
  1604. // delete a random byte:
  1605. if (!ssSend.empty()) {
  1606. CDataStream::size_type pos = GetRand(ssSend.size());
  1607. ssSend.erase(ssSend.begin()+pos);
  1608. }
  1609. break;
  1610. case 2:
  1611. // insert a random byte at a random position
  1612. {
  1613. CDataStream::size_type pos = GetRand(ssSend.size());
  1614. char ch = (char)GetRand(256);
  1615. ssSend.insert(ssSend.begin()+pos, ch);
  1616. }
  1617. break;
  1618. }
  1619. // Chance of more than one change half the time:
  1620. // (more changes exponentially less likely):
  1621. Fuzz(2);
  1622. }
  1623. //
  1624. // CAddrDB
  1625. //
  1626. CAddrDB::CAddrDB()
  1627. {
  1628. pathAddr = GetDataDir() / "peers.dat";
  1629. }
  1630. bool CAddrDB::Write(const CAddrMan& addr)
  1631. {
  1632. // Generate random temporary filename
  1633. unsigned short randv = 0;
  1634. GetRandBytes((unsigned char*)&randv, sizeof(randv));
  1635. std::string tmpfn = strprintf("peers.dat.%04x", randv);
  1636. // serialize addresses, checksum data up to that point, then append csum
  1637. CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
  1638. ssPeers << FLATDATA(Params().MessageStart());
  1639. ssPeers << addr;
  1640. uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
  1641. ssPeers << hash;
  1642. // open temp output file, and associate with CAutoFile
  1643. boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
  1644. FILE *file = fopen(pathTmp.string().c_str(), "wb");
  1645. CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
  1646. if (!fileout)
  1647. return error("%s : Failed to open file %s", __func__, pathTmp.string());
  1648. // Write and commit header, data
  1649. try {
  1650. fileout << ssPeers;
  1651. }
  1652. catch (std::exception &e) {
  1653. return error("%s : Serialize or I/O error - %s", __func__, e.what());
  1654. }
  1655. FileCommit(fileout);
  1656. fileout.fclose();
  1657. // replace existing peers.dat, if any, with new peers.dat.XXXX
  1658. if (!RenameOver(pathTmp, pathAddr))
  1659. return error("%s : Rename-into-place failed", __func__);
  1660. return true;
  1661. }
  1662. bool CAddrDB::Read(CAddrMan& addr)
  1663. {
  1664. // open input file, and associate with CAutoFile
  1665. FILE *file = fopen(pathAddr.string().c_str(), "rb");
  1666. CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
  1667. if (!filein)
  1668. return error("%s : Failed to open file %s", __func__, pathAddr.string());
  1669. // use file size to size memory buffer
  1670. int fileSize = boost::filesystem::file_size(pathAddr);
  1671. int dataSize = fileSize - sizeof(uint256);
  1672. // Don't try to resize to a negative number if file is small
  1673. if (dataSize < 0)
  1674. dataSize = 0;
  1675. vector<unsigned char> vchData;
  1676. vchData.resize(dataSize);
  1677. uint256 hashIn;
  1678. // read data and checksum from file
  1679. try {
  1680. filein.read((char *)&vchData[0], dataSize);
  1681. filein >> hashIn;
  1682. }
  1683. catch (std::exception &e) {
  1684. return error("%s : Deserialize or I/O error - %s", __func__, e.what());
  1685. }
  1686. filein.fclose();
  1687. CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
  1688. // verify stored checksum matches input data
  1689. uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
  1690. if (hashIn != hashTmp)
  1691. return error("%s : Checksum mismatch, data corrupted", __func__);
  1692. unsigned char pchMsgTmp[4];
  1693. try {
  1694. // de-serialize file header (network specific magic number) and ..
  1695. ssPeers >> FLATDATA(pchMsgTmp);
  1696. // ... verify the network matches ours
  1697. if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
  1698. return error("%s : Invalid network magic number", __func__);
  1699. // de-serialize address data into one CAddrMan object
  1700. ssPeers >> addr;
  1701. }
  1702. catch (std::exception &e) {
  1703. return error("%s : Deserialize or I/O error - %s", __func__, e.what());
  1704. }
  1705. return true;
  1706. }
  1707. unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
  1708. unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
  1709. CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
  1710. {
  1711. nServices = 0;
  1712. hSocket = hSocketIn;
  1713. nRecvVersion = INIT_PROTO_VERSION;
  1714. nLastSend = 0;
  1715. nLastRecv = 0;
  1716. nSendBytes = 0;
  1717. nRecvBytes = 0;
  1718. nTimeConnected = GetTime();
  1719. addr = addrIn;
  1720. addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
  1721. nVersion = 0;
  1722. strSubVer = "";
  1723. fWhitelisted = false;
  1724. fOneShot = false;
  1725. fClient = false; // set by version message
  1726. fInbound = fInboundIn;
  1727. fNetworkNode = false;
  1728. fSuccessfullyConnected = false;
  1729. fDisconnect = false;
  1730. nRefCount = 0;
  1731. nSendSize = 0;
  1732. nSendOffset = 0;
  1733. hashContinue = 0;
  1734. nStartingHeight = -1;
  1735. fGetAddr = false;
  1736. fRelayTxes = false;
  1737. setInventoryKnown.max_size(SendBufferSize() / 1000);
  1738. pfilter = new CBloomFilter();
  1739. nPingNonceSent = 0;
  1740. nPingUsecStart = 0;
  1741. nPingUsecTime = 0;
  1742. fPingQueued = false;
  1743. {
  1744. LOCK(cs_nLastNodeId);
  1745. id = nLastNodeId++;
  1746. }
  1747. if (fLogIPs)
  1748. LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
  1749. else
  1750. LogPrint("net", "Added connection peer=%d\n", id);
  1751. // Be shy and don't send version until we hear
  1752. if (hSocket != INVALID_SOCKET && !fInbound)
  1753. PushVersion();
  1754. GetNodeSignals().InitializeNode(GetId(), this);
  1755. }
  1756. CNode::~CNode()
  1757. {
  1758. CloseSocket(hSocket);
  1759. if (pfilter)
  1760. delete pfilter;
  1761. GetNodeSignals().FinalizeNode(GetId());
  1762. }
  1763. void CNode::AskFor(const CInv& inv)
  1764. {
  1765. if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
  1766. return;
  1767. // We're using mapAskFor as a priority queue,
  1768. // the key is the earliest time the request can be sent
  1769. int64_t nRequestTime;
  1770. limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
  1771. if (it != mapAlreadyAskedFor.end())
  1772. nRequestTime = it->second;
  1773. else
  1774. nRequestTime = 0;
  1775. LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
  1776. // Make sure not to reuse time indexes to keep things in the same order
  1777. int64_t nNow = GetTimeMicros() - 1000000;
  1778. static int64_t nLastTime;
  1779. ++nLastTime;
  1780. nNow = std::max(nNow, nLastTime);
  1781. nLastTime = nNow;
  1782. // Each retry is 2 minutes after the last
  1783. nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
  1784. if (it != mapAlreadyAskedFor.end())
  1785. mapAlreadyAskedFor.update(it, nRequestTime);
  1786. else
  1787. mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
  1788. mapAskFor.insert(std::make_pair(nRequestTime, inv));
  1789. }
  1790. void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
  1791. {
  1792. ENTER_CRITICAL_SECTION(cs_vSend);
  1793. assert(ssSend.size() == 0);
  1794. ssSend << CMessageHeader(pszCommand, 0);
  1795. LogPrint("net", "sending: %s ", pszCommand);
  1796. }
  1797. void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
  1798. {
  1799. ssSend.clear();
  1800. LEAVE_CRITICAL_SECTION(cs_vSend);
  1801. LogPrint("net", "(aborted)\n");
  1802. }
  1803. void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
  1804. {
  1805. // The -*messagestest options are intentionally not documented in the help message,
  1806. // since they are only used during development to debug the networking code and are
  1807. // not intended for end-users.
  1808. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
  1809. {
  1810. LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
  1811. AbortMessage();
  1812. return;
  1813. }
  1814. if (mapArgs.count("-fuzzmessagestest"))
  1815. Fuzz(GetArg("-fuzzmessagestest", 10));
  1816. if (ssSend.size() == 0)
  1817. return;
  1818. // Set the size
  1819. unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
  1820. memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
  1821. // Set the checksum
  1822. uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
  1823. unsigned int nChecksum = 0;
  1824. memcpy(&nChecksum, &hash, sizeof(nChecksum));
  1825. assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
  1826. memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
  1827. LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
  1828. std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
  1829. ssSend.GetAndClear(*it);
  1830. nSendSize += (*it).size();
  1831. // If write queue empty, attempt "optimistic write"
  1832. if (it == vSendMsg.begin())
  1833. SocketSendData(this);
  1834. LEAVE_CRITICAL_SECTION(cs_vSend);
  1835. }