-
Notifications
You must be signed in to change notification settings - Fork 420
/
client.c
1862 lines (1628 loc) · 54.5 KB
/
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
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* coap-client -- simple CoAP client
*
* Copyright (C) 2010--2019 Olaf Bergmann <bergmann@tzi.org> and others
*
* This file is part of the CoAP library libcoap. Please see README for terms of
* use.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#include "getopt.c"
#if !defined(S_ISDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
static char* strndup(const char* s1, size_t n)
{
char* copy = (char*)malloc(n + 1);
if (copy) {
memcpy(copy, s1, n);
copy[n] = 0;
}
return copy;
};
#else
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include <coap2/coap.h>
#define MAX_USER 128 /* Maximum length of a user name (i.e., PSK
* identity) in bytes. */
#define MAX_KEY 64 /* Maximum length of a key (i.e., PSK) in bytes. */
int flags = 0;
static unsigned char _token_data[8];
coap_binary_t the_token = { 0, _token_data };
#define FLAGS_BLOCK 0x01
static coap_optlist_t *optlist = NULL;
/* Request URI.
* TODO: associate the resources with transaction id and make it expireable */
static coap_uri_t uri;
static coap_string_t proxy = { 0, NULL };
static uint16_t proxy_port = COAP_DEFAULT_PORT;
static unsigned int ping_seconds = 0;
/* reading is done when this flag is set */
static int ready = 0;
/* processing a block response when this flag is set */
static int doing_getting_block = 0;
static coap_string_t output_file = { 0, NULL }; /* output file name */
static FILE *file = NULL; /* output file stream */
static coap_string_t payload = { 0, NULL }; /* optional payload to send */
static int reliable = 0;
unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */
static char *cert_file = NULL; /* certificate and optional private key in PEM,
or PKCS11 URI*/
static char *key_file = NULL; /* private key in PEM, DER or PKCS11 URI */
static char *pkcs11_pin = NULL; /* PKCS11 pin to unlock access to token */
static char *ca_file = NULL; /* CA for cert_file - for cert checking in PEM,
DER or PKCS11 URI */
static char *root_ca_file = NULL; /* List of trusted Root CAs in PEM */
typedef struct ih_def_t {
char* hint_match;
coap_bin_const_t *new_identity;
coap_bin_const_t *new_key;
} ih_def_t;
typedef struct valid_ihs_t {
size_t count;
ih_def_t *ih_list;
} valid_ihs_t;
static valid_ihs_t valid_ihs = {0, NULL};
typedef unsigned char method_t;
method_t method = 1; /* the method we are using in our requests */
coap_block_t block = { .num = 0, .m = 0, .szx = 6 };
uint16_t last_block1_tid = 0;
unsigned int wait_seconds = 90; /* default timeout in seconds */
unsigned int wait_ms = 0;
int wait_ms_reset = 0;
int obs_started = 0;
unsigned int obs_seconds = 30; /* default observe time */
unsigned int obs_ms = 0; /* timeout for current subscription */
int obs_ms_reset = 0;
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifdef __GNUC__
#define UNUSED_PARAM __attribute__ ((unused))
#else /* not a GCC */
#define UNUSED_PARAM
#endif /* GCC */
static int quit = 0;
/* SIGINT handler: set quit to 1 for graceful termination */
static void
handle_sigint(int signum UNUSED_PARAM) {
quit = 1;
}
static int
append_to_output(const uint8_t *data, size_t len) {
size_t written;
if (!file) {
if (!output_file.s || (output_file.length && output_file.s[0] == '-'))
file = stdout;
else {
if (!(file = fopen((char *)output_file.s, "w"))) {
perror("fopen");
return -1;
}
}
}
do {
written = fwrite(data, 1, len, file);
len -= written;
data += written;
} while ( written && len );
fflush(file);
return 0;
}
static void
close_output(void) {
if (file) {
/* add a newline before closing if no option '-o' was specified */
if (!output_file.s)
fwrite("\n", 1, 1, file);
fflush(file);
fclose(file);
}
}
static coap_pdu_t *
coap_new_request(coap_context_t *ctx,
coap_session_t *session,
method_t m,
coap_optlist_t **options,
unsigned char *data,
size_t length) {
coap_pdu_t *pdu;
(void)ctx;
if (!(pdu = coap_new_pdu(session)))
return NULL;
pdu->type = msgtype;
pdu->tid = coap_new_message_id(session);
pdu->code = m;
if ( !coap_add_token(pdu, the_token.length, the_token.s)) {
coap_log(LOG_DEBUG, "cannot add token to request\n");
}
if (options)
coap_add_optlist_pdu(pdu, options);
if (length) {
if ((flags & FLAGS_BLOCK) == 0)
coap_add_data(pdu, length, data);
else {
unsigned char buf[4];
coap_add_option(pdu,
COAP_OPTION_SIZE1,
coap_encode_var_safe8(buf, sizeof(buf), length),
buf);
coap_add_block(pdu, length, data, block.num, block.szx);
}
}
return pdu;
}
static coap_tid_t
clear_obs(coap_context_t *ctx, coap_session_t *session) {
coap_pdu_t *pdu;
coap_optlist_t *option;
coap_tid_t tid = COAP_INVALID_TID;
unsigned char buf[2];
(void)ctx;
/* create bare PDU w/o any option */
pdu = coap_pdu_init(msgtype,
COAP_REQUEST_GET,
coap_new_message_id(session),
coap_session_max_pdu_size(session));
if (!pdu) {
return tid;
}
if (!coap_add_token(pdu, the_token.length, the_token.s)) {
coap_log(LOG_CRIT, "cannot add token\n");
goto error;
}
for (option = optlist; option; option = option->next ) {
if (option->number == COAP_OPTION_URI_HOST) {
if (!coap_add_option(pdu, option->number, option->length,
option->data)) {
goto error;
}
break;
}
}
if (!coap_add_option(pdu,
COAP_OPTION_OBSERVE,
coap_encode_var_safe(buf, sizeof(buf), COAP_OBSERVE_CANCEL),
buf)) {
coap_log(LOG_CRIT, "cannot add option Observe: %u\n", COAP_OBSERVE_CANCEL);
goto error;
}
for (option = optlist; option; option = option->next ) {
switch (option->number) {
case COAP_OPTION_URI_PORT : /* 7 */
case COAP_OPTION_URI_PATH : /* 11 */
case COAP_OPTION_URI_QUERY : /* 15 */
case COAP_OPTION_HOP_LIMIT : /* 16 */
if (!coap_add_option(pdu, option->number, option->length,
option->data)) {
goto error;
}
break;
default:
;
}
}
if (flags & FLAGS_BLOCK) {
block.num = 0;
block.m = 0;
coap_add_option(pdu,
COAP_OPTION_BLOCK2,
coap_encode_var_safe(buf, sizeof(buf), (block.num << 4 | block.m << 3 | block.szx)),
buf);
}
if (coap_get_log_level() < LOG_DEBUG)
coap_show_pdu(LOG_INFO, pdu);
tid = coap_send(session, pdu);
if (tid == COAP_INVALID_TID)
coap_log(LOG_DEBUG, "clear_obs: error sending new request\n");
return tid;
error:
coap_delete_pdu(pdu);
return tid;
}
static int
resolve_address(const coap_str_const_t *server, struct sockaddr *dst) {
struct addrinfo *res, *ainfo;
struct addrinfo hints;
static char addrstr[256];
int error, len=-1;
memset(addrstr, 0, sizeof(addrstr));
if (server->length)
memcpy(addrstr, server->s, server->length);
else
memcpy(addrstr, "localhost", 9);
memset ((char *)&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_UNSPEC;
error = getaddrinfo(addrstr, NULL, &hints, &res);
if (error != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
return error;
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
switch (ainfo->ai_family) {
case AF_INET6:
case AF_INET:
len = (int)ainfo->ai_addrlen;
memcpy(dst, ainfo->ai_addr, len);
goto finish;
default:
;
}
}
finish:
freeaddrinfo(res);
return len;
}
#define HANDLE_BLOCK1(Pdu) \
((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) && \
((flags & FLAGS_BLOCK) == 0) && \
((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) || \
(Pdu)->hdr->code == COAP_RESPONSE_CODE(204)))
static inline int
check_token(coap_pdu_t *received) {
return received->token_length == the_token.length &&
memcmp(received->token, the_token.s, the_token.length) == 0;
}
static int
event_handler(coap_context_t *ctx UNUSED_PARAM,
coap_event_t event,
struct coap_session_t *session UNUSED_PARAM) {
switch(event) {
case COAP_EVENT_DTLS_CLOSED:
case COAP_EVENT_TCP_CLOSED:
case COAP_EVENT_SESSION_CLOSED:
quit = 1;
break;
default:
break;
}
return 0;
}
static void
nack_handler(coap_context_t *context UNUSED_PARAM,
coap_session_t *session UNUSED_PARAM,
coap_pdu_t *sent UNUSED_PARAM,
coap_nack_reason_t reason,
const coap_tid_t id UNUSED_PARAM) {
switch(reason) {
case COAP_NACK_TOO_MANY_RETRIES:
case COAP_NACK_NOT_DELIVERABLE:
case COAP_NACK_RST:
case COAP_NACK_TLS_FAILED:
quit = 1;
break;
case COAP_NACK_ICMP_ISSUE:
default:
break;
}
return;
}
static void
message_handler(struct coap_context_t *ctx,
coap_session_t *session,
coap_pdu_t *sent,
coap_pdu_t *received,
const coap_tid_t id UNUSED_PARAM) {
coap_pdu_t *pdu = NULL;
coap_opt_t *block_opt;
coap_opt_iterator_t opt_iter;
unsigned char buf[4];
coap_optlist_t *option;
size_t len;
unsigned char *databuf;
coap_tid_t tid;
coap_log(LOG_DEBUG, "** process incoming %d.%02d response:\n",
(received->code >> 5), received->code & 0x1F);
if (coap_get_log_level() < LOG_DEBUG)
coap_show_pdu(LOG_INFO, received);
/* check if this is a response to our original request */
if (!check_token(received)) {
/* drop if this was just some message, or send RST in case of notification */
if (!sent && (received->type == COAP_MESSAGE_CON ||
received->type == COAP_MESSAGE_NON))
coap_send_rst(session, received);
return;
}
if (received->type == COAP_MESSAGE_RST) {
coap_log(LOG_INFO, "got RST\n");
return;
}
/* output the received data, if any */
if (COAP_RESPONSE_CLASS(received->code) == 2) {
/* set obs timer if we have successfully subscribed a resource */
if (!obs_started && coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter)) {
coap_log(LOG_DEBUG,
"observation relationship established, set timeout to %d\n",
obs_seconds);
obs_started = 1;
obs_ms = obs_seconds * 1000;
obs_ms_reset = 1;
}
/* Got some data, check if block option is set. Behavior is undefined if
* both, Block1 and Block2 are present. */
block_opt = coap_check_option(received, COAP_OPTION_BLOCK2, &opt_iter);
if (block_opt) { /* handle Block2 */
uint16_t blktype = opt_iter.type;
/* TODO: check if we are looking at the correct block number */
if (coap_get_data(received, &len, &databuf))
append_to_output(databuf, len);
if (coap_opt_block_num(block_opt) == 0) {
/* See if observe is set in first response */
ready = coap_check_option(received,
COAP_OPTION_OBSERVE, &opt_iter) == NULL;
}
if(COAP_OPT_BLOCK_MORE(block_opt)) {
/* more bit is set */
coap_log(LOG_DEBUG, "found the M bit, block size is %u, block nr. %u\n",
COAP_OPT_BLOCK_SZX(block_opt),
coap_opt_block_num(block_opt));
/* create pdu with request for next block */
pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
if ( pdu ) {
/* add URI components from optlist in ascending order */
for (option = optlist; option; option = option->next ) {
switch (option->number) {
case COAP_OPTION_URI_HOST : /* 3 */
case COAP_OPTION_URI_PORT : /* 7 */
case COAP_OPTION_URI_PATH : /* 11 */
case COAP_OPTION_URI_QUERY : /* 15 */
case COAP_OPTION_HOP_LIMIT : /* 16 */
coap_add_option(pdu, option->number, option->length,
option->data);
break;
default:
; /* skip other options */
}
}
/* finally add updated block option from response, clear M bit */
/* blocknr = (blocknr & 0xfffffff7) + 0x10; */
coap_log(LOG_DEBUG, "query block %d\n",
(coap_opt_block_num(block_opt) + 1));
coap_add_option(pdu,
blktype,
coap_encode_var_safe(buf, sizeof(buf),
((coap_opt_block_num(block_opt) + 1) << 4) |
COAP_OPT_BLOCK_SZX(block_opt)), buf);
tid = coap_send(session, pdu);
if (tid == COAP_INVALID_TID) {
coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
} else {
wait_ms = wait_seconds * 1000;
wait_ms_reset = 1;
doing_getting_block = 1;
}
return;
}
}
/* Failure of some sort */
doing_getting_block = 0;
return;
} else { /* no Block2 option */
block_opt = coap_check_option(received, COAP_OPTION_BLOCK1, &opt_iter);
if (block_opt) { /* handle Block1 */
unsigned int szx = COAP_OPT_BLOCK_SZX(block_opt);
unsigned int num = coap_opt_block_num(block_opt);
coap_log(LOG_DEBUG,
"found Block1 option, block size is %u, block nr. %u\n",
szx, num);
if (szx != block.szx) {
unsigned int bytes_sent = ((block.num + 1) << (block.szx + 4));
if (bytes_sent % (1 << (szx + 4)) == 0) {
/* Recompute the block number of the previous packet given the new block size */
num = block.num = (bytes_sent >> (szx + 4)) - 1;
block.szx = szx;
coap_log(LOG_DEBUG,
"new Block1 size is %u, block number %u completed\n",
(1 << (block.szx + 4)), block.num);
} else {
coap_log(LOG_DEBUG, "ignoring request to increase Block1 size, "
"next block is not aligned on requested block size boundary. "
"(%u x %u mod %u = %u != 0)\n",
block.num + 1, (1 << (block.szx + 4)), (1 << (szx + 4)),
bytes_sent % (1 << (szx + 4)));
}
}
if (last_block1_tid == received->tid) {
/*
* Duplicate BLOCK1 ACK
*
* RFCs not clear here, but on a lossy connection, there could
* be multiple BLOCK1 ACKs, causing the client to retransmit the
* same block multiple times.
*
* Once a block has been ACKd, there is no need to retransmit it.
*/
return;
}
last_block1_tid = received->tid;
if (payload.length <= (block.num+1) * (1 << (block.szx + 4))) {
coap_log(LOG_DEBUG, "upload ready\n");
if (coap_get_data(received, &len, &databuf))
append_to_output(databuf, len);
ready = 1;
return;
}
/* create pdu with request for next block */
pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
if (pdu) {
/* add URI components from optlist */
for (option = optlist; option; option = option->next ) {
switch (option->number) {
case COAP_OPTION_URI_HOST : /* 3 */
case COAP_OPTION_URI_PORT : /* 7 */
case COAP_OPTION_URI_PATH : /* 11 */
case COAP_OPTION_CONTENT_FORMAT : /* 12 */
case COAP_OPTION_URI_QUERY : /* 15 */
case COAP_OPTION_HOP_LIMIT : /* 16 */
coap_add_option(pdu, option->number, option->length,
option->data);
break;
default:
; /* skip other options */
}
}
/* finally add updated block option from response, clear M bit */
/* blocknr = (blocknr & 0xfffffff7) + 0x10; */
block.num = num + 1;
block.m = ((block.num+1) * (1 << (block.szx + 4)) < payload.length);
coap_log(LOG_DEBUG, "send block %d\n", block.num);
coap_add_option(pdu,
COAP_OPTION_BLOCK1,
coap_encode_var_safe(buf, sizeof(buf),
(block.num << 4) | (block.m << 3) | block.szx), buf);
coap_add_option(pdu,
COAP_OPTION_SIZE1,
coap_encode_var_safe8(buf, sizeof(buf), payload.length),
buf);
coap_add_block(pdu,
payload.length,
payload.s,
block.num,
block.szx);
if (coap_get_log_level() < LOG_DEBUG)
coap_show_pdu(LOG_INFO, pdu);
tid = coap_send(session, pdu);
if (tid == COAP_INVALID_TID) {
coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
} else {
wait_ms = wait_seconds * 1000;
wait_ms_reset = 1;
}
return;
}
} else {
/* There is no block option set, just read the data and we are done. */
if (coap_get_data(received, &len, &databuf))
append_to_output(databuf, len);
}
}
} else { /* no 2.05 */
/* check if an error was signaled and output payload if so */
if (COAP_RESPONSE_CLASS(received->code) >= 4) {
fprintf(stderr, "%d.%02d",
(received->code >> 5), received->code & 0x1F);
if (coap_get_data(received, &len, &databuf)) {
fprintf(stderr, " ");
while(len--)
fprintf(stderr, "%c", *databuf++);
}
fprintf(stderr, "\n");
}
}
/* any pdu that has been created in this function must be sent by now */
assert(pdu == NULL);
/* our job is done, we can exit at any time */
ready = coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter) == NULL;
}
static void
usage( const char *program, const char *version) {
const char *p;
char buffer[64];
p = strrchr( program, '/' );
if ( p )
program = ++p;
fprintf( stderr, "%s v%s -- a small CoAP implementation\n"
"Copyright (C) 2010-2019 Olaf Bergmann <bergmann@tzi.org> and others\n\n"
"%s\n\n"
"Usage: %s [-a addr] [-b [num,]size] [-e text] [-f file] [-l loss]\n"
"\t\t[-m method] [-o file] [-p port] [-r] [-s duration] [-t type]\n"
"\t\t[-v num] [-A type] [-B seconds] [-H hoplimit] [-K interval] [-N]\n"
"\t\t[-O num,text] [-P addr[:port]] [-T token] [-U]\n"
"\t\t[[-h match_hint_file] [-k key] [-u user]]\n"
"\t\t[[-c certfile] [-j keyfile] [-C cafile] [-J pkcs11_pin]\n"
"\t\t[-R root_cafile] [-S match_pki_sni_file]] URI\n"
"\tURI can be an absolute URI or a URI prefixed with scheme and host\n\n"
"General Options\n"
"\t-a addr\t\tThe local interface address to use\n"
"\t-b [num,]size\tBlock size to be used in GET/PUT/POST requests\n"
"\t \t\t(value must be a multiple of 16 not larger than 1024)\n"
"\t \t\tIf num is present, the request chain will start at\n"
"\t \t\tblock num\n"
"\t-e text\t\tInclude text as payload (use percent-encoding for\n"
"\t \t\tnon-ASCII characters)\n"
"\t-f file\t\tFile to send with PUT/POST (use '-' for STDIN)\n"
"\t-l list\t\tFail to send some datagrams specified by a comma\n"
"\t \t\tseparated list of numbers or number ranges\n"
"\t \t\t(for debugging only)\n"
"\t-l loss%%\tRandomly fail to send datagrams with the specified\n"
"\t \t\tprobability - 100%% all datagrams, 0%% no datagrams\n"
"\t-m method\tRequest method (get|put|post|delete|fetch|patch|ipatch),\n"
"\t \t\tdefault is 'get'\n"
"\t-o file\t\tOutput received data to this file (use '-' for STDOUT)\n"
"\t-p port\t\tListen on specified port\n"
"\t-r \t\tUse reliable protocol (TCP or TLS); requires TCP support\n"
"\t-s duration\tSubscribe to / Observe resource for given duration\n"
"\t \t\tin seconds\n"
"\t-t type\t\tContent format for given resource for PUT/POST\n"
"\t-v num \t\tVerbosity level (default 3, maximum is 9). Above 7,\n"
"\t \t\tthere is increased verbosity in GnuTLS logging\n"
"\t-A type\t\tAccepted media type\n"
"\t-B seconds\tBreak operation after waiting given seconds\n"
"\t \t\t(default is %d)\n"
"\t-H hoplimit\tSet the Hop Limit count to hoplimit for proxies. Must\n"
"\t \t\thave a value between 1 and 255 inclusive.\n"
"\t \t\tDefault is '16'\n"
"\t-K interval\tsend a ping after interval seconds of inactivity\n"
"\t-N \t\tSend NON-confirmable message\n"
"\t-O num,text\tAdd option num with contents text to request. If the\n"
"\t \t\ttext begins with 0x, then the hex text is converted to\n"
"\t \t\tbinary data\n"
"\t-P addr[:port]\tUse proxy (automatically adds Proxy-Uri option to\n"
"\t \t\trequest)\n"
"\t-T token\tInclude specified token\n"
"\t-U \t\tNever include Uri-Host or Uri-Port options\n"
,program, version, coap_string_tls_version(buffer, sizeof(buffer))
,program, wait_seconds);
fprintf( stderr,
"PSK Options (if supported by underlying (D)TLS library)\n"
"\t-h match_hint_file\n"
"\t \t\tThis is a file that contains one or more lines of Identity\n"
"\t \t\tHints to match for new user and new pre-shared key\n"
"\t \t\t(PSK) (comma separated) to be used. E.g., per line\n"
"\t \t\t hint_to_match,new_user,new_key\n"
"\t \t\tNote: -k and -u still need to be defined for the default\n"
"\t \t\tcase\n"
"\t-k key \t\tPre-shared key for the specified user\n"
"\t-u user\t\tUser identity for pre-shared key mode\n"
"PKI Options (if supported by underlying (D)TLS library)\n"
"\tNote: If any one of '-c certfile', '-j keyfile' or '-C cafile' is in\n"
"\tPKCS11 URI naming format (pkcs11: prefix), then any remaining non\n"
"\tPKCS11 URI file definitions have to be in DER, not PEM, format.\n"
"\tOtherwise all of '-c certfile', '-j keyfile' or '-C cafile' are in\n"
"\tPEM format.\n\n"
"\t-c certfile\tPEM file or PKCS11 URI for the Certificate. The private\n"
"\t \t\tkey can be in the PEM file, or use the same PKCS11 URI.\n"
"\t \t\tIf not, the private ney is defined by '-j keyfile'\n"
"\t-j keyfile\tPEM file or PKCS11 URI for the private key for the\n"
"\t \t\tnertificate in '-c certfile' if the parameter is different\n"
"\t \t\tfrom certfile in '-c certfile'\n"
"\t-C cafile\tPEM file or PKCS11 URI for the CA Certificate that was\n"
"\t \t\tused to sign the certfile. This will trigger\n"
"\t \t\tthe validation of the server certificate. If certfile is\n"
"\t \t\tself-signed (as defined by '-c certfile'), then you need\n"
"\t \t\tto have on the command line the same filename for both\n"
"\t \t\tthe certfile and cafile (as in '-c certfile -C certfile')\n"
"\t \t\tto trigger validation\n"
"\t-J pkcs11_pin\tThe user pin to unlock access to the PKCS11 token\n"
"\t-R root_cafile\tPEM file containing the set of trusted root CAs that\n"
"\t \t\tare to be used to validate the server certificate.\n"
"\t \t\tThe '-C cafile' does not have to be in this list and is\n"
"\t \t\t'trusted' for the verification.\n"
"\t \t\tAlternatively, this can point to a directory containing\n"
"\t \t\ta set of CA PEM files\n"
);
fprintf( stderr,
"Examples:\n"
"\tcoap-client -m get coap://[::1]/\n"
"\tcoap-client -m get coap://[::1]/.well-known/core\n"
"\tcoap-client -m get coap+tcp://[::1]/.well-known/core\n"
"\tcoap-client -m get coaps://[::1]/.well-known/core\n"
"\tcoap-client -m get coaps+tcp://[::1]/.well-known/core\n"
"\tcoap-client -m get -T cafe coap://[::1]/time\n"
"\techo -n 1000 | coap-client -m put -T cafe coap://[::1]/time -f -\n"
);
}
typedef struct {
unsigned char code;
const char *media_type;
} content_type_t;
static void
cmdline_content_type(char *arg, uint16_t key) {
static content_type_t content_types[] = {
{ 0, "plain" },
{ 0, "text/plain" },
{ 40, "link" },
{ 40, "link-format" },
{ 40, "application/link-format" },
{ 41, "xml" },
{ 41, "application/xml" },
{ 42, "binary" },
{ 42, "octet-stream" },
{ 42, "application/octet-stream" },
{ 47, "exi" },
{ 47, "application/exi" },
{ 50, "json" },
{ 50, "application/json" },
{ 60, "cbor" },
{ 60, "application/cbor" },
{ 255, NULL }
};
coap_optlist_t *node;
unsigned char i;
uint16_t value;
uint8_t buf[2];
if (isdigit(*arg)) {
value = atoi(arg);
} else {
for (i=0;
content_types[i].media_type &&
strncmp(arg, content_types[i].media_type, strlen(arg)) != 0 ;
++i)
;
if (content_types[i].media_type) {
value = content_types[i].code;
} else {
coap_log(LOG_WARNING, "W: unknown content-format '%s'\n",arg);
return;
}
}
node = coap_new_optlist(key, coap_encode_var_safe(buf, sizeof(buf), value), buf);
if (node) {
coap_insert_optlist(&optlist, node);
}
}
static int
cmdline_hop_limit(char *arg) {
coap_optlist_t *node;
uint32_t value;
uint8_t buf[4];
value = strtol(arg, NULL, 10);
if (value < 1 || value > 255) {
return 0;
}
node = coap_new_optlist(COAP_OPTION_HOP_LIMIT, coap_encode_var_safe(buf, sizeof(buf), value), buf);
if (node) {
coap_insert_optlist(&optlist, node);
}
return 1;
}
static uint16_t
get_default_port(const coap_uri_t *u) {
return coap_uri_scheme_is_secure(u) ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT;
}
/**
* Sets global URI options according to the URI passed as @p arg.
* This function returns 0 on success or -1 on error.
*
* @param arg The URI string.
* @param create_uri_opts Flags that indicate whether Uri-Host and
* Uri-Port should be suppressed.
* @return 0 on success, -1 otherwise
*/
static int
cmdline_uri(char *arg, int create_uri_opts) {
unsigned char portbuf[2];
#define BUFSIZE 100
unsigned char _buf[BUFSIZE];
unsigned char *buf = _buf;
size_t buflen;
int res;
if (proxy.length) { /* create Proxy-Uri from argument */
size_t len = strlen(arg);
while (len > 270) {
coap_insert_optlist(&optlist,
coap_new_optlist(COAP_OPTION_PROXY_URI,
270,
(unsigned char *)arg));
len -= 270;
arg += 270;
}
coap_insert_optlist(&optlist,
coap_new_optlist(COAP_OPTION_PROXY_URI,
len,
(unsigned char *)arg));
} else { /* split arg into Uri-* options */
if (coap_split_uri((unsigned char *)arg, strlen(arg), &uri) < 0) {
coap_log(LOG_ERR, "invalid CoAP URI\n");
return -1;
}
if (uri.scheme==COAP_URI_SCHEME_COAPS && !reliable && !coap_dtls_is_supported()) {
coap_log(LOG_EMERG,
"coaps URI scheme not supported in this version of libcoap\n");
return -1;
}
if ((uri.scheme==COAP_URI_SCHEME_COAPS_TCP || (uri.scheme==COAP_URI_SCHEME_COAPS && reliable)) && !coap_tls_is_supported()) {
coap_log(LOG_EMERG,
"coaps+tcp URI scheme not supported in this version of libcoap\n");
return -1;
}
if (uri.scheme==COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) {
/* coaps+tcp caught above */
coap_log(LOG_EMERG,
"coap+tcp URI scheme not supported in this version of libcoap\n");
return -1;
}
if (uri.port != get_default_port(&uri) && create_uri_opts) {
coap_insert_optlist(&optlist,
coap_new_optlist(COAP_OPTION_URI_PORT,
coap_encode_var_safe(portbuf, sizeof(portbuf),
(uri.port & 0xffff)),
portbuf));
}
if (uri.path.length) {
buflen = BUFSIZE;
if (uri.path.length > BUFSIZE)
coap_log(LOG_WARNING, "URI path will be truncated (max buffer %d)\n", BUFSIZE);
res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
while (res--) {
coap_insert_optlist(&optlist,
coap_new_optlist(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_optlist(&optlist,
coap_new_optlist(COAP_OPTION_URI_QUERY,
coap_opt_length(buf),
coap_opt_value(buf)));
buf += coap_opt_size(buf);
}
}
}
return 0;
}
static int
cmdline_blocksize(char *arg) {
uint16_t size;
again:
size = 0;
while(*arg && *arg != ',')
size = size * 10 + (*arg++ - '0');
if (*arg == ',') {
arg++;
block.num = size;
goto again;
}
if (size)
block.szx = (coap_fls(size >> 4) - 1) & 0x07;
flags |= FLAGS_BLOCK;
return 1;
}
/* Called after processing the options from the commandline to set
* Block1 or Block2 depending on method. */
static void
set_blocksize(void) {
static unsigned char buf[4]; /* hack: temporarily take encoded bytes */
uint16_t opt;
unsigned int opt_length;
if (method != COAP_REQUEST_DELETE) {
opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1;
block.m = (opt == COAP_OPTION_BLOCK1) &&
((1ull << (block.szx + 4)) < payload.length);
opt_length = coap_encode_var_safe(buf, sizeof(buf),
(block.num << 4 | block.m << 3 | block.szx));
coap_insert_optlist(&optlist, coap_new_optlist(opt, opt_length, buf));
}
}
static void
cmdline_subscribe(char *arg) {
obs_seconds = atoi(arg);
coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_OBSERVE,
COAP_OBSERVE_ESTABLISH, NULL));
}
static int
cmdline_proxy(char *arg) {
char *proxy_port_str = strrchr((const char *)arg, ':'); /* explicit port ? */
if (proxy_port_str) {
char *ipv6_delimiter = strrchr((const char *)arg, ']');
if (!ipv6_delimiter) {
if (proxy_port_str == strchr((const char *)arg, ':')) {
/* host:port format - host not in ipv6 hexadecimal string format */
*proxy_port_str++ = '\0'; /* split */
proxy_port = atoi(proxy_port_str);
}
} else {
arg = strchr((const char *)arg, '[');
if (!arg) return 0;
arg++;
*ipv6_delimiter = '\0'; /* split */
if (ipv6_delimiter + 1 == proxy_port_str++) {
/* [ipv6 address]:port */
proxy_port = atoi(proxy_port_str);
}
}
}
proxy.length = strlen(arg);
if ( (proxy.s = coap_malloc(proxy.length + 1)) == NULL) {
proxy.length = 0;
return 0;