Browse Source

spaces in hex input were not being ignored, causing incorrect values

git-svn-id: svn://bind10.isc.org/svn/bind10/trunk@1315 e5f2f494-b856-4b98-b285-d166d9295462
Evan Hunt 15 years ago
parent
commit
6950466ea2
2 changed files with 32 additions and 8 deletions
  1. 26 8
      src/lib/dns/hex.cc
  2. 6 0
      src/lib/dns/tests/hex_unittest.cc

+ 26 - 8
src/lib/dns/hex.cc

@@ -55,25 +55,46 @@ encodeHex(const std::vector<uint8_t>& binary)
 void
 decodeHex(const std::string& hex, std::vector<uint8_t>& result)
 {
+    ostringstream comp;
+
+    // compress input by removing whitespace
+    size_t len = hex.length();
+    for (int i = 0; i < len; i++) {
+        char c = hex.at(i);
+        if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
+            continue;
+        }
+        comp << c;
+    }
+
+    istringstream iss(comp.str());
     result.clear();
-    std::istringstream iss(hex);
     char c1, c2;
     uint8_t n;
 
     iss.width(1);
-    if ((hex.size() % 2) == 1) {
+    if ((comp.str().length() % 2) == 1) {
+        c2 = '0';
         iss >> c2;
+
         const char* pos = strchr(hexdigits, toupper(c2));
         if (!pos) {
             isc_throw (BadHexString, "Invalid hex digit");
         }
 
-        n = pos - hexdigits;
-        result.push_back(n);
+        if (!iss.eof() && !iss.bad() && !iss.fail()) {
+            n = pos - hexdigits;
+            result.push_back(n);
+        }
     }
     while (!iss.eof()) {
+        c1 = c2 = '0';
         iss >> c1 >> c2;;
 
+        if (iss.eof() || iss.fail() || iss.bad()) {
+            break;
+        }
+
         const char* pos1 = strchr(hexdigits, toupper(c1));
         const char* pos2 = strchr(hexdigits, toupper(c2));
         if (!pos1 || !pos2) {
@@ -82,10 +103,7 @@ decodeHex(const std::string& hex, std::vector<uint8_t>& result)
 
         n = (pos1 - hexdigits) << 4;
         n |= (pos2 - hexdigits);
-
-        if (!iss.bad() && !iss.fail()) {
-            result.push_back(n);
-        }
+        result.push_back(n);
     }
 }
 

+ 6 - 0
src/lib/dns/tests/hex_unittest.cc

@@ -36,6 +36,7 @@ protected:
 };
 
 const std::string hex_txt("DEADBEEFDECADE");
+const std::string hex_txt_space("DEAD BEEF DECADE");
 const std::string hex_txt_lower("deadbeefdecade");
 
 TEST_F(HexTest, encodeHex) {
@@ -74,6 +75,11 @@ TEST_F(HexTest, decodeHex) {
     decodeHex(hex_txt_lower, result);
     compareData(result);
 
+    // white space should be ignored
+    result.clear();
+    decodeHex(hex_txt_space, result);
+    compareData(result);
+
     // Bogus input: should fail
     result.clear();
     EXPECT_THROW(decodeHex("1x", result), BadHexString);