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.2.0 · 2009-12-16

net.cpp

1,371 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009 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"67void ThreadMessageHandler2(void* parg);8void ThreadSocketHandler2(void* parg);9void ThreadOpenConnections2(void* parg);10bool OpenNetworkConnection(const CAddress& addrConnect);111213141516//17// Global state variables18//19bool fClient = false;20uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);21CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);22CNode* pnodeLocalHost = NULL;23uint64 nLocalHostNonce = 0;24array<int, 10> vnThreadsRunning;25SOCKET hListenSocket = INVALID_SOCKET;26int64 nThreadSocketHandlerHeartbeat = INT64_MAX;2728vector<CNode*> vNodes;29CCriticalSection cs_vNodes;30map<vector<unsigned char>, CAddress> mapAddresses;31CCriticalSection cs_mapAddresses;32map<CInv, CDataStream> mapRelay;33deque<pair<int64, CInv> > vRelayExpiration;34CCriticalSection cs_mapRelay;35map<CInv, int64> mapAlreadyAskedFor;3637// Settings38int fUseProxy = false;39CAddress addrProxy("127.0.0.1:9050");404142434445void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)46{47    // Filter out duplicate requests48    if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)49        return;50    pindexLastGetBlocksBegin = pindexBegin;51    hashLastGetBlocksEnd = hashEnd;5253    PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);54}555657585960bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet)61{62    hSocketRet = INVALID_SOCKET;6364    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);65    if (hSocket == INVALID_SOCKET)66        return false;67#if defined(__BSD__) || defined(__WXOSX__)68    int set = 1;69    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));70#endif7172    bool fRoutable = !(addrConnect.GetByte(3) == 10 || (addrConnect.GetByte(3) == 192 && addrConnect.GetByte(2) == 168));73    bool fProxy = (fUseProxy && fRoutable);74    struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());7576    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)77    {78        closesocket(hSocket);79        return false;80    }8182    if (fProxy)83    {84        printf("proxy connecting %s\n", addrConnect.ToStringLog().c_str());85        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";86        memcpy(pszSocks4IP + 2, &addrConnect.port, 2);87        memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);88        char* pszSocks4 = pszSocks4IP;89        int nSize = sizeof(pszSocks4IP);9091        int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);92        if (ret != nSize)93        {94            closesocket(hSocket);95            return error("Error sending to proxy");96        }97        char pchRet[8];98        if (recv(hSocket, pchRet, 8, 0) != 8)99        {100            closesocket(hSocket);101            return error("Error reading proxy response");102        }103        if (pchRet[1] != 0x5a)104        {105            closesocket(hSocket);106            if (pchRet[1] != 0x5b)107                printf("ERROR: Proxy returned error %d\n", pchRet[1]);108            return false;109        }110        printf("proxy connected %s\n", addrConnect.ToStringLog().c_str());111    }112113    hSocketRet = hSocket;114    return true;115}116117118119bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)120{121    SOCKET hSocket;122    if (!ConnectSocket(addrConnect, hSocket))123        return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());124125    send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);126127    string strLine;128    while (RecvLine(hSocket, strLine))129    {130        if (strLine.empty())131        {132            loop133            {134                if (!RecvLine(hSocket, strLine))135                {136                    closesocket(hSocket);137                    return false;138                }139                if (strLine.find(pszKeyword) != -1)140                {141                    strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));142                    break;143                }144            }145            closesocket(hSocket);146            if (strLine.find("<"))147                strLine = strLine.substr(0, strLine.find("<"));148            strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));149            while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))150                strLine.resize(strLine.size()-1);151            CAddress addr(strLine.c_str());152            printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());153            if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())154                return false;155            ipRet = addr.ip;156            return true;157        }158    }159    closesocket(hSocket);160    return error("GetMyExternalIP() : connection closed");161}162163164bool GetMyExternalIP(unsigned int& ipRet)165{166    CAddress addrConnect;167    const char* pszGet;168    const char* pszKeyword;169170    if (fUseProxy)171        return false;172173    for (int nLookup = 0; nLookup <= 1; nLookup++)174    for (int nHost = 1; nHost <= 2; nHost++)175    {176        if (nHost == 1)177        {178            addrConnect = CAddress("70.86.96.218:80"); // www.ipaddressworld.com179180            if (nLookup == 1)181            {182                struct hostent* phostent = gethostbyname("www.ipaddressworld.com");183                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])184                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));185            }186187            pszGet = "GET /ip.php HTTP/1.1\r\n"188                     "Host: www.ipaddressworld.com\r\n"189                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"190                     "Connection: close\r\n"191                     "\r\n";192193            pszKeyword = "IP:";194        }195        else if (nHost == 2)196        {197            addrConnect = CAddress("208.78.68.70:80"); // checkip.dyndns.org198199            if (nLookup == 1)200            {201                struct hostent* phostent = gethostbyname("checkip.dyndns.org");202                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])203                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));204            }205206            pszGet = "GET / HTTP/1.1\r\n"207                     "Host: checkip.dyndns.org\r\n"208                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"209                     "Connection: close\r\n"210                     "\r\n";211212            pszKeyword = "Address:";213        }214215        if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))216            return true;217    }218219    return false;220}221222223224225226bool AddAddress(CAddrDB& addrdb, CAddress addr, bool fCurrentlyOnline)227{228    if (!addr.IsRoutable())229        return false;230    if (addr.ip == addrLocalHost.ip)231        return false;232    if (fCurrentlyOnline)233        addr.nTime = GetAdjustedTime();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            addrdb.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            int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);256            if (addrFound.nTime < addr.nTime - nUpdateInterval)257            {258                // Periodically update most recently seen time259                addrFound.nTime = addr.nTime;260                fUpdated = true;261            }262            if (fUpdated)263                addrdb.WriteAddress(addrFound);264        }265    }266    return false;267}268269void AddressCurrentlyConnected(const CAddress& addr)270{271    CRITICAL_BLOCK(cs_mapAddresses)272    {273        // Only if it's been published already274        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());275        if (it != mapAddresses.end())276        {277            CAddress& addrFound = (*it).second;278            int64 nUpdateInterval = 20 * 60;279            if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)280            {281                // Periodically update most recently seen time282                addrFound.nTime = GetAdjustedTime();283                CAddrDB addrdb;284                addrdb.WriteAddress(addrFound);285            }286        }287    }288}289290291292293294void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)295{296    // If the dialog might get closed before the reply comes back,297    // call this in the destructor so it doesn't get called after it's deleted.298    CRITICAL_BLOCK(cs_vNodes)299    {300        foreach(CNode* pnode, vNodes)301        {302            CRITICAL_BLOCK(pnode->cs_mapRequests)303            {304                for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)305                {306                    CRequestTracker& tracker = (*mi).second;307                    if (tracker.fn == fn && tracker.param1 == param1)308                        pnode->mapRequests.erase(mi++);309                    else310                        mi++;311                }312            }313        }314    }315}316317318319320321322323//324// Subscription methods for the broadcast and subscription system.325// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.326//327// The subscription system uses a meet-in-the-middle strategy.328// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers329// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.330//331332bool AnySubscribed(unsigned int nChannel)333{334    if (pnodeLocalHost->IsSubscribed(nChannel))335        return true;336    CRITICAL_BLOCK(cs_vNodes)337        foreach(CNode* pnode, vNodes)338            if (pnode->IsSubscribed(nChannel))339                return true;340    return false;341}342343bool CNode::IsSubscribed(unsigned int nChannel)344{345    if (nChannel >= vfSubscribe.size())346        return false;347    return vfSubscribe[nChannel];348}349350void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)351{352    if (nChannel >= vfSubscribe.size())353        return;354355    if (!AnySubscribed(nChannel))356    {357        // Relay subscribe358        CRITICAL_BLOCK(cs_vNodes)359            foreach(CNode* pnode, vNodes)360                if (pnode != this)361                    pnode->PushMessage("subscribe", nChannel, nHops);362    }363364    vfSubscribe[nChannel] = true;365}366367void CNode::CancelSubscribe(unsigned int nChannel)368{369    if (nChannel >= vfSubscribe.size())370        return;371372    // Prevent from relaying cancel if wasn't subscribed373    if (!vfSubscribe[nChannel])374        return;375    vfSubscribe[nChannel] = false;376377    if (!AnySubscribed(nChannel))378    {379        // Relay subscription cancel380        CRITICAL_BLOCK(cs_vNodes)381            foreach(CNode* pnode, vNodes)382                if (pnode != this)383                    pnode->PushMessage("sub-cancel", nChannel);384385        // Clear memory, no longer subscribed386        if (nChannel == MSG_PRODUCT)387            CRITICAL_BLOCK(cs_mapProducts)388                mapProducts.clear();389    }390}391392393394395396397398399400CNode* FindNode(unsigned int ip)401{402    CRITICAL_BLOCK(cs_vNodes)403    {404        foreach(CNode* pnode, vNodes)405            if (pnode->addr.ip == ip)406                return (pnode);407    }408    return NULL;409}410411CNode* FindNode(CAddress addr)412{413    CRITICAL_BLOCK(cs_vNodes)414    {415        foreach(CNode* pnode, vNodes)416            if (pnode->addr == addr)417                return (pnode);418    }419    return NULL;420}421422CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)423{424    if (addrConnect.ip == addrLocalHost.ip)425        return NULL;426427    // Look for an existing connection428    CNode* pnode = FindNode(addrConnect.ip);429    if (pnode)430    {431        if (nTimeout != 0)432            pnode->AddRef(nTimeout);433        else434            pnode->AddRef();435        return pnode;436    }437438    /// debug print439    printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",440        addrConnect.ToStringLog().c_str(),441        (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,442        (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);443444    CRITICAL_BLOCK(cs_mapAddresses)445        mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();446447    // Connect448    SOCKET hSocket;449    if (ConnectSocket(addrConnect, hSocket))450    {451        /// debug print452        printf("connected %s\n", addrConnect.ToStringLog().c_str());453454        // Set to nonblocking455#ifdef __WXMSW__456        u_long nOne = 1;457        if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)458            printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());459#else460        if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)461            printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);462#endif463464        // Add node465        CNode* pnode = new CNode(hSocket, addrConnect, false);466        if (nTimeout != 0)467            pnode->AddRef(nTimeout);468        else469            pnode->AddRef();470        CRITICAL_BLOCK(cs_vNodes)471            vNodes.push_back(pnode);472473        pnode->nTimeConnected = GetTime();474        return pnode;475    }476    else477    {478        return NULL;479    }480}481482void CNode::CloseSocketDisconnect()483{484    fDisconnect = true;485    if (hSocket != INVALID_SOCKET)486    {487        if (fDebug)488            printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());489        printf("disconnecting node %s\n", addr.ToStringLog().c_str());490        closesocket(hSocket);491        hSocket = INVALID_SOCKET;492    }493}494495void CNode::Cleanup()496{497    // All of a nodes broadcasts and subscriptions are automatically torn down498    // when it goes down, so a node has to stay up to keep its broadcast going.499500    CRITICAL_BLOCK(cs_mapProducts)501        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end();)502            AdvertRemoveSource(this, MSG_PRODUCT, 0, (*(mi++)).second);503504    // Cancel subscriptions505    for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)506        if (vfSubscribe[nChannel])507            CancelSubscribe(nChannel);508}509510511512513514515516517518519520521522void ThreadSocketHandler(void* parg)523{524    IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));525526    try527    {528        vnThreadsRunning[0]++;529        ThreadSocketHandler2(parg);530        vnThreadsRunning[0]--;531    }532    catch (std::exception& e) {533        vnThreadsRunning[0]--;534        PrintException(&e, "ThreadSocketHandler()");535    } catch (...) {536        vnThreadsRunning[0]--;537        throw; // support pthread_cancel()538    }539540    printf("ThreadSocketHandler exiting\n");541}542543void ThreadSocketHandler2(void* parg)544{545    printf("ThreadSocketHandler started\n");546    list<CNode*> vNodesDisconnected;547    int nPrevNodeCount = 0;548549    loop550    {551        //552        // Disconnect nodes553        //554        CRITICAL_BLOCK(cs_vNodes)555        {556            // Disconnect unused nodes557            vector<CNode*> vNodesCopy = vNodes;558            foreach(CNode* pnode, vNodesCopy)559            {560                if (pnode->fDisconnect ||561                    (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))562                {563                    // remove from vNodes564                    vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());565566                    // close socket and cleanup567                    pnode->CloseSocketDisconnect();568                    pnode->Cleanup();569570                    // hold in disconnected pool until all refs are released571                    pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);572                    if (pnode->fNetworkNode || pnode->fInbound)573                        pnode->Release();574                    vNodesDisconnected.push_back(pnode);575                }576            }577578            // Delete disconnected nodes579            list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;580            foreach(CNode* pnode, vNodesDisconnectedCopy)581            {582                // wait until threads are done using it583                if (pnode->GetRefCount() <= 0)584                {585                    bool fDelete = false;586                    TRY_CRITICAL_BLOCK(pnode->cs_vSend)587                     TRY_CRITICAL_BLOCK(pnode->cs_vRecv)588                      TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)589                       TRY_CRITICAL_BLOCK(pnode->cs_inventory)590                        fDelete = true;591                    if (fDelete)592                    {593                        vNodesDisconnected.remove(pnode);594                        delete pnode;595                    }596                }597            }598        }599        if (vNodes.size() != nPrevNodeCount)600        {601            nPrevNodeCount = vNodes.size();602            MainFrameRepaint();603        }604605606        //607        // Find which sockets have data to receive608        //609        struct timeval timeout;610        timeout.tv_sec  = 0;611        timeout.tv_usec = 50000; // frequency to poll pnode->vSend612613        fd_set fdsetRecv;614        fd_set fdsetSend;615        fd_set fdsetError;616        FD_ZERO(&fdsetRecv);617        FD_ZERO(&fdsetSend);618        FD_ZERO(&fdsetError);619        SOCKET hSocketMax = 0;620        FD_SET(hListenSocket, &fdsetRecv);621        hSocketMax = max(hSocketMax, hListenSocket);622        CRITICAL_BLOCK(cs_vNodes)623        {624            foreach(CNode* pnode, vNodes)625            {626                if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)627                    continue;628                FD_SET(pnode->hSocket, &fdsetRecv);629                FD_SET(pnode->hSocket, &fdsetError);630                hSocketMax = max(hSocketMax, pnode->hSocket);631                TRY_CRITICAL_BLOCK(pnode->cs_vSend)632                    if (!pnode->vSend.empty())633                        FD_SET(pnode->hSocket, &fdsetSend);634            }635        }636637        vnThreadsRunning[0]--;638        int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);639        vnThreadsRunning[0]++;640        if (fShutdown)641            return;642        if (nSelect == SOCKET_ERROR)643        {644            int nErr = WSAGetLastError();645            printf("socket select error %d\n", nErr);646            for (int i = 0; i <= hSocketMax; i++)647                FD_SET(i, &fdsetRecv);648            FD_ZERO(&fdsetSend);649            FD_ZERO(&fdsetError);650            Sleep(timeout.tv_usec/1000);651        }652653654        //655        // Accept new connections656        //657        if (FD_ISSET(hListenSocket, &fdsetRecv))658        {659            struct sockaddr_in sockaddr;660#ifdef __WXMSW__661            int len = sizeof(sockaddr);662#else663            socklen_t len = sizeof(sockaddr);664#endif665            SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);666            CAddress addr(sockaddr);667            if (hSocket == INVALID_SOCKET)668            {669                if (WSAGetLastError() != WSAEWOULDBLOCK)670                    printf("socket error accept failed: %d\n", WSAGetLastError());671            }672            else673            {674                printf("accepted connection %s\n", addr.ToStringLog().c_str());675                CNode* pnode = new CNode(hSocket, addr, true);676                pnode->AddRef();677                CRITICAL_BLOCK(cs_vNodes)678                    vNodes.push_back(pnode);679            }680        }681682683        //684        // Service each socket685        //686        vector<CNode*> vNodesCopy;687        CRITICAL_BLOCK(cs_vNodes)688        {689            vNodesCopy = vNodes;690            foreach(CNode* pnode, vNodesCopy)691                pnode->AddRef();692        }693        foreach(CNode* pnode, vNodesCopy)694        {695            if (fShutdown)696                return;697698            //699            // Receive700            //701            if (pnode->hSocket == INVALID_SOCKET)702                continue;703            if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))704            {705                TRY_CRITICAL_BLOCK(pnode->cs_vRecv)706                {707                    CDataStream& vRecv = pnode->vRecv;708                    unsigned int nPos = vRecv.size();709710                    // typical socket buffer is 8K-64K711                    char pchBuf[0x10000];712                    int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);713                    if (nBytes > 0)714                    {715                        vRecv.resize(nPos + nBytes);716                        memcpy(&vRecv[nPos], pchBuf, nBytes);717                        pnode->nLastRecv = GetTime();718                    }719                    else if (nBytes == 0)720                    {721                        // socket closed gracefully722                        if (!pnode->fDisconnect)723                            printf("socket closed\n");724                        pnode->CloseSocketDisconnect();725                    }726                    else if (nBytes < 0)727                    {728                        // error729                        int nErr = WSAGetLastError();730                        if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)731                        {732                            if (!pnode->fDisconnect)733                                printf("socket recv error %d\n", nErr);734                            pnode->CloseSocketDisconnect();735                        }736                    }737                }738            }739740            //741            // Send742            //743            if (pnode->hSocket == INVALID_SOCKET)744                continue;745            if (FD_ISSET(pnode->hSocket, &fdsetSend))746            {747                TRY_CRITICAL_BLOCK(pnode->cs_vSend)748                {749                    CDataStream& vSend = pnode->vSend;750                    if (!vSend.empty())751                    {752                        int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);753                        if (nBytes > 0)754                        {755                            vSend.erase(vSend.begin(), vSend.begin() + nBytes);756                            pnode->nLastSend = GetTime();757                        }758                        else if (nBytes < 0)759                        {760                            // error761                            int nErr = WSAGetLastError();762                            if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)763                            {764                                printf("socket send error %d\n", nErr);765                                pnode->CloseSocketDisconnect();766                            }767                        }768                    }769                }770            }771772            //773            // Inactivity checking774            //775            if (pnode->vSend.empty())776                pnode->nLastSendEmpty = GetTime();777            if (GetTime() - pnode->nTimeConnected > 60)778            {779                if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)780                {781                    printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);782                    pnode->fDisconnect = true;783                }784                else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)785                {786                    printf("socket not sending\n");787                    pnode->fDisconnect = true;788                }789                else if (GetTime() - pnode->nLastRecv > 90*60)790                {791                    printf("socket inactivity timeout\n");792                    pnode->fDisconnect = true;793                }794            }795        }796        CRITICAL_BLOCK(cs_vNodes)797        {798            foreach(CNode* pnode, vNodesCopy)799                pnode->Release();800        }801802        nThreadSocketHandlerHeartbeat = GetTime();803        Sleep(10);804    }805}806807808809810811812813814815816void ThreadOpenConnections(void* parg)817{818    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));819820    try821    {822        vnThreadsRunning[1]++;823        ThreadOpenConnections2(parg);824        vnThreadsRunning[1]--;825    }826    catch (std::exception& e) {827        vnThreadsRunning[1]--;828        PrintException(&e, "ThreadOpenConnections()");829    } catch (...) {830        vnThreadsRunning[1]--;831        PrintException(NULL, "ThreadOpenConnections()");832    }833834    printf("ThreadOpenConnections exiting\n");835}836837void ThreadOpenConnections2(void* parg)838{839    printf("ThreadOpenConnections started\n");840841    // Connect to specific addresses842    if (mapArgs.count("-connect"))843    {844        for (int64 nLoop = 0;; nLoop++)845        {846            foreach(string strAddr, mapMultiArgs["-connect"])847            {848                CAddress addr(strAddr, NODE_NETWORK);849                if (addr.IsValid())850                    OpenNetworkConnection(addr);851                for (int i = 0; i < 10 && i < nLoop; i++)852                {853                    Sleep(500);854                    if (fShutdown)855                        return;856                }857            }858        }859    }860861    // Connect to manually added nodes first862    if (mapArgs.count("-addnode"))863    {864        foreach(string strAddr, mapMultiArgs["-addnode"])865        {866            CAddress addr(strAddr, NODE_NETWORK);867            if (addr.IsValid())868            {869                OpenNetworkConnection(addr);870                Sleep(500);871                if (fShutdown)872                    return;873            }874        }875    }876877    // Initiate network connections878    loop879    {880        // Wait881        vnThreadsRunning[1]--;882        Sleep(500);883        const int nMaxConnections = 15;884        while (vNodes.size() >= nMaxConnections || vNodes.size() >= mapAddresses.size())885        {886            if (fShutdown)887                return;888            Sleep(2000);889        }890        vnThreadsRunning[1]++;891        if (fShutdown)892            return;893894        //895        // Choose an address to connect to based on most recently seen896        //897        CAddress addrConnect;898        int64 nBest = INT64_MIN;899900        // Do this here so we don't have to critsect vNodes inside mapAddresses critsect901        set<unsigned int> setConnected;902        CRITICAL_BLOCK(cs_vNodes)903            foreach(CNode* pnode, vNodes)904                setConnected.insert(pnode->addr.ip);905906        CRITICAL_BLOCK(cs_mapAddresses)907        {908            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)909            {910                const CAddress& addr = item.second;911                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip))912                    continue;913                int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime;914                int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry;915916                // Randomize the order in a deterministic way, putting the standard port first917                int64 nRandomizer = (uint64)(addr.nLastTry * 9567851 + addr.ip * 7789) % (30 * 60);918                if (addr.port != DEFAULT_PORT)919                    nRandomizer += 30 * 60;920921                // Last seen  Base retry frequency922                //   <1 hour   10 min923                //    1 hour    1 hour924                //    4 hours   2 hours925                //   24 hours   5 hours926                //   48 hours   7 hours927                //    7 days   13 hours928                //   30 days   27 hours929                //   90 days   46 hours930                //  365 days   93 hours931                int64 nDelay = (int64)(3600.0 * sqrt(fabs(nSinceLastSeen) / 3600.0) + nRandomizer);932933                // Fast reconnect for one hour after last seen934                if (nSinceLastSeen < 60 * 60)935                    nDelay = 10 * 60;936937                // Limit retry frequency938                if (nSinceLastTry < nDelay)939                    continue;940941                // If we have IRC, we'll be notified when they first come online,942                // and again every 24 hours by the refresh broadcast.943                if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)944                    continue;945946                // Only try the old stuff if we don't have enough connections947                if (vNodes.size() >= 2 && nSinceLastSeen > 7 * 24 * 60 * 60)948                    continue;949                if (vNodes.size() >= 5 && nSinceLastSeen > 24 * 60 * 60)950                    continue;951952                // If multiple addresses are ready, prioritize by time since953                // last seen and time since last tried.954                int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;955                if (nScore > nBest)956                {957                    nBest = nScore;958                    addrConnect = addr;959                }960            }961        }962963        if (addrConnect.IsValid())964            OpenNetworkConnection(addrConnect);965    }966}967968bool OpenNetworkConnection(const CAddress& addrConnect)969{970    //971    // Initiate outbound network connection972    //973    if (fShutdown)974        return false;975    if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))976        return false;977978    vnThreadsRunning[1]--;979    CNode* pnode = ConnectNode(addrConnect);980    vnThreadsRunning[1]++;981    if (fShutdown)982        return false;983    if (!pnode)984        return false;985    pnode->fNetworkNode = true;986987    if (addrLocalHost.IsRoutable() && !fUseProxy)988    {989        // Advertise our address990        vector<CAddress> vAddrToSend;991        vAddrToSend.push_back(addrLocalHost);992        pnode->PushMessage("addr", vAddrToSend);993    }994995    // Get as many addresses as we can996    pnode->PushMessage("getaddr");997    pnode->fGetAddr = true; // don't relay the results of the getaddr998999    ////// should the one on the receiving end do this too?1000    // Subscribe our local subscription list1001    const unsigned int nHops = 0;1002    for (unsigned int nChannel = 0; nChannel < pnodeLocalHost->vfSubscribe.size(); nChannel++)1003        if (pnodeLocalHost->vfSubscribe[nChannel])1004            pnode->PushMessage("subscribe", nChannel, nHops);10051006    return true;1007}100810091010101110121013101410151016void ThreadMessageHandler(void* parg)1017{1018    IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));10191020    try1021    {1022        vnThreadsRunning[2]++;1023        ThreadMessageHandler2(parg);1024        vnThreadsRunning[2]--;1025    }1026    catch (std::exception& e) {1027        vnThreadsRunning[2]--;1028        PrintException(&e, "ThreadMessageHandler()");1029    } catch (...) {1030        vnThreadsRunning[2]--;1031        PrintException(NULL, "ThreadMessageHandler()");1032    }10331034    printf("ThreadMessageHandler exiting\n");1035}10361037void ThreadMessageHandler2(void* parg)1038{1039    printf("ThreadMessageHandler started\n");1040    SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);1041    loop1042    {1043        // Poll the connected nodes for messages1044        vector<CNode*> vNodesCopy;1045        CRITICAL_BLOCK(cs_vNodes)1046        {1047            vNodesCopy = vNodes;1048            foreach(CNode* pnode, vNodesCopy)1049                pnode->AddRef();1050        }1051        foreach(CNode* pnode, vNodesCopy)1052        {1053            // Receive messages1054            TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1055                ProcessMessages(pnode);1056            if (fShutdown)1057                return;10581059            // Send messages1060            TRY_CRITICAL_BLOCK(pnode->cs_vSend)1061                SendMessages(pnode);1062            if (fShutdown)1063                return;1064        }1065        CRITICAL_BLOCK(cs_vNodes)1066        {1067            foreach(CNode* pnode, vNodesCopy)1068                pnode->Release();1069        }10701071        // Wait and allow messages to bunch up1072        vnThreadsRunning[2]--;1073        Sleep(100);1074        vnThreadsRunning[2]++;1075        if (fShutdown)1076            return;1077    }1078}1079108010811082108310841085108610871088bool BindListenPort(string& strError)1089{1090    strError = "";1091    int nOne = 1;10921093#ifdef __WXMSW__1094    // Initialize Windows Sockets1095    WSADATA wsadata;1096    int ret = WSAStartup(MAKEWORD(2,2), &wsadata);1097    if (ret != NO_ERROR)1098    {1099        strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);1100        printf("%s\n", strError.c_str());1101        return false;1102    }1103#endif11041105    // Create socket for listening for incoming connections1106    hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);1107    if (hListenSocket == INVALID_SOCKET)1108    {1109        strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());1110        printf("%s\n", strError.c_str());1111        return false;1112    }11131114#if defined(__BSD__) || defined(__WXOSX__)1115    // Different way of disabling SIGPIPE on BSD1116    setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));1117#endif11181119#ifndef __WXMSW__1120    // Allow binding if the port is still in TIME_WAIT state after1121    // the program was closed and restarted.  Not an issue on windows.1122    setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));1123#endif11241125#ifdef __WXMSW__1126    // Set to nonblocking, incoming connections will also inherit this1127    if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)1128#else1129    if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)1130#endif1131    {1132        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());1133        printf("%s\n", strError.c_str());1134        return false;1135    }11361137    // The sockaddr_in structure specifies the address family,1138    // IP address, and port for the socket that is being bound1139    struct sockaddr_in sockaddr;1140    memset(&sockaddr, 0, sizeof(sockaddr));1141    sockaddr.sin_family = AF_INET;1142    sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer1143    sockaddr.sin_port = DEFAULT_PORT;1144    if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)1145    {1146        int nErr = WSAGetLastError();1147        if (nErr == WSAEADDRINUSE)1148            strError = strprintf("Unable to bind to port %d on this computer.  Bitcoin is probably already running.", ntohs(sockaddr.sin_port));1149        else1150            strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);1151        printf("%s\n", strError.c_str());1152        return false;1153    }1154    printf("Bound to port %d\n", ntohs(sockaddr.sin_port));11551156    // Listen for incoming connections1157    if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)1158    {1159        strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());1160        printf("%s\n", strError.c_str());1161        return false;1162    }11631164    return true;1165}11661167void StartNode(void* parg)1168{1169    if (pnodeLocalHost == NULL)1170        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));11711172#ifdef __WXMSW__1173    // Get local host ip1174    char pszHostName[1000] = "";1175    if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)1176    {1177        struct hostent* phostent = gethostbyname(pszHostName);1178        if (phostent)1179        {1180            // Take the first IP that isn't loopback 127.x.x.x1181            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1182                printf("host ip %d: %s\n", i, CAddress(*(unsigned int*)phostent->h_addr_list[i]).ToStringIP().c_str());1183            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1184            {1185                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], DEFAULT_PORT, nLocalServices);1186                if (addr.IsValid() && addr.GetByte(3) != 127)1187                {1188                    addrLocalHost = addr;1189                    break;1190                }1191            }1192        }1193    }1194#else1195    // Get local host ip1196    struct ifaddrs* myaddrs;1197    if (getifaddrs(&myaddrs) == 0)1198    {1199        for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)1200        {1201            if (ifa->ifa_addr == NULL) continue;1202            if ((ifa->ifa_flags & IFF_UP) == 0) continue;1203            if (strcmp(ifa->ifa_name, "lo") == 0) continue;1204            if (strcmp(ifa->ifa_name, "lo0") == 0) continue;1205            char pszIP[100];1206            if (ifa->ifa_addr->sa_family == AF_INET)1207            {1208                struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);1209                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL)1210                    printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);12111212                // Take the first IP that isn't loopback 127.x.x.x1213                CAddress addr(*(unsigned int*)&s4->sin_addr, DEFAULT_PORT, nLocalServices);1214                if (addr.IsValid() && addr.GetByte(3) != 127)1215                {1216                    addrLocalHost = addr;1217                    break;1218                }1219            }1220            else if (ifa->ifa_addr->sa_family == AF_INET6)1221            {1222                struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);1223                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL)1224                    printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP);1225            }1226        }1227        freeifaddrs(myaddrs);1228    }1229#endif1230    printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());12311232    // Get our external IP address for incoming connections1233    if (fUseProxy)1234    {1235        // Proxies can't take incoming connections1236        addrLocalHost.ip = CAddress("0.0.0.0").ip;1237        printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1238    }1239    else1240    {1241        if (addrIncoming.IsValid())1242            addrLocalHost.ip = addrIncoming.ip;12431244        if (GetMyExternalIP(addrLocalHost.ip))1245        {1246            addrIncoming = addrLocalHost;1247            CWalletDB().WriteSetting("addrIncoming", addrIncoming);1248            printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1249        }1250    }12511252    //1253    // Start threads1254    //12551256    // Get addresses from IRC and advertise ours1257    if (!CreateThread(ThreadIRCSeed, NULL))1258        printf("Error: CreateThread(ThreadIRCSeed) failed\n");12591260    // Send and receive from sockets, accept connections1261    pthread_t hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);12621263    // Initiate outbound connections1264    if (!CreateThread(ThreadOpenConnections, NULL))1265        printf("Error: CreateThread(ThreadOpenConnections) failed\n");12661267    // Process messages1268    if (!CreateThread(ThreadMessageHandler, NULL))1269        printf("Error: CreateThread(ThreadMessageHandler) failed\n");12701271    // Generate coins in the background1272    GenerateBitcoins(fGenerateBitcoins);12731274    //1275    // Thread monitoring1276    // Not really needed anymore, the cause of the hanging was fixed1277    //1278    loop1279    {1280        Sleep(1000);1281        if (fShutdown)1282            return;1283        if (GetTime() - nThreadSocketHandlerHeartbeat > 15 * 60)1284        {1285            // First see if closing sockets will free it1286            printf("*** ThreadSocketHandler is stopped ***\n");1287            CRITICAL_BLOCK(cs_vNodes)1288            {1289                foreach(CNode* pnode, vNodes)1290                {1291                    bool fGot = false;1292                    TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1293                        TRY_CRITICAL_BLOCK(pnode->cs_vSend)1294                            fGot = true;1295                    if (!fGot)1296                    {1297                        printf("*** closing socket\n");1298                        pnode->CloseSocketDisconnect();1299                    }1300                }1301            }1302            Sleep(10000);1303            if (fShutdown)1304                return;1305            if (GetTime() - nThreadSocketHandlerHeartbeat < 60)1306                continue;13071308            // Hopefully it never comes to this.1309            // We know it'll always be hung in the recv or send call.1310            // cs_vRecv or cs_vSend may be left permanently unreleased,1311            // but we always only use TRY_CRITICAL_SECTION on them.1312            printf("*** Restarting ThreadSocketHandler ***\n");1313            TerminateThread(hThreadSocketHandler, 0);1314            #ifdef __WXMSW__1315            CloseHandle(hThreadSocketHandler);1316            #endif1317            vnThreadsRunning[0] = 0;13181319            // Restart1320            hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);1321            nThreadSocketHandlerHeartbeat = GetTime();1322        }1323    }1324}13251326bool StopNode()1327{1328    printf("StopNode()\n");1329    fShutdown = true;1330    nTransactionsUpdated++;1331    int64 nStart = GetTime();1332    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0)1333    {1334        if (GetTime() - nStart > 20)1335            break;1336        Sleep(20);1337    }1338    if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n");1339    if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");1340    if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");1341    if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");1342    while (vnThreadsRunning[2] > 0)1343        Sleep(20);1344    Sleep(50);13451346    return true;1347}13481349class CNetCleanup1350{1351public:1352    CNetCleanup()1353    {1354    }1355    ~CNetCleanup()1356    {1357        // Close sockets1358        foreach(CNode* pnode, vNodes)1359            if (pnode->hSocket != INVALID_SOCKET)1360                closesocket(pnode->hSocket);1361        if (hListenSocket != INVALID_SOCKET)1362            if (closesocket(hListenSocket) == SOCKET_ERROR)1363                printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());13641365#ifdef __WXMSW__1366        // Shutdown Windows Sockets1367        WSACleanup();1368#endif1369    }1370}1371instance_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