forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserDirectedCommissioningServer.cpp
578 lines (501 loc) · 21.3 KB
/
UserDirectedCommissioningServer.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/*
*
* Copyright (c) 2021-2022 Project CHIP Authors
* All rights reserved.
*
* 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.
*/
/**
* @file
* This file implements an object for a Matter User Directed Commissioning unsolicited
* recipient (server).
*
*/
#include "UserDirectedCommissioning.h"
#include <lib/core/CHIPSafeCasts.h>
#include <system/TLVPacketBufferBackingStore.h>
#include <transport/raw/Base.h>
#include <unistd.h>
namespace chip {
namespace Protocols {
namespace UserDirectedCommissioning {
void UserDirectedCommissioningServer::OnMessageReceived(const Transport::PeerAddress & source, System::PacketBufferHandle && msg,
Transport::MessageTransportContext * ctxt)
{
char addrBuffer[chip::Transport::PeerAddress::kMaxToStringSize];
source.ToString(addrBuffer);
ChipLogProgress(AppServer, "UserDirectedCommissioningServer::OnMessageReceived from %s", addrBuffer);
PacketHeader packetHeader;
ReturnOnFailure(packetHeader.DecodeAndConsume(msg));
if (packetHeader.IsEncrypted())
{
ChipLogError(AppServer, "UDC encryption flag set - ignoring");
return;
}
PayloadHeader payloadHeader;
ReturnOnFailure(payloadHeader.DecodeAndConsume(msg));
ChipLogProgress(AppServer, "IdentityDeclaration DataLength()=%" PRIu32, static_cast<uint32_t>(msg->DataLength()));
uint8_t udcPayload[IdentificationDeclaration::kUdcTLVDataMaxBytes];
size_t udcPayloadLength = std::min<size_t>(msg->DataLength(), sizeof(udcPayload));
msg->Read(udcPayload, udcPayloadLength);
IdentificationDeclaration id;
id.ReadPayload(udcPayload, sizeof(udcPayload));
if (id.GetCancelPasscode())
{
HandleUDCCancel(id);
return;
}
if (id.GetCommissionerPasscodeReady())
{
HandleUDCCommissionerPasscodeReady(id);
return;
}
HandleNewUDC(source, id);
}
void UserDirectedCommissioningServer::HandleNewUDC(const Transport::PeerAddress & source, IdentificationDeclaration & id)
{
char * instanceName = (char *) id.GetInstanceName();
ChipLogProgress(AppServer, "HandleNewUDC instance=%s ", id.GetInstanceName());
UDCClientState * client = mUdcClients.FindUDCClientState(instanceName);
if (client == nullptr)
{
ChipLogProgress(AppServer, "UDC new instance state received");
id.DebugLog();
CHIP_ERROR err;
err = mUdcClients.CreateNewUDCClientState(instanceName, &client);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "UDC error creating new connection state");
return;
}
if (id.HasDiscoveryInfo())
{
// if we received mDNS info, skip the commissionable lookup
ChipLogDetail(AppServer, "UDC discovery info provided");
mUdcClients.MarkUDCClientActive(client);
client->SetUDCClientProcessingState(UDCClientProcessingState::kPromptingUser);
client->SetPeerAddress(source);
id.UpdateClientState(client);
// Call the registered mUserConfirmationProvider, if any.
if (mUserConfirmationProvider != nullptr)
{
mUserConfirmationProvider->OnUserDirectedCommissioningRequest(*client);
}
return;
}
// Call the registered InstanceNameResolver, if any.
if (mInstanceNameResolver != nullptr)
{
mInstanceNameResolver->FindCommissionableNode(instanceName);
}
else
{
ChipLogError(AppServer, "UserDirectedCommissioningServer::OnMessageReceived no mInstanceNameResolver registered");
}
}
mUdcClients.MarkUDCClientActive(client);
}
void UserDirectedCommissioningServer::HandleUDCCancel(IdentificationDeclaration & id)
{
char * instanceName = (char *) id.GetInstanceName();
ChipLogProgress(AppServer, "HandleUDCCancel instance=%s ", id.GetInstanceName());
UDCClientState * client = mUdcClients.FindUDCClientState(instanceName);
if (client == nullptr)
{
ChipLogProgress(AppServer, "UDC no matching instance found");
return;
}
id.DebugLog();
mUdcClients.MarkUDCClientActive(client);
// Call the registered mUserConfirmationProvider, if any.
if (mUserConfirmationProvider != nullptr)
{
mUserConfirmationProvider->OnCancel(*client);
}
// reset this entry so that the client can try again without waiting an hour
client->Reset();
}
void UserDirectedCommissioningServer::HandleUDCCommissionerPasscodeReady(IdentificationDeclaration & id)
{
char * instanceName = (char *) id.GetInstanceName();
ChipLogProgress(AppServer, "HandleUDCCommissionerPasscodeReady instance=%s ", id.GetInstanceName());
UDCClientState * client = mUdcClients.FindUDCClientState(instanceName);
if (client == nullptr)
{
ChipLogProgress(AppServer, "UDC no matching instance found");
return;
}
if (client->GetUDCClientProcessingState() != UDCClientProcessingState::kWaitingForCommissionerPasscodeReady)
{
ChipLogProgress(AppServer, "UDC instance not in waiting for passcode ready state");
return;
}
id.DebugLog();
mUdcClients.MarkUDCClientActive(client);
client->SetUDCClientProcessingState(UDCClientProcessingState::kObtainingOnboardingPayload);
// Call the registered mUserConfirmationProvider, if any.
if (mUserConfirmationProvider != nullptr)
{
mUserConfirmationProvider->OnCommissionerPasscodeReady(*client);
}
}
CHIP_ERROR UserDirectedCommissioningServer::SendCDCMessage(CommissionerDeclaration cd, chip::Transport::PeerAddress peerAddress)
{
if (mTransportMgr == nullptr)
{
ChipLogError(AppServer, "CDC: No transport manager\n");
return CHIP_ERROR_INCORRECT_STATE;
}
uint8_t idBuffer[IdentificationDeclaration::kUdcTLVDataMaxBytes];
uint32_t length = cd.WritePayload(idBuffer, sizeof(idBuffer));
if (length == 0)
{
ChipLogError(AppServer, "CDC: error writing payload\n");
return CHIP_ERROR_INTERNAL;
}
chip::System::PacketBufferHandle payload = chip::MessagePacketBuffer::NewWithData(idBuffer, length);
if (payload.IsNull())
{
ChipLogError(AppServer, "Unable to allocate packet buffer\n");
return CHIP_ERROR_NO_MEMORY;
}
ReturnErrorOnFailure(EncodeUDCMessage(payload));
cd.DebugLog();
ChipLogProgress(Inet, "Sending CDC msg");
auto err = mTransportMgr->SendMessage(peerAddress, std::move(payload));
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "CDC SendMessage failed: %" CHIP_ERROR_FORMAT, err.Format());
return err;
}
ChipLogProgress(Inet, "CDC msg sent");
return CHIP_NO_ERROR;
}
CHIP_ERROR UserDirectedCommissioningServer::EncodeUDCMessage(const System::PacketBufferHandle & payload)
{
PayloadHeader payloadHeader;
PacketHeader packetHeader;
payloadHeader.SetMessageType(MsgType::IdentificationDeclaration).SetInitiator(true).SetNeedsAck(false);
VerifyOrReturnError(!payload.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(!payload->HasChainedBuffer(), CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrReturnError(payload->TotalLength() <= kMaxAppMessageLen, CHIP_ERROR_MESSAGE_TOO_LONG);
ReturnErrorOnFailure(payloadHeader.EncodeBeforeData(payload));
ReturnErrorOnFailure(packetHeader.EncodeBeforeData(payload));
return CHIP_NO_ERROR;
}
CHIP_ERROR IdentificationDeclaration::ReadPayload(uint8_t * udcPayload, size_t payloadBufferSize)
{
size_t i = 0;
while (i < std::min<size_t>(sizeof(mInstanceName), payloadBufferSize) && udcPayload[i] != '\0')
{
mInstanceName[i] = (char) udcPayload[i];
i++;
}
mInstanceName[i] = '\0';
if (payloadBufferSize <= sizeof(mInstanceName))
{
ChipLogProgress(AppServer, "UDC - No TLV information in Identification Declaration");
return CHIP_NO_ERROR;
}
// advance i to the end of the fixed length block containing instance name
i = sizeof(mInstanceName);
CHIP_ERROR err;
TLV::TLVReader reader;
reader.Init(udcPayload + i, payloadBufferSize - i);
// read the envelope
ReturnErrorOnFailure(reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()));
chip::TLV::TLVType outerContainerType = chip::TLV::kTLVType_Structure;
ReturnErrorOnFailure(reader.EnterContainer(outerContainerType));
while ((err = reader.Next()) == CHIP_NO_ERROR)
{
chip::TLV::Tag containerTag = reader.GetTag();
if (!TLV::IsContextTag(containerTag))
{
ChipLogError(AppServer, "Unexpected non-context TLV tag.");
return CHIP_ERROR_INVALID_TLV_TAG;
}
uint8_t tagNum = static_cast<uint8_t>(chip::TLV::TagNumFromTag(containerTag));
switch (tagNum)
{
case kVendorIdTag:
// vendorId
err = reader.Get(mVendorId);
break;
case kProductIdTag:
// productId
err = reader.Get(mProductId);
break;
case kCdPortTag:
// port
err = reader.Get(mCdPort);
break;
case kDeviceNameTag:
// deviceName
err = reader.GetString(mDeviceName, sizeof(mDeviceName));
break;
case kPairingInstTag:
// pairingInst
err = reader.GetString(mPairingInst, sizeof(mPairingInst));
break;
case kPairingHintTag:
// pairingHint
err = reader.Get(mPairingHint);
break;
case kRotatingIdTag:
// rotatingId
mRotatingIdLen = reader.GetLength();
err = reader.GetBytes(mRotatingId, sizeof(mRotatingId));
break;
case kTargetAppListTag:
// app vendor list
{
ChipLogProgress(AppServer, "TLV found an applist");
chip::TLV::TLVType listContainerType = chip::TLV::kTLVType_List;
ReturnErrorOnFailure(reader.EnterContainer(listContainerType));
while ((err = reader.Next()) == CHIP_NO_ERROR && mNumTargetAppInfos < sizeof(mTargetAppInfos))
{
containerTag = reader.GetTag();
if (!TLV::IsContextTag(containerTag))
{
ChipLogError(AppServer, "Unexpected non-context TLV tag.");
return CHIP_ERROR_INVALID_TLV_TAG;
}
tagNum = static_cast<uint8_t>(chip::TLV::TagNumFromTag(containerTag));
if (tagNum == kTargetAppTag)
{
ReturnErrorOnFailure(reader.EnterContainer(outerContainerType));
uint16_t appVendorId = 0;
uint16_t appProductId = 0;
while ((err = reader.Next()) == CHIP_NO_ERROR)
{
containerTag = reader.GetTag();
if (!TLV::IsContextTag(containerTag))
{
ChipLogError(AppServer, "Unexpected non-context TLV tag.");
return CHIP_ERROR_INVALID_TLV_TAG;
}
tagNum = static_cast<uint8_t>(chip::TLV::TagNumFromTag(containerTag));
if (tagNum == kAppVendorIdTag)
{
err = reader.Get(appVendorId);
}
else if (tagNum == kAppProductIdTag)
{
err = reader.Get(appProductId);
}
}
if (err == CHIP_END_OF_TLV)
{
ChipLogProgress(AppServer, "TLV end of struct TLV");
ReturnErrorOnFailure(reader.ExitContainer(outerContainerType));
}
if (appVendorId != 0)
{
mTargetAppInfos[mNumTargetAppInfos].vendorId = appVendorId;
mTargetAppInfos[mNumTargetAppInfos].productId = appProductId;
mNumTargetAppInfos++;
}
}
else
{
ChipLogError(AppServer, "unrecognized tag %d", tagNum);
}
}
if (err == CHIP_END_OF_TLV)
{
ChipLogProgress(AppServer, "TLV end of array");
ReturnErrorOnFailure(reader.ExitContainer(listContainerType));
err = CHIP_NO_ERROR;
}
}
break;
case kNoPasscodeTag:
err = reader.Get(mNoPasscode);
break;
case kCdUponPasscodeDialogTag:
err = reader.Get(mCdUponPasscodeDialog);
break;
case kCommissionerPasscodeTag:
err = reader.Get(mCommissionerPasscode);
break;
case kCommissionerPasscodeReadyTag:
err = reader.Get(mCommissionerPasscodeReady);
break;
case kCancelPasscodeTag:
err = reader.Get(mCancelPasscode);
break;
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "IdentificationDeclaration::ReadPayload read error %" CHIP_ERROR_FORMAT, err.Format());
}
}
if (err == CHIP_END_OF_TLV)
{
// Exiting container
ReturnErrorOnFailure(reader.ExitContainer(outerContainerType));
}
else
{
ChipLogError(AppServer, "IdentificationDeclaration::ReadPayload exiting early error %" CHIP_ERROR_FORMAT, err.Format());
}
ChipLogProgress(AppServer, "UDC TLV parse complete");
return CHIP_NO_ERROR;
}
/**
* Reset the connection state to a completely uninitialized status.
*/
uint32_t CommissionerDeclaration::WritePayload(uint8_t * payloadBuffer, size_t payloadBufferSize)
{
CHIP_ERROR err;
chip::TLV::TLVWriter writer;
writer.Init(payloadBuffer, payloadBufferSize);
chip::TLV::TLVType outerContainerType = chip::TLV::kTLVType_Structure;
VerifyOrExit(CHIP_NO_ERROR ==
(err = writer.StartContainer(chip::TLV::AnonymousTag(), chip::TLV::kTLVType_Structure, outerContainerType)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.Put(chip::TLV::ContextTag(kErrorCodeTag), GetErrorCode())), LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.PutBoolean(chip::TLV::ContextTag(kNeedsPasscodeTag), mNeedsPasscode)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.PutBoolean(chip::TLV::ContextTag(kNoAppsFoundTag), mNoAppsFound)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR ==
(err = writer.PutBoolean(chip::TLV::ContextTag(kPasscodeDialogDisplayedTag), mPasscodeDialogDisplayed)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.PutBoolean(chip::TLV::ContextTag(kCommissionerPasscodeTag), mCommissionerPasscode)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.PutBoolean(chip::TLV::ContextTag(kQRCodeDisplayedTag), mQRCodeDisplayed)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.PutBoolean(chip::TLV::ContextTag(kCancelPasscodeTag), mCancelPasscode)),
LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.EndContainer(outerContainerType)), LogErrorOnFailure(err));
VerifyOrExit(CHIP_NO_ERROR == (err = writer.Finalize()), LogErrorOnFailure(err));
ChipLogProgress(AppServer, "TLV write done");
return writer.GetLengthWritten();
exit:
return 0;
}
void UserDirectedCommissioningServer::SetUDCClientProcessingState(char * instanceName, UDCClientProcessingState state)
{
UDCClientState * client = mUdcClients.FindUDCClientState(instanceName);
if (client == nullptr)
{
CHIP_ERROR err;
err = mUdcClients.CreateNewUDCClientState(instanceName, &client);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer,
"UserDirectedCommissioningServer::SetUDCClientProcessingState error creating new connection state");
return;
}
}
ChipLogDetail(AppServer, "SetUDCClientProcessingState instance=%s new state=%d", StringOrNullMarker(instanceName), (int) state);
client->SetUDCClientProcessingState(state);
mUdcClients.MarkUDCClientActive(client);
}
void UserDirectedCommissioningServer::OnCommissionableNodeFound(const Dnssd::DiscoveredNodeData & discNodeData)
{
if (!discNodeData.Is<Dnssd::CommissionNodeData>())
{
return;
}
const Dnssd::CommissionNodeData & nodeData = discNodeData.Get<Dnssd::CommissionNodeData>();
if (nodeData.numIPs == 0)
{
ChipLogError(AppServer, "OnCommissionableNodeFound no IP addresses returned for instance name=%s", nodeData.instanceName);
return;
}
if (nodeData.port == 0)
{
ChipLogError(AppServer, "OnCommissionableNodeFound no port returned for instance name=%s", nodeData.instanceName);
return;
}
UDCClientState * client = mUdcClients.FindUDCClientState(nodeData.instanceName);
if (client != nullptr && client->GetUDCClientProcessingState() == UDCClientProcessingState::kDiscoveringNode)
{
ChipLogDetail(AppServer, "OnCommissionableNodeFound instance: name=%s old_state=%d new_state=%d", client->GetInstanceName(),
(int) client->GetUDCClientProcessingState(), (int) UDCClientProcessingState::kPromptingUser);
client->SetUDCClientProcessingState(UDCClientProcessingState::kPromptingUser);
#if INET_CONFIG_ENABLE_IPV4
// prefer IPv4 if its an option
bool foundV4 = false;
for (unsigned i = 0; i < nodeData.numIPs; ++i)
{
if (nodeData.ipAddress[i].IsIPv4())
{
foundV4 = true;
client->SetPeerAddress(chip::Transport::PeerAddress::UDP(nodeData.ipAddress[i], nodeData.port));
break;
}
}
// use IPv6 as last resort
if (!foundV4)
{
client->SetPeerAddress(chip::Transport::PeerAddress::UDP(nodeData.ipAddress[0], nodeData.port));
}
#else // INET_CONFIG_ENABLE_IPV4
// if we only support V6, then try to find a v6 address
bool foundV6 = false;
for (unsigned i = 0; i < nodeData.numIPs; ++i)
{
if (nodeData.ipAddress[i].IsIPv6())
{
foundV6 = true;
client->SetPeerAddress(chip::Transport::PeerAddress::UDP(nodeData.ipAddress[i], nodeData.port));
break;
}
}
// last resort, try with what we have
if (!foundV6)
{
ChipLogError(AppServer, "OnCommissionableNodeFound no v6 returned for instance name=%s", nodeData.instanceName);
client->SetPeerAddress(chip::Transport::PeerAddress::UDP(nodeData.ipAddress[0], nodeData.port));
}
#endif // INET_CONFIG_ENABLE_IPV4
client->SetDeviceName(nodeData.deviceName);
client->SetLongDiscriminator(nodeData.longDiscriminator);
client->SetVendorId(nodeData.vendorId);
client->SetProductId(nodeData.productId);
client->SetRotatingId(nodeData.rotatingId, nodeData.rotatingIdLen);
// Call the registered mUserConfirmationProvider, if any.
if (mUserConfirmationProvider != nullptr)
{
mUserConfirmationProvider->OnUserDirectedCommissioningRequest(*client);
}
}
}
void UserDirectedCommissioningServer::PrintUDCClients()
{
for (uint8_t i = 0; i < kMaxUDCClients; i++)
{
UDCClientState * state = GetUDCClients().GetUDCClientState(i);
if (state == nullptr)
{
ChipLogProgress(AppServer, "UDC Client[%d] null", i);
}
else
{
char addrBuffer[chip::Transport::PeerAddress::kMaxToStringSize];
state->GetPeerAddress().ToString(addrBuffer);
char rotatingIdString[chip::Dnssd::kMaxRotatingIdLen * 2 + 1] = "";
Encoding::BytesToUppercaseHexString(state->GetRotatingId(), chip::Dnssd::kMaxRotatingIdLen, rotatingIdString,
sizeof(rotatingIdString));
ChipLogProgress(AppServer, "UDC Client[%d] instance=%s deviceName=%s address=%s, vid/pid=%d/%d disc=%d rid=%s", i,
state->GetInstanceName(), state->GetDeviceName(), addrBuffer, state->GetVendorId(),
state->GetProductId(), state->GetLongDiscriminator(), rotatingIdString);
}
}
}
} // namespace UserDirectedCommissioning
} // namespace Protocols
} // namespace chip