forked from Yurik72/ESPHap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
3725 lines (2972 loc) · 127 KB
/
server.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
#include "port_x.h"
#if !defined(ARDUINO8266_SERVER) && !defined(ARDUINO8266_SERVER_CPP)
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include <lwip/sockets.h>
#include <unistd.h>
#if defined(ESP_IDF)
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
#elif defined(ESP_OPEN_RTOS)
#include <FreeRTOS.h>
#include <task.h>
#include <queue.h>
#elif defined(ARDUINO)
#include <Arduino.h>
#include "os_settings.h"
#else
#error "Unknown target platform"
#endif
#include "http_parser.h"
#include "esphap_cJSON.h"
#include "cJSON_memory.h"
#include <wolfssl/wolfcrypt/hash.h>
#include <wolfssl/wolfcrypt/coding.h>
#include "esphap_base64.h"
#include "crypto.h"
#include "pairing.h"
#include "storage.h"
#include "query_params.h"
#include "json.h"
#include "esphap_debug.h"
#include "port.h"
#include "homekit.h"
#include "characteristics.h"
#include "tlv.h"
#define PORT 5556
#ifndef HOMEKIT_MAX_CLIENTS
#define HOMEKIT_MAX_CLIENTS 16
#endif
#define CLIENT_CONTEXT_CACHE_SIZE 4
bool stop_flag = 0;
bool is_initialized=false;
struct _client_context_t;
typedef struct _client_context_t client_context_t;
#define HOMEKIT_NOTIFY_EVENT(server, event) \
if ((server)->config->on_event) \
(server)->config->on_event(event);
typedef enum {
HOMEKIT_ENDPOINT_UNKNOWN = 0,
HOMEKIT_ENDPOINT_PAIR_SETUP,
HOMEKIT_ENDPOINT_PAIR_VERIFY,
HOMEKIT_ENDPOINT_IDENTIFY,
HOMEKIT_ENDPOINT_GET_ACCESSORIES,
HOMEKIT_ENDPOINT_GET_CHARACTERISTICS,
HOMEKIT_ENDPOINT_UPDATE_CHARACTERISTICS,
HOMEKIT_ENDPOINT_PAIRINGS,
HOMEKIT_ENDPOINT_RESET,
HOMEKIT_ENDPOINT_RESOURCE,
} homekit_endpoint_t;
typedef struct {
Srp *srp;
byte *public_key;
size_t public_key_size;
client_context_t *client;
} pairing_context_t;
typedef struct {
byte *secret;
size_t secret_size;
byte *session_key;
size_t session_key_size;
byte *device_public_key;
size_t device_public_key_size;
byte *accessory_public_key;
size_t accessory_public_key_size;
} pair_verify_context_t;
typedef struct {
char *accessory_id;
ed25519_key *accessory_key;
homekit_server_config_t *config;
bool paired;
pairing_context_t *pairing_context;
byte data[1024 + 18];
byte output_buffer[1024];
int listen_fd;
fd_set fds;
int max_fd;
int nfds;
http_parser parser;
json_stream json;
bool request_completed;
client_context_t *clients;
} homekit_server_t;
struct _client_context_t {
homekit_server_t *server;
int socket;
homekit_endpoint_t endpoint;
query_param_t *endpoint_params;
//byte *data;
// size_t data_size;
// size_t data_available;
char *body;
size_t body_length;
// http_parser *parser;
int pairing_id;
byte permissions;
bool disconnect;
homekit_characteristic_t *current_characteristic;
homekit_value_t *current_value;
bool encrypted;
byte read_key[32];
byte write_key[32];
int count_reads;
int count_writes;
QueueHandle_t event_queue;
pair_verify_context_t *verify_context;
bool is_static;
bool is_used;
struct _client_context_t *next;
};
static client_context_t cache_client_contexts[CLIENT_CONTEXT_CACHE_SIZE];
//#if !defined(ARDUINO) && !defined(ESP8266)
typedef struct {
homekit_characteristic_t *characteristic;
homekit_value_t value;
} characteristic_event_t;
//#endif
void client_context_free(client_context_t *c);
void pairing_context_free(pairing_context_t *context);
void client_send_chunk(byte *data, size_t size, void *arg);
void setstopflag() {
stop_flag = 1;
}
homekit_server_t *server_new() {
homekit_server_t *server = malloc(sizeof(homekit_server_t));
FD_ZERO(&server->fds);
http_parser_init(&server->parser, HTTP_REQUEST);
json_init(&server->json, server->output_buffer, sizeof(server->output_buffer),
client_send_chunk, NULL);
server->max_fd = 0;
server->nfds = 0;
server->accessory_id = NULL;
server->accessory_key = NULL;
server->config = NULL;
server->paired = false;
server->pairing_context = NULL;
server->clients = NULL;
return server;
}
void server_free(homekit_server_t *server) {
if (server->accessory_id)
free(server->accessory_id);
if (server->accessory_key)
crypto_ed25519_free(server->accessory_key);
if (server->pairing_context)
pairing_context_free(server->pairing_context);
if (server->clients) {
client_context_t *client = server->clients;
while (client) {
client_context_t *next = client->next;
client_context_free(client);
client = next;
}
}
free(server);
}
#ifdef HOMEKIT_DEBUG
#define TLV_DEBUG(values) tlv_debug(values)
#else
#define TLV_DEBUG(values)
#endif
#define CLIENT_DEBUG(client, message, ...) DEBUG("[Client %d] " message, client->socket, ##__VA_ARGS__)
#define CLIENT_INFO(client, message, ...) INFO("[Client %d] " message, client->socket, ##__VA_ARGS__)
#define CLIENT_ERROR(client, message, ...) ERROR("[Client %d] " message, client->socket, ##__VA_ARGS__)
void tlv_debug(const tlv_values_t *values) {
DEBUG("Got following TLV values:");
for (tlv_t *t=values->head; t; t=t->next) {
char *escaped_payload = binary_to_string(t->value, t->size);
DEBUG("Type %d value (%d bytes): %s", t->type, t->size, escaped_payload);
free(escaped_payload);
}
}
typedef enum {
TLVType_Method = 0, // (integer) Method to use for pairing. See PairMethod
TLVType_Identifier = 1, // (UTF-8) Identifier for authentication
TLVType_Salt = 2, // (bytes) 16+ bytes of random salt
TLVType_PublicKey = 3, // (bytes) Curve25519, SRP public key or signed Ed25519 key
TLVType_Proof = 4, // (bytes) Ed25519 or SRP proof
TLVType_EncryptedData = 5, // (bytes) Encrypted data with auth tag at end
TLVType_State = 6, // (integer) State of the pairing process. 1=M1, 2=M2, etc.
TLVType_Error = 7, // (integer) Error code. Must only be present if error code is
// not 0. See TLVError
TLVType_RetryDelay = 8, // (integer) Seconds to delay until retrying a setup code
TLVType_Certificate = 9, // (bytes) X.509 Certificate
TLVType_Signature = 10, // (bytes) Ed25519
TLVType_Permissions = 11, // (integer) Bit value describing permissions of the controller
// being added.
// None (0x00): Regular user
// Bit 1 (0x01): Admin that is able to add and remove
// pairings against the accessory
TLVType_FragmentData = 13, // (bytes) Non-last fragment of data. If length is 0,
// it's an ACK.
TLVType_FragmentLast = 14, // (bytes) Last fragment of data
TLVType_Separator = 0xff,
} TLVType;
typedef enum {
TLVMethod_PairSetup = 1,
TLVMethod_PairVerify = 2,
TLVMethod_AddPairing = 3,
TLVMethod_RemovePairing = 4,
TLVMethod_ListPairings = 5,
} TLVMethod;
typedef enum {
TLVError_Unknown = 1, // Generic error to handle unexpected errors
TLVError_Authentication = 2, // Setup code or signature verification failed
TLVError_Backoff = 3, // Client must look at the retry delay TLV item and
// wait that many seconds before retrying
TLVError_MaxPeers = 4, // Server cannot accept any more pairings
TLVError_MaxTries = 5, // Server reached its maximum number of
// authentication attempts
TLVError_Unavailable = 6, // Server pairing method is unavailable
TLVError_Busy = 7, // Server is busy and cannot accept a pairing
// request at this time
} TLVError;
typedef enum {
// This specifies a success for the request
HAPStatus_Success = 0,
// Request denied due to insufficient privileges
HAPStatus_InsufficientPrivileges = -70401,
// Unable to communicate with requested services,
// e.g. the power to the accessory was turned off
HAPStatus_NoAccessoryConnection = -70402,
// Resource is busy, try again
HAPStatus_ResourceBusy = -70403,
// Connot write to read only characteristic
HAPStatus_ReadOnly = -70404,
// Cannot read from a write only characteristic
HAPStatus_WriteOnly = -70405,
// Notification is not supported for characteristic
HAPStatus_NotificationsUnsupported = -70406,
// Out of resources to process request
HAPStatus_OutOfResources = -70407,
// Operation timed out
HAPStatus_Timeout = -70408,
// Resource does not exist
HAPStatus_NoResource = -70409,
// Accessory received an invalid value in a write request
HAPStatus_InvalidValue = -70410,
// Insufficient Authorization
HAPStatus_InsufficientAuthorization = -70411,
} HAPStatus;
pair_verify_context_t *pair_verify_context_new() {
pair_verify_context_t *context = malloc(sizeof(pair_verify_context_t));
context->secret = NULL;
context->secret_size = 0;
context->session_key = NULL;
context->session_key_size = 0;
context->device_public_key = NULL;
context->device_public_key_size = 0;
context->accessory_public_key = NULL;
context->accessory_public_key_size = 0;
return context;
}
void pair_verify_context_free(pair_verify_context_t *context) {
if (context->secret)
free(context->secret);
if (context->session_key)
free(context->session_key);
if (context->device_public_key)
free(context->device_public_key);
if (context->accessory_public_key)
free(context->accessory_public_key);
free(context);
}
void init_client_context(client_context_t *c) {
c->server = NULL;
c->endpoint_params = NULL;
c->body = NULL;
c->body_length = 0;
c->pairing_id = -1;
c->encrypted = false;
c->count_reads = 0;
c->count_writes = 0;
c->disconnect = false;
c->event_queue = xQueueCreate(20, sizeof(characteristic_event_t*));
c->verify_context = NULL;
c->next = NULL;
}
void server_static_init() {
if (is_initialized)
return;
for (int i = 0; i < CLIENT_CONTEXT_CACHE_SIZE; i++) {
client_context_t*c= &(cache_client_contexts[i]);
init_client_context(c);
c->is_static = true;
c->is_used = false;
}
is_initialized = true;
}
client_context_t *client_context_new() {
for (int i = 0; i < CLIENT_CONTEXT_CACHE_SIZE; i++) {
client_context_t*c = &(cache_client_contexts[i]);
if (!c->is_used) {
c->is_used = true;
return c;
}
}
client_context_t *c = malloc(sizeof(client_context_t));
init_client_context(c);
return c;
}
void client_context_free(client_context_t *c) {
c->pairing_id = -1;
c->encrypted = false;
c->server = NULL;
c->count_reads = 0;
c->count_writes = 0;
c->disconnect = false;
if (c->verify_context)
pair_verify_context_free(c->verify_context);
c->verify_context = NULL;
if (c->endpoint_params)
query_params_free(c->endpoint_params);
c->endpoint_params = NULL;
// if (c->data)
// free(c->data);
if (c->body)
free(c->body);
c->body = NULL;
if (c->is_static) {
c->is_used = false;
if(c->event_queue)
xQueueReset(c->event_queue);
return;
}
if (c->event_queue)
vQueueDelete(c->event_queue);
free(c);
}
pairing_context_t *pairing_context_new() {
//INFO("allocating pairing_context_t");
DEBUG_HEAP();
//INFO("pc 1");
int i = sizeof(pairing_context_t);
//INFO("pc 2");
//INFO("size 0x%d", i);
pairing_context_t *context = malloc(sizeof(pairing_context_t));
//INFO("allocated 0x%d", (int)context);
//INFO("starting crypto");
context->srp = crypto_srp_new();
INFO("started crypto");
context->client = NULL;
context->public_key = NULL;
context->public_key_size = 0;
return context;
}
void pairing_context_free(pairing_context_t *context) {
if (context->srp) {
crypto_srp_free(context->srp);
}
if (context->public_key) {
free(context->public_key);
}
free(context);
}
void client_notify_characteristic(homekit_characteristic_t *ch, homekit_value_t value, void *client);
typedef enum {
characteristic_format_type = (1 << 1),
characteristic_format_meta = (1 << 2),
characteristic_format_perms = (1 << 3),
characteristic_format_events = (1 << 4),
} characteristic_format_t;
void write_characteristic_json(json_stream *json, client_context_t *client, const homekit_characteristic_t *ch, characteristic_format_t format, const homekit_value_t *value) {
json_string(json, "aid"); json_integer(json, ch->service->accessory->id);
json_string(json, "iid"); json_integer(json, ch->id);
if (format & characteristic_format_type) {
json_string(json, "type"); json_string(json, ch->type);
}
if (format & characteristic_format_perms) {
json_string(json, "perms"); json_array_start(json);
if (ch->permissions & homekit_permissions_paired_read)
json_string(json, "pr");
if (ch->permissions & homekit_permissions_paired_write)
json_string(json, "pw");
if (ch->permissions & homekit_permissions_notify)
json_string(json, "ev");
if (ch->permissions & homekit_permissions_additional_authorization)
json_string(json, "aa");
if (ch->permissions & homekit_permissions_timed_write)
json_string(json, "tw");
if (ch->permissions & homekit_permissions_hidden)
json_string(json, "hd");
json_array_end(json);
}
if ((format & characteristic_format_events) && (ch->permissions & homekit_permissions_notify)) {
bool events = homekit_characteristic_has_notify_callback(ch, client_notify_characteristic, client);
json_string(json, "ev"); json_boolean(json, events);
}
if (format & characteristic_format_meta) {
if (ch->description) {
json_string(json, "description"); json_string(json, ch->description);
}
const char *format_str = NULL;
switch(ch->format) {
case homekit_format_bool: format_str = "bool"; break;
case homekit_format_uint8: format_str = "uint8"; break;
case homekit_format_uint16: format_str = "uint16"; break;
case homekit_format_uint32: format_str = "uint32"; break;
case homekit_format_uint64: format_str = "uint64"; break;
case homekit_format_int: format_str = "int"; break;
case homekit_format_float: format_str = "float"; break;
case homekit_format_string: format_str = "string"; break;
case homekit_format_tlv: format_str = "tlv8"; break;
case homekit_format_data: format_str = "data"; break;
}
if (format_str) {
json_string(json, "format"); json_string(json, format_str);
}
const char *unit_str = NULL;
switch(ch->unit) {
case homekit_unit_none: break;
case homekit_unit_celsius: unit_str = "celsius"; break;
case homekit_unit_percentage: unit_str = "percentage"; break;
case homekit_unit_arcdegrees: unit_str = "arcdegrees"; break;
case homekit_unit_lux: unit_str = "lux"; break;
case homekit_unit_seconds: unit_str = "seconds"; break;
}
if (unit_str) {
json_string(json, "unit"); json_string(json, unit_str);
}
if (ch->min_value) {
json_string(json, "minValue"); json_float(json, *ch->min_value);
}
if (ch->max_value) {
json_string(json, "maxValue"); json_float(json, *ch->max_value);
}
if (ch->min_step) {
json_string(json, "minStep"); json_float(json, *ch->min_step);
}
if (ch->max_len) {
json_string(json, "maxLen"); json_integer(json, *ch->max_len);
}
if (ch->max_data_len) {
json_string(json, "maxDataLen"); json_integer(json, *ch->max_data_len);
}
if (ch->valid_values.count) {
json_string(json, "valid-values"); json_array_start(json);
for (int i=0; i<ch->valid_values.count; i++) {
json_integer(json, ch->valid_values.values[i]);
}
json_array_end(json);
}
if (ch->valid_values_ranges.count) {
json_string(json, "valid-values-range"); json_array_start(json);
for (int i=0; i<ch->valid_values_ranges.count; i++) {
json_array_start(json);
json_integer(json, ch->valid_values_ranges.ranges[i].start);
json_integer(json, ch->valid_values_ranges.ranges[i].end);
json_array_end(json);
}
json_array_end(json);
}
}
if (ch->permissions & homekit_permissions_paired_read) {
homekit_value_t v = value ? *value : ch->getter_ex ? ch->getter_ex(ch) : ch->value;
if (v.is_null) {
// json_string(json, "value"); json_null(json);
} else if (v.format != ch->format) {
ERROR("Characteristic value format is different from characteristic format");
} else {
switch(v.format) {
case homekit_format_bool: {
json_string(json, "value"); json_boolean(json, v.bool_value);
break;
}
case homekit_format_uint8:
case homekit_format_uint16:
case homekit_format_uint32:
case homekit_format_uint64:
case homekit_format_int: {
json_string(json, "value"); json_integer(json, v.int_value);
break;
}
case homekit_format_float: {
json_string(json, "value"); json_float(json, v.float_value);
break;
}
case homekit_format_string: {
json_string(json, "value"); json_string(json, v.string_value);
break;
}
case homekit_format_tlv: {
json_string(json, "value");
if (!v.tlv_values) {
json_string(json, "");
} else {
size_t tlv_size = 0;
tlv_format(v.tlv_values, NULL, &tlv_size);
if (tlv_size == 0) {
json_string(json, "");
} else {
byte *tlv_data = malloc(tlv_size);
tlv_format(v.tlv_values, tlv_data, &tlv_size);
size_t encoded_tlv_size = base64_encoded_size(tlv_data, tlv_size);
byte *encoded_tlv_data = malloc(encoded_tlv_size + 1);
esphap_base64_encode(tlv_data, tlv_size, encoded_tlv_data);
encoded_tlv_data[encoded_tlv_size] = 0;
json_string(json, (char*) encoded_tlv_data);
free(encoded_tlv_data);
free(tlv_data);
}
}
break;
}
case homekit_format_data:
json_string(json, "value");
if (!v.data_value || v.data_size == 0) {
json_string(json, "");
}
else {
size_t encoded_data_size = base64_encoded_size(v.data_value, v.data_size);
byte *encoded_data = malloc(encoded_data_size + 1);
if (!encoded_data) {
CLIENT_ERROR(client, "Failed to allocate %d bytes for encoding characteristic data", encoded_data_size + 1);
json_string(json, "");
break;
}
esphap_base64_encode(v.data_value, v.data_size, encoded_data);
encoded_data[encoded_data_size] = 0;
json_string(json, (char*)encoded_data);
free(encoded_data);
}
break;
}
}
if (!value && ch->getter_ex) {
// called getter to get value, need to free it
homekit_value_destruct(&v);
}
}
}
int client_send_encrypted(
client_context_t *context,
byte *payload, size_t size
) {
if (!context || !context->encrypted )
return -1;
byte nonce[12];
memset(nonce, 0, sizeof(nonce));
byte encrypted[1024 + 18];
int payload_offset = 0;
while (payload_offset < size) {
size_t chunk_size = size - payload_offset;
if (chunk_size > 1024)
chunk_size = 1024;
byte aead[2] = {chunk_size % 256, chunk_size / 256};
memcpy(encrypted, aead, 2);
byte i = 4;
int x = context->count_reads++;
while (x) {
nonce[i++] = x % 256;
x /= 256;
}
size_t available = sizeof(encrypted) - 2;
int r = crypto_chacha20poly1305_encrypt(
context->read_key, nonce, aead, 2,
payload+payload_offset, chunk_size,
encrypted+2, &available
);
if (r) {
ERROR("Failed to chacha encrypt payload (code %d)", r);
return -1;
}
payload_offset += chunk_size;
write(context->socket, encrypted, available + 2);
}
return 0;
}
int client_decrypt(
client_context_t *context,
byte *payload, size_t payload_size,
byte *decrypted, size_t *decrypted_size
) {
if (!context || !context->encrypted )
return -1;
const size_t block_size = 1024 + 16 + 2;
size_t required_decrypted_size =
payload_size / block_size * 1024 + payload_size % block_size - 16 - 2;
if (*decrypted_size < required_decrypted_size) {
*decrypted_size = required_decrypted_size;
return -2;
}
*decrypted_size = required_decrypted_size;
byte nonce[12];
memset(nonce, 0, sizeof(nonce));
int payload_offset = 0;
int decrypted_offset = 0;
while (payload_offset < payload_size) {
size_t chunk_size = payload[payload_offset] + payload[payload_offset+1]*256;
if (chunk_size+18 > payload_size-payload_offset) {
// Unfinished chunk
break;
}
byte i = 4;
int x = context->count_writes++;
while (x) {
nonce[i++] = x % 256;
x /= 256;
}
size_t decrypted_len = *decrypted_size - decrypted_offset;
int r = crypto_chacha20poly1305_decrypt(
context->write_key, nonce, payload+payload_offset, 2,
payload+payload_offset+2, chunk_size + 16,
decrypted, &decrypted_len
);
if (r) {
ERROR("Failed to chacha decrypt payload (code %d)", r);
return -1;
}
decrypted_offset += decrypted_len;
payload_offset += chunk_size + 0x12; // 0x10 is for some auth bytes
}
return payload_offset;
}
void homekit_setup_mdns(homekit_server_t *server);
void client_notify_characteristic(homekit_characteristic_t *ch, homekit_value_t value, void *context) {
client_context_t *client = context;
if (client->current_characteristic == ch && client->current_value && homekit_value_equal(client->current_value, &value))
// This value is set by this client, no need to send notification
return;
DEBUG("Got characteristic %d.%d change event", ch->service->accessory->id, ch->id);
if (!client->event_queue) {
ERROR("Client has no event queue. Skipping notification");
return;
}
characteristic_event_t *event = malloc(sizeof(characteristic_event_t));
event->characteristic = ch;
homekit_value_copy(&event->value, &value);
DEBUG("Sending event to client %d", client->socket);
xQueueSendToBack(client->event_queue, &event, 10);
}
void client_send(client_context_t *context, byte *data, size_t data_size) {
#ifdef HOMEKIT_DEBUG
if (data_size < 4096) {
char *payload = binary_to_string(data, data_size);
CLIENT_DEBUG(context, "Sending payload: %s", payload);
free(payload);
}
#endif
if (context->encrypted) {
int r = client_send_encrypted(context, data, data_size);
if (r) {
CLIENT_ERROR(context, "Failed to encrypt response (code %d)", r);
return;
}
} else {
write(context->socket, data, data_size);
}
}
void client_send_chunk(byte *data, size_t size, void *arg) {
client_context_t *context = arg;
size_t payload_size = size + 8;
byte *payload = malloc(payload_size);
int offset = snprintf((char *)payload, payload_size, "%x\r\n", size);
memcpy(payload + offset, data, size);
payload[offset + size] = '\r';
payload[offset + size + 1] = '\n';
client_send(context, payload, offset + size + 2);
free(payload);
}
void send_204_response(client_context_t *context) {
static char response[] = "HTTP/1.1 204 No Content\r\n\r\n";
client_send(context, (byte *)response, sizeof(response)-1);
}
void send_404_response(client_context_t *context) {
static char response[] = "HTTP/1.1 404 Not Found\r\n\r\n";
client_send(context, (byte *)response, sizeof(response)-1);
}
typedef struct _client_event {
const homekit_characteristic_t *characteristic;
homekit_value_t value;
struct _client_event *next;
} client_event_t;
void send_client_events(client_context_t *context, client_event_t *events) {
CLIENT_DEBUG(context, "Sending EVENT");
DEBUG_HEAP();
static byte http_headers[] =
"EVENT/1.0 200 OK\r\n"
"Content-Type: application/hap+json\r\n"
"Transfer-Encoding: chunked\r\n\r\n";
client_send(context, http_headers, sizeof(http_headers)-1);
// ~35 bytes per event JSON
// 256 should be enough for ~7 characteristic updates
json_stream *json = json_new(256, client_send_chunk, context);
json_object_start(json);
json_string(json, "characteristics"); json_array_start(json);
client_event_t *e = events;
while (e) {
json_object_start(json);
write_characteristic_json(json, context, e->characteristic, 0, &e->value);
json_object_end(json);
e = e->next;
}
json_array_end(json);
json_object_end(json);
json_flush(json);
json_free(json);
client_send_chunk(NULL, 0, context);
}
void send_tlv_response(client_context_t *context, tlv_values_t *values);
void send_tlv_error_response(client_context_t *context, int state, TLVError error) {
tlv_values_t *response = tlv_new();
tlv_add_integer_value(response, TLVType_State, 1, state);
tlv_add_integer_value(response, TLVType_Error, 1, error);
send_tlv_response(context, response);
}
void send_tlv_response(client_context_t *context, tlv_values_t *values) {
CLIENT_DEBUG(context, "Sending TLV response");
TLV_DEBUG(values);
size_t payload_size = 0;
tlv_format(values, NULL, &payload_size);
byte *payload = malloc(payload_size);
int r = tlv_format(values, payload, &payload_size);
if (r) {
CLIENT_ERROR(context, "Failed to format TLV payload (code %d)", r);
free(payload);
return;
}
tlv_free(values);
static char *http_headers =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/pairing+tlv8\r\n"
"Content-Length: %d\r\n"
"Connection: keep-alive\r\n\r\n";
int response_size = strlen(http_headers) + payload_size + 32;
char *response = malloc(response_size);
int response_len = snprintf(response, response_size, http_headers, payload_size);
if (response_size - response_len < payload_size + 1) {
CLIENT_ERROR(context, "Incorrect response buffer size %d: headers took %d, payload size %d", response_size, response_len, payload_size);
free(response);
free(payload);
return;
}
memcpy(response+response_len, payload, payload_size);
response_len += payload_size;
free(payload);
client_send(context, (byte *)response, response_len);
free(response);
}
static byte json_200_response_headers[] =
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/hap+json\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: keep-alive\r\n\r\n";
static byte json_207_response_headers[] =
"HTTP/1.1 207 Multi-Status\r\n"
"Content-Type: application/hap+json\r\n"
"Transfer-Encoding: chunked\r\n"
"Connection: keep-alive\r\n\r\n";
void send_json_response(client_context_t *context, int status_code, byte *payload, size_t payload_size) {
CLIENT_DEBUG(context, "Sending JSON response");
DEBUG_HEAP();
static char *http_headers =
"HTTP/1.1 %d %s\r\n"
"Content-Type: application/hap+json\r\n"
"Content-Length: %d\r\n"
"Connection: keep-alive\r\n\r\n";
CLIENT_DEBUG(context, "Payload: %s", payload);
const char *status_text = "OK";
switch (status_code) {
case 204: status_text = "No Content"; break;
case 207: status_text = "Multi-Status"; break;
case 400: status_text = "Bad Request"; break;
case 404: status_text = "Not Found"; break;
case 422: status_text = "Unprocessable Entity"; break;
case 500: status_text = "Internal Server Error"; break;
case 503: status_text = "Service Unavailable"; break;
}
int response_size = strlen(http_headers) + payload_size + strlen(status_text) + 32;
char *response = malloc(response_size);