3 * Copyright (c) 2021 Project CHIP Authors
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include <core/CHIPEncoding.h>
19 #include <support/SafeInt.h>
20 #include <transport/StorablePeerConnection.h>
24 StorablePeerConnection::StorablePeerConnection(PASESession & session, Transport::AdminId admin)
26 session.ToSerializable(mSession.mOpCreds);
27 mSession.mAdmin = Encoding::LittleEndian::HostSwap16(admin);
28 mKeyId = session.GetLocalKeyId();
31 CHIP_ERROR StorablePeerConnection::StoreIntoKVS(PersistentStorageDelegate & kvs)
34 ReturnErrorOnFailure(GenerateKey(mKeyId, key, sizeof(key)));
36 return kvs.SyncSetKeyValue(key, &mSession, sizeof(mSession));
39 CHIP_ERROR StorablePeerConnection::FetchFromKVS(PersistentStorageDelegate & kvs, uint16_t keyId)
42 ReturnErrorOnFailure(GenerateKey(keyId, key, sizeof(key)));
44 uint16_t size = sizeof(mSession);
45 return kvs.SyncGetKeyValue(key, &mSession, size);
48 CHIP_ERROR StorablePeerConnection::DeleteFromKVS(PersistentStorageDelegate & kvs, uint16_t keyId)
51 ReturnErrorOnFailure(GenerateKey(keyId, key, sizeof(key)));
53 kvs.AsyncDeleteKeyValue(key);
57 constexpr size_t StorablePeerConnection::KeySize()
59 return sizeof(kStorablePeerConnectionKeyPrefix) + 2 * sizeof(uint16_t);
62 CHIP_ERROR StorablePeerConnection::GenerateKey(uint16_t id, char * key, size_t len)
64 VerifyOrReturnError(len >= KeySize(), CHIP_ERROR_INVALID_ARGUMENT);
65 int keySize = snprintf(key, len, "%s%x", kStorablePeerConnectionKeyPrefix, id);
66 VerifyOrReturnError(keySize > 0, CHIP_ERROR_INTERNAL);
67 VerifyOrReturnError(len > (size_t) keySize, CHIP_ERROR_INTERNAL);