Change some code according G10h4ck remarks.

This commit is contained in:
Phenom 2021-11-04 13:10:15 +01:00
parent 7755f85c4c
commit 91a35f4a21
9 changed files with 242 additions and 212 deletions

View File

@ -47,15 +47,15 @@ struct RsLog::logInfo p3netmgrzoneInfo = {RsLog::Default, "p3netmgr"};
/* Network setup States */ /* Network setup States */
const uint32_t RS_NET_NEEDS_RESET = 0x0000; constexpr uint32_t RS_NET_NEEDS_RESET = 0x0000;
const uint32_t RS_NET_UNKNOWN = 0x0001; constexpr uint32_t RS_NET_UNKNOWN = 0x0001;
const uint32_t RS_NET_UPNP_INIT = 0x0002; constexpr uint32_t RS_NET_UPNP_INIT = 0x0002;
const uint32_t RS_NET_UPNP_SETUP = 0x0003; constexpr uint32_t RS_NET_UPNP_SETUP = 0x0003;
const uint32_t RS_NET_EXT_SETUP = 0x0004; constexpr uint32_t RS_NET_EXT_SETUP = 0x0004;
const uint32_t RS_NET_DONE = 0x0005; constexpr uint32_t RS_NET_DONE = 0x0005;
const uint32_t RS_NET_LOOPBACK = 0x0006; constexpr uint32_t RS_NET_LOOPBACK = 0x0006;
//const uint32_t RS_NET_DOWN = 0x0007; //constexpr uint32_t RS_NET_DOWN = 0x0007;
const uint32_t RS_NET_SHUTDOWN = 0x00FF; //Highest value to not restart UPnP nor ExtAddrFinder constexpr uint32_t RS_NET_SHUTDOWN = 0x00FF; //Highest value to not restart UPnP nor ExtAddrFinder
/* Stun modes (TODO) */ /* Stun modes (TODO) */
//const uint32_t RS_STUN_DHT = 0x0001; //const uint32_t RS_STUN_DHT = 0x0001;
@ -118,7 +118,7 @@ p3NetMgrIMPL::p3NetMgrIMPL()
{ {
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mExtAddrFinder = new ExtAddrFinder(); mExtAddrFinder = new ExtAddrFinder();
@ -233,7 +233,7 @@ void p3NetMgrIMPL::netReset()
shutdown(); /* blocking shutdown call */ shutdown(); /* blocking shutdown call */
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStatus = RS_NET_UNKNOWN; mNetStatus = RS_NET_UNKNOWN;
} }
@ -266,7 +266,7 @@ void p3NetMgrIMPL::netReset()
* as it calls back to p3ConnMgr. * as it calls back to p3ConnMgr.
*/ */
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
struct sockaddr_storage iaddr = mLocalAddr; struct sockaddr_storage iaddr = mLocalAddr;
@ -284,7 +284,7 @@ void p3NetMgrIMPL::netReset()
} }
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
netStatusReset_locked(); netStatusReset_locked();
} }
@ -311,7 +311,7 @@ bool p3NetMgrIMPL::shutdown() /* blocking shutdown call */
std::cerr << std::endl; std::cerr << std::endl;
#endif #endif
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStatus = RS_NET_SHUTDOWN; mNetStatus = RS_NET_SHUTDOWN;
mNetInitTS = time(NULL); mNetInitTS = time(NULL);
netStatusReset_locked(); netStatusReset_locked();
@ -347,7 +347,7 @@ void p3NetMgrIMPL::netStartup()
*/ */
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetInitTS = time(NULL); mNetInitTS = time(NULL);
netStatusReset_locked(); netStatusReset_locked();
@ -462,7 +462,7 @@ void p3NetMgrIMPL::netStatusTick()
rstime_t age = 0; rstime_t age = 0;
bool needExtFinderUpdate = false; bool needExtFinderUpdate = false;
{ {
RsStackMutex stack(mNetMtx); /************** LOCK MUTEX ***************/ RS_STACK_MUTEX(mNetMtx); /************** LOCK MUTEX ***************/
netStatus = mNetStatus; netStatus = mNetStatus;
age = time(NULL) - mNetInitTS; age = time(NULL) - mNetInitTS;
@ -477,9 +477,10 @@ void p3NetMgrIMPL::netStatusTick()
&& ( netStatus <= RS_NET_UPNP_SETUP && ( netStatus <= RS_NET_UPNP_SETUP
|| needExtFinderUpdate) ) || needExtFinderUpdate) )
{ {
sockaddr_storage tmpip = mLocalAddr; // copies local port and correctly inits the IP family sockaddr_storage tmpip;
sockaddr_storage_copy( mLocalAddr, tmpip); // copies local port and correctly inits the IP family
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " Asking ExtAddrFinder for IP. Initializing port with ", sockaddr_storage_port(tmpip)); RS_DBG("Asking ExtAddrFinder for IP. Initializing port with ", sockaddr_storage_port(tmpip));
#endif #endif
if(mExtAddrFinder->hasValidIPV4(tmpip)) if(mExtAddrFinder->hasValidIPV4(tmpip))
@ -487,7 +488,7 @@ void p3NetMgrIMPL::netStatusTick()
if(!sockaddr_storage_same(tmpip,mExtAddr)) if(!sockaddr_storage_same(tmpip,mExtAddr))
{ {
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " Ext supplied by ExtAddrFinder", " ExtAddr: ", sockaddr_storage_tostring(tmpip)); RS_DBG("Ext supplied by ExtAddrFinder. ExtAddr: ", tmpip);
#endif #endif
setExtAddress(tmpip); setExtAddress(tmpip);
} }
@ -498,7 +499,7 @@ void p3NetMgrIMPL::netStatusTick()
{ {
//Only if no IPv4 else, reset connections on setExtAddress() //Only if no IPv4 else, reset connections on setExtAddress()
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " Ext supplied by ExtAddrFinder", " ExtAddr: ", sockaddr_storage_tostring(tmpip)); RS_DBG("Ext supplied by ExtAddrFinder. ExtAddr: ", tmpip);
#endif #endif
setExtAddress(tmpip); setExtAddress(tmpip);
} }
@ -593,7 +594,7 @@ void p3NetMgrIMPL::netDhtInit()
uint32_t vs = 0; uint32_t vs = 0;
{ {
RsStackMutex stack(mNetMtx); /*********** LOCKED MUTEX ************/ RS_STACK_MUTEX(mNetMtx); /*********** LOCKED MUTEX ************/
vs = mVsDht; vs = mVsDht;
} }
@ -760,16 +761,14 @@ void p3NetMgrIMPL::netExtCheck()
if (mUseExtAddrFinder) if (mUseExtAddrFinder)
{ {
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " checking ExtAddrFinder"); RS_DBG("checking ExtAddrFinder");
#endif #endif
sockaddr_storage tmpip = mLocalAddr; // copies local port and correctly inits the IP family sockaddr_storage tmpip;
sockaddr_storage_copy( mLocalAddr, tmpip); // copies local port and correctly inits the IP family
// Test for IPv4 first to be compatible with older versions. // Test for IPv4 first to be compatible with older versions.
if (mExtAddrFinder->hasValidIPV4(tmpip)) if (mExtAddrFinder->hasValidIPV4(tmpip))
{ {
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " Ext IPv4 supplied by ExtAddrFinder", sockaddr_storage_tostring(tmpip));
#endif
sockaddr_storage_setport(tmpip, guessNewExtPort()); sockaddr_storage_setport(tmpip, guessNewExtPort());
mNetFlags.mExtAddrOk = true; mNetFlags.mExtAddrOk = true;
@ -781,13 +780,10 @@ void p3NetMgrIMPL::netExtCheck()
* (which it is not normally) */ * (which it is not normally) */
mNetFlags.mExtAddrStableOk = true; mNetFlags.mExtAddrStableOk = true;
RsErr(__PRETTY_FUNCTION__, " reported external IPv4 address ", sockaddr_storage_iptostring(tmpip)); RS_DBG("Reported external IPv4 address ", sockaddr_storage_iptostring(tmpip));
} }
else if (mExtAddrFinder->hasValidIPV6(tmpip)) else if (mExtAddrFinder->hasValidIPV6(tmpip))
{ {
#if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET)
RsDbg(__PRETTY_FUNCTION__, " Ext IPv6 supplied by ExtAddrFinder", sockaddr_storage_tostring(tmpip));
#endif
sockaddr_storage_setport(tmpip, guessNewExtPort()); sockaddr_storage_setport(tmpip, guessNewExtPort());
mNetFlags.mExtAddrOk = true; mNetFlags.mExtAddrOk = true;
@ -799,7 +795,7 @@ void p3NetMgrIMPL::netExtCheck()
* (which it is not normally) */ * (which it is not normally) */
mNetFlags.mExtAddrStableOk = true; mNetFlags.mExtAddrStableOk = true;
RsErr(__PRETTY_FUNCTION__, " reported external IPv6 address ", sockaddr_storage_iptostring(tmpip)); RS_DBG("Reported external IPv6 address ", sockaddr_storage_iptostring(tmpip));
} }
} }
} }
@ -990,7 +986,7 @@ void p3NetMgrIMPL::netExtCheck()
if (netSetupDone) if (netSetupDone)
{ {
RsDbg(__PRETTY_FUNCTION__, " netSetupDone"); RS_DBG("netSetupDone");
/* Setup NetStateBox with this info */ /* Setup NetStateBox with this info */
updateNetStateBox_startup(); updateNetStateBox_startup();
@ -1008,7 +1004,7 @@ void p3NetMgrIMPL::netExtCheck()
netAssistKnownPeer(fakeId, mExtAddr, NETASSIST_KNOWN_PEER_SELF | NETASSIST_KNOWN_PEER_ONLINE); netAssistKnownPeer(fakeId, mExtAddr, NETASSIST_KNOWN_PEER_SELF | NETASSIST_KNOWN_PEER_ONLINE);
} }
RsDbg(__PRETTY_FUNCTION__, " Network Setup Complete"); RS_INFO("Network Setup Complete");
} }
} }
@ -1093,8 +1089,7 @@ bool p3NetMgrIMPL::checkNetAddress()
if (!validAddr) if (!validAddr)
{ {
RsErr() << __PRETTY_FUNCTION__ << " no valid local network address " RS_ERR("no valid local network address found. Report to developers.");
<<" found. Report to developers." << std::endl;
print_stacktrace(); print_stacktrace();
return false; return false;
@ -1179,7 +1174,7 @@ bool p3NetMgrIMPL::checkNetAddress()
/* to allow resets of network stuff */ /* to allow resets of network stuff */
void p3NetMgrIMPL::addNetListener(pqiNetListener *listener) void p3NetMgrIMPL::addNetListener(pqiNetListener *listener)
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetListeners.push_back(listener); mNetListeners.push_back(listener);
} }
@ -1189,7 +1184,7 @@ bool p3NetMgrIMPL::setLocalAddress(const struct sockaddr_storage &addr)
{ {
bool changed = false; bool changed = false;
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
if (!sockaddr_storage_same(mLocalAddr, addr)) if (!sockaddr_storage_same(mLocalAddr, addr))
{ {
changed = true; changed = true;
@ -1211,7 +1206,7 @@ bool p3NetMgrIMPL::setLocalAddress(const struct sockaddr_storage &addr)
} }
bool p3NetMgrIMPL::getExtAddress(struct sockaddr_storage& addr) bool p3NetMgrIMPL::getExtAddress(struct sockaddr_storage& addr)
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
if(mNetFlags.mExtAddrOk) if(mNetFlags.mExtAddrOk)
{ {
@ -1226,7 +1221,7 @@ bool p3NetMgrIMPL::setExtAddress(const struct sockaddr_storage &addr)
{ {
bool changed = false; bool changed = false;
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
if (!sockaddr_storage_same(mExtAddr, addr)) if (!sockaddr_storage_same(mExtAddr, addr))
{ {
changed = true; changed = true;
@ -1260,7 +1255,7 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode)
{ {
uint32_t oldNetMode; uint32_t oldNetMode;
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
/* only change TRY flags */ /* only change TRY flags */
oldNetMode = mNetMode; oldNetMode = mNetMode;
@ -1306,7 +1301,7 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode)
bool p3NetMgrIMPL::setVisState(uint16_t vs_disc, uint16_t vs_dht) bool p3NetMgrIMPL::setVisState(uint16_t vs_disc, uint16_t vs_dht)
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mVsDisc = vs_disc; mVsDisc = vs_disc;
mVsDht = vs_dht; mVsDht = vs_dht;
@ -1668,7 +1663,7 @@ void p3NetMgrIMPL::getNetStatus(pqiNetStatus &status)
uint32_t netsize = 0, rsnetsize = 0; uint32_t netsize = 0, rsnetsize = 0;
netAssistConnectStats(netsize, rsnetsize); netAssistConnectStats(netsize, rsnetsize);
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
/* quick update of the stuff that can change! */ /* quick update of the stuff that can change! */
mNetFlags.mDhtOk = dhtOk; mNetFlags.mDhtOk = dhtOk;
@ -1692,7 +1687,7 @@ void p3NetMgrIMPL::getNetStatus(pqiNetStatus &status)
bool p3NetMgrIMPL::getIPServersEnabled() bool p3NetMgrIMPL::getIPServersEnabled()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mUseExtAddrFinder; return mUseExtAddrFinder;
} }
@ -1721,12 +1716,12 @@ void p3NetMgrIMPL::setIPServersEnabled(bool b)
} }
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mUseExtAddrFinder = b; mUseExtAddrFinder = b;
} }
#ifdef NETMGR_DEBUG #ifdef NETMGR_DEBUG
RsDbg(__PRETTY_FUNCTION__, " set mUseExtAddrFinder to ", b); RS_DBG("set mUseExtAddrFinder to ", b);
#endif #endif
} }
@ -1739,31 +1734,31 @@ void p3NetMgrIMPL::setIPServersEnabled(bool b)
RsNetState p3NetMgrIMPL::getNetStateMode() RsNetState p3NetMgrIMPL::getNetStateMode()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mNetStateBox.getNetStateMode(); return mNetStateBox.getNetStateMode();
} }
RsNetworkMode p3NetMgrIMPL::getNetworkMode() RsNetworkMode p3NetMgrIMPL::getNetworkMode()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mNetStateBox.getNetworkMode(); return mNetStateBox.getNetworkMode();
} }
RsNatTypeMode p3NetMgrIMPL::getNatTypeMode() RsNatTypeMode p3NetMgrIMPL::getNatTypeMode()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mNetStateBox.getNatTypeMode(); return mNetStateBox.getNatTypeMode();
} }
RsNatHoleMode p3NetMgrIMPL::getNatHoleMode() RsNatHoleMode p3NetMgrIMPL::getNatHoleMode()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mNetStateBox.getNatHoleMode(); return mNetStateBox.getNatHoleMode();
} }
RsConnectModes p3NetMgrIMPL::getConnectModes() RsConnectModes p3NetMgrIMPL::getConnectModes()
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
return mNetStateBox.getConnectModes(); return mNetStateBox.getConnectModes();
} }
@ -1787,7 +1782,7 @@ void p3NetMgrIMPL::updateNetStateBox_temporal()
/* input network bits */ /* input network bits */
if (mDhtStunner->getExternalAddr(tmpaddr, isstable)) if (mDhtStunner->getExternalAddr(tmpaddr, isstable))
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStateBox.setAddressStunDht(tmpaddr, isstable); mNetStateBox.setAddressStunDht(tmpaddr, isstable);
#ifdef NETMGR_DEBUG_STATEBOX #ifdef NETMGR_DEBUG_STATEBOX
@ -1806,7 +1801,7 @@ void p3NetMgrIMPL::updateNetStateBox_temporal()
/* input network bits */ /* input network bits */
if (mProxyStunner->getExternalAddr(tmpaddr, isstable)) if (mProxyStunner->getExternalAddr(tmpaddr, isstable))
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStateBox.setAddressStunProxy(tmpaddr, isstable); mNetStateBox.setAddressStunProxy(tmpaddr, isstable);
#ifdef NETMGR_DEBUG_STATEBOX #ifdef NETMGR_DEBUG_STATEBOX
@ -1825,7 +1820,7 @@ void p3NetMgrIMPL::updateNetStateBox_temporal()
bool dhtOn = netAssistConnectEnabled(); bool dhtOn = netAssistConnectEnabled();
bool dhtActive = netAssistConnectActive(); bool dhtActive = netAssistConnectActive();
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStateBox.setDhtState(dhtOn, dhtActive); mNetStateBox.setDhtState(dhtOn, dhtActive);
} }
@ -1834,7 +1829,7 @@ void p3NetMgrIMPL::updateNetStateBox_temporal()
#ifdef NETMGR_DEBUG_STATEBOX #ifdef NETMGR_DEBUG_STATEBOX
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
auto netstate = mNetStateBox.getNetStateMode(); auto netstate = mNetStateBox.getNetStateMode();
auto netMode = mNetStateBox.getNetworkMode(); auto netMode = mNetStateBox.getNetworkMode();
@ -1880,7 +1875,7 @@ void p3NetMgrIMPL::updateNatSetting()
RsNatTypeMode natType = RsNatTypeMode::UNKNOWN; RsNatTypeMode natType = RsNatTypeMode::UNKNOWN;
RsNatHoleMode natHole = RsNatHoleMode::UNKNOWN; RsNatHoleMode natHole = RsNatHoleMode::UNKNOWN;
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
natType = mNetStateBox.getNatTypeMode(); natType = mNetStateBox.getNatTypeMode();
natHole = mNetStateBox.getNatHoleMode(); natHole = mNetStateBox.getNatHoleMode();
@ -1982,7 +1977,7 @@ void p3NetMgrIMPL::updateNetStateBox_startup()
std::cerr << std::endl; std::cerr << std::endl;
#endif #endif
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
/* fill in the data */ /* fill in the data */
struct sockaddr_storage tmpip; struct sockaddr_storage tmpip;
@ -2077,7 +2072,7 @@ void p3NetMgrIMPL::updateNetStateBox_startup()
void p3NetMgrIMPL::updateNetStateBox_reset() void p3NetMgrIMPL::updateNetStateBox_reset()
{ {
{ {
RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ RS_STACK_MUTEX(mNetMtx); /****** STACK LOCK MUTEX *******/
mNetStateBox.reset(); mNetStateBox.reset();

View File

@ -1293,7 +1293,11 @@ bool p3Peers::getShortInvite(std::string& invite, const RsPeerId& _sslId, Retros
} }
#else #else
sockaddr_storage tLocal; sockaddr_storage tLocal;
if(sockaddr_storage_inet_pton(tLocal, tDetails.localAddr) && sockaddr_storage_isValidNet(tLocal) && sockaddr_storage_ipv6_to_ipv4(tLocal) && tDetails.localPort ) bool validLoc = sockaddr_storage_inet_pton(tLocal, tDetails.localAddr)
&& sockaddr_storage_isValidNet(tLocal)
&& tDetails.localPort;
bool isLocIpv4 = sockaddr_storage_ipv6_to_ipv4(tLocal);
if(validLoc && isLocIpv4)
{ {
uint32_t t4Addr = reinterpret_cast<sockaddr_in&>(tLocal).sin_addr.s_addr; uint32_t t4Addr = reinterpret_cast<sockaddr_in&>(tLocal).sin_addr.s_addr;
@ -1311,8 +1315,11 @@ bool p3Peers::getShortInvite(std::string& invite, const RsPeerId& _sslId, Retros
} }
sockaddr_storage tExt; sockaddr_storage tExt;
struct in6_addr sin6_addr; bool validExt = sockaddr_storage_inet_pton(tExt, tDetails.extAddr)
if(sockaddr_storage_inet_pton(tExt, tDetails.extAddr) && sockaddr_storage_isValidNet(tExt) && sockaddr_storage_ipv6_to_ipv4(tExt) && tDetails.extPort ) && sockaddr_storage_isValidNet(tExt)
&& tDetails.extPort;
bool isExtIpv4 = sockaddr_storage_ipv6_to_ipv4(tExt);
if(validExt && isExtIpv4)
{ {
uint32_t t4Addr = reinterpret_cast<sockaddr_in&>(tExt).sin_addr.s_addr; uint32_t t4Addr = reinterpret_cast<sockaddr_in&>(tExt).sin_addr.s_addr;
@ -1328,10 +1335,11 @@ bool p3Peers::getShortInvite(std::string& invite, const RsPeerId& _sslId, Retros
offset += 4+2; offset += 4+2;
} }
else if(inet_pton(AF_INET6, tDetails.extAddr.c_str(), &(sin6_addr))) else if(validExt && !isExtIpv4)
{ {
// External address is IPv6, save it on LOCATOR // External address is IPv6, save it on LOCATOR
std::string tLocator = "ipv6://[" + tDetails.extAddr + "]:" + std::to_string(tDetails.extPort); sockaddr_storage_setport(tExt,tDetails.extPort);
std::string tLocator = sockaddr_storage_tostring(tExt);
addPacketHeader(RsShortInviteFieldType::LOCATOR, tLocator.size(),buf,offset,buf_size); addPacketHeader(RsShortInviteFieldType::LOCATOR, tLocator.size(),buf,offset,buf_size);
memcpy(&buf[offset],tLocator.c_str(),tLocator.size()); memcpy(&buf[offset],tLocator.c_str(),tLocator.size());
@ -1612,16 +1620,23 @@ std::string p3Peers::GetRetroshareInvite( const RsPeerId& sslId, RetroshareInvit
if (getPeerDetails(ssl_id, detail)) if (getPeerDetails(ssl_id, detail))
{ {
if(!(invite_flags & RetroshareInviteFlags::FULL_IP_HISTORY) || detail.isHiddenNode) if( !(invite_flags & RetroshareInviteFlags::FULL_IP_HISTORY)
|| detail.isHiddenNode)
detail.ipAddressList.clear(); detail.ipAddressList.clear();
//Check if external address is IPv6, then move it to ipAddressList as RsCertificate only allow 4 numbers. //Check if external address is IPv6, then move it to ipAddressList as RsCertificate only allow 4 numbers.
struct in6_addr sin6_addr; sockaddr_storage tExt;
if( inet_pton(AF_INET6, detail.extAddr.c_str(), &(sin6_addr)) bool validExt = sockaddr_storage_inet_pton(tExt, detail.extAddr)
&& !(invite_flags & RetroshareInviteFlags::FULL_IP_HISTORY) && sockaddr_storage_isValidNet(tExt)
&& !detail.isHiddenNode) && detail.extPort;
bool isExtIpv4 = sockaddr_storage_ipv6_to_ipv4(tExt);
if( !(invite_flags & RetroshareInviteFlags::FULL_IP_HISTORY)
&& !detail.isHiddenNode
&& validExt && !isExtIpv4)
{ {
detail.ipAddressList.push_front("ipv6://[" + detail.extAddr + "]:" + std::to_string(detail.extPort) + " "); sockaddr_storage_setport(tExt,detail.extPort);
detail.ipAddressList.push_front(sockaddr_storage_tostring(tExt) + " "); // Space needed to later parse.
detail.extAddr = ""; //Clear it to not trigg error. detail.extAddr = ""; //Clear it to not trigg error.
detail.extPort = 0; detail.extPort = 0;
} }

View File

@ -19,6 +19,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * * along with this program. If not, see <https://www.gnu.org/licenses/>. *
* * * *
*******************************************************************************/ *******************************************************************************/
//#define EXTADDRSEARCH_DEBUG
#include "extaddrfinder.h" #include "extaddrfinder.h"
#include "pqi/pqinetwork.h" #include "pqi/pqinetwork.h"
@ -43,8 +46,6 @@
const uint32_t MAX_IP_STORE = 300; /* seconds ip address timeout */ const uint32_t MAX_IP_STORE = 300; /* seconds ip address timeout */
//#define EXTADDRSEARCH_DEBUG
class ZeroInt class ZeroInt
{ {
public: public:
@ -52,129 +53,122 @@ public:
uint32_t n ; uint32_t n ;
}; };
void* doExtAddrSearch(void *p) void ExtAddrFinder::run()
{ {
std::vector<std::string> res ; std::vector<std::string> res ;
ExtAddrFinder *af = (ExtAddrFinder*)p ; for(auto& it : _ip_servers)
for(std::list<std::string>::const_iterator it(af->_ip_servers.begin());it!=af->_ip_servers.end();++it)
{ {
std::string ip = ""; std::string ip = "";
rsGetHostByNameSpecDNS(*it,"myip.opendns.com",ip,2); rsGetHostByNameSpecDNS(it,"myip.opendns.com",ip,2);
if(ip != "") if(ip != "")
res.push_back(ip) ; res.push_back(ip) ;
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " ip found through DNS ", *it, ": \"", ip, "\""); RS_DBG("ip found through DNS ", it, ": \"", ip, "\"");
#endif #endif
} }
if(res.empty()) if(res.empty())
{ {
af->reset(); reset();
return NULL ; return ;
} }
std::map<sockaddr_storage,ZeroInt> addrV4_votes; std::map<sockaddr_storage,ZeroInt> addrV4_votes;
std::map<sockaddr_storage,ZeroInt> addrV6_votes; std::map<sockaddr_storage,ZeroInt> addrV6_votes;
std::string addrV4_Found; std::string all_addrV4_Found;
std::string addrV6_Found; std::string all_addrV6_Found;
for(auto curRes : res) for(auto curRes : res)
{ {
sockaddr_storage addr; sockaddr_storage addr;
sockaddr_storage_clear(addr); sockaddr_storage_clear(addr);
//sockaddr_storage_inet_pton convert IPv4 to IPv6 bool validIP = sockaddr_storage_inet_pton(addr, curRes)
struct sockaddr_in * addrv4p = (struct sockaddr_in *) &addr; && sockaddr_storage_isValidNet(addr);
struct sockaddr_in6 * addrv6p = (struct sockaddr_in6 *) &addr; bool isIPv4 = sockaddr_storage_ipv6_to_ipv4(addr);
if( inet_pton(AF_INET, curRes.c_str(), &(addrv4p->sin_addr)) ) if( validIP && isIPv4 )
{ {
addr.ss_family = AF_INET; addr.ss_family = AF_INET;
addrV4_votes[addr].n++ ; addrV4_votes[addr].n++ ;
addrV4_Found += sockaddr_storage_tostring(addr) + "\n"; all_addrV4_Found += sockaddr_storage_tostring(addr) + "\n";
} }
else if( inet_pton(AF_INET6, curRes.c_str(), &(addrv6p->sin6_addr)) ) else if( validIP && !isIPv4)
{ {
addr.ss_family = AF_INET6; addr.ss_family = AF_INET6;
addrV6_votes[addr].n++ ; addrV6_votes[addr].n++ ;
addrV6_Found += sockaddr_storage_tostring(addr) + "\n"; all_addrV6_Found += sockaddr_storage_tostring(addr) + "\n";
} }
else else
RsErr(__PRETTY_FUNCTION__, " Invalid addresse reported: ", curRes) ; RS_ERR("Invalid addresse reported: ", curRes) ;
} }
if( (0 == addrV4_votes.size()) && (0 == addrV6_votes.size()) ) if( (0 == addrV4_votes.size()) && (0 == addrV6_votes.size()) )
{ {
RsErr(__PRETTY_FUNCTION__, " Could not find any external address."); RS_ERR("Could not find any external address.");
af->reset(); reset();
return NULL ; return ;
} }
if( 1 < addrV4_votes.size() ) if( 1 < addrV4_votes.size() )
RsErr(__PRETTY_FUNCTION__, " Multiple external IPv4 addresses reported: " RS_ERR("Multiple external IPv4 addresses reported: "
, addrV4_Found ) ; , all_addrV4_Found ) ;
if( 1 < addrV6_votes.size() ) if( 1 < addrV6_votes.size() )
RsErr(__PRETTY_FUNCTION__, " Multiple external IPv6 addresses reported: " RS_ERR("Multiple external IPv6 addresses reported: "
, addrV6_Found ) ; , all_addrV6_Found ) ;
{ {
RsStackMutex mtx(af->mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx);
af->mSearching = false ;
af->mFoundTS = time(NULL) ; mSearching = false ;
mFoundTS = time(NULL) ;
// Only save more reported address if not only once. // Only save more reported address if not only once.
uint32_t admax = 0 ; uint32_t admax = 0 ;
sockaddr_storage_clear(af->mAddrV4); sockaddr_storage_clear(mAddrV4);
for (auto it : addrV4_votes) for (auto it : addrV4_votes)
if (admax < it.second.n) if (admax < it.second.n)
{ {
af->mAddrV4 = it.first ; mAddrV4 = it.first ;
af->mFoundV4 = true ; mFoundV4 = true ;
admax = it.second.n ; admax = it.second.n ;
} }
admax = 0 ; admax = 0 ;
sockaddr_storage_clear(af->mAddrV6); sockaddr_storage_clear(mAddrV6);
for (auto it : addrV6_votes) for (auto it : addrV6_votes)
if (admax < it.second.n) if (admax < it.second.n)
{ {
af->mAddrV6 = it.first ; mAddrV6 = it.first ;
af->mFoundV6 = true ; mFoundV6 = true ;
admax = it.second.n ; admax = it.second.n ;
} }
} }
return NULL ; return ;
} }
void ExtAddrFinder::start_request() void ExtAddrFinder::start_request()
{ {
void *data = (void *)this; if (!isRunning())
pthread_t tid ; start("ExtAddrFinder");
if(! pthread_create(&tid, 0, &doExtAddrSearch, data))
pthread_detach(tid); /* so memory is reclaimed in linux */
else
RsErr(__PRETTY_FUNCTION__, " Could not start ExtAddrFinder thread.");
} }
bool ExtAddrFinder::hasValidIPV4(struct sockaddr_storage &addr) bool ExtAddrFinder::hasValidIPV4(struct sockaddr_storage &addr)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Getting ip."); RS_DBG("Getting ip.");
#endif #endif
{ {
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
if(mFoundV4) if(mFoundV4)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Has stored ip responding with this ip:", sockaddr_storage_iptostring(mAddrV4)) ; RS_DBG("Has stored ip responding with this ip:", sockaddr_storage_iptostring(mAddrV4)) ;
#endif #endif
sockaddr_storage_copyip(addr,mAddrV4); // just copy the IP so we dont erase the port. sockaddr_storage_copyip(addr,mAddrV4); // just copy the IP so we dont erase the port.
} }
@ -182,22 +176,22 @@ bool ExtAddrFinder::hasValidIPV4(struct sockaddr_storage &addr)
testTimeOut(); testTimeOut();
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
return mFoundV4; return mFoundV4;
} }
bool ExtAddrFinder::hasValidIPV6(struct sockaddr_storage &addr) bool ExtAddrFinder::hasValidIPV6(struct sockaddr_storage &addr)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Getting ip."); RS_DBG("Getting ip.");
#endif #endif
{ {
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
if(mFoundV6) if(mFoundV6)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Has stored ip responding with this ip:", sockaddr_storage_iptostring(mAddrV6)) ; RS_DBG("Has stored ip responding with this ip:", sockaddr_storage_iptostring(mAddrV6)) ;
#endif #endif
sockaddr_storage_copyip(addr,mAddrV6); // just copy the IP so we dont erase the port. sockaddr_storage_copyip(addr,mAddrV6); // just copy the IP so we dont erase the port.
} }
@ -205,7 +199,7 @@ bool ExtAddrFinder::hasValidIPV6(struct sockaddr_storage &addr)
testTimeOut(); testTimeOut();
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
return mFoundV6; return mFoundV6;
} }
@ -213,7 +207,7 @@ void ExtAddrFinder::testTimeOut()
{ {
bool timeOut; bool timeOut;
{ {
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
//timeout the current ip //timeout the current ip
timeOut = (mFoundTS + MAX_IP_STORE < time(NULL)); timeOut = (mFoundTS + MAX_IP_STORE < time(NULL));
} }
@ -223,21 +217,21 @@ void ExtAddrFinder::testTimeOut()
if(!mSearching) if(!mSearching)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " No stored ip: Initiating new search."); RS_DBG("No stored ip: Initiating new search.");
#endif #endif
mSearching = true ; mSearching = true ;
start_request() ; start_request() ;
} }
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
else else
RsDbg(__PRETTY_FUNCTION__, " Already searching."); RS_DBG("Already searching.");
#endif #endif
mFirstTime = false; mFirstTime = false;
mAddrMtx.unlock(); mAddrMtx.unlock();
} }
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
else else
RsDbg(__PRETTY_FUNCTION__, " (Note) Could not acquire lock. Busy."); RS_DBG("(Note) Could not acquire lock. Busy.");
#endif #endif
} }
} }
@ -245,15 +239,15 @@ void ExtAddrFinder::testTimeOut()
void ExtAddrFinder::reset(bool firstTime /*=false*/) void ExtAddrFinder::reset(bool firstTime /*=false*/)
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " firstTime=", firstTime?"true":"false"); RS_DBG("firstTime=", firstTime);
#endif #endif
RsStackMutex mut(mAddrMtx) ; RS_STACK_MUTEX(mAddrMtx) ;
mSearching = false ; mSearching = false ;
mFoundV4 = false ; mFoundV4 = false ;
mFoundV6 = false ; mFoundV6 = false ;
mFirstTime = firstTime; mFirstTime = firstTime;
mFoundTS = time(NULL); mFoundTS = time(nullptr);
sockaddr_storage_clear(mAddrV4); sockaddr_storage_clear(mAddrV4);
sockaddr_storage_clear(mAddrV6); sockaddr_storage_clear(mAddrV6);
} }
@ -261,15 +255,14 @@ void ExtAddrFinder::reset(bool firstTime /*=false*/)
ExtAddrFinder::~ExtAddrFinder() ExtAddrFinder::~ExtAddrFinder()
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Deleting ExtAddrFinder."); RS_DBG("Deleting ExtAddrFinder.");
#endif #endif
} }
ExtAddrFinder::ExtAddrFinder() : mAddrMtx("ExtAddrFinder") ExtAddrFinder::ExtAddrFinder() : mAddrMtx("ExtAddrFinder")
{ {
#ifdef EXTADDRSEARCH_DEBUG #ifdef EXTADDRSEARCH_DEBUG
RsDbg(__PRETTY_FUNCTION__, " Creating new ExtAddrFinder."); RS_DBG("Creating new ExtAddrFinder.");
#endif #endif
reset( true ); reset( true );
@ -283,4 +276,3 @@ ExtAddrFinder::ExtAddrFinder() : mAddrMtx("ExtAddrFinder")
_ip_servers.push_back(std::string( "2620:119:35::35" )) ;//resolver1.opendns.com _ip_servers.push_back(std::string( "2620:119:35::35" )) ;//resolver1.opendns.com
_ip_servers.push_back(std::string( "2620:119:53::53" )) ;//resolver2.opendns.com _ip_servers.push_back(std::string( "2620:119:53::53" )) ;//resolver2.opendns.com
} }

