-
Notifications
You must be signed in to change notification settings - Fork 2k
/
gcoap.c
1969 lines (1767 loc) · 70.5 KB
/
gcoap.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-2020 Ken Bannister. All rights reserved.
* 2019 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup net_gcoap
* @{
*
* @file
* @brief GNRC's implementation of CoAP protocol
*
* Runs a thread (_pid) to manage request/response messaging.
*
* @author Ken Bannister <kb2ma@runbox.com>
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*/
#include <errno.h>
#include <stdint.h>
#include <stdatomic.h>
#include <string.h>
#include "assert.h"
#include "net/coap.h"
#include "net/gcoap.h"
#include "net/gcoap/forward_proxy.h"
#include "net/nanocoap/cache.h"
#include "net/sock/async/event.h"
#include "net/sock/util.h"
#include "mutex.h"
#include "random.h"
#include "thread.h"
#include "ztimer.h"
#if IS_USED(MODULE_GCOAP_DTLS)
#include "net/sock/dtls.h"
#include "net/credman.h"
#include "net/dsm.h"
#endif
#define ENABLE_DEBUG 0
#include "debug.h"
/* Sentinel value indicating that no immediate response is required */
#define NO_IMMEDIATE_REPLY (-1)
/* End of the range to pick a random timeout */
#define TIMEOUT_RANGE_END ((uint32_t)CONFIG_COAP_ACK_TIMEOUT_MS * CONFIG_COAP_RANDOM_FACTOR_1000 / 1000)
/* Internal functions */
static void *_event_loop(void *arg);
static void _on_sock_udp_evt(sock_udp_t *sock, sock_async_flags_t type, void *arg);
static void _process_coap_pdu(gcoap_socket_t *sock, sock_udp_ep_t *remote, sock_udp_aux_tx_t *aux,
uint8_t *buf, size_t len, bool truncated);
static int _tl_init_coap_socket(gcoap_socket_t *sock, gcoap_socket_type_t type);
static ssize_t _tl_send(gcoap_socket_t *sock, const void *data, size_t len,
const sock_udp_ep_t *remote, sock_udp_aux_tx_t *aux);
static ssize_t _tl_authenticate(gcoap_socket_t *sock, const sock_udp_ep_t *remote,
uint32_t timeout);
static ssize_t _well_known_core_handler(coap_pkt_t* pdu, uint8_t *buf, size_t len,
coap_request_ctx_t *ctx);
static void _cease_retransmission(gcoap_request_memo_t *memo);
static size_t _handle_req(gcoap_socket_t *sock, coap_pkt_t *pdu, uint8_t *buf,
size_t len, sock_udp_ep_t *remote, sock_udp_aux_tx_t *aux);
static void _expire_request(gcoap_request_memo_t *memo);
static gcoap_request_memo_t* _find_req_memo_by_mid(const sock_udp_ep_t *remote,
uint16_t mid);
static gcoap_request_memo_t* _find_req_memo_by_token(const sock_udp_ep_t *remote,
const uint8_t *token, size_t tkl);
static gcoap_request_memo_t* _find_req_memo_by_pdu_token(const coap_pkt_t *src_pdu,
const sock_udp_ep_t *remote);
static int _find_resource(gcoap_socket_type_t tl_type,
coap_pkt_t *pdu,
const coap_resource_t **resource_ptr,
gcoap_listener_t **listener_ptr);
static int _find_observer(sock_udp_ep_t **observer, sock_udp_ep_t *remote);
static int _find_obs_memo(gcoap_observe_memo_t **memo, sock_udp_ep_t *remote,
coap_pkt_t *pdu);
static void _find_obs_memo_resource(gcoap_observe_memo_t **memo,
const coap_resource_t *resource);
static void _check_and_expire_obs_memo_last_mid(sock_udp_ep_t *remote,
uint16_t last_notify_mid);
static nanocoap_cache_entry_t *_cache_lookup_memo(gcoap_request_memo_t *cache_key);
static void _cache_process(gcoap_request_memo_t *memo,
coap_pkt_t *pdu);
static ssize_t _cache_build_response(nanocoap_cache_entry_t *ce, coap_pkt_t *pdu,
uint8_t *buf, size_t len);
static void _receive_from_cache_cb(void *arg);
static int _request_matcher_default(gcoap_listener_t *listener,
const coap_resource_t **resource,
coap_pkt_t *pdu);
#if IS_USED(MODULE_GCOAP_DTLS)
static void _on_sock_dtls_evt(sock_dtls_t *sock, sock_async_flags_t type, void *arg);
static void _dtls_free_up_session(void *arg);
#endif
/* Internal variables */
const coap_resource_t _default_resources[] = {
{ "/.well-known/core", COAP_GET, _well_known_core_handler, NULL },
};
static gcoap_listener_t _default_listener = {
&_default_resources[0],
ARRAY_SIZE(_default_resources),
GCOAP_SOCKET_TYPE_UNDEF,
NULL,
NULL,
_request_matcher_default
};
/* Container for the state of gcoap itself */
typedef struct {
mutex_t lock; /* Shares state attributes safely */
gcoap_listener_t *listeners; /* List of registered listeners */
gcoap_request_memo_t open_reqs[CONFIG_GCOAP_REQ_WAITING_MAX];
/* Storage for open requests; if first
byte of an entry is zero, the entry
is available */
atomic_uint next_message_id; /* Next message ID to use */
sock_udp_ep_t observers[CONFIG_GCOAP_OBS_CLIENTS_MAX];
/* Observe clients; allows reuse for
observe memos */
gcoap_observe_memo_t observe_memos[CONFIG_GCOAP_OBS_REGISTRATIONS_MAX];
/* Observed resource registrations */
uint8_t resend_bufs[CONFIG_GCOAP_RESEND_BUFS_MAX][CONFIG_GCOAP_PDU_BUF_SIZE];
/* Buffers for PDU for request resends;
if first byte of an entry is zero,
the entry is available */
} gcoap_state_t;
static gcoap_state_t _coap_state = {
.listeners = &_default_listener,
};
static kernel_pid_t _pid = KERNEL_PID_UNDEF;
static char _msg_stack[GCOAP_STACK_SIZE];
static event_queue_t _queue;
static uint8_t _listen_buf[CONFIG_GCOAP_PDU_BUF_SIZE];
static sock_udp_t _sock_udp;
static event_callback_t _receive_from_cache;
#if IS_USED(MODULE_GCOAP_DTLS)
/* DTLS variables and definitions */
#define SOCK_DTLS_CLIENT_TAG (2)
static sock_udp_t _sock_dtls_base;
static sock_dtls_t _sock_dtls;
static kernel_pid_t _auth_waiting_thread;
static event_timeout_t _dtls_session_free_up_tmout;
static event_callback_t _dtls_session_free_up_tmout_cb;
#endif
/* Event loop for gcoap _pid thread. */
static void *_event_loop(void *arg)
{
(void)arg;
sock_udp_ep_t local;
memset(&local, 0, sizeof(sock_udp_ep_t));
/* FIXME: Once the problems with IPv4/IPv6 dual stack use in RIOT are fixed, adapt these lines
* (and e.g. use AF_UNSPEC) */
#ifdef SOCK_HAS_IPV4
local.family = AF_INET;
#endif
#ifdef SOCK_HAS_IPV6
local.family = AF_INET6;
#endif
local.netif = SOCK_ADDR_ANY_NETIF;
local.port = CONFIG_GCOAP_PORT;
int res = sock_udp_create(&_sock_udp, &local, NULL, 0);
if (res < 0) {
DEBUG("gcoap: cannot create sock: %d\n", res);
return 0;
}
event_queue_init(&_queue);
sock_udp_event_init(&_sock_udp, &_queue, _on_sock_udp_evt, NULL);
if (IS_USED(MODULE_GCOAP_DTLS)) {
#if IS_USED(MODULE_GCOAP_DTLS)
local.port = CONFIG_GCOAPS_PORT;
if (sock_udp_create(&_sock_dtls_base, &local, NULL, 0)) {
DEBUG("gcoap: error creating DTLS transport sock\n");
return 0;
}
if (sock_dtls_create(&_sock_dtls, &_sock_dtls_base,
CREDMAN_TAG_EMPTY,
SOCK_DTLS_1_2, SOCK_DTLS_SERVER) < 0) {
DEBUG("gcoap: error creating DTLS sock\n");
sock_udp_close(&_sock_dtls_base);
return 0;
}
sock_dtls_event_init(&_sock_dtls, &_queue, _on_sock_dtls_evt,
NULL);
#endif
}
event_loop(&_queue);
return 0;
}
#if IS_USED(MODULE_GCOAP_DTLS)
/* Handles DTLS socket events from the event queue */
static void _on_sock_dtls_evt(sock_dtls_t *sock, sock_async_flags_t type, void *arg) {
(void)arg;
gcoap_socket_t socket = { .type = GCOAP_SOCKET_TYPE_DTLS, .socket.dtls = sock};
if (type & SOCK_ASYNC_CONN_RECV) {
ssize_t res = sock_dtls_recv(sock, &socket.ctx_dtls_session,
_listen_buf, sizeof(_listen_buf),
CONFIG_GCOAP_DTLS_HANDSHAKE_TIMEOUT_MSEC);
if (res != -SOCK_DTLS_HANDSHAKE) {
DEBUG("gcoap: could not establish DTLS session: %" PRIdSIZE "\n", res);
sock_dtls_session_destroy(sock, &socket.ctx_dtls_session);
return;
}
dsm_state_t prev_state = dsm_store(sock, &socket.ctx_dtls_session,
SESSION_STATE_ESTABLISHED, false);
/* If session is already stored and the state was SESSION_STATE_HANDSHAKE
before, the handshake has been initiated internally by a gcoap client request
and another thread is waiting for the handshake. Send message to the
waiting thread to inform about established session */
if (prev_state == SESSION_STATE_HANDSHAKE) {
msg_t msg = { .type = DTLS_EVENT_CONNECTED };
msg_send(&msg, _auth_waiting_thread);
} else if (prev_state == NO_SPACE) {
/* No space in session management. Should not happen. If it occurs,
we lost track of sessions */
DEBUG("gcoap: no space in session management. We lost track of sessions!");
sock_dtls_session_destroy(sock, &socket.ctx_dtls_session);
}
/* If not enough session slots left: set timeout to free up session */
uint8_t minimum_free = CONFIG_GCOAP_DTLS_MINIMUM_AVAILABLE_SESSIONS;
if (dsm_get_num_available_slots() < minimum_free)
{
uint32_t timeout = CONFIG_GCOAP_DTLS_MINIMUM_AVAILABLE_SESSIONS_TIMEOUT_MSEC;
event_callback_init(&_dtls_session_free_up_tmout_cb,
_dtls_free_up_session, NULL);
event_timeout_ztimer_init(&_dtls_session_free_up_tmout, ZTIMER_MSEC, &_queue,
&_dtls_session_free_up_tmout_cb.super);
event_timeout_set(&_dtls_session_free_up_tmout, timeout);
}
}
if (type & SOCK_ASYNC_CONN_FIN) {
if (sock_dtls_get_event_session(sock, &socket.ctx_dtls_session)) {
/* Session is already destroyed, only remove it from dsm */
dsm_remove(sock, &socket.ctx_dtls_session);
} else {
puts("gcoap: A session was closed, but the corresponding session " \
"could not be retrieved from the socket!");
return;
}
sock_udp_ep_t ep;
sock_dtls_session_get_udp_ep(&socket.ctx_dtls_session, &ep);
/* Remove all memos of the concerned session. TODO: oberservable memos! */
for (int i = 0; i < CONFIG_GCOAP_REQ_WAITING_MAX; i++) {
if (_coap_state.open_reqs[i].state == GCOAP_MEMO_UNUSED) {
continue;
}
gcoap_request_memo_t *memo = &_coap_state.open_reqs[i];
if (sock_udp_ep_equal(&memo->remote_ep, &ep)) {
_expire_request(memo);
event_timeout_clear(&memo->resp_evt_tmout);
}
}
}
if (type & SOCK_ASYNC_MSG_RECV) {
ssize_t res = sock_dtls_recv(sock, &socket.ctx_dtls_session, _listen_buf,
sizeof(_listen_buf), 0);
if (res <= 0) {
DEBUG("gcoap: DTLS recv failure: %" PRIdSIZE "\n", res);
return;
}
sock_udp_ep_t ep;
sock_dtls_session_get_udp_ep(&socket.ctx_dtls_session, &ep);
/* Truncated DTLS messages would already have gotten lost at verification */
_process_coap_pdu(&socket, &ep, NULL, _listen_buf, res, false);
}
}
/* Timeout function to free up a session when too many session slots are occupied */
static void _dtls_free_up_session(void *arg) {
(void)arg;
sock_dtls_session_t session;
uint8_t minimum_free = CONFIG_GCOAP_DTLS_MINIMUM_AVAILABLE_SESSIONS;
if (dsm_get_num_available_slots() < minimum_free) {
if (dsm_get_least_recently_used_session(&_sock_dtls, &session) != -1) {
/* free up session */
dsm_remove(&_sock_dtls, &session);
sock_dtls_session_destroy(&_sock_dtls, &session);
}
}
}
#endif /* MODULE_GCOAP_DTLS */
/* Handles UDP socket events from the event queue. */
static void _on_sock_udp_evt(sock_udp_t *sock, sock_async_flags_t type, void *arg)
{
(void)arg;
sock_udp_ep_t remote;
if (type & SOCK_ASYNC_MSG_RECV) {
void *stackbuf;
void *buf_ctx = NULL;
bool truncated = false;
size_t cursor = 0;
sock_udp_aux_rx_t aux_in = {
.flags = SOCK_AUX_GET_LOCAL,
};
/* The zero-copy _buf API is not used to its full potential here -- we
* still copy out data in what is a manual version of sock_udp_recv,
* but this gives the direly needed overflow information.
*
* A version that actually doesn't copy would vastly change the way
* gcoap passes the buffer to be read from and written into to the
* handler. Also, given that neither nanocoap nor the handler expects
* to gather scattered data, it'd need to rely on the data coming in a
* single slice (but that may be a realistic assumption).
*/
while (true) {
ssize_t res = sock_udp_recv_buf_aux(sock, &stackbuf, &buf_ctx, 0, &remote, &aux_in);
if (res < 0) {
DEBUG("gcoap: udp recv failure: %" PRIdSIZE "\n", res);
return;
}
if (res == 0) {
break;
}
if (cursor + res > sizeof(_listen_buf)) {
res = sizeof(_listen_buf) - cursor;
truncated = true;
}
memcpy(&_listen_buf[cursor], stackbuf, res);
cursor += res;
}
/* make sure we reply with the same address that the request was
* destined for -- except in the multicast case */
sock_udp_aux_tx_t *aux_out_ptr;
sock_udp_aux_tx_t aux_out = {
.flags = SOCK_AUX_SET_LOCAL,
.local = aux_in.local,
};
if (sock_udp_ep_is_multicast(&aux_in.local)) {
/* This eventually gets passed to sock_udp_send_aux, where NULL
* simply does not set any flags */
aux_out_ptr = NULL;
} else {
aux_out_ptr = &aux_out;
}
gcoap_socket_t socket = {
.type = GCOAP_SOCKET_TYPE_UDP,
.socket.udp = sock,
};
_process_coap_pdu(&socket, &remote, aux_out_ptr, _listen_buf, cursor, truncated);
}
}
/* Processes and evaluates the coap pdu */
static void _process_coap_pdu(gcoap_socket_t *sock, sock_udp_ep_t *remote, sock_udp_aux_tx_t *aux,
uint8_t *buf, size_t len, bool truncated)
{
coap_pkt_t pdu;
gcoap_request_memo_t *memo = NULL;
/* Code paths that necessitate a response on the message layer can set a
* response type here (COAP_TYPE_RST or COAP_TYPE_ACK). If set, at the end
* of the function there will be
* * that value will be put in the code field,
* * token length cleared,
* * code set to EMPTY, and
* * the message is returned with the rest of its header intact.
*/
int8_t messagelayer_emptyresponse_type = NO_IMMEDIATE_REPLY;
ssize_t res = coap_parse(&pdu, buf, len);
if (res < 0) {
DEBUG("gcoap: parse failure: %" PRIdSIZE "\n", res);
/* If a response, can't clear memo, but it will timeout later.
*
* There are *some* error cases in which we could continue (eg. all
* sorts of "packet ends mid-options" in truncated cases, and maybe
* also when the maximum option count is exceeded to at least respond
* with Bad Request), but these would likely require incompatible
* changes to nanocoap.
*/
return;
}
if (coap_get_type(&pdu) == COAP_TYPE_RST) {
DEBUG("gcoap: received RST, expiring potentially existing memo\n");
memo = _find_req_memo_by_mid(remote, pdu.hdr->id);
if (memo) {
event_timeout_clear(&memo->resp_evt_tmout);
_expire_request(memo);
}
/* check if this RST is due to the client not being interested
* in receiving observe notifications anymore. */
_check_and_expire_obs_memo_last_mid(remote, coap_get_id(&pdu));
}
/* validate class and type for incoming */
unsigned code_class = coap_get_code_class(&pdu);
switch (code_class) {
/* incoming request or empty */
case COAP_CLASS_REQ:
if (coap_get_code_raw(&pdu) == COAP_CODE_EMPTY) {
/* ping request */
if (coap_get_type(&pdu) == COAP_TYPE_CON) {
messagelayer_emptyresponse_type = COAP_TYPE_RST;
DEBUG("gcoap: Answering empty CON request with RST\n");
} else if (coap_get_type(&pdu) == COAP_TYPE_ACK) {
memo = _find_req_memo_by_mid(remote, pdu.hdr->id);
if ((memo != NULL) && (memo->send_limit != GCOAP_SEND_LIMIT_NON)) {
DEBUG("gcoap: empty ACK processed, stopping retransmissions\n");
_cease_retransmission(memo);
} else {
DEBUG("gcoap: empty ACK matches no known CON, ignoring\n");
}
} else {
DEBUG("gcoap: Ignoring empty non-CON request\n");
}
}
/* normal request */
else if (coap_get_type(&pdu) == COAP_TYPE_NON
|| coap_get_type(&pdu) == COAP_TYPE_CON) {
size_t pdu_len;
if (truncated) {
/* TBD: Set a Size1 */
pdu_len = gcoap_response(&pdu, _listen_buf, sizeof(_listen_buf),
COAP_CODE_REQUEST_ENTITY_TOO_LARGE);
} else {
pdu_len = _handle_req(sock, &pdu, _listen_buf,
sizeof(_listen_buf), remote, aux);
}
if (pdu_len > 0) {
ssize_t bytes = _tl_send(sock, _listen_buf, pdu_len, remote, aux);
if (bytes <= 0) {
DEBUG("gcoap: send response failed: %" PRIdSIZE "\n", bytes);
}
}
}
else {
DEBUG("gcoap: illegal request type: %u\n", coap_get_type(&pdu));
}
break;
/* incoming response */
case COAP_CLASS_SUCCESS:
case COAP_CLASS_CLIENT_FAILURE:
case COAP_CLASS_SERVER_FAILURE:
memo = _find_req_memo_by_pdu_token(&pdu, remote);
if (memo) {
switch (coap_get_type(&pdu)) {
case COAP_TYPE_CON:
messagelayer_emptyresponse_type = COAP_TYPE_ACK;
DEBUG("gcoap: Answering CON response with ACK\n");
/* fall through */
case COAP_TYPE_NON:
case COAP_TYPE_ACK:
if (memo->resp_evt_tmout.queue) {
event_timeout_clear(&memo->resp_evt_tmout);
}
memo->state = truncated ? GCOAP_MEMO_RESP_TRUNC : GCOAP_MEMO_RESP;
if (IS_USED(MODULE_NANOCOAP_CACHE)) {
nanocoap_cache_entry_t *ce = NULL;
if ((pdu.hdr->code == COAP_CODE_VALID) &&
(ce = _cache_lookup_memo(memo))) {
/* update max_age from response and send cached response */
uint32_t max_age = 60;
coap_opt_get_uint(&pdu, COAP_OPT_MAX_AGE, &max_age);
ce->max_age = ztimer_now(ZTIMER_SEC) + max_age;
/* copy all options and possible payload from the cached response
* to the new response */
assert((uint8_t *)pdu.hdr == &_listen_buf[0]);
if (_cache_build_response(ce, &pdu, _listen_buf,
sizeof(_listen_buf)) < 0) {
memo->state = GCOAP_MEMO_ERR;
}
if (ce->truncated) {
memo->state = GCOAP_MEMO_RESP_TRUNC;
}
}
/* TODO: resend request if VALID but no cache entry? */
else if ((pdu.hdr->code != COAP_CODE_VALID)) {
_cache_process(memo, &pdu);
}
}
bool observe_notification = coap_has_observe(&pdu);
if (memo->resp_handler) {
memo->resp_handler(memo, &pdu, remote);
}
if (memo->send_limit >= 0) { /* if confirmable */
*memo->msg.data.pdu_buf = 0; /* clear resend PDU buffer */
}
/* The memo must be kept if the response is an observe notification.
* Non-2.xx notifications indicate that the associated observe entry
* was removed on the server side. Then also free the memo here. */
if (!observe_notification || (code_class != COAP_CLASS_SUCCESS)) {
/* setting the state to unused frees (drops) the memo entry */
memo->state = GCOAP_MEMO_UNUSED;
}
break;
default:
DEBUG("gcoap: illegal response type: %u\n", coap_get_type(&pdu));
break;
}
}
else {
DEBUG("gcoap: msg not found for ID: %u\n", coap_get_id(&pdu));
if (coap_get_type(&pdu) == COAP_TYPE_CON) {
/* we might run into this if an ACK to a sender got lost
* see https://datatracker.ietf.org/doc/html/rfc7252#section-5.3.2 */
messagelayer_emptyresponse_type = COAP_TYPE_RST;
DEBUG("gcoap: Answering unknown CON response with RST to "
"shut up sender\n");
} else {
/* if the response was a (NON) observe notification and there is no
* matching request, the server must be informed that this node is
* no longer interested in this notification. */
if (coap_has_observe(&pdu)) {
messagelayer_emptyresponse_type = COAP_TYPE_RST;
}
}
}
break;
default:
DEBUG("gcoap: illegal code class: %u\n", coap_get_code_class(&pdu));
}
if (messagelayer_emptyresponse_type != NO_IMMEDIATE_REPLY) {
coap_hdr_set_type(pdu.hdr, (uint8_t)messagelayer_emptyresponse_type);
coap_hdr_set_code(pdu.hdr, COAP_CODE_EMPTY);
/* Set the token length to 0, preserving the CoAP version as it was and
* the empty message type that was just set.
*
* FIXME: Introduce an internal function to set or truncate the token
* */
pdu.hdr->ver_t_tkl &= 0xf0;
ssize_t bytes = _tl_send(sock, buf, sizeof(coap_hdr_t), remote, aux);
if (bytes <= 0) {
DEBUG("gcoap: empty response failed: %" PRIdSIZE "\n", bytes);
}
}
}
/* Handles response timeout for a request; resend confirmable if needed. */
static void _on_resp_timeout(void *arg) {
gcoap_request_memo_t *memo = (gcoap_request_memo_t *)arg;
/* no retries remaining */
if ((memo->send_limit == GCOAP_SEND_LIMIT_NON) || (memo->send_limit == 0)) {
_expire_request(memo);
}
/* reduce retries remaining, double timeout and resend */
else {
memo->send_limit--;
#ifdef CONFIG_GCOAP_NO_RETRANS_BACKOFF
unsigned i = 0;
#else
unsigned i = CONFIG_COAP_MAX_RETRANSMIT - memo->send_limit;
#endif
uint32_t timeout = (uint32_t)CONFIG_COAP_ACK_TIMEOUT_MS << i;
#if CONFIG_COAP_RANDOM_FACTOR_1000 > 1000
uint32_t end = (uint32_t)TIMEOUT_RANGE_END << i;
timeout = random_uint32_range(timeout, end);
#endif
event_timeout_set(&memo->resp_evt_tmout, timeout);
if (memo->state == GCOAP_MEMO_WAIT) {
/* See _cease_retransmission: Still going through the timeouts and
* rescheduling, but not actually sending any more */
return;
}
ssize_t bytes = _tl_send(&memo->socket, memo->msg.data.pdu_buf,
memo->msg.data.pdu_len, &memo->remote_ep, NULL);
if (bytes <= 0) {
DEBUG("gcoap: sock resend failed: %" PRIdSIZE "\n", bytes);
_expire_request(memo);
}
}
}
/* Change the retransmission of the memo such that no requests are sent any more.
*
* This is used in response to an empty ACK.
*
* The current implementation does not touch the timers, but merely sets the
* memo's state to GCOAP_MEMO_WAIT. This approach needs less complex code at
* the cost of the remaining `send_limit` timers firing and some memory not
* being freed until the actual response arrives.
*
* An alternative implementation would stop the timeouts, and either free the
* whole memo if it has no response handler, or calculate the remaining timeout
* from `send_limit` to set a final timeout then. In that case, it might also
* free the gcoap_resend_t data and move it back into hdr_buf (along with a
* change in the discriminator for that). (That's not an option with the
* current design because the discriminator is the send_limit field, which is
* still used to count down).
*
* @param[inout] memo The memo indicating the pending request
*
* @pre The @p memo is GCOAP_MEMO_RETRANSMIT or GCOAP_MEMO_WAIT, and its
* send_limit is not GCOAP_SEND_LIMIT_NON.
*/
static void _cease_retransmission(gcoap_request_memo_t *memo) {
memo->state = GCOAP_MEMO_WAIT;
/* there is also no response handler to wait for => expire memo */
if (memo->resp_handler == NULL) {
event_timeout_clear(&memo->resp_evt_tmout);
_expire_request(memo);
}
}
/*
* Main request handler: generates response PDU in the provided buffer.
*
* Caller must finish the PDU and send it.
*
* return length of response pdu, or < 0 if can't handle
*/
static size_t _handle_req(gcoap_socket_t *sock, coap_pkt_t *pdu, uint8_t *buf,
size_t len, sock_udp_ep_t *remote, sock_udp_aux_tx_t *aux)
{
const coap_resource_t *resource = NULL;
gcoap_listener_t *listener = NULL;
sock_udp_ep_t *observer = NULL;
gcoap_observe_memo_t *memo = NULL;
gcoap_observe_memo_t *resource_memo = NULL;
switch (_find_resource(sock->type, pdu, &resource, &listener)) {
case GCOAP_RESOURCE_WRONG_METHOD:
return gcoap_response(pdu, buf, len, COAP_CODE_METHOD_NOT_ALLOWED);
case GCOAP_RESOURCE_NO_PATH:
return gcoap_response(pdu, buf, len, COAP_CODE_PATH_NOT_FOUND);
case GCOAP_RESOURCE_FOUND:
/* find observe registration for resource */
_find_obs_memo_resource(&resource_memo, resource);
break;
case GCOAP_RESOURCE_ERROR:
default:
return gcoap_response(pdu, buf, len, COAP_CODE_INTERNAL_SERVER_ERROR);
break;
}
if (coap_get_observe(pdu) == COAP_OBS_REGISTER) {
/* lookup remote+token */
int empty_slot = _find_obs_memo(&memo, remote, pdu);
/* validate re-registration request */
if (resource_memo != NULL) {
if (memo != NULL) {
if (memo != resource_memo) {
/* reject token already used for a different resource */
memo = NULL;
coap_clear_observe(pdu);
DEBUG("gcoap: can't change resource for token\n");
}
/* otherwise OK to re-register resource with the same token */
}
else if ((sock->type == resource_memo->socket.type) &&
sock_udp_ep_equal(remote, resource_memo->observer)) {
/* accept new token for resource */
memo = resource_memo;
}
}
/* initialize new registration request */
if ((memo == NULL) && coap_has_observe(pdu)) {
/* verify resource not already registered (for another endpoint) */
if ((empty_slot >= 0) && (resource_memo == NULL)) {
int obs_slot = _find_observer(&observer, remote);
/* cache new observer */
if (observer == NULL) {
if (obs_slot >= 0) {
observer = &_coap_state.observers[obs_slot];
memcpy(observer, remote, sizeof(sock_udp_ep_t));
} else {
DEBUG("gcoap: can't register observer\n");
}
}
if (observer != NULL) {
memo = &_coap_state.observe_memos[empty_slot];
memo->observer = observer;
}
}
if (memo == NULL) {
coap_clear_observe(pdu);
DEBUG("gcoap: can't register observe memo\n");
}
}
/* finish registration */
if (memo != NULL) {
/* resource may be assigned here if it is not already registered */
memo->resource = resource;
memo->token_len = coap_get_token_len(pdu);
memo->socket = *sock;
if (memo->token_len) {
memcpy(&memo->token[0], coap_get_token(pdu), memo->token_len);
}
DEBUG("gcoap: Registered observer for: %s\n", memo->resource->path);
}
} else if (coap_get_observe(pdu) == COAP_OBS_DEREGISTER) {
_find_obs_memo(&memo, remote, pdu);
/* clear memo, and clear observer if no other memos */
if (memo != NULL) {
DEBUG("gcoap: Deregistering observer for: %s\n", memo->resource->path);
memo->observer = NULL;
memo = NULL;
_find_obs_memo(&memo, remote, NULL);
if (memo == NULL) {
_find_observer(&observer, remote);
if (observer != NULL) {
observer->family = AF_UNSPEC;
}
}
}
coap_clear_observe(pdu);
} else if (coap_has_observe(pdu)) {
/* bogus request; don't respond */
DEBUG("gcoap: Observe value unexpected: %" PRIu32 "\n", coap_get_observe(pdu));
return -1;
}
ssize_t pdu_len;
coap_request_ctx_t ctx = {
.resource = resource,
.tl_type = (uint32_t)sock->type,
.remote = remote,
.local = aux ? &aux->local : NULL,
};
pdu_len = resource->handler(pdu, buf, len, &ctx);
if (pdu_len < 0) {
pdu_len = gcoap_response(pdu, buf, len,
COAP_CODE_INTERNAL_SERVER_ERROR);
}
return pdu_len;
}
static int _request_matcher_default(gcoap_listener_t *listener,
const coap_resource_t **resource,
coap_pkt_t *pdu)
{
uint8_t uri[CONFIG_NANOCOAP_URI_MAX];
int ret = GCOAP_RESOURCE_NO_PATH;
if (coap_get_uri_path(pdu, uri) <= 0) {
/* The Uri-Path options are longer than
* CONFIG_NANOCOAP_URI_MAX, and thus do not match anything
* that could be found by this handler. */
return GCOAP_RESOURCE_NO_PATH;
}
coap_method_flags_t method_flag = coap_method2flag(
coap_get_code_detail(pdu));
for (size_t i = 0; i < listener->resources_len; i++) {
*resource = &listener->resources[i];
int res = coap_match_path(*resource, uri);
/* URI mismatch */
if (res != 0) {
continue;
}
/* potential match, check for method */
if (! ((*resource)->methods & method_flag)) {
/* record wrong method error for next iteration, in case
* another resource with the same URI and correct method
* exists */
ret = GCOAP_RESOURCE_WRONG_METHOD;
continue;
}
else {
return GCOAP_RESOURCE_FOUND;
}
}
return ret;
}
/*
* Searches listener registrations for the resource matching the path in a PDU.
*
* param[in] tl_type -- transport the request for the resource came over.
* param[in] pdu -- the PDU to check the resource for
* param[out] resource_ptr -- found resource
* param[out] listener_ptr -- listener for found resource
* return `GCOAP_RESOURCE_FOUND` if the resource was found,
* `GCOAP_RESOURCE_WRONG_METHOD` if a resource was found but the method
* code didn't match and `GCOAP_RESOURCE_NO_PATH` if no matching
* resource was found.
*/
static int _find_resource(gcoap_socket_type_t tl_type,
coap_pkt_t *pdu,
const coap_resource_t **resource_ptr,
gcoap_listener_t **listener_ptr)
{
int ret = GCOAP_RESOURCE_NO_PATH;
/* Find path for CoAP msg among listener resources and execute callback. */
gcoap_listener_t *listener = _coap_state.listeners;
while (listener) {
const coap_resource_t *resource;
int res;
/* only makes sense to check if non-UDP transports are supported,
* so check if module is used first. */
if (IS_USED(MODULE_GCOAP_DTLS) &&
(listener->tl_type != GCOAP_SOCKET_TYPE_UNDEF) &&
!(listener->tl_type & tl_type)) {
listener = listener->next;
continue;
}
res = listener->request_matcher(listener, &resource, pdu);
/* check next resource on mismatch */
if (res == GCOAP_RESOURCE_NO_PATH) {
listener = listener->next;
continue;
}
/* found a resource, but methods do not match */
else if (res == GCOAP_RESOURCE_WRONG_METHOD) {
ret = GCOAP_RESOURCE_WRONG_METHOD;
listener = listener->next;
continue;
}
/* found a suitable resource */
else if (res == GCOAP_RESOURCE_FOUND) {
*resource_ptr = resource;
*listener_ptr = listener;
return GCOAP_RESOURCE_FOUND;
}
/* res is probably GCOAP_RESOURCE_ERROR or some other
* unhandled error */
else {
return GCOAP_RESOURCE_ERROR;
}
}
return ret;
}
/*
* Finds the memo for an outstanding request within the _coap_state.open_reqs
* array. Matches on remote endpoint and token.
*
* remote[in] Remote endpoint to match
* token[in] Token to match
* tkl[in] Length of the token in bytes
*
* return Registered request memo, or NULL if not found
*/
static gcoap_request_memo_t* _find_req_memo_by_token(const sock_udp_ep_t *remote,
const uint8_t *token, size_t tkl)
{
/* no need to initialize struct; we only care about buffer contents below */
coap_pkt_t memo_pdu_data;
coap_pkt_t *memo_pdu = &memo_pdu_data;
for (int i = 0; i < CONFIG_GCOAP_REQ_WAITING_MAX; i++) {
if (_coap_state.open_reqs[i].state == GCOAP_MEMO_UNUSED) {
continue;
}
gcoap_request_memo_t *memo = &_coap_state.open_reqs[i];
memo_pdu->hdr = gcoap_request_memo_get_hdr(memo);
if (coap_get_token_len(memo_pdu) == tkl) {
if ((memcmp(token, coap_get_token(memo_pdu), tkl) == 0)
&& (sock_udp_ep_equal(&memo->remote_ep, remote)
/* Multicast addresses are not considered in matching responses */
|| sock_udp_ep_is_multicast(&memo->remote_ep)
)) {
return memo;
}
}
}
return NULL;
}
/*
* Utility wrapper for _find_req_memo_by_token(), using the pdu token.
* Finds the memo for an outstanding request within the _coap_state.open_reqs
* array. Matches on remote endpoint and token of the pdu.
*
* src_pdu[in] PDU which holds the token for matching
* remote[in] Remote endpoint to match
*
* return Registered request memo, or NULL if not found
*/
static gcoap_request_memo_t* _find_req_memo_by_pdu_token(
const coap_pkt_t *src_pdu,
const sock_udp_ep_t *remote)
{
unsigned tkl = coap_get_token_len(src_pdu);
uint8_t *token = coap_get_token(src_pdu);
return _find_req_memo_by_token(remote, token, tkl);
}
/*
* Finds the memo for an outstanding request within the _coap_state.open_reqs
* array. Matches on remote endpoint and message ID.
*
* remote[in] Remote endpoint to match
* mid[in] Message ID to match
*
* return Registered request memo, or NULL if not found
*/
static gcoap_request_memo_t* _find_req_memo_by_mid(const sock_udp_ep_t *remote, uint16_t mid)
{
for (int i = 0; i < CONFIG_GCOAP_REQ_WAITING_MAX; i++) {
if (_coap_state.open_reqs[i].state == GCOAP_MEMO_UNUSED) {
continue;
}
gcoap_request_memo_t *memo = &_coap_state.open_reqs[i];
if ((mid == gcoap_request_memo_get_hdr(memo)->id) &&
sock_udp_ep_equal(&memo->remote_ep, remote)) {
return memo;
}
}
return NULL;
}
/* Calls handler callback on receipt of a timeout message. */
static void _expire_request(gcoap_request_memo_t *memo)
{
DEBUG("coap: received timeout message\n");
if ((memo->state == GCOAP_MEMO_RETRANSMIT) || (memo->state == GCOAP_MEMO_WAIT)) {
memo->state = GCOAP_MEMO_TIMEOUT;
/* Pass response to handler */
if (memo->resp_handler) {
coap_pkt_t req;
req.hdr = gcoap_request_memo_get_hdr(memo);
memo->resp_handler(memo, &req, NULL);
}
if (memo->send_limit != GCOAP_SEND_LIMIT_NON) {
*memo->msg.data.pdu_buf = 0; /* clear resend buffer */
}
memo->state = GCOAP_MEMO_UNUSED;
}
else {
/* Response already handled; timeout must have fired while response */
/* was in queue. */
}
}
/*
* Handler for /.well-known/core. Lists registered handlers, except for
* /.well-known/core itself.
*/
static ssize_t _well_known_core_handler(coap_pkt_t* pdu, uint8_t *buf, size_t len,
coap_request_ctx_t *ctx)
{
(void)ctx;
gcoap_resp_init(pdu, buf, len, COAP_CODE_CONTENT);
coap_opt_add_format(pdu, COAP_FORMAT_LINK);
ssize_t plen = coap_opt_finish(pdu, COAP_OPT_FINISH_PAYLOAD);
plen += gcoap_get_resource_list(pdu->payload, (size_t)pdu->payload_len,
COAP_FORMAT_LINK,