From 19e8d7be42039724b4893515ec6457d0187024a9 Mon Sep 17 00:00:00 2001 From: "Wladimir J. van der Laan" Date: Tue, 26 May 2015 08:59:13 +0200 Subject: Simplify code for CSubnet Simplify the code by using CAddress.ip directly, instead of the reversed GetByte() semantics. --- src/netbase.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'src/netbase.cpp') diff --git a/src/netbase.cpp b/src/netbase.cpp index 2015d0271..b765b35ee 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -1252,12 +1252,12 @@ CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup) std::string strNetmask = strSubnet.substr(slash + 1); int32_t n; // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n - int noffset = network.IsIPv4() ? (12 * 8) : 0; + const int astartofs = network.IsIPv4() ? 12 : 0; if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex { - if(n >= 0 && n <= (128 - noffset)) // Only valid if in range of bits of address + if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address { - n += noffset; + n += astartofs*8; // Clear bits [n..127] for (; n < 128; ++n) netmask[n>>3] &= ~(1<<(n&7)); @@ -1271,12 +1271,10 @@ CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup) { if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask { - // Remember: GetByte returns bytes in reversed order // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as // we don't want pchIPv4 to be part of the mask. - int asize = network.IsIPv4() ? 4 : 16; - for(int x=0; x Date: Tue, 26 May 2015 08:59:20 +0200 Subject: Fix two problems in CSubNet parsing Fix two CSubNet constructor problems: - The use of `/x` where 8 does not divide x was broken, due to a bit-order issue - The use of e.g. `1.2.3.4/24` where the netmasked bits in the network are not 0 was broken. Fix this by explicitly normalizing the netwok according to the bitmask. Also add tests for these cases. Fixes #6179. Thanks to @jonasschnelli for reporting and initial fix. --- src/netbase.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src/netbase.cpp') diff --git a/src/netbase.cpp b/src/netbase.cpp index b765b35ee..41cc18d3c 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -1260,7 +1260,7 @@ CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup) n += astartofs*8; // Clear bits [n..127] for (; n < 128; ++n) - netmask[n>>3] &= ~(1<<(n&7)); + netmask[n>>3] &= ~(1<<(7-(n&7))); } else { @@ -1287,6 +1287,10 @@ CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup) { valid = false; } + + // Normalize network according to netmask + for(int x=0; x<16; ++x) + network.ip[x] &= netmask[x]; } bool CSubNet::Match(const CNetAddr &addr) const -- cgit v1.2.3