forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericNetworkCommissioningThreadDriver.cpp
405 lines (332 loc) · 14.5 KB
/
GenericNetworkCommissioningThreadDriver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <lib/support/CodeUtils.h>
#include <lib/support/DefaultStorageKeyAllocator.h>
#include <lib/support/SafeInt.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/KeyValueStoreManager.h>
#include <platform/NetworkCommissioning.h>
#include <platform/OpenThread/GenericNetworkCommissioningThreadDriver.h>
#include <platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h>
#include <platform/ThreadStackManager.h>
#include <limits>
using namespace chip;
using namespace chip::Thread;
using namespace chip::DeviceLayer::PersistedStorage;
namespace chip {
namespace DeviceLayer {
namespace NetworkCommissioning {
// NOTE: For GenericThreadDriver, we assume that the network configuration is persisted by
// the OpenThread stack after ConnectNetwork command is called, and before that, all the changes
// are made to a local copy of the dataset stored in mStagingNetwork.
// Also, in order to support the fail-safe mechanism, the configuration is backed up in a temporary
// KVS slot upon any changes and restored when the fail-safe timeout is triggered or the device
// reboots without completing all the changes.
CHIP_ERROR GenericThreadDriver::Init(Internal::BaseDriver::NetworkStatusChangeCallback * statusChangeCallback)
{
ThreadStackMgrImpl().SetNetworkStatusChangeCallback(statusChangeCallback);
ThreadStackMgrImpl().GetThreadProvision(mStagingNetwork);
ReturnErrorOnFailure(PlatformMgr().AddEventHandler(OnThreadStateChangeHandler, reinterpret_cast<intptr_t>(this)));
// If the network configuration backup exists, it means that the device has been rebooted with
// the fail-safe armed. Since OpenThread persists all operational dataset changes, the backup
// must be restored.
if (BackupExists())
{
// Set flag and postpone revert until OpenThread is initialized,
// as we need to clear SRP host and services before restoring the backup.
mRevertOnServerReady = true;
}
CheckInterfaceEnabled();
return CHIP_NO_ERROR;
}
void GenericThreadDriver::OnThreadStateChangeHandler(const ChipDeviceEvent * event, intptr_t arg)
{
auto & driver = *reinterpret_cast<GenericThreadDriver *>(arg);
switch (event->Type)
{
case DeviceEventType::kThreadStateChange:
if (event->ThreadStateChange.OpenThread.Flags & OT_CHANGED_THREAD_PANID)
{
// Update the mStagingNetwork when thread panid changed
ThreadStackMgrImpl().GetThreadProvision(driver.mStagingNetwork);
}
break;
case DeviceEventType::kServerReady:
if (driver.mRevertOnServerReady)
{
driver.mRevertOnServerReady = false;
driver.RevertConfiguration();
}
break;
default:
break;
}
}
void GenericThreadDriver::Shutdown()
{
ThreadStackMgrImpl().SetNetworkStatusChangeCallback(nullptr);
}
CHIP_ERROR GenericThreadDriver::CommitConfiguration()
{
// OpenThread persists the network configuration on AttachToThreadNetwork, so simply remove
// the backup, so that it cannot be restored. If no backup could be found, it means that the
// configuration has not been modified since the fail-safe was armed, so return with no error.
CHIP_ERROR error = KeyValueStoreMgr().Delete(DefaultStorageKeyAllocator::FailSafeNetworkConfig().KeyName());
return error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND ? CHIP_NO_ERROR : error;
}
CHIP_ERROR GenericThreadDriver::RevertConfiguration()
{
uint8_t datasetBytes[Thread::kSizeOperationalDataset];
size_t datasetLength;
CHIP_ERROR error = KeyValueStoreMgr().Get(DefaultStorageKeyAllocator::FailSafeNetworkConfig().KeyName(), datasetBytes,
sizeof(datasetBytes), &datasetLength);
// If no backup could be found, it means that the network configuration has not been modified
// since the fail-safe was armed, so return with no error.
VerifyOrReturnError(error != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR);
ThreadStackMgrImpl().ClearAllSrpHostAndServices();
if (!GetEnabled())
{
// When reverting configuration, set InterfaceEnabled to default value (true).
// From the spec:
// If InterfaceEnabled is written to false on the same interface as that which is used to write the value, the Administrator
// could await the recovery of network configuration to prior safe values, before being able to communicate with the
// node again.
ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Delete(kInterfaceEnabled));
}
ChipLogProgress(NetworkProvisioning, "Reverting Thread operational dataset");
if (error == CHIP_NO_ERROR)
{
error = mStagingNetwork.Init(ByteSpan(datasetBytes, datasetLength));
}
if (error == CHIP_NO_ERROR)
{
error = DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, /* callback */ nullptr);
}
// Always remove the backup, regardless if it can be successfully restored.
KeyValueStoreMgr().Delete(DefaultStorageKeyAllocator::FailSafeNetworkConfig().KeyName());
return error;
}
Status GenericThreadDriver::AddOrUpdateNetwork(ByteSpan operationalDataset, MutableCharSpan & outDebugText,
uint8_t & outNetworkIndex)
{
ByteSpan newExtpanid;
Thread::OperationalDataset newDataset;
outDebugText.reduce_size(0);
outNetworkIndex = 0;
VerifyOrReturnError(newDataset.Init(operationalDataset) == CHIP_NO_ERROR && newDataset.IsCommissioned(), Status::kOutOfRange);
newDataset.GetExtendedPanIdAsByteSpan(newExtpanid);
// We only support one active operational dataset. Add/Update based on either:
// Staging network not commissioned yet (active) or we are updating the dataset with same Extended Pan ID.
VerifyOrReturnError(!mStagingNetwork.IsCommissioned() || MatchesNetworkId(mStagingNetwork, newExtpanid) == Status::kSuccess,
Status::kBoundsExceeded);
VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError);
mStagingNetwork = newDataset;
return Status::kSuccess;
}
Status GenericThreadDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex)
{
outDebugText.reduce_size(0);
outNetworkIndex = 0;
NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId);
VerifyOrReturnError(status == Status::kSuccess, status);
VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError);
mStagingNetwork.Clear();
return Status::kSuccess;
}
Status GenericThreadDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText)
{
outDebugText.reduce_size(0);
NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId);
VerifyOrReturnError(status == Status::kSuccess, status);
VerifyOrReturnError(index == 0, Status::kOutOfRange);
return Status::kSuccess;
}
void GenericThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback)
{
NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId);
if (!GetEnabled())
{
// Set InterfaceEnabled to default value (true).
ReturnOnFailure(PersistedStorage::KeyValueStoreMgr().Delete(kInterfaceEnabled));
}
if (status == Status::kSuccess && BackupConfiguration() != CHIP_NO_ERROR)
{
status = Status::kUnknownError;
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT
if (status == Status::kSuccess && ThreadStackMgrImpl().IsThreadAttached())
{
Thread::OperationalDataset currentDataset;
if (ThreadStackMgrImpl().GetThreadProvision(currentDataset) == CHIP_NO_ERROR)
{
// Clear the previous srp host and services
if (!currentDataset.AsByteSpan().data_equal(mStagingNetwork.AsByteSpan()) &&
ThreadStackMgrImpl().ClearAllSrpHostAndServices() != CHIP_NO_ERROR)
{
status = Status::kUnknownError;
}
}
else
{
status = Status::kUnknownError;
}
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT
if (status == Status::kSuccess &&
DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, callback) != CHIP_NO_ERROR)
{
status = Status::kUnknownError;
}
if (status != Status::kSuccess)
{
callback->OnResult(status, CharSpan(), 0);
}
}
CHIP_ERROR GenericThreadDriver::SetEnabled(bool enabled)
{
if (enabled == GetEnabled())
{
return CHIP_NO_ERROR;
}
ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(kInterfaceEnabled, &enabled, sizeof(enabled)));
if ((!enabled && ThreadStackMgrImpl().IsThreadEnabled()) || (enabled && ThreadStackMgrImpl().IsThreadProvisioned()))
{
ReturnErrorOnFailure(ThreadStackMgrImpl().SetThreadEnabled(enabled));
}
return CHIP_NO_ERROR;
}
bool GenericThreadDriver::GetEnabled()
{
bool value;
// InterfaceEnabled default value is true.
VerifyOrReturnValue(PersistedStorage::KeyValueStoreMgr().Get(kInterfaceEnabled, &value, sizeof(value)) == CHIP_NO_ERROR, true);
return value;
}
void GenericThreadDriver::ScanNetworks(ThreadDriver::ScanCallback * callback)
{
if (DeviceLayer::ThreadStackMgrImpl().StartThreadScan(callback) != CHIP_NO_ERROR)
{
callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr);
}
}
Status GenericThreadDriver::MatchesNetworkId(const Thread::OperationalDataset & dataset, const ByteSpan & networkId) const
{
ByteSpan extpanid;
if (!dataset.IsCommissioned())
{
return Status::kNetworkIDNotFound;
}
if (dataset.GetExtendedPanIdAsByteSpan(extpanid) != CHIP_NO_ERROR)
{
return Status::kUnknownError;
}
return networkId.data_equal(extpanid) ? Status::kSuccess : Status::kNetworkIDNotFound;
}
CHIP_ERROR GenericThreadDriver::BackupConfiguration()
{
// Abort pending revert
mRevertOnServerReady = false;
// If configuration is already backed up, return with no error
if (BackupExists())
{
return CHIP_NO_ERROR;
}
ByteSpan dataset = mStagingNetwork.AsByteSpan();
return KeyValueStoreMgr().Put(DefaultStorageKeyAllocator::FailSafeNetworkConfig().KeyName(), dataset.data(), dataset.size());
}
bool GenericThreadDriver::BackupExists()
{
CHIP_ERROR err = KeyValueStoreMgr().Get(DefaultStorageKeyAllocator::FailSafeNetworkConfig().KeyName(), nullptr, 0);
if (err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL)
{
return true;
}
return false;
}
void GenericThreadDriver::CheckInterfaceEnabled()
{
#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD_AUTOSTART
// If the Thread interface is enabled and stack has been provisioned, but is not currently enabled, enable it now.
if (GetEnabled() && ThreadStackMgrImpl().IsThreadProvisioned() && !ThreadStackMgrImpl().IsThreadEnabled())
{
ReturnOnFailure(ThreadStackMgrImpl().SetThreadEnabled(true));
ChipLogProgress(DeviceLayer, "OpenThread ifconfig up and thread start");
}
#endif
}
#if CHIP_DEVICE_CONFIG_SUPPORTS_CONCURRENT_CONNECTION
CHIP_ERROR GenericThreadDriver::DisconnectFromNetwork()
{
if (ThreadStackMgrImpl().IsThreadProvisioned())
{
Thread::OperationalDataset emptyNetwork = {};
// Attach to an empty network will disconnect the driver.
ReturnErrorOnFailure(ThreadStackMgrImpl().AttachToThreadNetwork(emptyNetwork, nullptr));
}
return CHIP_NO_ERROR;
}
#endif
size_t GenericThreadDriver::ThreadNetworkIterator::Count()
{
return driver->mStagingNetwork.IsCommissioned() ? 1 : 0;
}
bool GenericThreadDriver::ThreadNetworkIterator::Next(Network & item)
{
if (exhausted || !driver->mStagingNetwork.IsCommissioned())
{
return false;
}
uint8_t extpanid[kSizeExtendedPanId];
VerifyOrReturnError(driver->mStagingNetwork.GetExtendedPanId(extpanid) == CHIP_NO_ERROR, false);
memcpy(item.networkID, extpanid, kSizeExtendedPanId);
item.networkIDLen = kSizeExtendedPanId;
item.connected = false;
exhausted = true;
Thread::OperationalDataset currentDataset;
uint8_t enabledExtPanId[Thread::kSizeExtendedPanId];
// The Thread network is not actually enabled.
VerifyOrReturnError(ConnectivityMgrImpl().IsThreadAttached(), true);
VerifyOrReturnError(ThreadStackMgrImpl().GetThreadProvision(currentDataset) == CHIP_NO_ERROR, true);
// The Thread network is not enabled, but has a different extended pan id.
VerifyOrReturnError(currentDataset.GetExtendedPanId(enabledExtPanId) == CHIP_NO_ERROR, true);
VerifyOrReturnError(memcmp(extpanid, enabledExtPanId, kSizeExtendedPanId) == 0, true);
// The Thread network is enabled and has the same extended pan id as the one in our record.
item.connected = true;
return true;
}
ThreadCapabilities GenericThreadDriver::GetSupportedThreadFeatures()
{
BitMask<ThreadCapabilities> capabilites = 0;
capabilites.SetField(ThreadCapabilities::kIsBorderRouterCapable,
CHIP_DEVICE_CONFIG_THREAD_BORDER_ROUTER /*OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE*/);
capabilites.SetField(ThreadCapabilities::kIsRouterCapable, CHIP_DEVICE_CONFIG_THREAD_FTD);
capabilites.SetField(ThreadCapabilities::kIsSleepyEndDeviceCapable, !CHIP_DEVICE_CONFIG_THREAD_FTD);
capabilites.SetField(ThreadCapabilities::kIsFullThreadDevice, CHIP_DEVICE_CONFIG_THREAD_FTD);
capabilites.SetField(ThreadCapabilities::kIsSynchronizedSleepyEndDeviceCapable,
(!CHIP_DEVICE_CONFIG_THREAD_FTD && CHIP_DEVICE_CONFIG_THREAD_SSED));
return capabilites;
}
uint16_t GenericThreadDriver::GetThreadVersion()
{
uint16_t version = 0;
ThreadStackMgrImpl().GetThreadVersion(version);
return version;
}
} // namespace NetworkCommissioning
} // namespace DeviceLayer
} // namespace chip