forked from particle-iot/device-os
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spark_protocol.cpp
1865 lines (1618 loc) · 54 KB
/
spark_protocol.cpp
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
/**
******************************************************************************
* @file spark_protocol.cpp
* @authors Zachary Crockett, Matthew McGowan
* @version V1.0.0
* @date 15-Nov-2013
* @brief SPARK PROTOCOL
******************************************************************************
Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
#include "logging.h"
LOG_SOURCE_CATEGORY("comm.sparkprotocol")
#include "spark_protocol.h"
#include "protocol_selector.h"
#if !PARTICLE_PROTOCOL
#include "protocol_defs.h"
#include "handshake.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "device_keys.h"
#include "service_debug.h"
#include "messages.h"
#ifdef USE_MBEDTLS
#include "mbedtls_compat.h"
#include "mbedtls_util.h"
#endif
#include "communication_diagnostic.h"
using namespace particle::protocol;
#if 0
extern void serial_dump(const char* msg, ...);
#else
#define serial_dump(x, ...)
#endif
static inline size_t round_to_16(size_t len)
{
if (len == 0)
return len;
size_t rem = len % 16;
if (rem != 0) {
len += 16 - rem;
}
return len;
}
static inline int message_padding_strip(uint8_t* buf, int len)
{
if (len > 0) {
int nopadlen = len - (int)buf[len - 1];
if (nopadlen < 0)
nopadlen = 0;
return nopadlen;
}
return 0;
}
/**
* Handle the cryptographically secure random seed from the cloud by using
* it to seed the stdlib PRNG.
* @param seed A random value from a cryptographically secure random number generator.
*/
inline void default_random_seed_from_cloud(unsigned int seed)
{
srand(seed);
}
bool SparkProtocol::is_initialized(void)
{
return initialized;
}
void SparkProtocol::reset_updating(void)
{
updating = false;
last_chunk_millis = 0; // this is used for the time latency also
timesync_.reset();
}
SparkProtocol::SparkProtocol() :
QUEUE_SIZE(sizeof(queue)),
handlers({sizeof(handlers), NULL}),
last_ack_handlers_update(0),
expecting_ping_ack(false),
initialized(false),
updating(false),
product_id(PRODUCT_ID),
product_firmware_version(PRODUCT_FIRMWARE_VERSION)
{
queue_init();
}
void SparkProtocol::init(const char *id,
const SparkKeys &keys,
const SparkCallbacks &callbacks,
const SparkDescriptor &descriptor)
{
memcpy(server_public_key, keys.server_public, MAX_SERVER_PUBLIC_KEY_LENGTH);
memcpy(core_private_key, keys.core_private, MAX_DEVICE_PRIVATE_KEY_LENGTH);
memcpy(device_id, id, 12);
// when using this lib in C, constructor is never called
queue_init();
this->callbacks = callbacks;
this->descriptor = descriptor;
memset(event_handlers, 0, sizeof(event_handlers));
initialized = true;
}
int SparkProtocol::handshake(void)
{
LOG_CATEGORY("comm.sparkprotocol.handshake");
// FIXME: Pending completion handlers should be cancelled at the end of a previous session
ack_handlers.clear();
last_ack_handlers_update = callbacks.millis();
LOG(INFO,"Started: Receive nonce");
memcpy(queue + 40, device_id, 12);
int err = blocking_receive(queue, 40);
if (0 > err) { LOG(ERROR,"Could not receive nonce: %d", err); return err; }
LOG(INFO,"Encrypting handshake nonce");
extract_public_rsa_key(queue+52, core_private_key);
rsa_context rsa;
init_rsa_context_with_public_key(&rsa, server_public_key);
const int len = 52+MAX_DEVICE_PUBLIC_KEY_LENGTH;
#ifdef USE_MBEDTLS
err = mbedtls_rsa_pkcs1_encrypt(&rsa, mbedtls_default_rng, nullptr, MBEDTLS_RSA_PUBLIC, len, queue, queue + len);
#else
err = rsa_pkcs1_encrypt(&rsa, RSA_PUBLIC, len, queue, queue + len);
#endif
rsa_free(&rsa);
if (err) { LOG(ERROR,"RSA encrypt error %d", err); return err; }
LOG(INFO,"Sending encrypted nonce");
blocking_send(queue + len, 256);
LOG(INFO,"Receive key");
err = blocking_receive(queue, 384);
if (0 > err) { LOG(ERROR,"Unable to receive key %d", err); return err; }
LOG(INFO,"Setting key");
err = set_key(queue);
if (err) { LOG(ERROR,"Could not set key, %d"); return err; }
LOG(INFO,"Sending HELLO message");
hello(queue, descriptor.was_ota_upgrade_successful());
err = blocking_send(queue, 18);
if (0 > err) { LOG(ERROR,"Could not send HELLO message: %d", err); return err; }
LOG(INFO,"Receiving HELLO response");
if (!event_loop(CoAPMessageType::HELLO, 2000)) // read the hello message from the server
{
LOG(ERROR,"Could not receive HELLO response");
return -1;
}
LOG(INFO,"Completed");
return 0;
}
bool SparkProtocol::event_loop(CoAPMessageType::Enum message_type, system_tick_t timeout)
{
system_tick_t start = callbacks.millis();
do
{
CoAPMessageType::Enum msgtype;
if (!event_loop(msgtype))
return false;
if (msgtype==message_type)
return true;
// todo - ideally need a delay here
}
while ((callbacks.millis()-start) < timeout);
return false;
}
// Returns true if no errors and still connected.
// Returns false if there was an error, and we are probably disconnected.
bool SparkProtocol::event_loop(CoAPMessageType::Enum& message_type)
{
// Process expired completion handlers
const system_tick_t t = callbacks.millis();
ack_handlers.update(t - last_ack_handlers_update);
last_ack_handlers_update = t;
message_type = CoAPMessageType::NONE;
int bytes_received = callbacks.receive(queue, 2, nullptr);
if (2 <= bytes_received)
{
message_type = handle_received_message();
if (message_type==CoAPMessageType::ERROR)
{
LOG(WARN,"received ERROR CoAPMessage");
if (updating) { // was updating but had an error, inform the client
serial_dump("handle received message failed - aborting transfer");
callbacks.finish_firmware_update(file, UpdateFlag::ERROR, NULL);
updating = false;
}
// bail if and only if there was an error
return false;
}
}
else
{
if (0 > bytes_received)
{
LOG(WARN,"bytes recieved error %d", bytes_received);
// error, disconnected
return false;
}
if (updating)
{
system_tick_t millis_since_last_chunk = callbacks.millis() - last_chunk_millis;
if (3000 < millis_since_last_chunk)
{
if (updating==2) { // send missing chunks
serial_dump("timeout - resending missing chunks");
if (!send_missing_chunks(MISSED_CHUNKS_TO_SEND))
return false;
}
/* Do not resend chunks since this can cause duplicates on the server.
else
{
queue[0] = 0;
queue[1] = 16;
chunk_missed(queue + 2, chunk_index);
if (0 > blocking_send(queue, 18))
{
// error
return false;
}
}
*/
last_chunk_millis = callbacks.millis();
}
}
else
{
system_tick_t millis_since_last_message = callbacks.millis() - last_message_millis;
if (expecting_ping_ack)
{
if (10000 < millis_since_last_message)
{
// timed out, disconnect
expecting_ping_ack = false;
last_message_millis = callbacks.millis();
LOG(WARN,"ping ACK not received");
return false;
}
}
else
{
if (15000 < millis_since_last_message)
{
queue[0] = 0;
queue[1] = 16;
ping(queue + 2);
blocking_send(queue, 18);
expecting_ping_ack = true;
last_message_millis = callbacks.millis();
}
}
}
}
// no errors, still connected
return true;
}
// Returns bytes sent or -1 on error
int SparkProtocol::blocking_send(const unsigned char *buf, int length)
{
int bytes_or_error;
int byte_count = 0;
system_tick_t _millis = callbacks.millis();
while (length > byte_count)
{
bytes_or_error = callbacks.send(buf + byte_count, length - byte_count, nullptr);
if (0 > bytes_or_error)
{
// error, disconnected
serial_dump("blocking send error %d", bytes_or_error);
return bytes_or_error;
}
else if (0 < bytes_or_error)
{
byte_count += bytes_or_error;
}
else
{
if (20000 < (callbacks.millis() - _millis))
{
// timed out, disconnect
serial_dump("blocking send timeout");
return -1;
}
}
}
return byte_count;
}
// Returns bytes received or -1 on error
int SparkProtocol::blocking_receive(unsigned char *buf, int length)
{
int bytes_or_error;
int byte_count = 0;
system_tick_t _millis = callbacks.millis();
while (length > byte_count)
{
bytes_or_error = callbacks.receive(buf + byte_count, length - byte_count, nullptr);
if (0 > bytes_or_error)
{
// error, disconnected
serial_dump("receive error %d", bytes_or_error);
return bytes_or_error;
}
else if (0 < bytes_or_error)
{
byte_count += bytes_or_error;
}
else
{
if (20000 < (callbacks.millis() - _millis))
{
// timed out, disconnect
serial_dump("receive timeout");
return -1;
}
}
}
return byte_count;
}
CoAPMessageType::Enum
SparkProtocol::received_message(unsigned char *buf, size_t length)
{
unsigned char next_iv[16];
memcpy(next_iv, buf, 16);
#ifdef USE_MBEDTLS
mbedtls_aes_setkey_dec(&aes, key, 128);
mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, round_to_16(length), iv_receive, buf, buf);
#else
aes_setkey_dec(&aes, key, 128);
aes_crypt_cbc(&aes, AES_DECRYPT, length, iv_receive, buf, buf);
#endif
memcpy(iv_receive, next_iv, 16);
return Messages::decodeType(buf, length);
}
void SparkProtocol::hello(unsigned char *buf, bool newly_upgraded)
{
unsigned short message_id = next_message_id();
uint8_t flags = newly_upgraded ? 1 : 0;
// diagnostics are not supported in this protocol implementation.
size_t len = Messages::hello(buf+2, message_id, flags, PLATFORM_ID, product_id, product_firmware_version, false, nullptr, 0);
wrap(buf, len);
}
void SparkProtocol::key_changed(unsigned char *buf, unsigned char token)
{
separate_response(buf, token, 0x44);
}
void SparkProtocol::function_return(unsigned char *buf,
unsigned char token,
int return_value)
{
unsigned short message_id = next_message_id();
buf[0] = 0x51; // non-confirmable, one-byte token
buf[1] = 0x44; // response code 2.04 CHANGED
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value >> 24;
buf[7] = return_value >> 16 & 0xff;
buf[8] = return_value >> 8 & 0xff;
buf[9] = return_value & 0xff;
memset(buf + 10, 6, 6); // PKCS #7 padding
encrypt(buf, 16);
}
void SparkProtocol::variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
bool return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value ? 1 : 0;
memset(buf + 7, 9, 9); // PKCS #7 padding
encrypt(buf, 16);
}
void SparkProtocol::variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
int return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
buf[6] = return_value >> 24;
buf[7] = return_value >> 16 & 0xff;
buf[8] = return_value >> 8 & 0xff;
buf[9] = return_value & 0xff;
memset(buf + 10, 6, 6); // PKCS #7 padding
encrypt(buf, 16);
}
void SparkProtocol::variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
double return_value)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
memcpy(buf + 6, &return_value, 8);
memset(buf + 14, 2, 2); // PKCS #7 padding
encrypt(buf, 16);
}
// Returns the length of the buffer to send
int SparkProtocol::variable_value(unsigned char *buf,
unsigned char token,
unsigned char message_id_msb,
unsigned char message_id_lsb,
const void *return_value,
int length)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
memcpy(buf + 6, return_value, length);
int msglen = 6 + length;
int buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(buf + msglen, pad, pad); // PKCS #7 padding
encrypt(buf, buflen);
return buflen;
}
inline bool is_system(const char* event_name) {
return !strncmp(event_name, "spark/", 6);
}
// Returns true on success, false on sending timeout or rate-limiting failure
bool SparkProtocol::send_event(const char *event_name, const char *data, int ttl, EventType::Enum event_type,
int flags, CompletionHandler handler)
{
if (updating)
{
handler.setError(SYSTEM_ERROR_BUSY);
return false;
}
bool is_system_event = is_system(event_name);
if (is_system_event) {
static uint16_t lastMinute = 0;
static uint8_t eventsThisMinute = 0;
uint16_t currentMinute = uint16_t(callbacks.millis()>>16);
if (currentMinute==lastMinute) { // == handles millis() overflow
if (eventsThisMinute==255) {
g_rateLimitedEventsCounter++;
handler.setError(SYSTEM_ERROR_LIMIT_EXCEEDED);
return false;
}
}
else {
lastMinute = currentMinute;
eventsThisMinute = 0;
}
eventsThisMinute++;
}
else {
static system_tick_t recent_event_ticks[5] = {
(system_tick_t) -1000, (system_tick_t) -1000,
(system_tick_t) -1000, (system_tick_t) -1000,
(system_tick_t) -1000 };
static int evt_tick_idx = 0;
system_tick_t now = recent_event_ticks[evt_tick_idx] = callbacks.millis();
evt_tick_idx++;
evt_tick_idx %= 5;
if (now - recent_event_ticks[evt_tick_idx] < 1000)
{
// exceeded allowable burst of 4 events per second
g_rateLimitedEventsCounter++;
handler.setError(SYSTEM_ERROR_LIMIT_EXCEEDED);
return false;
}
}
uint16_t msg_id = next_message_id();
const bool confirmable = flags & EventType::WITH_ACK;
size_t msglen = Messages::event(queue + 2, msg_id, event_name, data, ttl, event_type, confirmable);
size_t wrapped_len = wrap(queue, msglen);
const int n = blocking_send(queue, wrapped_len);
if (n < 0) {
handler.setError(SYSTEM_ERROR_IO);
return false;
}
// Currently, the server sends acknowledgements for all published events, regardless of whether
// original request has been sent as confirmable or non-confirmable CoAP message. Here we register
// completion handler only if acknowledgement was requested explicitly
if (flags & EventType::WITH_ACK) {
ack_handlers.addHandler(msg_id, std::move(handler), SEND_EVENT_ACK_TIMEOUT);
} else {
handler.setResult();
}
return true;
}
size_t SparkProtocol::time_request(unsigned char *buf)
{
uint16_t msg_id = next_message_id();
uint8_t token = next_token();
return Messages::time_request(buf, msg_id, token);
}
// returns true on success, false on failure
bool SparkProtocol::send_time_request(void)
{
if (updating)
{
return false;
}
return timesync_.send_request(callbacks.millis(), [&]() {
size_t msglen = time_request(queue + 2);
size_t wrapped_len = wrap(queue, msglen);
last_chunk_millis = callbacks.millis();
return (0 <= blocking_send(queue, wrapped_len));
});
}
bool SparkProtocol::send_subscription(const char *event_name, const char *device_id)
{
uint16_t msg_id = next_message_id();
size_t msglen = subscription(queue + 2, msg_id, event_name, device_id);
size_t buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(queue + 2 + msglen, pad, pad); // PKCS #7 padding
encrypt(queue + 2, buflen);
queue[0] = (buflen >> 8) & 0xff;
queue[1] = buflen & 0xff;
return (0 <= blocking_send(queue, buflen + 2));
}
bool SparkProtocol::send_subscription(const char *event_name,
SubscriptionScope::Enum scope)
{
uint16_t msg_id = next_message_id();
size_t msglen = subscription(queue + 2, msg_id, event_name, scope);
size_t buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(queue + 2 + msglen, pad, pad); // PKCS #7 padding
encrypt(queue + 2, buflen);
queue[0] = (buflen >> 8) & 0xff;
queue[1] = buflen & 0xff;
return (0 <= blocking_send(queue, buflen + 2));
}
void SparkProtocol::send_subscriptions()
{
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (NULL != event_handlers[i].handler)
{
if (event_handlers[i].device_id[0])
{
send_subscription(event_handlers[i].filter, event_handlers[i].device_id);
}
else
{
send_subscription(event_handlers[i].filter, event_handlers[i].scope);
}
}
}
}
void SparkProtocol::remove_event_handlers(const char* event_name)
{
if (NULL == event_name)
{
memset(event_handlers, 0, sizeof(event_handlers));
}
else
{
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
int dest = 0;
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (!strcmp(event_name, event_handlers[i].filter))
{
memset(&event_handlers[i], 0, sizeof(event_handlers[i]));
}
else
{
if (dest!=i) {
memcpy(event_handlers+dest, event_handlers+i, sizeof(event_handlers[i]));
memset(event_handlers+i, 0, sizeof(event_handlers[i]));
}
dest++;
}
}
}
}
bool SparkProtocol::event_handler_exists(const char *event_name, EventHandler handler,
void *handler_data, SubscriptionScope::Enum scope, const char* id)
{
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (event_handlers[i].handler==handler &&
event_handlers[i].handler_data==handler_data &&
event_handlers[i].scope==scope) {
const size_t MAX_FILTER_LEN = sizeof(event_handlers[i].filter);
const size_t FILTER_LEN = strnlen(event_name, MAX_FILTER_LEN);
if (!strncmp(event_handlers[i].filter, event_name, FILTER_LEN)) {
const size_t MAX_ID_LEN = sizeof(event_handlers[i].device_id)-1;
const size_t id_len = id ? strnlen(id, MAX_ID_LEN) : 0;
if (id_len)
return !strncmp(event_handlers[i].device_id, id, id_len);
else
return !event_handlers[i].device_id[0];
}
}
}
return false;
}
bool SparkProtocol::add_event_handler(const char *event_name, EventHandler handler,
void *handler_data, SubscriptionScope::Enum scope, const char* id)
{
if (event_handler_exists(event_name, handler, handler_data, scope, id))
return true;
const int NUM_HANDLERS = sizeof(event_handlers) / sizeof(FilteringEventHandler);
for (int i = 0; i < NUM_HANDLERS; i++)
{
if (NULL == event_handlers[i].handler)
{
const size_t MAX_FILTER_LEN = sizeof(event_handlers[i].filter);
const size_t FILTER_LEN = strnlen(event_name, MAX_FILTER_LEN);
memcpy(event_handlers[i].filter, event_name, FILTER_LEN);
memset(event_handlers[i].filter + FILTER_LEN, 0, MAX_FILTER_LEN - FILTER_LEN);
event_handlers[i].handler = handler;
event_handlers[i].handler_data = handler_data;
event_handlers[i].device_id[0] = 0;
const size_t MAX_ID_LEN = sizeof(event_handlers[i].device_id)-1;
const size_t id_len = id ? strnlen(id, MAX_ID_LEN) : 0;
memcpy(event_handlers[i].device_id, id, id_len);
event_handlers[i].device_id[id_len] = 0;
event_handlers[i].scope = scope;
return true;
}
}
return false;
}
void SparkProtocol::chunk_received(unsigned char *buf,
unsigned char token,
ChunkReceivedCode::Enum code)
{
separate_response(buf, token, code);
}
int SparkProtocol::send_missing_chunks(int count)
{
int sent = 0;
chunk_index_t idx = 0;
uint8_t* buf = queue+2;
unsigned short message_id = next_message_id();
buf[0] = 0x40; // confirmable, no token
buf[1] = 0x01; // code 0.01 GET
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
buf[4] = 0xb1; // one-byte Uri-Path option
buf[5] = 'c';
buf[6] = 0xff; // payload marker
while ((idx=next_chunk_missing(chunk_index_t(idx)))!=NO_CHUNKS_MISSING && sent<count)
{
buf[(sent*2)+7] = idx >> 8;
buf[(sent*2)+8] = idx & 0xFF;
missed_chunk_index = idx;
idx++;
sent++;
}
if (sent>0) {
LOG(WARN,"Sent %d missing chunks", sent);
size_t message_size = 7+(sent*2);
message_size = wrap(queue, message_size);
if (0 > blocking_send(queue, message_size))
return -1;
}
return sent;
}
void SparkProtocol::chunk_missed(unsigned char *buf, unsigned short chunk_index)
{
unsigned short message_id = next_message_id();
buf[0] = 0x40; // confirmable, no token
buf[1] = 0x01; // code 0.01 GET
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
buf[4] = 0xb1; // one-byte Uri-Path option
buf[5] = 'c';
buf[6] = 0xff; // payload marker
buf[7] = chunk_index >> 8;
buf[8] = chunk_index & 0xff;
memset(buf + 9, 7, 7); // PKCS #7 padding
encrypt(buf, 16);
}
void SparkProtocol::update_ready(unsigned char *buf, unsigned char token)
{
separate_response_with_payload(buf, token, 0x44, NULL, 0);
}
void SparkProtocol::update_ready(unsigned char *buf, unsigned char token, uint8_t flags)
{
separate_response_with_payload(buf, token, 0x44, &flags, 1);
}
int SparkProtocol::description(unsigned char *buf, unsigned char token,
unsigned char message_id_msb, unsigned char message_id_lsb, int desc_flags)
{
buf[0] = 0x61; // acknowledgment, one-byte token
buf[1] = 0x45; // response code 2.05 CONTENT
buf[2] = message_id_msb;
buf[3] = message_id_lsb;
buf[4] = token;
buf[5] = 0xff; // payload marker
BufferAppender appender(buf+6, QUEUE_SIZE-8);
appender.append("{");
bool has_content = false;
if (desc_flags & DESCRIBE_APPLICATION) {
has_content = true;
appender.append("\"f\":[");
int num_keys = descriptor.num_functions();
int i;
for (i = 0; i < num_keys; ++i)
{
if (i)
{
appender.append(',');
}
appender.append('"');
const char* key = descriptor.get_function_key(i);
size_t function_name_length = strlen(key);
if (MAX_FUNCTION_KEY_LENGTH < function_name_length)
{
function_name_length = MAX_FUNCTION_KEY_LENGTH;
}
appender.append((const uint8_t*)key, function_name_length);
appender.append('"');
}
appender.append("],\"v\":{");
num_keys = descriptor.num_variables();
for (i = 0; i < num_keys; ++i)
{
if (i)
{
appender.append(',');
}
appender.append('"');
const char* key = descriptor.get_variable_key(i);
size_t variable_name_length = strlen(key);
SparkReturnType::Enum t = descriptor.variable_type(key);
if (MAX_VARIABLE_KEY_LENGTH < variable_name_length)
{
variable_name_length = MAX_VARIABLE_KEY_LENGTH;
}
appender.append((const uint8_t*)key, variable_name_length);
appender.append("\":");
appender.append('0' + (char)t);
}
appender.append('}');
}
if (descriptor.append_system_info && (desc_flags&DESCRIBE_SYSTEM)) {
if (has_content)
appender.append(',');
descriptor.append_system_info(append_instance, &appender, NULL);
}
appender.append('}');
int msglen = appender.next() - (uint8_t *)buf;
int buflen = (msglen & ~15) + 16;
char pad = buflen - msglen;
memset(buf+msglen, pad, pad); // PKCS #7 padding
encrypt(buf, buflen);
return buflen;
}
void SparkProtocol::ping(unsigned char *buf)
{
unsigned short message_id = next_message_id();
buf[0] = 0x40; // Confirmable, no token
buf[1] = 0x00; // code signifying empty message
buf[2] = message_id >> 8;
buf[3] = message_id & 0xff;
memset(buf + 4, 12, 12); // PKCS #7 padding
encrypt(buf, 16);
}
int SparkProtocol::presence_announcement(unsigned char *buf, const unsigned char *id)
{
buf[0] = 0x50; // Confirmable, no token
buf[1] = 0x02; // Code POST
buf[2] = 0x00; // message id ignorable in this context
buf[3] = 0x00;
buf[4] = 0xb1; // Uri-Path option of length 1
buf[5] = 'h';
buf[6] = 0xff; // payload marker
memcpy(buf + 7, id, 12);
return 19;
}
/********** Queue **********/
#if 0
int SparkProtocol::queue_bytes_available()
{
int unoccupied = queue_front - queue_back - 1;
if (unoccupied < 0)
return unoccupied + QUEUE_SIZE;
else
return unoccupied;
}
// these methods are unused
int SparkProtocol::queue_push(const char *src, int length)
{
int available = queue_bytes_available();
if (queue_back >= queue_front)
{
int tail_available = queue_mem_boundary - queue_back;
if (length <= available)
{
if (length <= tail_available)
{
memcpy(queue_back, src, length);
queue_back += length;
}
else
{
int head_needed = length - tail_available;
memcpy(queue_back, src, tail_available);
memcpy(queue, src + tail_available, head_needed);
queue_back = queue + head_needed;
}
return length;
}
else
{
// queue_back is greater than or equal to queue_front
// and length is greater than available
if (available < tail_available)
{
// queue_front is equal to queue, so don't fill the last bucket
memcpy(queue_back, src, available);
queue_back += available;
}
else
{
int head_available = available - tail_available;
memcpy(queue_back, src, tail_available);
memcpy(queue, src + tail_available, head_available);
queue_back = queue + head_available;
}
return available;
}
}
else
{
// queue_back is less than queue_front
int count = length < available ? length : available;
memcpy(queue_back, src, count);
queue_back += count;
return count;
}
}
int SparkProtocol::queue_pop(char *dst, int length)
{
if (queue_back >= queue_front)
{
int filled = queue_back - queue_front;
int count = length <= filled ? length : filled;