-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathSetUpCodePairer.cpp
More file actions
972 lines (850 loc) · 36.7 KB
/
SetUpCodePairer.cpp
File metadata and controls
972 lines (850 loc) · 36.7 KB
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
/*
*
* Copyright (c) 2021 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
* Implementation of SetUp Code Pairer, a class that parses a given
* setup code and uses the extracted informations to discover and
* filter commissionables nodes, before initiating the pairing process.
*
*/
#include <controller/SetUpCodePairer.h>
#include <controller/CHIPDeviceController.h>
#include <lib/dnssd/Resolver.h>
#include <lib/support/CodeUtils.h>
#include <memory>
#include <platform/internal/NFCCommissioningManager.h>
#include <system/SystemClock.h>
#include <tracing/metric_event.h>
#include <vector>
constexpr uint32_t kDeviceDiscoveredTimeout = CHIP_CONFIG_SETUP_CODE_PAIRER_DISCOVERY_TIMEOUT_SECS * chip::kMillisecondsPerSecond;
using namespace chip::Tracing;
namespace chip {
namespace Controller {
CHIP_ERROR SetUpCodePairer::PairDevice(NodeId remoteId, const char * setUpCode, SetupCodePairerBehaviour commission,
DiscoveryType discoveryType, Optional<Dnssd::CommonResolutionData> resolutionData)
{
VerifyOrReturnErrorWithMetric(kMetricSetupCodePairerPairDevice, mSystemLayer != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnErrorWithMetric(kMetricSetupCodePairerPairDevice, remoteId != kUndefinedNodeId, CHIP_ERROR_INVALID_ARGUMENT);
std::vector<SetupPayload> payloads;
ReturnErrorOnFailure(SetupPayload::FromStringRepresentation(setUpCode, payloads));
// If the caller has provided a specific single resolution data, and we were
// only looking for one commissionee, and the caller says that the provided
// data matches that one commissionee, just go ahead and use the provided data.
//
// If we were looking for more than one device (i.e. if either of the
// payload arrays involved does not have length 1), we can't make use of the
// incoming resolution data, since it does not contain the long
// discriminator of the thing that was discovered, and therefore we can't
// tell which setup passcode to use for it.
if (resolutionData.HasValue() && payloads.size() == 1 && mSetupPayloads.size() == 1)
{
VerifyOrReturnErrorWithMetric(kMetricSetupCodePairerPairDevice, discoveryType != DiscoveryType::kAll,
CHIP_ERROR_INVALID_ARGUMENT);
if (mRemoteId == remoteId && mSetupPayloads[0].setUpPINCode == payloads[0].setUpPINCode && mConnectionType == commission &&
mDiscoveryType == discoveryType)
{
// Not passing a discriminator is ok, since we have only one payload.
NotifyCommissionableDeviceDiscovered(resolutionData.Value(), /* matchedLongDiscriminator = */ std::nullopt);
return CHIP_NO_ERROR;
}
}
ResetDiscoveryState();
mConnectionType = commission;
mDiscoveryType = discoveryType;
mRemoteId = remoteId;
mSetupPayloads = std::move(payloads);
if (resolutionData.HasValue() && mSetupPayloads.size() == 1)
{
// No need to pass in a discriminator if we have only one payload, which
// is good because we don't have a full discriminator here anyway.
NotifyCommissionableDeviceDiscovered(resolutionData.Value(), /* matchedLongDiscriminator = */ std::nullopt);
return CHIP_NO_ERROR;
}
ReturnErrorOnFailureWithMetric(kMetricSetupCodePairerPairDevice, Connect());
auto errorCode =
mSystemLayer->StartTimer(System::Clock::Milliseconds32(kDeviceDiscoveredTimeout), OnDeviceDiscoveredTimeoutCallback, this);
if (CHIP_NO_ERROR == errorCode)
{
MATTER_LOG_METRIC_BEGIN(kMetricSetupCodePairerPairDevice);
}
return errorCode;
}
CHIP_ERROR SetUpCodePairer::Connect()
{
if (mDiscoveryType == DiscoveryType::kAll)
{
if (ShouldDiscoverUsing(RendezvousInformationFlag::kBLE))
{
CHIP_ERROR err = StartDiscoveryOverBLE();
if ((CHIP_ERROR_NOT_IMPLEMENTED == err) || (CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE == err))
{
ChipLogProgress(Controller,
"Skipping commissionable node discovery over BLE since not supported by the controller!");
}
else if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to start commissionable node discovery over BLE: %" CHIP_ERROR_FORMAT,
err.Format());
}
}
if (ShouldDiscoverUsing(RendezvousInformationFlag::kWiFiPAF))
{
CHIP_ERROR err = StartDiscoveryOverWiFiPAF();
if ((CHIP_ERROR_NOT_IMPLEMENTED == err) || (CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE == err))
{
ChipLogProgress(Controller,
"Skipping commissionable node discovery over Wi-Fi PAF since not supported by the controller!");
}
else if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to start commissionable node discovery over Wi-Fi PAF: %" CHIP_ERROR_FORMAT,
err.Format());
}
}
if (ShouldDiscoverUsing(RendezvousInformationFlag::kNFC))
{
CHIP_ERROR err = StartDiscoveryOverNFC();
if ((CHIP_ERROR_NOT_IMPLEMENTED == err) || (CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE == err))
{
ChipLogProgress(Controller,
"Skipping commissionable node discovery over NFC since not supported by the controller!");
}
else if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to start commissionable node discovery over NFC: %" CHIP_ERROR_FORMAT,
err.Format());
}
}
}
// We always want to search on network because any node that has already been commissioned will use on-network regardless of the
// QR code flag.
CHIP_ERROR err = StartDiscoveryOverDNSSD();
if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Failed to start commissionable node discovery over DNS-SD: %" CHIP_ERROR_FORMAT, err.Format());
}
return err;
}
CHIP_ERROR SetUpCodePairer::StartDiscoveryOverBLE()
{
#if CONFIG_NETWORK_LAYER_BLE
#if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
VerifyOrReturnError(mCommissioner != nullptr, CHIP_ERROR_INCORRECT_STATE);
mCommissioner->ConnectBleTransportToSelf();
#endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
VerifyOrReturnError(mBleLayer != nullptr, CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
ChipLogProgress(Controller, "Starting commissionable node discovery over BLE");
// Handle possibly-sync callbacks.
mWaitingForDiscovery[kBLETransport] = true;
CHIP_ERROR err;
// Not all BLE backends support the new NewBleConnectionByDiscriminators
// API, so use the old one when we can (i.e. when we only have one setup
// payload), to avoid breaking existing API consumers.
if (mSetupPayloads.size() == 1)
{
err = mBleLayer->NewBleConnectionByDiscriminator(mSetupPayloads[0].discriminator, this, OnDiscoveredDeviceOverBleSuccess,
OnDiscoveredDeviceOverBleError);
}
else
{
std::vector<SetupDiscriminator> discriminators;
discriminators.reserve(mSetupPayloads.size());
for (auto & payload : mSetupPayloads)
{
discriminators.emplace_back(payload.discriminator);
}
err = mBleLayer->NewBleConnectionByDiscriminators(Span(discriminators.data(), discriminators.size()), this,
OnDiscoveredDeviceWithDiscriminatorOverBleSuccess,
OnDiscoveredDeviceOverBleError);
}
if (err != CHIP_NO_ERROR)
{
mWaitingForDiscovery[kBLETransport] = false;
}
return err;
#else
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
#endif // CONFIG_NETWORK_LAYER_BLE
}
CHIP_ERROR SetUpCodePairer::StopDiscoveryOverBLE()
{
// Make sure to not call CancelBleIncompleteConnection unless we are in fact
// waiting on BLE discovery. It will cancel connections that are in fact
// completed. In particular, if we just established PASE over BLE calling
// CancelBleIncompleteConnection here unconditionally would cancel the BLE
// connection underlying the PASE session. So make sure to only call
// CancelBleIncompleteConnection if we're still waiting to hear back on the
// BLE discovery bits.
if (!mWaitingForDiscovery[kBLETransport])
{
return CHIP_NO_ERROR;
}
mWaitingForDiscovery[kBLETransport] = false;
#if CONFIG_NETWORK_LAYER_BLE
VerifyOrReturnError(mBleLayer != nullptr, CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE);
ChipLogProgress(Controller, "Stopping commissionable node discovery over BLE");
return mBleLayer->CancelBleIncompleteConnection();
#else
return CHIP_NO_ERROR;
#endif // CONFIG_NETWORK_LAYER_BLE
}
CHIP_ERROR SetUpCodePairer::StartDiscoveryOverDNSSD()
{
ChipLogProgress(Controller, "Starting commissionable node discovery over DNS-SD");
Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kNone);
if (mSetupPayloads.size() == 1)
{
auto & discriminator = mSetupPayloads[0].discriminator;
if (discriminator.IsShortDiscriminator())
{
filter.type = Dnssd::DiscoveryFilterType::kShortDiscriminator;
filter.code = discriminator.GetShortValue();
}
else
{
filter.type = Dnssd::DiscoveryFilterType::kLongDiscriminator;
filter.code = discriminator.GetLongValue();
}
}
// In theory we could try to filter on the vendor ID if it's the same across all the setup
// payloads, but DNS-SD advertisements are not required to include the Vendor ID subtype, so in
// practice that's not doable.
// Handle possibly-sync callbacks.
mWaitingForDiscovery[kIPTransport] = true;
CHIP_ERROR err = mCommissioner->DiscoverCommissionableNodes(filter);
if (err != CHIP_NO_ERROR)
{
mWaitingForDiscovery[kIPTransport] = false;
}
return err;
}
CHIP_ERROR SetUpCodePairer::StopDiscoveryOverDNSSD()
{
ChipLogProgress(Controller, "Stopping commissionable node discovery over DNS-SD");
mWaitingForDiscovery[kIPTransport] = false;
return mCommissioner->StopCommissionableDiscovery();
}
CHIP_ERROR SetUpCodePairer::StartDiscoveryOverWiFiPAF()
{
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
if (mSetupPayloads.size() != 1)
{
ChipLogError(Controller, "Wi-Fi PAF commissioning does not support concatenated QR codes yet.");
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
auto & payload = mSetupPayloads[0];
ChipLogProgress(Controller, "Starting commissionable node discovery over Wi-Fi PAF");
VerifyOrReturnError(mCommissioner != nullptr, CHIP_ERROR_INCORRECT_STATE);
const SetupDiscriminator connDiscriminator(payload.discriminator);
VerifyOrReturnValue(!connDiscriminator.IsShortDiscriminator(), CHIP_ERROR_INVALID_ARGUMENT,
ChipLogError(Controller, "Error, Long discriminator is required"));
uint16_t discriminator = connDiscriminator.GetLongValue();
WiFiPAF::WiFiPAFSession sessionInfo = { .role = WiFiPAF::WiFiPafRole::kWiFiPafRole_Subscriber,
.nodeId = mRemoteId,
.discriminator = discriminator };
ReturnErrorOnFailure(
DeviceLayer::ConnectivityMgr().GetWiFiPAF()->AddPafSession(WiFiPAF::PafInfoAccess::kAccNodeInfo, sessionInfo));
mWaitingForDiscovery[kWiFiPAFTransport] = true;
CHIP_ERROR err = DeviceLayer::ConnectivityMgr().WiFiPAFSubscribe(discriminator, (void *) this, OnWiFiPAFSubscribeComplete,
OnWiFiPAFSubscribeError);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Commissionable node discovery over Wi-Fi PAF failed, err = %" CHIP_ERROR_FORMAT, err.Format());
mWaitingForDiscovery[kWiFiPAFTransport] = false;
}
return err;
#else
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
}
CHIP_ERROR SetUpCodePairer::StopDiscoveryOverWiFiPAF()
{
mWaitingForDiscovery[kWiFiPAFTransport] = false;
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
return DeviceLayer::ConnectivityMgr().WiFiPAFCancelIncompleteSubscribe();
#else
return CHIP_NO_ERROR;
#endif
}
CHIP_ERROR SetUpCodePairer::StartDiscoveryOverNFC()
{
#if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
if (mSetupPayloads.size() != 1)
{
ChipLogError(Controller, "NFC commissioning does not support concatenated QR codes yet.");
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
auto & payload = mSetupPayloads[0];
ChipLogProgress(Controller, "Starting commissionable node discovery over NFC");
VerifyOrReturnError(mCommissioner != nullptr, CHIP_ERROR_INCORRECT_STATE);
const SetupDiscriminator connDiscriminator(payload.discriminator);
VerifyOrReturnValue(!connDiscriminator.IsShortDiscriminator(), CHIP_ERROR_INVALID_ARGUMENT,
ChipLogError(Controller, "Error, Long discriminator is required"));
chip::Nfc::NFCTag::Identifier identifier = { .discriminator = payload.discriminator.GetLongValue() };
Nfc::NFCReaderTransport * readerTransport = DeviceLayer::Internal::NFCCommissioningMgr().GetNFCReaderTransport();
if (!readerTransport)
{
ChipLogError(Controller, "Commissionable node discovery over NFC since there is no valid NFC reader transport");
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
readerTransport->SetDelegate(this);
CHIP_ERROR err = readerTransport->StartDiscoveringTagMatchingAddress(identifier);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Controller, "Commissionable node discovery over NFC failed, err = %" CHIP_ERROR_FORMAT, err.Format());
}
else
{
mWaitingForDiscovery[kNFCTransport] = true;
}
return err;
#else
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
#endif // CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
}
CHIP_ERROR SetUpCodePairer::StopDiscoveryOverNFC()
{
#if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
mWaitingForDiscovery[kNFCTransport] = false;
Nfc::NFCReaderTransport * readerTransport = DeviceLayer::Internal::NFCCommissioningMgr().GetNFCReaderTransport();
if (!readerTransport)
{
ChipLogError(Controller,
"Failed to stop commissionable node discovery over NFC since there is no valid NFC reader transport");
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
ChipLogProgress(Controller, "Stopping commissionable node discovery over NFC by removing delegate");
readerTransport->SetDelegate(nullptr);
#endif
return CHIP_NO_ERROR;
}
bool SetUpCodePairer::ConnectToDiscoveredDevice()
{
if (mWaitingForPASE)
{
// Nothing to do. Just wait until we either succeed or fail at that
// PASE session establishment.
return false;
}
while (!mDiscoveredParameters.empty())
{
mCurrentPASEPayload.reset();
// Grab the first element from the queue and try connecting to it.
// Remove it from the queue before we try to connect, in case the
// connection attempt fails and calls right back into us to try the next
// thing.
SetUpCodePairerParameters params(mDiscoveredParameters.front());
mDiscoveredParameters.pop_front();
if (params.mLongDiscriminator)
{
auto longDiscriminator = *params.mLongDiscriminator;
// Look for a matching setup passcode.
for (auto & payload : mSetupPayloads)
{
if (payload.discriminator.MatchesLongDiscriminator(longDiscriminator))
{
params.SetSetupPINCode(payload.setUpPINCode);
params.SetSetupDiscriminator(payload.discriminator);
mCurrentPASEPayload = payload;
break;
}
}
if (!mCurrentPASEPayload)
{
ChipLogError(Controller, "SetUpCodePairer: Discovered discriminator %u does not match any of our setup payloads",
longDiscriminator);
// Move on to the the next discovered params; nothing we can do here.
continue;
}
}
else
{
// No discriminator known for this discovered device. This can work if we have only one
// setup payload, but otherwise we have no idea what setup passcode to use for it.
if (mSetupPayloads.size() == 1)
{
params.SetSetupPINCode(mSetupPayloads[0].setUpPINCode);
params.SetSetupDiscriminator(mSetupPayloads[0].discriminator);
mCurrentPASEPayload = mSetupPayloads[0];
}
else
{
ChipLogError(Controller,
"SetUpCodePairer: Unable to handle discovered parameters with no discriminator, because it has %u "
"possible payloads",
static_cast<unsigned>(mSetupPayloads.size()));
continue;
}
}
#if CHIP_PROGRESS_LOGGING
char buf[Transport::PeerAddress::kMaxToStringSize];
params.GetPeerAddress().ToString(buf);
ChipLogProgress(Controller, "Attempting PASE connection to %s", buf);
#endif // CHIP_PROGRESS_LOGGING
// Handle possibly-sync call backs from attempts to establish PASE.
ExpectPASEEstablishment();
if (params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp)
{
mCurrentPASEParameters.SetValue(params);
}
CHIP_ERROR err;
if (mConnectionType == SetupCodePairerBehaviour::kCommission)
{
err = mCommissioner->PairDevice(mRemoteId, params);
}
else
{
err = mCommissioner->EstablishPASEConnection(mRemoteId, params);
}
LogErrorOnFailure(err);
if (err == CHIP_NO_ERROR)
{
return true;
}
// Failed to start establishing PASE. Move on to the next item.
mCurrentPASEParameters.ClearValue();
mCurrentPASEPayload.reset();
PASEEstablishmentComplete();
}
return false;
}
#if CONFIG_NETWORK_LAYER_BLE
void SetUpCodePairer::OnDiscoveredDeviceOverBle(BLE_CONNECTION_OBJECT connObj, std::optional<uint16_t> matchedLongDiscriminator)
{
ChipLogProgress(Controller, "Discovered device to be commissioned over BLE");
mWaitingForDiscovery[kBLETransport] = false;
// In order to not wait for all the possible addresses discovered over mdns to
// be tried before trying to connect over BLE, the discovered connection object is
// inserted at the beginning of the list.
//
// It makes it the 'next' thing to try to connect to if there are already some
// discovered parameters in the list.
//
// TODO: Consider implementing the SHOULD the spec has about commissioning things
// in QR code order by waiting for a second or something before actually starting
// the first PASE session when we have multiple setup payloads, and sorting the
// results in setup payload order. If we do this, we might want to restrict it to
// cases when the different payloads have different vendor/product IDs, since if
// they are all the same product presumably ordering really does not matter.
mDiscoveredParameters.emplace_front(connObj, matchedLongDiscriminator);
ConnectToDiscoveredDevice();
}
void SetUpCodePairer::OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj)
{
(static_cast<SetUpCodePairer *>(appState))->OnDiscoveredDeviceOverBle(connObj, std::nullopt);
}
void SetUpCodePairer::OnDiscoveredDeviceWithDiscriminatorOverBleSuccess(void * appState, uint16_t matchedLongDiscriminator,
BLE_CONNECTION_OBJECT connObj)
{
(static_cast<SetUpCodePairer *>(appState))->OnDiscoveredDeviceOverBle(connObj, std::make_optional(matchedLongDiscriminator));
}
void SetUpCodePairer::OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err)
{
static_cast<SetUpCodePairer *>(appState)->OnBLEDiscoveryError(err);
}
void SetUpCodePairer::OnBLEDiscoveryError(CHIP_ERROR err)
{
ChipLogError(Controller, "Commissionable node discovery over BLE failed: %" CHIP_ERROR_FORMAT, err.Format());
mWaitingForDiscovery[kBLETransport] = false;
LogErrorOnFailure(err);
StopPairingIfTransportsExhausted(err);
}
#endif // CONFIG_NETWORK_LAYER_BLE
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
void SetUpCodePairer::OnDiscoveredDeviceOverWifiPAF()
{
ChipLogProgress(Controller, "Discovered device to be commissioned over Wi-Fi PAF, RemoteId: %" PRIu64, mRemoteId);
mWaitingForDiscovery[kWiFiPAFTransport] = false;
auto param = SetUpCodePairerParameters();
param.SetPeerAddress(Transport::PeerAddress(Transport::Type::kWiFiPAF, mRemoteId));
// TODO: This needs to support concatenated QR codes and set the relevant
// long discriminator on param.
//
// See https://github.com/project-chip/connectedhomeip/issues/39134
mDiscoveredParameters.emplace_back(param);
ConnectToDiscoveredDevice();
}
void SetUpCodePairer::OnWifiPAFDiscoveryError(CHIP_ERROR err)
{
ChipLogError(Controller, "Commissionable node discovery over Wi-Fi PAF failed: %" CHIP_ERROR_FORMAT, err.Format());
mWaitingForDiscovery[kWiFiPAFTransport] = false;
StopPairingIfTransportsExhausted(err);
}
void SetUpCodePairer::OnWiFiPAFSubscribeComplete(void * appState)
{
auto self = reinterpret_cast<SetUpCodePairer *>(appState);
self->OnDiscoveredDeviceOverWifiPAF();
}
void SetUpCodePairer::OnWiFiPAFSubscribeError(void * appState, CHIP_ERROR err)
{
auto self = reinterpret_cast<SetUpCodePairer *>(appState);
self->OnWifiPAFDiscoveryError(err);
}
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
void SetUpCodePairer::OnTagDiscovered(const chip::Nfc::NFCTag::Identifier & identifier)
{
ChipLogProgress(Controller, "Discovered device to be commissioned over NFC, Identifier: %u", identifier.discriminator);
mWaitingForDiscovery[kNFCTransport] = false;
auto param = SetUpCodePairerParameters();
param.SetPeerAddress(Transport::PeerAddress(Transport::PeerAddress::NFC(identifier.discriminator)));
// TODO: This needs to support concatenated QR codes and set the relevant
// long discriminator on param.
//
// See https://github.com/project-chip/connectedhomeip/issues/39134
mDiscoveredParameters.emplace_back(param);
ConnectToDiscoveredDevice();
}
void SetUpCodePairer::OnTagDiscoveryFailed(CHIP_ERROR error)
{
ChipLogError(Controller, "Commissionable node discovery over NFC failed: %" CHIP_ERROR_FORMAT, error.Format());
mWaitingForDiscovery[kNFCTransport] = false;
StopPairingIfTransportsExhausted(error);
}
#endif
bool SetUpCodePairer::IdIsPresent(uint16_t vendorOrProductID)
{
return vendorOrProductID != kNotAvailable;
}
bool SetUpCodePairer::NodeMatchesCurrentFilter(const Dnssd::DiscoveredNodeData & discNodeData) const
{
if (!discNodeData.Is<Dnssd::CommissionNodeData>())
{
return false;
}
const Dnssd::CommissionNodeData & nodeData = discNodeData.Get<Dnssd::CommissionNodeData>();
VerifyOrReturnError(mCommissioner != nullptr, false);
VerifyOrReturnError(mCommissioner->HasValidCommissioningMode(nodeData), false);
// Check whether this matches one of our setup payloads.
for (auto & payload : mSetupPayloads)
{
// The advertisement may not include a vendor id, and the payload may not have one either.
if (IdIsPresent(payload.vendorID) && IdIsPresent(nodeData.vendorId) && payload.vendorID != nodeData.vendorId)
{
ChipLogProgress(Controller, "Discovered device vendor ID (%u) does not match our vendor ID (%u).", nodeData.vendorId,
payload.vendorID);
continue;
}
// The advertisement may not include a product id, and the payload may not have one either.
if (IdIsPresent(payload.productID) && IdIsPresent(nodeData.productId) && payload.productID != nodeData.productId)
{
ChipLogProgress(Controller, "Discovered device product ID (%u) does not match our product ID (%u).", nodeData.productId,
payload.productID);
continue;
}
if (!payload.discriminator.MatchesLongDiscriminator(nodeData.longDiscriminator))
{
ChipLogProgress(Controller, "Discovered device discriminator (%u) does not match our discriminator.",
nodeData.longDiscriminator);
continue;
}
ChipLogProgress(Controller, "Discovered device with discriminator %u matches one of our setup payloads",
nodeData.longDiscriminator);
return true;
}
return false;
}
void SetUpCodePairer::NotifyCommissionableDeviceDiscovered(const Dnssd::DiscoveredNodeData & nodeData)
{
if (!NodeMatchesCurrentFilter(nodeData))
{
return;
}
ChipLogProgress(Controller, "Discovered device to be commissioned over DNS-SD");
auto & commissionableNodeData = nodeData.Get<Dnssd::CommissionNodeData>();
NotifyCommissionableDeviceDiscovered(commissionableNodeData, std::make_optional(commissionableNodeData.longDiscriminator));
}
void SetUpCodePairer::NotifyCommissionableDeviceDiscovered(const Dnssd::CommonResolutionData & resolutionData,
std::optional<uint16_t> matchedLongDiscriminator)
{
if (mDiscoveryType == DiscoveryType::kDiscoveryNetworkOnlyWithoutPASEAutoRetry)
{
// If the discovery type does not want the PASE auto retry mechanism, we will just store
// a single IP. So the discovery process is stopped as it won't be of any help anymore.
TEMPORARY_RETURN_IGNORED StopDiscoveryOverDNSSD();
mDiscoveredParameters.emplace_back(resolutionData, matchedLongDiscriminator, 0);
}
else
{
for (size_t i = 0; i < resolutionData.numIPs; i++)
{
mDiscoveredParameters.emplace_back(resolutionData, matchedLongDiscriminator, i);
}
}
ConnectToDiscoveredDevice();
}
bool SetUpCodePairer::StopPairing(NodeId remoteId)
{
VerifyOrReturnValue(mRemoteId != kUndefinedNodeId, false);
VerifyOrReturnValue(remoteId == kUndefinedNodeId || remoteId == mRemoteId, false);
if (mWaitingForPASE)
{
PASEEstablishmentComplete();
}
ResetDiscoveryState();
mRemoteId = kUndefinedNodeId;
return true;
}
bool SetUpCodePairer::TryNextRendezvousParameters()
{
if (ConnectToDiscoveredDevice())
{
ChipLogProgress(Controller, "Trying connection to commissionee over different transport");
return true;
}
if (DiscoveryInProgress())
{
ChipLogProgress(Controller, "Waiting to discover commissionees that match our filters");
return true;
}
return false;
}
bool SetUpCodePairer::DiscoveryInProgress() const
{
for (const auto & waiting : mWaitingForDiscovery)
{
if (waiting)
{
return true;
}
}
return false;
}
void SetUpCodePairer::StopPairingIfTransportsExhausted(CHIP_ERROR err)
{
if (mWaitingForPASE || !mDiscoveredParameters.empty() || DiscoveryInProgress() || mRemoteId == kUndefinedNodeId)
{
return;
}
// Clear mRemoteId first to guard against re-entrant calls (e.g. from an async
// cancel callback fired after StopAllDiscoveryAttempts already cleared the flags).
mRemoteId = kUndefinedNodeId;
CHIP_ERROR failErr = mLastPASEError != CHIP_NO_ERROR ? mLastPASEError : err;
MATTER_LOG_METRIC_END(kMetricSetupCodePairerPairDevice, failErr);
mCommissioner->OnSessionEstablishmentError(failErr);
}
void SetUpCodePairer::StopAllDiscoveryAttempts()
{
LogErrorOnFailure(StopDiscoveryOverBLE());
LogErrorOnFailure(StopDiscoveryOverDNSSD());
LogErrorOnFailure(StopDiscoveryOverWiFiPAF());
LogErrorOnFailure(StopDiscoveryOverNFC());
// Just in case any of those failed to reset the waiting state properly.
for (auto & waiting : mWaitingForDiscovery)
{
waiting = false;
}
}
void SetUpCodePairer::ResetDiscoveryState()
{
StopAllDiscoveryAttempts();
mDiscoveredParameters.clear();
mCurrentPASEParameters.ClearValue();
mLastPASEError = CHIP_NO_ERROR;
mSetupPayloads.clear();
mSystemLayer->CancelTimer(OnDeviceDiscoveredTimeoutCallback, this);
}
void SetUpCodePairer::ExpectPASEEstablishment()
{
VerifyOrDie(!mWaitingForPASE);
mWaitingForPASE = true;
auto * delegate = mCommissioner->GetPairingDelegate();
VerifyOrDie(delegate != this);
mPairingDelegate = delegate;
mCommissioner->RegisterPairingDelegate(this);
}
void SetUpCodePairer::PASEEstablishmentComplete()
{
VerifyOrDie(mWaitingForPASE);
mWaitingForPASE = false;
mCommissioner->RegisterPairingDelegate(mPairingDelegate);
mPairingDelegate = nullptr;
}
void SetUpCodePairer::OnStatusUpdate(DevicePairingDelegate::Status status)
{
if (status == DevicePairingDelegate::Status::SecurePairingFailed)
{
// If we're still waiting on discovery, don't propagate this failure
// (which is due to PASE failure with something we discovered, but the
// "something" may not have been the right thing) for now. Wait until
// discovery completes. Then we will either succeed and notify
// accordingly or time out and land in OnStatusUpdate again, but at that
// point we will not be waiting on discovery anymore.
if (!mDiscoveredParameters.empty())
{
ChipLogProgress(Controller, "Ignoring SecurePairingFailed status for now; we have more discovered devices to try");
return;
}
if (DiscoveryInProgress())
{
ChipLogProgress(Controller,
"Ignoring SecurePairingFailed status for now; we are waiting to see if we discover more devices");
return;
}
}
if (mPairingDelegate)
{
mPairingDelegate->OnStatusUpdate(status);
}
}
void SetUpCodePairer::OnPairingComplete(CHIP_ERROR error, const std::optional<RendezvousParameters> & rendezvousParameters,
const std::optional<SetupPayload> & setupPayload)
{
// Save the pairing delegate so we can notify it. We want to notify it
// _after_ we restore the state on the commissioner, in case the delegate
// ends up immediately calling back into the commissioner again when
// notified.
auto * pairingDelegate = mPairingDelegate;
PASEEstablishmentComplete();
// Make sure to clear out mCurrentPASEPayload whether we succeeded or failed.
std::optional<SetupPayload> pasePayload;
pasePayload.swap(mCurrentPASEPayload);
if (CHIP_NO_ERROR == error)
{
ChipLogProgress(Controller, "PASE session established with commissionee. Stopping discovery.");
ResetDiscoveryState();
mRemoteId = kUndefinedNodeId;
MATTER_LOG_METRIC_END(kMetricSetupCodePairerPairDevice, error);
if (pairingDelegate != nullptr)
{
// We don't expect to have a setupPayload passed in here.
if (setupPayload)
{
ChipLogError(Controller,
"Unexpected setupPayload passed to SetUpCodePairer::OnPairingComplete. Where did it come from?");
}
pairingDelegate->OnPairingComplete(error, rendezvousParameters, pasePayload);
}
return;
}
// It may happen that there is a stale DNS entry. If so, ReconfirmRecord will flush
// the record from the daemon cache once it determines that it is invalid.
// It may not help for this particular resolve, but may help subsequent resolves.
if (CHIP_ERROR_TIMEOUT == error && mCurrentPASEParameters.HasValue())
{
const auto & params = mCurrentPASEParameters.Value();
const auto & peer = params.GetPeerAddress();
const auto & ip = peer.GetIPAddress();
auto err = Dnssd::Resolver::Instance().ReconfirmRecord(params.mHostName, ip, params.mInterfaceId);
if (CHIP_NO_ERROR != err && CHIP_ERROR_NOT_IMPLEMENTED != err)
{
ChipLogError(Controller, "Error when verifying the validity of an address: %" CHIP_ERROR_FORMAT, err.Format());
}
}
mCurrentPASEParameters.ClearValue();
// We failed to establish PASE. Try the next thing we have discovered, if
// any.
if (TryNextRendezvousParameters())
{
// Keep waiting until that finishes. Don't call OnPairingComplete yet.
mLastPASEError = error;
return;
}
MATTER_LOG_METRIC_END(kMetricSetupCodePairerPairDevice, error);
if (pairingDelegate != nullptr)
{
pairingDelegate->OnPairingComplete(error, rendezvousParameters, pasePayload);
}
}
void SetUpCodePairer::OnPairingDeleted(CHIP_ERROR error)
{
if (mPairingDelegate)
{
mPairingDelegate->OnPairingDeleted(error);
}
}
void SetUpCodePairer::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR error)
{
// Not really expecting this, but handle it anyway.
if (mPairingDelegate)
{
mPairingDelegate->OnCommissioningComplete(deviceId, error);
}
}
void SetUpCodePairer::OnDeviceDiscoveredTimeoutCallback(System::Layer * layer, void * context)
{
ChipLogError(Controller, "Discovery timed out");
auto * pairer = static_cast<SetUpCodePairer *>(context);
// If a PASE attempt is in progress, do not stop physical-proximity
// transports (BLE, Wi-Fi PAF, NFC) — they have their own completion/timeout
// mechanisms. DNS-SD, however, runs indefinitely, so stop it now to
// prevent DiscoveryInProgress() from being true forever.
if (pairer->mWaitingForPASE)
{
LogErrorOnFailure(pairer->StopDiscoveryOverDNSSD());
return;
}
// No PASE in progress — stop all remaining discovery and fail if nothing is left to try.
pairer->StopAllDiscoveryAttempts();
pairer->StopPairingIfTransportsExhausted(CHIP_ERROR_TIMEOUT);
}
bool SetUpCodePairer::ShouldDiscoverUsing(RendezvousInformationFlag commissioningChannel) const
{
for (auto & payload : mSetupPayloads)
{
auto & rendezvousInformation = payload.rendezvousInformation;
if (!rendezvousInformation.HasValue())
{
// No idea which commissioning channels this device supports, so we
// should be trying using all of them.
return true;
}
if (rendezvousInformation.Value().Has(commissioningChannel))
{
return true;
}
}
// None of the payloads claimed support for this commissioning channel.
return false;
}
SetUpCodePairerParameters::SetUpCodePairerParameters(const Dnssd::CommonResolutionData & data,
std::optional<uint16_t> longDiscriminator, size_t index) :
mLongDiscriminator(longDiscriminator)
{
mInterfaceId = data.interfaceId;
Platform::CopyString(mHostName, data.hostName);
auto & ip = data.ipAddress[index];
SetPeerAddress(Transport::PeerAddress::UDP(ip, data.port, ip.IsIPv6LinkLocal() ? data.interfaceId : Inet::InterfaceId::Null()));
if (data.mrpRetryIntervalIdle.has_value())
{
SetIdleInterval(*data.mrpRetryIntervalIdle);
}
if (data.mrpRetryIntervalActive.has_value())
{
SetActiveInterval(*data.mrpRetryIntervalActive);
}
}
#if CONFIG_NETWORK_LAYER_BLE
SetUpCodePairerParameters::SetUpCodePairerParameters(BLE_CONNECTION_OBJECT connObj, std::optional<uint16_t> longDiscriminator,
bool connected) :
mLongDiscriminator(longDiscriminator)
{
Transport::PeerAddress peerAddress = Transport::PeerAddress::BLE();
SetPeerAddress(peerAddress);
if (connected)
{
SetConnectionObject(connObj);
}
else
{
SetDiscoveredObject(connObj);
}
}
#endif // CONFIG_NETWORK_LAYER_BLE
} // namespace Controller
} // namespace chip