Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.3.10 · 2010-08-15

net.cpp

1,466 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"67static const int MAX_OUTBOUND_CONNECTIONS = 8;89void ThreadMessageHandler2(void* parg);10void ThreadSocketHandler2(void* parg);11void ThreadOpenConnections2(void* parg);12bool OpenNetworkConnection(const CAddress& addrConnect);131415161718//19// Global state variables20//21bool fClient = false;22uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);23CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);24CNode* pnodeLocalHost = NULL;25uint64 nLocalHostNonce = 0;26array<int, 10> vnThreadsRunning;27SOCKET hListenSocket = INVALID_SOCKET;28int64 nThreadSocketHandlerHeartbeat = INT64_MAX;2930vector<CNode*> vNodes;31CCriticalSection cs_vNodes;32map<vector<unsigned char>, CAddress> mapAddresses;33CCriticalSection cs_mapAddresses;34map<CInv, CDataStream> mapRelay;35deque<pair<int64, CInv> > vRelayExpiration;36CCriticalSection cs_mapRelay;37map<CInv, int64> mapAlreadyAskedFor;3839// Settings40int fUseProxy = false;41CAddress addrProxy("127.0.0.1:9050");424344454647void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)48{49    // Filter out duplicate requests50    if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)51        return;52    pindexLastGetBlocksBegin = pindexBegin;53    hashLastGetBlocksEnd = hashEnd;5455    PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);56}575859606162bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet)63{64    hSocketRet = INVALID_SOCKET;6566    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);67    if (hSocket == INVALID_SOCKET)68        return false;69#ifdef BSD70    int set = 1;71    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));72#endif7374    bool fRoutable = !(addrConnect.GetByte(3) == 10 || (addrConnect.GetByte(3) == 192 && addrConnect.GetByte(2) == 168));75    bool fProxy = (fUseProxy && fRoutable);76    struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());7778    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)79    {80        closesocket(hSocket);81        return false;82    }8384    if (fProxy)85    {86        printf("proxy connecting %s\n", addrConnect.ToStringLog().c_str());87        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";88        memcpy(pszSocks4IP + 2, &addrConnect.port, 2);89        memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);90        char* pszSocks4 = pszSocks4IP;91        int nSize = sizeof(pszSocks4IP);9293        int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);94        if (ret != nSize)95        {96            closesocket(hSocket);97            return error("Error sending to proxy");98        }99        char pchRet[8];100        if (recv(hSocket, pchRet, 8, 0) != 8)101        {102            closesocket(hSocket);103            return error("Error reading proxy response");104        }105        if (pchRet[1] != 0x5a)106        {107            closesocket(hSocket);108            if (pchRet[1] != 0x5b)109                printf("ERROR: Proxy returned error %d\n", pchRet[1]);110            return false;111        }112        printf("proxy connected %s\n", addrConnect.ToStringLog().c_str());113    }114115    hSocketRet = hSocket;116    return true;117}118119120121bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)122{123    SOCKET hSocket;124    if (!ConnectSocket(addrConnect, hSocket))125        return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());126127    send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);128129    string strLine;130    while (RecvLine(hSocket, strLine))131    {132        if (strLine.empty())133        {134            loop135            {136                if (!RecvLine(hSocket, strLine))137                {138                    closesocket(hSocket);139                    return false;140                }141                if (strLine.find(pszKeyword) != -1)142                {143                    strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));144                    break;145                }146            }147            closesocket(hSocket);148            if (strLine.find("<"))149                strLine = strLine.substr(0, strLine.find("<"));150            strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));151            while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))152                strLine.resize(strLine.size()-1);153            CAddress addr(strLine.c_str());154            printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());155            if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())156                return false;157            ipRet = addr.ip;158            return true;159        }160    }161    closesocket(hSocket);162    return error("GetMyExternalIP() : connection closed");163}164165166bool GetMyExternalIP(unsigned int& ipRet)167{168    CAddress addrConnect;169    const char* pszGet;170    const char* pszKeyword;171172    if (fUseProxy)173        return false;174175    for (int nLookup = 0; nLookup <= 1; nLookup++)176    for (int nHost = 1; nHost <= 2; nHost++)177    {178        if (nHost == 1)179        {180            addrConnect = CAddress("70.86.96.218:80"); // www.ipaddressworld.com181182            if (nLookup == 1)183            {184                struct hostent* phostent = gethostbyname("www.ipaddressworld.com");185                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])186                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));187            }188189            pszGet = "GET /ip.php HTTP/1.1\r\n"190                     "Host: www.ipaddressworld.com\r\n"191                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"192                     "Connection: close\r\n"193                     "\r\n";194195            pszKeyword = "IP:";196        }197        else if (nHost == 2)198        {199            addrConnect = CAddress("208.78.68.70:80"); // checkip.dyndns.org200201            if (nLookup == 1)202            {203                struct hostent* phostent = gethostbyname("checkip.dyndns.org");204                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])205                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));206            }207208            pszGet = "GET / HTTP/1.1\r\n"209                     "Host: checkip.dyndns.org\r\n"210                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"211                     "Connection: close\r\n"212                     "\r\n";213214            pszKeyword = "Address:";215        }216217        if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))218            return true;219    }220221    return false;222}223224225226227228bool AddAddress(CAddress addr)229{230    if (!addr.IsRoutable())231        return false;232    if (addr.ip == addrLocalHost.ip)233        return false;234    CRITICAL_BLOCK(cs_mapAddresses)235    {236        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());237        if (it == mapAddresses.end())238        {239            // New address240            printf("AddAddress(%s)\n", addr.ToStringLog().c_str());241            mapAddresses.insert(make_pair(addr.GetKey(), addr));242            CAddrDB().WriteAddress(addr);243            return true;244        }245        else246        {247            bool fUpdated = false;248            CAddress& addrFound = (*it).second;249            if ((addrFound.nServices | addr.nServices) != addrFound.nServices)250            {251                // Services have been added252                addrFound.nServices |= addr.nServices;253                fUpdated = true;254            }255            bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);256            int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);257            if (addrFound.nTime < addr.nTime - nUpdateInterval)258            {259                // Periodically update most recently seen time260                addrFound.nTime = addr.nTime;261                fUpdated = true;262            }263            if (fUpdated)264                CAddrDB().WriteAddress(addrFound);265        }266    }267    return false;268}269270void AddressCurrentlyConnected(const CAddress& addr)271{272    CRITICAL_BLOCK(cs_mapAddresses)273    {274        // Only if it's been published already275        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());276        if (it != mapAddresses.end())277        {278            CAddress& addrFound = (*it).second;279            int64 nUpdateInterval = 20 * 60;280            if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)281            {282                // Periodically update most recently seen time283                addrFound.nTime = GetAdjustedTime();284                CAddrDB addrdb;285                addrdb.WriteAddress(addrFound);286            }287        }288    }289}290291292293294295void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)296{297    // If the dialog might get closed before the reply comes back,298    // call this in the destructor so it doesn't get called after it's deleted.299    CRITICAL_BLOCK(cs_vNodes)300    {301        foreach(CNode* pnode, vNodes)302        {303            CRITICAL_BLOCK(pnode->cs_mapRequests)304            {305                for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)306                {307                    CRequestTracker& tracker = (*mi).second;308                    if (tracker.fn == fn && tracker.param1 == param1)309                        pnode->mapRequests.erase(mi++);310                    else311                        mi++;312                }313            }314        }315    }316}317318319320321322323324//325// Subscription methods for the broadcast and subscription system.326// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.327//328// The subscription system uses a meet-in-the-middle strategy.329// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers330// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.331//332333bool AnySubscribed(unsigned int nChannel)334{335    if (pnodeLocalHost->IsSubscribed(nChannel))336        return true;337    CRITICAL_BLOCK(cs_vNodes)338        foreach(CNode* pnode, vNodes)339            if (pnode->IsSubscribed(nChannel))340                return true;341    return false;342}343344bool CNode::IsSubscribed(unsigned int nChannel)345{346    if (nChannel >= vfSubscribe.size())347        return false;348    return vfSubscribe[nChannel];349}350351void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)352{353    if (nChannel >= vfSubscribe.size())354        return;355356    if (!AnySubscribed(nChannel))357    {358        // Relay subscribe359        CRITICAL_BLOCK(cs_vNodes)360            foreach(CNode* pnode, vNodes)361                if (pnode != this)362                    pnode->PushMessage("subscribe", nChannel, nHops);363    }364365    vfSubscribe[nChannel] = true;366}367368void CNode::CancelSubscribe(unsigned int nChannel)369{370    if (nChannel >= vfSubscribe.size())371        return;372373    // Prevent from relaying cancel if wasn't subscribed374    if (!vfSubscribe[nChannel])375        return;376    vfSubscribe[nChannel] = false;377378    if (!AnySubscribed(nChannel))379    {380        // Relay subscription cancel381        CRITICAL_BLOCK(cs_vNodes)382            foreach(CNode* pnode, vNodes)383                if (pnode != this)384                    pnode->PushMessage("sub-cancel", nChannel);385    }386}387388389390391392393394395396CNode* FindNode(unsigned int ip)397{398    CRITICAL_BLOCK(cs_vNodes)399    {400        foreach(CNode* pnode, vNodes)401            if (pnode->addr.ip == ip)402                return (pnode);403    }404    return NULL;405}406407CNode* FindNode(CAddress addr)408{409    CRITICAL_BLOCK(cs_vNodes)410    {411        foreach(CNode* pnode, vNodes)412            if (pnode->addr == addr)413                return (pnode);414    }415    return NULL;416}417418CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)419{420    if (addrConnect.ip == addrLocalHost.ip)421        return NULL;422423    // Look for an existing connection424    CNode* pnode = FindNode(addrConnect.ip);425    if (pnode)426    {427        if (nTimeout != 0)428            pnode->AddRef(nTimeout);429        else430            pnode->AddRef();431        return pnode;432    }433434    /// debug print435    printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",436        addrConnect.ToStringLog().c_str(),437        (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,438        (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);439440    CRITICAL_BLOCK(cs_mapAddresses)441        mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();442443    // Connect444    SOCKET hSocket;445    if (ConnectSocket(addrConnect, hSocket))446    {447        /// debug print448        printf("connected %s\n", addrConnect.ToStringLog().c_str());449450        // Set to nonblocking451#ifdef __WXMSW__452        u_long nOne = 1;453        if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)454            printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());455#else456        if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)457            printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);458#endif459460        // Add node461        CNode* pnode = new CNode(hSocket, addrConnect, false);462        if (nTimeout != 0)463            pnode->AddRef(nTimeout);464        else465            pnode->AddRef();466        CRITICAL_BLOCK(cs_vNodes)467            vNodes.push_back(pnode);468469        pnode->nTimeConnected = GetTime();470        return pnode;471    }472    else473    {474        return NULL;475    }476}477478void CNode::CloseSocketDisconnect()479{480    fDisconnect = true;481    if (hSocket != INVALID_SOCKET)482    {483        if (fDebug)484            printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());485        printf("disconnecting node %s\n", addr.ToStringLog().c_str());486        closesocket(hSocket);487        hSocket = INVALID_SOCKET;488    }489}490491void CNode::Cleanup()492{493    // All of a nodes broadcasts and subscriptions are automatically torn down494    // when it goes down, so a node has to stay up to keep its broadcast going.495496    // Cancel subscriptions497    for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)498        if (vfSubscribe[nChannel])499            CancelSubscribe(nChannel);500}501502503504505506507508509510511512513514void ThreadSocketHandler(void* parg)515{516    IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));517    try518    {519        vnThreadsRunning[0]++;520        ThreadSocketHandler2(parg);521        vnThreadsRunning[0]--;522    }523    catch (std::exception& e) {524        vnThreadsRunning[0]--;525        PrintException(&e, "ThreadSocketHandler()");526    } catch (...) {527        vnThreadsRunning[0]--;528        throw; // support pthread_cancel()529    }530    printf("ThreadSocketHandler exiting\n");531}532533void ThreadSocketHandler2(void* parg)534{535    printf("ThreadSocketHandler started\n");536    list<CNode*> vNodesDisconnected;537    int nPrevNodeCount = 0;538539    loop540    {541        //542        // Disconnect nodes543        //544        CRITICAL_BLOCK(cs_vNodes)545        {546            // Disconnect unused nodes547            vector<CNode*> vNodesCopy = vNodes;548            foreach(CNode* pnode, vNodesCopy)549            {550                if (pnode->fDisconnect ||551                    (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))552                {553                    // remove from vNodes554                    vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());555556                    // close socket and cleanup557                    pnode->CloseSocketDisconnect();558                    pnode->Cleanup();559560                    // hold in disconnected pool until all refs are released561                    pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);562                    if (pnode->fNetworkNode || pnode->fInbound)563                        pnode->Release();564                    vNodesDisconnected.push_back(pnode);565                }566            }567568            // Delete disconnected nodes569            list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;570            foreach(CNode* pnode, vNodesDisconnectedCopy)571            {572                // wait until threads are done using it573                if (pnode->GetRefCount() <= 0)574                {575                    bool fDelete = false;576                    TRY_CRITICAL_BLOCK(pnode->cs_vSend)577                     TRY_CRITICAL_BLOCK(pnode->cs_vRecv)578                      TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)579                       TRY_CRITICAL_BLOCK(pnode->cs_inventory)580                        fDelete = true;581                    if (fDelete)582                    {583                        vNodesDisconnected.remove(pnode);584                        delete pnode;585                    }586                }587            }588        }589        if (vNodes.size() != nPrevNodeCount)590        {591            nPrevNodeCount = vNodes.size();592            MainFrameRepaint();593        }594595596        //597        // Find which sockets have data to receive598        //599        struct timeval timeout;600        timeout.tv_sec  = 0;601        timeout.tv_usec = 50000; // frequency to poll pnode->vSend602603        fd_set fdsetRecv;604        fd_set fdsetSend;605        fd_set fdsetError;606        FD_ZERO(&fdsetRecv);607        FD_ZERO(&fdsetSend);608        FD_ZERO(&fdsetError);609        SOCKET hSocketMax = 0;610        FD_SET(hListenSocket, &fdsetRecv);611        hSocketMax = max(hSocketMax, hListenSocket);612        CRITICAL_BLOCK(cs_vNodes)613        {614            foreach(CNode* pnode, vNodes)615            {616                if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)617                    continue;618                FD_SET(pnode->hSocket, &fdsetRecv);619                FD_SET(pnode->hSocket, &fdsetError);620                hSocketMax = max(hSocketMax, pnode->hSocket);621                TRY_CRITICAL_BLOCK(pnode->cs_vSend)622                    if (!pnode->vSend.empty())623                        FD_SET(pnode->hSocket, &fdsetSend);624            }625        }626627        vnThreadsRunning[0]--;628        int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);629        vnThreadsRunning[0]++;630        if (fShutdown)631            return;632        if (nSelect == SOCKET_ERROR)633        {634            int nErr = WSAGetLastError();635            printf("socket select error %d\n", nErr);636            for (int i = 0; i <= hSocketMax; i++)637                FD_SET(i, &fdsetRecv);638            FD_ZERO(&fdsetSend);639            FD_ZERO(&fdsetError);640            Sleep(timeout.tv_usec/1000);641        }642643644        //645        // Accept new connections646        //647        if (FD_ISSET(hListenSocket, &fdsetRecv))648        {649            struct sockaddr_in sockaddr;650            socklen_t len = sizeof(sockaddr);651            SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);652            CAddress addr(sockaddr);653            if (hSocket == INVALID_SOCKET)654            {655                if (WSAGetLastError() != WSAEWOULDBLOCK)656                    printf("socket error accept failed: %d\n", WSAGetLastError());657            }658            else if (mapArgs.count("-maxconnections") && (int)vNodes.size() >= atoi(mapArgs["-maxconnections"]) - MAX_OUTBOUND_CONNECTIONS)659            {660                closesocket(hSocket);661            }662            else663            {664                printf("accepted connection %s\n", addr.ToStringLog().c_str());665                CNode* pnode = new CNode(hSocket, addr, true);666                pnode->AddRef();667                CRITICAL_BLOCK(cs_vNodes)668                    vNodes.push_back(pnode);669            }670        }671672673        //674        // Service each socket675        //676        vector<CNode*> vNodesCopy;677        CRITICAL_BLOCK(cs_vNodes)678        {679            vNodesCopy = vNodes;680            foreach(CNode* pnode, vNodesCopy)681                pnode->AddRef();682        }683        foreach(CNode* pnode, vNodesCopy)684        {685            if (fShutdown)686                return;687688            //689            // Receive690            //691            if (pnode->hSocket == INVALID_SOCKET)692                continue;693            if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))694            {695                TRY_CRITICAL_BLOCK(pnode->cs_vRecv)696                {697                    CDataStream& vRecv = pnode->vRecv;698                    unsigned int nPos = vRecv.size();699700                    // typical socket buffer is 8K-64K701                    char pchBuf[0x10000];702                    int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);703                    if (nBytes > 0)704                    {705                        vRecv.resize(nPos + nBytes);706                        memcpy(&vRecv[nPos], pchBuf, nBytes);707                        pnode->nLastRecv = GetTime();708                    }709                    else if (nBytes == 0)710                    {711                        // socket closed gracefully712                        if (!pnode->fDisconnect)713                            printf("socket closed\n");714                        pnode->CloseSocketDisconnect();715                    }716                    else if (nBytes < 0)717                    {718                        // error719                        int nErr = WSAGetLastError();720                        if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)721                        {722                            if (!pnode->fDisconnect)723                                printf("socket recv error %d\n", nErr);724                            pnode->CloseSocketDisconnect();725                        }726                    }727                }728            }729730            //731            // Send732            //733            if (pnode->hSocket == INVALID_SOCKET)734                continue;735            if (FD_ISSET(pnode->hSocket, &fdsetSend))736            {737                TRY_CRITICAL_BLOCK(pnode->cs_vSend)738                {739                    CDataStream& vSend = pnode->vSend;740                    if (!vSend.empty())741                    {742                        int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);743                        if (nBytes > 0)744                        {745                            vSend.erase(vSend.begin(), vSend.begin() + nBytes);746                            pnode->nLastSend = GetTime();747                        }748                        else if (nBytes < 0)749                        {750                            // error751                            int nErr = WSAGetLastError();752                            if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)753                            {754                                printf("socket send error %d\n", nErr);755                                pnode->CloseSocketDisconnect();756                            }757                        }758                    }759                }760            }761762            //763            // Inactivity checking764            //765            if (pnode->vSend.empty())766                pnode->nLastSendEmpty = GetTime();767            if (GetTime() - pnode->nTimeConnected > 60)768            {769                if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)770                {771                    printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);772                    pnode->fDisconnect = true;773                }774                else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)775                {776                    printf("socket not sending\n");777                    pnode->fDisconnect = true;778                }779                else if (GetTime() - pnode->nLastRecv > 90*60)780                {781                    printf("socket inactivity timeout\n");782                    pnode->fDisconnect = true;783                }784            }785        }786        CRITICAL_BLOCK(cs_vNodes)787        {788            foreach(CNode* pnode, vNodesCopy)789                pnode->Release();790        }791792        nThreadSocketHandlerHeartbeat = GetTime();793        Sleep(10);794    }795}796797798799800801802803804805806807808809unsigned int pnSeed[] =810{811    // 2010/06812    0x35218252, 0x9c9c9618, 0xda6bacad, 0xb9aca862, 0x97c235c6,813    0x146f9562, 0xb67b9e4b, 0x87cf4bc0, 0xb83945d0, 0x984333ad,814    0xbbeec555, 0x6f0eb440, 0xe0005318, 0x7797e460, 0xddc60fcc,815    0xb3bbd24a, 0x1ac85746, 0x641846a6, 0x85ee1155, 0xbb2e7a4c,816    0x9cb8514b, 0xfc342648, 0x62958fae, 0xd0a8c87a, 0xa800795b,817    0xda8c814e, 0x256a0c80, 0x3f23ec63, 0xd565df43, 0x997d9044,818    0xaa121448, 0xbed8688e, 0x59d09a5e, 0xb2931243, 0x3730ba18,819    0xdd3462d0, 0x4e4d1448, 0x171df645, 0x84ee1155,820    0x248ac445, 0x0e634444, 0x0ded1b63, 0x30c01e60,821    0xa2b9a094, 0x29e4fd43, 0x9ce61b4c, 0xdae09744,822823    // 2010/08824    0x5ae6bf43, 0x460be257, 0x7245c0cf, 0x4e0f028d, 0x26501760, 0x38643255, 0x67094f4f, 0x480449b8,825    0x16545143, 0x1f082e5a, 0xaa428018, 0xe411e793, 0x14c1f862, 0x2726105b, 0x9b33ea50, 0xeeef86ca,826    0xe3210d44, 0x0dca8b63, 0x3f9dfb18, 0x860340ad, 0xf33ba17a, 0x9018375c, 0x1de4e353, 0x0fa52dcb,827    0x89c4555b, 0x109cf37b, 0x28c55b40, 0x04c801ae, 0x275c1e80, 0x6f7f745d, 0x7a2a5653, 0xa28e26d8,828    0xa4e65db2, 0x99a06580, 0xf253ba44, 0x82cf6ab8, 0x859c2e8e, 0xf71a815d, 0xc18f1454, 0x71c8a943,829    0x90d24e18, 0x311789b2, 0x74aba645, 0xde0bbfc3, 0xad724fad, 0xbf1ae15e, 0xbaa6fb54, 0x06e4d145,830    0x51528645, 0x72120cd4, 0xd4cfd145, 0x0a7afed8, 0x9b9a5fad, 0x9e9ff45e, 0x10128355, 0xd44e8646,831    0x04a07b47, 0x5fc9d547, 0xe0491e45, 0xbac21b41, 0x7aa31bae, 0x10483c5f, 0x94a23055, 0x73d9dc47,832    0x1a99c247, 0x822fe847, 0x7e57ba48, 0xb19ea843, 0xa60621b2, 0x778cf163, 0x125c6556, 0xf94ba44f,833    0xa61a0948, 0x6c839e4b, 0x29af5348, 0x68d84845, 0x752b95c3, 0xcf0d4663, 0x08e11e56, 0x75109550,834    0x5f24b94c, 0x42426d4d, 0xfbbc0a4c, 0x70a9a246, 0xda7837cb, 0xae2a986d, 0xe283c358, 0x0c7ca954,835    0x8e9bde59, 0x61521760, 0x6884444c, 0xa194e548, 0x9b8809cc, 0x16e96a8f, 0x956ff859, 0xfad5e555,836    0x0ea70c80, 0x5b4ce26d, 0x7984444c, 0x1080d24a, 0x22a686cf, 0x6bf8c2ad, 0xb0f7485f, 0x06b66e56,837    0x668373bc, 0x75506279, 0x3868694e, 0x12a5954b, 0x3a8b62d1, 0xb74fcbad, 0xa7dc3360, 0xc070b359,838    0xa2b87242, 0xc45cab7c, 0x69882050, 0x14a5464b, 0x386acad5, 0x80b85db2, 0x1f78a062, 0xc608c55b,839    0x4257d543, 0x7636ad80, 0x4432d655, 0xb2114d4b, 0x32639bd9, 0xadd75db2, 0x9be5a362, 0x6831bc5e,840    0xf7f77046, 0x8f35ba81, 0x09bb4e59, 0xd0fb6b4e, 0xc5daa445, 0x9c611618, 0x355dcc62, 0xf2cf435e,841    0x31e72c46, 0xdd8a43ad, 0x171f9c5b, 0xb4c2e355, 0xbe8af945, 0x613d3942, 0xe6f9e863, 0x7a3d855f,842    0xa66adc47, 0x261089b2, 0x5a27105b, 0x6c28105b, 0xdd247946, 0xe6c3a445, 0x43a1ec63, 0x99b4dd5f,843    0xb6834347, 0x5e9649bc, 0xf9dd545d, 0x6ae4c15b, 0xa5318a47, 0x7984ec47, 0x93a73b63, 0x0c60195f,844    0xa5c85e4b, 0xa0a36dc2, 0x0739a95e, 0x3d44c15b, 0xfb940f4b, 0xd67c9148, 0x614f9876, 0x0a241c5f,845    0xad9da74c, 0x4459abc8, 0x12e71b5f, 0x1c534a5d, 0x8ff5fc50, 0x2ca8864b, 0xd894fd80, 0x82ab3160,846    0x390d804e, 0x2cf310cc, 0x680dad80, 0x691be15e, 0x5a8f4652, 0xaad0784d, 0x0d2431ad,847};848849850851void ThreadOpenConnections(void* parg)852{853    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));854    try855    {856        vnThreadsRunning[1]++;857        ThreadOpenConnections2(parg);858        vnThreadsRunning[1]--;859    }860    catch (std::exception& e) {861        vnThreadsRunning[1]--;862        PrintException(&e, "ThreadOpenConnections()");863    } catch (...) {864        vnThreadsRunning[1]--;865        PrintException(NULL, "ThreadOpenConnections()");866    }867    printf("ThreadOpenConnections exiting\n");868}869870void ThreadOpenConnections2(void* parg)871{872    printf("ThreadOpenConnections started\n");873874    // Connect to specific addresses875    if (mapArgs.count("-connect"))876    {877        for (int64 nLoop = 0;; nLoop++)878        {879            foreach(string strAddr, mapMultiArgs["-connect"])880            {881                CAddress addr(strAddr, NODE_NETWORK);882                if (addr.IsValid())883                    OpenNetworkConnection(addr);884                for (int i = 0; i < 10 && i < nLoop; i++)885                {886                    Sleep(500);887                    if (fShutdown)888                        return;889                }890            }891        }892    }893894    // Connect to manually added nodes first895    if (mapArgs.count("-addnode"))896    {897        foreach(string strAddr, mapMultiArgs["-addnode"])898        {899            CAddress addr(strAddr, NODE_NETWORK);900            if (addr.IsValid())901            {902                OpenNetworkConnection(addr);903                Sleep(500);904                if (fShutdown)905                    return;906            }907        }908    }909910    // Initiate network connections911    int64 nStart = GetTime();912    loop913    {914        // Limit outbound connections915        vnThreadsRunning[1]--;916        Sleep(500);917        loop918        {919            int nOutbound = 0;920            CRITICAL_BLOCK(cs_vNodes)921                foreach(CNode* pnode, vNodes)922                    if (!pnode->fInbound)923                        nOutbound++;924            int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;925            if (mapArgs.count("-maxconnections"))926                nMaxOutboundConnections = min(nMaxOutboundConnections, atoi(mapArgs["-maxconnections"]));927            if (nOutbound < nMaxOutboundConnections)928                break;929            Sleep(2000);930            if (fShutdown)931                return;932        }933        vnThreadsRunning[1]++;934        if (fShutdown)935            return;936937        CRITICAL_BLOCK(cs_mapAddresses)938        {939            // Add seed nodes if IRC isn't working940            static bool fSeedUsed;941            bool fTOR = (fUseProxy && addrProxy.port == htons(9050));942            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR))943            {944                for (int i = 0; i < ARRAYLEN(pnSeed); i++)945                {946                    // It'll only connect to one or two seed nodes because once it connects,947                    // it'll get a pile of addresses with newer timestamps.948                    CAddress addr;949                    addr.ip = pnSeed[i];950                    addr.nTime = 0;951                    AddAddress(addr);952                }953                fSeedUsed = true;954            }955956            if (fSeedUsed && mapAddresses.size() > ARRAYLEN(pnSeed) + 100)957            {958                // Disconnect seed nodes959                set<unsigned int> setSeed(pnSeed, pnSeed + ARRAYLEN(pnSeed));960                static int64 nSeedDisconnected;961                if (nSeedDisconnected == 0)962                {963                    nSeedDisconnected = GetTime();964                    CRITICAL_BLOCK(cs_vNodes)965                        foreach(CNode* pnode, vNodes)966                            if (setSeed.count(pnode->addr.ip))967                                pnode->fDisconnect = true;968                }969970                // Keep setting timestamps to 0 so they won't reconnect971                if (GetTime() - nSeedDisconnected < 60 * 60)972                {973                    foreach(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses)974                    {975                        if (setSeed.count(item.second.ip))976                        {977                            item.second.nTime = 0;978                            CAddrDB().WriteAddress(item.second);979                        }980                    }981                }982            }983        }984985986        //987        // Choose an address to connect to based on most recently seen988        //989        CAddress addrConnect;990        int64 nBest = INT64_MIN;991992        // Only connect to one address per a.b.?.? range.993        // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.994        set<unsigned int> setConnected;995        CRITICAL_BLOCK(cs_vNodes)996            foreach(CNode* pnode, vNodes)997                setConnected.insert(pnode->addr.ip & 0x0000ffff);998999        CRITICAL_BLOCK(cs_mapAddresses)1000        {1001            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)1002            {1003                const CAddress& addr = item.second;1004                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))1005                    continue;1006                int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime;1007                int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry;10081009                // Randomize the order in a deterministic way, putting the standard port first1010                int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);1011                if (addr.port != DEFAULT_PORT)1012                    nRandomizer += 2 * 60 * 60;10131014                // Last seen  Base retry frequency1015                //   <1 hour   10 min1016                //    1 hour    1 hour1017                //    4 hours   2 hours1018                //   24 hours   5 hours1019                //   48 hours   7 hours1020                //    7 days   13 hours1021                //   30 days   27 hours1022                //   90 days   46 hours1023                //  365 days   93 hours1024                int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);10251026                // Fast reconnect for one hour after last seen1027                if (nSinceLastSeen < 60 * 60)1028                    nDelay = 10 * 60;10291030                // Limit retry frequency1031                if (nSinceLastTry < nDelay)1032                    continue;10331034                // If we have IRC, we'll be notified when they first come online,1035                // and again every 24 hours by the refresh broadcast.1036                if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)1037                    continue;10381039                // Only try the old stuff if we don't have enough connections1040                if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60)1041                    continue;10421043                // If multiple addresses are ready, prioritize by time since1044                // last seen and time since last tried.1045                int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;1046                if (nScore > nBest)1047                {1048                    nBest = nScore;1049                    addrConnect = addr;1050                }1051            }1052        }10531054        if (addrConnect.IsValid())1055            OpenNetworkConnection(addrConnect);1056    }1057}10581059bool OpenNetworkConnection(const CAddress& addrConnect)1060{1061    //1062    // Initiate outbound network connection1063    //1064    if (fShutdown)1065        return false;1066    if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))1067        return false;10681069    vnThreadsRunning[1]--;1070    CNode* pnode = ConnectNode(addrConnect);1071    vnThreadsRunning[1]++;1072    if (fShutdown)1073        return false;1074    if (!pnode)1075        return false;1076    pnode->fNetworkNode = true;10771078    if (addrLocalHost.IsRoutable() && !fUseProxy)1079    {1080        // Advertise our address1081        vector<CAddress> vAddr;1082        vAddr.push_back(addrLocalHost);1083        pnode->PushMessage("addr", vAddr);1084    }10851086    // Get as many addresses as we can1087    pnode->PushMessage("getaddr");1088    pnode->fGetAddr = true; // don't relay the results of the getaddr10891090    ////// should the one on the receiving end do this too?1091    // Subscribe our local subscription list1092    const unsigned int nHops = 0;1093    for (unsigned int nChannel = 0; nChannel < pnodeLocalHost->vfSubscribe.size(); nChannel++)1094        if (pnodeLocalHost->vfSubscribe[nChannel])1095            pnode->PushMessage("subscribe", nChannel, nHops);10961097    return true;1098}109911001101110211031104110511061107void ThreadMessageHandler(void* parg)1108{1109    IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));1110    try1111    {1112        vnThreadsRunning[2]++;1113        ThreadMessageHandler2(parg);1114        vnThreadsRunning[2]--;1115    }1116    catch (std::exception& e) {1117        vnThreadsRunning[2]--;1118        PrintException(&e, "ThreadMessageHandler()");1119    } catch (...) {1120        vnThreadsRunning[2]--;1121        PrintException(NULL, "ThreadMessageHandler()");1122    }1123    printf("ThreadMessageHandler exiting\n");1124}11251126void ThreadMessageHandler2(void* parg)1127{1128    printf("ThreadMessageHandler started\n");1129    SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);1130    while (!fShutdown)1131    {1132        vector<CNode*> vNodesCopy;1133        CRITICAL_BLOCK(cs_vNodes)1134        {1135            vNodesCopy = vNodes;1136            foreach(CNode* pnode, vNodesCopy)1137                pnode->AddRef();1138        }11391140        // Poll the connected nodes for messages1141        CNode* pnodeTrickle = NULL;1142        if (!vNodesCopy.empty())1143            pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];1144        foreach(CNode* pnode, vNodesCopy)1145        {1146            // Receive messages1147            TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1148                ProcessMessages(pnode);1149            if (fShutdown)1150                return;11511152            // Send messages1153            TRY_CRITICAL_BLOCK(pnode->cs_vSend)1154                SendMessages(pnode, pnode == pnodeTrickle);1155            if (fShutdown)1156                return;1157        }11581159        CRITICAL_BLOCK(cs_vNodes)1160        {1161            foreach(CNode* pnode, vNodesCopy)1162                pnode->Release();1163        }11641165        // Wait and allow messages to bunch up1166        vnThreadsRunning[2]--;1167        Sleep(100);1168        vnThreadsRunning[2]++;1169        if (fShutdown)1170            return;1171    }1172}1173117411751176117711781179118011811182bool BindListenPort(string& strError)1183{1184    strError = "";1185    int nOne = 1;11861187#ifdef __WXMSW__1188    // Initialize Windows Sockets1189    WSADATA wsadata;1190    int ret = WSAStartup(MAKEWORD(2,2), &wsadata);1191    if (ret != NO_ERROR)1192    {1193        strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);1194        printf("%s\n", strError.c_str());1195        return false;1196    }1197#endif11981199    // Create socket for listening for incoming connections1200    hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);1201    if (hListenSocket == INVALID_SOCKET)1202    {1203        strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());1204        printf("%s\n", strError.c_str());1205        return false;1206    }12071208#ifdef BSD1209    // Different way of disabling SIGPIPE on BSD1210    setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));1211#endif12121213#ifndef __WXMSW__1214    // Allow binding if the port is still in TIME_WAIT state after1215    // the program was closed and restarted.  Not an issue on windows.1216    setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));1217#endif12181219#ifdef __WXMSW__1220    // Set to nonblocking, incoming connections will also inherit this1221    if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)1222#else1223    if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)1224#endif1225    {1226        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());1227        printf("%s\n", strError.c_str());1228        return false;1229    }12301231    // The sockaddr_in structure specifies the address family,1232    // IP address, and port for the socket that is being bound1233    struct sockaddr_in sockaddr;1234    memset(&sockaddr, 0, sizeof(sockaddr));1235    sockaddr.sin_family = AF_INET;1236    sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer1237    sockaddr.sin_port = DEFAULT_PORT;1238    if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)1239    {1240        int nErr = WSAGetLastError();1241        if (nErr == WSAEADDRINUSE)1242            strError = strprintf("Unable to bind to port %d on this computer.  Bitcoin is probably already running.", ntohs(sockaddr.sin_port));1243        else1244            strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);1245        printf("%s\n", strError.c_str());1246        return false;1247    }1248    printf("Bound to port %d\n", ntohs(sockaddr.sin_port));12491250    // Listen for incoming connections1251    if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)1252    {1253        strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());1254        printf("%s\n", strError.c_str());1255        return false;1256    }12571258    return true;1259}12601261void StartNode(void* parg)1262{1263    if (pnodeLocalHost == NULL)1264        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));12651266#ifdef __WXMSW__1267    // Get local host ip1268    char pszHostName[1000] = "";1269    if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)1270    {1271        struct hostent* phostent = gethostbyname(pszHostName);1272        if (phostent)1273        {1274            // Take the first IP that isn't loopback 127.x.x.x1275            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1276                printf("host ip %d: %s\n", i, CAddress(*(unsigned int*)phostent->h_addr_list[i]).ToStringIP().c_str());1277            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1278            {1279                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], DEFAULT_PORT, nLocalServices);1280                if (addr.IsValid() && addr.GetByte(3) != 127)1281                {1282                    addrLocalHost = addr;1283                    break;1284                }1285            }1286        }1287    }1288#else1289    // Get local host ip1290    struct ifaddrs* myaddrs;1291    if (getifaddrs(&myaddrs) == 0)1292    {1293        for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)1294        {1295            if (ifa->ifa_addr == NULL) continue;1296            if ((ifa->ifa_flags & IFF_UP) == 0) continue;1297            if (strcmp(ifa->ifa_name, "lo") == 0) continue;1298            if (strcmp(ifa->ifa_name, "lo0") == 0) continue;1299            char pszIP[100];1300            if (ifa->ifa_addr->sa_family == AF_INET)1301            {1302                struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);1303                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL)1304                    printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);13051306                // Take the first IP that isn't loopback 127.x.x.x1307                CAddress addr(*(unsigned int*)&s4->sin_addr, DEFAULT_PORT, nLocalServices);1308                if (addr.IsValid() && addr.GetByte(3) != 127)1309                {1310                    addrLocalHost = addr;1311                    break;1312                }1313            }1314            else if (ifa->ifa_addr->sa_family == AF_INET6)1315            {1316                struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);1317                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL)1318                    printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP);1319            }1320        }1321        freeifaddrs(myaddrs);1322    }1323#endif1324    printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());13251326    // Get our external IP address for incoming connections1327    if (fUseProxy)1328    {1329        // Proxies can't take incoming connections1330        addrLocalHost.ip = CAddress("0.0.0.0").ip;1331        printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1332    }1333    else1334    {1335        if (addrIncoming.IsValid())1336            addrLocalHost.ip = addrIncoming.ip;13371338        if (GetMyExternalIP(addrLocalHost.ip))1339        {1340            addrIncoming = addrLocalHost;1341            CWalletDB().WriteSetting("addrIncoming", addrIncoming);1342            printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1343        }1344    }13451346    //1347    // Start threads1348    //13491350    // Get addresses from IRC and advertise ours1351    if (!CreateThread(ThreadIRCSeed, NULL))1352        printf("Error: CreateThread(ThreadIRCSeed) failed\n");13531354    // Send and receive from sockets, accept connections1355    pthread_t hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);13561357    // Initiate outbound connections1358    if (!CreateThread(ThreadOpenConnections, NULL))1359        printf("Error: CreateThread(ThreadOpenConnections) failed\n");13601361    // Process messages1362    if (!CreateThread(ThreadMessageHandler, NULL))1363        printf("Error: CreateThread(ThreadMessageHandler) failed\n");13641365    // Generate coins in the background1366    GenerateBitcoins(fGenerateBitcoins);13671368    //1369    // Thread monitoring1370    // Not really needed anymore, the cause of the hanging was fixed1371    //1372    loop1373    {1374        Sleep(1000);1375        if (fShutdown)1376            return;1377        if (GetTime() - nThreadSocketHandlerHeartbeat > 15 * 60)1378        {1379            // First see if closing sockets will free it1380            printf("*** ThreadSocketHandler is stopped ***\n");1381            CRITICAL_BLOCK(cs_vNodes)1382            {1383                foreach(CNode* pnode, vNodes)1384                {1385                    bool fGot = false;1386                    TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1387                        TRY_CRITICAL_BLOCK(pnode->cs_vSend)1388                            fGot = true;1389                    if (!fGot)1390                    {1391                        printf("*** closing socket\n");1392                        pnode->CloseSocketDisconnect();1393                    }1394                }1395            }1396            Sleep(10000);1397            if (fShutdown)1398                return;1399            if (GetTime() - nThreadSocketHandlerHeartbeat < 60)1400                continue;14011402            // Hopefully it never comes to this.1403            // We know it'll always be hung in the recv or send call.1404            // cs_vRecv or cs_vSend may be left permanently unreleased,1405            // but we always only use TRY_CRITICAL_SECTION on them.1406            printf("*** Restarting ThreadSocketHandler ***\n");1407            TerminateThread(hThreadSocketHandler, 0);1408            #ifdef __WXMSW__1409            CloseHandle(hThreadSocketHandler);1410            #endif1411            vnThreadsRunning[0] = 0;14121413            // Restart1414            hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);1415            nThreadSocketHandlerHeartbeat = GetTime();1416        }1417    }1418}14191420bool StopNode()1421{1422    printf("StopNode()\n");1423    fShutdown = true;1424    nTransactionsUpdated++;1425    int64 nStart = GetTime();1426    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0)1427    {1428        if (GetTime() - nStart > 20)1429            break;1430        Sleep(20);1431    }1432    if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n");1433    if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");1434    if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");1435    if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");1436    if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");1437    while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)1438        Sleep(20);1439    Sleep(50);14401441    return true;1442}14431444class CNetCleanup1445{1446public:1447    CNetCleanup()1448    {1449    }1450    ~CNetCleanup()1451    {1452        // Close sockets1453        foreach(CNode* pnode, vNodes)1454            if (pnode->hSocket != INVALID_SOCKET)1455                closesocket(pnode->hSocket);1456        if (hListenSocket != INVALID_SOCKET)1457            if (closesocket(hListenSocket) == SOCKET_ERROR)1458                printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());14591460#ifdef __WXMSW__1461        // Shutdown Windows Sockets1462        WSACleanup();1463#endif1464    }1465}1466instance_of_cnetcleanup;

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00