PPCoin: default ports; disabling irc; dns seeds; ThreadOpenConnections fix
[novacoin.git] / src / net.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6
7 #include "headers.h"
8 #include "irc.h"
9 #include "db.h"
10 #include "net.h"
11 #include "init.h"
12 #include "strlcpy.h"
13
14 #ifdef WIN32
15 #include <string.h>
16 #endif
17
18 #ifdef USE_UPNP
19 #include <miniupnpc/miniwget.h>
20 #include <miniupnpc/miniupnpc.h>
21 #include <miniupnpc/upnpcommands.h>
22 #include <miniupnpc/upnperrors.h>
23 #endif
24
25 using namespace std;
26 using namespace boost;
27
28 static const int MAX_OUTBOUND_CONNECTIONS = 8;
29
30 void ThreadMessageHandler2(void* parg);
31 void ThreadSocketHandler2(void* parg);
32 void ThreadOpenConnections2(void* parg);
33 #ifdef USE_UPNP
34 void ThreadMapPort2(void* parg);
35 #endif
36 void ThreadDNSAddressSeed2(void* parg);
37 bool OpenNetworkConnection(const CAddress& addrConnect);
38
39
40
41
42
43 //
44 // Global state variables
45 //
46 bool fClient = false;
47 bool fAllowDNS = false;
48 uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
49 CAddress addrLocalHost("0.0.0.0", 0, false, nLocalServices);
50 static CNode* pnodeLocalHost = NULL;
51 uint64 nLocalHostNonce = 0;
52 array<int, 10> vnThreadsRunning;
53 static SOCKET hListenSocket = INVALID_SOCKET;
54
55 vector<CNode*> vNodes;
56 CCriticalSection cs_vNodes;
57 map<vector<unsigned char>, CAddress> mapAddresses;
58 CCriticalSection cs_mapAddresses;
59 map<CInv, CDataStream> mapRelay;
60 deque<pair<int64, CInv> > vRelayExpiration;
61 CCriticalSection cs_mapRelay;
62 map<CInv, int64> mapAlreadyAskedFor;
63
64 // Settings
65 int fUseProxy = false;
66 int nConnectTimeout = 5000;
67 CAddress addrProxy("127.0.0.1",9050);
68
69
70
71
72 unsigned short GetListenPort()
73 {
74     return (unsigned short)(GetArg("-port", GetDefaultPort()));
75 }
76
77 void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
78 {
79     // Filter out duplicate requests
80     if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
81         return;
82     pindexLastGetBlocksBegin = pindexBegin;
83     hashLastGetBlocksEnd = hashEnd;
84
85     PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
86 }
87
88
89
90
91
92 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout)
93 {
94     hSocketRet = INVALID_SOCKET;
95
96     SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
97     if (hSocket == INVALID_SOCKET)
98         return false;
99 #ifdef SO_NOSIGPIPE
100     int set = 1;
101     setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
102 #endif
103
104     bool fProxy = (fUseProxy && addrConnect.IsRoutable());
105     struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());
106
107 #ifdef WIN32
108     u_long fNonblock = 1;
109     if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
110 #else
111     int fFlags = fcntl(hSocket, F_GETFL, 0);
112     if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
113 #endif
114     {
115         closesocket(hSocket);
116         return false;
117     }
118
119
120     if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
121     {
122         // WSAEINVAL is here because some legacy version of winsock uses it
123         if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
124         {
125             struct timeval timeout;
126             timeout.tv_sec  = nTimeout / 1000;
127             timeout.tv_usec = (nTimeout % 1000) * 1000;
128
129             fd_set fdset;
130             FD_ZERO(&fdset);
131             FD_SET(hSocket, &fdset);
132             int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
133             if (nRet == 0)
134             {
135                 printf("connection timeout\n");
136                 closesocket(hSocket);
137                 return false;
138             }
139             if (nRet == SOCKET_ERROR)
140             {
141                 printf("select() for connection failed: %i\n",WSAGetLastError());
142                 closesocket(hSocket);
143                 return false;
144             }
145             socklen_t nRetSize = sizeof(nRet);
146 #ifdef WIN32
147             if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
148 #else
149             if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
150 #endif
151             {
152                 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
153                 closesocket(hSocket);
154                 return false;
155             }
156             if (nRet != 0)
157             {
158                 printf("connect() failed after select(): %s\n",strerror(nRet));
159                 closesocket(hSocket);
160                 return false;
161             }
162         }
163 #ifdef WIN32
164         else if (WSAGetLastError() != WSAEISCONN)
165 #else
166         else
167 #endif
168         {
169             printf("connect() failed: %i\n",WSAGetLastError());
170             closesocket(hSocket);
171             return false;
172         }
173     }
174
175     /*
176     this isn't even strictly necessary
177     CNode::ConnectNode immediately turns the socket back to non-blocking
178     but we'll turn it back to blocking just in case
179     */
180 #ifdef WIN32
181     fNonblock = 0;
182     if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
183 #else
184     fFlags = fcntl(hSocket, F_GETFL, 0);
185     if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
186 #endif
187     {
188         closesocket(hSocket);
189         return false;
190     }
191
192     if (fProxy)
193     {
194         printf("proxy connecting %s\n", addrConnect.ToString().c_str());
195         char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
196         memcpy(pszSocks4IP + 2, &addrConnect.port, 2);
197         memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);
198         char* pszSocks4 = pszSocks4IP;
199         int nSize = sizeof(pszSocks4IP);
200
201         int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
202         if (ret != nSize)
203         {
204             closesocket(hSocket);
205             return error("Error sending to proxy");
206         }
207         char pchRet[8];
208         if (recv(hSocket, pchRet, 8, 0) != 8)
209         {
210             closesocket(hSocket);
211             return error("Error reading proxy response");
212         }
213         if (pchRet[1] != 0x5a)
214         {
215             closesocket(hSocket);
216             if (pchRet[1] != 0x5b)
217                 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
218             return false;
219         }
220         printf("proxy connected %s\n", addrConnect.ToString().c_str());
221     }
222
223     hSocketRet = hSocket;
224     return true;
225 }
226
227 // portDefault is in host order
228 bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup, int portDefault, bool fAllowPort)
229 {
230     vaddr.clear();
231     if (pszName[0] == 0)
232         return false;
233     int port = portDefault;
234     char psz[256];
235     char *pszHost = psz;
236     strlcpy(psz, pszName, sizeof(psz));
237     if (fAllowPort)
238     {
239         char* pszColon = strrchr(psz+1,':');
240         char *pszPortEnd = NULL;
241         int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0;
242         if (pszColon && pszPortEnd && pszPortEnd[0] == 0)
243         {
244             if (psz[0] == '[' && pszColon[-1] == ']')
245             {
246                 // Future: enable IPv6 colon-notation inside []
247                 pszHost = psz+1;
248                 pszColon[-1] = 0;
249             }
250             else
251                 pszColon[0] = 0;
252             port = portParsed;
253             if (port < 0 || port > USHRT_MAX)
254                 port = USHRT_MAX;
255         }
256     }
257
258     unsigned int addrIP = inet_addr(pszHost);
259     if (addrIP != INADDR_NONE)
260     {
261         // valid IP address passed
262         vaddr.push_back(CAddress(addrIP, port, nServices));
263         return true;
264     }
265
266     if (!fAllowLookup)
267         return false;
268
269     struct hostent* phostent = gethostbyname(pszHost);
270     if (!phostent)
271         return false;
272
273     if (phostent->h_addrtype != AF_INET)
274         return false;
275
276     char** ppAddr = phostent->h_addr_list;
277     while (*ppAddr != NULL && vaddr.size() != nMaxSolutions)
278     {
279         CAddress addr(((struct in_addr*)ppAddr[0])->s_addr, port, nServices);
280         if (addr.IsValid())
281             vaddr.push_back(addr);
282         ppAddr++;
283     }
284
285     return (vaddr.size() > 0);
286 }
287
288 // portDefault is in host order
289 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup, int portDefault, bool fAllowPort)
290 {
291     vector<CAddress> vaddr;
292     bool fRet = Lookup(pszName, vaddr, nServices, 1, fAllowLookup, portDefault, fAllowPort);
293     if (fRet)
294         addr = vaddr[0];
295     return fRet;
296 }
297
298 bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)
299 {
300     SOCKET hSocket;
301     if (!ConnectSocket(addrConnect, hSocket))
302         return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
303
304     send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
305
306     string strLine;
307     while (RecvLine(hSocket, strLine))
308     {
309         if (strLine.empty()) // HTTP response is separated from headers by blank line
310         {
311             loop
312             {
313                 if (!RecvLine(hSocket, strLine))
314                 {
315                     closesocket(hSocket);
316                     return false;
317                 }
318                 if (pszKeyword == NULL)
319                     break;
320                 if (strLine.find(pszKeyword) != -1)
321                 {
322                     strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
323                     break;
324                 }
325             }
326             closesocket(hSocket);
327             if (strLine.find("<") != -1)
328                 strLine = strLine.substr(0, strLine.find("<"));
329             strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
330             while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
331                 strLine.resize(strLine.size()-1);
332             CAddress addr(strLine,0,true);
333             printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
334             if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())
335                 return false;
336             ipRet = addr.ip;
337             return true;
338         }
339     }
340     closesocket(hSocket);
341     return error("GetMyExternalIP() : connection closed");
342 }
343
344 // We now get our external IP from the IRC server first and only use this as a backup
345 bool GetMyExternalIP(unsigned int& ipRet)
346 {
347     CAddress addrConnect;
348     const char* pszGet;
349     const char* pszKeyword;
350
351     if (fUseProxy)
352         return false;
353
354     for (int nLookup = 0; nLookup <= 1; nLookup++)
355     for (int nHost = 1; nHost <= 2; nHost++)
356     {
357         // We should be phasing out our use of sites like these.  If we need
358         // replacements, we should ask for volunteers to put this simple
359         // php file on their webserver that prints the client IP:
360         //  <?php echo $_SERVER["REMOTE_ADDR"]; ?>
361         if (nHost == 1)
362         {
363             addrConnect = CAddress("91.198.22.70",80); // checkip.dyndns.org
364
365             if (nLookup == 1)
366             {
367                 CAddress addrIP("checkip.dyndns.org", 80, true);
368                 if (addrIP.IsValid())
369                     addrConnect = addrIP;
370             }
371
372             pszGet = "GET / HTTP/1.1\r\n"
373                      "Host: checkip.dyndns.org\r\n"
374                      "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
375                      "Connection: close\r\n"
376                      "\r\n";
377
378             pszKeyword = "Address:";
379         }
380         else if (nHost == 2)
381         {
382             addrConnect = CAddress("74.208.43.192", 80); // www.showmyip.com
383
384             if (nLookup == 1)
385             {
386                 CAddress addrIP("www.showmyip.com", 80, true);
387                 if (addrIP.IsValid())
388                     addrConnect = addrIP;
389             }
390
391             pszGet = "GET /simple/ HTTP/1.1\r\n"
392                      "Host: www.showmyip.com\r\n"
393                      "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
394                      "Connection: close\r\n"
395                      "\r\n";
396
397             pszKeyword = NULL; // Returns just IP address
398         }
399
400         if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
401             return true;
402     }
403
404     return false;
405 }
406
407 void ThreadGetMyExternalIP(void* parg)
408 {
409     // Wait for IRC to get it first - disabled with ppcoin
410     if (false && !GetBoolArg("-noirc"))
411     {
412         for (int i = 0; i < 2 * 60; i++)
413         {
414             Sleep(1000);
415             if (fGotExternalIP || fShutdown)
416                 return;
417         }
418     }
419
420     // Fallback in case IRC fails to get it
421     if (GetMyExternalIP(addrLocalHost.ip))
422     {
423         printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
424         if (addrLocalHost.IsRoutable())
425         {
426             // If we already connected to a few before we had our IP, go back and addr them.
427             // setAddrKnown automatically filters any duplicate sends.
428             CAddress addr(addrLocalHost);
429             addr.nTime = GetAdjustedTime();
430             CRITICAL_BLOCK(cs_vNodes)
431                 BOOST_FOREACH(CNode* pnode, vNodes)
432                     pnode->PushAddress(addr);
433         }
434     }
435 }
436
437
438
439
440
441 bool AddAddress(CAddress addr, int64 nTimePenalty, CAddrDB *pAddrDB)
442 {
443     if (!addr.IsRoutable())
444         return false;
445     if (addr.ip == addrLocalHost.ip)
446         return false;
447     addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty);
448     bool fUpdated = false;
449     bool fNew = false;
450     CAddress addrFound = addr;
451
452     CRITICAL_BLOCK(cs_mapAddresses)
453     {
454         map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());
455         if (it == mapAddresses.end())
456         {
457             // New address
458             printf("AddAddress(%s)\n", addr.ToString().c_str());
459             mapAddresses.insert(make_pair(addr.GetKey(), addr));
460             fUpdated = true;
461             fNew = true;
462         }
463         else
464         {
465             addrFound = (*it).second;
466             if ((addrFound.nServices | addr.nServices) != addrFound.nServices)
467             {
468                 // Services have been added
469                 addrFound.nServices |= addr.nServices;
470                 fUpdated = true;
471             }
472             bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
473             int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
474             if (addrFound.nTime < addr.nTime - nUpdateInterval)
475             {
476                 // Periodically update most recently seen time
477                 addrFound.nTime = addr.nTime;
478                 fUpdated = true;
479             }
480         }
481     }
482     // There is a nasty deadlock bug if this is done inside the cs_mapAddresses
483     // CRITICAL_BLOCK:
484     // Thread 1:  begin db transaction (locks inside-db-mutex)
485     //            then AddAddress (locks cs_mapAddresses)
486     // Thread 2:  AddAddress (locks cs_mapAddresses)
487     //             ... then db operation hangs waiting for inside-db-mutex
488     if (fUpdated)
489     {
490         if (pAddrDB)
491             pAddrDB->WriteAddress(addrFound);
492         else
493             CAddrDB().WriteAddress(addrFound);
494     }
495     return fNew;
496 }
497
498 void AddressCurrentlyConnected(const CAddress& addr)
499 {
500     CRITICAL_BLOCK(cs_mapAddresses)
501     {
502         // Only if it's been published already
503         map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());
504         if (it != mapAddresses.end())
505         {
506             CAddress& addrFound = (*it).second;
507             int64 nUpdateInterval = 20 * 60;
508             if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)
509             {
510                 // Periodically update most recently seen time
511                 addrFound.nTime = GetAdjustedTime();
512                 CAddrDB addrdb;
513                 addrdb.WriteAddress(addrFound);
514             }
515         }
516     }
517 }
518
519
520
521
522
523 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)
524 {
525     // If the dialog might get closed before the reply comes back,
526     // call this in the destructor so it doesn't get called after it's deleted.
527     CRITICAL_BLOCK(cs_vNodes)
528     {
529         BOOST_FOREACH(CNode* pnode, vNodes)
530         {
531             CRITICAL_BLOCK(pnode->cs_mapRequests)
532             {
533                 for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)
534                 {
535                     CRequestTracker& tracker = (*mi).second;
536                     if (tracker.fn == fn && tracker.param1 == param1)
537                         pnode->mapRequests.erase(mi++);
538                     else
539                         mi++;
540                 }
541             }
542         }
543     }
544 }
545
546
547
548
549
550
551
552 //
553 // Subscription methods for the broadcast and subscription system.
554 // Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.
555 //
556 // The subscription system uses a meet-in-the-middle strategy.
557 // With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers
558 // subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.
559 //
560
561 bool AnySubscribed(unsigned int nChannel)
562 {
563     if (pnodeLocalHost->IsSubscribed(nChannel))
564         return true;
565     CRITICAL_BLOCK(cs_vNodes)
566         BOOST_FOREACH(CNode* pnode, vNodes)
567             if (pnode->IsSubscribed(nChannel))
568                 return true;
569     return false;
570 }
571
572 bool CNode::IsSubscribed(unsigned int nChannel)
573 {
574     if (nChannel >= vfSubscribe.size())
575         return false;
576     return vfSubscribe[nChannel];
577 }
578
579 void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)
580 {
581     if (nChannel >= vfSubscribe.size())
582         return;
583
584     if (!AnySubscribed(nChannel))
585     {
586         // Relay subscribe
587         CRITICAL_BLOCK(cs_vNodes)
588             BOOST_FOREACH(CNode* pnode, vNodes)
589                 if (pnode != this)
590                     pnode->PushMessage("subscribe", nChannel, nHops);
591     }
592
593     vfSubscribe[nChannel] = true;
594 }
595
596 void CNode::CancelSubscribe(unsigned int nChannel)
597 {
598     if (nChannel >= vfSubscribe.size())
599         return;
600
601     // Prevent from relaying cancel if wasn't subscribed
602     if (!vfSubscribe[nChannel])
603         return;
604     vfSubscribe[nChannel] = false;
605
606     if (!AnySubscribed(nChannel))
607     {
608         // Relay subscription cancel
609         CRITICAL_BLOCK(cs_vNodes)
610             BOOST_FOREACH(CNode* pnode, vNodes)
611                 if (pnode != this)
612                     pnode->PushMessage("sub-cancel", nChannel);
613     }
614 }
615
616
617
618
619
620
621
622
623
624 CNode* FindNode(unsigned int ip)
625 {
626     CRITICAL_BLOCK(cs_vNodes)
627     {
628         BOOST_FOREACH(CNode* pnode, vNodes)
629             if (pnode->addr.ip == ip)
630                 return (pnode);
631     }
632     return NULL;
633 }
634
635 CNode* FindNode(CAddress addr)
636 {
637     CRITICAL_BLOCK(cs_vNodes)
638     {
639         BOOST_FOREACH(CNode* pnode, vNodes)
640             if (pnode->addr == addr)
641                 return (pnode);
642     }
643     return NULL;
644 }
645
646 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)
647 {
648     if (addrConnect.ip == addrLocalHost.ip)
649         return NULL;
650
651     // Look for an existing connection
652     CNode* pnode = FindNode(addrConnect.ip);
653     if (pnode)
654     {
655         if (nTimeout != 0)
656             pnode->AddRef(nTimeout);
657         else
658             pnode->AddRef();
659         return pnode;
660     }
661
662     /// debug print
663     printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",
664         addrConnect.ToString().c_str(),
665         (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,
666         (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);
667
668     CRITICAL_BLOCK(cs_mapAddresses)
669         mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();
670
671     // Connect
672     SOCKET hSocket;
673     if (ConnectSocket(addrConnect, hSocket))
674     {
675         /// debug print
676         printf("connected %s\n", addrConnect.ToString().c_str());
677
678         // Set to nonblocking
679 #ifdef WIN32
680         u_long nOne = 1;
681         if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
682             printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
683 #else
684         if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
685             printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
686 #endif
687
688         // Add node
689         CNode* pnode = new CNode(hSocket, addrConnect, false);
690         if (nTimeout != 0)
691             pnode->AddRef(nTimeout);
692         else
693             pnode->AddRef();
694         CRITICAL_BLOCK(cs_vNodes)
695             vNodes.push_back(pnode);
696
697         pnode->nTimeConnected = GetTime();
698         return pnode;
699     }
700     else
701     {
702         return NULL;
703     }
704 }
705
706 void CNode::CloseSocketDisconnect()
707 {
708     fDisconnect = true;
709     if (hSocket != INVALID_SOCKET)
710     {
711         if (fDebug)
712             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
713         printf("disconnecting node %s\n", addr.ToString().c_str());
714         closesocket(hSocket);
715         hSocket = INVALID_SOCKET;
716     }
717 }
718
719 void CNode::Cleanup()
720 {
721     // All of a nodes broadcasts and subscriptions are automatically torn down
722     // when it goes down, so a node has to stay up to keep its broadcast going.
723
724     // Cancel subscriptions
725     for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)
726         if (vfSubscribe[nChannel])
727             CancelSubscribe(nChannel);
728 }
729
730
731 std::map<unsigned int, int64> CNode::setBanned;
732 CCriticalSection CNode::cs_setBanned;
733
734 void CNode::ClearBanned()
735 {
736     setBanned.clear();
737 }
738
739 bool CNode::IsBanned(unsigned int ip)
740 {
741     bool fResult = false;
742     CRITICAL_BLOCK(cs_setBanned)
743     {
744         std::map<unsigned int, int64>::iterator i = setBanned.find(ip);
745         if (i != setBanned.end())
746         {
747             int64 t = (*i).second;
748             if (GetTime() < t)
749                 fResult = true;
750         }
751     }
752     return fResult;
753 }
754
755 bool CNode::Misbehaving(int howmuch)
756 {
757     if (addr.IsLocal())
758     {
759         printf("Warning: local node %s misbehaving\n", addr.ToString().c_str());
760         return false;
761     }
762
763     nMisbehavior += howmuch;
764     if (nMisbehavior >= GetArg("-banscore", 100))
765     {
766         int64 banTime = GetTime()+GetArg("-bantime", 60*60*24);  // Default 24-hour ban
767         CRITICAL_BLOCK(cs_setBanned)
768             if (setBanned[addr.ip] < banTime)
769                 setBanned[addr.ip] = banTime;
770         CloseSocketDisconnect();
771         printf("Disconnected %s for misbehavior (score=%d)\n", addr.ToString().c_str(), nMisbehavior);
772         return true;
773     }
774     return false;
775 }
776
777
778
779
780
781
782
783
784
785
786
787
788 void ThreadSocketHandler(void* parg)
789 {
790     IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
791     try
792     {
793         vnThreadsRunning[0]++;
794         ThreadSocketHandler2(parg);
795         vnThreadsRunning[0]--;
796     }
797     catch (std::exception& e) {
798         vnThreadsRunning[0]--;
799         PrintException(&e, "ThreadSocketHandler()");
800     } catch (...) {
801         vnThreadsRunning[0]--;
802         throw; // support pthread_cancel()
803     }
804     printf("ThreadSocketHandler exiting\n");
805 }
806
807 void ThreadSocketHandler2(void* parg)
808 {
809     printf("ThreadSocketHandler started\n");
810     list<CNode*> vNodesDisconnected;
811     int nPrevNodeCount = 0;
812
813     loop
814     {
815         //
816         // Disconnect nodes
817         //
818         CRITICAL_BLOCK(cs_vNodes)
819         {
820             // Disconnect unused nodes
821             vector<CNode*> vNodesCopy = vNodes;
822             BOOST_FOREACH(CNode* pnode, vNodesCopy)
823             {
824                 if (pnode->fDisconnect ||
825                     (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
826                 {
827                     // remove from vNodes
828                     vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
829
830                     // close socket and cleanup
831                     pnode->CloseSocketDisconnect();
832                     pnode->Cleanup();
833
834                     // hold in disconnected pool until all refs are released
835                     pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
836                     if (pnode->fNetworkNode || pnode->fInbound)
837                         pnode->Release();
838                     vNodesDisconnected.push_back(pnode);
839                 }
840             }
841
842             // Delete disconnected nodes
843             list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
844             BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
845             {
846                 // wait until threads are done using it
847                 if (pnode->GetRefCount() <= 0)
848                 {
849                     bool fDelete = false;
850                     TRY_CRITICAL_BLOCK(pnode->cs_vSend)
851                      TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
852                       TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)
853                        TRY_CRITICAL_BLOCK(pnode->cs_inventory)
854                         fDelete = true;
855                     if (fDelete)
856                     {
857                         vNodesDisconnected.remove(pnode);
858                         delete pnode;
859                     }
860                 }
861             }
862         }
863         if (vNodes.size() != nPrevNodeCount)
864         {
865             nPrevNodeCount = vNodes.size();
866             MainFrameRepaint();
867         }
868
869
870         //
871         // Find which sockets have data to receive
872         //
873         struct timeval timeout;
874         timeout.tv_sec  = 0;
875         timeout.tv_usec = 50000; // frequency to poll pnode->vSend
876
877         fd_set fdsetRecv;
878         fd_set fdsetSend;
879         fd_set fdsetError;
880         FD_ZERO(&fdsetRecv);
881         FD_ZERO(&fdsetSend);
882         FD_ZERO(&fdsetError);
883         SOCKET hSocketMax = 0;
884
885         if(hListenSocket != INVALID_SOCKET)
886             FD_SET(hListenSocket, &fdsetRecv);
887         hSocketMax = max(hSocketMax, hListenSocket);
888         CRITICAL_BLOCK(cs_vNodes)
889         {
890             BOOST_FOREACH(CNode* pnode, vNodes)
891             {
892                 if (pnode->hSocket == INVALID_SOCKET)
893                     continue;
894                 FD_SET(pnode->hSocket, &fdsetRecv);
895                 FD_SET(pnode->hSocket, &fdsetError);
896                 hSocketMax = max(hSocketMax, pnode->hSocket);
897                 TRY_CRITICAL_BLOCK(pnode->cs_vSend)
898                     if (!pnode->vSend.empty())
899                         FD_SET(pnode->hSocket, &fdsetSend);
900             }
901         }
902
903         vnThreadsRunning[0]--;
904         int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
905         vnThreadsRunning[0]++;
906         if (fShutdown)
907             return;
908         if (nSelect == SOCKET_ERROR)
909         {
910             int nErr = WSAGetLastError();
911             if (hSocketMax > -1)
912             {
913                 printf("socket select error %d\n", nErr);
914                 for (int i = 0; i <= hSocketMax; i++)
915                     FD_SET(i, &fdsetRecv);
916             }
917             FD_ZERO(&fdsetSend);
918             FD_ZERO(&fdsetError);
919             Sleep(timeout.tv_usec/1000);
920         }
921
922
923         //
924         // Accept new connections
925         //
926         if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
927         {
928             struct sockaddr_in sockaddr;
929             socklen_t len = sizeof(sockaddr);
930             SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
931             CAddress addr(sockaddr);
932             int nInbound = 0;
933
934             CRITICAL_BLOCK(cs_vNodes)
935                 BOOST_FOREACH(CNode* pnode, vNodes)
936                 if (pnode->fInbound)
937                     nInbound++;
938             if (hSocket == INVALID_SOCKET)
939             {
940                 if (WSAGetLastError() != WSAEWOULDBLOCK)
941                     printf("socket error accept failed: %d\n", WSAGetLastError());
942             }
943             else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
944             {
945                 closesocket(hSocket);
946             }
947             else if (CNode::IsBanned(addr.ip))
948             {
949                 printf("connetion from %s dropped (banned)\n", addr.ToString().c_str());
950                 closesocket(hSocket);
951             }
952             else
953             {
954                 printf("accepted connection %s\n", addr.ToString().c_str());
955                 CNode* pnode = new CNode(hSocket, addr, true);
956                 pnode->AddRef();
957                 CRITICAL_BLOCK(cs_vNodes)
958                     vNodes.push_back(pnode);
959             }
960         }
961
962
963         //
964         // Service each socket
965         //
966         vector<CNode*> vNodesCopy;
967         CRITICAL_BLOCK(cs_vNodes)
968         {
969             vNodesCopy = vNodes;
970             BOOST_FOREACH(CNode* pnode, vNodesCopy)
971                 pnode->AddRef();
972         }
973         BOOST_FOREACH(CNode* pnode, vNodesCopy)
974         {
975             if (fShutdown)
976                 return;
977
978             //
979             // Receive
980             //
981             if (pnode->hSocket == INVALID_SOCKET)
982                 continue;
983             if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
984             {
985                 TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
986                 {
987                     CDataStream& vRecv = pnode->vRecv;
988                     unsigned int nPos = vRecv.size();
989
990                     if (nPos > ReceiveBufferSize()) {
991                         if (!pnode->fDisconnect)
992                             printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
993                         pnode->CloseSocketDisconnect();
994                     }
995                     else {
996                         // typical socket buffer is 8K-64K
997                         char pchBuf[0x10000];
998                         int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
999                         if (nBytes > 0)
1000                         {
1001                             vRecv.resize(nPos + nBytes);
1002                             memcpy(&vRecv[nPos], pchBuf, nBytes);
1003                             pnode->nLastRecv = GetTime();
1004                         }
1005                         else if (nBytes == 0)
1006                         {
1007                             // socket closed gracefully
1008                             if (!pnode->fDisconnect)
1009                                 printf("socket closed\n");
1010                             pnode->CloseSocketDisconnect();
1011                         }
1012                         else if (nBytes < 0)
1013                         {
1014                             // error
1015                             int nErr = WSAGetLastError();
1016                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1017                             {
1018                                 if (!pnode->fDisconnect)
1019                                     printf("socket recv error %d\n", nErr);
1020                                 pnode->CloseSocketDisconnect();
1021                             }
1022                         }
1023                     }
1024                 }
1025             }
1026
1027             //
1028             // Send
1029             //
1030             if (pnode->hSocket == INVALID_SOCKET)
1031                 continue;
1032             if (FD_ISSET(pnode->hSocket, &fdsetSend))
1033             {
1034                 TRY_CRITICAL_BLOCK(pnode->cs_vSend)
1035                 {
1036                     CDataStream& vSend = pnode->vSend;
1037                     if (!vSend.empty())
1038                     {
1039                         int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
1040                         if (nBytes > 0)
1041                         {
1042                             vSend.erase(vSend.begin(), vSend.begin() + nBytes);
1043                             pnode->nLastSend = GetTime();
1044                         }
1045                         else if (nBytes < 0)
1046                         {
1047                             // error
1048                             int nErr = WSAGetLastError();
1049                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1050                             {
1051                                 printf("socket send error %d\n", nErr);
1052                                 pnode->CloseSocketDisconnect();
1053                             }
1054                         }
1055                         if (vSend.size() > SendBufferSize()) {
1056                             if (!pnode->fDisconnect)
1057                                 printf("socket send flood control disconnect (%d bytes)\n", vSend.size());
1058                             pnode->CloseSocketDisconnect();
1059                         }
1060                     }
1061                 }
1062             }
1063
1064             //
1065             // Inactivity checking
1066             //
1067             if (pnode->vSend.empty())
1068                 pnode->nLastSendEmpty = GetTime();
1069             if (GetTime() - pnode->nTimeConnected > 60)
1070             {
1071                 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1072                 {
1073                     printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
1074                     pnode->fDisconnect = true;
1075                 }
1076                 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
1077                 {
1078                     printf("socket not sending\n");
1079                     pnode->fDisconnect = true;
1080                 }
1081                 else if (GetTime() - pnode->nLastRecv > 90*60)
1082                 {
1083                     printf("socket inactivity timeout\n");
1084                     pnode->fDisconnect = true;
1085                 }
1086             }
1087         }
1088         CRITICAL_BLOCK(cs_vNodes)
1089         {
1090             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1091                 pnode->Release();
1092         }
1093
1094         Sleep(10);
1095     }
1096 }
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106 #ifdef USE_UPNP
1107 void ThreadMapPort(void* parg)
1108 {
1109     IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg));
1110     try
1111     {
1112         vnThreadsRunning[5]++;
1113         ThreadMapPort2(parg);
1114         vnThreadsRunning[5]--;
1115     }
1116     catch (std::exception& e) {
1117         vnThreadsRunning[5]--;
1118         PrintException(&e, "ThreadMapPort()");
1119     } catch (...) {
1120         vnThreadsRunning[5]--;
1121         PrintException(NULL, "ThreadMapPort()");
1122     }
1123     printf("ThreadMapPort exiting\n");
1124 }
1125
1126 void ThreadMapPort2(void* parg)
1127 {
1128     printf("ThreadMapPort started\n");
1129
1130     char port[6];
1131     sprintf(port, "%d", GetListenPort());
1132
1133     const char * rootdescurl = 0;
1134     const char * multicastif = 0;
1135     const char * minissdpdpath = 0;
1136     struct UPNPDev * devlist = 0;
1137     char lanaddr[64];
1138
1139 #ifndef UPNPDISCOVER_SUCCESS
1140     /* miniupnpc 1.5 */
1141     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1142 #else
1143     /* miniupnpc 1.6 */
1144     int error = 0;
1145     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1146 #endif
1147
1148     struct UPNPUrls urls;
1149     struct IGDdatas data;
1150     int r;
1151
1152     r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1153     if (r == 1)
1154     {
1155         char intClient[16];
1156         char intPort[6];
1157         string strDesc = "Bitcoin " + FormatFullVersion();
1158 #ifndef UPNPDISCOVER_SUCCESS
1159     /* miniupnpc 1.5 */
1160         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1161                                 port, port, lanaddr, strDesc.c_str(), "TCP", 0);
1162 #else
1163     /* miniupnpc 1.6 */
1164         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1165                                 port, port, lanaddr, strDesc.c_str(), "TCP", 0, "0");
1166 #endif
1167
1168         if(r!=UPNPCOMMAND_SUCCESS)
1169             printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1170                 port, port, lanaddr, r, strupnperror(r));
1171         else
1172             printf("UPnP Port Mapping successful.\n");
1173         loop {
1174             if (fShutdown || !fUseUPnP)
1175             {
1176                 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0);
1177                 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1178                 freeUPNPDevlist(devlist); devlist = 0;
1179                 FreeUPNPUrls(&urls);
1180                 return;
1181             }
1182             Sleep(2000);
1183         }
1184     } else {
1185         printf("No valid UPnP IGDs found\n");
1186         freeUPNPDevlist(devlist); devlist = 0;
1187         if (r != 0)
1188             FreeUPNPUrls(&urls);
1189         loop {
1190             if (fShutdown || !fUseUPnP)
1191                 return;
1192             Sleep(2000);
1193         }
1194     }
1195 }
1196
1197 void MapPort(bool fMapPort)
1198 {
1199     if (fUseUPnP != fMapPort)
1200     {
1201         fUseUPnP = fMapPort;
1202         WriteSetting("fUseUPnP", fUseUPnP);
1203     }
1204     if (fUseUPnP && vnThreadsRunning[5] < 1)
1205     {
1206         if (!CreateThread(ThreadMapPort, NULL))
1207             printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1208     }
1209 }
1210 #else
1211 void MapPort(bool /* unused fMapPort */)
1212 {
1213     // Intentionally left blank.
1214 }
1215 #endif
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225 // testnet dns seed begins with 't', all else are ppcoin dns seeds.
1226 static const char *strDNSSeed[] = {
1227     "ppcseed.zapto.org",
1228     "tncseed.zapto.org"
1229 };
1230
1231 void ThreadDNSAddressSeed(void* parg)
1232 {
1233     IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
1234     try
1235     {
1236         vnThreadsRunning[6]++;
1237         ThreadDNSAddressSeed2(parg);
1238         vnThreadsRunning[6]--;
1239     }
1240     catch (std::exception& e) {
1241         vnThreadsRunning[6]--;
1242         PrintException(&e, "ThreadDNSAddressSeed()");
1243     } catch (...) {
1244         vnThreadsRunning[6]--;
1245         throw; // support pthread_cancel()
1246     }
1247     printf("ThreadDNSAddressSeed exiting\n");
1248 }
1249
1250 void ThreadDNSAddressSeed2(void* parg)
1251 {
1252     printf("ThreadDNSAddressSeed started\n");
1253     int found = 0;
1254
1255     if (true /*!fTestNet*/)  // ppcoin enables dns seeding with testnet too
1256     {
1257         printf("Loading addresses from DNS seeds (could take a while)\n");
1258         CAddrDB addrDB;
1259         addrDB.TxnBegin();
1260
1261         for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1262             if (fTestNet && strDNSSeed[seed_idx][0] != 't') continue;
1263             if ((!fTestNet) && strDNSSeed[seed_idx][0] == 't') continue;
1264  
1265             vector<CAddress> vaddr;
1266             if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true))
1267             {
1268                 BOOST_FOREACH (CAddress& addr, vaddr)
1269                 {
1270                     if (addr.GetByte(3) != 127)
1271                     {
1272                         addr.nTime = 0;
1273                         AddAddress(addr, 0, &addrDB);
1274                         found++;
1275                     }
1276                 }
1277             }
1278         }
1279
1280         addrDB.TxnCommit();  // Save addresses (it's ok if this fails)
1281     }
1282
1283     printf("%d addresses found from DNS seeds\n", found);
1284 }
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297 unsigned int pnSeed[] =
1298 {
1299     0xfc01a8c0
1300 };
1301
1302
1303
1304 void ThreadOpenConnections(void* parg)
1305 {
1306     IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
1307     try
1308     {
1309         vnThreadsRunning[1]++;
1310         ThreadOpenConnections2(parg);
1311         vnThreadsRunning[1]--;
1312     }
1313     catch (std::exception& e) {
1314         vnThreadsRunning[1]--;
1315         PrintException(&e, "ThreadOpenConnections()");
1316     } catch (...) {
1317         vnThreadsRunning[1]--;
1318         PrintException(NULL, "ThreadOpenConnections()");
1319     }
1320     printf("ThreadOpenConnections exiting\n");
1321 }
1322
1323 void ThreadOpenConnections2(void* parg)
1324 {
1325     printf("ThreadOpenConnections started\n");
1326
1327     // Connect to specific addresses
1328     if (mapArgs.count("-connect"))
1329     {
1330         for (int64 nLoop = 0;; nLoop++)
1331         {
1332             BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1333             {
1334                 CAddress addr(strAddr, fAllowDNS);
1335                 if (addr.IsValid())
1336                     OpenNetworkConnection(addr);
1337                 for (int i = 0; i < 10 && i < nLoop; i++)
1338                 {
1339                     Sleep(500);
1340                     if (fShutdown)
1341                         return;
1342                 }
1343             }
1344         }
1345     }
1346
1347     // Connect to manually added nodes first
1348     if (mapArgs.count("-addnode"))
1349     {
1350         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
1351         {
1352             CAddress addr(strAddr, fAllowDNS);
1353             if (addr.IsValid())
1354             {
1355                 OpenNetworkConnection(addr);
1356                 Sleep(500);
1357                 if (fShutdown)
1358                     return;
1359             }
1360         }
1361     }
1362
1363     // Initiate network connections
1364     int64 nStart = GetTime();
1365     loop
1366     {
1367         // Limit outbound connections
1368         vnThreadsRunning[1]--;
1369         Sleep(500);
1370         loop
1371         {
1372             int nOutbound = 0;
1373             CRITICAL_BLOCK(cs_vNodes)
1374                 BOOST_FOREACH(CNode* pnode, vNodes)
1375                     if (!pnode->fInbound)
1376                         nOutbound++;
1377             int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;
1378             nMaxOutboundConnections = min(nMaxOutboundConnections, (int)GetArg("-maxconnections", 125));
1379             if (nOutbound < nMaxOutboundConnections)
1380                 break;
1381             Sleep(2000);
1382             if (fShutdown)
1383                 return;
1384         }
1385         vnThreadsRunning[1]++;
1386         if (fShutdown)
1387             return;
1388
1389         CRITICAL_BLOCK(cs_mapAddresses)
1390         {
1391             // Add seed nodes if IRC isn't working
1392             bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
1393             if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)
1394             {
1395                 for (int i = 0; i < ARRAYLEN(pnSeed); i++)
1396                 {
1397                     // It'll only connect to one or two seed nodes because once it connects,
1398                     // it'll get a pile of addresses with newer timestamps.
1399                     // Seed nodes are given a random 'last seen time' of between one and two
1400                     // weeks ago.
1401                     const int64 nOneWeek = 7*24*60*60;
1402                     CAddress addr;
1403                     addr.ip = pnSeed[i];
1404                     addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1405                     AddAddress(addr);
1406                 }
1407             }
1408         }
1409
1410
1411         //
1412         // Choose an address to connect to based on most recently seen
1413         //
1414         CAddress addrConnect;
1415         int64 nBest = INT64_MIN;
1416
1417         // Only connect to one address per a.b.?.? range.
1418         // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1419         set<unsigned int> setConnected;
1420         CRITICAL_BLOCK(cs_vNodes)
1421             BOOST_FOREACH(CNode* pnode, vNodes)
1422                 setConnected.insert(pnode->addr.ip & 0x0000ffff);
1423
1424         int64 nANow = GetAdjustedTime();
1425
1426         CRITICAL_BLOCK(cs_mapAddresses)
1427         {
1428             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
1429             {
1430                 const CAddress& addr = item.second;
1431                 if (addr.ip == addrLocalHost.ip || !addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))
1432                     continue;
1433                 int64 nSinceLastSeen = nANow - addr.nTime;
1434                 int64 nSinceLastTry = nANow - addr.nLastTry;
1435
1436                 // Randomize the order in a deterministic way, putting the standard port first
1437                 int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);
1438                 if (addr.port != htons(GetDefaultPort()))
1439                     nRandomizer += 2 * 60 * 60;
1440
1441                 // Last seen  Base retry frequency
1442                 //   <1 hour   10 min
1443                 //    1 hour    1 hour
1444                 //    4 hours   2 hours
1445                 //   24 hours   5 hours
1446                 //   48 hours   7 hours
1447                 //    7 days   13 hours
1448                 //   30 days   27 hours
1449                 //   90 days   46 hours
1450                 //  365 days   93 hours
1451                 int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);
1452
1453                 // Fast reconnect for one hour after last seen
1454                 if (nSinceLastSeen < 60 * 60)
1455                     nDelay = 10 * 60;
1456
1457                 // Limit retry frequency
1458                 if (nSinceLastTry < nDelay)
1459                     continue;
1460
1461                 // If we have IRC, we'll be notified when they first come online,
1462                 // and again every 24 hours by the refresh broadcast.
1463                 if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)
1464                     continue;
1465
1466                 // Only try the old stuff if we don't have enough connections
1467                 if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60)
1468                     continue;
1469
1470                 // If multiple addresses are ready, prioritize by time since
1471                 // last seen and time since last tried.
1472                 int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;
1473                 if (nScore > nBest)
1474                 {
1475                     nBest = nScore;
1476                     addrConnect = addr;
1477                 }
1478             }
1479         }
1480
1481         if (addrConnect.IsValid())
1482             OpenNetworkConnection(addrConnect);
1483     }
1484 }
1485
1486 bool OpenNetworkConnection(const CAddress& addrConnect)
1487 {
1488     //
1489     // Initiate outbound network connection
1490     //
1491     if (fShutdown)
1492         return false;
1493     if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() ||
1494         FindNode(addrConnect.ip) || CNode::IsBanned(addrConnect.ip))
1495         return false;
1496
1497     vnThreadsRunning[1]--;
1498     CNode* pnode = ConnectNode(addrConnect);
1499     vnThreadsRunning[1]++;
1500     if (fShutdown)
1501         return false;
1502     if (!pnode)
1503         return false;
1504     pnode->fNetworkNode = true;
1505
1506     return true;
1507 }
1508
1509
1510
1511
1512
1513
1514
1515
1516 void ThreadMessageHandler(void* parg)
1517 {
1518     IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
1519     try
1520     {
1521         vnThreadsRunning[2]++;
1522         ThreadMessageHandler2(parg);
1523         vnThreadsRunning[2]--;
1524     }
1525     catch (std::exception& e) {
1526         vnThreadsRunning[2]--;
1527         PrintException(&e, "ThreadMessageHandler()");
1528     } catch (...) {
1529         vnThreadsRunning[2]--;
1530         PrintException(NULL, "ThreadMessageHandler()");
1531     }
1532     printf("ThreadMessageHandler exiting\n");
1533 }
1534
1535 void ThreadMessageHandler2(void* parg)
1536 {
1537     printf("ThreadMessageHandler started\n");
1538     SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1539     while (!fShutdown)
1540     {
1541         vector<CNode*> vNodesCopy;
1542         CRITICAL_BLOCK(cs_vNodes)
1543         {
1544             vNodesCopy = vNodes;
1545             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1546                 pnode->AddRef();
1547         }
1548
1549         // Poll the connected nodes for messages
1550         CNode* pnodeTrickle = NULL;
1551         if (!vNodesCopy.empty())
1552             pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1553         BOOST_FOREACH(CNode* pnode, vNodesCopy)
1554         {
1555             // Receive messages
1556             TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
1557                 ProcessMessages(pnode);
1558             if (fShutdown)
1559                 return;
1560
1561             // Send messages
1562             TRY_CRITICAL_BLOCK(pnode->cs_vSend)
1563                 SendMessages(pnode, pnode == pnodeTrickle);
1564             if (fShutdown)
1565                 return;
1566         }
1567
1568         CRITICAL_BLOCK(cs_vNodes)
1569         {
1570             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1571                 pnode->Release();
1572         }
1573
1574         // Wait and allow messages to bunch up.
1575         // Reduce vnThreadsRunning so StopNode has permission to exit while
1576         // we're sleeping, but we must always check fShutdown after doing this.
1577         vnThreadsRunning[2]--;
1578         Sleep(100);
1579         if (fRequestShutdown)
1580             Shutdown(NULL);
1581         vnThreadsRunning[2]++;
1582         if (fShutdown)
1583             return;
1584     }
1585 }
1586
1587
1588
1589
1590
1591
1592 bool BindListenPort(string& strError)
1593 {
1594     strError = "";
1595     int nOne = 1;
1596     addrLocalHost.port = htons(GetListenPort());
1597
1598 #ifdef WIN32
1599     // Initialize Windows Sockets
1600     WSADATA wsadata;
1601     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1602     if (ret != NO_ERROR)
1603     {
1604         strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1605         printf("%s\n", strError.c_str());
1606         return false;
1607     }
1608 #endif
1609
1610     // Create socket for listening for incoming connections
1611     hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1612     if (hListenSocket == INVALID_SOCKET)
1613     {
1614         strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1615         printf("%s\n", strError.c_str());
1616         return false;
1617     }
1618
1619 #ifdef SO_NOSIGPIPE
1620     // Different way of disabling SIGPIPE on BSD
1621     setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1622 #endif
1623
1624 #ifndef WIN32
1625     // Allow binding if the port is still in TIME_WAIT state after
1626     // the program was closed and restarted.  Not an issue on windows.
1627     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1628 #endif
1629
1630 #ifdef WIN32
1631     // Set to nonblocking, incoming connections will also inherit this
1632     if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1633 #else
1634     if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1635 #endif
1636     {
1637         strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1638         printf("%s\n", strError.c_str());
1639         return false;
1640     }
1641
1642     // The sockaddr_in structure specifies the address family,
1643     // IP address, and port for the socket that is being bound
1644     struct sockaddr_in sockaddr;
1645     memset(&sockaddr, 0, sizeof(sockaddr));
1646     sockaddr.sin_family = AF_INET;
1647     sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer
1648     sockaddr.sin_port = htons(GetListenPort());
1649     if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
1650     {
1651         int nErr = WSAGetLastError();
1652         if (nErr == WSAEADDRINUSE)
1653             strError = strprintf(_("Unable to bind to port %d on this computer.  Bitcoin is probably already running."), ntohs(sockaddr.sin_port));
1654         else
1655             strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);
1656         printf("%s\n", strError.c_str());
1657         return false;
1658     }
1659     printf("Bound to port %d\n", ntohs(sockaddr.sin_port));
1660
1661     // Listen for incoming connections
1662     if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1663     {
1664         strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1665         printf("%s\n", strError.c_str());
1666         return false;
1667     }
1668
1669     return true;
1670 }
1671
1672 void StartNode(void* parg)
1673 {
1674     if (pnodeLocalHost == NULL)
1675         pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", 0, false, nLocalServices));
1676
1677 #ifdef WIN32
1678     // Get local host ip
1679     char pszHostName[1000] = "";
1680     if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1681     {
1682         vector<CAddress> vaddr;
1683         if (Lookup(pszHostName, vaddr, nLocalServices, -1, true))
1684             BOOST_FOREACH (const CAddress &addr, vaddr)
1685                 if (addr.GetByte(3) != 127)
1686                 {
1687                     addrLocalHost = addr;
1688                     break;
1689                 }
1690     }
1691 #else
1692     // Get local host ip
1693     struct ifaddrs* myaddrs;
1694     if (getifaddrs(&myaddrs) == 0)
1695     {
1696         for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1697         {
1698             if (ifa->ifa_addr == NULL) continue;
1699             if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1700             if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1701             if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1702             char pszIP[100];
1703             if (ifa->ifa_addr->sa_family == AF_INET)
1704             {
1705                 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1706                 if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL)
1707                     printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);
1708
1709                 // Take the first IP that isn't loopback 127.x.x.x
1710                 CAddress addr(*(unsigned int*)&s4->sin_addr, GetListenPort(), nLocalServices);
1711                 if (addr.IsValid() && addr.GetByte(3) != 127)
1712                 {
1713                     addrLocalHost = addr;
1714                     break;
1715                 }
1716             }
1717             else if (ifa->ifa_addr->sa_family == AF_INET6)
1718             {
1719                 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1720                 if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL)
1721                     printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP);
1722             }
1723         }
1724         freeifaddrs(myaddrs);
1725     }
1726 #endif
1727     printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());
1728
1729     if (fUseProxy || mapArgs.count("-connect") || fNoListen)
1730     {
1731         // Proxies can't take incoming connections
1732         addrLocalHost.ip = CAddress("0.0.0.0").ip;
1733         printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());
1734     }
1735     else
1736     {
1737         CreateThread(ThreadGetMyExternalIP, NULL);
1738     }
1739
1740     //
1741     // Start threads
1742     //
1743
1744     if (GetBoolArg("-nodnsseed"))
1745         printf("DNS seeding disabled\n");
1746     else
1747         if (!CreateThread(ThreadDNSAddressSeed, NULL))
1748             printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
1749
1750     // Map ports with UPnP
1751     if (fHaveUPnP)
1752         MapPort(fUseUPnP);
1753
1754     // Get addresses from IRC and advertise ours
1755     // if (!CreateThread(ThreadIRCSeed, NULL))
1756     //     printf("Error: CreateThread(ThreadIRCSeed) failed\n");
1757     // IRC disabled with ppcoin
1758     printf("IRC seeding/communication disabled\n");
1759
1760     // Send and receive from sockets, accept connections
1761     if (!CreateThread(ThreadSocketHandler, NULL))
1762         printf("Error: CreateThread(ThreadSocketHandler) failed\n");
1763
1764     // Initiate outbound connections
1765     if (!CreateThread(ThreadOpenConnections, NULL))
1766         printf("Error: CreateThread(ThreadOpenConnections) failed\n");
1767
1768     // Process messages
1769     if (!CreateThread(ThreadMessageHandler, NULL))
1770         printf("Error: CreateThread(ThreadMessageHandler) failed\n");
1771
1772     // Generate coins in the background
1773     GenerateBitcoins(fGenerateBitcoins, pwalletMain);
1774 }
1775
1776 bool StopNode()
1777 {
1778     printf("StopNode()\n");
1779     fShutdown = true;
1780     nTransactionsUpdated++;
1781     int64 nStart = GetTime();
1782     while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0
1783 #ifdef USE_UPNP
1784         || vnThreadsRunning[5] > 0
1785 #endif
1786     )
1787     {
1788         if (GetTime() - nStart > 20)
1789             break;
1790         Sleep(20);
1791     }
1792     if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n");
1793     if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");
1794     if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");
1795     if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");
1796     if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");
1797     if (fHaveUPnP && vnThreadsRunning[5] > 0) printf("ThreadMapPort still running\n");
1798     if (vnThreadsRunning[6] > 0) printf("ThreadDNSAddressSeed still running\n");
1799     while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)
1800         Sleep(20);
1801     Sleep(50);
1802
1803     return true;
1804 }
1805
1806 class CNetCleanup
1807 {
1808 public:
1809     CNetCleanup()
1810     {
1811     }
1812     ~CNetCleanup()
1813     {
1814         // Close sockets
1815         BOOST_FOREACH(CNode* pnode, vNodes)
1816             if (pnode->hSocket != INVALID_SOCKET)
1817                 closesocket(pnode->hSocket);
1818         if (hListenSocket != INVALID_SOCKET)
1819             if (closesocket(hListenSocket) == SOCKET_ERROR)
1820                 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1821
1822 #ifdef WIN32
1823         // Shutdown Windows Sockets
1824         WSACleanup();
1825 #endif
1826     }
1827 }
1828 instance_of_cnetcleanup;