From cfe2999c942366ee5afed4827ce7c06178b5b10a Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Sat, 8 Nov 2025 11:25:23 -0800 Subject: [PATCH] [dns] update `Name::ValidateName()` for max-length names (#12127) `ValidateName()` did not correctly handle names that were exactly the maximum allowed length (`kMaxNameLength`). A name of this length is only valid if it ends with a trailing dot. Otherwise, when encoded, the added root label causes the encoded name to exceed the `kMaxEncodedLength` of 255 bytes. This commit updates `ValidateName()` to enforce that any name with length equal to `kMaxNameLength` must end with a dot character. It also updates the `TestDnsName` unit test to verify this corrected behavior, ensuring `ValidateName()` and `AppendName()` handle such names consistently. --- src/core/net/dns_types.cpp | 9 +++++++++ tests/unit/test_dns.cpp | 10 ++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/core/net/dns_types.cpp b/src/core/net/dns_types.cpp index c8d1c5bab..1d3a89aae 100644 --- a/src/core/net/dns_types.cpp +++ b/src/core/net/dns_types.cpp @@ -775,6 +775,15 @@ Error Name::ValidateName(const char *aName) VerifyOrExit(length > 0, error = kErrorInvalidArgs); VerifyOrExit(length <= kMaxNameLength, error = kErrorInvalidArgs); + if (length == kMaxNameLength) + { + // Allow `kMaxNameLength` only if the `aName` ends with a dot. + // This ensures that the encoded name always fits within the + // `kMaxEncodedLength = 255` octets. + + VerifyOrExit(aName[length - 1] == kLabelSeparatorChar, error = kErrorInvalidArgs); + } + do { ch = aName[index]; diff --git a/tests/unit/test_dns.cpp b/tests/unit/test_dns.cpp index 860a4469d..38410da46 100644 --- a/tests/unit/test_dns.cpp +++ b/tests/unit/test_dns.cpp @@ -485,9 +485,13 @@ void TestDnsName(void) IgnoreError(message->SetLength(0)); - printf("\"%s\"\n", maxLengthName); + printf("\"%s\" (len:%u)\n", maxLengthName, static_cast(strlen(maxLengthName))); + + SuccessOrQuit(Dns::Name::ValidateName(maxLengthName)); SuccessOrQuit(Dns::Name::AppendName(maxLengthName, *message)); + + VerifyOrQuit(message->GetLength() == Dns::Name::kMaxNameSize); } printf("----------------------------------------------------------------\n"); @@ -497,7 +501,9 @@ void TestDnsName(void) { IgnoreError(message->SetLength(0)); - printf("\"%s\"\n", invalidName); + printf("\"%s\" (len:%u)\n", invalidName, static_cast(strlen(invalidName))); + + VerifyOrQuit(Dns::Name::ValidateName(invalidName) != kErrorNone); VerifyOrQuit(Dns::Name::AppendName(invalidName, *message) == kErrorInvalidArgs); }