From 10750020fcfa62b6948b4ec2aea0611d13dddf45 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 18 Nov 2021 10:47:32 -0500 Subject: [PATCH] Cleanup darwin usage of strtok and strncpy in DNS implementation (#11934) * Update DnssdImpl for darwin * Replace one more instance of strncpy with copystring * Restyle fixes * Use platform namespace prefix for CopyString * Use a memcpy for sometthing that is not a string * add a limit to valuelen on txt records * Validate value lenght - 0 size value should not copy anything * Restyle fixes * Fix off by one memcpy --- src/platform/Darwin/DnssdImpl.cpp | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/platform/Darwin/DnssdImpl.cpp b/src/platform/Darwin/DnssdImpl.cpp index 8915c3d1d340e4..8cb8d609e74f41 100644 --- a/src/platform/Darwin/DnssdImpl.cpp +++ b/src/platform/Darwin/DnssdImpl.cpp @@ -312,19 +312,22 @@ void OnBrowseAdd(BrowseContext * context, const char * name, const char * type, VerifyOrReturn(strcmp(kLocalDot, domain) == 0); - char * tokens = strdup(type); - char * regtype = strtok(tokens, "."); - free(tokens); - DnssdService service = {}; service.mInterface = interfaceId; service.mProtocol = context->protocol; - strncpy(service.mName, name, sizeof(service.mName)); - service.mName[Common::kInstanceNameMaxLength] = 0; + Platform::CopyString(service.mName, name); + Platform::CopyString(service.mType, type); - strncpy(service.mType, regtype, sizeof(service.mType)); - service.mType[kDnssdTypeMaxSize] = 0; + // only the first token after '.' should be included in the type + for (char * p = service.mType; *p != '\0'; p++) + { + if (*p == '.') + { + *p = '\0'; + break; + } + } context->services.push_back(service); } @@ -426,7 +429,12 @@ static CHIP_ERROR GetAddrInfo(void * context, DnssdResolveCallback callback, uin err = TXTRecordGetItemAtIndex(txtLen, txtRecord, i, kDnssdKeyMaxSize, key, &valueLen, &valuePtr); VerifyOrReturnError(CheckForSuccess(sdCtx, __func__, err, true), CHIP_ERROR_INTERNAL); - strncpy(value, reinterpret_cast(valuePtr), valueLen); + if (valueLen >= sizeof(value)) + { + // Truncation, but nothing better we can do + valueLen = sizeof(value) - 1; + } + memcpy(value, valuePtr, valueLen); value[valueLen] = 0; sdCtx->textEntries.push_back(TextEntry{ strdup(key), reinterpret_cast(strdup(value)), valueLen });