forked from zephyrproject-rtos/net-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coap-client.c
1911 lines (1604 loc) · 47.3 KB
/
coap-client.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 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Various utility functions taken from libcoap with this license:
Copyright (c) 2010--2015, Olaf Bergmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <errno.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <net/if.h>
#include <linux/sockios.h>
#include <ifaddrs.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <tinydtls.h>
#include <global.h>
#include <debug.h>
#include <dtls.h>
/* tinyDTLS and libcoap have same preprocessor symbols defined in their
* include files so undef conflicting symbols here.
*/
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_URL
#undef PACKAGE_VERSION
#undef UTHASH_VERSION
#undef HASH_FIND
#undef HASH_ADD
#undef HASH_ADD_KEYPTR
#undef HASH_DELETE
#undef HASH_FIND_STR
#undef HASH_ADD_STR
#undef HASH_BER
#undef HASH_FNV
#undef HASH_JEN
#undef HASH_SFH
#undef HASH_FIND_IN_BKT
#undef HASH_SRT
#undef HASH_CLEAR
#undef UTLIST_VERSION
#undef _NEXT
#undef _NEXTASGN
#undef _PREVASGN
#undef LL_SORT
#undef DL_SORT
#undef CDL_SORT
#undef LL_PREPEND
#undef LL_APPEND
#undef LL_DELETE
#undef LL_APPEND_VS2008
#undef LL_DELETE_VS2008
#undef LL_FOREACH
#undef LL_FOREACH_SAFE
#undef LL_SEARCH_SCALAR
#undef LL_SEARCH
#undef DL_PREPEND
#undef DL_APPEND
#undef DL_DELETE
#undef DL_FOREACH
#undef DL_FOREACH_SAFE
#undef CDL_PREPEND
#undef CDL_DELETE
#undef CDL_FOREACH
#undef CDL_FOREACH_SAFE
#undef CDL_SEARCH_SCALAR
#undef CDL_SEARCH
#define UTHASH_H
#include <coap/coap.h>
typedef struct coap_list_t {
struct coap_list_t *next;
char data[];
} coap_list_t;
#ifdef __GNUC__
#define UNUSED_PARAM __attribute__((unused))
#else
#define UNUSED_PARAM
#endif /* __GNUC__ */
#define SERVER_PORT 5683
#define SERVER_SECURE_PORT 5684
#define CLIENT_PORT 8484
#define MAX_BUF_SIZE 1280 /* min IPv6 MTU, the actual data is smaller */
#define MAX_TIMEOUT 6 /* in seconds */
static bool debug;
static int renegotiate = -1;
static session_t session;
static bool no_dtls;
static const char *target;
static int family;
static coap_block_t block = {
.num = 0,
.m = 0,
.szx = 6
};
static unsigned int wait_seconds = MAX_TIMEOUT; /* default timeout in secs */
static coap_tick_t max_wait;
static unsigned int obs_seconds = MAX_TIMEOUT * 2; /* default observe time */
static coap_tick_t obs_wait = 0; /* timeout for current subscription */
static int ready = 0;
static coap_list_t *optlist;
static unsigned char _token_data[8];
static str the_token = { 0, _token_data };
typedef unsigned char method_t;
static str payload = { 0, NULL }; /* optional payload to send */
static int flags = 0;
#define FLAGS_BLOCK 0x01
static method_t method;
static coap_pdu_t *coap_new_request(coap_context_t *ctx,
method_t m,
coap_list_t **options,
const unsigned char *data,
size_t length,
int msgtype);
#define ENTRY(desc, entry, expect_result, method, test_data, length, mid,\
confirmed) \
{ \
.description = #desc , \
.len = sizeof(entry), \
.buf = entry, \
.expecting_reply = expect_result, \
.data = test_data, \
.data_len = length, \
.coap_method = COAP_REQUEST_ ## method, \
.check_mid = mid, \
.message_type = confirmed, \
}
#define ENTRY2(desc, entry, expect_result, method, test_data, length, \
test_payload, test_payload_len, mid, confirmed) \
{ \
.description = #desc , \
.len = sizeof(entry), \
.buf = entry, \
.expecting_reply = expect_result, \
.data = test_data, \
.data_len = length, \
.payload = test_payload, \
.payload_len = test_payload_len, \
.coap_method = COAP_REQUEST_ ## method, \
.check_mid = mid, \
.message_type = confirmed, \
}
#define ENTRY3(desc, entry, expect_result, method, test_data, length, mid,\
confirmed) \
{ \
.description = #desc , \
.len = sizeof(entry), \
.buf = entry, \
.expecting_reply = expect_result, \
.data = test_data, \
.data_len = length, \
.coap_method = COAP_REQUEST_ ## method, \
.check_mid = mid, \
.message_type = confirmed, \
.add_token = true, \
}
#define ENTRY4(desc, entry, expect_result, method, test_data, length, \
test_payload, test_payload_len, mid, confirmed) \
{ \
.description = #desc , \
.len = sizeof(entry), \
.buf = entry, \
.expecting_reply = expect_result, \
.data = test_data, \
.data_len = length, \
.payload = test_payload, \
.payload_len = test_payload_len, \
.coap_method = COAP_REQUEST_ ## method, \
.check_mid = mid, \
.message_type = confirmed, \
.add_token = true, \
}
#define GET_CON(desc, e, r, c) ENTRY(desc, e, true, GET, r, sizeof(r), c, \
COAP_MESSAGE_CON)
#define POST_CON(desc, e, r, c) ENTRY(desc, e, true, POST, r, sizeof(r), c, \
COAP_MESSAGE_CON)
#define PUT_CON(desc, e, d, p, c) ENTRY2(desc, e, true, PUT, d, sizeof(d), \
p, sizeof(p), c, COAP_MESSAGE_CON)
#define DELETE_CON(desc,e, r, c) ENTRY(desc, e, true, DELETE, r, sizeof(r), c,\
COAP_MESSAGE_CON)
#define GET_NON(desc, e, r, c) ENTRY(desc, e, true, GET, r, sizeof(r), c, \
COAP_MESSAGE_NON)
#define POST_NON(desc, e, r, c) ENTRY(desc, e, true, POST, r, sizeof(r), c, \
COAP_MESSAGE_NON)
#define PUT_NON(desc, e, d, p, c) ENTRY2(desc, e, true, PUT, d, sizeof(d), \
p, sizeof(p), c, COAP_MESSAGE_NON)
#define DELETE_NON(desc,e, r, c) ENTRY(desc, e, true, DELETE, r, sizeof(r), c,\
COAP_MESSAGE_NON)
#define GET_CON_TOKEN(desc, e, r, c) ENTRY3(desc, e, true, GET, r, sizeof(r), \
c, COAP_MESSAGE_CON)
#define POST_CON_TOKEN(desc, e, r, c) ENTRY3(desc, e, true, POST, r, \
sizeof(r), c, COAP_MESSAGE_CON)
#define PUT_CON_TOKEN(desc, e, d, p, c) ENTRY4(desc, e, true, PUT, d, \
sizeof(d), p, sizeof(p), c,\
COAP_MESSAGE_CON)
#define DELETE_CON_TOKEN(desc,e, r, c) ENTRY3(desc, e, true, DELETE, r, \
sizeof(r), c, COAP_MESSAGE_CON)
#define GET_CON_PAYLOAD(desc, e, d, p, c) ENTRY2(desc, e, true, GET, \
d, sizeof(d), \
p, sizeof(p), c, \
COAP_MESSAGE_CON)
#define RES(var, path) \
static const char res_ ## var [] = path ;
#define DATA_ARRAY(var, data, ...) \
static const char var [] = { data, __VA_ARGS__ } ;
#define DATA_STRING(var, data) \
static const char var [] = data;
RES(core, ".well-known/core");
RES(test, "test");
RES(seg, "seg1/seg2/seg3");
RES(query, "query");
/* See this test specification document for different test descriptions
* http://www.etsi.org/plugtests/CoAP/Document/CoAP_TestDescriptions_v015.pdf
*/
DATA_STRING(get_con, "Type: 0\nCode: 1\n");
DATA_STRING(post_con, "Type: 0\nCode: 2\n");
DATA_STRING(put_con, "Type: 0\nCode: 3\n");
DATA_STRING(delete_con, "Type: 0\nCode: 4\n");
DATA_STRING(get_non, "Type: 1\nCode: 1\n");
DATA_STRING(post_non, "Type: 1\nCode: 2\n");
DATA_STRING(put_non, "Type: 1\nCode: 3\n");
DATA_STRING(delete_non, "Type: 1\nCode: 4\n");
/* Generated by http://www.lipsum.com/
* 1202 bytes of Lorem Ipsum.
*
* This is the maximum we can send with encryption.
*/
static const char lorem_ipsum[] =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin congue orci et lectus ultricies, sed elementum urna finibus. Nam bibendum, massa id sollicitudin finibus, massa ante pharetra lacus, nec semper felis metus eu massa. Curabitur gravida, neque a pulvinar suscipit, felis massa maximus neque, eu sagittis felis enim nec justo. Suspendisse sit amet sem a magna aliquam tincidunt. Mauris consequat ante in consequat auctor. Nam eu congue mauris, congue aliquet metus. Etiam elit ipsum, vehicula et lectus at, dignissim accumsan turpis. Sed magna nisl, tempor ut dolor sed, feugiat pharetra velit. Nulla sed purus at elit dapibus lobortis. In hac habitasse platea dictumst. Praesent quis libero id enim aliquet viverra eleifend non urna. Vivamus metus justo, dignissim eget libero molestie, tincidunt pellentesque purus. Quisque pulvinar, nisi sed egestas vestibulum, ante felis elementum justo, ut viverra nisl est sagittis leo. Curabitur pharetra eros at felis ultricies efficitur."
"\n"
"Ut rutrum urna vitae neque rhoncus, id dictum ex dictum. Suspendisse venenatis vel mauris sed maximus. Sed malesuada elit vel neque hendrerit, in accumsan odio sodales. Aliquam erat volutpat. Praesent non situ.\n";
static const char lorem_ipsum_short[] = "Lorem ipsum dolor sit amet.";
static struct data {
const char *description;
int len;
method_t coap_method;
const unsigned char *buf;
bool expecting_reply;
const unsigned char *data; /* data to be sent */
int data_len;
const unsigned char *payload; /* possible payload to be sent */
int payload_len;
bool check_mid;
int expected_mid; /* message id we sent */
int message_type;
bool add_token;
} data[] = {
GET_CON(TD_COAP_CORE_01, res_test, get_con, true),
POST_CON(TD_COAP_CORE_02, res_test, post_con, false),
PUT_CON(TD_COAP_CORE_03, res_test, put_con, lorem_ipsum, false),
DELETE_CON(TD_COAP_CORE_04, res_test, delete_con, false),
GET_NON(TD_COAP_CORE_05, res_test, get_non, true),
POST_NON(TD_COAP_CORE_06, res_test, post_non, false),
PUT_NON(TD_COAP_CORE_07, res_test, put_non, lorem_ipsum, false),
DELETE_NON(TD_COAP_CORE_08, res_test, delete_non, false),
/* /separate not supported atm */
//GET_CON(TD_COAP_CORE_09, res_separate, get_con, true),
GET_CON_TOKEN(TD_COAP_CORE_10, res_test, get_con, true),
/* Isn't test case 11 same as test case 01? */
GET_CON(TD_COAP_CORE_11, res_test, get_con, true),
GET_CON(TD_COAP_CORE_12, res_seg, get_con, true),
GET_CON(TD_COAP_CORE_13, res_query, get_con, true),
/* Test 14 & 15 are for testing gateway scenario so not used here */
// TD_COAP_CORE_14
// TD_COAP_CORE_15
/* /separate not supported atm */
//GET_NON(TD_COAP_CORE_16, res_separate, get_con, true),
#if TO_BE_DONE
GET_CON(TD_COAP_LINK_01, res_core, get_con, true),
//TD_COAP_LINK_02
// TD_COAP_BLOCK_01
// TD_COAP_BLOCK_02
// TD_COAP_BLOCK_03
// TD_COAP_BLOCK_04
// TD_COAP_OBS_01
// TD_COAP_OBS_02
// TD_COAP_OBS_03
// TD_COAP_OBS_04
// TD_COAP_OBS_05
#endif
{ 0, 0 }
};
struct client_data {
bool fail;
int fd;
int index; /* position in data[] */
int ifindex; /* network interface index */
coap_context_t *coap_ctx;
coap_address_t coap_dst;
int len;
#define MAX_READ_BUF 2000
uint8 buf[MAX_READ_BUF];
};
static struct client_data *test_context;
static void set_coap_timeout(coap_tick_t *timer, const unsigned int seconds)
{
coap_ticks(timer);
*timer += seconds * COAP_TICKS_PER_SECOND;
}
static int get_ifindex(const char *name)
{
struct ifreq ifr;
int sk, err;
if (!name)
return -1;
sk = socket(PF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (sk < 0)
return -1;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
err = ioctl(sk, SIOCGIFINDEX, &ifr);
close(sk);
if (err < 0)
return -1;
return ifr.ifr_ifindex;
}
static int find_address(int family, struct ifaddrs *if_address,
const char *if_name, void *address)
{
struct ifaddrs *tmp;
struct sockaddr_in6 *ll = NULL;
int error = -ENOENT;
for (tmp = if_address; tmp; tmp = tmp->ifa_next) {
if (tmp->ifa_addr &&
!strncmp(tmp->ifa_name, if_name, IF_NAMESIZE) &&
tmp->ifa_addr->sa_family == family) {
switch (family) {
case AF_INET: {
struct sockaddr_in *in4 =
(struct sockaddr_in *)tmp->ifa_addr;
if (in4->sin_addr.s_addr == INADDR_ANY)
continue;
if ((in4->sin_addr.s_addr & IN_CLASSB_NET) ==
((in_addr_t)0xa9fe0000))
continue;
memcpy(address, &in4->sin_addr,
sizeof(struct in_addr));
error = 0;
goto out;
}
case AF_INET6: {
struct sockaddr_in6 *in6 =
(struct sockaddr_in6 *)tmp->ifa_addr;
if (!memcmp(&in6->sin6_addr, &in6addr_any,
sizeof(struct in6_addr)))
continue;
if (IN6_IS_ADDR_LINKLOCAL(&in6->sin6_addr)) {
ll = in6;
continue;
}
memcpy(address, &in6->sin6_addr,
sizeof(struct in6_addr));
error = 0;
goto out;
}
default:
error = -EINVAL;
goto out;
}
}
}
out:
if (error < 0 && ll) {
/* As a last resort use link local address */
memcpy(address, &ll->sin6_addr, sizeof(struct in6_addr));
error = 0;
}
return error;
}
static int get_address(const char *if_name, int family, void *address)
{
struct ifaddrs *if_address;
int err;
if (getifaddrs(&if_address) < 0) {
err = -errno;
fprintf(stderr, "Cannot get interface addresses for "
"interface %s error %d/%s",
if_name, err, strerror(-err));
return err;
}
err = find_address(family, if_address, if_name, address);
freeifaddrs(if_address);
return err;
}
#define PSK_DEFAULT_IDENTITY "Client_identity"
#define PSK_DEFAULT_KEY "secretPSK"
#define PSK_OPTIONS "i:k:"
static bool quit = false;
static dtls_context_t *dtls_context;
static const unsigned char ecdsa_priv_key[] = {
0x41, 0xC1, 0xCB, 0x6B, 0x51, 0x24, 0x7A, 0x14,
0x43, 0x21, 0x43, 0x5B, 0x7A, 0x80, 0xE7, 0x14,
0x89, 0x6A, 0x33, 0xBB, 0xAD, 0x72, 0x94, 0xCA,
0x40, 0x14, 0x55, 0xA1, 0x94, 0xA9, 0x49, 0xFA};
static const unsigned char ecdsa_pub_key_x[] = {
0x36, 0xDF, 0xE2, 0xC6, 0xF9, 0xF2, 0xED, 0x29,
0xDA, 0x0A, 0x9A, 0x8F, 0x62, 0x68, 0x4E, 0x91,
0x63, 0x75, 0xBA, 0x10, 0x30, 0x0C, 0x28, 0xC5,
0xE4, 0x7C, 0xFB, 0xF2, 0x5F, 0xA5, 0x8F, 0x52};
static const unsigned char ecdsa_pub_key_y[] = {
0x71, 0xA0, 0xD4, 0xFC, 0xDE, 0x1A, 0xB8, 0x78,
0x5A, 0x3C, 0x78, 0x69, 0x35, 0xA7, 0xCF, 0xAB,
0xE9, 0x3F, 0x98, 0x72, 0x09, 0xDA, 0xED, 0x0B,
0x4F, 0xAB, 0xC3, 0x6F, 0xC7, 0x72, 0xF8, 0x29};
#ifdef DTLS_PSK
/* The PSK information for DTLS */
#define PSK_ID_MAXLEN 256
#define PSK_MAXLEN 256
static unsigned char psk_id[PSK_ID_MAXLEN];
static size_t psk_id_length = 0;
static unsigned char psk_key[PSK_MAXLEN];
static size_t psk_key_length = 0;
/* This function is the "key store" for tinyDTLS. It is called to
* retrieve a key for the given identity within this particular
* session. */
static int get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
const session_t *session UNUSED_PARAM,
dtls_credentials_type_t type,
const unsigned char *id, size_t id_len,
unsigned char *result, size_t result_length)
{
switch (type) {
case DTLS_PSK_IDENTITY:
if (id_len) {
dtls_debug("got psk_identity_hint: '%.*s'\n", id_len,
id);
}
if (result_length < psk_id_length) {
dtls_warn("cannot set psk_identity -- buffer too small\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
memcpy(result, psk_id, psk_id_length);
return psk_id_length;
case DTLS_PSK_KEY:
if (id_len != psk_id_length || memcmp(psk_id, id, id_len) != 0) {
dtls_warn("PSK for unknown id requested, exiting\n");
return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
} else if (result_length < psk_key_length) {
dtls_warn("cannot set psk -- buffer too small\n");
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
memcpy(result, psk_key, psk_key_length);
return psk_key_length;
default:
dtls_warn("unsupported request type: %d\n", type);
}
return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
}
#endif /* DTLS_PSK */
#ifdef DTLS_ECC
static int get_ecdsa_key(struct dtls_context_t *ctx,
const session_t *session,
const dtls_ecdsa_key_t **result)
{
static const dtls_ecdsa_key_t ecdsa_key = {
.curve = DTLS_ECDH_CURVE_SECP256R1,
.priv_key = ecdsa_priv_key,
.pub_key_x = ecdsa_pub_key_x,
.pub_key_y = ecdsa_pub_key_y
};
*result = &ecdsa_key;
return 0;
}
static int verify_ecdsa_key(struct dtls_context_t *ctx,
const session_t *session,
const unsigned char *other_pub_x,
const unsigned char *other_pub_y,
size_t key_size)
{
return 0;
}
#endif /* DTLS_ECC */
static void print_data(const unsigned char *packet, int length)
{
int n = 0;
while (length--) {
if (n % 16 == 0)
printf("%X: ", n);
printf("%X ", *packet++);
n++;
if (n % 8 == 0) {
if (n % 16 == 0)
printf("\n");
else
printf(" ");
}
}
printf("\n");
}
static coap_list_t *new_option_node(unsigned short key,
unsigned int length,
unsigned char *data)
{
coap_list_t *node;
node = coap_malloc(sizeof(coap_list_t) + sizeof(coap_option) + length);
if (node) {
coap_option *option = (coap_option *)(node->data);
COAP_OPTION_KEY(*option) = key;
COAP_OPTION_LENGTH(*option) = length;
memcpy(COAP_OPTION_DATA(*option), data, length);
} else {
coap_log(LOG_DEBUG, "new_option_node: malloc\n");
}
return node;
}
static int coap_insert(coap_list_t **head, coap_list_t *node)
{
if (!node) {
coap_log(LOG_WARNING, "cannot create option Proxy-Uri\n");
} else {
LL_APPEND((*head), node);
}
return node != NULL;
}
static int coap_delete(coap_list_t *node)
{
if (node) {
coap_free(node);
}
return 1;
}
static void coap_delete_list(coap_list_t *queue)
{
coap_list_t *elt, *tmp;
if (!queue)
return;
LL_FOREACH_SAFE(queue, elt, tmp) {
coap_delete(elt);
}
}
static coap_list_t *parse_uri(const char *arg)
{
coap_uri_t uri;
coap_list_t *opts = NULL;
#define BUFSIZE 40
unsigned char _buf[BUFSIZE];
unsigned char *buf = _buf;
size_t buflen;
int res;
coap_split_uri((unsigned char *)arg, strlen(arg), &uri );
if (uri.path.length) {
buflen = BUFSIZE;
res = coap_split_path(uri.path.s, uri.path.length,
buf, &buflen);
while (res--) {
coap_insert(&opts,
new_option_node(COAP_OPTION_URI_PATH,
COAP_OPT_LENGTH(buf),
COAP_OPT_VALUE(buf)));
buf += COAP_OPT_SIZE(buf);
}
}
if (uri.query.length) {
buflen = BUFSIZE;
buf = _buf;
res = coap_split_query(uri.query.s, uri.query.length,
buf, &buflen);
while (res--) {
coap_insert(&opts,
new_option_node(COAP_OPTION_URI_QUERY,
COAP_OPT_LENGTH(buf),
COAP_OPT_VALUE(buf)));
buf += COAP_OPT_SIZE(buf);
}
}
return opts;
}
static coap_list_t *clone_option(coap_list_t *item)
{
coap_list_t *node;
coap_option *option = (coap_option *)(item->data);
node = coap_malloc(sizeof(coap_list_t) + sizeof(coap_option) +
option->length);
if (node) {
memcpy(node->data, option,
sizeof(coap_option) + option->length);
return node;
} else
return NULL;
}
static char *create_uri(char *uri, int len, const char *target,
struct client_data *user_data)
{
snprintf(uri, len, "coap://%s%s%s/%s",
family == AF_INET6 ? "[" : "",
target,
family == AF_INET6 ? "]" : "",
data[user_data->index].buf);
if (debug)
print_data(uri, data[user_data->index].len);
return uri;
}
static coap_pdu_t *create_pdu(struct client_data *user_data)
{
coap_pdu_t *pdu;
coap_list_t *opts;
coap_list_t *elt, *tmp;
#define MAX_URI 256
char uri_buf[MAX_URI], *uri;
const unsigned char *send_data = NULL;
int send_data_len = 0;
uri = create_uri(uri_buf, MAX_URI, target, user_data);
opts = parse_uri(uri);
LL_FOREACH_SAFE(optlist, elt, tmp) {
coap_insert(&opts,
clone_option(elt));
}
if (data[user_data->index].data) {
send_data = data[user_data->index].data;
send_data_len = data[user_data->index].data_len;
if (send_data[send_data_len] == '\0')
send_data_len--; /* skip the null at the end */
}
pdu = coap_new_request(user_data->coap_ctx,
data[user_data->index].coap_method,
&opts,
send_data, send_data_len,
data[user_data->index].message_type);
if (pdu) {
if (data[user_data->index].check_mid)
data[user_data->index].expected_mid = ntohs(pdu->hdr->id);
}
coap_delete_list(opts);
return pdu;
}
static void send_packets(struct client_data *user_data)
{
int ret;
coap_pdu_t *pdu;
coap_tid_t tid;
printf("%s: sending [%d] %d bytes\n",
data[user_data->index].description,
user_data->index, data[user_data->index].len);
test_context = user_data;
pdu = create_pdu(user_data);
if (!pdu) {
/* Failure */
quit = true;
user_data->fail = true;
printf("Cannot allocate pdu\n");
return;
}
method = data[user_data->index].coap_method;
if (coap_get_log_level() >= LOG_DEBUG) {
printf("sending CoAP request:\n");
coap_show_pdu(pdu);
}
if (pdu->hdr->type == COAP_MESSAGE_CON)
tid = coap_send_confirmed(user_data->coap_ctx,
user_data->coap_ctx->endpoint,
&user_data->coap_dst,
pdu);
else
tid = coap_send(user_data->coap_ctx,
user_data->coap_ctx->endpoint,
&user_data->coap_dst,
pdu);
if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID)
coap_delete_pdu(pdu);
set_coap_timeout(&max_wait, wait_seconds);
if (debug)
printf("timeout is set to %d seconds\n", wait_seconds);
}
static void try_send(struct dtls_context_t *ctx)
{
struct client_data *user_data =
(struct client_data *)dtls_get_app_data(ctx);
int ret;
coap_pdu_t *pdu;
coap_tid_t tid;
printf("%s: sending [%d] %d bytes\n",
data[user_data->index].description,
user_data->index, data[user_data->index].len);
test_context = user_data;
pdu = create_pdu(user_data);
if (!pdu) {
/* Failure */
quit = true;
user_data->fail = true;
printf("Cannot allocate pdu\n");
return;
}
method = data[user_data->index].coap_method;
if (coap_get_log_level() >= LOG_DEBUG) {
printf("sending CoAP request:\n");
coap_show_pdu(pdu);
}
if (pdu->hdr->type == COAP_MESSAGE_CON)
tid = coap_send_confirmed(user_data->coap_ctx,
user_data->coap_ctx->endpoint,
&user_data->coap_dst,
pdu);
else
tid = coap_send(user_data->coap_ctx,
user_data->coap_ctx->endpoint,
&user_data->coap_dst,
pdu);
if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID)
coap_delete_pdu(pdu);
set_coap_timeout(&max_wait, wait_seconds);
if (debug)
printf("timeout is set to %d seconds\n", wait_seconds);
}
static int dispatch_data(char *buf, ssize_t bytes_read,
coap_context_t *ctx, coap_address_t *src)
{
coap_hdr_t *pdu;
coap_queue_t *node;
pdu = (coap_hdr_t *)buf;
if ((size_t)bytes_read < sizeof(coap_hdr_t)) {
printf("coap_read: discarded invalid frame\n");
goto error_early;
}
if (pdu->version != COAP_DEFAULT_VERSION) {
printf("coap_read: unknown protocol version\n");
goto error_early;
}
node = coap_new_node();
if (!node)
goto error_early;
node->pdu = coap_pdu_init(0, 0, 0, bytes_read);
if (!node->pdu)
goto error;
coap_ticks(&node->t);
memcpy(&node->local_if, ctx->endpoint, sizeof(coap_endpoint_t));
memcpy(&node->remote, src, sizeof(coap_address_t));
if (!coap_pdu_parse((unsigned char *)buf, bytes_read, node->pdu)) {
printf("discard malformed PDU");
goto error;
}
coap_transaction_id(&node->remote, node->pdu, &node->id);
if (coap_get_log_level() >= LOG_DEBUG) {
unsigned char addr[INET6_ADDRSTRLEN+8];
if (coap_print_addr(src, addr, INET6_ADDRSTRLEN+8))
printf("** received %d bytes from %s:\n",
(int)bytes_read, addr);
coap_show_pdu(node->pdu);
}
coap_dispatch(ctx, node);
return 0;
error:
coap_delete_node(node);
error_early:
return -1;
}
static int read_from_peer(struct dtls_context_t *ctx,
session_t *session,
uint8 *read_data, size_t read_len)
{
struct client_data *user_data =
(struct client_data *)dtls_get_app_data(ctx);
coap_address_t addr;
printf("%s: read [%u] from peer %zu bytes\n",
data[user_data->index].description, user_data->index, read_len);
memcpy(&(addr.addr), &(session->addr), session->size);
addr.size = session->size;
/* Process the received CoAP packet */
if (dispatch_data(read_data, read_len, user_data->coap_ctx,
&addr) < 0) {
printf("Cannot parse received CoAP packet.\n");
quit = true;
user_data->fail = true;
return 0;
}
if (debug)
print_data(read_data, read_len);
if (!data[user_data->index + 1].buf) {
/* last entry, just bail out */
quit = true;
return 0;
}
if (user_data->index == renegotiate) {
printf("Starting to renegotiate keys\n");
dtls_renegotiate(ctx, session);
return 1;
}
try_send(ctx);
return 0;
}
static inline void sleep_ms(int ms)
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = ms * 1000;
select(1, NULL, NULL, NULL, &tv);
}
static int send_to_peer(struct dtls_context_t *ctx,
session_t *session,
uint8 *data, size_t len)
{
struct client_data *user_data =
(struct client_data *)dtls_get_app_data(ctx);
/* The Qemu uart driver can loose chars if sent too fast.
* So before sending more data, sleep a while.
*/
sleep_ms(200);