View File

@ -30,7 +30,7 @@
struct sockaddr ; struct sockaddr ;
class ExtAddrFinder class ExtAddrFinder: public RsThread
{ {
public: public:
ExtAddrFinder() ; ExtAddrFinder() ;
@ -45,7 +45,7 @@ class ExtAddrFinder
void reset(bool firstTime = false) ; void reset(bool firstTime = false) ;
private: private:
friend void* doExtAddrSearch(void *p); virtual void run();
void testTimeOut(); void testTimeOut();
RsMutex mAddrMtx; RsMutex mAddrMtx;

View File

@ -21,6 +21,7 @@
*******************************************************************************/ *******************************************************************************/
//#define DEBUG_SPEC_DNS 1 //#define DEBUG_SPEC_DNS 1
#include "util/rsnet.h" #include "util/rsnet.h"
#include "util/rsdebug.h" #include "util/rsdebug.h"
@ -101,51 +102,49 @@ struct RR_DATA
bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& hostname, std::string& returned_addr, int timeout_s /*= -1*/) bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& hostname, std::string& returned_addr, int timeout_s /*= -1*/)
{ {
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<<" servername="<< servername << " hostname=" << hostname << std::endl; RS_DBG("servername=", servername, " hostname=", hostname);
#endif #endif
if (strlen(servername.c_str()) > 256) if (strlen(servername.c_str()) > 256)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": servername is too long > 256 chars:"<<servername<<std::endl; RS_ERR("servername is too long > 256 chars: ", servername);
return false; return false;
} }
if (strlen(hostname.c_str()) > 256) if (strlen(hostname.c_str()) > 256)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": hostname is too long > 256 chars:"<<hostname<<std::endl; RS_ERR("hostname is too long > 256 chars: ", hostname);
return false; return false;
} }
bool isIPV4 = false; sockaddr_storage serverAddr;
in_addr dns_server_4; in6_addr dns_server_6; bool validServer = sockaddr_storage_inet_pton(serverAddr, servername)
if (inet_pton(AF_INET, servername.c_str(), &dns_server_4)) && sockaddr_storage_isValidNet(serverAddr);
isIPV4 = true; bool isIPV4 = validServer && sockaddr_storage_ipv6_to_ipv4(serverAddr);
else if (inet_pton(AF_INET6, servername.c_str(), &dns_server_6))
isIPV4 = false; if (!validServer)
else if (rsGetHostByName(servername, dns_server_4))
isIPV4 = true;
else
{ {
RsErr()<<__PRETTY_FUNCTION__<<": servername is on an unknow format: "<<servername<<std::endl; in_addr in ;
if (!rsGetHostByName(servername, in))
{
RS_ERR("servername is on an unknow format: ", servername);
return false; return false;
} }
unsigned char buf[65536]; validServer = sockaddr_storage_inet_pton(serverAddr, rs_inet_ntoa(in))
&& sockaddr_storage_isValidNet(serverAddr);
isIPV4 = validServer && sockaddr_storage_ipv6_to_ipv4(serverAddr);
struct sockaddr_in dest4;struct sockaddr_in6 dest6; if (!validServer)
if (isIPV4)
{ {
dest4.sin_family = AF_INET; RS_ERR("rsGetHostByName return bad answer: ", rs_inet_ntoa(in));
dest4.sin_port = htons(53); return false;
dest4.sin_addr.s_addr = dns_server_4.s_addr;
} else {
dest6.sin6_family = AF_INET6;
dest6.sin6_port = htons(53);
dest6.sin6_flowinfo = 0;
dest6.sin6_addr = dns_server_6;
dest6.sin6_scope_id = 0;
} }
}
sockaddr_storage_setport( serverAddr, 53);
//Set the DNS structure to standard queries //Set the DNS structure to standard queries
unsigned char buf[65536];
struct DNS_HEADER* dns = (struct DNS_HEADER *)&buf; struct DNS_HEADER* dns = (struct DNS_HEADER *)&buf;
dns->id = static_cast<unsigned short>(htons(getpid())); //Transaction Id dns->id = static_cast<unsigned short>(htons(getpid())); //Transaction Id
//dns flags = 0x0100 Standard Query //dns flags = 0x0100 Standard Query
@ -191,86 +190,81 @@ bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& ho
curSendSize += sizeof(struct QUESTION); curSendSize += sizeof(struct QUESTION);
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<< " Sending Packet: " << std::endl << hexDump(buf, curSendSize) << std::endl; RS_DBG("Sending Packet:\n", hexDump(buf, curSendSize));
#endif #endif
int s = isIPV4 ? socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP) int s = socket(serverAddr.ss_family , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries
: socket(AF_INET6 , SOCK_DGRAM , IPPROTO_UDP) ; //UDP packet for DNS queries
if (timeout_s > -1) if (timeout_s > -1)
{ rs_setSockTimeout(s, true, timeout_s);
#ifdef WINDOWS_SYS
DWORD timeout = timeout_s * 1000;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
#else
struct timeval tv;
tv.tv_sec = timeout_s;
tv.tv_usec = 0;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
#endif
}
ssize_t send_size = sendto( s, (char*)buf, curSendSize, 0 ssize_t send_size = sendto( s, (char*)buf, curSendSize, 0
,isIPV4 ? (struct sockaddr*)&dest4 , (struct sockaddr*)&serverAddr
: (struct sockaddr*)&dest6 , isIPV4 ? sizeof(sockaddr_in)
,isIPV4 ? sizeof(dest4) : sizeof(sockaddr_in6)
: sizeof(dest6)
); );
if( send_size < 0) if( send_size < 0)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Send Failed with size = " << send_size << std::endl; RS_ERR("Send Failed with size = ", send_size);
return false; return false;
} }
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<< " Waiting answer..." << std::endl; RS_DBG("Waiting answer...");
#endif #endif
//****************************************************************************************// //****************************************************************************************//
//--- Receive the answer ---// //--- Receive the answer ---//
//****************************************************************************************// //****************************************************************************************//
socklen_t dest_size = static_cast<socklen_t>(sizeof dest4); socklen_t sa_size = static_cast<socklen_t>(isIPV4 ? sizeof(sockaddr_in)
ssize_t rec_size=recvfrom(s,(char*)buf , 65536 , 0 , (struct sockaddr*)&dest4 , &dest_size ); : sizeof(sockaddr_in6)
);
ssize_t rec_size=recvfrom( s,(char*)buf , 65536 , 0
, (struct sockaddr*)&serverAddr
, &sa_size
);
if(rec_size <= 0) if(rec_size <= 0)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Receive Failed"<<std::endl; RS_ERR("Receive Failed");
return false; return false;
} }
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<< " Received: " << hexDump(buf, rec_size) << std::endl; RS_DBG("Received:\n", hexDump(buf, rec_size));
#endif #endif
if (rec_size< static_cast<ssize_t>(sizeof(struct DNS_HEADER)) ) if (rec_size< static_cast<ssize_t>(sizeof(struct DNS_HEADER)) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received too small to get DNSHeader."<<std::endl; RS_ERR("Request received too small to get DNSHeader.");
return false; return false;
} }
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
//Point to the header portion //Point to the header portion
dns = (struct DNS_HEADER*) buf; dns = (struct DNS_HEADER*) buf;
RsDbg()<<__PRETTY_FUNCTION__<<" The response contains : " << std::endl RS_DBG("The response contains :\n"
<<ntohs(dns->q_count) << " Questions." << std::endl ,ntohs(dns->q_count) , " Questions.\n"
<<ntohs(dns->ans_count) << " Answers." << std::endl ,ntohs(dns->ans_count) , " Answers.\n"
<<ntohs(dns->auth_count) << " Authoritative Servers." << std::endl ,ntohs(dns->auth_count) , " Authoritative Servers.\n"
<<ntohs(dns->add_count) << " Additional records." << std::endl; ,ntohs(dns->add_count) , " Additional records.");
#endif #endif
size_t curRecSize = sizeof(struct DNS_HEADER); size_t curRecSize = sizeof(struct DNS_HEADER);
if (rec_size< static_cast<ssize_t>(curRecSize + 1 + sizeof(struct QUESTION)) ) if (rec_size< static_cast<ssize_t>(curRecSize + 1 + sizeof(struct QUESTION)) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received too small to get Question return."<<std::endl; RS_ERR("Request received too small to get Question return.");
return false; return false;
} }
//Point to the query portion //Point to the query portion
unsigned char* qnameRecv =static_cast<unsigned char*>(&buf[curRecSize]); unsigned char* qnameRecv =static_cast<unsigned char*>(&buf[curRecSize]);
if (memcmp(qname,qnameRecv,qnameSize + 1 + sizeof(struct QUESTION)) ) if (memcmp(qname,qnameRecv,qnameSize + 1 + sizeof(struct QUESTION)) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received different from that sent."<<std::endl; RS_ERR("Request received different from that sent.");
return false; return false;
} }
curRecSize += qnameSize + 1 + sizeof(struct QUESTION); curRecSize += qnameSize + 1 + sizeof(struct QUESTION);
if (rec_size< static_cast<ssize_t>(curRecSize + 2) ) if (rec_size< static_cast<ssize_t>(curRecSize + 2) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received too small to get Answer return."<<std::endl; RS_ERR("Request received too small to get Answer return.");
return false; return false;
} }
//Point to the Answer portion //Point to the Answer portion
@ -290,33 +284,33 @@ bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& ho
} }
else else
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Answer received with unmanaged label format."<<std::endl; RS_ERR("Answer received with unmanaged label format.");
return false; return false;
} }
curRecSize += 2 + rLabelSize; curRecSize += 2 + rLabelSize;
if (rec_size< static_cast<ssize_t>(curRecSize + sizeof(struct RR_DATA)) ) if (rec_size< static_cast<ssize_t>(curRecSize + sizeof(struct RR_DATA)) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received too small to get Data return."<<std::endl; RS_ERR("Request received too small to get Data return.");
return false; return false;
} }
//Point to the query portion //Point to the query portion
struct RR_DATA* rec_data = (struct RR_DATA *)&buf[curRecSize]; struct RR_DATA* rec_data = (struct RR_DATA *)&buf[curRecSize];
if (rec_data->rtype!=qinfo->qtype) if (rec_data->rtype!=qinfo->qtype)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Answer's type received different from query sent."<<std::endl; RS_ERR("Answer's type received different from query sent.");
return false; return false;
} }
if (rec_data->rclass!=qinfo->qclass) if (rec_data->rclass!=qinfo->qclass)
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Answer's class received different from query sent."<<std::endl; RS_ERR("Answer's class received different from query sent.");
return false; return false;
} }
curRecSize += sizeof(struct RR_DATA); curRecSize += sizeof(struct RR_DATA);
if (rec_size< static_cast<ssize_t>(curRecSize + ntohs(rec_data->data_len)) ) if (rec_size< static_cast<ssize_t>(curRecSize + ntohs(rec_data->data_len)) )
{ {
RsErr()<<__PRETTY_FUNCTION__<<": Request received too small to get Full Data return."<<std::endl; RS_ERR("Request received too small to get Full Data return.");
return false; return false;
} }
@ -328,7 +322,7 @@ bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& ho
in_addr ipv4Add; in_addr ipv4Add;
ipv4Add.s_addr=*(in_addr_t*)&buf[curRecSize]; ipv4Add.s_addr=*(in_addr_t*)&buf[curRecSize];
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<< " Retrieve address: " << rs_inet_ntoa(ipv4Add) << std::endl; RS_DBG("Retrieve address: ", rs_inet_ntoa(ipv4Add));
#endif #endif
returned_addr = rs_inet_ntoa(ipv4Add); returned_addr = rs_inet_ntoa(ipv4Add);
return true; return true;
@ -348,13 +342,13 @@ bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& ho
sockaddr_storage_setipv6(ss,&addr_ipv6); sockaddr_storage_setipv6(ss,&addr_ipv6);
#ifdef DEBUG_SPEC_DNS #ifdef DEBUG_SPEC_DNS
RsDbg()<<__PRETTY_FUNCTION__<< " Retrieve address: " << sockaddr_storage_iptostring(ss).c_str() << std::endl; RS_DBG("Retrieve address: ", sockaddr_storage_iptostring(ss).c_str());
#endif #endif
returned_addr = sockaddr_storage_iptostring(ss); returned_addr = sockaddr_storage_iptostring(ss);
return true; return true;
} }
} }
RsErr()<<__PRETTY_FUNCTION__<< " Retrieve unmanaged data size=" << ntohs(rec_data->data_len) << std::endl; RS_ERR("Retrieve unmanaged data size=", ntohs(rec_data->data_len));
return false; return false;
} }

