-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathHAPAccessoryServer.c
1700 lines (1523 loc) · 64.2 KB
/
HAPAccessoryServer.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 = "AccessoryServer" };
/**
* Completes accessory server shutdown after HAPAccessoryServerStop.
*
* @param server_ Accessory server.
*/
static void CompleteShutdown(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
// Reset Pair Setup procedure state.
HAPAssert(!server->pairSetup.sessionThatIsCurrentlyPairing);
HAPAccessorySetupInfoHandleAccessoryServerStop(server_);
// Reset state.
server->primaryAccessory = NULL;
server->ip.bridgedAccessories = NULL;
// Check that everything is cleaned up.
HAPAssert(!server->ip.discoverableService);
// Shutdown complete.
HAPLogInfo(&logObject, "Accessory server shutdown completed.");
server->state = kHAPAccessoryServerState_Idle;
HAPAssert(server->callbacks.handleUpdatedState);
server->callbacks.handleUpdatedState(server_, server->context);
}
static void CallbackTimerExpired(HAPPlatformTimerRef timer, void* _Nullable context) {
HAPPrecondition(context);
HAPAccessoryServerRef* server_ = context;
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(timer == server->callbackTimer);
server->callbackTimer = 0;
HAPAccessorySetupInfoHandleAccessoryServerStateUpdate(server_);
// Complete shutdown if accessory server has been stopped using a server engine.
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->stop &&
HAPAccessoryServerGetState(server_) == kHAPAccessoryServerState_Idle) {
CompleteShutdown(server_);
return;
}
}
// Invoke handleUpdatedState callback.
HAPAssert(server->callbacks.handleUpdatedState);
server->callbacks.handleUpdatedState(server_, server->context);
}
void HAPAccessoryServerDelegateScheduleHandleUpdatedState(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPError err;
if (server->callbackTimer) {
return;
}
err = HAPPlatformTimerRegister(&server->callbackTimer, 0, CallbackTimerExpired, server_);
if (err) {
HAPAssert(err == kHAPError_OutOfResources);
HAPLogError(&logObject, "Not enough resources to allocate accessory server callback timer.");
HAPFatalError();
}
}
void HAPAccessoryServerCreate(
HAPAccessoryServerRef* server_,
const HAPAccessoryServerOptions* options,
const HAPPlatform* platform,
const HAPAccessoryServerCallbacks* callbacks,
void* _Nullable context) {
HAPPrecondition(HAPPlatformGetCompatibilityVersion() == HAP_PLATFORM_COMPATIBILITY_VERSION);
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(options);
HAPPrecondition(platform);
HAPPrecondition(callbacks);
if (HAP_LOG_LEVEL >= 1) {
char stringBuilderBytes[1024];
HAPStringBuilderRef stringBuilder;
HAPStringBuilderCreate(&stringBuilder, stringBuilderBytes, sizeof stringBuilderBytes);
HAPStringBuilderAppend(&stringBuilder, "Version information:");
HAPStringBuilderAppend(&stringBuilder, "\nlibhap: %s", HAPGetIdentification());
HAPStringBuilderAppend(
&stringBuilder,
"\n - Version: %s (%s) - compatibility version %lu",
HAPGetVersion(),
HAPGetBuild(),
(unsigned long) HAPGetCompatibilityVersion());
HAPStringBuilderAppend(&stringBuilder, "\nUsing platform: %s", HAPPlatformGetIdentification());
HAPStringBuilderAppend(
&stringBuilder,
"\n - Version: %s (%s) - compatibility version %lu",
HAPPlatformGetVersion(),
HAPPlatformGetBuild(),
(unsigned long) HAPPlatformGetCompatibilityVersion());
HAPStringBuilderAppend(&stringBuilder, "\n - Available features:");
if (platform->keyValueStore) {
HAPStringBuilderAppend(&stringBuilder, "\n - Key-Value store");
}
if (platform->accessorySetup) {
HAPStringBuilderAppend(&stringBuilder, "\n - Accessory setup manager");
}
if (platform->setupDisplay) {
HAPStringBuilderAppend(&stringBuilder, "\n - Accessory setup display");
}
if (platform->setupNFC) {
HAPStringBuilderAppend(&stringBuilder, "\n - Accessory setup programmable NFC tag");
}
if (platform->ip.serviceDiscovery) {
HAPStringBuilderAppend(&stringBuilder, "\n - Service discovery");
}
if (platform->ble.blePeripheralManager) {
HAPStringBuilderAppend(&stringBuilder, "\n - BLE peripheral manager");
}
if (platform->authentication.mfiHWAuth) {
HAPStringBuilderAppend(&stringBuilder, "\n - Apple Authentication Coprocessor provider");
}
if (platform->authentication.mfiTokenAuth) {
HAPStringBuilderAppend(&stringBuilder, "\n - Software Token provider");
}
if (HAPStringBuilderDidOverflow(&stringBuilder)) {
HAPLogError(&logObject, "Version information truncated.");
}
HAPLog(&logObject, "%s", HAPStringBuilderGetString(&stringBuilder));
}
HAPLogDebug(&logObject, "Storage configuration: server = %lu", (unsigned long) sizeof *server);
HAPRawBufferZero(server, sizeof *server);
// Copy generic options.
HAPPrecondition(options->maxPairings >= kHAPPairingStorage_MinElements);
server->maxPairings = options->maxPairings;
// Copy platform.
HAPAssert(sizeof *platform == sizeof server->platform);
HAPRawBufferCopyBytes(&server->platform, platform, sizeof server->platform);
HAPPrecondition(server->platform.keyValueStore);
HAPPrecondition(server->platform.accessorySetup);
HAPMFiHWAuthCreate(&server->mfi, server->platform.authentication.mfiHWAuth);
// Deprecation check for accessory setup.
HAP_DIAGNOSTIC_PUSH
HAP_DIAGNOSTIC_IGNORED_CLANG("-Wdeprecated-declarations")
HAP_DIAGNOSTIC_IGNORED_GCC("-Wdeprecated-declarations")
HAP_DIAGNOSTIC_IGNORED_ARMCC(2570)
HAP_DIAGNOSTIC_IGNORED_ICCARM(Pe1444)
HAPPlatformAccessorySetupCapabilities accessorySetupCapabilities =
HAPPlatformAccessorySetupGetCapabilities(server->platform.accessorySetup);
HAP_DIAGNOSTIC_RESTORE_ICCARM(Pe1444)
HAP_DIAGNOSTIC_POP
if (accessorySetupCapabilities.supportsDisplay) {
HAPLogError(
&logObject,
"HAPPlatformAccessorySetupGetCapabilities is deprecated. "
"Return false and use HAPPlatformAccessorySetupDisplay instead.");
}
if (accessorySetupCapabilities.supportsProgrammableNFC) {
HAPLogError(
&logObject,
"HAPPlatformAccessorySetupGetCapabilities is deprecated. "
"Return false and use HAPPlatformAccessorySetupNFC instead.");
}
if (server->platform.setupDisplay || server->platform.setupNFC) {
HAPPrecondition(!accessorySetupCapabilities.supportsDisplay);
HAPPrecondition(!accessorySetupCapabilities.supportsProgrammableNFC);
}
// Copy callbacks.
HAPPrecondition(callbacks->handleUpdatedState);
HAPAssert(sizeof *callbacks == sizeof server->callbacks);
HAPRawBufferCopyBytes(&server->callbacks, callbacks, sizeof server->callbacks);
// Deprecation check for transports.
HAP_DIAGNOSTIC_PUSH
HAP_DIAGNOSTIC_IGNORED_CLANG("-Wdeprecated-declarations")
HAP_DIAGNOSTIC_IGNORED_GCC("-Wdeprecated-declarations")
HAP_DIAGNOSTIC_IGNORED_ARMCC(2570)
HAP_DIAGNOSTIC_IGNORED_ICCARM(Pe1444)
if (options->ip.available) {
HAPLogFault(
&logObject,
"HAPAccessoryServerOptions must no longer set ip.available. "
"Set ip.transport to &kHAPAccessoryServerTransport_IP instead.");
HAPFatalError();
}
if (options->ble.available) {
HAPLogFault(
&logObject,
"HAPAccessoryServerOptions must no longer set ble.available. "
"Set ble.transport to &kHAPAccessoryServerTransport_BLE instead.");
HAPFatalError();
}
HAP_DIAGNOSTIC_RESTORE_ICCARM(Pe1444)
HAP_DIAGNOSTIC_POP
// One transport must be supported.
HAPPrecondition(options->ip.transport || options->ble.transport);
// Copy IP parameters.
server->transports.ip = options->ip.transport;
if (server->transports.ip) {
HAPNonnull(server->transports.ip)->create(server_, options);
} else {
HAPRawBufferZero(&server->platform.ip, sizeof server->platform.ip);
}
// Copy Bluetooth LE parameters.
server->transports.ble = options->ble.transport;
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->create(server_, options);
} else {
HAPRawBufferZero(&server->platform.ble, sizeof server->platform.ble);
}
// Copy client context.
server->context = context;
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->init) {
serverEngine->init(server_);
}
}
}
void HAPAccessoryServerRelease(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPError err;
HAPAccessoryServerStop(server_);
if (server->callbackTimer) {
HAPPlatformTimerDeregister(server->callbackTimer);
server->callbackTimer = 0;
}
if (server->transports.ble) {
HAPAssert(server->platform.ble.blePeripheralManager);
HAPNonnull(server->transports.ble)->peripheralManager.release(server_);
}
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->deinit) {
err = serverEngine->deinit(server_);
if (err) {
HAPFatalError();
}
}
}
if (server->transports.ble) {
if (server->ble.adv.fast_timer) {
HAPPlatformTimerDeregister(server->ble.adv.fast_timer);
server->ble.adv.fast_timer = 0;
}
if (server->ble.adv.timer) {
HAPPlatformTimerDeregister(server->ble.adv.timer);
server->ble.adv.timer = 0;
}
}
HAPMFiHWAuthRelease(&server->mfi);
if (server->transports.ip) {
HAPNonnull(server->transports.ip)->serverEngine.uninstall();
}
HAPRawBufferZero(server_, sizeof *server_);
}
HAP_RESULT_USE_CHECK
HAPAccessoryServerState HAPAccessoryServerGetState(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->get_state) {
return serverEngine->get_state(server_);
}
}
return server->state;
}
HAP_RESULT_USE_CHECK
void* _Nullable HAPAccessoryServerGetClientContext(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
return server->context;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Parses a version string where each element is capped at 2^32-1.
*
* @param version Version string.
* @param[out] major Major version number.
* @param[out] minor Minor version number.
* @param[out] revision Revision version number.
*
* @return kHAPError_None If successful.
* @return kHAPError_InvalidData If the version string is malformed.
*/
HAP_RESULT_USE_CHECK
static HAPError ParseVersionString(const char* version, uint32_t* major, uint32_t* minor, uint32_t* revision) {
HAPPrecondition(version);
HAPPrecondition(major);
HAPPrecondition(minor);
HAPPrecondition(revision);
*major = 0;
*minor = 0;
*revision = 0;
// Read numbers.
uint32_t* numbers[3] = { major, minor, revision };
size_t i = 0;
bool first = true;
for (const char* c = version; *c; c++) {
if (!first && *c == '.') {
// Advance to next number.
if (i >= 2) {
HAPLog(&logObject, "Invalid version string: %s.", version);
return kHAPError_InvalidData;
}
i++;
first = true;
continue;
}
first = false;
// Add digit.
if (*c < '0' || *c > '9') {
HAPLog(&logObject, "Invalid version string: %s.", version);
return kHAPError_InvalidData;
}
if (*numbers[i] > UINT32_MAX / 10) {
HAPLog(&logObject, "Invalid version string: %s.", version);
return kHAPError_InvalidData;
}
(*numbers[i]) *= 10;
if (*numbers[i] > UINT32_MAX - (uint32_t)(*c - '0')) {
HAPLog(&logObject, "Invalid version string: %s.", version);
return kHAPError_InvalidData;
}
(*numbers[i]) += (uint32_t)(*c - '0');
}
if (first) {
HAPLog(&logObject, "Invalid version string: %s.", version);
return kHAPError_InvalidData;
}
return kHAPError_None;
}
void HAPAccessoryServerLoadLTSK(HAPPlatformKeyValueStoreRef keyValueStore, HAPAccessoryServerLongTermSecretKey* ltsk) {
HAPPrecondition(keyValueStore);
HAPPrecondition(ltsk);
HAPError err;
// An attacker who gains application processor code execution privileges can:
// - Control any accessory functionality.
// - List, add, remove, and modify HAP pairings.
// - Provide a service to sign arbitrary messages with the accessory LTSK.
// These assumptions remain valid even when a separate Trusted Execution Environment (TEE) is present,
// because as of HomeKit Accessory Protocol R14, HAP only defines transport security.
// Augmenting the HAP protocol with true end-to-end security for HAP pairings would require a protocol change.
//
// The raw accessory LTSK could theoretically be stored in a TEE,
// but given the user impact when an attacker takes control of the application processor
// there does not seem to be a realistic threat that can be mitigated if this would be done.
// The attacker could still set up a service to sign arbitrary messages with the accessory LTSK
// when the accessory LTSK is stored in a TEE, and could use this service to impersonate the accessory.
//
// The only security that can currently be provided is to store all secrets in secure memory
// so that they cannot easily be extracted at rest (without having code execution privileges or RAM access).
// It is left up to the platform implementation to store the HAPPlatformKeyValueStore content securely.
//
// Note: If this mechanism is ever replaced to redirect to a TEE for the LTSK,
// an upgrade path must be specified for the following scenarios:
// - LTSK was stored in HAPPlatformKeyValueStore, and needs to be migrated into a TEE.
// - HAP protocol gets extended with real TEE support, and LTSK needs to be migrated into a new TEE.
bool found;
size_t numBytes;
err = HAPPlatformKeyValueStoreGet(
keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_LTSK,
ltsk->bytes,
sizeof ltsk->bytes,
&numBytes,
&found);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPLogError(&logObject, "Reading LTSK failed.");
HAPFatalError();
}
if (!found) {
// Reset pairings.
err = HAPPlatformKeyValueStorePurgeDomain(keyValueStore, kHAPKeyValueStoreDomain_Pairings);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPLogError(&logObject, "Purge of pairing domain failed.");
HAPFatalError();
}
// Generate new LTSK.
HAPPlatformRandomNumberFill(ltsk->bytes, sizeof ltsk->bytes);
HAPLogSensitiveBufferInfo(&logObject, ltsk->bytes, sizeof ltsk->bytes, "Generated new LTSK.");
// Store new LTSK.
err = HAPPlatformKeyValueStoreSet(
keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_LTSK,
ltsk->bytes,
sizeof ltsk->bytes);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPLogError(&logObject, "Storing LTSK failed.");
HAPFatalError();
}
} else if (numBytes != sizeof ltsk->bytes) {
HAPLogError(&logObject, "Corrupted LTSK in Key-Value Store.");
HAPFatalError();
}
}
/**
* Prepares starting the accessory server.
*
* @param server_ Accessory server.
* @param primaryAccessory Primary accessory to host.
* @param bridgedAccessories NULL-terminated array of bridged accessories for a bridge accessory. NULL otherwise.
*/
static void HAPAccessoryServerPrepareStart(
HAPAccessoryServerRef* server_,
const HAPAccessory* primaryAccessory,
const HAPAccessory* _Nullable const* _Nullable bridgedAccessories) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->state == kHAPAccessoryServerState_Idle);
HAPPrecondition(!server->primaryAccessory);
HAPPrecondition(!server->ip.bridgedAccessories);
HAPPrecondition(primaryAccessory);
HAPError err;
HAPLogInfo(&logObject, "Accessory server starting.");
server->state = kHAPAccessoryServerState_Running;
HAPAccessoryServerDelegateScheduleHandleUpdatedState(server_);
// Reset state.
if (server->transports.ip) {
HAPNonnull(server->transports.ip)->prepareStart(server_);
}
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->prepareStart(server_);
}
// Firmware version check.
{
// Read firmware version.
HAPAssert(primaryAccessory->firmwareVersion);
uint32_t major;
uint32_t minor;
uint32_t revision;
err = ParseVersionString(primaryAccessory->firmwareVersion, &major, &minor, &revision);
if (err) {
HAPAssert(err == kHAPError_InvalidData);
HAPFatalError();
}
HAPLogInfo(
&logObject,
"Firmware version: %lu.%lu.%lu",
(unsigned long) major,
(unsigned long) minor,
(unsigned long) revision);
// Check for configuration change.
HAPPrecondition(server->platform.keyValueStore);
uint8_t bytes[3 * 4];
bool found;
size_t numBytes;
err = HAPPlatformKeyValueStoreGet(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_FirmwareVersion,
bytes,
sizeof bytes,
&numBytes,
&found);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
bool saveVersion = false;
if (found) {
if (numBytes != sizeof bytes) {
HAPLogError(
&logObject,
"Key-value store corrupted - unexpected length for firmware revision: %lu.",
(unsigned long) numBytes);
HAPFatalError();
}
uint32_t previousMajor = HAPReadLittleUInt32(&bytes[0]);
uint32_t previousMinor = HAPReadLittleUInt32(&bytes[4]);
uint32_t previousRevision = HAPReadLittleUInt32(&bytes[8]);
if (major != previousMajor || minor != previousMinor || revision != previousRevision) {
if (major < previousMajor || (major == previousMajor && minor < previousMinor) ||
(major == previousMajor && minor == previousMinor && revision < previousRevision)) {
HAPLogError(
&logObject,
"[%lu.%lu.%lu > %lu.%lu.%lu] Firmware must not be downgraded! Not starting "
"HAPAccessoryServer.",
(unsigned long) previousMajor,
(unsigned long) previousMinor,
(unsigned long) previousRevision,
(unsigned long) major,
(unsigned long) minor,
(unsigned long) revision);
server->state = kHAPAccessoryServerState_Idle;
return;
}
HAPLogInfo(
&logObject,
"[%lu.%lu.%lu > %lu.%lu.%lu] Performing post firmware update tasks.",
(unsigned long) previousMajor,
(unsigned long) previousMinor,
(unsigned long) previousRevision,
(unsigned long) major,
(unsigned long) minor,
(unsigned long) revision);
err = HAPHandleFirmwareUpdate(server_);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
saveVersion = true;
}
} else {
HAPLogInfo(
&logObject,
"[%lu.%lu.%lu] Storing initial firmware version.",
(unsigned long) major,
(unsigned long) minor,
(unsigned long) revision);
saveVersion = true;
}
if (saveVersion) {
HAPWriteLittleUInt32(&bytes[0], major);
HAPWriteLittleUInt32(&bytes[4], minor);
HAPWriteLittleUInt32(&bytes[8], revision);
err = HAPPlatformKeyValueStoreSet(
server->platform.keyValueStore,
kHAPKeyValueStoreDomain_Configuration,
kHAPKeyValueStoreKey_Configuration_FirmwareVersion,
bytes,
sizeof bytes);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
}
}
// Register accessory.
HAPLogDebug(&logObject, "Registering accessories.");
server->primaryAccessory = primaryAccessory;
server->ip.bridgedAccessories = bridgedAccessories;
// Load LTSK.
HAPLogDebug(&logObject, "Loading accessory identity.");
HAPAccessoryServerLoadLTSK(server->platform.keyValueStore, &server->identity.ed_LTSK);
HAP_ed25519_public_key(server->identity.ed_LTPK, server->identity.ed_LTSK.bytes);
// Cleanup pairings.
err = HAPAccessoryServerCleanupPairings(server_);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPLogError(&logObject, "Cleanup pairings failed.");
HAPFatalError();
}
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->start(server_);
}
// Update setup payload.
HAPAccessorySetupInfoHandleAccessoryServerStart(server_);
// Update advertising state.
HAPAccessoryServerUpdateAdvertisingData(server_);
}
void HAPAccessoryServerStart(HAPAccessoryServerRef* server_, const HAPAccessory* accessory) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(accessory);
HAPLogDebug(
&logObject,
"Checking accessory definition. "
"If this crashes, verify that service and characteristic lists are properly NULL-terminated.");
HAPPrecondition(HAPRegularAccessoryIsValid(server_, accessory));
HAPLogDebug(&logObject, "Accessory definition ok.");
// Check Bluetooth LE requirements.
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->validateAccessory(accessory);
}
// Start accessory server.
HAPAccessoryServerPrepareStart(server_, accessory, /* bridgedAccessories: */ NULL);
if (server->state != kHAPAccessoryServerState_Running) {
HAPAssert(server->state == kHAPAccessoryServerState_Idle);
return;
}
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->start) {
serverEngine->start(server_);
}
}
}
void HAPAccessoryServerStartBridge(
HAPAccessoryServerRef* server_,
const HAPAccessory* bridgeAccessory,
const HAPAccessory* _Nullable const* _Nullable bridgedAccessories,
bool configurationChanged) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(bridgeAccessory);
HAPError err;
HAPLogDebug(
&logObject,
"Checking accessory definition. "
"If this crashes, verify that accessory, service and characteristic lists are properly NULL-terminated.");
HAPPrecondition(HAPRegularAccessoryIsValid(server_, bridgeAccessory));
if (bridgedAccessories) {
size_t i;
for (i = 0; bridgedAccessories[i]; i++) {
HAPPrecondition(HAPBridgedAccessoryIsValid(bridgedAccessories[i]));
}
HAPPrecondition(i <= kHAPAccessoryServerMaxBridgedAccessories);
}
HAPLogDebug(&logObject, "Accessory definition ok.");
HAPAccessoryServerPrepareStart(server_, bridgeAccessory, bridgedAccessories);
if (server->state != kHAPAccessoryServerState_Running) {
HAPAssert(server->state == kHAPAccessoryServerState_Idle);
return;
}
// Increment configuration number if necessary.
if (configurationChanged) {
HAPLogInfo(&logObject, "Configuration changed. Incrementing CN.");
err = HAPAccessoryServerIncrementCN(server->platform.keyValueStore);
if (err) {
HAPAssert(err == kHAPError_Unknown);
HAPFatalError();
}
}
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->start) {
serverEngine->start(server_);
}
}
}
void HAPAccessoryServerStop(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPError err;
if (server->state == kHAPAccessoryServerState_Idle) {
return;
}
if (server->state != kHAPAccessoryServerState_Stopping) {
HAPAssert(server->state == kHAPAccessoryServerState_Running);
HAPLogInfo(&logObject, "Accessory server shutting down.");
server->state = kHAPAccessoryServerState_Stopping;
if (!server->transports.ip || !HAPNonnull(server->transports.ip)->serverEngine.get()) {
server->callbacks.handleUpdatedState(server_, server->context);
}
}
// Stop advertising.
if (server->transports.ble) {
HAPAccessoryServerUpdateAdvertisingData(server_);
}
if (server->transports.ip) {
HAPNonnull(server->transports.ip)->prepareStop(server_);
}
if (server->transports.ble) {
bool didStop;
HAPNonnull(server->transports.ble)->tryStop(server_, &didStop);
if (!didStop) {
return;
}
}
// Inform server engine.
// Server engine will complete the shutdown process.
// - _serverEngine->stop
// - ...
// - HAPAccessoryServerDelegateScheduleHandleUpdatedState => kHAPAccessoryServerState_Idle.
// - CompleteShutdown.
if (server->transports.ip) {
const HAPAccessoryServerServerEngine* _Nullable serverEngine =
HAPNonnull(server->transports.ip)->serverEngine.get();
if (serverEngine && serverEngine->stop) {
err = serverEngine->stop(server_);
if (err) {
HAPFatalError();
}
return;
}
}
// Complete shutdown.
CompleteShutdown(server_);
}
void HAPAccessoryServerUpdateAdvertisingData(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
if (server->transports.ble) {
HAPNonnull(server->transports.ble)->updateAdvertisingData(server_);
}
}
typedef struct {
bool exists; /**< Pairing found. */
} PairingExistsEnumerateContext;
HAP_RESULT_USE_CHECK
static HAPError PairingExistsEnumerateCallback(
void* _Nullable context,
HAPPlatformKeyValueStoreRef keyValueStore,
HAPPlatformKeyValueStoreDomain domain,
HAPPlatformKeyValueStoreKey key HAP_UNUSED,
bool* shouldContinue) {
HAPPrecondition(context);
PairingExistsEnumerateContext* arguments = context;
HAPPrecondition(keyValueStore);
HAPPrecondition(domain == kHAPKeyValueStoreDomain_Pairings);
HAPPrecondition(shouldContinue);
arguments->exists = true;
*shouldContinue = false;
return kHAPError_None;
}
HAP_RESULT_USE_CHECK
bool HAPAccessoryServerIsPaired(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
const HAPAccessoryServer* server = (const HAPAccessoryServer*) server_;
HAPError err;
// Enumerate pairings.
PairingExistsEnumerateContext context = { .exists = false };
err = HAPPlatformKeyValueStoreEnumerate(
server->platform.keyValueStore, kHAPKeyValueStoreDomain_Pairings, PairingExistsEnumerateCallback, &context);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return false;
}
return context.exists;
}
HAP_DEPRECATED_MSG(
"For displays: See HAPPlatformAccessorySetupDisplay. For NFC: Use HAPAccessoryServerEnterNFCPairingMode "
"instead.")
void HAPAccessoryServerEnterPairingMode(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.accessorySetup);
HAPPrecondition(!server->platform.setupDisplay);
HAPPrecondition(!server->platform.setupNFC);
HAPAccessorySetupInfoEnterLegacyPairingMode(server_);
}
void HAPAccessoryServerRefreshSetupPayload(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.setupDisplay);
HAPAccessorySetupInfoRefreshSetupPayload(server_);
}
void HAPAccessoryServerEnterNFCPairingMode(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.setupNFC);
HAPAccessorySetupInfoEnterNFCPairingMode(server_);
}
void HAPAccessoryServerExitNFCPairingMode(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPPrecondition(server->platform.setupNFC);
HAPAccessorySetupInfoExitNFCPairingMode(server_);
}
HAP_RESULT_USE_CHECK
bool HAPAccessoryServerSupportsMFiHWAuth(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
return HAPMFiHWAuthIsAvailable(&server->mfi);
}
HAP_RESULT_USE_CHECK
uint8_t HAPAccessoryServerGetPairingFeatureFlags(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPError err;
// See HomeKit Accessory Protocol Specification R14
// Table 5-15 Pairing Feature Flags
// Check if Apple Authentication Coprocessor is supported.
bool supportsAppleAuthenticationCoprocessor = HAPAccessoryServerSupportsMFiHWAuth(server_);
// Check if Software Authentication is supported.
bool supportsSoftwareAuthentication = false;
if (server->platform.authentication.mfiTokenAuth) {
err = HAPPlatformMFiTokenAuthLoad(
HAPNonnull(server->platform.authentication.mfiTokenAuth),
&supportsSoftwareAuthentication,
NULL,
NULL,
0,
NULL);
if (err) {
HAPAssert(err == kHAPError_Unknown || err == kHAPError_OutOfResources);
HAPLogError(&logObject, "HAPPlatformMFiTokenAuthLoad failed: %u.", err);
HAPFatalError();
}
}
// Serialize response.
uint8_t pairingFeatureFlags = 0;
if (supportsAppleAuthenticationCoprocessor) {
pairingFeatureFlags |= kHAPCharacteristicValue_PairingFeatures_SupportsAppleAuthenticationCoprocessor;
}
if (supportsSoftwareAuthentication) {
pairingFeatureFlags |= kHAPCharacteristicValue_PairingFeatures_SupportsSoftwareAuthentication;
}
return pairingFeatureFlags;
}
/**
* Status flags.
*
* @see HomeKit Accessory Protocol Specification R14
* Table 6-8 Bonjour TXT Status Flags
*
* @see HomeKit Accessory Protocol Specification R14
* Section 7.4.2.1.2 Manufacturer Data
*/
HAP_ENUM_BEGIN(uint8_t, HAPAccessoryServerStatusFlags) {
/** Accessory has not been paired with any controllers. */
kHAPAccessoryServerStatusFlags_NotPaired = 1 << 0,
/**
* A problem has been detected on the accessory.
*
* - Used by accessories supporting HAP over IP (Ethernet / Wi-Fi) only.
*/
kHAPAccessoryServerStatusFlags_ProblemDetected = 1 << 2
} HAP_ENUM_END(uint8_t, HAPAccessoryServerStatusFlags);
HAP_RESULT_USE_CHECK
uint8_t HAPAccessoryServerGetStatusFlags(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
uint8_t statusFlags = 0;
if (!HAPAccessoryServerIsPaired(server_)) {
statusFlags |= kHAPAccessoryServerStatusFlags_NotPaired;
}
return statusFlags;
}
typedef struct {
bool hasPairings : 1;
bool adminFound : 1;
} FindAdminPairingEnumerateContext;
HAP_RESULT_USE_CHECK
static HAPError FindAdminPairingEnumerateCallback(
void* _Nullable context,
HAPPlatformKeyValueStoreRef keyValueStore,
HAPPlatformKeyValueStoreDomain domain,
HAPPlatformKeyValueStoreKey key,
bool* shouldContinue) {
FindAdminPairingEnumerateContext* arguments = context;
HAPPrecondition(arguments);
HAPPrecondition(!arguments->adminFound);
HAPPrecondition(domain == kHAPKeyValueStoreDomain_Pairings);
HAPPrecondition(shouldContinue);
HAPError err;
// Load pairing.
bool found;
size_t numBytes;
uint8_t pairingBytes[sizeof(HAPPairingID) + sizeof(uint8_t) + sizeof(HAPPairingPublicKey) + sizeof(uint8_t)];
err = HAPPlatformKeyValueStoreGet(keyValueStore, domain, key, pairingBytes, sizeof pairingBytes, &numBytes, &found);
if (err) {
HAPAssert(err == kHAPError_Unknown);
return err;
}
HAPAssert(found);
if (numBytes != sizeof pairingBytes) {
HAPLog(&logObject, "Invalid pairing 0x%02X size %lu.", key, (unsigned long) numBytes);
return kHAPError_Unknown;
}
HAPPairing pairing;
HAPRawBufferZero(&pairing, sizeof pairing);
HAPAssert(sizeof pairing.identifier.bytes == 36);
HAPRawBufferCopyBytes(pairing.identifier.bytes, &pairingBytes[0], 36);
pairing.numIdentifierBytes = pairingBytes[36];
HAPAssert(sizeof pairing.publicKey.value == 32);
HAPRawBufferCopyBytes(pairing.publicKey.value, &pairingBytes[37], 32);
pairing.permissions = pairingBytes[69];
arguments->hasPairings = true;
// Check if admin found.
if (pairing.permissions & 0x01) {
arguments->adminFound = true;
*shouldContinue = false;
}
return kHAPError_None;
}
HAP_RESULT_USE_CHECK
HAPError HAPAccessoryServerCleanupPairings(HAPAccessoryServerRef* server_) {
HAPPrecondition(server_);
HAPAccessoryServer* server = (HAPAccessoryServer*) server_;
HAPError err;
HAPLogDebug(&logObject, "Checking if admin pairing exists.");
// Look for admin pairing.
FindAdminPairingEnumerateContext context = { .adminFound = false };
err = HAPPlatformKeyValueStoreEnumerate(
server->platform.keyValueStore,