PageRenderTime 65ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/src/net.cpp

https://gitlab.com/intersango/bitcoind
C++ | 1636 lines | 1271 code | 211 blank | 154 comment | 374 complexity | 36137a450675c8577f9f37ab4b7f779f MD5 | raw file

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

  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  4. #include "headers.h"
  5. #include "irc.h"
  6. #include "db.h"
  7. #include "net.h"
  8. #include "init.h"
  9. #include "strlcpy.h"
  10. #ifdef __WXMSW__
  11. #include <string.h>
  12. // This file can be downloaded as a part of the Windows Platform SDK
  13. // and is required for Bitcoin binaries to work properly on versions
  14. // of Windows before XP. If you are doing builds of Bitcoin for
  15. // public release, you should uncomment this line.
  16. //#include <WSPiApi.h>
  17. #endif
  18. using namespace std;
  19. using namespace boost;
  20. static const int MAX_OUTBOUND_CONNECTIONS = 8;
  21. void ThreadMessageHandler2(void* parg);
  22. void ThreadSocketHandler2(void* parg);
  23. void ThreadOpenConnections2(void* parg);
  24. bool OpenNetworkConnection(const CAddress& addrConnect);
  25. //
  26. // Global state variables
  27. //
  28. bool fClient = false;
  29. bool fAllowDNS = false;
  30. uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
  31. CAddress addrLocalHost("0.0.0.0", 0, false, nLocalServices);
  32. CNode* pnodeLocalHost = NULL;
  33. uint64 nLocalHostNonce = 0;
  34. array<int, 10> vnThreadsRunning;
  35. SOCKET hListenSocket = INVALID_SOCKET;
  36. vector<CNode*> vNodes;
  37. CCriticalSection cs_vNodes;
  38. map<vector<unsigned char>, CAddress> mapAddresses;
  39. CCriticalSection cs_mapAddresses;
  40. map<CInv, CDataStream> mapRelay;
  41. deque<pair<int64, CInv> > vRelayExpiration;
  42. CCriticalSection cs_mapRelay;
  43. map<CInv, int64> mapAlreadyAskedFor;
  44. // Settings
  45. int fUseProxy = false;
  46. int nConnectTimeout = 500;
  47. CAddress addrProxy("127.0.0.1",9050);
  48. unsigned short GetListenPort()
  49. {
  50. return (unsigned short)(GetArg("-port", GetDefaultPort()));
  51. }
  52. void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
  53. {
  54. // Filter out duplicate requests
  55. if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
  56. return;
  57. pindexLastGetBlocksBegin = pindexBegin;
  58. hashLastGetBlocksEnd = hashEnd;
  59. PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
  60. }
  61. bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout)
  62. {
  63. hSocketRet = INVALID_SOCKET;
  64. SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  65. if (hSocket == INVALID_SOCKET)
  66. return false;
  67. #ifdef BSD
  68. int set = 1;
  69. setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
  70. #endif
  71. bool fProxy = (fUseProxy && addrConnect.IsRoutable());
  72. struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());
  73. #ifdef __WXMSW__
  74. u_long fNonblock = 1;
  75. if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
  76. #else
  77. int fFlags = fcntl(hSocket, F_GETFL, 0);
  78. if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
  79. #endif
  80. {
  81. closesocket(hSocket);
  82. return false;
  83. }
  84. if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
  85. {
  86. // WSAEINVAL is here because some legacy version of winsock uses it
  87. if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
  88. {
  89. struct timeval timeout;
  90. timeout.tv_sec = nTimeout / 1000;
  91. timeout.tv_usec = (nTimeout % 1000) * 1000;
  92. fd_set fdset;
  93. FD_ZERO(&fdset);
  94. FD_SET(hSocket, &fdset);
  95. int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
  96. if (nRet == 0)
  97. {
  98. printf("connection timeout\n");
  99. closesocket(hSocket);
  100. return false;
  101. }
  102. if (nRet == SOCKET_ERROR)
  103. {
  104. printf("select() for connection failed: %i\n",WSAGetLastError());
  105. closesocket(hSocket);
  106. return false;
  107. }
  108. socklen_t nRetSize = sizeof(nRet);
  109. #ifdef __WXMSW__
  110. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
  111. #else
  112. if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
  113. #endif
  114. {
  115. printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
  116. closesocket(hSocket);
  117. return false;
  118. }
  119. if (nRet != 0)
  120. {
  121. printf("connect() failed after select(): %s\n",strerror(nRet));
  122. closesocket(hSocket);
  123. return false;
  124. }
  125. }
  126. #ifdef __WXMSW__
  127. else if (WSAGetLastError() != WSAEISCONN)
  128. #else
  129. else
  130. #endif
  131. {
  132. printf("connect() failed: %i\n",WSAGetLastError());
  133. closesocket(hSocket);
  134. return false;
  135. }
  136. }
  137. /*
  138. this isn't even strictly necessary
  139. CNode::ConnectNode immediately turns the socket back to non-blocking
  140. but we'll turn it back to blocking just in case
  141. */
  142. #ifdef __WXMSW__
  143. fNonblock = 0;
  144. if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
  145. #else
  146. fFlags = fcntl(hSocket, F_GETFL, 0);
  147. if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
  148. #endif
  149. {
  150. closesocket(hSocket);
  151. return false;
  152. }
  153. if (fProxy)
  154. {
  155. printf("proxy connecting %s\n", addrConnect.ToString().c_str());
  156. char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
  157. memcpy(pszSocks4IP + 2, &addrConnect.port, 2);
  158. memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);
  159. char* pszSocks4 = pszSocks4IP;
  160. int nSize = sizeof(pszSocks4IP);
  161. int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
  162. if (ret != nSize)
  163. {
  164. closesocket(hSocket);
  165. return error("Error sending to proxy");
  166. }
  167. char pchRet[8];
  168. if (recv(hSocket, pchRet, 8, 0) != 8)
  169. {
  170. closesocket(hSocket);
  171. return error("Error reading proxy response");
  172. }
  173. if (pchRet[1] != 0x5a)
  174. {
  175. closesocket(hSocket);
  176. if (pchRet[1] != 0x5b)
  177. printf("ERROR: Proxy returned error %d\n", pchRet[1]);
  178. return false;
  179. }
  180. printf("proxy connected %s\n", addrConnect.ToString().c_str());
  181. }
  182. hSocketRet = hSocket;
  183. return true;
  184. }
  185. // portDefault is in host order
  186. bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup, int portDefault, bool fAllowPort)
  187. {
  188. vaddr.clear();
  189. if (pszName[0] == 0)
  190. return false;
  191. int port = portDefault;
  192. char psz[256];
  193. char *pszHost = psz;
  194. strlcpy(psz, pszName, sizeof(psz));
  195. if (fAllowPort)
  196. {
  197. char* pszColon = strrchr(psz+1,':');
  198. char *pszPortEnd = NULL;
  199. int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0;
  200. if (pszColon && pszPortEnd && pszPortEnd[0] == 0)
  201. {
  202. if (psz[0] == '[' && pszColon[-1] == ']')
  203. {
  204. // Future: enable IPv6 colon-notation inside []
  205. pszHost = psz+1;
  206. pszColon[-1] = 0;
  207. }
  208. else
  209. pszColon[0] = 0;
  210. port = portParsed;
  211. if (port < 0 || port > USHRT_MAX)
  212. port = USHRT_MAX;
  213. }
  214. }
  215. unsigned int addrIP = inet_addr(pszHost);
  216. if (addrIP != INADDR_NONE)
  217. {
  218. // valid IP address passed
  219. vaddr.push_back(CAddress(addrIP, port, nServices));
  220. return true;
  221. }
  222. if (!fAllowLookup)
  223. return false;
  224. struct hostent* phostent = gethostbyname(pszHost);
  225. if (!phostent)
  226. return false;
  227. if (phostent->h_addrtype != AF_INET)
  228. return false;
  229. char** ppAddr = phostent->h_addr_list;
  230. while (*ppAddr != NULL && vaddr.size() != nMaxSolutions)
  231. {
  232. CAddress addr(((struct in_addr*)ppAddr[0])->s_addr, port, nServices);
  233. if (addr.IsValid())
  234. vaddr.push_back(addr);
  235. ppAddr++;
  236. }
  237. return (vaddr.size() > 0);
  238. }
  239. // portDefault is in host order
  240. bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup, int portDefault, bool fAllowPort)
  241. {
  242. vector<CAddress> vaddr;
  243. bool fRet = Lookup(pszName, vaddr, nServices, 1, fAllowLookup, portDefault, fAllowPort);
  244. if (fRet)
  245. addr = vaddr[0];
  246. return fRet;
  247. }
  248. bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& 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) != -1)
  269. {
  270. strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
  271. break;
  272. }
  273. }
  274. closesocket(hSocket);
  275. if (strLine.find("<") != -1)
  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. CAddress addr(strLine,0,true);
  281. printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
  282. if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())
  283. return false;
  284. ipRet = addr.ip;
  285. return true;
  286. }
  287. }
  288. closesocket(hSocket);
  289. return error("GetMyExternalIP() : connection closed");
  290. }
  291. // We now get our external IP from the IRC server first and only use this as a backup
  292. bool GetMyExternalIP(unsigned int& ipRet)
  293. {
  294. CAddress addrConnect;
  295. const char* pszGet;
  296. const char* pszKeyword;
  297. if (fUseProxy)
  298. return false;
  299. for (int nLookup = 0; nLookup <= 1; nLookup++)
  300. for (int nHost = 1; nHost <= 2; nHost++)
  301. {
  302. // We should be phasing out our use of sites like these. If we need
  303. // replacements, we should ask for volunteers to put this simple
  304. // php file on their webserver that prints the client IP:
  305. // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
  306. if (nHost == 1)
  307. {
  308. addrConnect = CAddress("91.198.22.70",80); // checkip.dyndns.org
  309. if (nLookup == 1)
  310. {
  311. CAddress addrIP("checkip.dyndns.org", 80, true);
  312. if (addrIP.IsValid())
  313. addrConnect = addrIP;
  314. }
  315. pszGet = "GET / HTTP/1.1\r\n"
  316. "Host: checkip.dyndns.org\r\n"
  317. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  318. "Connection: close\r\n"
  319. "\r\n";
  320. pszKeyword = "Address:";
  321. }
  322. else if (nHost == 2)
  323. {
  324. addrConnect = CAddress("74.208.43.192", 80); // www.showmyip.com
  325. if (nLookup == 1)
  326. {
  327. CAddress addrIP("www.showmyip.com", 80, true);
  328. if (addrIP.IsValid())
  329. addrConnect = addrIP;
  330. }
  331. pszGet = "GET /simple/ HTTP/1.1\r\n"
  332. "Host: www.showmyip.com\r\n"
  333. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  334. "Connection: close\r\n"
  335. "\r\n";
  336. pszKeyword = NULL; // Returns just IP address
  337. }
  338. if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
  339. return true;
  340. }
  341. return false;
  342. }
  343. void ThreadGetMyExternalIP(void* parg)
  344. {
  345. // Wait for IRC to get it first
  346. if (!GetBoolArg("-noirc"))
  347. {
  348. for (int i = 0; i < 2 * 60; i++)
  349. {
  350. Sleep(1000);
  351. if (fGotExternalIP || fShutdown)
  352. return;
  353. }
  354. }
  355. // Fallback in case IRC fails to get it
  356. if (GetMyExternalIP(addrLocalHost.ip))
  357. {
  358. printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
  359. if (addrLocalHost.IsRoutable())
  360. {
  361. // If we already connected to a few before we had our IP, go back and addr them.
  362. // setAddrKnown automatically filters any duplicate sends.
  363. CAddress addr(addrLocalHost);
  364. addr.nTime = GetAdjustedTime();
  365. CRITICAL_BLOCK(cs_vNodes)
  366. BOOST_FOREACH(CNode* pnode, vNodes)
  367. pnode->PushAddress(addr);
  368. }
  369. }
  370. }
  371. bool AddAddress(CAddress addr, int64 nTimePenalty)
  372. {
  373. if (!addr.IsRoutable())
  374. return false;
  375. if (addr.ip == addrLocalHost.ip)
  376. return false;
  377. addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty);
  378. CRITICAL_BLOCK(cs_mapAddresses)
  379. {
  380. map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());
  381. if (it == mapAddresses.end())
  382. {
  383. // New address
  384. printf("AddAddress(%s)\n", addr.ToString().c_str());
  385. mapAddresses.insert(make_pair(addr.GetKey(), addr));
  386. CAddrDB().WriteAddress(addr);
  387. return true;
  388. }
  389. else
  390. {
  391. bool fUpdated = false;
  392. CAddress& addrFound = (*it).second;
  393. if ((addrFound.nServices | addr.nServices) != addrFound.nServices)
  394. {
  395. // Services have been added
  396. addrFound.nServices |= addr.nServices;
  397. fUpdated = true;
  398. }
  399. bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
  400. int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
  401. if (addrFound.nTime < addr.nTime - nUpdateInterval)
  402. {
  403. // Periodically update most recently seen time
  404. addrFound.nTime = addr.nTime;
  405. fUpdated = true;
  406. }
  407. if (fUpdated)
  408. CAddrDB().WriteAddress(addrFound);
  409. }
  410. }
  411. return false;
  412. }
  413. void AddressCurrentlyConnected(const CAddress& addr)
  414. {
  415. CRITICAL_BLOCK(cs_mapAddresses)
  416. {
  417. // Only if it's been published already
  418. map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());
  419. if (it != mapAddresses.end())
  420. {
  421. CAddress& addrFound = (*it).second;
  422. int64 nUpdateInterval = 20 * 60;
  423. if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)
  424. {
  425. // Periodically update most recently seen time
  426. addrFound.nTime = GetAdjustedTime();
  427. CAddrDB addrdb;
  428. addrdb.WriteAddress(addrFound);
  429. }
  430. }
  431. }
  432. }
  433. void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)
  434. {
  435. // If the dialog might get closed before the reply comes back,
  436. // call this in the destructor so it doesn't get called after it's deleted.
  437. CRITICAL_BLOCK(cs_vNodes)
  438. {
  439. BOOST_FOREACH(CNode* pnode, vNodes)
  440. {
  441. CRITICAL_BLOCK(pnode->cs_mapRequests)
  442. {
  443. for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)
  444. {
  445. CRequestTracker& tracker = (*mi).second;
  446. if (tracker.fn == fn && tracker.param1 == param1)
  447. pnode->mapRequests.erase(mi++);
  448. else
  449. mi++;
  450. }
  451. }
  452. }
  453. }
  454. }
  455. //
  456. // Subscription methods for the broadcast and subscription system.
  457. // Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.
  458. //
  459. // The subscription system uses a meet-in-the-middle strategy.
  460. // With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers
  461. // subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.
  462. //
  463. bool AnySubscribed(unsigned int nChannel)
  464. {
  465. if (pnodeLocalHost->IsSubscribed(nChannel))
  466. return true;
  467. CRITICAL_BLOCK(cs_vNodes)
  468. BOOST_FOREACH(CNode* pnode, vNodes)
  469. if (pnode->IsSubscribed(nChannel))
  470. return true;
  471. return false;
  472. }
  473. bool CNode::IsSubscribed(unsigned int nChannel)
  474. {
  475. if (nChannel >= vfSubscribe.size())
  476. return false;
  477. return vfSubscribe[nChannel];
  478. }
  479. void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)
  480. {
  481. if (nChannel >= vfSubscribe.size())
  482. return;
  483. if (!AnySubscribed(nChannel))
  484. {
  485. // Relay subscribe
  486. CRITICAL_BLOCK(cs_vNodes)
  487. BOOST_FOREACH(CNode* pnode, vNodes)
  488. if (pnode != this)
  489. pnode->PushMessage("subscribe", nChannel, nHops);
  490. }
  491. vfSubscribe[nChannel] = true;
  492. }
  493. void CNode::CancelSubscribe(unsigned int nChannel)
  494. {
  495. if (nChannel >= vfSubscribe.size())
  496. return;
  497. // Prevent from relaying cancel if wasn't subscribed
  498. if (!vfSubscribe[nChannel])
  499. return;
  500. vfSubscribe[nChannel] = false;
  501. if (!AnySubscribed(nChannel))
  502. {
  503. // Relay subscription cancel
  504. CRITICAL_BLOCK(cs_vNodes)
  505. BOOST_FOREACH(CNode* pnode, vNodes)
  506. if (pnode != this)
  507. pnode->PushMessage("sub-cancel", nChannel);
  508. }
  509. }
  510. CNode* FindNode(unsigned int ip)
  511. {
  512. CRITICAL_BLOCK(cs_vNodes)
  513. {
  514. BOOST_FOREACH(CNode* pnode, vNodes)
  515. if (pnode->addr.ip == ip)
  516. return (pnode);
  517. }
  518. return NULL;
  519. }
  520. CNode* FindNode(CAddress addr)
  521. {
  522. CRITICAL_BLOCK(cs_vNodes)
  523. {
  524. BOOST_FOREACH(CNode* pnode, vNodes)
  525. if (pnode->addr == addr)
  526. return (pnode);
  527. }
  528. return NULL;
  529. }
  530. CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)
  531. {
  532. if (addrConnect.ip == addrLocalHost.ip)
  533. return NULL;
  534. // Look for an existing connection
  535. CNode* pnode = FindNode(addrConnect.ip);
  536. if (pnode)
  537. {
  538. if (nTimeout != 0)
  539. pnode->AddRef(nTimeout);
  540. else
  541. pnode->AddRef();
  542. return pnode;
  543. }
  544. /// debug print
  545. printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",
  546. addrConnect.ToString().c_str(),
  547. (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,
  548. (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);
  549. CRITICAL_BLOCK(cs_mapAddresses)
  550. mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();
  551. // Connect
  552. SOCKET hSocket;
  553. if (ConnectSocket(addrConnect, hSocket))
  554. {
  555. /// debug print
  556. printf("connected %s\n", addrConnect.ToString().c_str());
  557. // Set to nonblocking
  558. #ifdef __WXMSW__
  559. u_long nOne = 1;
  560. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
  561. printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
  562. #else
  563. if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  564. printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
  565. #endif
  566. // Add node
  567. CNode* pnode = new CNode(hSocket, addrConnect, false);
  568. if (nTimeout != 0)
  569. pnode->AddRef(nTimeout);
  570. else
  571. pnode->AddRef();
  572. CRITICAL_BLOCK(cs_vNodes)
  573. vNodes.push_back(pnode);
  574. pnode->nTimeConnected = GetTime();
  575. return pnode;
  576. }
  577. else
  578. {
  579. return NULL;
  580. }
  581. }
  582. void CNode::CloseSocketDisconnect()
  583. {
  584. fDisconnect = true;
  585. if (hSocket != INVALID_SOCKET)
  586. {
  587. if (fDebug)
  588. printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
  589. printf("disconnecting node %s\n", addr.ToString().c_str());
  590. closesocket(hSocket);
  591. hSocket = INVALID_SOCKET;
  592. }
  593. }
  594. void CNode::Cleanup()
  595. {
  596. // All of a nodes broadcasts and subscriptions are automatically torn down
  597. // when it goes down, so a node has to stay up to keep its broadcast going.
  598. // Cancel subscriptions
  599. for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)
  600. if (vfSubscribe[nChannel])
  601. CancelSubscribe(nChannel);
  602. }
  603. void ThreadSocketHandler(void* parg)
  604. {
  605. IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
  606. try
  607. {
  608. vnThreadsRunning[0]++;
  609. ThreadSocketHandler2(parg);
  610. vnThreadsRunning[0]--;
  611. }
  612. catch (std::exception& e) {
  613. vnThreadsRunning[0]--;
  614. PrintException(&e, "ThreadSocketHandler()");
  615. } catch (...) {
  616. vnThreadsRunning[0]--;
  617. throw; // support pthread_cancel()
  618. }
  619. printf("ThreadSocketHandler exiting\n");
  620. }
  621. void ThreadSocketHandler2(void* parg)
  622. {
  623. printf("ThreadSocketHandler started\n");
  624. list<CNode*> vNodesDisconnected;
  625. int nPrevNodeCount = 0;
  626. loop
  627. {
  628. //
  629. // Disconnect nodes
  630. //
  631. CRITICAL_BLOCK(cs_vNodes)
  632. {
  633. // Disconnect unused nodes
  634. vector<CNode*> vNodesCopy = vNodes;
  635. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  636. {
  637. if (pnode->fDisconnect ||
  638. (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
  639. {
  640. // remove from vNodes
  641. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  642. // close socket and cleanup
  643. pnode->CloseSocketDisconnect();
  644. pnode->Cleanup();
  645. // hold in disconnected pool until all refs are released
  646. pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
  647. if (pnode->fNetworkNode || pnode->fInbound)
  648. pnode->Release();
  649. vNodesDisconnected.push_back(pnode);
  650. }
  651. }
  652. // Delete disconnected nodes
  653. list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  654. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  655. {
  656. // wait until threads are done using it
  657. if (pnode->GetRefCount() <= 0)
  658. {
  659. bool fDelete = false;
  660. TRY_CRITICAL_BLOCK(pnode->cs_vSend)
  661. TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
  662. TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)
  663. TRY_CRITICAL_BLOCK(pnode->cs_inventory)
  664. fDelete = true;
  665. if (fDelete)
  666. {
  667. vNodesDisconnected.remove(pnode);
  668. delete pnode;
  669. }
  670. }
  671. }
  672. }
  673. if (vNodes.size() != nPrevNodeCount)
  674. {
  675. nPrevNodeCount = vNodes.size();
  676. MainFrameRepaint();
  677. }
  678. //
  679. // Find which sockets have data to receive
  680. //
  681. struct timeval timeout;
  682. timeout.tv_sec = 0;
  683. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  684. fd_set fdsetRecv;
  685. fd_set fdsetSend;
  686. fd_set fdsetError;
  687. FD_ZERO(&fdsetRecv);
  688. FD_ZERO(&fdsetSend);
  689. FD_ZERO(&fdsetError);
  690. SOCKET hSocketMax = 0;
  691. if(hListenSocket != INVALID_SOCKET)
  692. FD_SET(hListenSocket, &fdsetRecv);
  693. hSocketMax = max(hSocketMax, hListenSocket);
  694. CRITICAL_BLOCK(cs_vNodes)
  695. {
  696. BOOST_FOREACH(CNode* pnode, vNodes)
  697. {
  698. if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)
  699. continue;
  700. FD_SET(pnode->hSocket, &fdsetRecv);
  701. FD_SET(pnode->hSocket, &fdsetError);
  702. hSocketMax = max(hSocketMax, pnode->hSocket);
  703. TRY_CRITICAL_BLOCK(pnode->cs_vSend)
  704. if (!pnode->vSend.empty())
  705. FD_SET(pnode->hSocket, &fdsetSend);
  706. }
  707. }
  708. vnThreadsRunning[0]--;
  709. int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  710. vnThreadsRunning[0]++;
  711. if (fShutdown)
  712. return;
  713. if (nSelect == SOCKET_ERROR)
  714. {
  715. int nErr = WSAGetLastError();
  716. if (hSocketMax > -1)
  717. {
  718. printf("socket select error %d\n", nErr);
  719. for (int i = 0; i <= hSocketMax; i++)
  720. FD_SET(i, &fdsetRecv);
  721. }
  722. FD_ZERO(&fdsetSend);
  723. FD_ZERO(&fdsetError);
  724. Sleep(timeout.tv_usec/1000);
  725. }
  726. //
  727. // Accept new connections
  728. //
  729. if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
  730. {
  731. struct sockaddr_in sockaddr;
  732. socklen_t len = sizeof(sockaddr);
  733. SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
  734. CAddress addr(sockaddr);
  735. int nInbound = 0;
  736. CRITICAL_BLOCK(cs_vNodes)
  737. BOOST_FOREACH(CNode* pnode, vNodes)
  738. if (pnode->fInbound)
  739. nInbound++;
  740. if (hSocket == INVALID_SOCKET)
  741. {
  742. if (WSAGetLastError() != WSAEWOULDBLOCK)
  743. printf("socket error accept failed: %d\n", WSAGetLastError());
  744. }
  745. else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
  746. {
  747. closesocket(hSocket);
  748. }
  749. else
  750. {
  751. printf("accepted connection %s\n", addr.ToString().c_str());
  752. CNode* pnode = new CNode(hSocket, addr, true);
  753. pnode->AddRef();
  754. CRITICAL_BLOCK(cs_vNodes)
  755. vNodes.push_back(pnode);
  756. }
  757. }
  758. //
  759. // Service each socket
  760. //
  761. vector<CNode*> vNodesCopy;
  762. CRITICAL_BLOCK(cs_vNodes)
  763. {
  764. vNodesCopy = vNodes;
  765. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  766. pnode->AddRef();
  767. }
  768. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  769. {
  770. if (fShutdown)
  771. return;
  772. //
  773. // Receive
  774. //
  775. if (pnode->hSocket == INVALID_SOCKET)
  776. continue;
  777. if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
  778. {
  779. TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
  780. {
  781. CDataStream& vRecv = pnode->vRecv;
  782. unsigned int nPos = vRecv.size();
  783. if (nPos > ReceiveBufferSize()) {
  784. if (!pnode->fDisconnect)
  785. printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
  786. pnode->CloseSocketDisconnect();
  787. }
  788. else {
  789. // typical socket buffer is 8K-64K
  790. char pchBuf[0x10000];
  791. int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  792. if (nBytes > 0)
  793. {
  794. vRecv.resize(nPos + nBytes);
  795. memcpy(&vRecv[nPos], pchBuf, nBytes);
  796. pnode->nLastRecv = GetTime();
  797. }
  798. else if (nBytes == 0)
  799. {
  800. // socket closed gracefully
  801. if (!pnode->fDisconnect)
  802. printf("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. printf("socket recv error %d\n", 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_CRITICAL_BLOCK(pnode->cs_vSend)
  827. {
  828. CDataStream& vSend = pnode->vSend;
  829. if (!vSend.empty())
  830. {
  831. int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
  832. if (nBytes > 0)
  833. {
  834. vSend.erase(vSend.begin(), vSend.begin() + nBytes);
  835. pnode->nLastSend = GetTime();
  836. }
  837. else if (nBytes < 0)
  838. {
  839. // error
  840. int nErr = WSAGetLastError();
  841. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  842. {
  843. printf("socket send error %d\n", nErr);
  844. pnode->CloseSocketDisconnect();
  845. }
  846. }
  847. if (vSend.size() > SendBufferSize()) {
  848. if (!pnode->fDisconnect)
  849. printf("socket send flood control disconnect (%d bytes)\n", vSend.size());
  850. pnode->CloseSocketDisconnect();
  851. }
  852. }
  853. }
  854. }
  855. //
  856. // Inactivity checking
  857. //
  858. if (pnode->vSend.empty())
  859. pnode->nLastSendEmpty = GetTime();
  860. if (GetTime() - pnode->nTimeConnected > 60)
  861. {
  862. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  863. {
  864. printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
  865. pnode->fDisconnect = true;
  866. }
  867. else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
  868. {
  869. printf("socket not sending\n");
  870. pnode->fDisconnect = true;
  871. }
  872. else if (GetTime() - pnode->nLastRecv > 90*60)
  873. {
  874. printf("socket inactivity timeout\n");
  875. pnode->fDisconnect = true;
  876. }
  877. }
  878. }
  879. CRITICAL_BLOCK(cs_vNodes)
  880. {
  881. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  882. pnode->Release();
  883. }
  884. Sleep(10);
  885. }
  886. }
  887. static const char *strDNSSeed[] = {
  888. "bitseed.xf2.org",
  889. "bitseed.bitcoin.org.uk",
  890. "dnsseed.bluematt.me",
  891. };
  892. void DNSAddressSeed()
  893. {
  894. int found = 0;
  895. if (!fTestNet)
  896. {
  897. printf("Loading addresses from DNS seeds (could take a while)\n");
  898. for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
  899. vector<CAddress> vaddr;
  900. if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true))
  901. {
  902. BOOST_FOREACH (CAddress& addr, vaddr)
  903. {
  904. if (addr.GetByte(3) != 127)
  905. {
  906. addr.nTime = 0;
  907. AddAddress(addr);
  908. found++;
  909. }
  910. }
  911. }
  912. }
  913. }
  914. printf("%d addresses found from DNS seeds\n", found);
  915. }
  916. unsigned int pnSeed[] =
  917. {
  918. 0x1ddb1032, 0x6242ce40, 0x52d6a445, 0x2dd7a445, 0x8a53cd47, 0x73263750, 0xda23c257, 0xecd4ed57,
  919. 0x0a40ec59, 0x75dce160, 0x7df76791, 0x89370bad, 0xa4f214ad, 0x767700ae, 0x638b0418, 0x868a1018,
  920. 0xcd9f332e, 0x0129653e, 0xcc92dc3e, 0x96671640, 0x56487e40, 0x5b66f440, 0xb1d01f41, 0xf1dc6041,
  921. 0xc1d12b42, 0x86ba1243, 0x6be4df43, 0x6d4cef43, 0xd18e0644, 0x1ab0b344, 0x6584a345, 0xe7c1a445,
  922. 0x58cea445, 0xc5daa445, 0x21dda445, 0x3d3b5346, 0x13e55347, 0x1080d24a, 0x8e611e4b, 0x81518e4b,
  923. 0x6c839e4b, 0xe2ad0a4c, 0xfbbc0a4c, 0x7f5b6e4c, 0x7244224e, 0x1300554e, 0x20690652, 0x5a48b652,
  924. 0x75c5c752, 0x4335cc54, 0x340fd154, 0x87c07455, 0x087b2b56, 0x8a133a57, 0xac23c257, 0x70374959,
  925. 0xfb63d45b, 0xb9a1685c, 0x180d765c, 0x674f645d, 0x04d3495e, 0x1de44b5e, 0x4ee8a362, 0x0ded1b63,
  926. 0xc1b04b6d, 0x8d921581, 0x97b7ea82, 0x1cf83a8e, 0x91490bad, 0x09dc75ae, 0x9a6d79ae, 0xa26d79ae,
  927. 0x0fd08fae, 0x0f3e3fb2, 0x4f944fb2, 0xcca448b8, 0x3ecd6ab8, 0xa9d5a5bc, 0x8d0119c1, 0x045997d5,
  928. 0xca019dd9, 0x0d526c4d, 0xabf1ba44, 0x66b1ab55, 0x1165f462, 0x3ed7cbad, 0xa38fae6e, 0x3bd2cbad,
  929. 0xd36f0547, 0x20df7840, 0x7a337742, 0x549f8e4b, 0x9062365c, 0xd399f562, 0x2b5274a1, 0x8edfa153,
  930. 0x3bffb347, 0x7074bf58, 0xb74fcbad, 0x5b5a795b, 0x02fa29ce, 0x5a6738d4, 0xe8a1d23e, 0xef98c445,
  931. 0x4b0f494c, 0xa2bc1e56, 0x7694ad63, 0xa4a800c3, 0x05fda6cd, 0x9f22175e, 0x364a795b, 0x536285d5,
  932. 0xac44c9d4, 0x0b06254d, 0x150c2fd4, 0x32a50dcc, 0xfd79ce48, 0xf15cfa53, 0x66c01e60, 0x6bc26661,
  933. 0xc03b47ae, 0x4dda1b81, 0x3285a4c1, 0x883ca96d, 0x35d60a4c, 0xdae09744, 0x2e314d61, 0x84e247cf,
  934. 0x6c814552, 0x3a1cc658, 0x98d8f382, 0xe584cb5b, 0x15e86057, 0x7b01504e, 0xd852dd48, 0x56382f56,
  935. 0x0a5df454, 0xa0d18d18, 0x2e89b148, 0xa79c114c, 0xcbdcd054, 0x5523bc43, 0xa9832640, 0x8a066144,
  936. 0x3894c3bc, 0xab76bf58, 0x6a018ac1, 0xfebf4f43, 0x2f26c658, 0x31102f4e, 0x85e929d5, 0x2a1c175e,
  937. 0xfc6c2cd1, 0x27b04b6d, 0xdf024650, 0x161748b8, 0x28be6580, 0x57be6580, 0x1cee677a, 0xaa6bb742,
  938. 0x9a53964b, 0x0a5a2d4d, 0x2434c658, 0x9a494f57, 0x1ebb0e48, 0xf610b85d, 0x077ecf44, 0x085128bc,
  939. 0x5ba17a18, 0x27ca1b42, 0xf8a00b56, 0xfcd4c257, 0xcf2fc15e, 0xd897e052, 0x4cada04f, 0x2f35f6d5,
  940. 0x382ce8c9, 0xe523984b, 0x3f946846, 0x60c8be43, 0x41da6257, 0xde0be142, 0xae8a544b, 0xeff0c254,
  941. 0x1e0f795b, 0xaeb28890, 0xca16acd9, 0x1e47ddd8, 0x8c8c4829, 0xd27dc747, 0xd53b1663, 0x4096b163,
  942. 0x9c8dd958, 0xcb12f860, 0x9e79305c, 0x40c1a445, 0x4a90c2bc, 0x2c3a464d, 0x2727f23c, 0x30b04b6d,
  943. 0x59024cb8, 0xa091e6ad, 0x31b04b6d, 0xc29d46a6, 0x63934fb2, 0xd9224dbe, 0x9f5910d8, 0x7f530a6b,
  944. 0x752e9c95, 0x65453548, 0xa484be46, 0xce5a1b59, 0x710e0718, 0x46a13d18, 0xdaaf5318, 0xc4a8ff53,
  945. 0x87abaa52, 0xb764cf51, 0xb2025d4a, 0x6d351e41, 0xc035c33e, 0xa432c162, 0x61ef34ae, 0xd16fddbc,
  946. 0x0870e8c1, 0x3070e8c1, 0x9c71e8c1, 0xa4992363, 0x85a1f663, 0x4184e559, 0x18d96ed8, 0x17b8dbd5,
  947. 0x60e7cd18, 0xe5ee104c, 0xab17ac62, 0x1e786e1b, 0x5d23b762, 0xf2388fae, 0x88270360, 0x9e5b3d80,
  948. 0x7da518b2, 0xb5613b45, 0x1ad41f3e, 0xd550854a, 0x8617e9a9, 0x925b229c, 0xf2e92542, 0x47af0544,
  949. 0x73b5a843, 0xb9b7a0ad, 0x03a748d0, 0x0a6ff862, 0x6694df62, 0x3bfac948, 0x8e098f4f, 0x746916c3,
  950. 0x02f38e4f, 0x40bb1243, 0x6a54d162, 0x6008414b, 0xa513794c, 0x514aa343, 0x63781747, 0xdbb6795b,
  951. 0xed065058, 0x42d24b46, 0x1518794c, 0x9b271681, 0x73e4ffad, 0x0654784f, 0x438dc945, 0x641846a6,
  952. 0x2d1b0944, 0x94b59148, 0x8d369558, 0xa5a97662, 0x8b705b42, 0xce9204ae, 0x8d584450, 0x2df61555,
  953. 0xeebff943, 0x2e75fb4d, 0x3ef8fc57, 0x9921135e, 0x8e31042e, 0xb5afad43, 0x89ecedd1, 0x9cfcc047,
  954. 0x8fcd0f4c, 0xbe49f5ad, 0x146a8d45, 0x98669ab8, 0x98d9175e, 0xd1a8e46d, 0x839a3ab8, 0x40a0016c,
  955. 0x6d27c257, 0x977fffad, 0x7baa5d5d, 0x1213be43, 0xb167e5a9, 0x640fe8ca, 0xbc9ea655, 0x0f820a4c,
  956. 0x0f097059, 0x69ac957c, 0x366d8453, 0xb1ba2844, 0x8857f081, 0x70b5be63, 0xc545454b, 0xaf36ded1,
  957. 0xb5a4b052, 0x21f062d1, 0x72ab89b2, 0x74a45318, 0x8312e6bc, 0xb916965f, 0x8aa7c858, 0xfe7effad,
  958. };
  959. void ThreadOpenConnections(void* parg)
  960. {
  961. IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
  962. try
  963. {
  964. vnThreadsRunning[1]++;
  965. ThreadOpenConnections2(parg);
  966. vnThreadsRunning[1]--;
  967. }
  968. catch (std::exception& e) {
  969. vnThreadsRunning[1]--;
  970. PrintException(&e, "ThreadOpenConnections()");
  971. } catch (...) {
  972. vnThreadsRunning[1]--;
  973. PrintException(NULL, "ThreadOpenConnections()");
  974. }
  975. printf("ThreadOpenConnections exiting\n");
  976. }
  977. void ThreadOpenConnections2(void* parg)
  978. {
  979. printf("ThreadOpenConnections started\n");
  980. // Connect to specific addresses
  981. if (mapArgs.count("-connect"))
  982. {
  983. for (int64 nLoop = 0;; nLoop++)
  984. {
  985. BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
  986. {
  987. CAddress addr(strAddr, fAllowDNS);
  988. if (addr.IsValid())
  989. OpenNetworkConnection(addr);
  990. for (int i = 0; i < 10 && i < nLoop; i++)
  991. {
  992. Sleep(500);
  993. if (fShutdown)
  994. return;
  995. }
  996. }
  997. }
  998. }
  999. // Connect to manually added nodes first
  1000. if (mapArgs.count("-addnode"))
  1001. {
  1002. BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
  1003. {
  1004. CAddress addr(strAddr, fAllowDNS);
  1005. if (addr.IsValid())
  1006. {
  1007. OpenNetworkConnection(addr);
  1008. Sleep(500);
  1009. if (fShutdown)
  1010. return;
  1011. }
  1012. }
  1013. }
  1014. // Initiate network connections
  1015. int64 nStart = GetTime();
  1016. loop
  1017. {
  1018. // Limit outbound connections
  1019. vnThreadsRunning[1]--;
  1020. Sleep(500);
  1021. loop
  1022. {
  1023. int nOutbound = 0;
  1024. CRITICAL_BLOCK(cs_vNodes)
  1025. BOOST_FOREACH(CNode* pnode, vNodes)
  1026. if (!pnode->fInbound)
  1027. nOutbound++;
  1028. int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;
  1029. nMaxOutboundConnections = min(nMaxOutboundConnections, (int)GetArg("-maxconnections", 125));
  1030. if (nOutbound < nMaxOutboundConnections)
  1031. break;
  1032. Sleep(2000);
  1033. if (fShutdown)
  1034. return;
  1035. }
  1036. vnThreadsRunning[1]++;
  1037. if (fShutdown)
  1038. return;
  1039. CRITICAL_BLOCK(cs_mapAddresses)
  1040. {
  1041. // Add seed nodes if IRC isn't working
  1042. static bool fSeedUsed;
  1043. bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
  1044. if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)
  1045. {
  1046. for (int i = 0; i < ARRAYLEN(pnSeed); i++)
  1047. {
  1048. // It'll only connect to one or two seed nodes because once it connects,
  1049. // it'll get a pile of addresses with newer timestamps.
  1050. CAddress addr;
  1051. addr.ip = pnSeed[i];
  1052. addr.nTime = 0;
  1053. AddAddress(addr);
  1054. }
  1055. fSeedUsed = true;
  1056. }
  1057. if (fSeedUsed && mapAddresses.size() > ARRAYLEN(pnSeed) + 100)
  1058. {
  1059. // Disconnect seed nodes
  1060. set<unsigned int> setSeed(pnSeed, pnSeed + ARRAYLEN(pnSeed));
  1061. static int64 nSeedDisconnected;
  1062. if (nSeedDisconnected == 0)
  1063. {
  1064. nSeedDisconnected = GetTime();
  1065. CRITICAL_BLOCK(cs_vNodes)
  1066. BOOST_FOREACH(CNode* pnode, vNodes)
  1067. if (setSeed.count(pnode->addr.ip))
  1068. pnode->fDisconnect = true;
  1069. }
  1070. // Keep setting timestamps to 0 so they won't reconnect
  1071. if (GetTime() - nSeedDisconnected < 60 * 60)
  1072. {
  1073. BOOST_FOREACH(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses)
  1074. {
  1075. if (setSeed.count(item.second.ip) && item.second.nTime != 0)
  1076. {
  1077. item.second.nTime = 0;
  1078. CAddrDB().WriteAddress(item.second);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. //
  1085. // Choose an address to connect to based on most recently seen
  1086. //
  1087. CAddress addrConnect;
  1088. int64 nBest = INT64_MIN;
  1089. // Only connect to one address per a.b.?.? range.
  1090. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
  1091. set<unsigned int> setConnected;
  1092. CRITICAL_BLOCK(cs_vNodes)
  1093. BOOST_FOREACH(CNode* pnode, vNodes)
  1094. setConnected.insert(pnode->addr.ip & 0x0000ffff);
  1095. CRITICAL_BLOCK(cs_mapAddresses)
  1096. {
  1097. BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
  1098. {
  1099. const CAddress& addr = item.second;
  1100. if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))
  1101. continue;
  1102. int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime;
  1103. int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry;
  1104. // Randomize the order in a deterministic way, putting the standard port first
  1105. int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);
  1106. if (addr.port != htons(GetDefaultPort()))
  1107. nRandomizer += 2 * 60 * 60;
  1108. // Last seen Base retry frequency
  1109. // <1 hour 10 min
  1110. // 1 hour 1 hour
  1111. // 4 hours 2 hours
  1112. // 24 hours 5 hours
  1113. // 48 hours 7 hours
  1114. // 7 days 13 hours
  1115. // 30 days 27 hours
  1116. // 90 days 46 hours
  1117. // 365 days 93 hours
  1118. int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);
  1119. // Fast reconnect for one hour after last seen
  1120. if (nSinceLastSeen < 60 * 60)
  1121. nDelay = 10 * 60;
  1122. // Limit retry frequency
  1123. if (nSinceLastTry < nDelay)
  1124. continue;
  1125. // If we have IRC, we'll be notified when they first come online,
  1126. // and again every 24 hours by the refresh broadcast.
  1127. if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)
  1128. continue;
  1129. // Only try the old stuff if we don't have enough connections
  1130. if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60)
  1131. continue;
  1132. // If multiple addresses are ready, prioritize by time since
  1133. // last seen and time since last tried.
  1134. int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;
  1135. if (nScore > nBest)
  1136. {
  1137. nBest = nScore;
  1138. addrConnect = addr;
  1139. }
  1140. }
  1141. }
  1142. if (addrConnect.IsValid())
  1143. OpenNetworkConnection(addrConnect);
  1144. }
  1145. }
  1146. bool OpenNetworkConnection(const CAddress& addrConnect)
  1147. {
  1148. //
  1149. // Initiate outbound network connection
  1150. //
  1151. if (fShutdown)
  1152. return false;
  1153. if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))
  1154. return false;
  1155. vnThreadsRunning[1]--;
  1156. CNode* pnode = ConnectNode(addrConnect);
  1157. vnThreadsRunning[1]++;
  1158. if (fShutdown)
  1159. return false;
  1160. if (!pnode)
  1161. return false;
  1162. pnode->fNetworkNode = true;
  1163. return true;
  1164. }
  1165. void ThreadMessageHandler(void* parg)
  1166. {
  1167. IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
  1168. try
  1169. {
  1170. vnThreadsRunning[2]++;
  1171. ThreadMessageHandler2(parg);
  1172. vnThreadsRunning[2]--;
  1173. }
  1174. catch (std::exception& e) {
  1175. vnThreadsRunning[2]--;
  1176. PrintException(&e, "ThreadMessageHandler()");
  1177. } catch (...) {
  1178. vnThreadsRunning[2]--;
  1179. PrintException(NULL, "ThreadMessageHandler()");
  1180. }
  1181. printf("ThreadMessageHandler exiting\n");
  1182. }
  1183. void ThreadMessageHandler2(void* parg)
  1184. {
  1185. printf("ThreadMessageHandler started\n");
  1186. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1187. while (!fShutdown)
  1188. {
  1189. vector<CNode*> vNodesCopy;
  1190. CRITICAL_BLOCK(cs_vNodes)
  1191. {
  1192. vNodesCopy = vNodes;
  1193. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1194. pnode->AddRef();
  1195. }
  1196. // Poll the connected nodes for messages
  1197. CNode* pnodeTrickle = NULL;
  1198. if (!vNodesCopy.empty())
  1199. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1200. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1201. {
  1202. // Receive messages
  1203. TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
  1204. ProcessMessages(pnode);
  1205. if (fShutdown)
  1206. return;
  1207. // Send messages
  1208. TRY_CRITICAL_BLOCK(pnode->cs_vSend)
  1209. SendMessages(pnode, pnode == pnodeTrickle);
  1210. if (fShutdown)
  1211. return;
  1212. }
  1213. CRITICAL_BLOCK(cs_vNodes)
  1214. {
  1215. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1216. pnode->Release();
  1217. }
  1218. // Wait and allow messages to bunch up.
  1219. // Reduce vnThreadsRunning so StopNode has permission to exit while
  1220. // we're sleeping, but we must always check fShutdown after doing this.
  1221. vnThreadsRunning[2]--;
  1222. Sleep(100);
  1223. if (fRequestShutdown)
  1224. Shutdown(NULL);
  1225. vnThreadsRunning[2]++;
  1226. if (fShutdown)
  1227. return;
  1228. }
  1229. }
  1230. bool BindListenPort(string& strError)
  1231. {
  1232. strError = "";
  1233. int nOne = 1;
  1234. addrLocalHost.port = htons(GetListenPort());
  1235. #ifdef __WXMSW__
  1236. // Initialize Windows Sockets
  1237. WSADATA wsadata;
  1238. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  1239. if (ret != NO_ERROR)
  1240. {
  1241. strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
  1242. printf("%s\n", strError.c_str());
  1243. return false;
  1244. }
  1245. #endif
  1246. // Create socket for listening for incoming connections
  1247. hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1248. if (hListenSocket == INVALID_SOCKET)
  1249. {
  1250. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
  1251. printf("%s\n", strError.c_str());
  1252. return false;
  1253. }
  1254. #ifdef BSD
  1255. // Different way of disabling SIGPIPE on BSD
  1256. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1257. #endif
  1258. #ifndef __WXMSW__
  1259. // Allow binding if the port is still in TIME_WAIT state after
  1260. // the program was closed and restarted. Not an issue on windows.
  1261. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1262. #endif
  1263. #ifdef __WXMSW__
  1264. // Set to nonblocking, incoming connections will also inherit this
  1265. if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
  1266. #else
  1267. if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  1268. #endif
  1269. {
  1270. strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
  1271. printf("%s\n", strError.c_str());
  1272. return false;
  1273. }
  1274. // The sockaddr_in structure specifies the address family,
  1275. // IP address, and port for the socket that is being bound
  1276. struct sockaddr_in sockaddr;
  1277. memset(&sockaddr, 0, sizeof(sockaddr));
  1278. sockaddr.sin_family = AF_INET;
  1279. sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer
  1280. sockaddr.sin_port = htons(GetListenPort());
  1281. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
  1282. {
  1283. int nErr = WSAGetLastError();
  1284. if (nErr == WSAEADDRINUSE)
  1285. strError = strprintf(_("Unable to bind to port %d on this computer. Bitcoin is probably already running."), ntohs(sockaddr.sin_port));
  1286. else
  1287. strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);
  1288. printf("%s\n", strError.c_str());
  1289. return false;
  1290. }
  1291. printf("Bound to port %d\n", ntohs(sockaddr.sin_port));
  1292. // Listen for incoming connections
  1293. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1294. {
  1295. strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
  1296. printf("%s\n", strError.c_str());
  1297. return false;
  1298. }
  1299. return true;
  1300. }
  1301. void StartNode(void* parg)
  1302. {
  1303. if (pnodeLocalHost == NULL)
  1304. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", 0, false, nLocalServices));
  1305. #ifdef __WXMSW__
  1306. // Get local host ip
  1307. char pszHostName[1000] = "";
  1308. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1309. {
  1310. vector<CAddress> vaddr;
  1311. if (Lookup(pszHostName, vaddr, nLocalServices, -1, true))
  1312. BOOST_FOREACH (const CAddress &addr, vaddr)
  1313. if (addr.GetByte(3) != 127)
  1314. {
  1315. addrLocalHost = addr;

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