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

net.cpp 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "irc.h"
  6. #include "db.h"
  7. #include "net.h"
  8. #include "init.h"
  9. #include "strlcpy.h"
  10. #include "addrman.h"
  11. #include "ui_interface.h"
  12. #ifdef WIN32
  13. #include <string.h>
  14. #endif
  15. #ifdef USE_UPNP
  16. #include <miniupnpc/miniwget.h>
  17. #include <miniupnpc/miniupnpc.h>
  18. #include <miniupnpc/upnpcommands.h>
  19. #include <miniupnpc/upnperrors.h>
  20. #endif
  21. using namespace std;
  22. using namespace boost;
  23. static const int MAX_OUTBOUND_CONNECTIONS = 8;
  24. void ThreadMessageHandler2(void* parg);
  25. void ThreadSocketHandler2(void* parg);
  26. void ThreadOpenConnections2(void* parg);
  27. void ThreadOpenAddedConnections2(void* parg);
  28. #ifdef USE_UPNP
  29. void ThreadMapPort2(void* parg);
  30. #endif
  31. void ThreadDNSAddressSeed2(void* parg);
  32. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
  33. struct LocalServiceInfo {
  34. int nScore;
  35. int nPort;
  36. };
  37. //
  38. // Global state variables
  39. //
  40. bool fClient = false;
  41. bool fDiscover = true;
  42. bool fUseUPnP = false;
  43. uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
  44. static CCriticalSection cs_mapLocalHost;
  45. static map<CNetAddr, LocalServiceInfo> mapLocalHost;
  46. static bool vfReachable[NET_MAX] = {};
  47. static bool vfLimited[NET_MAX] = {};
  48. static CNode* pnodeLocalHost = NULL;
  49. uint64 nLocalHostNonce = 0;
  50. array<int, THREAD_MAX> vnThreadsRunning;
  51. static std::vector<SOCKET> vhListenSocket;
  52. CAddrMan addrman;
  53. vector<CNode*> vNodes;
  54. CCriticalSection cs_vNodes;
  55. map<CInv, CDataStream> mapRelay;
  56. deque<pair<int64, CInv> > vRelayExpiration;
  57. CCriticalSection cs_mapRelay;
  58. map<CInv, int64> mapAlreadyAskedFor;
  59. static deque<string> vOneShots;
  60. CCriticalSection cs_vOneShots;
  61. set<CNetAddr> setservAddNodeAddresses;
  62. CCriticalSection cs_setservAddNodeAddresses;
  63. static CSemaphore *semOutbound = NULL;
  64. void AddOneShot(string strDest)
  65. {
  66. LOCK(cs_vOneShots);
  67. vOneShots.push_back(strDest);
  68. }
  69. unsigned short GetListenPort()
  70. {
  71. return (unsigned short)(GetArg("-port", GetDefaultPort()));
  72. }
  73. void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
  74. {
  75. // Filter out duplicate requests
  76. if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
  77. return;
  78. pindexLastGetBlocksBegin = pindexBegin;
  79. hashLastGetBlocksEnd = hashEnd;
  80. PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
  81. }
  82. // find 'best' local address for a particular peer
  83. bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
  84. {
  85. if (fNoListen)
  86. return false;
  87. int nBestScore = -1;
  88. int nBestReachability = -1;
  89. {
  90. LOCK(cs_mapLocalHost);
  91. for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
  92. {
  93. int nScore = (*it).second.nScore;
  94. int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
  95. if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
  96. {
  97. addr = CService((*it).first, (*it).second.nPort);
  98. nBestReachability = nReachability;
  99. nBestScore = nScore;
  100. }
  101. }
  102. }
  103. return nBestScore >= 0;
  104. }
  105. // get best local address for a particular peer as a CAddress
  106. CAddress GetLocalAddress(const CNetAddr *paddrPeer)
  107. {
  108. CAddress ret(CService("0.0.0.0",0),0);
  109. CService addr;
  110. if (GetLocal(addr, paddrPeer))
  111. {
  112. ret = CAddress(addr);
  113. ret.nServices = nLocalServices;
  114. ret.nTime = GetAdjustedTime();
  115. }
  116. return ret;
  117. }
  118. bool RecvLine(SOCKET hSocket, string& strLine)
  119. {
  120. strLine = "";
  121. loop
  122. {
  123. char c;
  124. int nBytes = recv(hSocket, &c, 1, 0);
  125. if (nBytes > 0)
  126. {
  127. if (c == '\n')
  128. continue;
  129. if (c == '\r')
  130. return true;
  131. strLine += c;
  132. if (strLine.size() >= 9000)
  133. return true;
  134. }
  135. else if (nBytes <= 0)
  136. {
  137. if (fShutdown)
  138. return false;
  139. if (nBytes < 0)
  140. {
  141. int nErr = WSAGetLastError();
  142. if (nErr == WSAEMSGSIZE)
  143. continue;
  144. if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
  145. {
  146. Sleep(10);
  147. continue;
  148. }
  149. }
  150. if (!strLine.empty())
  151. return true;
  152. if (nBytes == 0)
  153. {
  154. // socket closed
  155. printf("socket closed\n");
  156. return false;
  157. }
  158. else
  159. {
  160. // socket error
  161. int nErr = WSAGetLastError();
  162. printf("recv failed: %d\n", nErr);
  163. return false;
  164. }
  165. }
  166. }
  167. }
  168. // used when scores of local addresses may have changed
  169. // pushes better local address to peers
  170. void static AdvertizeLocal()
  171. {
  172. LOCK(cs_vNodes);
  173. BOOST_FOREACH(CNode* pnode, vNodes)
  174. {
  175. if (pnode->fSuccessfullyConnected)
  176. {
  177. CAddress addrLocal = GetLocalAddress(&pnode->addr);
  178. if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
  179. {
  180. pnode->PushAddress(addrLocal);
  181. pnode->addrLocal = addrLocal;
  182. }
  183. }
  184. }
  185. }
  186. void SetReachable(enum Network net, bool fFlag)
  187. {
  188. LOCK(cs_mapLocalHost);
  189. vfReachable[net] = fFlag;
  190. if (net == NET_IPV6 && fFlag)
  191. vfReachable[NET_IPV4] = true;
  192. }
  193. // learn a new local address
  194. bool AddLocal(const CService& addr, int nScore)
  195. {
  196. if (!addr.IsRoutable())
  197. return false;
  198. if (!fDiscover && nScore < LOCAL_MANUAL)
  199. return false;
  200. if (IsLimited(addr))
  201. return false;
  202. printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
  203. {
  204. LOCK(cs_mapLocalHost);
  205. bool fAlready = mapLocalHost.count(addr) > 0;
  206. LocalServiceInfo &info = mapLocalHost[addr];
  207. if (!fAlready || nScore >= info.nScore) {
  208. info.nScore = nScore;
  209. info.nPort = addr.GetPort() + (fAlready ? 1 : 0);
  210. }
  211. SetReachable(addr.GetNetwork());
  212. }
  213. AdvertizeLocal();
  214. return true;
  215. }
  216. bool AddLocal(const CNetAddr &addr, int nScore)
  217. {
  218. return AddLocal(CService(addr, GetListenPort()), nScore);
  219. }
  220. /** Make a particular network entirely off-limits (no automatic connects to it) */
  221. void SetLimited(enum Network net, bool fLimited)
  222. {
  223. if (net == NET_UNROUTABLE)
  224. return;
  225. LOCK(cs_mapLocalHost);
  226. vfLimited[net] = fLimited;
  227. }
  228. bool IsLimited(enum Network net)
  229. {
  230. LOCK(cs_mapLocalHost);
  231. return vfLimited[net];
  232. }
  233. bool IsLimited(const CNetAddr &addr)
  234. {
  235. return IsLimited(addr.GetNetwork());
  236. }
  237. /** vote for a local address */
  238. bool SeenLocal(const CService& addr)
  239. {
  240. {
  241. LOCK(cs_mapLocalHost);
  242. if (mapLocalHost.count(addr) == 0)
  243. return false;
  244. mapLocalHost[addr].nScore++;
  245. }
  246. AdvertizeLocal();
  247. return true;
  248. }
  249. /** check whether a given address is potentially local */
  250. bool IsLocal(const CService& addr)
  251. {
  252. LOCK(cs_mapLocalHost);
  253. return mapLocalHost.count(addr) > 0;
  254. }
  255. /** check whether a given address is in a network we can probably connect to */
  256. bool IsReachable(const CNetAddr& addr)
  257. {
  258. LOCK(cs_mapLocalHost);
  259. enum Network net = addr.GetNetwork();
  260. return vfReachable[net] && !vfLimited[net];
  261. }
  262. bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
  263. {
  264. SOCKET hSocket;
  265. if (!ConnectSocket(addrConnect, hSocket))
  266. return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
  267. send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
  268. string strLine;
  269. while (RecvLine(hSocket, strLine))
  270. {
  271. if (strLine.empty()) // HTTP response is separated from headers by blank line
  272. {
  273. loop
  274. {
  275. if (!RecvLine(hSocket, strLine))
  276. {
  277. closesocket(hSocket);
  278. return false;
  279. }
  280. if (pszKeyword == NULL)
  281. break;
  282. if (strLine.find(pszKeyword) != string::npos)
  283. {
  284. strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
  285. break;
  286. }
  287. }
  288. closesocket(hSocket);
  289. if (strLine.find("<") != string::npos)
  290. strLine = strLine.substr(0, strLine.find("<"));
  291. strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
  292. while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
  293. strLine.resize(strLine.size()-1);
  294. CService addr(strLine,0,true);
  295. printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
  296. if (!addr.IsValid() || !addr.IsRoutable())
  297. return false;
  298. ipRet.SetIP(addr);
  299. return true;
  300. }
  301. }
  302. closesocket(hSocket);
  303. return error("GetMyExternalIP() : connection closed");
  304. }
  305. // We now get our external IP from the IRC server first and only use this as a backup
  306. bool GetMyExternalIP(CNetAddr& ipRet)
  307. {
  308. CService addrConnect;
  309. const char* pszGet;
  310. const char* pszKeyword;
  311. for (int nLookup = 0; nLookup <= 1; nLookup++)
  312. for (int nHost = 1; nHost <= 2; nHost++)
  313. {
  314. // We should be phasing out our use of sites like these. If we need
  315. // replacements, we should ask for volunteers to put this simple
  316. // php file on their webserver that prints the client IP:
  317. // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
  318. if (nHost == 1)
  319. {
  320. addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
  321. if (nLookup == 1)
  322. {
  323. CService addrIP("checkip.dyndns.org", 80, true);
  324. if (addrIP.IsValid())
  325. addrConnect = addrIP;
  326. }
  327. pszGet = "GET / HTTP/1.1\r\n"
  328. "Host: checkip.dyndns.org\r\n"
  329. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  330. "Connection: close\r\n"
  331. "\r\n";
  332. pszKeyword = "Address:";
  333. }
  334. else if (nHost == 2)
  335. {
  336. addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
  337. if (nLookup == 1)
  338. {
  339. CService addrIP("www.showmyip.com", 80, true);
  340. if (addrIP.IsValid())
  341. addrConnect = addrIP;
  342. }
  343. pszGet = "GET /simple/ HTTP/1.1\r\n"
  344. "Host: www.showmyip.com\r\n"
  345. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  346. "Connection: close\r\n"
  347. "\r\n";
  348. pszKeyword = NULL; // Returns just IP address
  349. }
  350. if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
  351. return true;
  352. }
  353. return false;
  354. }
  355. void ThreadGetMyExternalIP(void* parg)
  356. {
  357. CNetAddr addrLocalHost;
  358. if (GetMyExternalIP(addrLocalHost))
  359. {
  360. printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
  361. AddLocal(addrLocalHost, LOCAL_HTTP);
  362. }
  363. }
  364. void AddressCurrentlyConnected(const CService& addr)
  365. {
  366. addrman.Connected(addr);
  367. }
  368. CNode* FindNode(const CNetAddr& ip)
  369. {
  370. {
  371. LOCK(cs_vNodes);
  372. BOOST_FOREACH(CNode* pnode, vNodes)
  373. if ((CNetAddr)pnode->addr == ip)
  374. return (pnode);
  375. }
  376. return NULL;
  377. }
  378. CNode* FindNode(std::string addrName)
  379. {
  380. LOCK(cs_vNodes);
  381. BOOST_FOREACH(CNode* pnode, vNodes)
  382. if (pnode->addrName == addrName)
  383. return (pnode);
  384. return NULL;
  385. }
  386. CNode* FindNode(const CService& addr)
  387. {
  388. {
  389. LOCK(cs_vNodes);
  390. BOOST_FOREACH(CNode* pnode, vNodes)
  391. if ((CService)pnode->addr == addr)
  392. return (pnode);
  393. }
  394. return NULL;
  395. }
  396. CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
  397. {
  398. if (pszDest == NULL) {
  399. if (IsLocal(addrConnect))
  400. return NULL;
  401. // Look for an existing connection
  402. CNode* pnode = FindNode((CService)addrConnect);
  403. if (pnode)
  404. {
  405. if (nTimeout != 0)
  406. pnode->AddRef(nTimeout);
  407. else
  408. pnode->AddRef();
  409. return pnode;
  410. }
  411. }
  412. /// debug print
  413. printf("trying connection %s lastseen=%.1fhrs\n",
  414. pszDest ? pszDest : addrConnect.ToString().c_str(),
  415. pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
  416. // Connect
  417. SOCKET hSocket;
  418. if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
  419. {
  420. addrman.Attempt(addrConnect);
  421. /// debug print
  422. printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
  423. // Set to nonblocking
  424. #ifdef WIN32
  425. u_long nOne = 1;
  426. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
  427. printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
  428. #else
  429. if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  430. printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
  431. #endif
  432. // Add node
  433. CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
  434. if (nTimeout != 0)
  435. pnode->AddRef(nTimeout);
  436. else
  437. pnode->AddRef();
  438. {
  439. LOCK(cs_vNodes);
  440. vNodes.push_back(pnode);
  441. }
  442. pnode->nTimeConnected = GetTime();
  443. return pnode;
  444. }
  445. else
  446. {
  447. return NULL;
  448. }
  449. }
  450. void CNode::CloseSocketDisconnect()
  451. {
  452. fDisconnect = true;
  453. if (hSocket != INVALID_SOCKET)
  454. {
  455. printf("disconnecting node %s\n", addrName.c_str());
  456. closesocket(hSocket);
  457. hSocket = INVALID_SOCKET;
  458. vRecv.clear();
  459. }
  460. }
  461. void CNode::Cleanup()
  462. {
  463. }
  464. void CNode::PushVersion()
  465. {
  466. /// when NTP implemented, change to just nTime = GetAdjustedTime()
  467. int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
  468. CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
  469. CAddress addrMe = GetLocalAddress(&addr);
  470. RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
  471. printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
  472. PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
  473. nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
  474. }
  475. std::map<CNetAddr, int64> CNode::setBanned;
  476. CCriticalSection CNode::cs_setBanned;
  477. void CNode::ClearBanned()
  478. {
  479. setBanned.clear();
  480. }
  481. bool CNode::IsBanned(CNetAddr ip)
  482. {
  483. bool fResult = false;
  484. {
  485. LOCK(cs_setBanned);
  486. std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
  487. if (i != setBanned.end())
  488. {
  489. int64 t = (*i).second;
  490. if (GetTime() < t)
  491. fResult = true;
  492. }
  493. }
  494. return fResult;
  495. }
  496. bool CNode::Misbehaving(int howmuch)
  497. {
  498. if (addr.IsLocal())
  499. {
  500. printf("Warning: local node %s misbehaving\n", addrName.c_str());
  501. return false;
  502. }
  503. nMisbehavior += howmuch;
  504. if (nMisbehavior >= GetArg("-banscore", 100))
  505. {
  506. int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
  507. {
  508. LOCK(cs_setBanned);
  509. if (setBanned[addr] < banTime)
  510. setBanned[addr] = banTime;
  511. }
  512. CloseSocketDisconnect();
  513. printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior);
  514. return true;
  515. }
  516. return false;
  517. }
  518. #undef X
  519. #define X(name) stats.name = name
  520. void CNode::copyStats(CNodeStats &stats)
  521. {
  522. X(nServices);
  523. X(nLastSend);
  524. X(nLastRecv);
  525. X(nTimeConnected);
  526. X(addrName);
  527. X(nVersion);
  528. X(strSubVer);
  529. X(fInbound);
  530. X(nReleaseTime);
  531. X(nStartingHeight);
  532. X(nMisbehavior);
  533. }
  534. #undef X
  535. void ThreadSocketHandler(void* parg)
  536. {
  537. IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
  538. try
  539. {
  540. vnThreadsRunning[THREAD_SOCKETHANDLER]++;
  541. ThreadSocketHandler2(parg);
  542. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  543. }
  544. catch (std::exception& e) {
  545. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  546. PrintException(&e, "ThreadSocketHandler()");
  547. } catch (...) {
  548. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  549. throw; // support pthread_cancel()
  550. }
  551. printf("ThreadSocketHandler exited\n");
  552. }
  553. void ThreadSocketHandler2(void* parg)
  554. {
  555. printf("ThreadSocketHandler started\n");
  556. list<CNode*> vNodesDisconnected;
  557. unsigned int nPrevNodeCount = 0;
  558. loop
  559. {
  560. //
  561. // Disconnect nodes
  562. //
  563. {
  564. LOCK(cs_vNodes);
  565. // Disconnect unused nodes
  566. vector<CNode*> vNodesCopy = vNodes;
  567. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  568. {
  569. if (pnode->fDisconnect ||
  570. (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
  571. {
  572. // remove from vNodes
  573. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  574. // release outbound grant (if any)
  575. pnode->grantOutbound.Release();
  576. // close socket and cleanup
  577. pnode->CloseSocketDisconnect();
  578. pnode->Cleanup();
  579. // hold in disconnected pool until all refs are released
  580. pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
  581. if (pnode->fNetworkNode || pnode->fInbound)
  582. pnode->Release();
  583. vNodesDisconnected.push_back(pnode);
  584. }
  585. }
  586. // Delete disconnected nodes
  587. list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  588. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  589. {
  590. // wait until threads are done using it
  591. if (pnode->GetRefCount() <= 0)
  592. {
  593. bool fDelete = false;
  594. {
  595. TRY_LOCK(pnode->cs_vSend, lockSend);
  596. if (lockSend)
  597. {
  598. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  599. if (lockRecv)
  600. {
  601. TRY_LOCK(pnode->cs_mapRequests, lockReq);
  602. if (lockReq)
  603. {
  604. TRY_LOCK(pnode->cs_inventory, lockInv);
  605. if (lockInv)
  606. fDelete = true;
  607. }
  608. }
  609. }
  610. }
  611. if (fDelete)
  612. {
  613. vNodesDisconnected.remove(pnode);
  614. delete pnode;
  615. }
  616. }
  617. }
  618. }
  619. if (vNodes.size() != nPrevNodeCount)
  620. {
  621. nPrevNodeCount = vNodes.size();
  622. uiInterface.NotifyNumConnectionsChanged(vNodes.size());
  623. }
  624. //
  625. // Find which sockets have data to receive
  626. //
  627. struct timeval timeout;
  628. timeout.tv_sec = 0;
  629. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  630. fd_set fdsetRecv;
  631. fd_set fdsetSend;
  632. fd_set fdsetError;
  633. FD_ZERO(&fdsetRecv);
  634. FD_ZERO(&fdsetSend);
  635. FD_ZERO(&fdsetError);
  636. SOCKET hSocketMax = 0;
  637. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
  638. FD_SET(hListenSocket, &fdsetRecv);
  639. hSocketMax = max(hSocketMax, hListenSocket);
  640. }
  641. {
  642. LOCK(cs_vNodes);
  643. BOOST_FOREACH(CNode* pnode, vNodes)
  644. {
  645. if (pnode->hSocket == INVALID_SOCKET)
  646. continue;
  647. FD_SET(pnode->hSocket, &fdsetRecv);
  648. FD_SET(pnode->hSocket, &fdsetError);
  649. hSocketMax = max(hSocketMax, pnode->hSocket);
  650. {
  651. TRY_LOCK(pnode->cs_vSend, lockSend);
  652. if (lockSend && !pnode->vSend.empty())
  653. FD_SET(pnode->hSocket, &fdsetSend);
  654. }
  655. }
  656. }
  657. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  658. int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  659. vnThreadsRunning[THREAD_SOCKETHANDLER]++;
  660. if (fShutdown)
  661. return;
  662. if (nSelect == SOCKET_ERROR)
  663. {
  664. int nErr = WSAGetLastError();
  665. if (hSocketMax != INVALID_SOCKET)
  666. {
  667. printf("socket select error %d\n", nErr);
  668. for (unsigned int i = 0; i <= hSocketMax; i++)
  669. FD_SET(i, &fdsetRecv);
  670. }
  671. FD_ZERO(&fdsetSend);
  672. FD_ZERO(&fdsetError);
  673. Sleep(timeout.tv_usec/1000);
  674. }
  675. //
  676. // Accept new connections
  677. //
  678. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  679. if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
  680. {
  681. #ifdef USE_IPV6
  682. struct sockaddr_storage sockaddr;
  683. #else
  684. struct sockaddr sockaddr;
  685. #endif
  686. socklen_t len = sizeof(sockaddr);
  687. SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
  688. CAddress addr;
  689. int nInbound = 0;
  690. if (hSocket != INVALID_SOCKET)
  691. if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
  692. printf("warning: unknown socket family\n");
  693. {
  694. LOCK(cs_vNodes);
  695. BOOST_FOREACH(CNode* pnode, vNodes)
  696. if (pnode->fInbound)
  697. nInbound++;
  698. }
  699. if (hSocket == INVALID_SOCKET)
  700. {
  701. if (WSAGetLastError() != WSAEWOULDBLOCK)
  702. printf("socket error accept failed: %d\n", WSAGetLastError());
  703. }
  704. else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
  705. {
  706. {
  707. LOCK(cs_setservAddNodeAddresses);
  708. if (!setservAddNodeAddresses.count(addr))
  709. closesocket(hSocket);
  710. }
  711. }
  712. else if (CNode::IsBanned(addr))
  713. {
  714. printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
  715. closesocket(hSocket);
  716. }
  717. else
  718. {
  719. printf("accepted connection %s\n", addr.ToString().c_str());
  720. CNode* pnode = new CNode(hSocket, addr, "", true);
  721. pnode->AddRef();
  722. {
  723. LOCK(cs_vNodes);
  724. vNodes.push_back(pnode);
  725. }
  726. }
  727. }
  728. //
  729. // Service each socket
  730. //
  731. vector<CNode*> vNodesCopy;
  732. {
  733. LOCK(cs_vNodes);
  734. vNodesCopy = vNodes;
  735. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  736. pnode->AddRef();
  737. }
  738. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  739. {
  740. if (fShutdown)
  741. return;
  742. //
  743. // Receive
  744. //
  745. if (pnode->hSocket == INVALID_SOCKET)
  746. continue;
  747. if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
  748. {
  749. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  750. if (lockRecv)
  751. {
  752. CDataStream& vRecv = pnode->vRecv;
  753. unsigned int nPos = vRecv.size();
  754. if (nPos > ReceiveBufferSize()) {
  755. if (!pnode->fDisconnect)
  756. printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
  757. pnode->CloseSocketDisconnect();
  758. }
  759. else {
  760. // typical socket buffer is 8K-64K
  761. char pchBuf[0x10000];
  762. int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  763. if (nBytes > 0)
  764. {
  765. vRecv.resize(nPos + nBytes);
  766. memcpy(&vRecv[nPos], pchBuf, nBytes);
  767. pnode->nLastRecv = GetTime();
  768. }
  769. else if (nBytes == 0)
  770. {
  771. // socket closed gracefully
  772. if (!pnode->fDisconnect)
  773. printf("socket closed\n");
  774. pnode->CloseSocketDisconnect();
  775. }
  776. else if (nBytes < 0)
  777. {
  778. // error
  779. int nErr = WSAGetLastError();
  780. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  781. {
  782. if (!pnode->fDisconnect)
  783. printf("socket recv error %d\n", nErr);
  784. pnode->CloseSocketDisconnect();
  785. }
  786. }
  787. }
  788. }
  789. }
  790. //
  791. // Send
  792. //
  793. if (pnode->hSocket == INVALID_SOCKET)
  794. continue;
  795. if (FD_ISSET(pnode->hSocket, &fdsetSend))
  796. {
  797. TRY_LOCK(pnode->cs_vSend, lockSend);
  798. if (lockSend)
  799. {
  800. CDataStream& vSend = pnode->vSend;
  801. if (!vSend.empty())
  802. {
  803. int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
  804. if (nBytes > 0)
  805. {
  806. vSend.erase(vSend.begin(), vSend.begin() + nBytes);
  807. pnode->nLastSend = GetTime();
  808. }
  809. else if (nBytes < 0)
  810. {
  811. // error
  812. int nErr = WSAGetLastError();
  813. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  814. {
  815. printf("socket send error %d\n", nErr);
  816. pnode->CloseSocketDisconnect();
  817. }
  818. }
  819. }
  820. }
  821. }
  822. //
  823. // Inactivity checking
  824. //
  825. if (pnode->vSend.empty())
  826. pnode->nLastSendEmpty = GetTime();
  827. if (GetTime() - pnode->nTimeConnected > 60)
  828. {
  829. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  830. {
  831. printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
  832. pnode->fDisconnect = true;
  833. }
  834. else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
  835. {
  836. printf("socket not sending\n");
  837. pnode->fDisconnect = true;
  838. }
  839. else if (GetTime() - pnode->nLastRecv > 90*60)
  840. {
  841. printf("socket inactivity timeout\n");
  842. pnode->fDisconnect = true;
  843. }
  844. }
  845. }
  846. {
  847. LOCK(cs_vNodes);
  848. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  849. pnode->Release();
  850. }
  851. Sleep(10);
  852. }
  853. }
  854. #ifdef USE_UPNP
  855. void ThreadMapPort(void* parg)
  856. {
  857. IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg));
  858. try
  859. {
  860. vnThreadsRunning[THREAD_UPNP]++;
  861. ThreadMapPort2(parg);
  862. vnThreadsRunning[THREAD_UPNP]--;
  863. }
  864. catch (std::exception& e) {
  865. vnThreadsRunning[THREAD_UPNP]--;
  866. PrintException(&e, "ThreadMapPort()");
  867. } catch (...) {
  868. vnThreadsRunning[THREAD_UPNP]--;
  869. PrintException(NULL, "ThreadMapPort()");
  870. }
  871. printf("ThreadMapPort exited\n");
  872. }
  873. void ThreadMapPort2(void* parg)
  874. {
  875. printf("ThreadMapPort started\n");
  876. char port[6];
  877. sprintf(port, "%d", GetListenPort());
  878. const char * multicastif = 0;
  879. const char * minissdpdpath = 0;
  880. struct UPNPDev * devlist = 0;
  881. char lanaddr[64];
  882. #ifndef UPNPDISCOVER_SUCCESS
  883. /* miniupnpc 1.5 */
  884. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
  885. #else
  886. /* miniupnpc 1.6 */
  887. int error = 0;
  888. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
  889. #endif
  890. struct UPNPUrls urls;
  891. struct IGDdatas data;
  892. int r;
  893. r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
  894. if (r == 1)
  895. {
  896. if (fDiscover) {
  897. char externalIPAddress[40];
  898. r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
  899. if(r != UPNPCOMMAND_SUCCESS)
  900. printf("UPnP: GetExternalIPAddress() returned %d\n", r);
  901. else
  902. {
  903. if(externalIPAddress[0])
  904. {
  905. printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
  906. AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
  907. }
  908. else
  909. printf("UPnP: GetExternalIPAddress failed.\n");
  910. }
  911. }
  912. string strDesc = "Bitcoin " + FormatFullVersion();
  913. #ifndef UPNPDISCOVER_SUCCESS
  914. /* miniupnpc 1.5 */
  915. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  916. port, port, lanaddr, strDesc.c_str(), "TCP", 0);
  917. #else
  918. /* miniupnpc 1.6 */
  919. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  920. port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
  921. #endif
  922. if(r!=UPNPCOMMAND_SUCCESS)
  923. printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  924. port, port, lanaddr, r, strupnperror(r));
  925. else
  926. printf("UPnP Port Mapping successful.\n");
  927. int i = 1;
  928. loop {
  929. if (fShutdown || !fUseUPnP)
  930. {
  931. r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0);
  932. printf("UPNP_DeletePortMapping() returned : %d\n", r);
  933. freeUPNPDevlist(devlist); devlist = 0;
  934. FreeUPNPUrls(&urls);
  935. return;
  936. }
  937. if (i % 600 == 0) // Refresh every 20 minutes
  938. {
  939. #ifndef UPNPDISCOVER_SUCCESS
  940. /* miniupnpc 1.5 */
  941. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  942. port, port, lanaddr, strDesc.c_str(), "TCP", 0);
  943. #else
  944. /* miniupnpc 1.6 */
  945. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  946. port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
  947. #endif
  948. if(r!=UPNPCOMMAND_SUCCESS)
  949. printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  950. port, port, lanaddr, r, strupnperror(r));
  951. else
  952. printf("UPnP Port Mapping successful.\n");;
  953. }
  954. Sleep(2000);
  955. i++;
  956. }
  957. } else {
  958. printf("No valid UPnP IGDs found\n");
  959. freeUPNPDevlist(devlist); devlist = 0;
  960. if (r != 0)
  961. FreeUPNPUrls(&urls);
  962. loop {
  963. if (fShutdown || !fUseUPnP)
  964. return;
  965. Sleep(2000);
  966. }
  967. }
  968. }
  969. void MapPort()
  970. {
  971. if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
  972. {
  973. if (!CreateThread(ThreadMapPort, NULL))
  974. printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
  975. }
  976. }
  977. #else
  978. void MapPort()
  979. {
  980. // Intentionally left blank.
  981. }
  982. #endif
  983. // DNS seeds
  984. // Each pair gives a source name and a seed name.
  985. // The first name is used as information source for addrman.
  986. // The second name should resolve to a list of seed addresses.
  987. static const char *strDNSSeed[][2] = {
  988. {"bitcoin.sipa.be", "seed.bitcoin.sipa.be"},
  989. {"bluematt.me", "dnsseed.bluematt.me"},
  990. {"dashjr.org", "dnsseed.bitcoin.dashjr.org"},
  991. {"xf2.org", "bitseed.xf2.org"},
  992. };
  993. void ThreadDNSAddressSeed(void* parg)
  994. {
  995. IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
  996. try
  997. {
  998. vnThreadsRunning[THREAD_DNSSEED]++;
  999. ThreadDNSAddressSeed2(parg);
  1000. vnThreadsRunning[THREAD_DNSSEED]--;
  1001. }
  1002. catch (std::exception& e) {
  1003. vnThreadsRunning[THREAD_DNSSEED]--;
  1004. PrintException(&e, "ThreadDNSAddressSeed()");
  1005. } catch (...) {
  1006. vnThreadsRunning[THREAD_DNSSEED]--;
  1007. throw; // support pthread_cancel()
  1008. }
  1009. printf("ThreadDNSAddressSeed exited\n");
  1010. }
  1011. void ThreadDNSAddressSeed2(void* parg)
  1012. {
  1013. printf("ThreadDNSAddressSeed started\n");
  1014. int found = 0;
  1015. if (!fTestNet)
  1016. {
  1017. printf("Loading addresses from DNS seeds (could take a while)\n");
  1018. for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
  1019. if (GetNameProxy()) {
  1020. AddOneShot(strDNSSeed[seed_idx][1]);
  1021. } else {
  1022. vector<CNetAddr> vaddr;
  1023. vector<CAddress> vAdd;
  1024. if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
  1025. {
  1026. BOOST_FOREACH(CNetAddr& ip, vaddr)
  1027. {
  1028. int nOneDay = 24*3600;
  1029. CAddress addr = CAddress(CService(ip, GetDefaultPort()));
  1030. addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
  1031. vAdd.push_back(addr);
  1032. found++;
  1033. }
  1034. }
  1035. addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
  1036. }
  1037. }
  1038. }
  1039. printf("%d addresses found from DNS seeds\n", found);
  1040. }
  1041. unsigned int pnSeed[] =
  1042. {
  1043. 0x959bd347, 0xf8de42b2, 0x73bc0518, 0xea6edc50, 0x21b00a4d, 0xc725b43d, 0xd665464d, 0x1a2a770e,
  1044. 0x27c93946, 0x65b2fa46, 0xb80ae255, 0x66b3b446, 0xb1877a3e, 0x6ee89e3e, 0xc3175b40, 0x2a01a83c,
  1045. 0x95b1363a, 0xa079ad3d, 0xe6ca801f, 0x027f4f4a, 0x34f7f03a, 0xf790f04a, 0x16ca801f, 0x2f4d5e40,
  1046. 0x3a4d5e40, 0xc43a322e, 0xc8159753, 0x14d4724c, 0x7919a118, 0xe0bdb34e, 0x68a16b2e, 0xff64b44d,
  1047. 0x6099115b, 0x9b57b05b, 0x7bd1b4ad, 0xdf95944f, 0x29d2b73d, 0xafa8db79, 0xe247ba41, 0x24078348,
  1048. 0xf722f03c, 0x33567ebc, 0xace64ed4, 0x984d3932, 0xb5f34e55, 0x27b7024d, 0x94579247, 0x8894042e,
  1049. 0x9357d34c, 0x1063c24b, 0xcaa228b1, 0xa3c5a8b2, 0x5dc64857, 0xa2c23643, 0xa8369a54, 0x31203077,
  1050. 0x00707c5c, 0x09fc0b3a, 0x272e9e2e, 0xf80f043e, 0x9449ca3e, 0x5512c33e, 0xd106b555, 0xe8024157,
  1051. 0xe288ec29, 0xc79c5461, 0xafb63932, 0xdb02ab4b, 0x0e512777, 0x8a145a4c, 0xb201ff4f, 0x5e09314b,
  1052. 0xcd9bfbcd, 0x1c023765, 0x4394e75c, 0xa728bd4d, 0x65331552, 0xa98420b1, 0x89ecf559, 0x6e80801f,
  1053. 0xf404f118, 0xefd62b51, 0x05918346, 0x9b186d5f, 0xacabab46, 0xf912e255, 0xc188ea62, 0xcc55734e,
  1054. 0xc668064d, 0xd77a4558, 0x46201c55, 0xf17dfc80, 0xf7142f2e, 0x87bfb718, 0x8aa54fb2, 0xc451d518,
  1055. 0xc4ae8831, 0x8dd44d55, 0x5bbd206c, 0x64536b5d, 0x5c667e60, 0x3b064242, 0xfe963a42, 0xa28e6dc8,
  1056. 0xe8a9604a, 0xc989464e, 0xd124a659, 0x50065140, 0xa44dfe5e, 0x1079e655, 0x3fb986d5, 0x47895b18,
  1057. 0x7d3ce4ad, 0x4561ba50, 0x296eec62, 0x255b41ad, 0xaed35ec9, 0x55556f12, 0xc7d3154d, 0x3297b65d,
  1058. 0x8930121f, 0xabf42e4e, 0x4a29e044, 0x1212685d, 0x676c1e40, 0xce009744, 0x383a8948, 0xa2dbd0ad,
  1059. 0xecc2564d, 0x07dbc252, 0x887ee24b, 0x5171644c, 0x6bb798c1, 0x847f495d, 0x4cbb7145, 0x3bb81c32,
  1060. 0x45eb262e, 0xc8015a4e, 0x250a361b, 0xf694f946, 0xd64a183e, 0xd4f1dd59, 0x8f20ffd4, 0x51d9e55c,
  1061. 0x09521763, 0x5e02002e, 0x32c8074d, 0xe685762e, 0x8290b0bc, 0x762a922e, 0xfc5ee754, 0x83a24829,
  1062. 0x775b224d, 0x6295bb4d, 0x38ec0555, 0xbffbba50, 0xe5560260, 0x86b16a7c, 0xd372234e, 0x49a3c24b,
  1063. 0x2f6a171f, 0x4d75ed60, 0xae94115b, 0xcb543744, 0x63080c59, 0x3f9c724c, 0xc977ce18, 0x532efb18,
  1064. 0x69dc3b2e, 0x5f94d929, 0x1732bb4d, 0x9c814b4d, 0xe6b3762e, 0xc024f662, 0x8face35b, 0x6b5b044d,
  1065. 0x798c7b57, 0x79a6b44c, 0x067d3057, 0xf9e94e5f, 0x91cbe15b, 0x71405eb2, 0x2662234e, 0xcbcc4a6d,
  1066. 0xbf69d54b, 0xa79b4e55, 0xec6d3e51, 0x7c0b3c02, 0x60f83653, 0x24c1e15c, 0x1110b62e, 0x10350f59,
  1067. 0xa56f1d55, 0x3509e7a9, 0xeb128354, 0x14268e2e, 0x934e28bc, 0x8e32692e, 0x8331a21f, 0x3e633932,
  1068. 0xc812b12e, 0xc684bf2e, 0x80112d2e, 0xe0ddc96c, 0xc630ca4a, 0x5c09b3b2, 0x0b580518, 0xc8e9d54b,
  1069. 0xd169aa43, 0x17d0d655, 0x1d029963, 0x7ff87559, 0xcb701f1f, 0x6fa3e85d, 0xe45e9a54, 0xf05d1802,
  1070. 0x44d03b2e, 0x837b692e, 0xccd4354e, 0x3d6da13c, 0x3423084d, 0xf707c34a, 0x55f6db3a, 0xad26e442,
  1071. 0x6233a21f, 0x09e80e59, 0x8caeb54d, 0xbe870941, 0xb407d20e, 0x20b51018, 0x56fb152e, 0x460d2a4e,
  1072. 0xbb9a2946, 0x560eb12e, 0xed83dd29, 0xd6724f53, 0xa50aafb8, 0x451346d9, 0x88348e2e, 0x7312fead,
  1073. 0x8ecaf96f, 0x1bda4e5f, 0xf1671e40, 0x3c8c3e3b, 0x4716324d, 0xdde24ede, 0xf98cd17d, 0xa91d4644,
  1074. 0x28124eb2, 0x147d5129, 0xd022042e, 0x61733d3b, 0xad0d5e02, 0x8ce2932e, 0xe5c18502, 0x549c1e32,
  1075. 0x9685801f, 0x86e217ad, 0xd948214b, 0x4110f462, 0x3a2e894e, 0xbd35492e, 0x87e0d558, 0x64b8ef7d,
  1076. 0x7c3eb962, 0x72a84b3e, 0x7cd667c9, 0x28370a2e, 0x4bc60e7b, 0x6fc1ec60, 0x14a6983f, 0x86739a4b,
  1077. 0x46954e5f, 0x32e2e15c, 0x2e9326cf, 0xe5801c5e, 0x379607b2, 0x32151145, 0xf0e39744, 0xacb54c55,
  1078. 0xa37dfb60, 0x83b55cc9, 0x388f7ca5, 0x15034f5f, 0x3e94965b, 0x68e0ffad, 0x35280f59, 0x8fe190cf,
  1079. 0x7c6ba5b2, 0xa5e9db43, 0x4ee1fc60, 0xd9d94e5f, 0x04040677, 0x0ea9b35e, 0x5961f14f, 0x67fda063,
  1080. 0xa48a5a31, 0xc6524e55, 0x283d325e, 0x3f37515f, 0x96b94b3e, 0xacce620e, 0x6481cc5b, 0xa4a06d4b,
  1081. 0x9e95d2d9, 0xe40c03d5, 0xc2f4514b, 0xb79aad44, 0xf64be843, 0xb2064070, 0xfca00455, 0x429dfa4e,
  1082. 0x2323f173, 0xeda4185e, 0xabd5227d, 0x9efd4d58, 0xb1104758, 0x4811e955, 0xbd9ab355, 0xe921f44b,
  1083. 0x9f166dce, 0x09e279b2, 0xe0c9ac7b, 0x7901a5ad, 0xa145d4b0, 0x79104671, 0xec31e35a, 0x4fe0b555,
  1084. 0xc7d9cbad, 0xad057f55, 0xe94cc759, 0x7fe0b043, 0xe4529f2e, 0x0d4dd4b2, 0x9f11a54d, 0x031e2e4e,
  1085. 0xe6014f5f, 0x11d1ca6c, 0x26bd7f61, 0xeb86854f, 0x4d347b57, 0x116bbe2e, 0xdba7234e, 0x7bcbfd2e,
  1086. 0x174dd4b2, 0x6686762e, 0xb089ba50, 0xc6258246, 0x087e767b, 0xc4a8cb4a, 0x595dba50, 0x7f0ae502,
  1087. 0x7b1dbd5a, 0xa0603492, 0x57d1af4b, 0x9e21ffd4, 0x6393064d, 0x7407376e, 0xe484762e, 0x122a4e53,
  1088. 0x4a37aa43, 0x3888a6be, 0xee77864e, 0x039c8dd5, 0x688d89af, 0x0e988f62, 0x08218246, 0xfc2f8246,
  1089. 0xd1d97040, 0xd64cd4b2, 0x5ae4a6b8, 0x7d0de9bc, 0x8d304d61, 0x06c5c672, 0xa4c8bd4d, 0xe0fd373b,
  1090. 0x575ebe4d, 0x72d26277, 0x55570f55, 0x77b154d9, 0xe214293a, 0xfc740f4b, 0xfe3f6a57, 0xa9c55f02,
  1091. 0xae4054db, 0x2394d918, 0xb511b24a, 0xb8741ab2, 0x0758e65e, 0xc7b5795b, 0xb0a30a4c, 0xaf7f170c,
  1092. 0xf3b4762e, 0x8179576d, 0x738a1581, 0x4b95b64c, 0x9829b618, 0x1bea932e, 0x7bdeaa4b, 0xcb5e0281,
  1093. 0x65618f54, 0x0658474b, 0x27066acf, 0x40556d65, 0x7d204d53, 0xf28bc244, 0xdce23455, 0xadc0ff54,
  1094. 0x3863c948, 0xcee34e5f, 0xdeb85e02, 0x2ed17a61, 0x6a7b094d, 0x7f0cfc40, 0x59603f54, 0x3220afbc,
  1095. 0xb5dfd962, 0x125d21c0, 0x13f8d243, 0xacfefb4e, 0x86c2c147, 0x3d8bbd59, 0xbd02a21f, 0x2593042e,
  1096. 0xc6a17a7c, 0x28925861, 0xb487ed44, 0xb5f4fd6d, 0x90c28a45, 0x5a14f74d, 0x43d71b4c, 0x728ebb5d,
  1097. 0x885bf950, 0x08134dd0, 0x38ec046e, 0xc575684b, 0x50082d2e, 0xa2f47757, 0x270f86ae, 0xf3ff6462,
  1098. 0x10ed3f4e, 0x4b58d462, 0xe01ce23e, 0x8c5b092e, 0x63e52f4e, 0x22c1e85d, 0xa908f54e, 0x8591624f,
  1099. 0x2c0fb94e, 0xa280ba3c, 0xb6f41b4c, 0x24f9aa47, 0x27201647, 0x3a3ea6dc, 0xa14fc3be, 0x3c34bdd5,
  1100. 0x5b8d4f5b, 0xaadeaf4b, 0xc71cab50, 0x15697a4c, 0x9a1a734c, 0x2a037d81, 0x2590bd59, 0x48ec2741,
  1101. 0x53489c5b, 0x7f00314b, 0x2170d362, 0xf2e92542, 0x42c10b44, 0x98f0f118, 0x883a3456, 0x099a932e,
  1102. 0xea38f7bc, 0x644e9247, 0xbb61b62e, 0x30e0863d, 0x5f51be54, 0x207215c7, 0x5f306c45, 0xaa7f3932,
  1103. 0x98da7d45, 0x4e339b59, 0x2e411581, 0xa808f618, 0xad2c0c59, 0x54476741, 0x09e99fd1, 0x5db8f752,
  1104. 0xc16df8bd, 0x1dd4b44f, 0x106edf2e, 0x9e15c180, 0x2ad6b56f, 0x633a5332, 0xff33787c, 0x077cb545,
  1105. 0x6610be6d, 0x75aad2c4, 0x72fb4d5b, 0xe81e0f59, 0x576f6332, 0x47333373, 0x351ed783, 0x2d90fb50,
  1106. 0x8d5e0f6c, 0x5b27a552, 0xdb293ebb, 0xe55ef950, 0x4b133ad8, 0x75df975a, 0x7b6a8740, 0xa899464b,
  1107. 0xfab15161, 0x10f8b64d, 0xd055ea4d, 0xee8e146b, 0x4b14afb8, 0x4bc1c44a, 0x9b961dcc, 0xd111ff43,
  1108. 0xfca0b745, 0xc800e412, 0x0afad9d1, 0xf751c350, 0xf9f0cccf, 0xa290a545, 0x8ef13763, 0x7ec70d59,
  1109. 0x2b066acf, 0x65496c45, 0xade02c1b, 0xae6eb077, 0x92c1e65b, 0xc064e6a9, 0xc649e56d, 0x5287a243,
  1110. 0x36de4f5b, 0x5b1df6ad, 0x65c39a59, 0xdba805b2, 0x20067aa8, 0x6457e56d, 0x3cee26cf, 0xfd3ff26d,
  1111. 0x04f86d4a, 0x06b8e048, 0xa93bcd5c, 0x91135852, 0xbe90a643, 0x8fa0094d, 0x06d8215f, 0x2677094d,
  1112. 0xd735685c, 0x164a00c9, 0x5209ac5f, 0xa9564c5c, 0x3b504f5f, 0xcc826bd0, 0x4615042e, 0x5fe13b4a,
  1113. 0x8c81b86d, 0x879ab68c, 0x1de564b8, 0x434487d8, 0x2dcb1b63, 0x82ab524a, 0xb0676abb, 0xa13d9c62,
  1114. 0xdbb5b86d, 0x5b7f4b59, 0xaddfb44d, 0xad773532, 0x3997054c, 0x72cebd89, 0xb194544c, 0xc5b8046e,
  1115. 0x6e1adeb2, 0xaa5abb51, 0xefb54b44, 0x15efc54f, 0xe9f1bc4d, 0x5f401b6c, 0x97f018ad, 0xc82f9252,
  1116. 0x2cdc762e, 0x8e52e56d, 0x1827175e, 0x9b7d7d80, 0xb2ad6845, 0x51065140, 0x71180a18, 0x5b27006c,
  1117. 0x0621e255, 0x721cbe58, 0x670c0cb8, 0xf8bd715d, 0xe0bdc5d9, 0xed843501, 0x4b84554d, 0x7f1a18bc,
  1118. 0x53bcaf47, 0x5729d35f, 0xf0dda246, 0x22382bd0, 0x4d641fb0, 0x316afcde, 0x50a22f1f, 0x73608046,
  1119. 0xc461d84a, 0xb2dbe247,
  1120. };
  1121. void DumpAddresses()
  1122. {
  1123. int64 nStart = GetTimeMillis();
  1124. CAddrDB adb;
  1125. adb.Write(addrman);
  1126. printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
  1127. addrman.size(), GetTimeMillis() - nStart);
  1128. }
  1129. void ThreadDumpAddress2(void* parg)
  1130. {
  1131. vnThreadsRunning[THREAD_DUMPADDRESS]++;
  1132. while (!fShutdown)
  1133. {
  1134. DumpAddresses();
  1135. vnThreadsRunning[THREAD_DUMPADDRESS]--;
  1136. Sleep(100000);
  1137. vnThreadsRunning[THREAD_DUMPADDRESS]++;
  1138. }
  1139. vnThreadsRunning[THREAD_DUMPADDRESS]--;
  1140. }
  1141. void ThreadDumpAddress(void* parg)
  1142. {
  1143. IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg));
  1144. try
  1145. {
  1146. ThreadDumpAddress2(parg);
  1147. }
  1148. catch (std::exception& e) {
  1149. PrintException(&e, "ThreadDumpAddress()");
  1150. }
  1151. printf("ThreadDumpAddress exited\n");
  1152. }
  1153. void ThreadOpenConnections(void* parg)
  1154. {
  1155. IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
  1156. try
  1157. {
  1158. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1159. ThreadOpenConnections2(parg);
  1160. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1161. }
  1162. catch (std::exception& e) {
  1163. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1164. PrintException(&e, "ThreadOpenConnections()");
  1165. } catch (...) {
  1166. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1167. PrintException(NULL, "ThreadOpenConnections()");
  1168. }
  1169. printf("ThreadOpenConnections exited\n");
  1170. }
  1171. void static ProcessOneShot()
  1172. {
  1173. string strDest;
  1174. {
  1175. LOCK(cs_vOneShots);
  1176. if (vOneShots.empty())
  1177. return;
  1178. strDest = vOneShots.front();
  1179. vOneShots.pop_front();
  1180. }
  1181. CAddress addr;
  1182. CSemaphoreGrant grant(*semOutbound, true);
  1183. if (grant) {
  1184. if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
  1185. AddOneShot(strDest);
  1186. }
  1187. }
  1188. void ThreadOpenConnections2(void* parg)
  1189. {
  1190. printf("ThreadOpenConnections started\n");
  1191. // Connect to specific addresses
  1192. if (mapArgs.count("-connect"))
  1193. {
  1194. for (int64 nLoop = 0;; nLoop++)
  1195. {
  1196. ProcessOneShot();
  1197. BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
  1198. {
  1199. CAddress addr;
  1200. OpenNetworkConnection(addr, NULL, strAddr.c_str());
  1201. for (int i = 0; i < 10 && i < nLoop; i++)
  1202. {
  1203. Sleep(500);
  1204. if (fShutdown)
  1205. return;
  1206. }
  1207. }
  1208. }
  1209. }
  1210. // Initiate network connections
  1211. int64 nStart = GetTime();
  1212. loop
  1213. {
  1214. ProcessOneShot();
  1215. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1216. Sleep(500);
  1217. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1218. if (fShutdown)
  1219. return;
  1220. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1221. CSemaphoreGrant grant(*semOutbound);
  1222. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1223. if (fShutdown)
  1224. return;
  1225. // Add seed nodes if IRC isn't working
  1226. if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
  1227. {
  1228. std::vector<CAddress> vAdd;
  1229. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
  1230. {
  1231. // It'll only connect to one or two seed nodes because once it connects,
  1232. // it'll get a pile of addresses with newer timestamps.
  1233. // Seed nodes are given a random 'last seen time' of between one and two
  1234. // weeks ago.
  1235. const int64 nOneWeek = 7*24*60*60;
  1236. struct in_addr ip;
  1237. memcpy(&ip, &pnSeed[i], sizeof(ip));
  1238. CAddress addr(CService(ip, GetDefaultPort()));
  1239. addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
  1240. vAdd.push_back(addr);
  1241. }
  1242. addrman.Add(vAdd, CNetAddr("127.0.0.1"));
  1243. }
  1244. //
  1245. // Choose an address to connect to based on most recently seen
  1246. //
  1247. CAddress addrConnect;
  1248. // Only connect out to one peer per network group (/16 for IPv4).
  1249. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
  1250. int nOutbound = 0;
  1251. set<vector<unsigned char> > setConnected;
  1252. {
  1253. LOCK(cs_vNodes);
  1254. BOOST_FOREACH(CNode* pnode, vNodes) {
  1255. if (!pnode->fInbound) {
  1256. setConnected.insert(pnode->addr.GetGroup());
  1257. nOutbound++;
  1258. }
  1259. }
  1260. }
  1261. int64 nANow = GetAdjustedTime();
  1262. int nTries = 0;
  1263. loop
  1264. {
  1265. // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
  1266. CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
  1267. // if we selected an invalid address, restart
  1268. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1269. break;
  1270. nTries++;
  1271. if (IsLimited(addr))
  1272. continue;
  1273. // only consider very recently tried nodes after 30 failed attempts
  1274. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1275. continue;
  1276. // do not allow non-default ports, unless after 50 invalid addresses selected already
  1277. if (addr.GetPort() != GetDefaultPort() && nTries < 50)
  1278. continue;
  1279. addrConnect = addr;
  1280. break;
  1281. }
  1282. if (addrConnect.IsValid())
  1283. OpenNetworkConnection(addrConnect, &grant);
  1284. }
  1285. }
  1286. void ThreadOpenAddedConnections(void* parg)
  1287. {
  1288. IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
  1289. try
  1290. {
  1291. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1292. ThreadOpenAddedConnections2(parg);
  1293. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1294. }
  1295. catch (std::exception& e) {
  1296. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1297. PrintException(&e, "ThreadOpenAddedConnections()");
  1298. } catch (...) {
  1299. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1300. PrintException(NULL, "ThreadOpenAddedConnections()");
  1301. }
  1302. printf("ThreadOpenAddedConnections exited\n");
  1303. }
  1304. void ThreadOpenAddedConnections2(void* parg)
  1305. {
  1306. printf("ThreadOpenAddedConnections started\n");
  1307. if (mapArgs.count("-addnode") == 0)
  1308. return;
  1309. if (GetNameProxy()) {
  1310. while(!fShutdown) {
  1311. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
  1312. CAddress addr;
  1313. CSemaphoreGrant grant(*semOutbound);
  1314. OpenNetworkConnection(addr, &grant, strAddNode.c_str());
  1315. Sleep(500);
  1316. }
  1317. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1318. Sleep(120000); // Retry every 2 minutes
  1319. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1320. }
  1321. return;
  1322. }
  1323. vector<vector<CService> > vservAddressesToAdd(0);
  1324. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
  1325. {
  1326. vector<CService> vservNode(0);
  1327. if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
  1328. {
  1329. vservAddressesToAdd.push_back(vservNode);
  1330. {
  1331. LOCK(cs_setservAddNodeAddresses);
  1332. BOOST_FOREACH(CService& serv, vservNode)
  1333. setservAddNodeAddresses.insert(serv);
  1334. }
  1335. }
  1336. }
  1337. loop
  1338. {
  1339. vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
  1340. // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
  1341. // (keeping in mind that addnode entries can have many IPs if fNameLookup)
  1342. {
  1343. LOCK(cs_vNodes);
  1344. BOOST_FOREACH(CNode* pnode, vNodes)
  1345. for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
  1346. BOOST_FOREACH(CService& addrNode, *(it))
  1347. if (pnode->addr == addrNode)
  1348. {
  1349. it = vservConnectAddresses.erase(it);
  1350. it--;
  1351. break;
  1352. }
  1353. }
  1354. BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
  1355. {
  1356. CSemaphoreGrant grant(*semOutbound);
  1357. OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
  1358. Sleep(500);
  1359. if (fShutdown)
  1360. return;
  1361. }
  1362. if (fShutdown)
  1363. return;
  1364. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1365. Sleep(120000); // Retry every 2 minutes
  1366. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1367. if (fShutdown)
  1368. return;
  1369. }
  1370. }
  1371. // if succesful, this moves the passed grant to the constructed node
  1372. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
  1373. {
  1374. //
  1375. // Initiate outbound network connection
  1376. //
  1377. if (fShutdown)
  1378. return false;
  1379. if (!strDest)
  1380. if (IsLocal(addrConnect) ||
  1381. FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
  1382. FindNode(addrConnect.ToStringIPPort().c_str()))
  1383. return false;
  1384. if (strDest && FindNode(strDest))
  1385. return false;
  1386. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1387. CNode* pnode = ConnectNode(addrConnect, strDest);
  1388. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1389. if (fShutdown)
  1390. return false;
  1391. if (!pnode)
  1392. return false;
  1393. if (grantOutbound)
  1394. grantOutbound->MoveTo(pnode->grantOutbound);
  1395. pnode->fNetworkNode = true;
  1396. if (fOneShot)
  1397. pnode->fOneShot = true;
  1398. return true;
  1399. }
  1400. void ThreadMessageHandler(void* parg)
  1401. {
  1402. IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
  1403. try
  1404. {
  1405. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1406. ThreadMessageHandler2(parg);
  1407. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1408. }
  1409. catch (std::exception& e) {
  1410. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1411. PrintException(&e, "ThreadMessageHandler()");
  1412. } catch (...) {
  1413. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1414. PrintException(NULL, "ThreadMessageHandler()");
  1415. }
  1416. printf("ThreadMessageHandler exited\n");
  1417. }
  1418. void ThreadMessageHandler2(void* parg)
  1419. {
  1420. printf("ThreadMessageHandler started\n");
  1421. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1422. while (!fShutdown)
  1423. {
  1424. vector<CNode*> vNodesCopy;
  1425. {
  1426. LOCK(cs_vNodes);
  1427. vNodesCopy = vNodes;
  1428. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1429. pnode->AddRef();
  1430. }
  1431. // Poll the connected nodes for messages
  1432. CNode* pnodeTrickle = NULL;
  1433. if (!vNodesCopy.empty())
  1434. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1435. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1436. {
  1437. // Receive messages
  1438. {
  1439. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  1440. if (lockRecv)
  1441. ProcessMessages(pnode);
  1442. }
  1443. if (fShutdown)
  1444. return;
  1445. // Send messages
  1446. {
  1447. TRY_LOCK(pnode->cs_vSend, lockSend);
  1448. if (lockSend)
  1449. SendMessages(pnode, pnode == pnodeTrickle);
  1450. }
  1451. if (fShutdown)
  1452. return;
  1453. }
  1454. {
  1455. LOCK(cs_vNodes);
  1456. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1457. pnode->Release();
  1458. }
  1459. // Wait and allow messages to bunch up.
  1460. // Reduce vnThreadsRunning so StopNode has permission to exit while
  1461. // we're sleeping, but we must always check fShutdown after doing this.
  1462. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1463. Sleep(100);
  1464. if (fRequestShutdown)
  1465. StartShutdown();
  1466. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1467. if (fShutdown)
  1468. return;
  1469. }
  1470. }
  1471. bool BindListenPort(const CService &addrBind, string& strError)
  1472. {
  1473. strError = "";
  1474. int nOne = 1;
  1475. #ifdef WIN32
  1476. // Initialize Windows Sockets
  1477. WSADATA wsadata;
  1478. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  1479. if (ret != NO_ERROR)
  1480. {
  1481. strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
  1482. printf("%s\n", strError.c_str());
  1483. return false;
  1484. }
  1485. #endif
  1486. // Create socket for listening for incoming connections
  1487. #ifdef USE_IPV6
  1488. struct sockaddr_storage sockaddr;
  1489. #else
  1490. struct sockaddr sockaddr;
  1491. #endif
  1492. socklen_t len = sizeof(sockaddr);
  1493. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1494. {
  1495. strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
  1496. printf("%s\n", strError.c_str());
  1497. return false;
  1498. }
  1499. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1500. if (hListenSocket == INVALID_SOCKET)
  1501. {
  1502. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
  1503. printf("%s\n", strError.c_str());
  1504. return false;
  1505. }
  1506. #ifdef SO_NOSIGPIPE
  1507. // Different way of disabling SIGPIPE on BSD
  1508. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1509. #endif
  1510. #ifndef WIN32
  1511. // Allow binding if the port is still in TIME_WAIT state after
  1512. // the program was closed and restarted. Not an issue on windows.
  1513. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1514. #endif
  1515. #ifdef WIN32
  1516. // Set to nonblocking, incoming connections will also inherit this
  1517. if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
  1518. #else
  1519. if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  1520. #endif
  1521. {
  1522. strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
  1523. printf("%s\n", strError.c_str());
  1524. return false;
  1525. }
  1526. #ifdef USE_IPV6
  1527. // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
  1528. // and enable it by default or not. Try to enable it, if possible.
  1529. if (addrBind.IsIPv6()) {
  1530. #ifdef IPV6_V6ONLY
  1531. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1532. #endif
  1533. #ifdef WIN32
  1534. int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
  1535. int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
  1536. // this call is allowed to fail
  1537. setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
  1538. #endif
  1539. }
  1540. #endif
  1541. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1542. {
  1543. int nErr = WSAGetLastError();
  1544. if (nErr == WSAEADDRINUSE)
  1545. strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
  1546. else
  1547. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
  1548. printf("%s\n", strError.c_str());
  1549. return false;
  1550. }
  1551. printf("Bound to %s\n", addrBind.ToString().c_str());
  1552. // Listen for incoming connections
  1553. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1554. {
  1555. strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
  1556. printf("%s\n", strError.c_str());
  1557. return false;
  1558. }
  1559. vhListenSocket.push_back(hListenSocket);
  1560. if (addrBind.IsRoutable() && fDiscover)
  1561. AddLocal(addrBind, LOCAL_BIND);
  1562. return true;
  1563. }
  1564. void static Discover()
  1565. {
  1566. if (!fDiscover)
  1567. return;
  1568. #ifdef WIN32
  1569. // Get local host ip
  1570. char pszHostName[1000] = "";
  1571. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1572. {
  1573. vector<CNetAddr> vaddr;
  1574. if (LookupHost(pszHostName, vaddr))
  1575. {
  1576. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1577. {
  1578. AddLocal(addr, LOCAL_IF);
  1579. }
  1580. }
  1581. }
  1582. #else
  1583. // Get local host ip
  1584. struct ifaddrs* myaddrs;
  1585. if (getifaddrs(&myaddrs) == 0)
  1586. {
  1587. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1588. {
  1589. if (ifa->ifa_addr == NULL) continue;
  1590. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1591. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1592. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1593. if (ifa->ifa_addr->sa_family == AF_INET)
  1594. {
  1595. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1596. CNetAddr addr(s4->sin_addr);
  1597. if (AddLocal(addr, LOCAL_IF))
  1598. printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1599. }
  1600. #ifdef USE_IPV6
  1601. else if (ifa->ifa_addr->sa_family == AF_INET6)
  1602. {
  1603. struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
  1604. CNetAddr addr(s6->sin6_addr);
  1605. if (AddLocal(addr, LOCAL_IF))
  1606. printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1607. }
  1608. #endif
  1609. }
  1610. freeifaddrs(myaddrs);
  1611. }
  1612. #endif
  1613. CreateThread(ThreadGetMyExternalIP, NULL);
  1614. }
  1615. void StartNode(void* parg)
  1616. {
  1617. if (semOutbound == NULL) {
  1618. // initialize semaphore
  1619. int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
  1620. semOutbound = new CSemaphore(nMaxOutbound);
  1621. }
  1622. if (pnodeLocalHost == NULL)
  1623. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
  1624. Discover();
  1625. //
  1626. // Start threads
  1627. //
  1628. if (!GetBoolArg("-dnsseed", true))
  1629. printf("DNS seeding disabled\n");
  1630. else
  1631. if (!CreateThread(ThreadDNSAddressSeed, NULL))
  1632. printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
  1633. // Map ports with UPnP
  1634. if (fUseUPnP)
  1635. MapPort();
  1636. // Get addresses from IRC and advertise ours
  1637. if (!CreateThread(ThreadIRCSeed, NULL))
  1638. printf("Error: CreateThread(ThreadIRCSeed) failed\n");
  1639. // Send and receive from sockets, accept connections
  1640. if (!CreateThread(ThreadSocketHandler, NULL))
  1641. printf("Error: CreateThread(ThreadSocketHandler) failed\n");
  1642. // Initiate outbound connections from -addnode
  1643. if (!CreateThread(ThreadOpenAddedConnections, NULL))
  1644. printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
  1645. // Initiate outbound connections
  1646. if (!CreateThread(ThreadOpenConnections, NULL))
  1647. printf("Error: CreateThread(ThreadOpenConnections) failed\n");
  1648. // Process messages
  1649. if (!CreateThread(ThreadMessageHandler, NULL))
  1650. printf("Error: CreateThread(ThreadMessageHandler) failed\n");
  1651. // Dump network addresses
  1652. if (!CreateThread(ThreadDumpAddress, NULL))
  1653. printf("Error; CreateThread(ThreadDumpAddress) failed\n");
  1654. // Generate coins in the background
  1655. GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
  1656. }
  1657. bool StopNode()
  1658. {
  1659. printf("StopNode()\n");
  1660. fShutdown = true;
  1661. nTransactionsUpdated++;
  1662. int64 nStart = GetTime();
  1663. if (semOutbound)
  1664. for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
  1665. semOutbound->post();
  1666. do
  1667. {
  1668. int nThreadsRunning = 0;
  1669. for (int n = 0; n < THREAD_MAX; n++)
  1670. nThreadsRunning += vnThreadsRunning[n];
  1671. if (nThreadsRunning == 0)
  1672. break;
  1673. if (GetTime() - nStart > 20)
  1674. break;
  1675. Sleep(20);
  1676. } while(true);
  1677. if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
  1678. if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
  1679. if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
  1680. if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
  1681. if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
  1682. if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
  1683. #ifdef USE_UPNP
  1684. if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
  1685. #endif
  1686. if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
  1687. if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
  1688. if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
  1689. while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
  1690. Sleep(20);
  1691. Sleep(50);
  1692. DumpAddresses();
  1693. return true;
  1694. }
  1695. class CNetCleanup
  1696. {
  1697. public:
  1698. CNetCleanup()
  1699. {
  1700. }
  1701. ~CNetCleanup()
  1702. {
  1703. // Close sockets
  1704. BOOST_FOREACH(CNode* pnode, vNodes)
  1705. if (pnode->hSocket != INVALID_SOCKET)
  1706. closesocket(pnode->hSocket);
  1707. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  1708. if (hListenSocket != INVALID_SOCKET)
  1709. if (closesocket(hListenSocket) == SOCKET_ERROR)
  1710. printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
  1711. #ifdef WIN32
  1712. // Shutdown Windows Sockets
  1713. WSACleanup();
  1714. #endif
  1715. }
  1716. }
  1717. instance_of_cnetcleanup;