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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  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. {"xf2.org", "bitseed.xf2.org"},
  989. {"bluematt.me", "dnsseed.bluematt.me"},
  990. {"bitcoin.sipa.be", "seed.bitcoin.sipa.be"},
  991. {"dashjr.org", "dnsseed.bitcoin.dashjr.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 to one address per a.b.?.? range.
  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. setConnected.insert(pnode->addr.GetGroup());
  1256. if (!pnode->fInbound)
  1257. nOutbound++;
  1258. }
  1259. }
  1260. int64 nANow = GetAdjustedTime();
  1261. int nTries = 0;
  1262. loop
  1263. {
  1264. // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
  1265. CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
  1266. // if we selected an invalid address, restart
  1267. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1268. break;
  1269. nTries++;
  1270. if (IsLimited(addr))
  1271. continue;
  1272. // only consider very recently tried nodes after 30 failed attempts
  1273. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1274. continue;
  1275. // do not allow non-default ports, unless after 50 invalid addresses selected already
  1276. if (addr.GetPort() != GetDefaultPort() && nTries < 50)
  1277. continue;
  1278. addrConnect = addr;
  1279. break;
  1280. }
  1281. if (addrConnect.IsValid())
  1282. OpenNetworkConnection(addrConnect, &grant);
  1283. }
  1284. }
  1285. void ThreadOpenAddedConnections(void* parg)
  1286. {
  1287. IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
  1288. try
  1289. {
  1290. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1291. ThreadOpenAddedConnections2(parg);
  1292. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1293. }
  1294. catch (std::exception& e) {
  1295. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1296. PrintException(&e, "ThreadOpenAddedConnections()");
  1297. } catch (...) {
  1298. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1299. PrintException(NULL, "ThreadOpenAddedConnections()");
  1300. }
  1301. printf("ThreadOpenAddedConnections exited\n");
  1302. }
  1303. void ThreadOpenAddedConnections2(void* parg)
  1304. {
  1305. printf("ThreadOpenAddedConnections started\n");
  1306. if (mapArgs.count("-addnode") == 0)
  1307. return;
  1308. if (GetNameProxy()) {
  1309. while(!fShutdown) {
  1310. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
  1311. CAddress addr;
  1312. CSemaphoreGrant grant(*semOutbound);
  1313. OpenNetworkConnection(addr, &grant, strAddNode.c_str());
  1314. Sleep(500);
  1315. }
  1316. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1317. Sleep(120000); // Retry every 2 minutes
  1318. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1319. }
  1320. return;
  1321. }
  1322. vector<vector<CService> > vservAddressesToAdd(0);
  1323. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
  1324. {
  1325. vector<CService> vservNode(0);
  1326. if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
  1327. {
  1328. vservAddressesToAdd.push_back(vservNode);
  1329. {
  1330. LOCK(cs_setservAddNodeAddresses);
  1331. BOOST_FOREACH(CService& serv, vservNode)
  1332. setservAddNodeAddresses.insert(serv);
  1333. }
  1334. }
  1335. }
  1336. loop
  1337. {
  1338. vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
  1339. // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
  1340. // (keeping in mind that addnode entries can have many IPs if fNameLookup)
  1341. {
  1342. LOCK(cs_vNodes);
  1343. BOOST_FOREACH(CNode* pnode, vNodes)
  1344. for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
  1345. BOOST_FOREACH(CService& addrNode, *(it))
  1346. if (pnode->addr == addrNode)
  1347. {
  1348. it = vservConnectAddresses.erase(it);
  1349. it--;
  1350. break;
  1351. }
  1352. }
  1353. BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
  1354. {
  1355. CSemaphoreGrant grant(*semOutbound);
  1356. OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
  1357. Sleep(500);
  1358. if (fShutdown)
  1359. return;
  1360. }
  1361. if (fShutdown)
  1362. return;
  1363. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1364. Sleep(120000); // Retry every 2 minutes
  1365. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1366. if (fShutdown)
  1367. return;
  1368. }
  1369. }
  1370. // if succesful, this moves the passed grant to the constructed node
  1371. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
  1372. {
  1373. //
  1374. // Initiate outbound network connection
  1375. //
  1376. if (fShutdown)
  1377. return false;
  1378. if (!strDest)
  1379. if (IsLocal(addrConnect) ||
  1380. FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
  1381. FindNode(addrConnect.ToStringIPPort().c_str()))
  1382. return false;
  1383. if (strDest && FindNode(strDest))
  1384. return false;
  1385. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1386. CNode* pnode = ConnectNode(addrConnect, strDest);
  1387. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1388. if (fShutdown)
  1389. return false;
  1390. if (!pnode)
  1391. return false;
  1392. if (grantOutbound)
  1393. grantOutbound->MoveTo(pnode->grantOutbound);
  1394. pnode->fNetworkNode = true;
  1395. if (fOneShot)
  1396. pnode->fOneShot = true;
  1397. return true;
  1398. }
  1399. void ThreadMessageHandler(void* parg)
  1400. {
  1401. IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
  1402. try
  1403. {
  1404. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1405. ThreadMessageHandler2(parg);
  1406. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1407. }
  1408. catch (std::exception& e) {
  1409. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1410. PrintException(&e, "ThreadMessageHandler()");
  1411. } catch (...) {
  1412. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1413. PrintException(NULL, "ThreadMessageHandler()");
  1414. }
  1415. printf("ThreadMessageHandler exited\n");
  1416. }
  1417. void ThreadMessageHandler2(void* parg)
  1418. {
  1419. printf("ThreadMessageHandler started\n");
  1420. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1421. while (!fShutdown)
  1422. {
  1423. vector<CNode*> vNodesCopy;
  1424. {
  1425. LOCK(cs_vNodes);
  1426. vNodesCopy = vNodes;
  1427. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1428. pnode->AddRef();
  1429. }
  1430. // Poll the connected nodes for messages
  1431. CNode* pnodeTrickle = NULL;
  1432. if (!vNodesCopy.empty())
  1433. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1434. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1435. {
  1436. // Receive messages
  1437. {
  1438. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  1439. if (lockRecv)
  1440. ProcessMessages(pnode);
  1441. }
  1442. if (fShutdown)
  1443. return;
  1444. // Send messages
  1445. {
  1446. TRY_LOCK(pnode->cs_vSend, lockSend);
  1447. if (lockSend)
  1448. SendMessages(pnode, pnode == pnodeTrickle);
  1449. }
  1450. if (fShutdown)
  1451. return;
  1452. }
  1453. {
  1454. LOCK(cs_vNodes);
  1455. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1456. pnode->Release();
  1457. }
  1458. // Wait and allow messages to bunch up.
  1459. // Reduce vnThreadsRunning so StopNode has permission to exit while
  1460. // we're sleeping, but we must always check fShutdown after doing this.
  1461. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1462. Sleep(100);
  1463. if (fRequestShutdown)
  1464. StartShutdown();
  1465. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1466. if (fShutdown)
  1467. return;
  1468. }
  1469. }
  1470. bool BindListenPort(const CService &addrBind, string& strError)
  1471. {
  1472. strError = "";
  1473. int nOne = 1;
  1474. #ifdef WIN32
  1475. // Initialize Windows Sockets
  1476. WSADATA wsadata;
  1477. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  1478. if (ret != NO_ERROR)
  1479. {
  1480. strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
  1481. printf("%s\n", strError.c_str());
  1482. return false;
  1483. }
  1484. #endif
  1485. // Create socket for listening for incoming connections
  1486. #ifdef USE_IPV6
  1487. struct sockaddr_storage sockaddr;
  1488. #else
  1489. struct sockaddr sockaddr;
  1490. #endif
  1491. socklen_t len = sizeof(sockaddr);
  1492. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1493. {
  1494. strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
  1495. printf("%s\n", strError.c_str());
  1496. return false;
  1497. }
  1498. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1499. if (hListenSocket == INVALID_SOCKET)
  1500. {
  1501. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
  1502. printf("%s\n", strError.c_str());
  1503. return false;
  1504. }
  1505. #ifdef SO_NOSIGPIPE
  1506. // Different way of disabling SIGPIPE on BSD
  1507. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1508. #endif
  1509. #ifndef WIN32
  1510. // Allow binding if the port is still in TIME_WAIT state after
  1511. // the program was closed and restarted. Not an issue on windows.
  1512. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1513. #endif
  1514. #ifdef WIN32
  1515. // Set to nonblocking, incoming connections will also inherit this
  1516. if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
  1517. #else
  1518. if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  1519. #endif
  1520. {
  1521. strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
  1522. printf("%s\n", strError.c_str());
  1523. return false;
  1524. }
  1525. #ifdef USE_IPV6
  1526. // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
  1527. // and enable it by default or not. Try to enable it, if possible.
  1528. if (addrBind.IsIPv6()) {
  1529. #ifdef IPV6_V6ONLY
  1530. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1531. #endif
  1532. #ifdef WIN32
  1533. int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
  1534. int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
  1535. // this call is allowed to fail
  1536. setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
  1537. #endif
  1538. }
  1539. #endif
  1540. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1541. {
  1542. int nErr = WSAGetLastError();
  1543. if (nErr == WSAEADDRINUSE)
  1544. strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
  1545. else
  1546. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
  1547. printf("%s\n", strError.c_str());
  1548. return false;
  1549. }
  1550. printf("Bound to %s\n", addrBind.ToString().c_str());
  1551. // Listen for incoming connections
  1552. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1553. {
  1554. strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
  1555. printf("%s\n", strError.c_str());
  1556. return false;
  1557. }
  1558. vhListenSocket.push_back(hListenSocket);
  1559. if (addrBind.IsRoutable() && fDiscover)
  1560. AddLocal(addrBind, LOCAL_BIND);
  1561. return true;
  1562. }
  1563. void static Discover()
  1564. {
  1565. if (!fDiscover)
  1566. return;
  1567. #ifdef WIN32
  1568. // Get local host ip
  1569. char pszHostName[1000] = "";
  1570. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1571. {
  1572. vector<CNetAddr> vaddr;
  1573. if (LookupHost(pszHostName, vaddr))
  1574. {
  1575. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1576. {
  1577. AddLocal(addr, LOCAL_IF);
  1578. }
  1579. }
  1580. }
  1581. #else
  1582. // Get local host ip
  1583. struct ifaddrs* myaddrs;
  1584. if (getifaddrs(&myaddrs) == 0)
  1585. {
  1586. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1587. {
  1588. if (ifa->ifa_addr == NULL) continue;
  1589. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1590. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1591. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1592. if (ifa->ifa_addr->sa_family == AF_INET)
  1593. {
  1594. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1595. CNetAddr addr(s4->sin_addr);
  1596. if (AddLocal(addr, LOCAL_IF))
  1597. printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1598. }
  1599. #ifdef USE_IPV6
  1600. else if (ifa->ifa_addr->sa_family == AF_INET6)
  1601. {
  1602. struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
  1603. CNetAddr addr(s6->sin6_addr);
  1604. if (AddLocal(addr, LOCAL_IF))
  1605. printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1606. }
  1607. #endif
  1608. }
  1609. freeifaddrs(myaddrs);
  1610. }
  1611. #endif
  1612. CreateThread(ThreadGetMyExternalIP, NULL);
  1613. }
  1614. void StartNode(void* parg)
  1615. {
  1616. if (semOutbound == NULL) {
  1617. // initialize semaphore
  1618. int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
  1619. semOutbound = new CSemaphore(nMaxOutbound);
  1620. }
  1621. if (pnodeLocalHost == NULL)
  1622. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
  1623. Discover();
  1624. //
  1625. // Start threads
  1626. //
  1627. if (!GetBoolArg("-dnsseed", true))
  1628. printf("DNS seeding disabled\n");
  1629. else
  1630. if (!CreateThread(ThreadDNSAddressSeed, NULL))
  1631. printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
  1632. // Map ports with UPnP
  1633. if (fUseUPnP)
  1634. MapPort();
  1635. // Get addresses from IRC and advertise ours
  1636. if (!CreateThread(ThreadIRCSeed, NULL))
  1637. printf("Error: CreateThread(ThreadIRCSeed) failed\n");
  1638. // Send and receive from sockets, accept connections
  1639. if (!CreateThread(ThreadSocketHandler, NULL))
  1640. printf("Error: CreateThread(ThreadSocketHandler) failed\n");
  1641. // Initiate outbound connections from -addnode
  1642. if (!CreateThread(ThreadOpenAddedConnections, NULL))
  1643. printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
  1644. // Initiate outbound connections
  1645. if (!CreateThread(ThreadOpenConnections, NULL))
  1646. printf("Error: CreateThread(ThreadOpenConnections) failed\n");
  1647. // Process messages
  1648. if (!CreateThread(ThreadMessageHandler, NULL))
  1649. printf("Error: CreateThread(ThreadMessageHandler) failed\n");
  1650. // Dump network addresses
  1651. if (!CreateThread(ThreadDumpAddress, NULL))
  1652. printf("Error; CreateThread(ThreadDumpAddress) failed\n");
  1653. // Generate coins in the background
  1654. GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
  1655. }
  1656. bool StopNode()
  1657. {
  1658. printf("StopNode()\n");
  1659. fShutdown = true;
  1660. nTransactionsUpdated++;
  1661. int64 nStart = GetTime();
  1662. if (semOutbound)
  1663. for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
  1664. semOutbound->post();
  1665. do
  1666. {
  1667. int nThreadsRunning = 0;
  1668. for (int n = 0; n < THREAD_MAX; n++)
  1669. nThreadsRunning += vnThreadsRunning[n];
  1670. if (nThreadsRunning == 0)
  1671. break;
  1672. if (GetTime() - nStart > 20)
  1673. break;
  1674. Sleep(20);
  1675. } while(true);
  1676. if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
  1677. if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
  1678. if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
  1679. if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
  1680. if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
  1681. if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
  1682. #ifdef USE_UPNP
  1683. if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
  1684. #endif
  1685. if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
  1686. if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
  1687. if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
  1688. while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
  1689. Sleep(20);
  1690. Sleep(50);
  1691. DumpAddresses();
  1692. return true;
  1693. }
  1694. class CNetCleanup
  1695. {
  1696. public:
  1697. CNetCleanup()
  1698. {
  1699. }
  1700. ~CNetCleanup()
  1701. {
  1702. // Close sockets
  1703. BOOST_FOREACH(CNode* pnode, vNodes)
  1704. if (pnode->hSocket != INVALID_SOCKET)
  1705. closesocket(pnode->hSocket);
  1706. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  1707. if (hListenSocket != INVALID_SOCKET)
  1708. if (closesocket(hListenSocket) == SOCKET_ERROR)
  1709. printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
  1710. #ifdef WIN32
  1711. // Shutdown Windows Sockets
  1712. WSACleanup();
  1713. #endif
  1714. }
  1715. }
  1716. instance_of_cnetcleanup;