View File

@ -174,3 +174,17 @@ std::string rs_inet_ntoa(struct in_addr in)
rs_sprintf(str, "%u.%u.%u.%u", (int) bytes[0], (int) bytes[1], (int) bytes[2], (int) bytes[3]); rs_sprintf(str, "%u.%u.%u.%u", (int) bytes[0], (int) bytes[1], (int) bytes[2], (int) bytes[3]);
return str; return str;
} }
int rs_setSockTimeout( int sockfd, bool forReceive /*= true*/
, int timeout_Sec /*= 0*/, int timeout_uSec /*= 0*/)
{
#ifdef WINDOWS_SYS
DWORD timeout = timeout_Sec * 1000 + timeout_uSec;
#else
struct timeval timeout;
timeout.tv_sec = timeout_Sec;
timeout.tv_usec = timeout_uSec;
#endif
return setsockopt( sockfd, SOL_SOCKET, forReceive ? SO_RCVTIMEO : SO_SNDTIMEO
, (const char*)&timeout, sizeof timeout);
}

View File

@ -84,9 +84,16 @@ bool isExternalNet(const struct in_addr *addr);
// uses a re-entrant version of gethostbyname // uses a re-entrant version of gethostbyname
bool rsGetHostByName(const std::string& hostname, in_addr& returned_addr) ; bool rsGetHostByName(const std::string& hostname, in_addr& returned_addr) ;
// Get hostName address using specific DNS server /**
// Using it allow to direct ask our Address to IP, so no need to have a DNS (IPv4 or IPv6 ???). * @brief Get hostName address using specific DNS server.
// If we ask to a IPv6 DNS Server, it respond for our IPv6 address. * Using it allow to direct ask our Address to IP, so no need to have a DNS (IPv4 or IPv6).
* If we ask to a IPv6 DNS Server, it respond for our IPv6 address.
* @param servername: Address or name of DNS Server.
* @param hostname: HosteName to get IP ("myip.opendns.com" to get own).
* @param returned_addr: returned IP of hostname.
* @param timeout_s: Timeout in sec to wait server response.
* @return True in success.
*/
bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& hostname, std::string& returned_addr, int timeout_s = -1); bool rsGetHostByNameSpecDNS(const std::string& servername, const std::string& hostname, std::string& returned_addr, int timeout_s = -1);
std::ostream& operator<<(std::ostream& o, const sockaddr_in&); std::ostream& operator<<(std::ostream& o, const sockaddr_in&);
@ -164,4 +171,14 @@ bool sockaddr_storage_inet_ntop(const sockaddr_storage &addr, std::string &dst);
int rs_setsockopt( int sockfd, int level, int optname, int rs_setsockopt( int sockfd, int level, int optname,
const uint8_t *optval, uint32_t optlen ); const uint8_t *optval, uint32_t optlen );
/**
* @brief Set socket Timeout.
* @param sockfd: The socket to manage.
* @param forReceive: True for Receive, False for Send.
* @param timeout_Sec: Timeout second part.
* @param timeout_uSec: Timeout micro second part.
* @return 0 on success, -1 for errors.
*/
int rs_setSockTimeout( int sockfd, bool forReceive = true, int timeout_Sec = 0, int timeout_uSec = 0);
#endif /* RS_UNIVERSAL_NETWORK_HEADER */ #endif /* RS_UNIVERSAL_NETWORK_HEADER */

