Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / transport / StorablePeerConnection.cpp
1 /*
2  *
3  *    Copyright (c) 2021 Project CHIP Authors
4  *
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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #include <core/CHIPEncoding.h>
19 #include <support/SafeInt.h>
20 #include <transport/StorablePeerConnection.h>
21
22 namespace chip {
23
24 StorablePeerConnection::StorablePeerConnection(PASESession & session, Transport::AdminId admin)
25 {
26     session.ToSerializable(mSession.mOpCreds);
27     mSession.mAdmin = Encoding::LittleEndian::HostSwap16(admin);
28     mKeyId          = session.GetLocalKeyId();
29 }
30
31 CHIP_ERROR StorablePeerConnection::StoreIntoKVS(PersistentStorageDelegate & kvs)
32 {
33     char key[KeySize()];
34     ReturnErrorOnFailure(GenerateKey(mKeyId, key, sizeof(key)));
35
36     return kvs.SyncSetKeyValue(key, &mSession, sizeof(mSession));
37 }
38
39 CHIP_ERROR StorablePeerConnection::FetchFromKVS(PersistentStorageDelegate & kvs, uint16_t keyId)
40 {
41     char key[KeySize()];
42     ReturnErrorOnFailure(GenerateKey(keyId, key, sizeof(key)));
43
44     uint16_t size = sizeof(mSession);
45     return kvs.SyncGetKeyValue(key, &mSession, size);
46 }
47
48 CHIP_ERROR StorablePeerConnection::DeleteFromKVS(PersistentStorageDelegate & kvs, uint16_t keyId)
49 {
50     char key[KeySize()];
51     ReturnErrorOnFailure(GenerateKey(keyId, key, sizeof(key)));
52
53     kvs.AsyncDeleteKeyValue(key);
54     return CHIP_NO_ERROR;
55 }
56
57 constexpr size_t StorablePeerConnection::KeySize()
58 {
59     return sizeof(kStorablePeerConnectionKeyPrefix) + 2 * sizeof(uint16_t);
60 }
61
62 CHIP_ERROR StorablePeerConnection::GenerateKey(uint16_t id, char * key, size_t len)
63 {
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);
68     return CHIP_NO_ERROR;
69 }
70
71 } // namespace chip