PageRenderTime 61ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/net.cpp

https://gitlab.com/m0gliE/litecoin
C++ | 2075 lines | 1579 code | 304 blank | 192 comment | 355 complexity | 43dc8e8e458e7c989a6835d2a70a1ccd MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, 0BSD

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file