View File

@ -233,8 +233,7 @@ bool sockaddr_storage_setport(struct sockaddr_storage &addr, uint16_t port)
bool sockaddr_storage_setipv4(struct sockaddr_storage &addr, const sockaddr_in *addr_ipv4) bool sockaddr_storage_setipv4(struct sockaddr_storage &addr, const sockaddr_in *addr_ipv4)
{ {
#ifdef SS_DEBUG #ifdef SS_DEBUG
std::cerr << "sockaddr_storage_setipv4()"; RS_ERR();
std::cerr << std::endl;
#endif #endif
sockaddr_storage_clear(addr); sockaddr_storage_clear(addr);
@ -249,7 +248,9 @@ bool sockaddr_storage_setipv4(struct sockaddr_storage &addr, const sockaddr_in *
bool sockaddr_storage_setipv6(struct sockaddr_storage &addr, const sockaddr_in6 *addr_ipv6) bool sockaddr_storage_setipv6(struct sockaddr_storage &addr, const sockaddr_in6 *addr_ipv6)
{ {
std::cerr << "sockaddr_storage_setipv6()" << std::endl; #ifdef SS_DEBUG
RS_ERR();
#endif
sockaddr_storage_clear(addr); sockaddr_storage_clear(addr);
struct sockaddr_in6 *ipv6_ptr = to_ipv6_ptr(addr); struct sockaddr_in6 *ipv6_ptr = to_ipv6_ptr(addr);

View File

@ -459,6 +459,7 @@ void ServerPage::load()
whileBlocking(ui.ipAddressList)->clear(); whileBlocking(ui.ipAddressList)->clear();
detail.ipAddressList.sort();
for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it)
whileBlocking(ui.ipAddressList)->addItem(QString::fromStdString(*it)); whileBlocking(ui.ipAddressList)->addItem(QString::fromStdString(*it));
@ -827,7 +828,7 @@ void ServerPage::ipWhiteListContextMenu(const QPoint& /* point */)
// QString range0 = RsNetUtil::printAddrRange(addr,0) ; // QString range0 = RsNetUtil::printAddrRange(addr,0) ;
// QString range1 = RsNetUtil::printAddrRange(addr,1) ; // QString range1 = RsNetUtil::printAddrRange(addr,1) ;
// QString range2 = RsNetUtil::printAddrRange(addr,2) ; // QString range2 = RsNetUtil::printAddrRange(addr,2) ;
//
// contextMenu.addAction(QObject::tr("Whitelist only IP " )+range0,this,SLOT(enableBannedIp()))->setEnabled(false) ; // contextMenu.addAction(QObject::tr("Whitelist only IP " )+range0,this,SLOT(enableBannedIp()))->setEnabled(false) ;
//#warning UNIMPLEMENTED CODE //#warning UNIMPLEMENTED CODE
// contextMenu.addAction(QObject::tr("Whitelist entire range ")+range1,this,SLOT(enableBannedIp()))->setEnabled(false) ; // contextMenu.addAction(QObject::tr("Whitelist entire range ")+range1,this,SLOT(enableBannedIp()))->setEnabled(false) ;
@ -1180,6 +1181,7 @@ void ServerPage::loadHiddenNode()
// show what we have in ipAddresses. (should be nothing!) // show what we have in ipAddresses. (should be nothing!)
ui.ipAddressList->clear(); ui.ipAddressList->clear();
detail.ipAddressList.sort();
for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it)
whileBlocking(ui.ipAddressList)->addItem(QString::fromStdString(*it)); whileBlocking(ui.ipAddressList)->addItem(QString::fromStdString(*it));