Skip to content

Commit

Permalink
Use AsData and AsString more uniformly in Darwin code.
Browse files Browse the repository at this point in the history
Also adds error-checking for when AsString fails due to the string not actually
being valid UTF-8.
  • Loading branch information
bzbarsky-apple committed May 26, 2023
1 parent 58420de commit a489475
Show file tree
Hide file tree
Showing 14 changed files with 1,043 additions and 500 deletions.
25 changes: 14 additions & 11 deletions src/darwin/Framework/CHIP/MTRBaseDevice.mm
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
#import "MTRFramework.h"
#import "MTRLogging_Internal.h"
#import "MTRSetupPayload_Internal.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include "app/ConcreteAttributePath.h"
#include "app/ConcreteCommandPath.h"
Expand Down Expand Up @@ -522,26 +524,27 @@ id _Nullable MTRDecodeDataValueDictionaryFromCHIPTLV(chip::TLV::TLVReader * data
dictionaryWithObjectsAndKeys:MTRDoubleValueType, MTRTypeKey, [NSNumber numberWithDouble:val], MTRValueKey, nil];
}
case chip::TLV::kTLVType_UTF8String: {
uint32_t len = data->GetLength();
const uint8_t * ptr;
CHIP_ERROR err = data->GetDataPtr(ptr);
CharSpan stringValue;
CHIP_ERROR err = data->Get(stringValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String decoding failed", chip::ErrorStr(err));
return nil;
}
return [NSDictionary dictionaryWithObjectsAndKeys:MTRUTF8StringValueType, MTRTypeKey,
[[NSString alloc] initWithBytes:ptr length:len encoding:NSUTF8StringEncoding], MTRValueKey, nil];
NSString * stringObj = AsString(stringValue);
if (stringObj == nil) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String value is not actually UTF-8", err.AsString());
return nil;
}
return @{ MTRTypeKey: MTRUTF8StringValueType, MTRValueKey: stringObj };
}
case chip::TLV::kTLVType_ByteString: {
uint32_t len = data->GetLength();
const uint8_t * ptr;
CHIP_ERROR err = data->GetDataPtr(ptr);
ByteSpan bytesValue;
CHIP_ERROR err = data->Get(bytesValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV ByteString decoding failed", chip::ErrorStr(err));
return nil;
}
return [NSDictionary dictionaryWithObjectsAndKeys:MTROctetStringValueType, MTRTypeKey,
[NSData dataWithBytes:ptr length:len], MTRValueKey, nil];
return @{ MTRTypeKey: MTROctetStringValueType, MTRValueKey: AsData(bytesValue) };
}
case chip::TLV::kTLVType_Null: {
return [NSDictionary dictionaryWithObjectsAndKeys:MTRNullValueType, MTRTypeKey, nil];
Expand Down Expand Up @@ -653,7 +656,7 @@ static CHIP_ERROR MTREncodeTLVFromDataValueDictionary(id object, chip::TLV::TLVW
MTR_LOG_ERROR("Error: Object to encode has corrupt UTF8 string type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.PutString(tag, [value cStringUsingEncoding:NSUTF8StringEncoding]);
return writer.PutString(tag, [value UTF8String]);
}
if ([typeName isEqualToString:MTROctetStringValueType]) {
if (![value isKindOfClass:[NSData class]]) {
Expand Down
2 changes: 1 addition & 1 deletion src/darwin/Framework/CHIP/MTRFabricInfo.mm
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ - (instancetype)initWithFabricTable:(const FabricTable &)fabricTable fabricInfo:
return nil;
}

_rootPublicKey = [NSData dataWithBytes:publicKey.ConstBytes() length:publicKey.Length()];
_rootPublicKey = AsData(ByteSpan(publicKey.ConstBytes(), publicKey.Length()));

_vendorID = @(fabricInfo.GetVendorId());
_fabricID = @(fabricInfo.GetFabricId());
Expand Down
14 changes: 10 additions & 4 deletions src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#import "MTRDeviceController_Internal.h"
#import "NSDataSpanConversion.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <app/clusters/ota-provider/ota-provider.h>
#include <controller/CHIPDeviceController.h>
Expand Down Expand Up @@ -232,8 +233,13 @@ CHIP_ERROR OnTransferSessionBegin(TransferSession::OutputEvent & event)
uint16_t fdl = 0;
auto fd = mTransfer.GetFileDesignator(fdl);
VerifyOrReturnError(fdl <= bdx::kMaxFileDesignatorLen, CHIP_ERROR_INVALID_ARGUMENT);
CharSpan fileDesignatorSpan(Uint8::to_const_char(fd), fdl);

auto fileDesignator = AsString(fileDesignatorSpan);
if (fileDesignator == nil) {
return CHIP_ERROR_INCORRECT_STATE;
}

auto fileDesignator = [[NSString alloc] initWithBytes:fd length:fdl encoding:NSUTF8StringEncoding];
auto offset = @(mTransfer.GetStartOffset());

auto * controller = [[MTRDeviceControllerFactory sharedInstance] runningControllerForFabricIndex:mFabricIndex.Value()];
Expand Down Expand Up @@ -566,7 +572,7 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
auto * desc = [error description];
auto err = [MTRError errorToCHIPErrorCode:error];
ChipLogError(Controller, "%s: application returned error: '%s', sending error: '%s'", prefix,
[desc cStringUsingEncoding:NSUTF8StringEncoding], chip::ErrorStr(err));
desc.UTF8String, err.AsString());

handler->AddStatus(cachedCommandPath, StatusIB(err).mStatus);
handle.Release();
Expand Down Expand Up @@ -636,7 +642,7 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
VerifyOrReturn(handler != nullptr);

ChipLogDetail(Controller, "QueryImage: application responded with: %s",
[[data description] cStringUsingEncoding:NSUTF8StringEncoding]);
[[data description] UTF8String]);

auto hasUpdate = [data.status isEqual:@(MTROtaSoftwareUpdateProviderOTAQueryStatusUpdateAvailable)];
auto isBDXProtocolSupported = [commandParams.protocolsSupported
Expand Down Expand Up @@ -763,7 +769,7 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
VerifyOrReturn(handler != nullptr);

ChipLogDetail(Controller, "ApplyUpdateRequest: application responded with: %s",
[[data description] cStringUsingEncoding:NSUTF8StringEncoding]);
[[data description] UTF8String]);

Commands::ApplyUpdateResponse::Type response;
ConvertFromApplyUpdateRequestResponseParms(data, response);
Expand Down
5 changes: 4 additions & 1 deletion src/darwin/Framework/CHIP/MTRP256KeypairBridge.mm
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@

#import "MTRKeypair.h"
#import "MTRLogging_Internal.h"
#import "NSDataSpanConversion.h"

#include <lib/support/Span.h>

using namespace chip::Crypto;

Expand Down Expand Up @@ -82,7 +85,7 @@
MTR_LOG_ERROR("ECDSA sign msg failure: no keypair to sign with.");
return CHIP_ERROR_INCORRECT_STATE;
}
NSData * msgData = [NSData dataWithBytes:msg length:msg_length];
NSData * msgData = AsData(chip::ByteSpan(msg, msg_length));
NSData * signature;
if ([mKeypair respondsToSelector:@selector(signMessageECDSA_DER:)]) {
signature = [mKeypair signMessageECDSA_DER:msgData];
Expand Down
11 changes: 6 additions & 5 deletions src/darwin/Framework/CHIP/MTRThreadOperationalDataset.mm
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

#import "MTRThreadOperationalDataset.h"
#import "NSDataSpanConversion.h"

#include "MTRLogging_Internal.h"
#include <lib/support/Span.h>
Expand Down Expand Up @@ -62,7 +63,7 @@ - (instancetype _Nullable)initWithNetworkName:(NSString *)networkName
- (BOOL)_populateCppOperationalDataset
{
_cppThreadOperationalDataset.Clear();
_cppThreadOperationalDataset.SetNetworkName([self.networkName cStringUsingEncoding:NSUTF8StringEncoding]);
_cppThreadOperationalDataset.SetNetworkName(self.networkName.UTF8String);

if (![self _checkDataLength:self.extendedPANID expectedLength:MTRSizeThreadExtendedPANID]) {
MTR_LOG_ERROR("Invalid ExtendedPANID");
Expand Down Expand Up @@ -137,17 +138,17 @@ - (instancetype _Nullable)initWithData:(NSData *)data
panID = CFSwapInt16BigToHost(panID);

return [self initWithNetworkName:[NSString stringWithUTF8String:networkName]
extendedPANID:[NSData dataWithBytes:extendedPANID length:MTRSizeThreadExtendedPANID]
masterKey:[NSData dataWithBytes:masterKey length:MTRSizeThreadMasterKey]
PSKc:[NSData dataWithBytes:pskc length:MTRSizeThreadPSKc]
extendedPANID:AsData(chip::ByteSpan(extendedPANID))
masterKey:AsData(chip::ByteSpan(masterKey))
PSKc:AsData(chip::ByteSpan(pskc))
channelNumber:@(channel)
panID:[NSData dataWithBytes:&panID length:sizeof(uint16_t)]];
}

- (NSData *)data
{
chip::ByteSpan span = _cppThreadOperationalDataset.AsByteSpan();
return [NSData dataWithBytes:span.data() length:span.size()];
return AsData(span);
}

@end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#import "MTRAttributeTLVValueDecoder_Internal.h"

#import "MTRStructsObjc.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <app/data-model/Decode.h>
#include <app/data-model/DecodableList.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#import "MTRStructsObjc.h"
#import "MTRCommandPayloadsObjc.h"
#import "MTRCommandPayloads_Internal.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <lib/support/TypeTraits.h>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
#import "MTRBaseDevice_Internal.h"
#import "MTRError_Internal.h"
#import "MTRLogging_Internal.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <lib/core/TLV.h>
#include <app/data-model/Decode.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#import "MTREventTLVValueDecoder_Internal.h"

#import "MTRStructsObjc.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <app/data-model/Decode.h>
#include <app/data-model/DecodableList.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,14 @@
{{#if_is_strongly_typed_bitmap type}}
{{target}} = [NSNumber numberWith{{asObjectiveCNumberType "" type false}}:{{source}}.Raw()];
{{else if (isOctetString type)}}
{{target}} = [NSData dataWithBytes:{{source}}.data() length:{{source}}.size()];
{{target}} = AsData({{source}});
{{else if (isCharString type)}}
{{target}} = [[NSString alloc] initWithBytes:{{source}}.data() length:{{source}}.size() encoding:NSUTF8StringEncoding];
{{target}} = AsString({{source}});
if ({{target}} == nil) {
{{! Invalid UTF-8. Just make up an error for now. }}
CHIP_ERROR err = CHIP_ERROR_INVALID_ARGUMENT;
{{errorCode}}
}
{{else}}
{{target}} = [NSNumber numberWith{{asObjectiveCNumberType "" type false}}:{{source}}];
{{/if_is_strongly_typed_bitmap}}
Expand Down
Loading

0 comments on commit a489475

Please sign in to comment.