From 2430e53c333708e064b4cb3ed166dc95b7623fd7 Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Mon, 1 Jul 2019 18:49:37 +0200 Subject: [PATCH] Don't create temporary strings to escape DNSName labels --- pdns/dnsname.cc | 27 +++++++++++++-------------- pdns/dnsname.hh | 3 +-- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/pdns/dnsname.cc b/pdns/dnsname.cc index 2eb1d9a12..68ce0d2d1 100644 --- a/pdns/dnsname.cc +++ b/pdns/dnsname.cc @@ -177,7 +177,8 @@ std::string DNSName::toString(const std::string& separator, const bool trailing) const char* end = p + d_storage.size(); while (p < end && *p) { - ret += escapeLabel(p + 1, static_cast(*p)) + separator; + appendEscapedLabel(ret, p + 1, static_cast(*p)); + ret += separator; p += *p + 1; } } @@ -430,29 +431,27 @@ size_t hash_value(DNSName const& d) return d.hash(); } -string DNSName::escapeLabel(const std::string& label) +void DNSName::appendEscapedLabel(std::string& appendTo, const char* orig, size_t len) { - return escapeLabel(label.c_str(), label.size()); -} - -string DNSName::escapeLabel(const char* orig, size_t len) -{ - std::string ret; size_t pos = 0; - ret.reserve(len); while (pos < len) { auto p = static_cast(orig[pos]); if(p=='.') - ret+="\\."; + appendTo+="\\."; else if(p=='\\') - ret+="\\\\"; + appendTo+="\\\\"; else if(p > 0x20 && p < 0x7f) - ret.append(1, (char)p); + appendTo.append(1, (char)p); else { - ret+="\\" + (boost::format("%03d") % (unsigned int)p).str(); + char buf[] = "000"; + auto got = snprintf(buf, sizeof(buf), "%03" PRIu8, p); + if (got < 0 || static_cast(got) >= sizeof(buf)) { + throw std::runtime_error("Error, snprintf returned " + std::to_string(got) + " while escaping label " + std::string(orig, len)); + } + appendTo.append(1, '\\'); + appendTo += buf; } ++pos; } - return ret; } diff --git a/pdns/dnsname.hh b/pdns/dnsname.hh index 5b571085e..68d17f7c4 100644 --- a/pdns/dnsname.hh +++ b/pdns/dnsname.hh @@ -150,8 +150,7 @@ private: string_t d_storage; void packetParser(const char* p, int len, int offset, bool uncompress, uint16_t* qtype, uint16_t* qclass, unsigned int* consumed, int depth, uint16_t minOffset); - static std::string escapeLabel(const std::string& orig); - static std::string escapeLabel(const char* orig, size_t len); + static void appendEscapedLabel(std::string& appendTo, const char* orig, size_t len); static std::string unescapeLabel(const std::string& orig); }; -- 2.40.0