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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 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. #include "chainparams.h"
  6. #include "db.h"
  7. #include "net.h"
  8. #include "core.h"
  9. #include "addrman.h"
  10. #include "ui_interface.h"
  11. #include "script.h"
  12. #ifdef WIN32
  13. #include <string.h>
  14. #endif
  15. #ifdef USE_UPNP
  16. #include <miniupnpc/miniwget.h>
  17. #include <miniupnpc/miniupnpc.h>
  18. #include <miniupnpc/upnpcommands.h>
  19. #include <miniupnpc/upnperrors.h>
  20. #endif
  21. using namespace std;
  22. using namespace boost;
  23. static const int MAX_OUTBOUND_CONNECTIONS = 8;
  24. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
  25. struct LocalServiceInfo {
  26. int nScore;
  27. int nPort;
  28. };
  29. //
  30. // Global state variables
  31. //
  32. bool fDiscover = true;
  33. uint64 nLocalServices = NODE_NETWORK;
  34. static CCriticalSection cs_mapLocalHost;
  35. static map<CNetAddr, LocalServiceInfo> mapLocalHost;
  36. static bool vfReachable[NET_MAX] = {};
  37. static bool vfLimited[NET_MAX] = {};
  38. static CNode* pnodeLocalHost = NULL;
  39. static CNode* pnodeSync = NULL;
  40. uint64 nLocalHostNonce = 0;
  41. static std::vector<SOCKET> vhListenSocket;
  42. CAddrMan addrman;
  43. int nMaxConnections = 125;
  44. vector<CNode*> vNodes;
  45. CCriticalSection cs_vNodes;
  46. map<CInv, CDataStream> mapRelay;
  47. deque<pair<int64, CInv> > vRelayExpiration;
  48. CCriticalSection cs_mapRelay;
  49. limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ);
  50. static deque<string> vOneShots;
  51. CCriticalSection cs_vOneShots;
  52. set<CNetAddr> setservAddNodeAddresses;
  53. CCriticalSection cs_setservAddNodeAddresses;
  54. vector<std::string> vAddedNodes;
  55. CCriticalSection cs_vAddedNodes;
  56. static CSemaphore *semOutbound = NULL;
  57. // Signals for message handling
  58. static CNodeSignals g_signals;
  59. CNodeSignals& GetNodeSignals() { return g_signals; }
  60. void AddOneShot(string strDest)
  61. {
  62. LOCK(cs_vOneShots);
  63. vOneShots.push_back(strDest);
  64. }
  65. unsigned short GetListenPort()
  66. {
  67. return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
  68. }
  69. // find 'best' local address for a particular peer
  70. bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
  71. {
  72. if (fNoListen)
  73. return false;
  74. int nBestScore = -1;
  75. int nBestReachability = -1;
  76. {
  77. LOCK(cs_mapLocalHost);
  78. for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
  79. {
  80. int nScore = (*it).second.nScore;
  81. int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
  82. if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
  83. {
  84. addr = CService((*it).first, (*it).second.nPort);
  85. nBestReachability = nReachability;
  86. nBestScore = nScore;
  87. }
  88. }
  89. }
  90. return nBestScore >= 0;
  91. }
  92. // get best local address for a particular peer as a CAddress
  93. CAddress GetLocalAddress(const CNetAddr *paddrPeer)
  94. {
  95. CAddress ret(CService("0.0.0.0",0),0);
  96. CService addr;
  97. if (GetLocal(addr, paddrPeer))
  98. {
  99. ret = CAddress(addr);
  100. ret.nServices = nLocalServices;
  101. ret.nTime = GetAdjustedTime();
  102. }
  103. return ret;
  104. }
  105. bool RecvLine(SOCKET hSocket, string& strLine)
  106. {
  107. strLine = "";
  108. loop
  109. {
  110. char c;
  111. int nBytes = recv(hSocket, &c, 1, 0);
  112. if (nBytes > 0)
  113. {
  114. if (c == '\n')
  115. continue;
  116. if (c == '\r')
  117. return true;
  118. strLine += c;
  119. if (strLine.size() >= 9000)
  120. return true;
  121. }
  122. else if (nBytes <= 0)
  123. {
  124. boost::this_thread::interruption_point();
  125. if (nBytes < 0)
  126. {
  127. int nErr = WSAGetLastError();
  128. if (nErr == WSAEMSGSIZE)
  129. continue;
  130. if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
  131. {
  132. MilliSleep(10);
  133. continue;
  134. }
  135. }
  136. if (!strLine.empty())
  137. return true;
  138. if (nBytes == 0)
  139. {
  140. // socket closed
  141. printf("socket closed\n");
  142. return false;
  143. }
  144. else
  145. {
  146. // socket error
  147. int nErr = WSAGetLastError();
  148. printf("recv failed: %d\n", nErr);
  149. return false;
  150. }
  151. }
  152. }
  153. }
  154. // used when scores of local addresses may have changed
  155. // pushes better local address to peers
  156. void static AdvertizeLocal()
  157. {
  158. LOCK(cs_vNodes);
  159. BOOST_FOREACH(CNode* pnode, vNodes)
  160. {
  161. if (pnode->fSuccessfullyConnected)
  162. {
  163. CAddress addrLocal = GetLocalAddress(&pnode->addr);
  164. if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
  165. {
  166. pnode->PushAddress(addrLocal);
  167. pnode->addrLocal = addrLocal;
  168. }
  169. }
  170. }
  171. }
  172. void SetReachable(enum Network net, bool fFlag)
  173. {
  174. LOCK(cs_mapLocalHost);
  175. vfReachable[net] = fFlag;
  176. if (net == NET_IPV6 && fFlag)
  177. vfReachable[NET_IPV4] = true;
  178. }
  179. // learn a new local address
  180. bool AddLocal(const CService& addr, int nScore)
  181. {
  182. if (!addr.IsRoutable())
  183. return false;
  184. if (!fDiscover && nScore < LOCAL_MANUAL)
  185. return false;
  186. if (IsLimited(addr))
  187. return false;
  188. printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
  189. {
  190. LOCK(cs_mapLocalHost);
  191. bool fAlready = mapLocalHost.count(addr) > 0;
  192. LocalServiceInfo &info = mapLocalHost[addr];
  193. if (!fAlready || nScore >= info.nScore) {
  194. info.nScore = nScore + (fAlready ? 1 : 0);
  195. info.nPort = addr.GetPort();
  196. }
  197. SetReachable(addr.GetNetwork());
  198. }
  199. AdvertizeLocal();
  200. return true;
  201. }
  202. bool AddLocal(const CNetAddr &addr, int nScore)
  203. {
  204. return AddLocal(CService(addr, GetListenPort()), nScore);
  205. }
  206. /** Make a particular network entirely off-limits (no automatic connects to it) */
  207. void SetLimited(enum Network net, bool fLimited)
  208. {
  209. if (net == NET_UNROUTABLE)
  210. return;
  211. LOCK(cs_mapLocalHost);
  212. vfLimited[net] = fLimited;
  213. }
  214. bool IsLimited(enum Network net)
  215. {
  216. LOCK(cs_mapLocalHost);
  217. return vfLimited[net];
  218. }
  219. bool IsLimited(const CNetAddr &addr)
  220. {
  221. return IsLimited(addr.GetNetwork());
  222. }
  223. /** vote for a local address */
  224. bool SeenLocal(const CService& addr)
  225. {
  226. {
  227. LOCK(cs_mapLocalHost);
  228. if (mapLocalHost.count(addr) == 0)
  229. return false;
  230. mapLocalHost[addr].nScore++;
  231. }
  232. AdvertizeLocal();
  233. return true;
  234. }
  235. /** check whether a given address is potentially local */
  236. bool IsLocal(const CService& addr)
  237. {
  238. LOCK(cs_mapLocalHost);
  239. return mapLocalHost.count(addr) > 0;
  240. }
  241. /** check whether a given address is in a network we can probably connect to */
  242. bool IsReachable(const CNetAddr& addr)
  243. {
  244. LOCK(cs_mapLocalHost);
  245. enum Network net = addr.GetNetwork();
  246. return vfReachable[net] && !vfLimited[net];
  247. }
  248. bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
  249. {
  250. SOCKET hSocket;
  251. if (!ConnectSocket(addrConnect, hSocket))
  252. return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
  253. send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
  254. string strLine;
  255. while (RecvLine(hSocket, strLine))
  256. {
  257. if (strLine.empty()) // HTTP response is separated from headers by blank line
  258. {
  259. loop
  260. {
  261. if (!RecvLine(hSocket, strLine))
  262. {
  263. closesocket(hSocket);
  264. return false;
  265. }
  266. if (pszKeyword == NULL)
  267. break;
  268. if (strLine.find(pszKeyword) != string::npos)
  269. {
  270. strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
  271. break;
  272. }
  273. }
  274. closesocket(hSocket);
  275. if (strLine.find("<") != string::npos)
  276. strLine = strLine.substr(0, strLine.find("<"));
  277. strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
  278. while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
  279. strLine.resize(strLine.size()-1);
  280. CService addr(strLine,0,true);
  281. printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
  282. if (!addr.IsValid() || !addr.IsRoutable())
  283. return false;
  284. ipRet.SetIP(addr);
  285. return true;
  286. }
  287. }
  288. closesocket(hSocket);
  289. return error("GetMyExternalIP() : connection closed");
  290. }
  291. bool GetMyExternalIP(CNetAddr& ipRet)
  292. {
  293. CService addrConnect;
  294. const char* pszGet;
  295. const char* pszKeyword;
  296. for (int nLookup = 0; nLookup <= 1; nLookup++)
  297. for (int nHost = 1; nHost <= 2; nHost++)
  298. {
  299. // We should be phasing out our use of sites like these. If we need
  300. // replacements, we should ask for volunteers to put this simple
  301. // php file on their web server that prints the client IP:
  302. // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
  303. if (nHost == 1)
  304. {
  305. addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
  306. if (nLookup == 1)
  307. {
  308. CService addrIP("checkip.dyndns.org", 80, true);
  309. if (addrIP.IsValid())
  310. addrConnect = addrIP;
  311. }
  312. pszGet = "GET / HTTP/1.1\r\n"
  313. "Host: checkip.dyndns.org\r\n"
  314. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  315. "Connection: close\r\n"
  316. "\r\n";
  317. pszKeyword = "Address:";
  318. }
  319. else if (nHost == 2)
  320. {
  321. addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
  322. if (nLookup == 1)
  323. {
  324. CService addrIP("www.showmyip.com", 80, true);
  325. if (addrIP.IsValid())
  326. addrConnect = addrIP;
  327. }
  328. pszGet = "GET /simple/ HTTP/1.1\r\n"
  329. "Host: www.showmyip.com\r\n"
  330. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  331. "Connection: close\r\n"
  332. "\r\n";
  333. pszKeyword = NULL; // Returns just IP address
  334. }
  335. if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
  336. return true;
  337. }
  338. return false;
  339. }
  340. void ThreadGetMyExternalIP()
  341. {
  342. CNetAddr addrLocalHost;
  343. if (GetMyExternalIP(addrLocalHost))
  344. {
  345. printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
  346. AddLocal(addrLocalHost, LOCAL_HTTP);
  347. }
  348. }
  349. void AddressCurrentlyConnected(const CService& addr)
  350. {
  351. addrman.Connected(addr);
  352. }
  353. CNode* FindNode(const CNetAddr& ip)
  354. {
  355. LOCK(cs_vNodes);
  356. BOOST_FOREACH(CNode* pnode, vNodes)
  357. if ((CNetAddr)pnode->addr == ip)
  358. return (pnode);
  359. return NULL;
  360. }
  361. CNode* FindNode(std::string addrName)
  362. {
  363. LOCK(cs_vNodes);
  364. BOOST_FOREACH(CNode* pnode, vNodes)
  365. if (pnode->addrName == addrName)
  366. return (pnode);
  367. return NULL;
  368. }
  369. CNode* FindNode(const CService& addr)
  370. {
  371. LOCK(cs_vNodes);
  372. BOOST_FOREACH(CNode* pnode, vNodes)
  373. if ((CService)pnode->addr == addr)
  374. return (pnode);
  375. return NULL;
  376. }
  377. CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
  378. {
  379. if (pszDest == NULL) {
  380. if (IsLocal(addrConnect))
  381. return NULL;
  382. // Look for an existing connection
  383. CNode* pnode = FindNode((CService)addrConnect);
  384. if (pnode)
  385. {
  386. pnode->AddRef();
  387. return pnode;
  388. }
  389. }
  390. /// debug print
  391. printf("trying connection %s lastseen=%.1fhrs\n",
  392. pszDest ? pszDest : addrConnect.ToString().c_str(),
  393. pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
  394. // Connect
  395. SOCKET hSocket;
  396. if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
  397. {
  398. addrman.Attempt(addrConnect);
  399. /// debug print
  400. printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
  401. // Set to non-blocking
  402. #ifdef WIN32
  403. u_long nOne = 1;
  404. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
  405. printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
  406. #else
  407. if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  408. printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
  409. #endif
  410. // Add node
  411. CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
  412. pnode->AddRef();
  413. {
  414. LOCK(cs_vNodes);
  415. vNodes.push_back(pnode);
  416. }
  417. pnode->nTimeConnected = GetTime();
  418. return pnode;
  419. }
  420. else
  421. {
  422. return NULL;
  423. }
  424. }
  425. void CNode::CloseSocketDisconnect()
  426. {
  427. fDisconnect = true;
  428. if (hSocket != INVALID_SOCKET)
  429. {
  430. printf("disconnecting node %s\n", addrName.c_str());
  431. closesocket(hSocket);
  432. hSocket = INVALID_SOCKET;
  433. }
  434. // in case this fails, we'll empty the recv buffer when the CNode is deleted
  435. TRY_LOCK(cs_vRecvMsg, lockRecv);
  436. if (lockRecv)
  437. vRecvMsg.clear();
  438. // if this was the sync node, we'll need a new one
  439. if (this == pnodeSync)
  440. pnodeSync = NULL;
  441. }
  442. void CNode::Cleanup()
  443. {
  444. }
  445. void CNode::PushVersion()
  446. {
  447. /// when NTP implemented, change to just nTime = GetAdjustedTime()
  448. int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
  449. CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
  450. CAddress addrMe = GetLocalAddress(&addr);
  451. RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
  452. printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
  453. PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
  454. nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
  455. }
  456. std::map<CNetAddr, int64> CNode::setBanned;
  457. CCriticalSection CNode::cs_setBanned;
  458. void CNode::ClearBanned()
  459. {
  460. setBanned.clear();
  461. }
  462. bool CNode::IsBanned(CNetAddr ip)
  463. {
  464. bool fResult = false;
  465. {
  466. LOCK(cs_setBanned);
  467. std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
  468. if (i != setBanned.end())
  469. {
  470. int64 t = (*i).second;
  471. if (GetTime() < t)
  472. fResult = true;
  473. }
  474. }
  475. return fResult;
  476. }
  477. bool CNode::Misbehaving(int howmuch)
  478. {
  479. if (addr.IsLocal())
  480. {
  481. printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
  482. return false;
  483. }
  484. nMisbehavior += howmuch;
  485. if (nMisbehavior >= GetArg("-banscore", 100))
  486. {
  487. int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
  488. printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
  489. {
  490. LOCK(cs_setBanned);
  491. if (setBanned[addr] < banTime)
  492. setBanned[addr] = banTime;
  493. }
  494. CloseSocketDisconnect();
  495. return true;
  496. } else
  497. printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
  498. return false;
  499. }
  500. #undef X
  501. #define X(name) stats.name = name
  502. void CNode::copyStats(CNodeStats &stats)
  503. {
  504. X(nServices);
  505. X(nLastSend);
  506. X(nLastRecv);
  507. X(nTimeConnected);
  508. X(addrName);
  509. X(nVersion);
  510. X(strSubVer);
  511. X(fInbound);
  512. X(nStartingHeight);
  513. X(nMisbehavior);
  514. X(nSendBytes);
  515. X(nRecvBytes);
  516. stats.fSyncNode = (this == pnodeSync);
  517. }
  518. #undef X
  519. // requires LOCK(cs_vRecvMsg)
  520. bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
  521. {
  522. while (nBytes > 0) {
  523. // get current incomplete message, or create a new one
  524. if (vRecvMsg.empty() ||
  525. vRecvMsg.back().complete())
  526. vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
  527. CNetMessage& msg = vRecvMsg.back();
  528. // absorb network data
  529. int handled;
  530. if (!msg.in_data)
  531. handled = msg.readHeader(pch, nBytes);
  532. else
  533. handled = msg.readData(pch, nBytes);
  534. if (handled < 0)
  535. return false;
  536. pch += handled;
  537. nBytes -= handled;
  538. }
  539. return true;
  540. }
  541. int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
  542. {
  543. // copy data to temporary parsing buffer
  544. unsigned int nRemaining = 24 - nHdrPos;
  545. unsigned int nCopy = std::min(nRemaining, nBytes);
  546. memcpy(&hdrbuf[nHdrPos], pch, nCopy);
  547. nHdrPos += nCopy;
  548. // if header incomplete, exit
  549. if (nHdrPos < 24)
  550. return nCopy;
  551. // deserialize to CMessageHeader
  552. try {
  553. hdrbuf >> hdr;
  554. }
  555. catch (std::exception &e) {
  556. return -1;
  557. }
  558. // reject messages larger than MAX_SIZE
  559. if (hdr.nMessageSize > MAX_SIZE)
  560. return -1;
  561. // switch state to reading message data
  562. in_data = true;
  563. vRecv.resize(hdr.nMessageSize);
  564. return nCopy;
  565. }
  566. int CNetMessage::readData(const char *pch, unsigned int nBytes)
  567. {
  568. unsigned int nRemaining = hdr.nMessageSize - nDataPos;
  569. unsigned int nCopy = std::min(nRemaining, nBytes);
  570. memcpy(&vRecv[nDataPos], pch, nCopy);
  571. nDataPos += nCopy;
  572. return nCopy;
  573. }
  574. // requires LOCK(cs_vSend)
  575. void SocketSendData(CNode *pnode)
  576. {
  577. std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
  578. while (it != pnode->vSendMsg.end()) {
  579. const CSerializeData &data = *it;
  580. assert(data.size() > pnode->nSendOffset);
  581. int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
  582. if (nBytes > 0) {
  583. pnode->nLastSend = GetTime();
  584. pnode->nSendBytes += nBytes;
  585. pnode->nSendOffset += nBytes;
  586. if (pnode->nSendOffset == data.size()) {
  587. pnode->nSendOffset = 0;
  588. pnode->nSendSize -= data.size();
  589. it++;
  590. } else {
  591. // could not send full message; stop sending more
  592. break;
  593. }
  594. } else {
  595. if (nBytes < 0) {
  596. // error
  597. int nErr = WSAGetLastError();
  598. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  599. {
  600. printf("socket send error %d\n", nErr);
  601. pnode->CloseSocketDisconnect();
  602. }
  603. }
  604. // couldn't send anything at all
  605. break;
  606. }
  607. }
  608. if (it == pnode->vSendMsg.end()) {
  609. assert(pnode->nSendOffset == 0);
  610. assert(pnode->nSendSize == 0);
  611. }
  612. pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
  613. }
  614. static list<CNode*> vNodesDisconnected;
  615. void ThreadSocketHandler()
  616. {
  617. unsigned int nPrevNodeCount = 0;
  618. loop
  619. {
  620. //
  621. // Disconnect nodes
  622. //
  623. {
  624. LOCK(cs_vNodes);
  625. // Disconnect unused nodes
  626. vector<CNode*> vNodesCopy = vNodes;
  627. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  628. {
  629. if (pnode->fDisconnect ||
  630. (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
  631. {
  632. // remove from vNodes
  633. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  634. // release outbound grant (if any)
  635. pnode->grantOutbound.Release();
  636. // close socket and cleanup
  637. pnode->CloseSocketDisconnect();
  638. pnode->Cleanup();
  639. // hold in disconnected pool until all refs are released
  640. if (pnode->fNetworkNode || pnode->fInbound)
  641. pnode->Release();
  642. vNodesDisconnected.push_back(pnode);
  643. }
  644. }
  645. // Delete disconnected nodes
  646. list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  647. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  648. {
  649. // wait until threads are done using it
  650. if (pnode->GetRefCount() <= 0)
  651. {
  652. bool fDelete = false;
  653. {
  654. TRY_LOCK(pnode->cs_vSend, lockSend);
  655. if (lockSend)
  656. {
  657. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  658. if (lockRecv)
  659. {
  660. TRY_LOCK(pnode->cs_inventory, lockInv);
  661. if (lockInv)
  662. fDelete = true;
  663. }
  664. }
  665. }
  666. if (fDelete)
  667. {
  668. vNodesDisconnected.remove(pnode);
  669. delete pnode;
  670. }
  671. }
  672. }
  673. }
  674. if (vNodes.size() != nPrevNodeCount)
  675. {
  676. nPrevNodeCount = vNodes.size();
  677. uiInterface.NotifyNumConnectionsChanged(vNodes.size());
  678. }
  679. //
  680. // Find which sockets have data to receive
  681. //
  682. struct timeval timeout;
  683. timeout.tv_sec = 0;
  684. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  685. fd_set fdsetRecv;
  686. fd_set fdsetSend;
  687. fd_set fdsetError;
  688. FD_ZERO(&fdsetRecv);
  689. FD_ZERO(&fdsetSend);
  690. FD_ZERO(&fdsetError);
  691. SOCKET hSocketMax = 0;
  692. bool have_fds = false;
  693. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
  694. FD_SET(hListenSocket, &fdsetRecv);
  695. hSocketMax = max(hSocketMax, hListenSocket);
  696. have_fds = true;
  697. }
  698. {
  699. LOCK(cs_vNodes);
  700. BOOST_FOREACH(CNode* pnode, vNodes)
  701. {
  702. if (pnode->hSocket == INVALID_SOCKET)
  703. continue;
  704. FD_SET(pnode->hSocket, &fdsetError);
  705. hSocketMax = max(hSocketMax, pnode->hSocket);
  706. have_fds = true;
  707. // Implement the following logic:
  708. // * If there is data to send, select() for sending data. As this only
  709. // happens when optimistic write failed, we choose to first drain the
  710. // write buffer in this case before receiving more. This avoids
  711. // needlessly queueing received data, if the remote peer is not themselves
  712. // receiving data. This means properly utilizing TCP flow control signalling.
  713. // * Otherwise, if there is no (complete) message in the receive buffer,
  714. // or there is space left in the buffer, select() for receiving data.
  715. // * (if neither of the above applies, there is certainly one message
  716. // in the receiver buffer ready to be processed).
  717. // Together, that means that at least one of the following is always possible,
  718. // so we don't deadlock:
  719. // * We send some data.
  720. // * We wait for data to be received (and disconnect after timeout).
  721. // * We process a message in the buffer (message handler thread).
  722. {
  723. TRY_LOCK(pnode->cs_vSend, lockSend);
  724. if (lockSend && !pnode->vSendMsg.empty()) {
  725. FD_SET(pnode->hSocket, &fdsetSend);
  726. continue;
  727. }
  728. }
  729. {
  730. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  731. if (lockRecv && (
  732. pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
  733. pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
  734. FD_SET(pnode->hSocket, &fdsetRecv);
  735. }
  736. }
  737. }
  738. int nSelect = select(have_fds ? hSocketMax + 1 : 0,
  739. &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  740. boost::this_thread::interruption_point();
  741. if (nSelect == SOCKET_ERROR)
  742. {
  743. if (have_fds)
  744. {
  745. int nErr = WSAGetLastError();
  746. printf("socket select error %d\n", nErr);
  747. for (unsigned int i = 0; i <= hSocketMax; i++)
  748. FD_SET(i, &fdsetRecv);
  749. }
  750. FD_ZERO(&fdsetSend);
  751. FD_ZERO(&fdsetError);
  752. MilliSleep(timeout.tv_usec/1000);
  753. }
  754. //
  755. // Accept new connections
  756. //
  757. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  758. if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
  759. {
  760. #ifdef USE_IPV6
  761. struct sockaddr_storage sockaddr;
  762. #else
  763. struct sockaddr sockaddr;
  764. #endif
  765. socklen_t len = sizeof(sockaddr);
  766. SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
  767. CAddress addr;
  768. int nInbound = 0;
  769. if (hSocket != INVALID_SOCKET)
  770. if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
  771. printf("Warning: Unknown socket family\n");
  772. {
  773. LOCK(cs_vNodes);
  774. BOOST_FOREACH(CNode* pnode, vNodes)
  775. if (pnode->fInbound)
  776. nInbound++;
  777. }
  778. if (hSocket == INVALID_SOCKET)
  779. {
  780. int nErr = WSAGetLastError();
  781. if (nErr != WSAEWOULDBLOCK)
  782. printf("socket error accept failed: %d\n", nErr);
  783. }
  784. else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
  785. {
  786. {
  787. LOCK(cs_setservAddNodeAddresses);
  788. if (!setservAddNodeAddresses.count(addr))
  789. closesocket(hSocket);
  790. }
  791. }
  792. else if (CNode::IsBanned(addr))
  793. {
  794. printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
  795. closesocket(hSocket);
  796. }
  797. else
  798. {
  799. printf("accepted connection %s\n", addr.ToString().c_str());
  800. CNode* pnode = new CNode(hSocket, addr, "", true);
  801. pnode->AddRef();
  802. {
  803. LOCK(cs_vNodes);
  804. vNodes.push_back(pnode);
  805. }
  806. }
  807. }
  808. //
  809. // Service each socket
  810. //
  811. vector<CNode*> vNodesCopy;
  812. {
  813. LOCK(cs_vNodes);
  814. vNodesCopy = vNodes;
  815. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  816. pnode->AddRef();
  817. }
  818. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  819. {
  820. boost::this_thread::interruption_point();
  821. //
  822. // Receive
  823. //
  824. if (pnode->hSocket == INVALID_SOCKET)
  825. continue;
  826. if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
  827. {
  828. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  829. if (lockRecv)
  830. {
  831. {
  832. // typical socket buffer is 8K-64K
  833. char pchBuf[0x10000];
  834. int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  835. if (nBytes > 0)
  836. {
  837. if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
  838. pnode->CloseSocketDisconnect();
  839. pnode->nLastRecv = GetTime();
  840. pnode->nRecvBytes += nBytes;
  841. }
  842. else if (nBytes == 0)
  843. {
  844. // socket closed gracefully
  845. if (!pnode->fDisconnect)
  846. printf("socket closed\n");
  847. pnode->CloseSocketDisconnect();
  848. }
  849. else if (nBytes < 0)
  850. {
  851. // error
  852. int nErr = WSAGetLastError();
  853. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  854. {
  855. if (!pnode->fDisconnect)
  856. printf("socket recv error %d\n", nErr);
  857. pnode->CloseSocketDisconnect();
  858. }
  859. }
  860. }
  861. }
  862. }
  863. //
  864. // Send
  865. //
  866. if (pnode->hSocket == INVALID_SOCKET)
  867. continue;
  868. if (FD_ISSET(pnode->hSocket, &fdsetSend))
  869. {
  870. TRY_LOCK(pnode->cs_vSend, lockSend);
  871. if (lockSend)
  872. SocketSendData(pnode);
  873. }
  874. //
  875. // Inactivity checking
  876. //
  877. if (pnode->vSendMsg.empty())
  878. pnode->nLastSendEmpty = GetTime();
  879. if (GetTime() - pnode->nTimeConnected > 60)
  880. {
  881. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  882. {
  883. printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
  884. pnode->fDisconnect = true;
  885. }
  886. else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
  887. {
  888. printf("socket not sending\n");
  889. pnode->fDisconnect = true;
  890. }
  891. else if (GetTime() - pnode->nLastRecv > 90*60)
  892. {
  893. printf("socket inactivity timeout\n");
  894. pnode->fDisconnect = true;
  895. }
  896. }
  897. }
  898. {
  899. LOCK(cs_vNodes);
  900. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  901. pnode->Release();
  902. }
  903. MilliSleep(10);
  904. }
  905. }
  906. #ifdef USE_UPNP
  907. void ThreadMapPort()
  908. {
  909. std::string port = strprintf("%u", GetListenPort());
  910. const char * multicastif = 0;
  911. const char * minissdpdpath = 0;
  912. struct UPNPDev * devlist = 0;
  913. char lanaddr[64];
  914. #ifndef UPNPDISCOVER_SUCCESS
  915. /* miniupnpc 1.5 */
  916. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
  917. #else
  918. /* miniupnpc 1.6 */
  919. int error = 0;
  920. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
  921. #endif
  922. struct UPNPUrls urls;
  923. struct IGDdatas data;
  924. int r;
  925. r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
  926. if (r == 1)
  927. {
  928. if (fDiscover) {
  929. char externalIPAddress[40];
  930. r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
  931. if(r != UPNPCOMMAND_SUCCESS)
  932. printf("UPnP: GetExternalIPAddress() returned %d\n", r);
  933. else
  934. {
  935. if(externalIPAddress[0])
  936. {
  937. printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
  938. AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
  939. }
  940. else
  941. printf("UPnP: GetExternalIPAddress failed.\n");
  942. }
  943. }
  944. string strDesc = "Bitcoin " + FormatFullVersion();
  945. try {
  946. loop {
  947. #ifndef UPNPDISCOVER_SUCCESS
  948. /* miniupnpc 1.5 */
  949. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  950. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
  951. #else
  952. /* miniupnpc 1.6 */
  953. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  954. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
  955. #endif
  956. if(r!=UPNPCOMMAND_SUCCESS)
  957. printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  958. port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
  959. else
  960. printf("UPnP Port Mapping successful.\n");;
  961. MilliSleep(20*60*1000); // Refresh every 20 minutes
  962. }
  963. }
  964. catch (boost::thread_interrupted)
  965. {
  966. r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
  967. printf("UPNP_DeletePortMapping() returned : %d\n", r);
  968. freeUPNPDevlist(devlist); devlist = 0;
  969. FreeUPNPUrls(&urls);
  970. throw;
  971. }
  972. } else {
  973. printf("No valid UPnP IGDs found\n");
  974. freeUPNPDevlist(devlist); devlist = 0;
  975. if (r != 0)
  976. FreeUPNPUrls(&urls);
  977. }
  978. }
  979. void MapPort(bool fUseUPnP)
  980. {
  981. static boost::thread* upnp_thread = NULL;
  982. if (fUseUPnP)
  983. {
  984. if (upnp_thread) {
  985. upnp_thread->interrupt();
  986. upnp_thread->join();
  987. delete upnp_thread;
  988. }
  989. upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
  990. }
  991. else if (upnp_thread) {
  992. upnp_thread->interrupt();
  993. upnp_thread->join();
  994. delete upnp_thread;
  995. upnp_thread = NULL;
  996. }
  997. }
  998. #else
  999. void MapPort(bool)
  1000. {
  1001. // Intentionally left blank.
  1002. }
  1003. #endif
  1004. void ThreadDNSAddressSeed()
  1005. {
  1006. const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
  1007. int found = 0;
  1008. printf("Loading addresses from DNS seeds (could take a while)\n");
  1009. BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
  1010. if (HaveNameProxy()) {
  1011. AddOneShot(seed.host);
  1012. } else {
  1013. vector<CNetAddr> vIPs;
  1014. vector<CAddress> vAdd;
  1015. if (LookupHost(seed.host.c_str(), vIPs))
  1016. {
  1017. BOOST_FOREACH(CNetAddr& ip, vIPs)
  1018. {
  1019. int nOneDay = 24*3600;
  1020. CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
  1021. addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
  1022. vAdd.push_back(addr);
  1023. found++;
  1024. }
  1025. }
  1026. addrman.Add(vAdd, CNetAddr(seed.name, true));
  1027. }
  1028. }
  1029. printf("%d addresses found from DNS seeds\n", found);
  1030. }
  1031. void DumpAddresses()
  1032. {
  1033. int64 nStart = GetTimeMillis();
  1034. CAddrDB adb;
  1035. adb.Write(addrman);
  1036. printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
  1037. addrman.size(), GetTimeMillis() - nStart);
  1038. }
  1039. void static ProcessOneShot()
  1040. {
  1041. string strDest;
  1042. {
  1043. LOCK(cs_vOneShots);
  1044. if (vOneShots.empty())
  1045. return;
  1046. strDest = vOneShots.front();
  1047. vOneShots.pop_front();
  1048. }
  1049. CAddress addr;
  1050. CSemaphoreGrant grant(*semOutbound, true);
  1051. if (grant) {
  1052. if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
  1053. AddOneShot(strDest);
  1054. }
  1055. }
  1056. void ThreadOpenConnections()
  1057. {
  1058. // Connect to specific addresses
  1059. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
  1060. {
  1061. for (int64 nLoop = 0;; nLoop++)
  1062. {
  1063. ProcessOneShot();
  1064. BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
  1065. {
  1066. CAddress addr;
  1067. OpenNetworkConnection(addr, NULL, strAddr.c_str());
  1068. for (int i = 0; i < 10 && i < nLoop; i++)
  1069. {
  1070. MilliSleep(500);
  1071. }
  1072. }
  1073. MilliSleep(500);
  1074. }
  1075. }
  1076. // Initiate network connections
  1077. int64 nStart = GetTime();
  1078. loop
  1079. {
  1080. ProcessOneShot();
  1081. MilliSleep(500);
  1082. CSemaphoreGrant grant(*semOutbound);
  1083. boost::this_thread::interruption_point();
  1084. // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
  1085. if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
  1086. static bool done = false;
  1087. if (!done) {
  1088. printf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
  1089. addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
  1090. done = true;
  1091. }
  1092. }
  1093. //
  1094. // Choose an address to connect to based on most recently seen
  1095. //
  1096. CAddress addrConnect;
  1097. // Only connect out to one peer per network group (/16 for IPv4).
  1098. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
  1099. int nOutbound = 0;
  1100. set<vector<unsigned char> > setConnected;
  1101. {
  1102. LOCK(cs_vNodes);
  1103. BOOST_FOREACH(CNode* pnode, vNodes) {
  1104. if (!pnode->fInbound) {
  1105. setConnected.insert(pnode->addr.GetGroup());
  1106. nOutbound++;
  1107. }
  1108. }
  1109. }
  1110. int64 nANow = GetAdjustedTime();
  1111. int nTries = 0;
  1112. loop
  1113. {
  1114. // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
  1115. CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
  1116. // if we selected an invalid address, restart
  1117. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1118. break;
  1119. // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
  1120. // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
  1121. // already-connected network ranges, ...) before trying new addrman addresses.
  1122. nTries++;
  1123. if (nTries > 100)
  1124. break;
  1125. if (IsLimited(addr))
  1126. continue;
  1127. // only consider very recently tried nodes after 30 failed attempts
  1128. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1129. continue;
  1130. // do not allow non-default ports, unless after 50 invalid addresses selected already
  1131. if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
  1132. continue;
  1133. addrConnect = addr;
  1134. break;
  1135. }
  1136. if (addrConnect.IsValid())
  1137. OpenNetworkConnection(addrConnect, &grant);
  1138. }
  1139. }
  1140. void ThreadOpenAddedConnections()
  1141. {
  1142. {
  1143. LOCK(cs_vAddedNodes);
  1144. vAddedNodes = mapMultiArgs["-addnode"];
  1145. }
  1146. if (HaveNameProxy()) {
  1147. while(true) {
  1148. list<string> lAddresses(0);
  1149. {
  1150. LOCK(cs_vAddedNodes);
  1151. BOOST_FOREACH(string& strAddNode, vAddedNodes)
  1152. lAddresses.push_back(strAddNode);
  1153. }
  1154. BOOST_FOREACH(string& strAddNode, lAddresses) {
  1155. CAddress addr;
  1156. CSemaphoreGrant grant(*semOutbound);
  1157. OpenNetworkConnection(addr, &grant, strAddNode.c_str());
  1158. MilliSleep(500);
  1159. }
  1160. MilliSleep(120000); // Retry every 2 minutes
  1161. }
  1162. }
  1163. for (unsigned int i = 0; true; i++)
  1164. {
  1165. list<string> lAddresses(0);
  1166. {
  1167. LOCK(cs_vAddedNodes);
  1168. BOOST_FOREACH(string& strAddNode, vAddedNodes)
  1169. lAddresses.push_back(strAddNode);
  1170. }
  1171. list<vector<CService> > lservAddressesToAdd(0);
  1172. BOOST_FOREACH(string& strAddNode, lAddresses)
  1173. {
  1174. vector<CService> vservNode(0);
  1175. if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
  1176. {
  1177. lservAddressesToAdd.push_back(vservNode);
  1178. {
  1179. LOCK(cs_setservAddNodeAddresses);
  1180. BOOST_FOREACH(CService& serv, vservNode)
  1181. setservAddNodeAddresses.insert(serv);
  1182. }
  1183. }
  1184. }
  1185. // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
  1186. // (keeping in mind that addnode entries can have many IPs if fNameLookup)
  1187. {
  1188. LOCK(cs_vNodes);
  1189. BOOST_FOREACH(CNode* pnode, vNodes)
  1190. for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
  1191. BOOST_FOREACH(CService& addrNode, *(it))
  1192. if (pnode->addr == addrNode)
  1193. {
  1194. it = lservAddressesToAdd.erase(it);
  1195. it--;
  1196. break;
  1197. }
  1198. }
  1199. BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
  1200. {
  1201. CSemaphoreGrant grant(*semOutbound);
  1202. OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
  1203. MilliSleep(500);
  1204. }
  1205. MilliSleep(120000); // Retry every 2 minutes
  1206. }
  1207. }
  1208. // if successful, this moves the passed grant to the constructed node
  1209. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
  1210. {
  1211. //
  1212. // Initiate outbound network connection
  1213. //
  1214. boost::this_thread::interruption_point();
  1215. if (!strDest)
  1216. if (IsLocal(addrConnect) ||
  1217. FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
  1218. FindNode(addrConnect.ToStringIPPort().c_str()))
  1219. return false;
  1220. if (strDest && FindNode(strDest))
  1221. return false;
  1222. CNode* pnode = ConnectNode(addrConnect, strDest);
  1223. boost::this_thread::interruption_point();
  1224. if (!pnode)
  1225. return false;
  1226. if (grantOutbound)
  1227. grantOutbound->MoveTo(pnode->grantOutbound);
  1228. pnode->fNetworkNode = true;
  1229. if (fOneShot)
  1230. pnode->fOneShot = true;
  1231. return true;
  1232. }
  1233. // for now, use a very simple selection metric: the node from which we received
  1234. // most recently
  1235. double static NodeSyncScore(const CNode *pnode) {
  1236. return -pnode->nLastRecv;
  1237. }
  1238. void static StartSync(const vector<CNode*> &vNodes) {
  1239. CNode *pnodeNewSync = NULL;
  1240. double dBestScore = 0;
  1241. // Iterate over all nodes
  1242. BOOST_FOREACH(CNode* pnode, vNodes) {
  1243. // check preconditions for allowing a sync
  1244. if (!pnode->fClient && !pnode->fOneShot &&
  1245. !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
  1246. (pnode->nStartingHeight > (nBestHeight - 144)) &&
  1247. (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
  1248. // if ok, compare node's score with the best so far
  1249. double dScore = NodeSyncScore(pnode);
  1250. if (pnodeNewSync == NULL || dScore > dBestScore) {
  1251. pnodeNewSync = pnode;
  1252. dBestScore = dScore;
  1253. }
  1254. }
  1255. }
  1256. // if a new sync candidate was found, start sync!
  1257. if (pnodeNewSync) {
  1258. pnodeNewSync->fStartSync = true;
  1259. pnodeSync = pnodeNewSync;
  1260. }
  1261. }
  1262. void ThreadMessageHandler()
  1263. {
  1264. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1265. while (true)
  1266. {
  1267. bool fHaveSyncNode = false;
  1268. vector<CNode*> vNodesCopy;
  1269. {
  1270. LOCK(cs_vNodes);
  1271. vNodesCopy = vNodes;
  1272. BOOST_FOREACH(CNode* pnode, vNodesCopy) {
  1273. pnode->AddRef();
  1274. if (pnode == pnodeSync)
  1275. fHaveSyncNode = true;
  1276. }
  1277. }
  1278. if (!fHaveSyncNode)
  1279. StartSync(vNodesCopy);
  1280. // Poll the connected nodes for messages
  1281. CNode* pnodeTrickle = NULL;
  1282. if (!vNodesCopy.empty())
  1283. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1284. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1285. {
  1286. if (pnode->fDisconnect)
  1287. continue;
  1288. // Receive messages
  1289. {
  1290. TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
  1291. if (lockRecv)
  1292. if (!g_signals.ProcessMessages(pnode))
  1293. pnode->CloseSocketDisconnect();
  1294. }
  1295. boost::this_thread::interruption_point();
  1296. // Send messages
  1297. {
  1298. TRY_LOCK(pnode->cs_vSend, lockSend);
  1299. if (lockSend)
  1300. g_signals.SendMessages(pnode, pnode == pnodeTrickle);
  1301. }
  1302. boost::this_thread::interruption_point();
  1303. }
  1304. {
  1305. LOCK(cs_vNodes);
  1306. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1307. pnode->Release();
  1308. }
  1309. MilliSleep(100);
  1310. }
  1311. }
  1312. bool BindListenPort(const CService &addrBind, string& strError)
  1313. {
  1314. strError = "";
  1315. int nOne = 1;
  1316. // Create socket for listening for incoming connections
  1317. #ifdef USE_IPV6
  1318. struct sockaddr_storage sockaddr;
  1319. #else
  1320. struct sockaddr sockaddr;
  1321. #endif
  1322. socklen_t len = sizeof(sockaddr);
  1323. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1324. {
  1325. strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
  1326. printf("%s\n", strError.c_str());
  1327. return false;
  1328. }
  1329. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1330. if (hListenSocket == INVALID_SOCKET)
  1331. {
  1332. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
  1333. printf("%s\n", strError.c_str());
  1334. return false;
  1335. }
  1336. #ifdef SO_NOSIGPIPE
  1337. // Different way of disabling SIGPIPE on BSD
  1338. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1339. #endif
  1340. #ifndef WIN32
  1341. // Allow binding if the port is still in TIME_WAIT state after
  1342. // the program was closed and restarted. Not an issue on windows.
  1343. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1344. #endif
  1345. #ifdef WIN32
  1346. // Set to non-blocking, incoming connections will also inherit this
  1347. if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
  1348. #else
  1349. if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  1350. #endif
  1351. {
  1352. strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
  1353. printf("%s\n", strError.c_str());
  1354. return false;
  1355. }
  1356. #ifdef USE_IPV6
  1357. // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
  1358. // and enable it by default or not. Try to enable it, if possible.
  1359. if (addrBind.IsIPv6()) {
  1360. #ifdef IPV6_V6ONLY
  1361. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1362. #endif
  1363. #ifdef WIN32
  1364. int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
  1365. int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
  1366. // this call is allowed to fail
  1367. setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
  1368. #endif
  1369. }
  1370. #endif
  1371. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1372. {
  1373. int nErr = WSAGetLastError();
  1374. if (nErr == WSAEADDRINUSE)
  1375. strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
  1376. else
  1377. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
  1378. printf("%s\n", strError.c_str());
  1379. return false;
  1380. }
  1381. printf("Bound to %s\n", addrBind.ToString().c_str());
  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 %d)", WSAGetLastError());
  1386. printf("%s\n", strError.c_str());
  1387. return false;
  1388. }
  1389. vhListenSocket.push_back(hListenSocket);
  1390. if (addrBind.IsRoutable() && fDiscover)
  1391. AddLocal(addrBind, LOCAL_BIND);
  1392. return true;
  1393. }
  1394. void static Discover()
  1395. {
  1396. if (!fDiscover)
  1397. return;
  1398. #ifdef WIN32
  1399. // Get local host IP
  1400. char pszHostName[1000] = "";
  1401. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1402. {
  1403. vector<CNetAddr> vaddr;
  1404. if (LookupHost(pszHostName, vaddr))
  1405. {
  1406. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1407. {
  1408. AddLocal(addr, LOCAL_IF);
  1409. }
  1410. }
  1411. }
  1412. #else
  1413. // Get local host ip
  1414. struct ifaddrs* myaddrs;
  1415. if (getifaddrs(&myaddrs) == 0)
  1416. {
  1417. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1418. {
  1419. if (ifa->ifa_addr == NULL) continue;
  1420. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1421. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1422. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1423. if (ifa->ifa_addr->sa_family == AF_INET)
  1424. {
  1425. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1426. CNetAddr addr(s4->sin_addr);
  1427. if (AddLocal(addr, LOCAL_IF))
  1428. printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1429. }
  1430. #ifdef USE_IPV6
  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. printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1437. }
  1438. #endif
  1439. }
  1440. freeifaddrs(myaddrs);
  1441. }
  1442. #endif
  1443. // Don't use external IPv4 discovery, when -onlynet="IPv6"
  1444. if (!IsLimited(NET_IPV4))
  1445. boost::thread(boost::bind(&TraceThread<void (*)()>, "ext-ip", &ThreadGetMyExternalIP));
  1446. }
  1447. void StartNode(boost::thread_group& threadGroup)
  1448. {
  1449. if (semOutbound == NULL) {
  1450. // initialize semaphore
  1451. int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
  1452. semOutbound = new CSemaphore(nMaxOutbound);
  1453. }
  1454. if (pnodeLocalHost == NULL)
  1455. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
  1456. Discover();
  1457. //
  1458. // Start threads
  1459. //
  1460. if (!GetBoolArg("-dnsseed", true))
  1461. printf("DNS seeding disabled\n");
  1462. else
  1463. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
  1464. #ifdef USE_UPNP
  1465. // Map ports with UPnP
  1466. MapPort(GetBoolArg("-upnp", USE_UPNP));
  1467. #endif
  1468. // Send and receive from sockets, accept connections
  1469. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
  1470. // Initiate outbound connections from -addnode
  1471. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
  1472. // Initiate outbound connections
  1473. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
  1474. // Process messages
  1475. threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
  1476. // Dump network addresses
  1477. threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 10000));
  1478. }
  1479. bool StopNode()
  1480. {
  1481. printf("StopNode()\n");
  1482. MapPort(false);
  1483. if (semOutbound)
  1484. for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
  1485. semOutbound->post();
  1486. MilliSleep(50);
  1487. DumpAddresses();
  1488. return true;
  1489. }
  1490. class CNetCleanup
  1491. {
  1492. public:
  1493. CNetCleanup()
  1494. {
  1495. }
  1496. ~CNetCleanup()
  1497. {
  1498. // Close sockets
  1499. BOOST_FOREACH(CNode* pnode, vNodes)
  1500. if (pnode->hSocket != INVALID_SOCKET)
  1501. closesocket(pnode->hSocket);
  1502. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  1503. if (hListenSocket != INVALID_SOCKET)
  1504. if (closesocket(hListenSocket) == SOCKET_ERROR)
  1505. printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
  1506. // clean up some globals (to help leak detection)
  1507. BOOST_FOREACH(CNode *pnode, vNodes)
  1508. delete pnode;
  1509. BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
  1510. delete pnode;
  1511. vNodes.clear();
  1512. vNodesDisconnected.clear();
  1513. delete semOutbound;
  1514. semOutbound = NULL;
  1515. delete pnodeLocalHost;
  1516. pnodeLocalHost = NULL;
  1517. #ifdef WIN32
  1518. // Shutdown Windows Sockets
  1519. WSACleanup();
  1520. #endif
  1521. }
  1522. }
  1523. instance_of_cnetcleanup;
  1524. void RelayTransaction(const CTransaction& tx, const uint256& hash)
  1525. {
  1526. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  1527. ss.reserve(10000);
  1528. ss << tx;
  1529. RelayTransaction(tx, hash, ss);
  1530. }
  1531. void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
  1532. {
  1533. CInv inv(MSG_TX, hash);
  1534. {
  1535. LOCK(cs_mapRelay);
  1536. // Expire old relay messages
  1537. while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
  1538. {
  1539. mapRelay.erase(vRelayExpiration.front().second);
  1540. vRelayExpiration.pop_front();
  1541. }
  1542. // Save original serialized message so newer versions are preserved
  1543. mapRelay.insert(std::make_pair(inv, ss));
  1544. vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
  1545. }
  1546. LOCK(cs_vNodes);
  1547. BOOST_FOREACH(CNode* pnode, vNodes)
  1548. {
  1549. if(!pnode->fRelayTxes)
  1550. continue;
  1551. LOCK(pnode->cs_filter);
  1552. if (pnode->pfilter)
  1553. {
  1554. if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
  1555. pnode->PushInventory(inv);
  1556. } else
  1557. pnode->PushInventory(inv);
  1558. }
  1559. }