-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathHAPBLEPeripheralManager.c
1749 lines (1569 loc) · 74.5 KB
/
HAPBLEPeripheralManager.c
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015-2019 The HomeKit ADK Contributors
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors.
#include "HAP+Internal.h"
static const HAPLogObject logObject = { .subsystem = kHAP_LogSubsystem, .category = "BLEPeripheralManager" };
#define DEBUG_DISABLE_TIMEOUTS (false)
/**
* Fallback procedure status.
*
* - Fallback procedures can only return very simple information and can't access characteristics.
* /!\ If this is ever extended, proper checking for transient Pair Setup procedures is necessary!
*/
HAP_ENUM_BEGIN(uint8_t, HAPBLEFallbackProcedureStatus) {
/** Max-Procedures. */
kHAPBLEFallbackProcedureStatus_MaxProcedures = 1,
/** Invalid instance ID. */
kHAPBLEFallbackProcedureStatus_InvalidInstanceID,
/** Operation is service signature read, and instance ID was 0. */
kHAPBLEFallbackProcedureStatus_ZeroInstanceIDServiceSignatureRead
} HAP_ENUM_END(uint8_t, HAPBLEFallbackProcedureStatus);
/**
* Fallback procedure state.
*
* - This keeps track of procedures beyond the maximum procedure limit.
*/
typedef struct {
/**
* Timer after which the procedure expires.
*
* - If this is 0, the procedure is not active.
*/
HAPPlatformTimerRef timer;
/** Remaining body bytes in the request before a response may be sent. */
uint16_t remainingBodyBytes;
/** Transaction ID of the procedure. */
uint8_t transactionID;
/** Status of the procedure. */
HAPBLEFallbackProcedureStatus status;
} HAPBLEFallbackProcedure;
HAP_STATIC_ASSERT(sizeof(HAPBLEFallbackProcedure) <= 16, HAPBLEFallbackProcedureMustBeKeptSmall);
typedef struct {
/**
* The linked HomeKit characteristic.
*
* - If this is NULL, the entry is only linked to a HomeKit service.
*/
const HAPCharacteristic* _Nullable characteristic;
/**
* The linked HomeKit service.
*
* - If this is NULL, the table entry is not used.
*/
const HAPService* _Nullable service;
/**
* The linked HomeKit accessory.
*
* - If this is NULL, the table entry is not used.
*/
const HAPAccessory* _Nullable accessory;
/**
* Attribute handle of the Characteristic Value declaration.
*/
HAPPlatformBLEPeripheralManagerAttributeHandle valueHandle;
/**
* Attribute handle of the added Client Characteristic Configuration descriptor.
*
* - This is only available for HomeKit characteristics that support HAP Events.
*
* - If BLE Indications are enabled, the value of this descriptor contains ((uint16_t) 0x0002) in little endian.
* If BLE Indications are disabled, the value of this descriptor contains ((uint16_t) 0x0000) in little endian.
*/
HAPPlatformBLEPeripheralManagerAttributeHandle cccDescriptorHandle;
/**
* For HomeKit characteristics: Attribute handle of the added Characteristic Instance ID descriptor.
* For HomeKit services: Characteristic Value declaration of the added Service Instance ID characteristic.
*/
HAPPlatformBLEPeripheralManagerAttributeHandle iidHandle;
/**
* State related about the connected controller.
*/
struct {
/**
* Fallback procedure in case there are not enough resources to use a full-featured one.
*/
HAPBLEFallbackProcedure fallbackProcedure;
/**
* Whether or not the connected central subscribed to this characteristic.
*
* - This is only available for HomeKit characteristics that support HAP Events.
*/
bool centralSubscribed : 1;
/**
* Whether or not the characteristic value changed since the last read by the connected controller.
*
* - This is only maintained for HomeKit characteristics that support HAP Events.
*/
bool pendingEvent : 1;
} connectionState;
} HAPBLEGATTTableElement;
HAP_STATIC_ASSERT(sizeof(HAPBLEGATTTableElementRef) >= sizeof(HAPBLEGATTTableElement), HAPBLEGATTTableElement);
HAP_NONNULL_SUPPORT(HAPBLEGATTTableElement)
/**
* Resets the state of HAP Events.
*
* @param server_ Accessory server.
*/
static void ResetEventState(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPLogDebug(&logObject, "%s", __func__);
for (size_t i = 0; i < server->ble.storage->numGATTTableElements; i++) {
HAPBLEGATTTableElement* gattAttribute = (HAPBLEGATTTableElement*) &server->ble.storage->gattTableElements[i];
if (!gattAttribute->accessory) {
break;
}
gattAttribute->connectionState.centralSubscribed = false;
gattAttribute->connectionState.pendingEvent = false;
}
}
/**
* Aborts all fallback HAP-BLE procedures.
*
* @param server_ Accessory server.
*/
static void AbortAllFallbackProcedures(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPLogDebug(&logObject, "%s", __func__);
for (size_t i = 0; i < server->ble.storage->numGATTTableElements; i++) {
HAPBLEGATTTableElement* gattAttribute = (HAPBLEGATTTableElement*) &server->ble.storage->gattTableElements[i];
if (!gattAttribute->accessory) {
break;
}
if (gattAttribute->connectionState.fallbackProcedure.timer) {
const HAPAccessory* accessory = gattAttribute->accessory;
HAPAssert(gattAttribute->service);
HAPAssert(gattAttribute->characteristic);
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
HAPLogCharacteristicInfo(&logObject, characteristic, service, accessory, "Aborting fallback procedure.");
#if !DEBUG_DISABLE_TIMEOUTS
HAPPlatformTimerDeregister(gattAttribute->connectionState.fallbackProcedure.timer);
#endif
HAPRawBufferZero(
&gattAttribute->connectionState.fallbackProcedure,
sizeof gattAttribute->connectionState.fallbackProcedure);
}
}
}
void HAPBLEPeripheralManagerRelease(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.ble.blePeripheralManager);
HAPPlatformBLEPeripheralManager* blePeripheralManager = server->platform.ble.blePeripheralManager;
// Abort procedures.
AbortAllFallbackProcedures(server_);
if (server->ble.connection.procedureAttached) {
HAPBLEProcedureDestroy(&server->ble.storage->procedures[0]);
server->ble.connection.procedureAttached = false;
}
// Abort connections.
if (server->ble.connection.connected) {
HAPAssert(server->ble.storage->session);
HAPSessionRelease(server_, server->ble.storage->session);
server->ble.connection.connected = false;
}
// Deregister platform callbacks.
HAPPlatformBLEPeripheralManagerRemoveAllServices(blePeripheralManager);
HAPPlatformBLEPeripheralManagerSetDelegate(blePeripheralManager, NULL);
}
static void HandleConnectedCentral(
HAPPlatformBLEPeripheralManagerRef blePeripheralManager,
HAPPlatformBLEPeripheralManagerConnectionHandle connectionHandle,
void* _Nullable context) {
HAPPrecondition(blePeripheralManager);
HAPPrecondition(context);
HAPAccessoryServerRef* server_ = context;
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->ble.storage->session);
HAPSessionRef* session = server->ble.storage->session;
HAPError err;
HAPLogInfo(&logObject, "%s(0x%04x)", __func__, connectionHandle);
HAPPrecondition(!server->ble.connection.connected);
AbortAllFallbackProcedures(server_);
ResetEventState(server_);
server->ble.connection.connectionHandle = connectionHandle;
server->ble.connection.connected = true;
err = HAPBLEAccessoryServerDidConnect(server_);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
HAPSessionCreate(server_, session, kHAPTransportType_BLE);
}
static void HandleDisconnectedCentral(
HAPPlatformBLEPeripheralManagerRef blePeripheralManager,
HAPPlatformBLEPeripheralManagerConnectionHandle connectionHandle,
void* _Nullable context) {
HAPPrecondition(blePeripheralManager);
HAPPrecondition(context);
HAPAccessoryServerRef* server_ = context;
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->ble.storage->session);
HAPSessionRef* session = server->ble.storage->session;
HAPError err;
HAPLogInfo(&logObject, "%s(0x%04x)", __func__, connectionHandle);
HAPPrecondition(server->ble.connection.connected);
HAPPrecondition(connectionHandle == server->ble.connection.connectionHandle);
server->ble.connection.connected = false;
if (server->ble.connection.procedureAttached) {
HAPAssert(server->ble.storage->numProcedures >= 1);
HAPBLEProcedureDestroy(&server->ble.storage->procedures[0]);
}
AbortAllFallbackProcedures(server_);
HAPSessionRelease(server_, session);
ResetEventState(server_);
HAPRawBufferZero(&server->ble.connection, sizeof server->ble.connection);
err = HAPBLEAccessoryServerDidDisconnect(server_);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
}
/**
* Continues sending of pending HAP event notifications.
*
* @param server_ Accessory server.
*/
static void SendPendingEventNotifications(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.ble.blePeripheralManager);
HAPPlatformBLEPeripheralManagerRef blePeripheralManager = server->platform.ble.blePeripheralManager;
HAPPrecondition(server->ble.connection.connected);
HAPPrecondition(server->ble.storage->session);
HAPSessionRef* session = server->ble.storage->session;
HAPError err;
for (size_t i = 0; i < server->ble.storage->numGATTTableElements; i++) {
HAPBLEGATTTableElement* gattAttribute = (HAPBLEGATTTableElement*) &server->ble.storage->gattTableElements[i];
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
const HAPService* service = gattAttribute->service;
const HAPAccessory* accessory = gattAttribute->accessory;
if (!accessory) {
break;
}
HAPAssert(service);
if (!characteristic) {
continue;
}
if (!characteristic->properties.supportsEventNotification) {
HAPAssert(!gattAttribute->connectionState.centralSubscribed);
HAPAssert(!gattAttribute->connectionState.pendingEvent);
continue;
}
if (characteristic->iid > UINT16_MAX) {
HAPLogCharacteristicError(
&logObject,
characteristic,
service,
accessory,
"Not sending Handle Value Indication because characteristic instance ID is not supported.");
continue;
}
HAPAssert(gattAttribute->valueHandle);
HAPAssert(gattAttribute->cccDescriptorHandle);
HAPAssert(gattAttribute->iidHandle);
if (!gattAttribute->connectionState.centralSubscribed) {
continue;
}
if (!gattAttribute->connectionState.pendingEvent) {
continue;
}
if (!HAPSessionIsSecured(session)) {
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Not sending Handle Value Indication because the session is not secured.");
return;
}
if (HAPSessionIsTransient(session)) {
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Not sending Handle Value Indication because the session is transient.");
return;
}
if (HAPCharacteristicReadRequiresAdminPermissions(characteristic) && !HAPSessionControllerIsAdmin(session)) {
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Not sending Handle Value Indication because event notification values will only be delivered to "
"controllers with admin permissions.");
continue;
}
err = HAPPlatformBLEPeripheralManagerSendHandleValueIndication(
blePeripheralManager,
server->ble.connection.connectionHandle,
gattAttribute->valueHandle,
/* bytes: */ NULL,
/* numBytes: */ 0);
if (err == kHAPError_InvalidState) {
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Delayed event sending until ready to update subscribers.");
return;
} else if (err) {
HAPAssert(err == kHAPError_OutOfResources);
HAPFatalError();
}
gattAttribute->connectionState.pendingEvent = false;
HAPLogCharacteristicInfo(&logObject, characteristic, service, accessory, "Sent event.");
err = HAPBLEAccessoryServerDidSendEventNotification(server_, characteristic, service, accessory);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
}
}
/**
* Gets the GATT attribute structure associated with an attribute handle.
*
* @param server_ Accessory server.
* @param attributeHandle GATT attribute handle.
*
* @return GATT attribute structure If found.
* @return NULL Otherwise.
*/
static HAPBLEGATTTableElement* _Nullable GetGATTAttribute(
HAPAccessoryServerRef* server_,
HAPPlatformBLEPeripheralManagerAttributeHandle attributeHandle) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(attributeHandle);
for (size_t i = 0; i < server->ble.storage->numGATTTableElements; i++) {
HAPBLEGATTTableElement* gattAttribute = (HAPBLEGATTTableElement*) &server->ble.storage->gattTableElements[i];
if (!gattAttribute->accessory) {
break;
}
// Validate GATT attribute.
HAPAssert(gattAttribute->service);
if (!gattAttribute->characteristic) {
HAPAssert(!gattAttribute->valueHandle);
HAPAssert(!gattAttribute->cccDescriptorHandle);
} else {
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
HAPAssert(gattAttribute->valueHandle);
if (!characteristic->properties.supportsEventNotification) {
HAPAssert(!gattAttribute->cccDescriptorHandle);
}
}
HAPAssert(gattAttribute->iidHandle);
// Check for match.
if (attributeHandle == gattAttribute->valueHandle || attributeHandle == gattAttribute->cccDescriptorHandle ||
attributeHandle == gattAttribute->iidHandle) {
return gattAttribute;
}
}
HAPLog(&logObject, "GATT attribute structure not found for handle 0x%04x", (unsigned int) attributeHandle);
return NULL;
}
HAP_RESULT_USE_CHECK
static bool AreNotificationsEnabled(
HAPAccessoryServerRef* server,
HAPSessionRef* session,
HAPBLEGATTTableElement* gattAttribute) {
HAPPrecondition(server);
HAPPrecondition(session);
HAPPrecondition(gattAttribute);
const HAPCharacteristic* characteristic = HAPNonnullVoid(gattAttribute->characteristic);
const HAPService* service HAP_UNUSED = HAPNonnull(gattAttribute->service);
const HAPAccessory* accessory = HAPNonnull(gattAttribute->accessory);
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Events are %s.",
gattAttribute->connectionState.centralSubscribed ? "enabled" : "disabled");
return gattAttribute->connectionState.centralSubscribed;
}
static void SetNotificationsEnabled(
HAPAccessoryServerRef* server,
HAPSessionRef* session,
HAPBLEGATTTableElement* gattAttribute,
bool enable) {
HAPPrecondition(server);
HAPPrecondition(session);
HAPPrecondition(gattAttribute);
const HAPCharacteristic* characteristic = gattAttribute->characteristic;
const HAPService* service = gattAttribute->service;
const HAPAccessory* accessory = gattAttribute->accessory;
HAPLogCharacteristicInfo(
&logObject, characteristic, service, accessory, "%s events.", enable ? "Enabling" : "Disabling");
if (gattAttribute->connectionState.centralSubscribed == enable) {
return;
}
gattAttribute->connectionState.centralSubscribed = enable;
// Inform application.
if (HAPSessionIsSecured(session)) {
HAPLogCharacteristicDebug(
&logObject,
characteristic,
service,
accessory,
"Informing application about %s of events.",
enable ? "enabling" : "disabling");
if (enable) {
HAPAccessoryServerHandleSubscribe(server, session, characteristic, service, accessory);
} else {
HAPAccessoryServerHandleUnsubscribe(server, session, characteristic, service, accessory);
}
} else {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Session is not secured. Delaying to inform application about %s of events.",
enable ? "enabling" : "disabling");
}
// Subscription state changed. Continue sending events.
SendPendingEventNotifications(server);
}
#if !DEBUG_DISABLE_TIMEOUTS
static void FallbackProcedureTimerExpired(HAPPlatformTimerRef timer, void* _Nullable context) {
HAPPrecondition(context);
HAPAccessoryServerRef* server_ = context;
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPLogDebug(&logObject, "%s", __func__);
// 39. Accessories must implement a 10 second HAP procedure timeout, all HAP procedures [...] must complete within
// 10 seconds, if a procedure fails to complete within the procedure timeout the accessory must drop the security
// session and also drop the Bluetooth link.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
for (size_t i = 0; i < server->ble.storage->numGATTTableElements; i++) {
HAPBLEGATTTableElement* gattAttribute = (HAPBLEGATTTableElement*) &server->ble.storage->gattTableElements[i];
if (!gattAttribute->accessory) {
break;
}
if (gattAttribute->connectionState.fallbackProcedure.timer != timer) {
continue;
}
const HAPAccessory* accessory = gattAttribute->accessory;
HAPAssert(gattAttribute->service);
HAPAssert(gattAttribute->characteristic);
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
HAPLogCharacteristicInfo(&logObject, characteristic, service, accessory, "Fallback procedure expired.");
#if !DEBUG_DISABLE_TIMEOUTS
HAPPlatformTimerDeregister(gattAttribute->connectionState.fallbackProcedure.timer);
#endif
HAPRawBufferZero(
&gattAttribute->connectionState.fallbackProcedure,
sizeof gattAttribute->connectionState.fallbackProcedure);
}
HAPAssert(server->ble.connection.connected);
HAPAssert(server->ble.storage->session);
HAPSessionRef* session = server->ble.storage->session;
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
}
#endif
/**
* HAP-BLE procedure type.
*/
HAP_ENUM_BEGIN(uint8_t, HAPBLEProcedureType) { /**
* Full-featured procedure.
*
* - Associated type: HAPBLEProcedureRef
*/
kHAPBLEProcedureType_Full = 1,
/**
* Fallback procedure.
*
* - Associated type: HAPBLEFallbackProcedure
*/
kHAPBLEProcedureType_Fallback
} HAP_ENUM_END(uint8_t, HAPBLEProcedureType);
/**
* Checks that a value matches the claimed HAPBLEProcedureType.
*
* - Argument numbers start at 1.
*
* @param valueArg Argument number of the value.
* @param typeArg Argument number of the value type.
*/
#if __has_attribute(pointer_with_type_tag) && __has_attribute(type_tag_for_datatype)
/**@cond */
__attribute__((type_tag_for_datatype(HAPBLEProcedureType, HAPBLEProcedureRef*))) static const HAPBLEProcedureType
_kHAPBLEProcedureType_Full HAP_UNUSED = kHAPBLEProcedureType_Full;
__attribute__((type_tag_for_datatype(HAPBLEProcedureType, HAPBLEFallbackProcedure*))) static const HAPBLEProcedureType
_kHAPBLEProcedureType_Fallback HAP_UNUSED = kHAPBLEProcedureType_Fallback;
/**@endcond */
#define HAP_PWT_HAPBLEProcedureType(valueArg, typeArg) \
__attribute__((pointer_with_type_tag(HAPBLEProcedureType, valueArg, typeArg)))
#else
#define HAP_PWT_HAPBLEProcedureType(valueArg, typeArg)
#endif
/**
* Gets the HAP-BLE procedure for a GATT attribute.
*
* @param server_ Accessory server.
* @param session_ The session over which the request has been received.
* @param gattAttribute The GATT attribute that is accessed.
* @param[out] procedureType Type of the attached procedure.
* @param[out] procedure HAP-BLE procedure.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidState If no procedure can be fetched at this time.
*/
HAP_PWT_HAPBLEProcedureType(5, 4) HAP_RESULT_USE_CHECK static HAPError GetProcedure(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
HAPBLEGATTTableElement* gattAttribute,
HAPBLEProcedureType* procedureType,
void* _Nonnull* _Nonnull procedure) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.ble.blePeripheralManager);
HAPPlatformBLEPeripheralManagerRef blePeripheralManager = server->platform.ble.blePeripheralManager;
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(gattAttribute);
HAPPrecondition(gattAttribute->characteristic);
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
HAPPrecondition(gattAttribute->service);
HAPPrecondition(gattAttribute->accessory);
const HAPAccessory* accessory = gattAttribute->accessory;
HAPPrecondition(procedureType);
HAPPrecondition(procedure);
// For now, we only support 1 concurrent full-featured procedure.
HAPPrecondition(server->ble.storage->procedures);
HAPPrecondition(server->ble.storage->procedures);
HAPPrecondition(server->ble.storage->numProcedures >= 1);
HAPBLEProcedureRef* fullProcedure = &server->ble.storage->procedures[0];
// Every characteristic supports a fallback procedure.
HAPBLEFallbackProcedure* fallbackProcedure = &gattAttribute->connectionState.fallbackProcedure;
// If session is terminal, no more requests may be accepted.
if (HAPBLESessionIsTerminal(&session->_.ble)) {
HAPLogCharacteristic(&logObject, characteristic, service, accessory, "Rejecting request: Session is terminal.");
HAPPlatformBLEPeripheralManagerCancelCentralConnection(
blePeripheralManager, server->ble.connection.connectionHandle);
return kHAPError_InvalidState;
}
// An accessory must cancel any pending procedures when a new HAP secure session starts getting established.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.1 HAP Transactions and Procedures
if (HAPBLECharacteristicDropsSecuritySession(characteristic)) {
HAPLogCharacteristicDebug(
&logObject,
characteristic,
service,
accessory,
"Aborting fallback procedure (%s).",
"Characteristic drops security session");
AbortAllFallbackProcedures(server_);
}
// Check if already attached to the same characteristic (fallback procedure).
if (gattAttribute->connectionState.fallbackProcedure.timer) {
*procedureType = kHAPBLEProcedureType_Fallback;
*procedure = fallbackProcedure;
return kHAPError_None;
}
// Check if already attached to the same characteristic (full procedure).
if (server->ble.connection.procedureAttached) {
const HAPBaseCharacteristic* attachedCharacteristic = HAPBLEProcedureGetAttachedCharacteristic(fullProcedure);
HAPAssert(attachedCharacteristic);
if (attachedCharacteristic == characteristic) {
*procedureType = kHAPBLEProcedureType_Full;
*procedure = fullProcedure;
return kHAPError_None;
}
}
// Unsolicited read request.
// 12. Accessory must reject GATT Read Requests on a HAP characteristic if it was not preceded by an
// GATT Write Request with the same transaction ID at most 10 seconds prior.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
return kHAPError_InvalidState;
}
HAP_RESULT_USE_CHECK
static HAPError HandleReadRequest(
HAPPlatformBLEPeripheralManagerRef blePeripheralManager,
HAPPlatformBLEPeripheralManagerConnectionHandle connectionHandle,
HAPPlatformBLEPeripheralManagerAttributeHandle attributeHandle,
void* bytes,
size_t maxBytes,
size_t* numBytes,
void* _Nullable context) {
HAPPrecondition(blePeripheralManager);
HAPPrecondition(attributeHandle);
HAPPrecondition(bytes);
HAPPrecondition(numBytes);
HAPPrecondition(context);
HAPAccessoryServerRef* server_ = context;
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->ble.storage->session);
HAPSessionRef* session = server->ble.storage->session;
HAPError err;
HAPLogDebug(&logObject, "%s(0x%04x, 0x%04x)", __func__, connectionHandle, attributeHandle);
HAPPrecondition(server->ble.connection.connected);
HAPPrecondition(connectionHandle == server->ble.connection.connectionHandle);
HAPBLEGATTTableElement* _Nullable gattAttribute = GetGATTAttribute(server_, attributeHandle);
HAPPrecondition(gattAttribute);
const HAPBaseCharacteristic* _Nullable characteristic = gattAttribute->characteristic;
const HAPService* _Nullable service = gattAttribute->service;
const HAPAccessory* _Nullable accessory = gattAttribute->accessory;
if (attributeHandle == gattAttribute->valueHandle) {
HAPAssert(characteristic);
HAPAssert(service);
HAPAssert(accessory);
HAPLogCharacteristicDebug(&logObject, characteristic, service, accessory, "GATT Read value.");
// Get HAP-BLE procedure.
HAPBLEProcedureType procedureType;
void* procedure;
err = GetProcedure(server_, session, gattAttribute, &procedureType, &procedure);
if (err) {
HAPAssert(err == kHAPError_InvalidState);
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
return err;
}
// Process request.
switch (procedureType) {
case kHAPBLEProcedureType_Full: {
HAPBLEProcedureRef* fullProcedure = procedure;
// Process request.
err = HAPBLEProcedureHandleGATTRead(fullProcedure, bytes, maxBytes, numBytes);
if (err) {
HAPAssert(err == kHAPError_InvalidState || err == kHAPError_OutOfResources);
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
return err;
}
} break;
case kHAPBLEProcedureType_Fallback: {
HAPBLEFallbackProcedure* fallbackProcedure = procedure;
HAPLogCharacteristicInfo(
&logObject, characteristic, service, accessory, "Processing response of fallback procedure.");
if (fallbackProcedure->remainingBodyBytes) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Response of fallback procedure expected before request was fully sent.");
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
return kHAPError_InvalidState;
}
// Compute response length.
*numBytes = 3;
switch (fallbackProcedure->status) {
case kHAPBLEFallbackProcedureStatus_MaxProcedures:
case kHAPBLEFallbackProcedureStatus_InvalidInstanceID: {
*numBytes += 0;
} break;
case kHAPBLEFallbackProcedureStatus_ZeroInstanceIDServiceSignatureRead: {
*numBytes += 2; // Body length.
*numBytes += 2;
} break;
}
// When Pair Verify is accessed, all fallback procedures are cancelled.
// Therefore, we do not need to remember whether or not the procedure has been secured at start.
bool isSecured = HAPSessionIsSecured(session);
if (isSecured) {
*numBytes += CHACHA20_POLY1305_TAG_BYTES;
}
if (maxBytes < *numBytes) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Response of fallback procedure on too long for available space.");
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
return kHAPError_OutOfResources;
}
// Serialize response.
uint8_t* data = bytes;
data[0] = (0 << 7) | (0 << 3) | (0 << 2) | (1 << 1) | (0 << 0);
data[1] = fallbackProcedure->transactionID;
switch (fallbackProcedure->status) {
case kHAPBLEFallbackProcedureStatus_MaxProcedures: {
HAPLogCharacteristic(
&logObject, characteristic, service, accessory, "Sending Max-Procedures error.");
data[2] = kHAPBLEPDUStatus_MaxProcedures;
} break;
case kHAPBLEFallbackProcedureStatus_InvalidInstanceID: {
HAPLogCharacteristic(
&logObject, characteristic, service, accessory, "Sending Invalid Instance ID error.");
data[2] = kHAPBLEPDUStatus_InvalidInstanceID;
} break;
case kHAPBLEFallbackProcedureStatus_ZeroInstanceIDServiceSignatureRead: {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Sending default service signature response (iid 0).");
data[2] = kHAPBLEPDUStatus_Success;
HAPWriteLittleUInt16(&data[3], 2);
data[5] = kHAPBLEPDUTLVType_HAPLinkedServices;
data[6] = 0;
} break;
}
// Encrypt response if necessary.
if (isSecured) {
err = HAPSessionEncryptControlMessage(
server_, session, bytes, bytes, *numBytes - CHACHA20_POLY1305_TAG_BYTES);
if (err) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Response of fallback procedure could not be encrypted.");
HAPAssert(err == kHAPError_InvalidState);
HAPSessionInvalidate(server_, session, /* terminateLink: */ true);
return err;
}
}
// Reset procedure.
HAPAssert(fallbackProcedure->timer);
#if !DEBUG_DISABLE_TIMEOUTS
HAPPlatformTimerDeregister(fallbackProcedure->timer);
#endif
HAPRawBufferZero(fallbackProcedure, sizeof *fallbackProcedure);
// Report response being sent.
HAPBLESessionDidSendGATTResponse(server_, session);
} break;
}
// Continue sending events (if security state changed).
SendPendingEventNotifications(server_);
} else if (attributeHandle == gattAttribute->cccDescriptorHandle) {
HAPAssert(characteristic);
HAPAssert(service);
HAPAssert(accessory);
HAPLogCharacteristicDebug(
&logObject,
characteristic,
service,
accessory,
"GATT Read Client Characteristic Configuration descriptor value.");
// This descriptor value must support always being read in the clear, i.e. with or without a security session.
// See HomeKit Accessory Protocol Specification R14
// Section 7.4.4.5.3 Client Characteristic Configuration
// Process request.
if (maxBytes < 2) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Not enough space available to write Client Characteristic Configuration descriptor value.");
return kHAPError_OutOfResources;
}
bool isEnabled = AreNotificationsEnabled(server_, session, gattAttribute);
HAPWriteLittleUInt16(bytes, isEnabled ? 0x0002u : 0x0000u);
*numBytes = sizeof(uint16_t);
} else {
HAPAssert(attributeHandle == gattAttribute->iidHandle);
HAPAssert(service);
HAPAssert(accessory);
if (characteristic) {
HAPLogCharacteristicDebug(
&logObject,
characteristic,
service,
accessory,
"GATT Read Characteristic Instance ID descriptor value.");
// Process request.
if (maxBytes < 2) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Not enough space available to write Characteristic Instance ID descriptor value.");
return kHAPError_OutOfResources;
}
HAPAssert(characteristic->iid <= UINT16_MAX);
HAPWriteLittleUInt16(bytes, characteristic->iid);
*numBytes = sizeof(uint16_t);
} else {
HAPLogServiceDebug(&logObject, service, accessory, "GATT Read Service Instance ID descriptor value.");
// Process request.
if (maxBytes < 2) {
HAPLogService(
&logObject,
service,
accessory,
"Not enough space available to write Service Instance ID descriptor value.");
return kHAPError_OutOfResources;
}
HAPAssert(service->iid <= UINT16_MAX);
HAPWriteLittleUInt16(bytes, service->iid);
*numBytes = sizeof(uint16_t);
}
}
return kHAPError_None;
}
/**
* Attaches a HAP-BLE procedure.
*
* @param server_ Accessory server.
* @param session_ The session over which the request has been received.
* @param gattAttribute The GATT attribute that is accessed.
* @param[out] procedureType Type of the attached procedure.
* @param[out] procedure HAP-BLE procedure.
* @param[out] isNewProcedure Whether a new or existing procedure was attached. true = new.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidState If no procedure can be fetched at this time.
* @return kHAPError_OutOfResources If no procedure is available.
*/
HAP_PWT_HAPBLEProcedureType(5, 4) HAP_RESULT_USE_CHECK static HAPError AttachProcedure(
HAPAccessoryServerRef* server_,
HAPSessionRef* session_,
HAPBLEGATTTableElement* gattAttribute,
HAPBLEProcedureType* procedureType,
void* _Nonnull* _Nonnull procedure,
bool* isNewProcedure) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.ble.blePeripheralManager);
HAPPlatformBLEPeripheralManagerRef blePeripheralManager = server->platform.ble.blePeripheralManager;
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(gattAttribute);
HAPPrecondition(gattAttribute->characteristic);
const HAPBaseCharacteristic* characteristic = gattAttribute->characteristic;
HAPPrecondition(gattAttribute->service);
const HAPService* service = gattAttribute->service;
HAPPrecondition(gattAttribute->accessory);
const HAPAccessory* accessory = gattAttribute->accessory;
HAPPrecondition(procedureType);
HAPPrecondition(procedure);
HAPPrecondition(isNewProcedure);
#if !DEBUG_DISABLE_TIMEOUTS
HAPError err;
#endif
// For now, we only support 1 concurrent full-featured procedure.
HAPPrecondition(server->ble.storage->procedures);
HAPPrecondition(server->ble.storage->procedures);
HAPPrecondition(server->ble.storage->numProcedures >= 1);
HAPBLEProcedureRef* fullProcedure = &server->ble.storage->procedures[0];
// Every characteristic supports a fallback procedure.
HAPBLEFallbackProcedure* fallbackProcedure = &gattAttribute->connectionState.fallbackProcedure;
// If session is terminal, no more requests may be accepted.
if (HAPBLESessionIsTerminal(&session->_.ble)) {
HAPLogCharacteristic(&logObject, characteristic, service, accessory, "Rejecting request: Session is terminal.");
HAPPlatformBLEPeripheralManagerCancelCentralConnection(
blePeripheralManager, server->ble.connection.connectionHandle);
return kHAPError_InvalidState;
}
// Handle shut down.
if (server->state != kHAPAccessoryServerState_Running) {
if (server->ble.connection.procedureAttached && HAPBLEProcedureIsInProgress(fullProcedure)) {
// Allow finishing procedure to avoid dealing with bugs from halfway completed procedures.
// Fallback procedures do not modify any state, so it's okay to abort them while they are ongoing.
// Procedures have a timeout so this cannot delay forever.
HAPLogCharacteristicInfo(
&logObject,
characteristic,
service,
accessory,
"Shutdown has been requested. Allowing current HAP-BLE procedure to finish.");
} else {
// Do not start new procedures and abort pending fallback procedures.
HAPLogCharacteristic(
&logObject, characteristic, service, accessory, "Rejecting request: Shutdown requested.");
HAPPlatformBLEPeripheralManagerCancelCentralConnection(
blePeripheralManager, server->ble.connection.connectionHandle);
return kHAPError_InvalidState;
}
}
// An accessory must cancel any pending procedures when a new HAP secure session starts getting established.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.1 HAP Transactions and Procedures
if (HAPBLECharacteristicDropsSecuritySession(characteristic)) {