-
Notifications
You must be signed in to change notification settings - Fork 9
/
net.c
1292 lines (1064 loc) · 34.1 KB
/
net.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
/* net.c -- CoAP network interface
*
* Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "config.h"
#include <ctype.h>
#include <stdio.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#elif HAVE_SYS_UNISTD_H
#include <sys/unistd.h>
#endif
#include <sys/types.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "debug.h"
#include "mem.h"
#include "str.h"
#include "async.h"
#include "resource.h"
#include "option.h"
#include "encode.h"
#include "net.h"
#ifndef WITH_CONTIKI
time_t clock_offset;
static inline coap_queue_t *
coap_malloc_node() {
return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
}
static inline void
coap_free_node(coap_queue_t *node) {
coap_free(node);
}
#else /* WITH_CONTIKI */
# ifndef DEBUG
# define DEBUG DEBUG_PRINT
# endif /* DEBUG */
#include "memb.h"
#include "net/uip-debug.h"
clock_time_t clock_offset;
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
void coap_resources_init();
void coap_pdu_resources_init();
unsigned char initialized = 0;
coap_context_t the_coap_context;
MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
PROCESS(coap_retransmit_process, "message retransmit process");
static inline coap_queue_t *
coap_malloc_node() {
return (coap_queue_t *)memb_alloc(&node_storage);
}
static inline void
coap_free_node(coap_queue_t *node) {
memb_free(&node_storage, node);
}
#endif /* WITH_CONTIKI */
int print_wellknown(coap_context_t *, unsigned char *, size_t *, coap_opt_t *);
void coap_handle_failed_notify(coap_context_t *, const coap_address_t *,
const str *);
int
coap_insert_node(coap_queue_t **queue, coap_queue_t *node,
int (*order)(coap_queue_t *, coap_queue_t *node) ) {
coap_queue_t *p, *q;
if ( !queue || !node )
return 0;
/* set queue head if empty */
if ( !*queue ) {
*queue = node;
return 1;
}
/* replace queue head if PDU's time is less than head's time */
q = *queue;
if ( order( node, q ) < 0) {
node->next = q;
*queue = node;
return 1;
}
/* search for right place to insert */
do {
p = q;
q = q->next;
} while ( q && order( node, q ) >= 0 );
/* insert new item */
node->next = q;
p->next = node;
return 1;
}
int
coap_delete_node(coap_queue_t *node) {
if ( !node )
return 0;
coap_delete_pdu(node->pdu);
coap_free_node(node);
return 1;
}
void
coap_delete_all(coap_queue_t *queue) {
if ( !queue )
return;
coap_delete_all( queue->next );
coap_delete_node( queue );
}
coap_queue_t *
coap_new_node() {
coap_queue_t *node;
node = coap_malloc_node();
if ( ! node ) {
#ifndef NDEBUG
coap_log(LOG_WARN, "coap_new_node: malloc");
#endif
return NULL;
}
memset(node, 0, sizeof *node );
return node;
}
coap_queue_t *
coap_peek_next( coap_context_t *context ) {
if ( !context || !context->sendqueue )
return NULL;
return context->sendqueue;
}
coap_queue_t *
coap_pop_next( coap_context_t *context ) {
coap_queue_t *next;
if ( !context || !context->sendqueue )
return NULL;
next = context->sendqueue;
context->sendqueue = context->sendqueue->next;
next->next = NULL;
return next;
}
#ifdef COAP_DEFAULT_WKC_HASHKEY
/** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
#define is_wkc(Key) \
(memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
#else
/* Implements a singleton to store a hash key for the .wellknown/core
* resources. */
int
is_wkc(coap_key_t k) {
static coap_key_t wkc;
static unsigned char _initialized = 0;
if (!_initialized) {
_initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN,
sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc);
}
return memcmp(k, wkc, sizeof(coap_key_t)) == 0;
}
#endif
coap_context_t *
coap_new_context(const coap_address_t *listen_addr) {
#ifndef WITH_CONTIKI
coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
int reuse = 1;
#else /* WITH_CONTIKI */
coap_context_t *c;
if (initialized)
return NULL;
#endif /* WITH_CONTIKI */
if (!listen_addr) {
coap_log(LOG_EMERG, "no listen address specified\n");
return NULL;
}
coap_clock_init();
prng_init((unsigned long)listen_addr ^ clock_offset);
#ifndef WITH_CONTIKI
if ( !c ) {
#ifndef NDEBUG
coap_log(LOG_EMERG, "coap_init: malloc:");
#endif
return NULL;
}
#else /* WITH_CONTIKI */
coap_resources_init();
coap_pdu_resources_init();
c = &the_coap_context;
initialized = 1;
#endif /* WITH_CONTIKI */
memset(c, 0, sizeof( coap_context_t ) );
/* initialize message id */
prng((unsigned char *)&c->message_id, sizeof(unsigned short));
/* register the critical options that we know */
coap_register_option(c, COAP_OPTION_IF_MATCH);
coap_register_option(c, COAP_OPTION_URI_HOST);
coap_register_option(c, COAP_OPTION_IF_NONE_MATCH);
coap_register_option(c, COAP_OPTION_URI_PORT);
coap_register_option(c, COAP_OPTION_URI_PATH);
coap_register_option(c, COAP_OPTION_URI_QUERY);
coap_register_option(c, COAP_OPTION_ACCEPT);
coap_register_option(c, COAP_OPTION_PROXY_URI);
coap_register_option(c, COAP_OPTION_PROXY_SCHEME);
#ifndef WITH_CONTIKI
c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
if ( c->sockfd < 0 ) {
#ifndef NDEBUG
coap_log(LOG_EMERG, "coap_new_context: socket");
#endif
goto onerror;
}
if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 ) {
#ifndef NDEBUG
coap_log(LOG_WARN, "setsockopt SO_REUSEADDR");
#endif
}
if (bind(c->sockfd, &listen_addr->addr.sa, listen_addr->size) < 0) {
#ifndef NDEBUG
coap_log(LOG_EMERG, "coap_new_context: bind");
#endif
goto onerror;
}
return c;
onerror:
if ( c->sockfd >= 0 )
close ( c->sockfd );
coap_free( c );
return NULL;
#else /* WITH_CONTIKI */
c->conn = udp_new(NULL, 0, NULL);
udp_bind(c->conn, listen_addr->port);
process_start(&coap_retransmit_process, (char *)c);
PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
#ifndef WITHOUT_OBSERVE
etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
#endif /* WITHOUT_OBSERVE */
/* the retransmit timer must be initialized to some large value */
etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
PROCESS_CONTEXT_END(&coap_retransmit_process);
return c;
#endif /* WITH_CONTIKI */
}
void
coap_free_context( coap_context_t *context ) {
#ifndef WITH_CONTIKI
coap_resource_t *res, *rtmp;
#endif /* WITH_CONTIKI */
if ( !context )
return;
coap_delete_all(context->recvqueue);
coap_delete_all(context->sendqueue);
#ifndef WITH_CONTIKI
HASH_ITER(hh, context->resources, res, rtmp) {
coap_delete_resource(context, res->key);
}
/* coap_delete_list(context->subscriptions); */
close( context->sockfd );
coap_free( context );
#else /* WITH_CONTIKI */
memset(&the_coap_context, 0, sizeof(coap_context_t));
initialized = 0;
#endif /* WITH_CONTIKI */
}
int
coap_option_check_critical(coap_context_t *ctx,
coap_pdu_t *pdu,
coap_opt_filter_t unknown) {
coap_opt_iterator_t opt_iter;
int ok = 1;
coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
while (coap_option_next(&opt_iter)) {
/* The following condition makes use of the fact that
* coap_option_getb() returns -1 if type exceeds the bit-vector
* filter. As the vector is supposed to be large enough to hold
* the largest known option, we know that everything beyond is
* bad.
*/
if (opt_iter.type & 0x01 &&
coap_option_getb(ctx->known_options, opt_iter.type) < 1) {
debug("unknown critical option %d\n", opt_iter.type);
ok = 0;
/* When opt_iter.type is beyond our known option range,
* coap_option_setb() will return -1 and we are safe to leave
* this loop. */
if (coap_option_setb(unknown, opt_iter.type) == -1)
break;
}
}
return ok;
}
void
coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
coap_tid_t *id) {
coap_key_t h;
memset(h, 0, sizeof(coap_key_t));
/* Compare the complete address structure in case of IPv4. For IPv6,
* we need to look at the transport address only. */
#ifndef WITH_CONTIKI
switch (peer->addr.sa.sa_family) {
case AF_INET:
coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h);
break;
case AF_INET6:
coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port,
sizeof(peer->addr.sin6.sin6_port), h);
coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr,
sizeof(peer->addr.sin6.sin6_addr), h);
break;
default:
return;
}
#else /* WITH_CONTIKI */
coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
#endif /* WITH_CONTIKI */
coap_hash((const unsigned char *)&pdu->hdr->id, sizeof(unsigned short), h);
*id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
}
coap_tid_t
coap_send_ack(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *request) {
coap_pdu_t *response;
coap_tid_t result = COAP_INVALID_TID;
if (request && request->hdr->type == COAP_MESSAGE_CON) {
response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id,
sizeof(coap_pdu_t));
if (response) {
result = coap_send(context, dst, response);
coap_delete_pdu(response);
}
}
return result;
}
#ifndef WITH_CONTIKI
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t
coap_send_impl(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *pdu) {
ssize_t bytes_written;
coap_tid_t id = COAP_INVALID_TID;
if ( !context || !dst || !pdu )
return id;
bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
&dst->addr.sa, dst->size);
if (bytes_written >= 0) {
coap_transaction_id(dst, pdu, &id);
} else {
coap_log(LOG_CRIT, "coap_send: sendto");
}
return id;
}
#else /* WITH_CONTIKI */
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t
coap_send_impl(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *pdu) {
coap_tid_t id = COAP_INVALID_TID;
if ( !context || !dst || !pdu )
return id;
/* FIXME: is there a way to check if send was successful? */
uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length,
&dst->addr, dst->port);
coap_transaction_id(dst, pdu, &id);
return id;
}
#endif /* WITH_CONTIKI */
coap_tid_t
coap_send(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *pdu) {
return coap_send_impl(context, dst, pdu);
}
coap_tid_t
coap_send_error(coap_context_t *context,
coap_pdu_t *request,
const coap_address_t *dst,
unsigned char code,
coap_opt_filter_t opts) {
coap_pdu_t *response;
coap_tid_t result = COAP_INVALID_TID;
assert(request);
assert(dst);
response = coap_new_error_response(request, code, opts);
if (response) {
result = coap_send(context, dst, response);
coap_delete_pdu(response);
}
return result;
}
coap_tid_t
coap_send_message_type(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *request,
unsigned char type) {
coap_pdu_t *response;
coap_tid_t result = COAP_INVALID_TID;
if (request) {
response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t));
if (response) {
result = coap_send(context, dst, response);
coap_delete_pdu(response);
}
}
return result;
}
int
_order_timestamp( coap_queue_t *lhs, coap_queue_t *rhs ) {
return lhs && rhs && ( lhs->t < rhs->t ) ? -1 : 1;
}
coap_tid_t
coap_send_confirmed(coap_context_t *context,
const coap_address_t *dst,
coap_pdu_t *pdu) {
coap_queue_t *node;
coap_tick_t now;
int r;
node = coap_new_node();
if (!node) {
debug("coap_send_confirmed: insufficient memory\n");
return COAP_INVALID_TID;
}
node->id = coap_send_impl(context, dst, pdu);
if (COAP_INVALID_TID == node->id) {
debug("coap_send_confirmed: error sending pdu\n");
coap_free_node(node);
return COAP_INVALID_TID;
}
prng((unsigned char *)&r,sizeof(r));
coap_ticks(&now);
node->t = now;
/* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND +
(COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) *
((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
node->t += node->timeout;
memcpy(&node->remote, dst, sizeof(coap_address_t));
node->pdu = pdu;
assert(&context->sendqueue);
coap_insert_node(&context->sendqueue, node, _order_timestamp);
#ifdef WITH_CONTIKI
{ /* (re-)initialize retransmission timer */
coap_queue_t *nextpdu;
nextpdu = coap_peek_next(context);
assert(nextpdu); /* we have just inserted a node */
/* must set timer within the context of the retransmit process */
PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
etimer_set(&context->retransmit_timer,
now < nextpdu->t ? nextpdu->t - now : 0);
PROCESS_CONTEXT_END(&coap_retransmit_process);
}
#endif /* WITH_CONTIKI */
return node->id;
}
coap_tid_t
coap_retransmit( coap_context_t *context, coap_queue_t *node ) {
if ( !context || !node )
return COAP_INVALID_TID;
/* re-initialize timeout when maximum number of retransmissions are not reached yet */
if ( node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT ) {
node->retransmit_cnt++;
node->t += ( node->timeout << node->retransmit_cnt );
coap_insert_node( &context->sendqueue, node, _order_timestamp );
#ifndef WITH_CONTIKI
debug("** retransmission #%d of transaction %d\n",
node->retransmit_cnt, ntohs(node->pdu->hdr->id));
#else /* WITH_CONTIKI */
debug("** retransmission #%u of transaction %u\n",
node->retransmit_cnt, uip_ntohs(node->pdu->hdr->id));
#endif /* WITH_CONTIKI */
node->id = coap_send_impl(context, &node->remote, node->pdu);
return node->id;
}
/* no more retransmissions, remove node from system */
#ifndef WITH_CONTIKI
debug("** removed transaction %d\n", ntohs(node->id));
#endif
#ifndef WITHOUT_OBSERVE
/* Check if subscriptions exist that should be canceled after
COAP_MAX_NOTIFY_FAILURES */
if (node->pdu->hdr->code >= 64) {
str token = { 0, NULL };
token.length = node->pdu->hdr->token_length;
token.s = node->pdu->hdr->token;
coap_handle_failed_notify(context, &node->remote, &token);
}
#endif /* WITHOUT_OBSERVE */
/* And finally delete the node */
coap_delete_node( node );
return COAP_INVALID_TID;
}
int
_order_transaction_id( coap_queue_t *lhs, coap_queue_t *rhs ) {
return ( lhs && rhs && lhs->pdu && rhs->pdu &&
( lhs->id < rhs->id ) )
? -1
: 1;
}
/**
* Checks if @p opt fits into the message that ends with @p maxpos.
* This function returns @c 1 on success, or @c 0 if the option @p opt
* would exceed @p maxpos.
*/
static inline int
check_opt_size(coap_opt_t *opt, unsigned char *maxpos) {
if (opt && opt < maxpos) {
if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos))
return opt + COAP_OPT_SIZE(opt) < maxpos;
}
return 0;
}
int
coap_read( coap_context_t *ctx ) {
#ifndef WITH_CONTIKI
static char buf[COAP_MAX_PDU_SIZE];
coap_hdr_t *pdu = (coap_hdr_t *)buf;
#else /* WITH_CONTIKI */
char *buf;
coap_hdr_t *pdu;
#endif /* WITH_CONTIKI */
ssize_t bytes_read = -1;
coap_address_t src, dst;
coap_queue_t *node;
#ifdef WITH_CONTIKI
buf = uip_appdata;
pdu = (coap_hdr_t *)buf;
#endif /* WITH_CONTIKI */
coap_address_init(&src);
#ifndef WITH_CONTIKI
bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0,
&src.addr.sa, &src.size);
#else /* WITH_CONTIKI */
if(uip_newdata()) {
uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr);
src.port = UIP_UDP_BUF->srcport;
uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr);
dst.port = UIP_UDP_BUF->destport;
bytes_read = uip_datalen();
((char *)uip_appdata)[bytes_read] = 0;
PRINTF("Server received %d bytes from [", (int)bytes_read);
PRINT6ADDR(&src.addr);
PRINTF("]:%d\n", uip_ntohs(src.port));
}
#endif /* WITH_CONTIKI */
if ( bytes_read < 0 ) {
warn("coap_read: recvfrom");
return -1;
}
if ( (size_t)bytes_read < sizeof(coap_hdr_t) ) {
debug("coap_read: discarded invalid frame\n" );
return -1;
}
if ( pdu->version != COAP_DEFAULT_VERSION ) {
debug("coap_read: unknown protocol version\n" );
return -1;
}
node = coap_new_node();
if ( !node )
return -1;
node->pdu = coap_pdu_init(0, 0, 0, bytes_read);
if (!node->pdu)
goto error;
coap_ticks( &node->t );
memcpy(&node->local, &dst, sizeof(coap_address_t));
memcpy(&node->remote, &src, sizeof(coap_address_t));
if (!coap_pdu_parse((unsigned char *)buf, bytes_read, node->pdu)) {
warn("discard malformed PDU");
goto error;
}
/* and add new node to receive queue */
coap_transaction_id(&node->remote, node->pdu, &node->id);
coap_insert_node(&ctx->recvqueue, node, _order_timestamp);
#ifndef NDEBUG
if (LOG_DEBUG <= coap_get_log_level()) {
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 40
#endif
unsigned char addr[INET6_ADDRSTRLEN+8];
if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN+8))
debug("** received %d bytes from %s:\n", (int)bytes_read, addr);
coap_show_pdu( node->pdu );
}
#endif
return 0;
error:
/* FIXME: send back RST? */
coap_delete_node(node);
return -1;
}
int
coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node) {
coap_queue_t *p, *q;
if ( !queue || !*queue)
return 0;
/* replace queue head if PDU's time is less than head's time */
if ( id == (*queue)->id ) { /* found transaction */
*node = *queue;
*queue = (*queue)->next;
(*node)->next = NULL;
/* coap_delete_node( q ); */
debug("*** removed transaction %u\n", id);
return 1;
}
/* search transaction to remove (only first occurence will be removed) */
q = *queue;
do {
p = q;
q = q->next;
} while ( q && id != q->id );
if ( q ) { /* found transaction */
p->next = q->next;
q->next = NULL;
*node = q;
/* coap_delete_node( q ); */
debug("*** removed transaction %u\n", id);
return 1;
}
return 0;
}
static inline int
token_match(const unsigned char *a, size_t alen,
const unsigned char *b, size_t blen) {
return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
}
void
coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst,
const unsigned char *token, size_t token_length) {
/* cancel all messages in sendqueue that are for dst
* and use the specified token */
coap_queue_t *p, *q;
debug("cancel_all_messages\n");
while (context->sendqueue &&
coap_address_equals(dst, &context->sendqueue->remote) &&
token_match(token, token_length,
context->sendqueue->pdu->hdr->token,
context->sendqueue->pdu->hdr->token_length)) {
q = context->sendqueue;
context->sendqueue = q->next;
debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
coap_delete_node(q);
}
if (!context->sendqueue)
return;
p = context->sendqueue;
q = p->next;
/* when q is not NULL, it does not match (dst, token), so we can skip it */
while (q) {
if (coap_address_equals(dst, &q->remote) &&
token_match(token, token_length,
q->pdu->hdr->token, q->pdu->hdr->token_length)) {
p->next = q->next;
debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
coap_delete_node(q);
q = p->next;
} else {
p = q;
q = q->next;
}
}
}
coap_queue_t *
coap_find_transaction(coap_queue_t *queue, coap_tid_t id) {
while (queue && queue->id != id)
queue = queue->next;
return queue;
}
coap_pdu_t *
coap_new_error_response(coap_pdu_t *request, unsigned char code,
coap_opt_filter_t opts) {
coap_opt_iterator_t opt_iter;
coap_pdu_t *response;
size_t size = sizeof(coap_hdr_t) + request->hdr->token_length;
int type;
coap_opt_t *option;
unsigned short opt_type = 0; /* used for calculating delta-storage */
#if COAP_ERROR_PHRASE_LENGTH > 0
char *phrase = coap_response_phrase(code);
/* Need some more space for the error phrase and payload start marker */
if (phrase)
size += strlen(phrase) + 1;
#endif
assert(request);
/* cannot send ACK if original request was not confirmable */
type = request->hdr->type == COAP_MESSAGE_CON
? COAP_MESSAGE_ACK
: COAP_MESSAGE_NON;
/* Estimate how much space we need for options to copy from
* request. We always need the Token, for 4.02 the unknown critical
* options must be included as well. */
coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
coap_option_iterator_init(request, &opt_iter, opts);
/* Add size of each unknown critical option. As known critical
options as well as elective options are not copied, the delta
value might grow.
*/
while((option = coap_option_next(&opt_iter))) {
unsigned short delta = opt_iter.type - opt_type;
/* calculate space required to encode (opt_iter.type - opt_type) */
if (delta < 13) {
size++;
} else if (delta < 269) {
size += 2;
} else {
size += 3;
}
/* add coap_opt_length(option) and the number of additional bytes
* required to encode the option length */
size += coap_opt_length(option);
switch (*option & 0x0f) {
case 0x0e:
size++;
/* fall through */
case 0x0d:
size++;
break;
default:
;
}
opt_type = opt_iter.type;
}
/* Now create the response and fill with options and payload data. */
response = coap_pdu_init(type, code, request->hdr->id, size);
if (response) {
/* copy token */
if (!coap_add_token(response, request->hdr->token_length,
request->hdr->token)) {
debug("cannot add token to error response\n");
coap_delete_pdu(response);
return NULL;
}
/* copy all options */
coap_option_iterator_init(request, &opt_iter, opts);
while((option = coap_option_next(&opt_iter)))
coap_add_option(response, opt_iter.type,
COAP_OPT_LENGTH(option),
COAP_OPT_VALUE(option));
#if COAP_ERROR_PHRASE_LENGTH > 0
/* note that diagnostic messages do not need a Content-Format option. */
if (phrase)
coap_add_data(response, strlen(phrase), (unsigned char *)phrase);
#endif
}
return response;
}
coap_pdu_t *
wellknown_response(coap_context_t *context, coap_pdu_t *request) {
coap_pdu_t *resp;
coap_opt_iterator_t opt_iter;
size_t len;
unsigned char buf[2];
resp = coap_pdu_init(request->hdr->type == COAP_MESSAGE_CON
? COAP_MESSAGE_ACK
: COAP_MESSAGE_NON,
COAP_RESPONSE_CODE(205),
request->hdr->id, COAP_MAX_PDU_SIZE);
if (!resp) {
debug("wellknown_response: cannot create PDU\n");
return NULL;
}
if (!coap_add_token(resp, request->hdr->token_length, request->hdr->token)) {
debug("wellknown_response: cannot add token\n");
goto error;
}
/* Check if there is sufficient space to add Content-Format option
* and data. We do this before adding the Content-Format option to
* avoid sending error responses with that option but no actual
* content. */
if (resp->max_size <= (size_t)resp->length + 3) {
debug("wellknown_response: insufficient storage space\n");
goto error;
}
/* Add Content-Format. As we have checked for available storage,
* nothing should go wrong here. */
assert(coap_encode_var_bytes(buf,
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
coap_encode_var_bytes(buf,
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
/* Manually set payload of response to let print_wellknown() write,
* into our buffer without copying data. */
resp->data = (unsigned char *)resp->hdr + resp->length;
*resp->data = COAP_PAYLOAD_START;
resp->data++;
resp->length++;
len = resp->max_size - resp->length;
if (!print_wellknown(context, resp->data, &len,
coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter))) {
debug("print_wellknown failed\n");
goto error;
}
resp->length += len;
return resp;
error:
/* set error code 5.03 and remove all options and data from response */
resp->hdr->code = COAP_RESPONSE_CODE(503);
resp->length = sizeof(coap_hdr_t) + resp->hdr->token_length;
return resp;
}
#define WANT_WKC(Pdu,Key) \
(((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key))
void
handle_request(coap_context_t *context, coap_queue_t *node) {
coap_method_handler_t h = NULL;
coap_pdu_t *response = NULL;
coap_opt_filter_t opt_filter;
coap_resource_t *resource;
coap_key_t key;
coap_option_filter_clear(opt_filter);
/* try to find the resource from the request URI */
coap_hash_request_uri(node->pdu, key);
resource = coap_get_resource_from_key(context, key);
if (!resource) {
/* The resource was not found. Check if the request URI happens to
* be the well-known URI. In that case, we generate a default
* response, otherwise, we return 4.04 */
switch(node->pdu->hdr->code) {
case COAP_REQUEST_GET:
if (is_wkc(key)) { /* GET request for .well-known/core */
info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
response = wellknown_response(context, node->pdu);