CPipeConnectSuccResult::CPipeConnectSuccResult( int32 nPipeId, uint32 uSessionID, const CAddress& LocalAddr, const CAddress& RemoteAddr, CPipeThread* pThread) : CPipeResult(nPipeId, uSessionID) { m_szLocalAddr = CloneString(LocalAddr.GetAddress(), pThread); m_uLocalPort = LocalAddr.GetPort(); m_szRemoteAddr = CloneString(RemoteAddr.GetAddress(), pThread); m_uRemotePort = RemoteAddr.GetPort(); }
CPipeAcceptedResult::CPipeAcceptedResult(int32 nPipeId,uint32 uSessionID, int32 newPipeId, uint32 threadId, uint32 oldthreadid, IPipe* pPipe, const CAddress& LocalAddr, const CAddress& RemoteAddr, CPipeThread* pThread) :CPipeResult(nPipeId, uSessionID) { m_szLocalAddr = CloneString( LocalAddr.GetAddress(), pThread ); m_uLocalPort = LocalAddr.GetPort(); m_szRemoteAddr = CloneString( RemoteAddr.GetAddress(), pThread ); m_uRemotePort = RemoteAddr.GetPort(); m_pPipe = pPipe; m_uOldThreadId = oldthreadid; m_nNewPipeID = newPipeId; m_uThreadId = threadId; }
int CPipeState_Listening::CreateBindedSocket(SOCKET& SocketOut,const CAddress& Address) { SOCKET Socket=CreateSocket(); sockaddr_in saiAddress; memset(&saiAddress,0,sizeof(saiAddress)); saiAddress.sin_addr.s_addr = inet_addr( Address.GetAddress() ); saiAddress.sin_port = htons( static_cast<u_short>( Address.GetPort() ) ); saiAddress.sin_family = AF_INET; //bind if( bind( Socket,reinterpret_cast<sockaddr*>( &saiAddress) , sizeof(sockaddr) ) ) { closesocket(Socket); return SocketGetLastError(); } SocketOut=Socket; return 0; }
void CBitcoinServer::BitcoinNetMaintain() { CChainManager& chain = CChainManager::CreateChainManagerInstance(); // chain.LoadBitcoinBlockIndex(); getAddrFromDb(); getAddrFromDnsSeed(); while(true) { if (!m_oneShot.empty()) { std::string strDest; strDest = m_oneShot.front(); m_oneShot.pop_front(); SOCKET hSocket = INVALID_SOCKET; CAddress addr; if (openNetworkConnection(addr, strDest.c_str(), hSocket)) { boost::shared_ptr<CBitcoinNode> node = createNode(hSocket, addr); if (node) { node->fOneShot = true; m_nodesManager.insert(node); node->PushVersion(); } } else { m_oneShot.push_back(strDest); } } if (Bitcoin_MAX_CONNECTED_SOCKECT > m_nodesManager.getNodesSize()) { do { SOCKET hSocket = INVALID_SOCKET; int nUnkBias = 10 + (int)min(m_nodesManager.getNodesSize(), Bitcoin_MAX_CONNECTED_SOCKECT)*10; CAddress addr = m_BitcoinAddrMan.Select(nUnkBias); if (!addr.IsValid() || m_nodesManager.exist(addr) || IsLocal(addr)) { break; } if (IsLimited(addr) || addr.GetPort() != Bitcoin_DEFAULT_PORT) { break; } if (openNetworkConnection(addr, NULL, hSocket)) { boost::shared_ptr<CBitcoinNode> node = createNode(hSocket, addr); if (node) { m_nodesManager.insert(node); node->PushVersion(); } } }while(false); } m_nodesManager.sockectSelect(); m_nodesManager.clearDisconnectNodes(); m_nodesManager.startSync(); } }
CPipeState_Connecting::CPipeState_Connecting(CSyncPipe* pPipe,const CAddress& Address,uint32& uResult) :CPipeState_Busy(pPipe) { pPipe->m_OutBuffer.OutBufferClear(); pPipe->m_InBuffer.InBufferClear(); CPipeState* pState=GetPipe()->m_pState; GetPipe()->m_pState=NULL; delete pState; GetPipe()->m_pState=this; const SOCKET& Socket=m_Socket; #ifdef _WIN32 SQR_TRY { m_Event.Create(Socket); } SQR_CATCH (exp) { LogExp(exp); closesocket(m_Socket); throw; } SQR_TRY_END; #endif Register(); sockaddr_in saiAddress; ::memset(&saiAddress,0,sizeof(saiAddress)); saiAddress.sin_addr.s_addr = inet_addr(Address.GetAddress()); saiAddress.sin_port = htons(static_cast<u_short>(Address.GetPort())); saiAddress.sin_family = AF_INET; //连接 int nResult; nResult=connect(Socket,reinterpret_cast<sockaddr*>(&saiAddress),sizeof(sockaddr)); if(SOCKET_ERROR!=nResult) { uResult=0; } else { int nError=SocketGetLastError(); switch(nError) { #if defined(__linux__) case EINPROGRESS: #elif defined(_WIN32) case EWOULDBLOCK: #endif uResult=1; break; #ifdef _WIN32 case ECONNABORTED://Windows下还真会出现这种情况 case ENOBUFS: uResult=2; GetPipe()->AddEventConnectFailed(ePCFR_OSERROR); return; #endif case ECONNRESET: case ECONNREFUSED: uResult=2; GetPipe()->AddEventConnectFailed(ePCFR_REFUSED); return; case ETIMEDOUT: case ENETRESET: case EHOSTUNREACH: case ENETUNREACH: uResult=2; GetPipe()->AddEventConnectFailed(ePCFR_UNREACHABLE); return; default: closesocket(m_Socket); stringstream strm; strm<<"connect failed with error code "<<nError<<"."; GenErr(strm.str()); } } m_RemoteAddress=Address; }
bool CAddrMan::Add_(const CAddress& addrIn, const CNetAddr& source, int64_t nTimePenalty) { #ifdef I2PADDRMAN_EXTENSIONS //! We now need to check for an possibly modify the CAddress object for the garliccat field, so we make a local copy CAddress addr = addrIn; /** * Before we can add an address, even before we can test if its Routable, or use the Find command to match correctly, * we need to make sure that any I2P addresses have the GarlicCat field setup correctly in the IP area of the * CNetAddr portion of a given CAddress->CService->CNetAddr object, this should have already been done, but * double checking it here also insures we do not get a polluted b32 hash map */ if( addr.CheckAndSetGarlicCat() ) LogPrint( "addrman", "While adding an i2p destination, did not expect to need the garliccat fixed for %s\n", addr.ToString() ); #endif if( !addr.IsRoutable() ) { LogPrint( "addrman", "While adding an address, did not expect to find it unroutable: %s\n", addr.ToString() ); return false; } bool fNew = false; int nId; /** * Find Matches by CNetAddr objects, and returns the CAddrInfo object it finds, which is fine and what we want normally * however this means the ports can be different (CService), and other details in the CAddress portion, such as nServices * should not simply be 'or'd with what was found, sometimes we have to remove services in the version exchange that * peers report incorrectly, and having the port wrong means when Good_ is called that the objects do not match exactly. */ CAddrInfo* pinfo = Find(addr, &nId); if (pinfo) { // periodically update nTime bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); /** * Only do the following, IF the source of this information is the node itself (source), * otherwise we're just constantly changing the details, while getting addresses from peers. * * The call (to addrman.Add()) which puts us here, happens at the end of a version message exchange, * for inbound connections only. * For outbound connections, we only have a call to good, if the connection is made. * Other places addrman.Add() is called is for address seeding and user lookup, see net.cpp for those details */ if( (CNetAddr)addr == source ) { /** * add services, don't just 'or' them in here, hard set them to the correct value * original code: pinfo->nServices |= addr.nServices; * ToDo: Why this and the port value has not been fixed as standard procedure could be investigated in more detail * for now Anoncoin has so many unique problems with these 2 values, this should help correct allot of the * current network issues in regard to the values getting corrected over time. */ if( pinfo->nServices != addr.nServices ) { LogPrint( "addrman", "Updating peer record %s, the services listed needed to be changed. From 0x%016x To 0x%016x\n", pinfo->ToString(), pinfo->nServices, addr.nServices ); pinfo->nServices = addr.nServices; } if( pinfo->GetPort() != addr.GetPort() ) { LogPrint( "addrman", "Updating peer record %s, port %d was wrong, changed it to %d\n", pinfo->ToString(), pinfo->GetPort(), addr.GetPort() ); pinfo->SetPort( addr.GetPort() ); } } // do not update if no new information is present if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime)) return false; // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (GetRandInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } int nUBucket = pinfo->GetNewBucket(nKey, source); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket][nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (!fInsert) { CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fNew; }
/** * The only time good is called, is during the version message exchange, for inbound it was added first and any address problems * looked over and fixed. For outbound, what we have, was likely what was used to make the connection, so it must have been good * or this would not have been called. * Still we may have services and port details incorrect in our database, and so any object differences can be corrected, if * a change is made to how this routine is called, from passing a CService to a CAddress object we can have the programmer fix * any problems before making this call, we'll look for, and fix the differences, if they show up here. */ void CAddrMan::Good_(const CAddress& addr, int64_t nTime) { bool fChanged = false; int nId; CAddrInfo* pinfo = Find(addr, &nId); // This matches on the CNetAddr portion of the object only aka the ip/i2p only // if not found, bail out if (!pinfo) { LogPrint( "addrman", "Marking as good failed, expected to find %s\n", addr.ToString() ); return; } CAddrInfo& info = *pinfo; // Only really for convenience, not really needed // check whether we are talking about the exact same CService (that includes the same port) if( (CService)info != (CService)addr) { assert( info.GetPort() != addr.GetPort() ); // The only reason which could cause a mismatch, or we have a serious programming problem LogPrint( "addrman", "While marking %s as good, it was found that port %d does not match our record, now updated.\n", info.ToString(), addr.GetPort() ); info.SetPort( addr.GetPort() ); fChanged = true; } // Ok so now we know that at least the CService details all match, lets check and fix the CAddress service bits for this peer, if its listed wrong, fix it. if( info.nServices != addr.nServices ) { LogPrint( "addrman", "While marking %s as good, the peer services was found to have changed from 0x%016x to 0x%016x, now updated.\n", info.ToString(), info.nServices, addr.nServices ); info.nServices = addr.nServices; fChanged = true; } // update info info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; // info.nTime = nTime; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else, except report we were here if(info.fInTried ) { if( !fChanged ) LogPrint( "addrman", "Marked as good peer %s\n", info.ToString() ); return; } // find a bucket it is in now int nRnd = GetRandInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if( nUBucket == -1 ) { LogPrint( "addrman", "Fatal error while trying to add %s to tried, bucket not found\n", info.ToString() ); return; } LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); // move nId to the tried tables MakeTried(info, nId); }