-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathHAPBLEProcedure.c
1328 lines (1214 loc) · 58.2 KB
/
HAPBLEProcedure.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 = "BLEProcedure" };
// Set this flag to disable all BLE procedure timeouts.
#define DEBUG_DISABLE_TIMEOUTS (false)
void HAPBLEProcedureAttach(
HAPBLEProcedureRef* bleProcedure_,
void* scratchBytes,
size_t numScratchBytes,
HAPAccessoryServerRef* server,
HAPSessionRef* session_,
const HAPCharacteristic* characteristic,
const HAPService* service,
const HAPAccessory* accessory) {
HAPPrecondition(bleProcedure_);
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
HAPPrecondition(scratchBytes);
HAPPrecondition(server);
HAPPrecondition(session_);
HAPSession* session = (HAPSession*) session_;
HAPPrecondition(session->transportType == kHAPTransportType_BLE);
HAPPrecondition(characteristic);
HAPPrecondition(service);
HAPPrecondition(accessory);
HAPRawBufferZero(bleProcedure, sizeof *bleProcedure);
bleProcedure->scratchBytes = scratchBytes;
bleProcedure->numScratchBytes = numScratchBytes;
bleProcedure->server = server;
bleProcedure->session = session_;
bleProcedure->characteristic = characteristic;
bleProcedure->service = service;
bleProcedure->accessory = accessory;
HAPBLETransactionCreate(&bleProcedure->transaction, bleProcedure->scratchBytes, bleProcedure->numScratchBytes);
bleProcedure->procedureTimer = 0;
}
void HAPBLEProcedureDestroy(HAPBLEProcedureRef* bleProcedure_) {
HAPPrecondition(bleProcedure_);
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
HAPLogDebug(&logObject, "%s", __func__);
if (bleProcedure->procedureTimer) {
#if !DEBUG_DISABLE_TIMEOUTS
HAPPlatformTimerDeregister(bleProcedure->procedureTimer);
#endif
bleProcedure->procedureTimer = 0;
}
}
static void HAPBLEProcedureReset(HAPBLEProcedureRef* bleProcedure_) {
HAPPrecondition(bleProcedure_);
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
void* scratchBytes = bleProcedure->scratchBytes;
size_t numScratchBytes = bleProcedure->numScratchBytes;
HAPAccessoryServerRef* server = bleProcedure->server;
HAPSessionRef* session = bleProcedure->session;
const HAPCharacteristic* characteristic = bleProcedure->characteristic;
const HAPService* service = bleProcedure->service;
const HAPAccessory* accessory = bleProcedure->accessory;
HAPBLEProcedureDestroy(bleProcedure_);
HAPBLEProcedureAttach(
bleProcedure_, scratchBytes, numScratchBytes, server, session, characteristic, service, accessory);
}
#if !DEBUG_DISABLE_TIMEOUTS
static void ProcedureTimerExpired(HAPPlatformTimerRef timer, void* _Nullable context) {
HAPPrecondition(context);
HAPBLEProcedureRef* bleProcedure_ = context;
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
HAPPrecondition(timer == bleProcedure->procedureTimer);
bleProcedure->procedureTimer = 0;
HAPLogDebug(&logObject, "%s", __func__);
// Any procedure that times out [...] shall result in the current HAP secure session being invalidated and a new
// session may be established by the controller.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.1 HAP Transactions and Procedures.
//
// 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
//
// 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
//
// ==> Having a 10 second procedure timeout that on expiry drops the security session and Bluetooth link fulfills
// all of these requirements. Since it is not defined when a procedure starts or ends, we assume that the timeout
// runs from the very first GATT write request until the very last GATT read request, and assume that there are no
// excess GATT read requests with empty fragments.
HAPBLEProcedureReset(bleProcedure_);
HAPSessionInvalidate(bleProcedure->server, bleProcedure->session, /* terminateLink: */ true);
}
#endif
const HAPCharacteristic* HAPBLEProcedureGetAttachedCharacteristic(const HAPBLEProcedureRef* bleProcedure_) {
HAPPrecondition(bleProcedure_);
const HAPBLEProcedure* bleProcedure = (const HAPBLEProcedure*) bleProcedure_;
return bleProcedure->characteristic;
}
HAP_RESULT_USE_CHECK
bool HAPBLEProcedureIsInProgress(const HAPBLEProcedureRef* bleProcedure_) {
HAPPrecondition(bleProcedure_);
const HAPBLEProcedure* bleProcedure = (const HAPBLEProcedure*) bleProcedure_;
return bleProcedure->procedureTimer != 0;
}
/**
* Destroys request body and creates response body writer.
*
* @param bleProcedure_ Procedure.
* @param[out] responseWriter Writer.
*/
static void DestroyRequestBodyAndCreateResponseBodyWriter(
HAPBLEProcedureRef* bleProcedure_,
HAPTLVWriterRef* responseWriter) {
HAPPrecondition(bleProcedure_);
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
HAPPrecondition(responseWriter);
size_t numBytes = bleProcedure->numScratchBytes;
if (numBytes > UINT16_MAX) {
// Maximum for HAP-BLE PDU. Note that the characteristic value TLV is even further limited by spec.
numBytes = UINT16_MAX;
}
HAPTLVWriterCreate(responseWriter, bleProcedure->scratchBytes, numBytes);
}
#define SEND_ERROR_AND_RETURN(STATUS) \
do { \
HAPBLETransactionSetResponse(&bleProcedure->transaction, (STATUS), NULL); \
return kHAPError_None; \
} while (0)
#define SEND_RESPONSE_AND_RETURN(BODY) \
do { \
HAPBLETransactionSetResponse(&bleProcedure->transaction, kHAPBLEPDUStatus_Success, (BODY)); \
return kHAPError_None; \
} while (0)
/**
* Handles a HAP-BLE transaction.
*
* @param bleProcedure_ Procedure.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidState If the request cannot be processed in the current state.
*/
HAP_RESULT_USE_CHECK
static HAPError HAPBLEProcedureProcessTransaction(HAPBLEProcedureRef* bleProcedure_) {
HAPPrecondition(bleProcedure_);
HAPBLEProcedure* bleProcedure = (HAPBLEProcedure*) bleProcedure_;
HAPPrecondition(bleProcedure->server);
HAPAccessoryServer* server = (HAPAccessoryServer*) bleProcedure->server;
HAPPrecondition(bleProcedure->accessory);
const HAPAccessory* accessory = bleProcedure->accessory;
HAPPrecondition(bleProcedure->service);
const HAPService* service = bleProcedure->service;
HAPPrecondition(bleProcedure->characteristic);
const HAPBaseCharacteristic* characteristic = bleProcedure->characteristic;
HAPError err;
// Get request.
HAPBLETransactionRequest request;
err = HAPBLETransactionGetRequest(&bleProcedure->transaction, &request);
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
// Validate opcode.
if (!HAPPDUIsValidOpcode(request.opcode)) {
// If an accessory receives a HAP PDU with an opcode that it does not support it shall reject the PDU and
// respond with a status code Unsupported PDU in its HAP response.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.3.2 HAP Request Format
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected request with unsupported opcode: 0x%02x.",
request.opcode);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// Check that HAP request's characteristic / service instance ID matches the addressed characteristic's instance ID.
HAPAssert(service->iid <= UINT16_MAX);
HAPAssert(characteristic->iid <= UINT16_MAX);
uint16_t iid;
if (HAPBLEPDUOpcodeIsServiceOperation(request.opcode)) {
iid = (uint16_t) service->iid;
} else {
iid = (uint16_t) characteristic->iid;
}
if (request.iid != iid) {
if (HAPBLEPDUOpcodeIsServiceOperation(request.opcode)) {
HAPLogService(
&logObject,
service,
accessory,
"Request's IID [00000000%08X] does not match the addressed IID.",
request.iid);
} else {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Request's IID [00000000%08X] does not match the addressed IID.",
request.iid);
}
if (request.opcode == kHAPPDUOpcode_ServiceSignatureRead) {
// If the accessory receives an invalid (eg., 0) service instance ID in the
// HAP-Service-Signature-Read-Request, it must respond with a valid HAP-Service-Signature-Read-Response with
// Svc Properties set to 0 and Linked Svc (if applicable) set to 0 length.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.4.13 HAP-Service-Signature-Read-Response
} else {
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidInstanceID);
}
}
// Handle request.
bool hasReturnResponse = true;
switch (request.opcode) {
case kHAPPDUOpcode_ServiceSignatureRead: {
// Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Service-Signature-Read-Request");
return kHAPError_InvalidState;
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.4.4.5.4 Service Signature Characteristic
if (!HAPBLECharacteristicSupportsServiceProcedures(characteristic)) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Not supported.",
"HAP-Service-Signature-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// HAP-Service-Signature-Read-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Service-Signature-Read-Response.
err = HAPBLEServiceGetSignatureReadResponse(request.iid == iid ? service : NULL, &writer);
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
}
case kHAPPDUOpcode_CharacteristicSignatureRead: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Characteristic-Signature-Read-Request");
return kHAPError_InvalidState;
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.1 HAP Characteristic Signature Read Procedure
// The characteristics `Pair Setup`, `Pair Verify` and `Pairing Features` of `Pairing Service`
// do not support "Paired Read" and "Paired Write" and only support the
// `HAP Characteristic Signature Read Procedure` without a secure session.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.1 HAP Characteristic Signature Read Procedure
if (HAPSessionIsSecured(bleProcedure->session) &&
HAPBLECharacteristicDropsSecuritySession(characteristic)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only non-secure access is permitted.",
"HAP-Characteristic-Signature-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// HAP-Characteristic-Signature-Read-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Characteristic-Signature-Read-Response.
err = HAPBLECharacteristicGetSignatureReadResponse(characteristic, service, &writer);
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
}
case kHAPPDUOpcode_CharacteristicConfiguration: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Characteristic-Configuration-Request");
return kHAPError_InvalidState;
}
if (HAPSessionIsTransient(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Session is transient.",
"HAP-Characteristic-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.8 HAP Characteristic Configuration Procedure
if (!HAPSessionIsSecured(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure access is permitted.",
"HAP-Characteristic-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// Handle HAP-Characteristic-Configuration-Request.
err = HAPBLECharacteristicHandleConfigurationRequest(
characteristic, service, accessory, &request.bodyReader, server->platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_InvalidData);
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Request handling failed with error %d.",
"HAP-Characteristic-Configuration-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
// HAP-Characteristic-Configuration-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Characteristic-Configuration-Response.
err = HAPBLECharacteristicGetConfigurationResponse(
characteristic, service, accessory, &writer, server->platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_OutOfResources);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
}
case kHAPPDUOpcode_ProtocolConfiguration: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Protocol-Configuration-Request");
return kHAPError_InvalidState;
}
if (HAPSessionIsTransient(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Session is transient.",
"HAP-Protocol-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.9 HAP Protocol Configuration Procedure
if (!HAPBLECharacteristicSupportsServiceProcedures(characteristic)) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Not supported.",
"HAP-Protocol-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!service->properties.ble.supportsConfiguration) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Service does not support configuration.",
"HAP-Protocol-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!HAPSessionIsSecured(bleProcedure->session)) {
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Only secure access is permitted.",
"HAP-Protocol-Configuration-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// Handle HAP-Protocol-Configuration-Request.
bool didRequestGetAll;
err = HAPBLEProtocolHandleConfigurationRequest(
bleProcedure->server,
bleProcedure->session,
service,
accessory,
&request.bodyReader,
&didRequestGetAll,
server->platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_InvalidData);
HAPLogService(
&logObject,
service,
accessory,
"Rejected %s: Request handling failed with error %d.",
"HAP-Protocol-Configuration-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
if (!didRequestGetAll) {
SEND_RESPONSE_AND_RETURN(NULL);
}
// HAP-Protocol-Configuration-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Protocol-Configuration-Response.
err = HAPBLEProtocolGetConfigurationResponse(
bleProcedure->server,
bleProcedure->session,
service,
accessory,
&writer,
server->platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_OutOfResources);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
}
case kHAPPDUOpcode_Token: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Token-Request");
return kHAPError_InvalidState;
}
// See HomeKit Accessory Protocol Specification R14
// Section 5.15.1 HAP-Token-Request
if (!HAPUUIDAreEqual(service->serviceType, &kHAPServiceType_HAPProtocolInformation) ||
!HAPUUIDAreEqual(characteristic->characteristicType, &kHAPCharacteristicType_ServiceSignature)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only supported on the Service Signature characteristic in the "
"HAP Protocol Information Service.",
"HAP-Token-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!HAPSessionIsSecured(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure access is permitted.",
"HAP-Token-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// HAP-Token-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Token-Response.
err = HAPMFiTokenAuthGetTokenResponse(bleProcedure->server, bleProcedure->session, accessory, &writer);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_InvalidState || err == kHAPError_OutOfResources);
HAPLogAccessory(
&logObject,
accessory,
"Rejected %s: Request handling failed with error %u.",
"HAP-Token-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
}
case kHAPPDUOpcode_TokenUpdate: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Token-Update-Request");
return kHAPError_InvalidState;
}
// See HomeKit Accessory Protocol Specification R14
// Section 5.15.3 HAP-Token-Update-Request
if (!HAPUUIDAreEqual(service->serviceType, &kHAPServiceType_HAPProtocolInformation) ||
!HAPUUIDAreEqual(characteristic->characteristicType, &kHAPCharacteristicType_ServiceSignature)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only supported on the Service Signature characteristic in the "
"HAP Protocol Information Service.",
"HAP-Token-Update-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!HAPSessionIsSecured(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure access is permitted.",
"HAP-Token-Update-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// Handle HAP-Token-Update-Request.
err = HAPMFiTokenAuthHandleTokenUpdateRequest(
bleProcedure->server, bleProcedure->session, accessory, &request.bodyReader);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_InvalidData);
HAPLogAccessory(
&logObject,
accessory,
"Rejected %s: Request handling failed with error %u.",
"HAP-Token-Update-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
// Send HAP-Token-Update-Response.
SEND_RESPONSE_AND_RETURN(NULL);
}
case kHAPPDUOpcode_Info: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Info-Request");
return kHAPError_InvalidState;
}
// See HomeKit Accessory Protocol Specification R14
// Section 5.15.5 HAP-Info-Request
if (!HAPUUIDAreEqual(service->serviceType, &kHAPServiceType_HAPProtocolInformation) ||
!HAPUUIDAreEqual(characteristic->characteristicType, &kHAPCharacteristicType_ServiceSignature)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only supported on Service Signature characteristic in the "
"HAP Protocol Information Service.",
"HAP-Info-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!HAPSessionIsSecured(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure access is permitted.",
"HAP-Info-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// HAP-Info-Request ok.
HAPTLVWriterRef writer;
DestroyRequestBodyAndCreateResponseBodyWriter(bleProcedure_, &writer);
// Serialize HAP-Info-Response.
err = HAPAccessoryGetInfoResponse(bleProcedure->server, bleProcedure->session, accessory, &writer);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_OutOfResources);
HAPLogAccessory(
&logObject,
accessory,
"Rejected %s: Request handler failed with error %d.",
"HAP-Info-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
SEND_RESPONSE_AND_RETURN(&writer);
};
case kHAPPDUOpcode_CharacteristicTimedWrite: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Characteristic-Timed-Write-Request");
return kHAPError_InvalidState;
}
if (HAPSessionIsTransient(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Session is transient.",
"HAP-Characteristic-Timed-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.4 HAP Characteristic Timed Write Procedure
// Cache body.
bleProcedure->multiTransactionType = kHAPBLEProcedureMultiTransactionType_TimedWrite;
HAPAssert(sizeof bleProcedure->_.timedWrite.bodyReader == sizeof request.bodyReader);
HAPRawBufferCopyBytes(
&bleProcedure->_.timedWrite.bodyReader,
&request.bodyReader,
sizeof bleProcedure->_.timedWrite.bodyReader);
// The accessory must start the TTL timer after sending the HAP-Characteristic-Timed-Write-Response.
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.4 HAP Characteristic Timed Write Procedure
bleProcedure->_.timedWrite.timedWriteStartTime = HAPPlatformClockGetCurrent();
SEND_RESPONSE_AND_RETURN(NULL);
}
case kHAPPDUOpcode_CharacteristicExecuteWrite: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_TimedWrite) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: No timed write in progress.",
"HAP-Characteristic-Execute-Write-Request");
return kHAPError_InvalidState;
}
HAPAssert(!HAPSessionIsTransient(bleProcedure->session));
bleProcedure->multiTransactionType = kHAPBLEProcedureMultiTransactionType_None;
HAPAssert(sizeof request.bodyReader == sizeof bleProcedure->_.timedWrite.bodyReader);
HAPRawBufferCopyBytes(
&request.bodyReader, &bleProcedure->_.timedWrite.bodyReader, sizeof request.bodyReader);
// Although undocumented, the pending Timed Write request may also include the Return Response flag and AAD.
// Request body has been restored and is still available.
} // Fallthrough.
case kHAPPDUOpcode_CharacteristicWrite: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Characteristic-Write-Request");
return kHAPError_InvalidState;
}
if (HAPSessionIsTransient(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Session is transient.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.2 HAP Characteristic Write Procedure
// Fetch permissions.
bool supportsWrite = characteristic->properties.ble.writableWithoutSecurity;
bool supportsSecureWrite = characteristic->properties.writable;
// Unpaired Identify must be allowed only if the accessory is unpaired, i.e. it has no paired controllers.
// See HomeKit Accessory Protocol Specification R14
// Section 7.4.1.9 Unpaired Identify
if (HAPUUIDAreEqual(characteristic->characteristicType, &kHAPCharacteristicType_Identify)) {
supportsWrite = !HAPAccessoryServerIsPaired(bleProcedure->server);
}
// Check permissions.
bool sessionIsSecured = HAPSessionIsSecured(bleProcedure->session);
if (!sessionIsSecured && !supportsWrite) {
if (supportsSecureWrite) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure writes are supported.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InsufficientAuthentication);
} else {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Not supported.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
}
if (sessionIsSecured && !supportsSecureWrite) {
if (supportsWrite) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only non-secure writes are supported.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
} else {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Not supported.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
}
if (HAPCharacteristicWriteRequiresAdminPermissions(characteristic) &&
!HAPSessionControllerIsAdmin(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Requires controller to have admin permissions.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InsufficientAuthentication);
}
// Check for Timed Write requirement.
bool isTimedWrite = request.opcode == kHAPPDUOpcode_CharacteristicExecuteWrite;
bool requiresTimedWrite = characteristic->properties.requiresTimedWrite;
if (!isTimedWrite && requiresTimedWrite) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only timed writes are supported.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
// Destroy request body and process HAP-Characteristic-Write-Request.
HAPAssert(server->ble.connection.connected);
HAPAssert(!server->ble.connection.write.characteristic);
HAPAssert(!server->ble.connection.write.service);
HAPAssert(!server->ble.connection.write.accessory);
server->ble.connection.write.characteristic = characteristic;
server->ble.connection.write.service = service;
server->ble.connection.write.accessory = accessory;
bool hasExpired;
err = HAPBLECharacteristicParseAndWriteValue(
bleProcedure->server,
bleProcedure->session,
characteristic,
service,
accessory,
&request.bodyReader,
isTimedWrite ? &bleProcedure->_.timedWrite.timedWriteStartTime : NULL,
&hasExpired,
&hasReturnResponse);
server->ble.connection.write.characteristic = NULL;
server->ble.connection.write.service = NULL;
server->ble.connection.write.accessory = NULL;
if (err == kHAPError_NotAuthorized) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Write failed due to insufficient authorization.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InsufficientAuthorization);
} else if (err) {
HAPAssert(
err == kHAPError_Unknown || err == kHAPError_InvalidState || err == kHAPError_InvalidData ||
err == kHAPError_OutOfResources || err == kHAPError_Busy);
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Write failed with error %d.",
"HAP-Characteristic-Write-Request",
err);
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InvalidRequest);
}
if (hasExpired) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Timed Write expired.",
"HAP-Characteristic-Write-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
if (!hasReturnResponse) {
if (characteristic->properties.ip.supportsWriteResponse) {
// The supportsWriteResponse characteristic property provides a guarantee to the application
// that the characteristic's handleRead callback is always called after a successful handleWrite.
// Whether the controller actually requested write response is hidden from the application.
// Although write response is mainly used in the HAP over IP transport it makes sense
// to follow the same behaviour when such a characteristic is accessed using HAP over Bluetooth LE.
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Characteristic supports write response: Calling read handler.");
} else {
SEND_RESPONSE_AND_RETURN(NULL);
}
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.5 HAP Characteristic Write-with-Response Procedure.
// Request body has been destroyed!
} // Fallthrough.
case kHAPPDUOpcode_CharacteristicRead: {
// 10. Accessory must support only one HAP procedure on a characteristic at any point in time.
// See HomeKit Accessory Protocol Specification R14
// Section 7.5 Testing Bluetooth LE Accessories
if (bleProcedure->multiTransactionType != kHAPBLEProcedureMultiTransactionType_None) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Different HAP procedure in progress.",
"HAP-Characteristic-Read-Request");
return kHAPError_InvalidState;
}
if (HAPSessionIsTransient(bleProcedure->session)) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Session is transient.",
"HAP-Characteristic-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
// See HomeKit Accessory Protocol Specification R14
// Section 7.3.5.3 HAP Characteristic Read Procedure
// Check permissions.
bool sessionIsSecured = HAPSessionIsSecured(bleProcedure->session);
bool supportsRead = characteristic->properties.ble.readableWithoutSecurity;
bool supportsSecureRead = characteristic->properties.readable;
if (!sessionIsSecured && !supportsRead) {
if (supportsSecureRead) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only secure reads are supported.",
"HAP-Characteristic-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_InsufficientAuthentication);
} else {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Not supported.",
"HAP-Characteristic-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);
}
}
if (sessionIsSecured && !supportsSecureRead) {
if (supportsRead) {
HAPLogCharacteristic(
&logObject,
characteristic,
service,
accessory,
"Rejected %s: Only non-secure reads are supported.",
"HAP-Characteristic-Read-Request");
SEND_ERROR_AND_RETURN(kHAPBLEPDUStatus_UnsupportedPDU);