Skip to content

Commit

Permalink
Update net.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
cqtenq committed Sep 24, 2014
1 parent 43997d5 commit d46f1ee
Showing 1 changed file with 46 additions and 75 deletions.
121 changes: 46 additions & 75 deletions src/net.cpp
Expand Up @@ -44,18 +44,13 @@ static const int MAX_OUTBOUND_CONNECTIONS = 8;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);


struct LocalServiceInfo {
int nScore;
int nPort;
};

//
// Global state variables
//
bool fDiscover = true;
uint64_t nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
Expand Down Expand Up @@ -183,7 +178,7 @@ bool RecvLine(SOCKET hSocket, string& strLine)
{
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %d\n", nErr);
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
Expand Down Expand Up @@ -355,7 +350,7 @@ bool GetMyExternalIP(CNetAddr& ipRet)
const char* pszKeyword;

for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
for (int nHost = 1; nHost <= 1; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
Expand All @@ -380,25 +375,6 @@ bool GetMyExternalIP(CNetAddr& ipRet)

pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com

if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}

pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";

pszKeyword = NULL; // Returns just IP address
}

if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
Expand Down Expand Up @@ -494,10 +470,10 @@ CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %s\n", NetworkErrorString(WSAGetLastError()));
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %s\n", NetworkErrorString(errno));
#endif

// Add node
Expand Down Expand Up @@ -741,7 +717,7 @@ void SocketSendData(CNode *pnode)
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
LogPrintf("socket send error %d\n", nErr);
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
Expand Down Expand Up @@ -901,7 +877,7 @@ void ThreadSocketHandler()
if (have_fds)
{
int nErr = WSAGetLastError();
LogPrintf("socket select error %d\n", nErr);
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
Expand All @@ -917,11 +893,7 @@ void ThreadSocketHandler()
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
Expand All @@ -942,15 +914,11 @@ void ThreadSocketHandler()
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %d\n", nErr);
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
closesocket(hSocket);
}
else if (CNode::IsBanned(addr))
{
Expand Down Expand Up @@ -1020,7 +988,7 @@ void ThreadSocketHandler()
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
LogPrintf("socket recv error %d\n", nErr);
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
Expand Down Expand Up @@ -1069,8 +1037,6 @@ void ThreadSocketHandler()
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}

MilliSleep(10);
}
}

Expand Down Expand Up @@ -1124,7 +1090,7 @@ void ThreadMapPort()
}
}

string strDesc = "Bitcoin " + FormatFullVersion();
string strDesc = "Feathercoin " + FormatFullVersion();

try {
while (true) {
Expand Down Expand Up @@ -1198,6 +1164,18 @@ void MapPort(bool)

void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);

LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}

const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
int found = 0;

Expand Down Expand Up @@ -1471,13 +1449,13 @@ bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOu

// for now, use a very simple selection metric: the node from which we received
// most recently
double static NodeSyncScore(const CNode *pnode) {
return -pnode->nLastRecv;
static int64_t NodeSyncScore(const CNode *pnode) {
return pnode->nLastRecv;
}

void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
double dBestScore = 0;
int64_t nBestScore = 0;

int nBestHeight = g_signals.GetHeight().get_value_or(0);

Expand All @@ -1489,10 +1467,10 @@ void static StartSync(const vector<CNode*> &vNodes) {
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
double dScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || dScore > dBestScore) {
int64_t nScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || nScore > nBestScore) {
pnodeNewSync = pnode;
dBestScore = dScore;
nBestScore = nScore;
}
}
}
Expand Down Expand Up @@ -1586,11 +1564,7 @@ bool BindListenPort(const CService &addrBind, string& strError)
int nOne = 1;

// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
Expand All @@ -1602,7 +1576,7 @@ bool BindListenPort(const CService &addrBind, string& strError)
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
Expand All @@ -1626,12 +1600,11 @@ bool BindListenPort(const CService &addrBind, string& strError)
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}

#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
Expand All @@ -1649,15 +1622,14 @@ bool BindListenPort(const CService &addrBind, string& strError)
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif

if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin Core is probably already running."), addrBind.ToString());
strError = strprintf(_("Unable to bind to %s on this computer. Feathercoin Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString(), nErr, strerror(nErr));
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
return false;
}
Expand All @@ -1666,7 +1638,7 @@ bool BindListenPort(const CService &addrBind, string& strError)
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %d)"), WSAGetLastError());
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
Expand Down Expand Up @@ -1716,15 +1688,13 @@ void static Discover(boost::thread_group& threadGroup)
if (AddLocal(addr, LOCAL_IF))
LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString());
}
#endif
}
freeifaddrs(myaddrs);
}
Expand Down Expand Up @@ -1806,7 +1776,7 @@ class CNetCleanup
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
LogPrintf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
LogPrintf("closesocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));

// clean up some globals (to help leak detection)
BOOST_FOREACH(CNode *pnode, vNodes)
Expand Down Expand Up @@ -1960,21 +1930,21 @@ bool CAddrDB::Write(const CAddrMan& addr)
FILE *file = fopen(pathTmp.string().c_str(), "wb");
CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CAddrman::Write() : open failed");
return error("%s : Failed to open file %s", __func__, pathTmp.string());

// Write and commit header, data
try {
fileout << ssPeers;
}
catch (std::exception &e) {
return error("CAddrman::Write() : I/O error");
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout);
fileout.fclose();

// replace existing peers.dat, if any, with new peers.dat.XXXX
if (!RenameOver(pathTmp, pathAddr))
return error("CAddrman::Write() : Rename-into-place failed");
return error("%s : Rename-into-place failed", __func__);

return true;
}
Expand All @@ -1985,13 +1955,14 @@ bool CAddrDB::Read(CAddrMan& addr)
FILE *file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CAddrman::Read() : open failed");
return error("%s : Failed to open file %s", __func__, pathAddr.string());

// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathAddr);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if ( dataSize < 0 ) dataSize = 0;
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
Expand All @@ -2002,7 +1973,7 @@ bool CAddrDB::Read(CAddrMan& addr)
filein >> hashIn;
}
catch (std::exception &e) {
return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();

Expand All @@ -2011,7 +1982,7 @@ bool CAddrDB::Read(CAddrMan& addr)
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("CAddrman::Read() : checksum mismatch; data corrupted");
return error("%s : Checksum mismatch, data corrupted", __func__);

unsigned char pchMsgTmp[4];
try {
Expand All @@ -2020,13 +1991,13 @@ bool CAddrDB::Read(CAddrMan& addr)

// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("CAddrman::Read() : invalid network magic number");
return error("%s : Invalid network magic number", __func__);

// de-serialize address data into one CAddrMan object
ssPeers >> addr;
}
catch (std::exception &e) {
return error("CAddrman::Read() : I/O error or stream data corrupted");
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}

return true;
Expand Down

0 comments on commit d46f1ee

Please sign in to comment.