libcoap 4.3.5-develop-5e86d78
Loading...
Searching...
No Matches
coap_block.c
Go to the documentation of this file.
1/* coap_block.c -- block transfer
2 *
3 * Copyright (C) 2010--2012,2015-2026 Olaf Bergmann <bergmann@tzi.org> and others
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
15
17
18#include <stdio.h>
19
20#ifndef min
21#define min(a,b) ((a) < (b) ? (a) : (b))
22#endif
23
24/* Can be 1 - 8 bytes long */
25#ifndef COAP_ETAG_MAX_BYTES
26#define COAP_ETAG_MAX_BYTES 4
27#endif
28#if COAP_ETAG_MAX_BYTES < 1 || COAP_ETAG_MAX_BYTES > 8
29#error COAP_ETAG_MAX_BYTES byte size invalid
30#endif
31
32#define COAP_LG_XMIT_TXT_SCALAR (8)
33
34#if COAP_Q_BLOCK_SUPPORT
35static int blocks_delete_entry(coap_rblock_t *rec_blocks, uint32_t block_num);
36static int blocks_add_entry(coap_rblock_t *rec_blocks, uint32_t block_num, uint32_t block_m);
37#endif /* COAP_Q_BLOCK_SUPPORT */
38
39#if COAP_Q_BLOCK_SUPPORT
40int
42 return 1;
43}
44#else /* ! COAP_Q_BLOCK_SUPPORT */
45int
47 return 0;
48}
49#endif /* ! COAP_Q_BLOCK_SUPPORT */
50
51unsigned int
52coap_opt_block_num(const coap_opt_t *block_opt) {
53 unsigned int num = 0;
54 uint16_t len;
55
56 len = coap_opt_length(block_opt);
57
58 if (len == 0) {
59 return 0;
60 }
61
62 if (len > 1) {
64 coap_opt_length(block_opt) - 1);
65 }
66
67 return (num << 4) | ((COAP_OPT_BLOCK_END_BYTE(block_opt) & 0xF0) >> 4);
68}
69
70int
71coap_get_block_b(const coap_session_t *session, const coap_pdu_t *pdu,
72 coap_option_num_t number, coap_block_b_t *block) {
73 coap_opt_iterator_t opt_iter;
74 coap_opt_t *option;
75
76 assert(block);
77 memset(block, 0, sizeof(coap_block_b_t));
78
79 if (pdu && (option = coap_check_option(pdu, number, &opt_iter)) != NULL) {
80 uint32_t num;
81
82 if (COAP_OPT_BLOCK_MORE(option))
83 block->m = 1;
84 block->aszx = block->szx = COAP_OPT_BLOCK_SZX(option);
85 if (block->szx == 7) {
86 size_t length;
87 const uint8_t *data;
88
89 if (session == NULL || COAP_PROTO_NOT_RELIABLE(session->proto) ||
90 !(session->csm_bert_rem_support && session->csm_bert_loc_support))
91 /* No BERT support */
92 return 0;
93
94 block->szx = 6; /* BERT is 1024 block chunks */
95 block->bert = 1;
96 if (coap_get_data(pdu, &length, &data)) {
97 if (block->m && (length % 1024) != 0) {
98 coap_log_debug("block: Oversized packet - reduced to %" PRIuS " from %" PRIuS "\n",
99 length - (length % 1024), length);
100 length -= length % 1024;
101 }
102 block->chunk_size = (uint32_t)length;
103 } else
104 block->chunk_size = 0;
105 } else {
106 block->chunk_size = (size_t)1 << (block->szx + 4);
107 }
108 block->defined = 1;
109
110 /* The block number is at most 20 bits, so values above 2^20 - 1
111 * are illegal. */
112 num = coap_opt_block_num(option);
113 if (num > 0xFFFFF) {
114 return 0;
115 }
116 block->num = num;
117 return 1;
118 }
119
120 return 0;
121}
122
123int
125 coap_block_t *block) {
126 coap_block_b_t block_b;
127
128 assert(block);
129 memset(block, 0, sizeof(coap_block_t));
130
131 if (coap_get_block_b(NULL, pdu, number, &block_b)) {
132 block->num = block_b.num;
133 block->m = block_b.m;
134 block->szx = block_b.szx;
135 return 1;
136 }
137 return 0;
138}
139
140static int
142 unsigned int num,
143 unsigned int blk_size, size_t total) {
144 size_t token_options = pdu->data ? (size_t)(pdu->data - pdu->token) : pdu->used_size;
145 size_t avail = pdu->max_size - token_options;
146 unsigned int start = num << (blk_size + 4);
147 unsigned int can_use_bert = block->defined == 0 || block->bert;
148
149 assert(start <= total);
150 memset(block, 0, sizeof(*block));
151 block->num = num;
152 block->szx = block->aszx = blk_size;
153 if (can_use_bert && blk_size == 6 && avail >= 1024 && session != NULL &&
154 COAP_PROTO_RELIABLE(session->proto) &&
155 session->csm_bert_rem_support && session->csm_bert_loc_support) {
156 block->bert = 1;
157 block->aszx = 7;
158 block->chunk_size = (uint32_t)((avail / 1024) * 1024);
159 } else {
160 block->chunk_size = (size_t)1 << (blk_size + 4);
161 if (avail < block->chunk_size && (total - start) >= avail) {
162 /* Need to reduce block size */
163 unsigned int szx;
164 int new_blk_size;
165
166 if (avail < 16) { /* bad luck, this is the smallest block size */
167 coap_log_debug("not enough space, even the smallest block does not fit (1)\n");
168 return 0;
169 }
170 new_blk_size = coap_flsll((long long)avail) - 5;
171 coap_log_debug("decrease block size for %" PRIuS " to %d\n", avail, new_blk_size);
172 szx = block->szx;
173 block->szx = new_blk_size;
174 block->num <<= szx - block->szx;
175 block->chunk_size = (size_t)1 << (new_blk_size + 4);
176 }
177 }
178 block->m = block->chunk_size < total - start;
179 return 1;
180}
181
182int
184 coap_pdu_t *pdu, size_t data_length) {
185 size_t start;
186 unsigned char buf[4];
187 coap_block_b_t block_b;
188
189 assert(pdu);
190
191 start = block->num << (block->szx + 4);
192 if (block->num != 0 && data_length <= start) {
193 coap_log_debug("illegal block requested\n");
194 return -2;
195 }
196
197 assert(pdu->max_size > 0);
198
199 block_b.defined = 1;
200 block_b.bert = 0;
201 if (!setup_block_b(NULL, pdu, &block_b, block->num,
202 block->szx, data_length))
203 return -3;
204
205 /* to re-encode the block option */
206 coap_update_option(pdu, number, coap_encode_var_safe(buf, sizeof(buf),
207 ((block_b.num << 4) |
208 (block_b.m << 3) |
209 block_b.szx)),
210 buf);
211
212 return 1;
213}
214
215int
217 coap_option_num_t number,
218 coap_pdu_t *pdu, size_t data_length) {
219 size_t start;
220 unsigned char buf[4];
221
222 assert(pdu);
223
224 start = block->num << (block->szx + 4);
225 if (block->num != 0 && data_length <= start) {
226 coap_log_debug("illegal block requested\n");
227 return -2;
228 }
229
230 assert(pdu->max_size > 0);
231
232 if (!setup_block_b(session, pdu, block, block->num,
233 block->szx, data_length))
234 return -3;
235
236 /* to re-encode the block option */
237 coap_update_option(pdu, number, coap_encode_var_safe(buf, sizeof(buf),
238 ((block->num << 4) |
239 (block->m << 3) |
240 block->aszx)),
241 buf);
242
243 return 1;
244}
245
246int
247coap_add_block(coap_pdu_t *pdu, size_t len, const uint8_t *data,
248 unsigned int block_num, unsigned char block_szx) {
249 unsigned int start;
250 start = block_num << (block_szx + 4);
251
252 if (len <= start)
253 return 0;
254
255 return coap_add_data(pdu,
256 min(len - start, ((size_t)1 << (block_szx + 4))),
257 data + start);
258}
259
260int
261coap_add_block_b_data(coap_pdu_t *pdu, size_t len, const uint8_t *data,
262 coap_block_b_t *block) {
263 unsigned int start = block->num << (block->szx + 4);
264 size_t max_size;
265
266 if (len <= start)
267 return 0;
268
269 if (block->bert) {
270 size_t token_options = pdu->data ? (size_t)(pdu->data - pdu->token) : pdu->used_size;
271 max_size = ((pdu->max_size - token_options) / 1024) * 1024;
272 } else {
273 max_size = (size_t)1 << (block->szx + 4);
274 }
275 block->chunk_size = (uint32_t)max_size;
276
277 return coap_add_data(pdu,
278 min(len - start, max_size),
279 data + start);
280}
281
282/*
283 * Note that the COAP_OPTION_ have to be added in the correct order
284 */
285void
287 coap_pdu_t *response,
288 uint16_t media_type,
289 int maxage,
290 size_t length,
291 const uint8_t *data
292 ) {
293 unsigned char buf[4];
294 coap_block_t block2;
295 int block2_requested = 0;
296#if COAP_SERVER_SUPPORT
297 uint64_t etag = 0;
298 coap_digest_t digest;
299 coap_digest_ctx_t *dctx = NULL;
300#endif /* COAP_SERVER_SUPPORT */
301
302 memset(&block2, 0, sizeof(block2));
303 /*
304 * Need to check that a valid block is getting asked for so that the
305 * correct options are put into the PDU.
306 */
307 if (request) {
308 if (coap_get_block(request, COAP_OPTION_BLOCK2, &block2)) {
309 block2_requested = 1;
310 if (block2.num != 0 && length <= (block2.num << (block2.szx + 4))) {
311 coap_log_debug("Illegal block requested (%d > last = %" PRIuS ")\n",
312 block2.num,
313 length >> (block2.szx + 4));
314 response->code = COAP_RESPONSE_CODE(400);
315 goto error;
316 }
317 }
318 }
319 response->code = COAP_RESPONSE_CODE(205);
320
321#if COAP_SERVER_SUPPORT
322 /* add ETag for the resource data */
323 if (length) {
324 dctx = coap_digest_setup();
325 if (!dctx)
326 goto error;
327 if (request && request->session &&
328 coap_is_mcast(&request->session->addr_info.local)) {
329 coap_digest_update(dctx, coap_unique_id, sizeof(coap_unique_id));
330 }
331 if (!coap_digest_update(dctx, data, length))
332 goto error;
333 if (!coap_digest_final(dctx, &digest))
334 goto error;
335 dctx = NULL;
336 memcpy(&etag, digest.key, sizeof(etag));
337#if COAP_ETAG_MAX_BYTES != 8
338 etag = etag >> 8*(8 - COAP_ETAG_MAX_BYTES);
339#endif
340 if (!etag)
341 etag = 1;
342 coap_update_option(response,
344 coap_encode_var_safe8(buf, sizeof(buf), etag),
345 buf);
346 }
347#endif /* COAP_SERVER_SUPPORT */
348
350 coap_encode_var_safe(buf, sizeof(buf),
351 media_type),
352 buf);
353
354 if (maxage >= 0) {
355 coap_insert_option(response,
357 coap_encode_var_safe(buf, sizeof(buf), maxage), buf);
358 }
359
360 if (block2_requested) {
361 int res;
362
363 res = coap_write_block_opt(&block2, COAP_OPTION_BLOCK2, response, length);
364
365 switch (res) {
366 case -2: /* illegal block (caught above) */
367 response->code = COAP_RESPONSE_CODE(400);
368 goto error;
369 case -1: /* should really not happen */
370 assert(0);
371 /* fall through if assert is a no-op */
372 case -3: /* cannot handle request */
373 response->code = COAP_RESPONSE_CODE(500);
374 goto error;
375 default: /* everything is good */
376 ;
377 }
378
381 coap_encode_var_safe8(buf, sizeof(buf), length),
382 buf);
383
384 coap_add_block(response, length, data,
385 block2.num, block2.szx);
386 return;
387 }
388
389 /*
390 * Block2 not requested
391 */
392 if (!coap_add_data(response, length, data)) {
393 /*
394 * Insufficient space to add in data - use block mode
395 * set initial block size, will be lowered by
396 * coap_write_block_opt() automatically
397 */
398 block2.num = 0;
399 block2.szx = 6;
400 coap_write_block_opt(&block2, COAP_OPTION_BLOCK2, response, length);
401
404 coap_encode_var_safe8(buf, sizeof(buf), length),
405 buf);
406
407 coap_add_block(response, length, data,
408 block2.num, block2.szx);
409 }
410 return;
411
412error:
413#if COAP_SERVER_SUPPORT
414 coap_digest_free(dctx);
415#endif /* COAP_SERVER_SUPPORT */
416 coap_add_data(response,
417 strlen(coap_response_phrase(response->code)),
418 (const unsigned char *)coap_response_phrase(response->code));
419}
420
421COAP_API void
423 uint32_t block_mode) {
424 coap_lock_lock(return);
425 coap_context_set_block_mode_lkd(context, block_mode);
427}
428
429void
431 uint32_t block_mode) {
433 if (!(block_mode & COAP_BLOCK_USE_LIBCOAP))
434 block_mode = 0;
436 context->block_mode |= block_mode & COAP_BLOCK_SET_MASK;
437#if ! COAP_Q_BLOCK_SUPPORT
439 coap_log_debug("Q-Block support not compiled in - ignored\n");
440#endif /* ! COAP_Q_BLOCK_SUPPORT */
441}
442
443COAP_API int
445 size_t max_block_size) {
446 int ret;
447
448 coap_lock_lock(return 0);
449 ret = coap_context_set_max_block_size_lkd(context, max_block_size);
451 return ret;
452}
453
454int
455coap_context_set_max_block_size_lkd(coap_context_t *context, size_t max_block_size) {
456 switch (max_block_size) {
457 case 0:
458 case 16:
459 case 32:
460 case 64:
461 case 128:
462 case 256:
463 case 512:
464 case 1024:
465 break;
466 default:
467 coap_log_info("coap_context_set_max_block_size: Invalid max block size (%" PRIuS ")\n",
468 max_block_size);
469 return 0;
470 }
472 max_block_size = (coap_fls((uint32_t)max_block_size >> 4) - 1) & 0x07;
474 context->block_mode |= COAP_BLOCK_MAX_SIZE_SET((uint32_t)max_block_size);
475 return 1;
476}
477
479full_match(const uint8_t *a, size_t alen,
480 const uint8_t *b, size_t blen) {
481 return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
482}
483
486 coap_lg_xmit_t *lg_xmit = NULL;
487 coap_lg_xmit_t *m_lg_xmit = NULL;
488 uint64_t token_match =
490 pdu->actual_token.length));
491
492 LL_FOREACH(session->lg_xmit, lg_xmit) {
493 if (token_match != STATE_TOKEN_BASE(lg_xmit->b.b1.state_token) &&
494 !coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
495 /* try out the next one */
496 continue;
497 }
498#if COAP_CLIENT_SUPPORT
499 if (COAP_PDU_IS_RESPONSE(pdu)) {
500 if (coap_is_mcast(&lg_xmit->b.b1.upstream)) {
501 m_lg_xmit = lg_xmit;
502 }
503 if (!coap_address_equals(&lg_xmit->b.b1.upstream, &session->addr_info.remote)) {
504 /* try out the next one */
505 continue;
506 }
507 }
508 /* Have a match */
509 return lg_xmit;
510#endif /* COAP_CLIENT_SUPPORT */
511 }
512 if (m_lg_xmit && (session->sock.flags & COAP_SOCKET_MULTICAST)) {
513 /* Need to set up unicast version of mcast lg_xmit entry */
514 lg_xmit = coap_malloc_type(COAP_LG_XMIT, sizeof(coap_lg_xmit_t));
515 if (!lg_xmit)
516 return NULL;
517 memcpy(lg_xmit, m_lg_xmit, sizeof(coap_lg_xmit_t));
518 lg_xmit->next = NULL;
519 lg_xmit->b.b1.app_token = NULL;
520 lg_xmit->data_info->ref++;
521 lg_xmit->sent_pdu = coap_pdu_reference_lkd(m_lg_xmit->sent_pdu);
522 coap_address_copy(&lg_xmit->b.b1.upstream, &session->addr_info.remote);
523 lg_xmit->b.b1.app_token = coap_new_binary(m_lg_xmit->b.b1.app_token->length);
524 if (!lg_xmit->b.b1.app_token)
525 goto fail;
526 if (m_lg_xmit->b.b1.app_token->length)
527 memcpy(lg_xmit->b.b1.app_token->s, m_lg_xmit->b.b1.app_token->s,
528 m_lg_xmit->b.b1.app_token->length);
529 LL_PREPEND(session->lg_xmit, lg_xmit);
530 coap_log_debug("** %s: lg_xmit %p mcast slave initialized\n",
531 coap_session_str(session), (void *)lg_xmit);
532 /* Allow the mcast lg_xmit to time out earlier */
533 coap_ticks(&m_lg_xmit->last_all_sent);
534#if COAP_CLIENT_SUPPORT
535 if (COAP_PDU_IS_RESPONSE(pdu)) {
536 coap_lg_crcv_t *lg_crcv;
537
538 lg_crcv = coap_find_lg_crcv(session, pdu);
539 if (lg_crcv) {
540 lg_xmit->b.b1.state_token = lg_crcv->state_token;
541 }
542 }
543#endif /* COAP_CLIENT_SUPPORT */
544 }
545 return lg_xmit;
546
547fail:
548 coap_block_delete_lg_xmit(session, lg_xmit);
549 return NULL;
550}
551
552#if COAP_CLIENT_SUPPORT
553
554COAP_API int
556 coap_pdu_type_t type) {
557 int ret;
558
559 coap_lock_lock(return 0);
560 ret = coap_cancel_observe_lkd(session, token, type);
562 return ret;
563}
564
565int
566coap_cancel_observe_lkd(coap_session_t *session, coap_binary_t *token,
567 coap_pdu_type_t type) {
568 coap_lg_crcv_t *lg_crcv, *q;
569
570 assert(session);
571 if (!session)
572 return 0;
573
575 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
576 coap_log_debug("** %s: coap_cancel_observe: COAP_BLOCK_USE_LIBCOAP not enabled\n",
577 coap_session_str(session));
578 return 0;
579 }
580
581 LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, q) {
582 if (lg_crcv->observe_set) {
583 if ((!token && !lg_crcv->app_token->length) || (token &&
584 coap_binary_equal(token, lg_crcv->app_token))) {
585 uint8_t buf[8];
586 coap_mid_t mid;
587 size_t size;
588 const uint8_t *data;
589#if COAP_Q_BLOCK_SUPPORT
590 coap_block_b_t block;
591 int using_q_block1 = coap_get_block_b(session, lg_crcv->sent_pdu,
592 COAP_OPTION_Q_BLOCK1, &block);
593#endif /* COAP_Q_BLOCK_SUPPORT */
594 coap_bin_const_t *otoken = lg_crcv->obs_token ?
595 lg_crcv->obs_token[0] ?
596 lg_crcv->obs_token[0] :
597 (coap_bin_const_t *)lg_crcv->app_token :
598 (coap_bin_const_t *)lg_crcv->app_token;
599 coap_pdu_t *pdu = coap_pdu_duplicate_lkd(lg_crcv->sent_pdu,
600 session,
601 otoken->length,
602 otoken->s,
603 NULL,
605
606 lg_crcv->observe_set = 0;
607 if (pdu == NULL)
608 return 0;
609 /* Need to make sure that this is the correct requested type */
610 pdu->type = type;
611
613 coap_encode_var_safe(buf, sizeof(buf),
615 buf);
616 if (lg_crcv->o_block_option) {
617 coap_update_option(pdu, lg_crcv->o_block_option,
618 coap_encode_var_safe(buf, sizeof(buf),
619 lg_crcv->o_blk_size),
620 buf);
621 }
622 if (lg_crcv->obs_data) {
623 coap_add_data_large_request_lkd(session, pdu,
624 lg_crcv->obs_data->length,
625 lg_crcv->obs_data->data, NULL, NULL);
626 } else if (coap_get_data(lg_crcv->sent_pdu, &size, &data)) {
627 coap_add_data_large_request_lkd(session, pdu, size, data, NULL, NULL);
628 }
629
630 /*
631 * Need to fix lg_xmit stateless token as using tokens from
632 * observe setup
633 */
634 if (pdu->lg_xmit)
635 pdu->lg_xmit->b.b1.state_token = lg_crcv->state_token;
636
637 coap_address_copy(&session->addr_info.remote, &lg_crcv->upstream);
638#if COAP_Q_BLOCK_SUPPORT
639 /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
640 if (using_q_block1) {
641 mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
642 } else {
643 mid = coap_send_internal(session, pdu, NULL);
644 }
645#else /* ! COAP_Q_BLOCK_SUPPORT */
646 mid = coap_send_internal(session, pdu, NULL);
647#endif /* ! COAP_Q_BLOCK_SUPPORT */
648 if (mid == COAP_INVALID_MID)
649 break;
650 }
651 }
652 }
653 return 1;
654}
655
657coap_find_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
658 coap_lg_crcv_t *lg_crcv;
659 coap_lg_crcv_t *m_lg_crcv = NULL;
660 uint64_t token_match =
662 pdu->actual_token.length));
663
664 LL_FOREACH(session->lg_crcv, lg_crcv) {
665 if (token_match != STATE_TOKEN_BASE(lg_crcv->state_token) &&
666 !coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
667 /* try out the next one */
668 continue;
669 }
670 if (coap_is_mcast(&lg_crcv->upstream)) {
671 m_lg_crcv = lg_crcv;
672 }
673 if (!coap_address_equals(&lg_crcv->upstream, &session->addr_info.remote)) {
674 /* try out the next one */
675 continue;
676 }
677 /* Have a match */
678 return lg_crcv;
679 }
680 if (m_lg_crcv && (session->sock.flags & COAP_SOCKET_MULTICAST)) {
681 /* Need to set up unicast version of mcast lg_crcv entry */
682 lg_crcv = coap_block_new_lg_crcv(session, m_lg_crcv->sent_pdu, NULL);
683 if (lg_crcv) {
684 if (m_lg_crcv->obs_data) {
685 m_lg_crcv->obs_data->ref++;
686 lg_crcv->obs_data = m_lg_crcv->obs_data;
687 }
688 LL_PREPEND(session->lg_crcv, lg_crcv);
689 }
690 }
691 return lg_crcv;
692}
693
694#if COAP_OSCORE_SUPPORT
696coap_retransmit_oscore_pdu(coap_session_t *session,
697 coap_pdu_t *pdu,
698 coap_opt_t *echo) {
699 coap_lg_crcv_t *lg_crcv;
700 uint8_t ltoken[8];
701 size_t ltoken_len;
702 uint64_t token;
703 const uint8_t *data;
704 size_t data_len;
705 coap_pdu_t *resend_pdu;
706 coap_block_b_t block;
707
708 lg_crcv = coap_find_lg_crcv(session, pdu);
709 if (lg_crcv) {
710 coap_opt_iterator_t opt_iter;
712 &opt_iter);
713 /* Re-send request with new token */
714 token = STATE_TOKEN_FULL(lg_crcv->state_token,
715 ++lg_crcv->retry_counter);
716 ltoken_len = coap_encode_var_safe8(ltoken, sizeof(token), token);
717 /* There could be a Block option in pdu */
718 resend_pdu = coap_pdu_duplicate_lkd(pdu, session, ltoken_len,
719 ltoken, NULL, COAP_BOOL_FALSE);
720 if (!resend_pdu)
721 goto error;
722 if (echo) {
724 coap_opt_value(echo));
725 }
726 if (opt) {
727 if (!lg_crcv->obs_token) {
728 lg_crcv->obs_token = coap_malloc_type(COAP_STRING, sizeof(lg_crcv->obs_token[0]));
729 if (!lg_crcv->obs_token) {
730 return COAP_INVALID_MID;
731 }
732 lg_crcv->obs_token_cnt = 1;
733 } else {
734 coap_delete_bin_const(lg_crcv->obs_token[0]);
735 }
736 lg_crcv->obs_token[0] = coap_new_bin_const(ltoken, ltoken_len);
737 if (lg_crcv->obs_token[0] == NULL)
738 return COAP_INVALID_MID;
739 }
740 if (coap_get_data(lg_crcv->sent_pdu, &data_len, &data)) {
741 if (coap_get_block_b(session, resend_pdu, COAP_OPTION_BLOCK1, &block)) {
742 if (data_len > block.chunk_size && block.chunk_size != 0) {
743 data_len = block.chunk_size;
744 }
745 }
746 coap_add_data(resend_pdu, data_len, data);
747 }
748
749 return coap_send_internal(session, resend_pdu, NULL);
750 }
751error:
752 return COAP_INVALID_MID;
753}
754#endif /* COAP_OSCORE_SUPPORT */
755#endif /* COAP_CLIENT_SUPPORT */
756
757#if COAP_SERVER_SUPPORT
758/*
759 * Find the response lg_xmit
760 */
762coap_find_lg_xmit_response(const coap_session_t *session,
763 const coap_pdu_t *request,
764 const coap_resource_t *resource,
765 const coap_string_t *query) {
766 coap_lg_xmit_t *lg_xmit;
767 coap_opt_iterator_t opt_iter;
768 coap_opt_t *rtag_opt = coap_check_option(request,
770 &opt_iter);
771 size_t rtag_length = rtag_opt ? coap_opt_length(rtag_opt) : 0;
772 const uint8_t *rtag = rtag_opt ? coap_opt_value(rtag_opt) : NULL;
773
774 LL_FOREACH(session->lg_xmit, lg_xmit) {
775 static coap_string_t empty = { 0, NULL};
776
777 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) ||
778 resource != lg_xmit->b.b2.resource ||
779 request->code != lg_xmit->b.b2.request_method ||
780 !coap_string_equal(query ? query : &empty,
781 lg_xmit->b.b2.query ?
782 lg_xmit->b.b2.query : &empty)) {
783 /* try out the next one */
784 continue;
785 }
786 /* lg_xmit is a response */
787 if (rtag_opt || lg_xmit->b.b2.rtag_set == 1) {
788 if (!(rtag_opt && lg_xmit->b.b2.rtag_set == 1))
789 continue;
790 if (lg_xmit->b.b2.rtag_length != rtag_length ||
791 memcmp(lg_xmit->b.b2.rtag, rtag, rtag_length) != 0)
792 continue;
793 }
794 return lg_xmit;
795 }
796 return NULL;
797}
798#endif /* COAP_SERVER_SUPPORT */
799
800static int
802 const coap_pdu_t *request,
803 coap_pdu_t *pdu,
804 coap_resource_t *resource,
805 const coap_string_t *query,
806 int maxage,
807 uint64_t etag,
808 size_t length,
809 const uint8_t *data,
810 coap_release_large_data_t release_func,
811 coap_get_large_data_t get_func,
812 void *app_ptr,
813 int single_request, coap_pdu_code_t request_method) {
814
815 ssize_t avail;
816 coap_block_b_t block;
817#if COAP_Q_BLOCK_SUPPORT
818 coap_block_b_t alt_block;
819#endif /* COAP_Q_BLOCK_SUPPORT */
820 size_t chunk;
821 coap_lg_xmit_t *lg_xmit = NULL;
822 uint8_t buf[8];
823 int have_block_defined = 0;
824 uint8_t blk_size;
825 uint8_t max_blk_size;
826 uint16_t option;
827 size_t token_options;
828 coap_opt_t *opt;
829 coap_opt_iterator_t opt_iter;
830#if COAP_Q_BLOCK_SUPPORT
831 uint16_t alt_option;
832#endif /* COAP_Q_BLOCK_SUPPORT */
833
834#if !COAP_SERVER_SUPPORT
835 (void)etag;
836#endif /* COAP_SERVER_SUPPORT */
837
838 assert(pdu);
839 if (pdu->data) {
840 coap_log_warn("coap_add_data_large: PDU already contains data\n");
841 if (release_func) {
842 coap_lock_callback(release_func(session, app_ptr));
843 }
844 return 0;
845 }
846
847 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
848 coap_log_debug("** %s: coap_add_data_large: COAP_BLOCK_USE_LIBCOAP not enabled\n",
849 coap_session_str(session));
850 goto add_data;
851 }
852
853 /* A lot of the reliable code assumes type is CON */
854 if (COAP_PROTO_RELIABLE(session->proto) && pdu->type == COAP_MESSAGE_NON)
855 pdu->type = COAP_MESSAGE_CON;
856
857 /* Block NUM max 20 bits (starting from 0) and block size is "2**(SZX + 4)"
858 and using SZX max of 6 gives maximum size = 1,073,740,800
859 CSM Max-Message-Size theoretical maximum = 4,294,967,295
860 So, if using blocks, we are limited to 1,073,740,800.
861 */
862#define MAX_BLK_LEN ((1UL << 20) * (1 << (6 + 4)))
863#if UINT_MAX < MAX_BLK_LEN
864#undef MAX_BLK_LEN
865#define MAX_BLK_LEN UINT_MAX
866#endif
867
868 if (length > MAX_BLK_LEN) {
869 coap_log_warn("Size of large buffer restricted to 0x%lx bytes\n", MAX_BLK_LEN);
870 length = MAX_BLK_LEN;
871 }
872
873#if COAP_SERVER_SUPPORT
874 /* Possible response code not yet set, so check if not request */
875 if (!COAP_PDU_IS_REQUEST(pdu) && length) {
876 coap_opt_t *etag_opt = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter);
877
878 if (etag_opt) {
879 /* Have to use ETag as supplied in the response PDU */
880 etag = coap_decode_var_bytes8(coap_opt_value(etag_opt),
881 coap_opt_length(etag_opt));
882 } else {
883 if (!etag) {
884 /* calculate ETag for the response */
885 coap_digest_t digest;
886 coap_digest_ctx_t *dctx = coap_digest_setup();
887
888 if (dctx) {
889 if (coap_is_mcast(&session->addr_info.local)) {
890 (void)coap_digest_update(dctx, coap_unique_id, sizeof(coap_unique_id));
891 }
892 if (coap_digest_update(dctx, data, length)) {
893 if (coap_digest_final(dctx, &digest)) {
894 memcpy(&etag, digest.key, sizeof(etag));
895#if COAP_ETAG_MAX_BYTES != 8
896 etag = etag >> 8*(8 - COAP_ETAG_MAX_BYTES);
897#endif
898 dctx = NULL;
899 }
900 }
901 coap_digest_free(dctx);
902 }
903 if (!etag)
904 etag = 1;
905 }
908 coap_encode_var_safe8(buf, sizeof(buf), etag),
909 buf);
910 }
911 if (request) {
912 etag_opt = coap_check_option(request, COAP_OPTION_ETAG, &opt_iter);
913 if (etag_opt) {
914 /* There may be multiple ETag - need to check each one */
915 coap_option_iterator_init(request, &opt_iter, COAP_OPT_ALL);
916 while ((etag_opt = coap_option_next(&opt_iter))) {
917 if (opt_iter.number == COAP_OPTION_ETAG) {
918 uint64_t etag_r = coap_decode_var_bytes8(coap_opt_value(etag_opt),
919 coap_opt_length(etag_opt));
920
921 if (etag == etag_r) {
922 pdu->code = COAP_RESPONSE_CODE(203);
923 return 1;
924 }
925 }
926 }
927 }
928 }
929 }
930#endif /* COAP_SERVER_SUPPORT */
931
932 /* Determine the block size to use, adding in sensible options if needed */
933 if (COAP_PDU_IS_REQUEST(pdu)) {
935
936#if COAP_Q_BLOCK_SUPPORT
937 if (session->block_mode & (COAP_BLOCK_HAS_Q_BLOCK|COAP_BLOCK_TRY_Q_BLOCK)) {
938 option = COAP_OPTION_Q_BLOCK1;
939 alt_option = COAP_OPTION_BLOCK1;
940 } else {
941 option = COAP_OPTION_BLOCK1;
942 alt_option = COAP_OPTION_Q_BLOCK1;
943 }
944#else /* ! COAP_Q_BLOCK_SUPPORT */
945 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
947 }
948 option = COAP_OPTION_BLOCK1;
949#endif /* ! COAP_Q_BLOCK_SUPPORT */
950
951 /* See if this token is already in use for large bodies (unlikely) */
952 LL_FOREACH_SAFE(session->lg_xmit, lg_xmit, q) {
953 if (coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
954 /* Unfortunately need to free this off as potential size change */
955 int is_mcast = 0;
956 coap_tick_t last_all_sent = lg_xmit->last_all_sent;
957#if COAP_CLIENT_SUPPORT
958 is_mcast = coap_is_mcast(&lg_xmit->b.b1.upstream);
959#endif /* COAP_CLIENT_SUPPORT */
960 LL_DELETE(session->lg_xmit, lg_xmit);
961 coap_block_delete_lg_xmit(session, lg_xmit);
962 lg_xmit = NULL;
963 if (!is_mcast && !last_all_sent)
965 break;
966 }
967 }
968 } else {
969 /* Have to assume that it is a response even if code is 0.00 */
970 assert(resource);
971#if COAP_Q_BLOCK_SUPPORT
972 if (session->block_mode & COAP_BLOCK_HAS_Q_BLOCK) {
973 option = COAP_OPTION_Q_BLOCK2;
974 alt_option = COAP_OPTION_BLOCK2;
975 } else {
976 option = COAP_OPTION_BLOCK2;
977 alt_option = COAP_OPTION_Q_BLOCK2;
978 }
979#else /* ! COAP_Q_BLOCK_SUPPORT */
980 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
982 }
983 option = COAP_OPTION_BLOCK2;
984#endif /* ! COAP_Q_BLOCK_SUPPORT */
985#if COAP_SERVER_SUPPORT
986 /*
987 * Check if resource+query+rtag is already in use for large bodies
988 * (unlikely)
989 */
990 lg_xmit = coap_find_lg_xmit_response(session, request, resource, query);
991 if (lg_xmit) {
992 coap_tick_t last_all_sent = lg_xmit->last_all_sent;
993 /* Unfortunately need to free this off as potential size change */
994 LL_DELETE(session->lg_xmit, lg_xmit);
995 coap_block_delete_lg_xmit(session, lg_xmit);
996 lg_xmit = NULL;
997 if (!last_all_sent)
999 }
1000#endif /* COAP_SERVER_SUPPORT */
1001 }
1002#if COAP_OSCORE_SUPPORT
1003 if (session->oscore_encryption) {
1004 /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1006 goto fail;
1007 }
1008#endif /* COAP_OSCORE_SUPPORT */
1009
1010 token_options = pdu->data ? (size_t)(pdu->data - pdu->token) : pdu->used_size;
1011 avail = pdu->max_size - token_options;
1012 /* There may be a response with Echo option */
1014#if COAP_OSCORE_SUPPORT
1015 avail -= coap_oscore_overhead(session, pdu);
1016#endif /* COAP_OSCORE_SUPPORT */
1017 /* May need token of length 8, so account for this */
1018 avail -= (pdu->actual_token.length < 8) ? 8 - pdu->actual_token.length : 0;
1019
1020 if (avail < 16) {
1021 blk_size = 0;
1022 } else {
1023 blk_size = coap_flsll((long long)avail) - 4 - 1;
1024 }
1025 if (blk_size > 6)
1026 blk_size = 6;
1027
1028 max_blk_size = COAP_BLOCK_MAX_SIZE_GET(session->block_mode);
1029 if (max_blk_size && blk_size > max_blk_size)
1030 blk_size = max_blk_size;
1031
1032 /* see if BlockX defined - if so update blk_size as given by app */
1033 if (coap_get_block_b(session, pdu, option, &block)) {
1034 if (block.szx < blk_size)
1035 blk_size = block.szx;
1036 have_block_defined = 1;
1037 }
1038#if COAP_Q_BLOCK_SUPPORT
1039 /* see if alternate BlockX defined */
1040 if (coap_get_block_b(session, pdu, alt_option, &alt_block)) {
1041 if (have_block_defined) {
1042 /* Cannot have both options set */
1043 coap_log_warn("Both BlockX and Q-BlockX cannot be set at the same time\n");
1044 coap_remove_option(pdu, alt_option);
1045 } else {
1046 block = alt_block;
1047 if (block.szx < blk_size)
1048 blk_size = block.szx;
1049 have_block_defined = 1;
1050 option = alt_option;
1051 }
1052 }
1053#endif /* COAP_Q_BLOCK_SUPPORT */
1054
1055 if (avail < 16 && ((ssize_t)length > avail || have_block_defined)) {
1056 /* bad luck, this is the smallest block size */
1057 coap_log_debug("not enough space, even the smallest block does not fit (2)\n");
1058 goto fail;
1059 }
1060
1061 chunk = (size_t)1 << (blk_size + 4);
1062 if ((have_block_defined && block.num != 0) || single_request ||
1063 ((session->block_mode & COAP_BLOCK_STLESS_BLOCK2) && session->type != COAP_SESSION_TYPE_CLIENT)) {
1064 /* App is defining a single block to send or we are stateless */
1065 size_t rem;
1066
1067 if (length >= block.num * chunk) {
1068#if COAP_SERVER_SUPPORT
1069 if (session->block_mode & COAP_BLOCK_STLESS_BLOCK2 && session->type != COAP_SESSION_TYPE_CLIENT) {
1070 /* We are running server stateless */
1073 coap_encode_var_safe(buf, sizeof(buf),
1074 (unsigned int)length),
1075 buf);
1076 if (request) {
1077 if (!coap_get_block_b(session, request, option, &block))
1078 block.num = 0;
1079 }
1080 if (!setup_block_b(session, pdu, &block, block.num,
1081 blk_size, length))
1082 goto fail;
1083
1084 /* Add in with requested block num, more bit and block size */
1086 option,
1087 coap_encode_var_safe(buf, sizeof(buf),
1088 (block.num << 4) | (block.m << 3) | block.aszx),
1089 buf);
1090 }
1091#endif /* COAP_SERVER_SUPPORT */
1092 rem = chunk;
1093 if (chunk > length - block.num * chunk)
1094 rem = length - block.num * chunk;
1095 if (!coap_add_data(pdu, rem, &data[block.num * chunk]))
1096 goto fail;
1097 }
1098 if (release_func) {
1099 coap_lock_callback(release_func(session, app_ptr));
1100 }
1101 } else if ((have_block_defined && length > chunk) || (ssize_t)length > avail) {
1102 /* Only add in lg_xmit if more than one block needs to be handled */
1103 size_t rem;
1104
1105 lg_xmit = coap_malloc_type(COAP_LG_XMIT, sizeof(coap_lg_xmit_t));
1106 if (!lg_xmit)
1107 goto fail;
1108
1109 /* Set up for displaying all the data in the pdu */
1110 if (!get_func) {
1111 pdu->body_data = data;
1112 pdu->body_length = length;
1113 coap_log_debug("PDU presented by app.\n");
1115 pdu->body_data = NULL;
1116 pdu->body_length = 0;
1117 } else {
1118 coap_log_debug("PDU presented by app without data.\n");
1120 }
1121
1122 coap_log_debug("** %s: lg_xmit %p initialized\n",
1123 coap_session_str(session), (void *)lg_xmit);
1124 /* Update lg_xmit with large data information */
1125 memset(lg_xmit, 0, sizeof(coap_lg_xmit_t));
1126 lg_xmit->blk_size = blk_size;
1127 lg_xmit->option = option;
1128 lg_xmit->data_info = coap_malloc_type(COAP_STRING, sizeof(coap_lg_xmit_data_t));
1129 if (!lg_xmit->data_info)
1130 goto fail;
1131 lg_xmit->data_info->ref = 0;
1132 lg_xmit->data_info->data = data;
1133 lg_xmit->data_info->length = length;
1134#if COAP_Q_BLOCK_SUPPORT
1135 lg_xmit->non_timeout_random_ticks =
1137#endif /* COAP_Q_BLOCK_SUPPORT */
1138 lg_xmit->data_info->get_func = get_func;
1139 lg_xmit->data_info->release_func = release_func;
1140 lg_xmit->data_info->app_ptr = app_ptr;
1141 pdu->lg_xmit = lg_xmit;
1142 coap_ticks(&lg_xmit->last_obs);
1143 coap_ticks(&lg_xmit->last_sent);
1144 if (COAP_PDU_IS_REQUEST(pdu)) {
1145 /* Need to keep original token for updating response PDUs */
1146 lg_xmit->b.b1.app_token = coap_new_binary(pdu->actual_token.length);
1147 if (!lg_xmit->b.b1.app_token)
1148 goto fail;
1149 memcpy(lg_xmit->b.b1.app_token->s, pdu->actual_token.s,
1150 pdu->actual_token.length);
1151 /*
1152 * Need to set up new token for use during transmits
1153 * RFC9177#section-5
1154 */
1155 lg_xmit->b.b1.count = 1;
1156 lg_xmit->b.b1.state_token = STATE_TOKEN_FULL(++session->tx_token,
1157 lg_xmit->b.b1.count);
1158 coap_address_copy(&lg_xmit->b.b1.upstream, &session->addr_info.remote);
1159 /*
1160 * Token will be updated in pdu later as original pdu may be needed in
1161 * coap_send()
1162 */
1165 coap_encode_var_safe(buf, sizeof(buf),
1166 (unsigned int)length),
1167 buf);
1168 if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter))
1171 coap_encode_var_safe(buf, sizeof(buf),
1172 ++session->tx_rtag),
1173 buf);
1174 } else {
1175 /*
1176 * resource+query+rtag match is used for Block2 large body transmissions
1177 * token match is used for Block1 large body transmissions
1178 */
1179 lg_xmit->b.b2.resource = resource;
1180 if (query) {
1181 lg_xmit->b.b2.query = coap_new_string(query->length);
1182 if (lg_xmit->b.b2.query) {
1183 memcpy(lg_xmit->b.b2.query->s, query->s, query->length);
1184 }
1185 } else {
1186 lg_xmit->b.b2.query = NULL;
1187 }
1188 opt = coap_check_option(request, COAP_OPTION_RTAG, &opt_iter);
1189 if (opt) {
1190 lg_xmit->b.b2.rtag_length = (uint8_t)min(coap_opt_length(opt),
1191 sizeof(lg_xmit->b.b2.rtag));
1192 memcpy(lg_xmit->b.b2.rtag, coap_opt_value(opt), lg_xmit->b.b2.rtag_length);
1193 lg_xmit->b.b2.rtag_set = 1;
1194 } else {
1195 lg_xmit->b.b2.rtag_set = 0;
1196 }
1197 lg_xmit->b.b2.etag = etag;
1198 lg_xmit->b.b2.request_method = request_method;
1199 if (maxage >= 0) {
1200 coap_tick_t now;
1201
1202 coap_ticks(&now);
1203 lg_xmit->b.b2.maxage_expire = coap_ticks_to_rt(now) + maxage;
1204 } else {
1205 lg_xmit->b.b2.maxage_expire = 0;
1206 }
1209 coap_encode_var_safe(buf, sizeof(buf),
1210 (unsigned int)length),
1211 buf);
1212 }
1213
1214 if (!setup_block_b(session, pdu, &block, block.num,
1215 blk_size, lg_xmit->data_info->length))
1216 goto fail;
1217
1218 /* Add in with requested block num, more bit and block size */
1220 lg_xmit->option,
1221 coap_encode_var_safe(buf, sizeof(buf),
1222 (block.num << 4) | (block.m << 3) | block.aszx),
1223 buf);
1224
1225 /* Reference PDU to use as a basis for all the subsequent blocks */
1226 lg_xmit->sent_pdu = coap_pdu_reference_lkd(pdu);
1227
1228 /* Check we still have space after adding in some options */
1229 token_options = pdu->data ? (size_t)(pdu->data - pdu->token) : pdu->used_size;
1230 avail = pdu->max_size - token_options;
1231 /* There may be a response with Echo option */
1233 /* May need token of length 8, so account for this */
1234 avail -= (pdu->actual_token.length < 8) ? 8 - pdu->actual_token.length : 0;
1235#if COAP_OSCORE_SUPPORT
1236 avail -= coap_oscore_overhead(session, pdu);
1237#endif /* COAP_OSCORE_SUPPORT */
1238 if (avail < (ssize_t)chunk) {
1239 /* chunk size change down */
1240 if (avail < 16) {
1241 coap_log_warn("not enough space, even the smallest block does not fit (3)\n");
1242 goto fail;
1243 }
1244 blk_size = coap_flsll((long long)avail) - 4 - 1;
1245 block.num = block.num << (lg_xmit->blk_size - blk_size);
1246 lg_xmit->blk_size = blk_size;
1247 chunk = (size_t)1 << (lg_xmit->blk_size + 4);
1248 block.chunk_size = (uint32_t)chunk;
1249 block.bert = 0;
1251 lg_xmit->option,
1252 coap_encode_var_safe(buf, sizeof(buf),
1253 (block.num << 4) | (block.m << 3) | lg_xmit->blk_size),
1254 buf);
1255 }
1256#if COAP_Q_BLOCK_SUPPORT
1257 /* Set up send_blocks */
1258 lg_xmit->send_blocks.used = 1;
1259 lg_xmit->send_blocks.range[0].end = (uint32_t)((lg_xmit->data_info->length - 1) / chunk);
1260#endif /* COAP_Q_BLOCK_SUPPORT */
1261
1262 rem = block.chunk_size;
1263 if (rem > lg_xmit->data_info->length - block.num * chunk)
1264 rem = lg_xmit->data_info->length - block.num * chunk;
1265 if (get_func) {
1266#if COAP_CONSTRAINED_STACK
1267 /* Protected by global_lock if needed */
1268 static uint8_t l_data[1024];
1269#else /* ! COAP_CONSTRAINED_STACK */
1270 uint8_t l_data[1024];
1271#endif /* ! COAP_CONSTRAINED_STACK */
1272 size_t l_length;
1273
1274 assert(rem <= 1024);
1275 if (get_func(session, rem, block.num * chunk, l_data, &l_length, lg_xmit->data_info->app_ptr)) {
1276 if (!coap_add_data(pdu, l_length, l_data)) {
1277 goto fail;
1278 }
1279 }
1280 } else {
1281 if (!coap_add_data(pdu, rem, &data[block.num * chunk]))
1282 goto fail;
1283 }
1284
1285 if (COAP_PDU_IS_REQUEST(pdu))
1286 lg_xmit->b.b1.bert_size = rem;
1287
1288 lg_xmit->last_block = -1;
1289
1290 /* Link the new lg_xmit in */
1291 LL_PREPEND(session->lg_xmit,lg_xmit);
1292 } else {
1293 /* No need to use blocks */
1294 if (have_block_defined) {
1296 option,
1297 coap_encode_var_safe(buf, sizeof(buf),
1298 (0 << 4) | (0 << 3) | blk_size), buf);
1299 if (COAP_PDU_IS_REQUEST(pdu)) {
1302 coap_encode_var_safe(buf, sizeof(buf),
1303 (unsigned int)length),
1304 buf);
1305 } else {
1308 coap_encode_var_safe(buf, sizeof(buf),
1309 (unsigned int)length),
1310 buf);
1311 }
1312 }
1313add_data:
1314 if (get_func) {
1315 uint8_t *l_data = coap_malloc_type(COAP_STRING, length);
1316 size_t l_length;
1317
1318 if (get_func(session, length, 0, l_data, &l_length, app_ptr)) {
1319 if (!coap_add_data(pdu, l_length, l_data)) {
1320 coap_free_type(COAP_STRING, l_data);
1321 goto fail;
1322 }
1323 coap_free_type(COAP_STRING, l_data);
1324 }
1325 } else {
1326 if (!coap_add_data(pdu, length, data))
1327 goto fail;
1328 }
1329
1330 if (release_func) {
1331 coap_lock_callback(release_func(session, app_ptr));
1332 }
1333 }
1334 return 1;
1335
1336fail:
1337 if (lg_xmit) {
1338 coap_block_delete_lg_xmit(session, lg_xmit);
1339 } else if (release_func) {
1340 coap_lock_callback(release_func(session, app_ptr));
1341 }
1342 return 0;
1343}
1344
1345#if COAP_CLIENT_SUPPORT
1346COAP_API int
1348 coap_pdu_t *pdu,
1349 size_t length,
1350 const uint8_t *data,
1351 coap_release_large_data_t release_func,
1352 void *app_ptr
1353 ) {
1354 int ret;
1355
1356 coap_lock_lock(return 0);
1357 ret = coap_add_data_large_request_lkd(session, pdu, length, data,
1358 release_func, app_ptr);
1360 return ret;
1361}
1362
1363int
1364coap_add_data_large_request_lkd(coap_session_t *session,
1365 coap_pdu_t *pdu,
1366 size_t length,
1367 const uint8_t *data,
1368 coap_release_large_data_t release_func,
1369 void *app_ptr) {
1370 /*
1371 * Delay if session->doing_first is set.
1372 * E.g. Reliable and CSM not in yet for checking block support
1373 */
1374 if (coap_client_delay_first(session) == 0) {
1375 if (release_func) {
1376 coap_lock_callback(release_func(session, app_ptr));
1377 }
1378 return 0;
1379 }
1380 return coap_add_data_large_internal(session, NULL, pdu, NULL, NULL, -1, 0,
1381 length, data, release_func, NULL, app_ptr, 0, 0);
1382}
1383
1384COAP_API int
1386 coap_pdu_t *pdu,
1387 size_t length,
1388 coap_release_large_data_t release_func,
1389 coap_get_large_data_t get_func,
1390 void *app_ptr) {
1391 int ret;
1392
1393 coap_lock_lock(return 0);
1394 ret = coap_add_data_large_request_app_lkd(session, pdu, length,
1395 release_func, get_func, app_ptr);
1397 return ret;
1398}
1399
1400int
1401coap_add_data_large_request_app_lkd(coap_session_t *session,
1402 coap_pdu_t *pdu,
1403 size_t length,
1404 coap_release_large_data_t release_func,
1405 coap_get_large_data_t get_func,
1406 void *app_ptr) {
1407 /*
1408 * Delay if session->doing_first is set.
1409 * E.g. Reliable and CSM not in yet for checking block support
1410 */
1411 if (coap_client_delay_first(session) == 0) {
1412 return 0;
1413 }
1414 return coap_add_data_large_internal(session, NULL, pdu, NULL, NULL, -1, 0,
1415 length, NULL, release_func, get_func,
1416 app_ptr, 0, 0);
1417}
1418#endif /* ! COAP_CLIENT_SUPPORT */
1419
1420#if COAP_SERVER_SUPPORT
1421COAP_API int
1423 coap_session_t *session,
1424 const coap_pdu_t *request,
1425 coap_pdu_t *response,
1426 const coap_string_t *query,
1427 uint16_t media_type,
1428 int maxage,
1429 uint64_t etag,
1430 size_t length,
1431 const uint8_t *data,
1432 coap_release_large_data_t release_func,
1433 void *app_ptr) {
1434 int ret;
1435
1436 coap_lock_lock(return 0);
1437 ret = coap_add_data_large_response_lkd(resource, session, request,
1438 response, query, media_type, maxage, etag,
1439 length, data, release_func, app_ptr);
1441 return ret;
1442}
1443
1444int
1445coap_add_data_large_response_lkd(coap_resource_t *resource,
1446 coap_session_t *session,
1447 const coap_pdu_t *request,
1448 coap_pdu_t *response,
1449 const coap_string_t *query,
1450 uint16_t media_type,
1451 int maxage,
1452 uint64_t etag,
1453 size_t length,
1454 const uint8_t *data,
1455 coap_release_large_data_t release_func,
1456 void *app_ptr
1457 ) {
1458 unsigned char buf[4];
1459 coap_block_b_t block;
1460 int block_requested = 0;
1461 int single_request = 0;
1462#if COAP_Q_BLOCK_SUPPORT
1463 uint32_t block_opt = (session->block_mode & COAP_BLOCK_HAS_Q_BLOCK) ?
1465#else /* ! COAP_Q_BLOCK_SUPPORT */
1466 uint16_t block_opt = COAP_OPTION_BLOCK2;
1467#endif /* ! COAP_Q_BLOCK_SUPPORT */
1468
1469 memset(&block, 0, sizeof(block));
1470 /*
1471 * Need to check that a valid block is getting asked for so that the
1472 * correct options are put into the PDU.
1473 */
1474 if (request) {
1475 if (coap_get_block_b(session, request, COAP_OPTION_BLOCK2, &block)) {
1476 block_requested = 1;
1477 if (block.num != 0 && length <= (block.num << (block.szx + 4))) {
1478 coap_log_debug("Illegal block requested (%d > last = %" PRIuS ")\n",
1479 block.num,
1480 length >> (block.szx + 4));
1481 response->code = COAP_RESPONSE_CODE(400);
1482 goto error;
1483 }
1484 }
1485#if COAP_Q_BLOCK_SUPPORT
1486 else if (coap_get_block_b(session, request, COAP_OPTION_Q_BLOCK2, &block)) {
1487 block_requested = 1;
1488 if (block.num != 0 && length <= (block.num << (block.szx + 4))) {
1489 coap_log_debug("Illegal block requested (%d > last = %" PRIuS ")\n",
1490 block.num,
1491 length >> (block.szx + 4));
1492 response->code = COAP_RESPONSE_CODE(400);
1493 goto error;
1494 }
1495 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK)) {
1496 set_block_mode_has_q(session->block_mode);
1497 block_opt = COAP_OPTION_Q_BLOCK2;
1498 }
1499 if (block.m == 0)
1500 single_request = 1;
1501 }
1502#endif /* COAP_Q_BLOCK_SUPPORT */
1503 }
1504
1506 coap_encode_var_safe(buf, sizeof(buf),
1507 media_type),
1508 buf);
1509
1510 if (maxage >= 0) {
1511 coap_update_option(response,
1513 coap_encode_var_safe(buf, sizeof(buf), maxage), buf);
1514 }
1515
1516 if (block_requested) {
1517 int res;
1518
1519 res = coap_write_block_b_opt(session, &block, block_opt, response,
1520 length);
1521
1522 switch (res) {
1523 case -2: /* illegal block (caught above) */
1524 response->code = COAP_RESPONSE_CODE(400);
1525 goto error;
1526 case -1: /* should really not happen */
1527 assert(0);
1528 /* fall through if assert is a no-op */
1529 case -3: /* cannot handle request */
1530 response->code = COAP_RESPONSE_CODE(500);
1531 goto error;
1532 default: /* everything is good */
1533 ;
1534 }
1535 }
1536
1537 /* add data body */
1538 if (request &&
1539 !coap_add_data_large_internal(session, request, response, resource,
1540 query, maxage, etag, length, data,
1541 release_func, NULL, app_ptr, single_request,
1542 request->code)) {
1543 response->code = COAP_RESPONSE_CODE(500);
1544 goto error_released;
1545 }
1546
1547 return 1;
1548
1549error:
1550 if (release_func) {
1551 coap_lock_callback(release_func(session, app_ptr));
1552 }
1553error_released:
1554#if COAP_ERROR_PHRASE_LENGTH > 0
1555 coap_add_data(response,
1556 strlen(coap_response_phrase(response->code)),
1557 (const unsigned char *)coap_response_phrase(response->code));
1558#endif /* COAP_ERROR_PHRASE_LENGTH > 0 */
1559 return 0;
1560}
1561#endif /* ! COAP_SERVER_SUPPORT */
1562
1563/*
1564 * return 1 if there is a future expire time, else 0.
1565 * update tim_rem with remaining value if return is 1.
1566 */
1567int
1569 coap_tick_t *tim_rem) {
1570 coap_lg_xmit_t *lg_xmit;
1571 coap_lg_xmit_t *q;
1572#if COAP_Q_BLOCK_SUPPORT
1574#else /* ! COAP_Q_BLOCK_SUPPORT */
1575 coap_tick_t idle_timeout = 8 * COAP_TICKS_PER_SECOND;
1576#endif /* ! COAP_Q_BLOCK_SUPPORT */
1577 coap_tick_t partial_timeout = COAP_MAX_TRANSMIT_WAIT_TICKS(session);
1578 int ret = 0;
1579
1580 *tim_rem = COAP_MAX_DELAY_TICKS;
1581
1582 LL_FOREACH_SAFE(session->lg_xmit, lg_xmit, q) {
1583 if (lg_xmit->last_all_sent) {
1584 if (lg_xmit->last_all_sent + idle_timeout <= now) {
1585 /* Expire this entry */
1586 LL_DELETE(session->lg_xmit, lg_xmit);
1587 coap_block_delete_lg_xmit(session, lg_xmit);
1588 } else {
1589 /* Delay until the lg_xmit needs to expire */
1590 if (*tim_rem > lg_xmit->last_all_sent + idle_timeout - now) {
1591 *tim_rem = lg_xmit->last_all_sent + idle_timeout - now;
1592 ret = 1;
1593 }
1594 }
1595 } else if (lg_xmit->last_sent) {
1596 if (lg_xmit->last_sent + partial_timeout <= now) {
1597 /* Expire this entry */
1598 coap_tick_t last_all_sent = lg_xmit->last_all_sent;
1599 int is_mcast = 0;
1600#if COAP_CLIENT_SUPPORT
1601 is_mcast = COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1602 coap_is_mcast(&lg_xmit->b.b1.upstream);
1603#endif /* COAP_CLIENT_SUPPORT */
1604 LL_DELETE(session->lg_xmit, lg_xmit);
1605
1606 coap_block_delete_lg_xmit(session, lg_xmit);
1607 if (!is_mcast && !last_all_sent)
1609 } else {
1610 /* Delay until the lg_xmit needs to expire */
1611 if (*tim_rem > lg_xmit->last_sent + partial_timeout - now) {
1612 *tim_rem = lg_xmit->last_sent + partial_timeout - now;
1613 ret = 1;
1614 }
1615 }
1616 }
1617 }
1618 return ret;
1619}
1620
1621#if COAP_CLIENT_SUPPORT
1622#if COAP_Q_BLOCK_SUPPORT
1623static coap_pdu_t *
1624coap_build_missing_pdu(coap_session_t *session, coap_lg_crcv_t *lg_crcv) {
1625 coap_pdu_t *pdu;
1626 coap_opt_filter_t drop_options;
1627 uint64_t token = STATE_TOKEN_FULL(lg_crcv->state_token, ++lg_crcv->retry_counter);
1628 uint8_t buf[8];
1629 size_t len = coap_encode_var_safe8(buf, sizeof(token), token);
1630
1631 memset(&drop_options, 0, sizeof(coap_opt_filter_t));
1635 pdu = coap_pdu_duplicate_lkd(lg_crcv->sent_pdu, session, len, buf,
1636 &drop_options, COAP_BOOL_FALSE);
1637 if (!pdu)
1638 return NULL;
1639 pdu->type = lg_crcv->last_type;
1640 return pdu;
1641}
1642
1643static void
1644coap_request_missing_q_block2(coap_session_t *session, coap_lg_crcv_t *lg_crcv) {
1645 uint8_t buf[8];
1646 uint32_t i;
1647 int block = -1; /* Last one seen */
1648 size_t sofar;
1649 size_t block_size;
1650 coap_pdu_t *pdu = NULL;
1651 int block_payload_set = -1;
1652
1653 if (session->block_mode & COAP_BLOCK_USE_M_Q_BLOCK) {
1654 /*
1655 * See if it is safe to use the single 'M' block variant of request
1656 *
1657 * If any blocks seen, then missing blocks are after range[0].end and
1658 * terminate on the last block or before range[1].begin if set.
1659 * If not defined or range[1].begin is in a different payload set then
1660 * safe to use M bit.
1661 */
1662 if (lg_crcv->rec_blocks.used &&
1663 (lg_crcv->rec_blocks.used < 2 ||
1664 ((lg_crcv->rec_blocks.range[0].end + 1) / COAP_MAX_PAYLOADS(session) !=
1665 (lg_crcv->rec_blocks.range[1].begin -1) / COAP_MAX_PAYLOADS(session)))) {
1666 block = lg_crcv->rec_blocks.range[0].end + 1;
1667 block_size = (size_t)1 << (lg_crcv->szx + 4);
1668 sofar = block * block_size;
1669 if (sofar < lg_crcv->total_len) {
1670 /* Ask for missing blocks */
1671 if (pdu == NULL) {
1672 pdu = coap_build_missing_pdu(session, lg_crcv);
1673 if (!pdu)
1674 return;
1675 }
1677 coap_encode_var_safe(buf, sizeof(buf),
1678 (block << 4) | (1 << 3) | lg_crcv->szx),
1679 buf);
1680 block_payload_set = block / COAP_MAX_PAYLOADS(session);
1681 goto send_it;
1682 }
1683 }
1684 }
1685 block = -1;
1686 for (i = 0; i < lg_crcv->rec_blocks.used; i++) {
1687 if (block < (int)lg_crcv->rec_blocks.range[i].begin &&
1688 lg_crcv->rec_blocks.range[i].begin != 0) {
1689 /* Ask for missing blocks */
1690 if (pdu == NULL) {
1691 pdu = coap_build_missing_pdu(session, lg_crcv);
1692 if (!pdu)
1693 continue;
1694 }
1695 block++;
1696 if (block_payload_set == -1)
1697 block_payload_set = block / COAP_MAX_PAYLOADS(session);
1698 for (; block < (int)lg_crcv->rec_blocks.range[i].begin &&
1699 block_payload_set == (block / COAP_MAX_PAYLOADS(session)); block++) {
1701 coap_encode_var_safe(buf, sizeof(buf),
1702 (block << 4) | (0 << 3) | lg_crcv->szx),
1703 buf);
1704 }
1705 }
1706 if (block < (int)lg_crcv->rec_blocks.range[i].end) {
1707 block = lg_crcv->rec_blocks.range[i].end;
1708 }
1709 }
1710 block_size = (size_t)1 << (lg_crcv->szx + 4);
1711 sofar = (block + 1) * block_size;
1712 if (sofar < lg_crcv->total_len) {
1713 /* Ask for trailing missing blocks */
1714 if (pdu == NULL) {
1715 pdu = coap_build_missing_pdu(session, lg_crcv);
1716 if (!pdu)
1717 return;
1718 }
1719 sofar = (lg_crcv->total_len + block_size - 1)/block_size;
1720 block++;
1721 if (block_payload_set == -1)
1722 block_payload_set = block / COAP_MAX_PAYLOADS(session);
1723 for (; block < (ssize_t)sofar &&
1724 block_payload_set == (block / COAP_MAX_PAYLOADS(session)); block++) {
1726 coap_encode_var_safe(buf, sizeof(buf),
1727 (block << 4) | (0 << 3) | lg_crcv->szx),
1728 buf);
1729 }
1730 }
1731send_it:
1732 if (pdu)
1733 coap_send_internal(session, pdu, NULL);
1734 lg_crcv->rec_blocks.retry++;
1735 if (block_payload_set != -1)
1736 lg_crcv->rec_blocks.processing_payload_set = block_payload_set;
1737 coap_ticks(&lg_crcv->rec_blocks.last_seen);
1738}
1739#endif /* COAP_Q_BLOCK_SUPPORT */
1740
1741/*
1742 * return 1 if there is a future expire time, else 0.
1743 * update tim_rem with remaining value if return is 1.
1744 */
1745int
1746coap_block_check_lg_crcv_timeouts(coap_session_t *session, coap_tick_t now,
1747 coap_tick_t *tim_rem) {
1748 coap_lg_crcv_t *lg_crcv;
1749 coap_lg_crcv_t *q;
1750 coap_tick_t partial_timeout;
1751#if COAP_Q_BLOCK_SUPPORT
1752 coap_tick_t receive_timeout = COAP_NON_RECEIVE_TIMEOUT_TICKS(session);
1753#endif /* COAP_Q_BLOCK_SUPPORT */
1754 int ret = 0;
1755
1756 *tim_rem = COAP_MAX_DELAY_TICKS;
1757#if COAP_Q_BLOCK_SUPPORT
1758 if (COAP_PROTO_NOT_RELIABLE(session->proto) &&
1759 session->block_mode & COAP_BLOCK_HAS_Q_BLOCK)
1760 partial_timeout = COAP_NON_PARTIAL_TIMEOUT_TICKS(session);
1761 else
1762#endif /* COAP_Q_BLOCK_SUPPORT */
1763 partial_timeout = COAP_MAX_TRANSMIT_WAIT_TICKS(session);
1764
1765 LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, q) {
1766 if (COAP_PROTO_RELIABLE(session->proto) || lg_crcv->last_type != COAP_MESSAGE_NON)
1767 goto check_expire;
1768
1769#if COAP_Q_BLOCK_SUPPORT
1770 if (lg_crcv->block_option == COAP_OPTION_Q_BLOCK2 && lg_crcv->rec_blocks.used) {
1771 size_t scaled_timeout = receive_timeout *
1772 ((size_t)1 << lg_crcv->rec_blocks.retry);
1773
1774 if (lg_crcv->rec_blocks.retry >= COAP_NON_MAX_RETRANSMIT(session)) {
1775 /* Done NON_MAX_RETRANSMIT retries */
1776 coap_handle_nack(session, lg_crcv->sent_pdu,
1777 COAP_NACK_TOO_MANY_RETRIES, lg_crcv->sent_pdu->mid);
1778 goto expire;
1779 }
1780 if (lg_crcv->rec_blocks.last_seen + scaled_timeout <= now) {
1781 coap_log_debug("** %s: lg_crcv %p timeout\n",
1782 coap_session_str(session), (void *)lg_crcv);
1783 coap_request_missing_q_block2(session, lg_crcv);
1784 } else {
1785 if (*tim_rem > lg_crcv->rec_blocks.last_seen + scaled_timeout - now) {
1786 *tim_rem = lg_crcv->rec_blocks.last_seen + scaled_timeout - now;
1787 ret = 1;
1788 }
1789 }
1790 }
1791#endif /* COAP_Q_BLOCK_SUPPORT */
1792 /* Used for Block2 and Q-Block2 */
1793check_expire:
1794 if (!lg_crcv->observe_set && lg_crcv->last_used &&
1795 lg_crcv->last_used + partial_timeout <= now) {
1796#if COAP_Q_BLOCK_SUPPORT
1797expire:
1798#endif /* COAP_Q_BLOCK_SUPPORT */
1799 /* Expire this entry */
1800 LL_DELETE(session->lg_crcv, lg_crcv);
1801 coap_block_delete_lg_crcv(session, lg_crcv);
1802 } else if (!lg_crcv->observe_set && lg_crcv->last_used) {
1803 /* Delay until the lg_crcv needs to expire */
1804 if (*tim_rem > lg_crcv->last_used + partial_timeout - now) {
1805 *tim_rem = lg_crcv->last_used + partial_timeout - now;
1806 ret = 1;
1807 }
1808 }
1809 }
1810 return ret;
1811}
1812#endif /* COAP_CLIENT_SUPPORT */
1813
1814#if COAP_SERVER_SUPPORT
1815#if COAP_Q_BLOCK_SUPPORT
1816static coap_pdu_t *
1817pdu_408_build(coap_session_t *session, coap_lg_srcv_t *lg_srcv) {
1818 coap_pdu_t *pdu;
1819 uint8_t buf[4];
1820
1822 COAP_RESPONSE_CODE(408),
1823 coap_new_message_id_lkd(session),
1825 if (!pdu)
1826 return NULL;
1827 if (lg_srcv->last_token)
1828 coap_add_token(pdu, lg_srcv->last_token->length, lg_srcv->last_token->s);
1830 coap_encode_var_safe(buf, sizeof(buf),
1832 buf);
1833 pdu->token[pdu->used_size++] = COAP_PAYLOAD_START;
1834 pdu->data = pdu->token + pdu->used_size;
1835 return pdu;
1836}
1837
1838static int
1839add_408_block(coap_pdu_t *pdu, uint32_t block) {
1840 size_t len;
1841 uint8_t val[8];
1842
1843 assert(block < (1U << 20));
1844 coap_log_debug("Q-Block1: Requesting missing block %" PRIu32 "\n", block);
1845
1846 if (block >= (1U << 20)) {
1847 return 0;
1848 } else if (block < 24) {
1849 len = 1;
1850 val[0] = (uint8_t)block;
1851 } else if (block < 0x100) {
1852 len = 2;
1853 val[0] = 24;
1854 val[1] = (uint8_t)block;
1855 } else if (block < 0x10000) {
1856 len = 3;
1857 val[0] = 25;
1858 val[1] = (uint8_t)((block >> 8) & 0xff);
1859 val[2] = (uint8_t)(block & 0xff);
1860 } else { /* Largest block number is 2^^20 - 1 */
1861 len = 5;
1862 val[0] = 26;
1863 val[1] = (uint8_t)((block >> 24) & 0xff); /* Will be 0 */
1864 val[2] = (uint8_t)((block >> 16) & 0xff);
1865 val[3] = (uint8_t)((block >> 8) & 0xff);
1866 val[4] = (uint8_t)(block & 0xff);
1867 }
1868 if (coap_pdu_check_resize(pdu, pdu->used_size + len)) {
1869 memcpy(&pdu->token[pdu->used_size], val, len);
1870 pdu->used_size += len;
1871 return 1;
1872 }
1873 return 0;
1874}
1875#endif /* COAP_Q_BLOCK_SUPPORT */
1876#endif /* COAP_SERVER_SUPPORT */
1877
1878static int
1879check_if_received_block(coap_rblock_t *rec_blocks, uint32_t block_num) {
1880 uint32_t i;
1881
1882 for (i = 0; i < rec_blocks->used; i++) {
1883 if (block_num < rec_blocks->range[i].begin)
1884 return 0;
1885 if (block_num <= rec_blocks->range[i].end)
1886 return 1;
1887 }
1888 return 0;
1889}
1890
1891#if COAP_SERVER_SUPPORT
1892static int
1893check_if_next_block(coap_rblock_t *rec_blocks, uint32_t block_num) {
1894 if (rec_blocks->used == 0) {
1895 return block_num == 0 ? 1 : 0;
1896 }
1897 if (rec_blocks->range[rec_blocks->used-1].end + 1 == block_num)
1898 return 1;
1899
1900 return 0;
1901}
1902#endif /* COAP_SERVER_SUPPORT */
1903
1904static int
1906 uint32_t i;
1907 uint32_t block = 0;
1908
1909 if (rec_blocks->total_blocks == 0) {
1910 /* Not seen block with More bit unset yet */
1911 return 0;
1912 }
1913
1914 for (i = 0; i < rec_blocks->used; i++) {
1915 if (block < rec_blocks->range[i].begin)
1916 return 0;
1917 if (block < rec_blocks->range[i].end)
1918 block = rec_blocks->range[i].end;
1919 }
1920 return 1;
1921}
1922
1923#if COAP_CLIENT_SUPPORT
1924#if COAP_Q_BLOCK_SUPPORT
1925static int
1926check_all_blocks_in_for_payload_set(coap_session_t *session,
1927 coap_rblock_t *rec_blocks) {
1928 if (rec_blocks->used &&
1929 (rec_blocks->range[0].end + 1) / COAP_MAX_PAYLOADS(session) >
1930 rec_blocks->processing_payload_set)
1931 return 1;
1932 return 0;
1933}
1934
1935static int
1936check_any_blocks_next_payload_set(coap_session_t *session,
1937 coap_rblock_t *rec_blocks) {
1938 if (rec_blocks->used > 1 &&
1939 rec_blocks->range[1].begin / COAP_MAX_PAYLOADS(session) ==
1940 rec_blocks->processing_payload_set)
1941 return 1;
1942 return 0;
1943}
1944#endif /* COAP_Q_BLOCK_SUPPORT */
1945#endif /* COAP_CLIENT_SUPPORT */
1946
1947#if COAP_SERVER_SUPPORT
1948#if COAP_Q_BLOCK_SUPPORT
1949/*
1950 * To reduce the number of retransmitted missing requests, if the request comes
1951 * from a inc_to_block in the same PAYLOAD_SET as the last time, the request is not
1952 * retransmitted, unless this is from a timeout request when inc_to_block is the
1953 * the last expected block based on SIZE1, not the last received block.
1954 *
1955 * If lg_srcv->rec_blocks.used == 0, then no blocks have been received (not expected).
1956 * If lg_srcv->rec_blocks.used == 1 and lg_srcv->rec_blocks.range[0].begin == 0,
1957 * then no blocks are missing, but the next block may be missing (picked up when
1958 * there is a timeout request).
1959 * If lg_srcv->rec_blocks.used > 1, then there are missing blocks.
1960 *
1961 * The final PAYLOAD_SET is a special case as it can have 1 to MAX_PAYLOADS -1 blocks.
1962 *
1963 * The first PAYLOAD_SET that has missing blocks is reported in the 4.08 code, and
1964 * is triggered when inc_to_block is in the next PAYLOAD_SET (unless in final).
1965 *
1966 * It is not safe to report missing blocks in the same PAYLOAD_SET as inc_to_block as
1967 * the individual blocks may arrive in a random order (generates a lot of duplicate
1968 * blocks).
1969 *
1970 * However, if some missing blocks, but the last 2 blocks of a PAYLOAD_SET have been
1971 * received, then immediately trigger the 4.08 missing blocks request (not suggested
1972 * in RFC9177) as this considerably reduces the risk that the penultimate block is in
1973 * flight, but received in the wrong order and hence requesting a duplicate
1974 * re-transmission.
1975 */
1976static int
1977coap_request_missing_q_block1(coap_session_t *session, coap_lg_srcv_t *lg_srcv,
1978 uint32_t inc_to_block) {
1979 uint32_t i;
1980 int32_t block = -1; /* Last one seen */
1981 uint32_t block_size = (uint32_t)1 << (lg_srcv->szx + 4);
1982 uint32_t first_missing;
1983 uint32_t missing_payload;
1984 uint32_t last_payload_block;
1985 coap_pdu_t *pdu = NULL;
1986 /* Block number starts at 0 */
1987 uint32_t end_block = ((uint32_t)lg_srcv->total_len + block_size - 1) / block_size - 1;
1988 int count = 0;
1989
1990 if (COAP_MAX_PAYLOADS(session) == 0 ||
1991 (int32_t)(inc_to_block / COAP_MAX_PAYLOADS(session)) == lg_srcv->r_m_payload_set)
1992 return 0;
1993
1994 if (inc_to_block != end_block) {
1995 lg_srcv->r_m_payload_set = inc_to_block / COAP_MAX_PAYLOADS(session);
1996 }
1997
1998 if (lg_srcv->rec_blocks.range[0].begin != 0) {
1999 first_missing = 0;
2000 } else {
2001 first_missing = lg_srcv->rec_blocks.range[0].end + 1;
2002 }
2003 if (first_missing > end_block)
2004 return 0;
2005 missing_payload = first_missing / COAP_MAX_PAYLOADS(session);
2006 last_payload_block = (missing_payload + 1) * COAP_MAX_PAYLOADS(session) - 1;
2007 if (inc_to_block != end_block && inc_to_block > last_payload_block) {
2008 inc_to_block = last_payload_block;
2009 }
2010 /* Ask for the missing blocks */
2011 block = -1;
2012 for (i = 0; i < lg_srcv->rec_blocks.used; i++) {
2013 if (block < (int32_t)lg_srcv->rec_blocks.range[i].begin &&
2014 lg_srcv->rec_blocks.range[i].begin != 0) {
2015 /* Report on missing blocks */
2016 if (pdu == NULL) {
2017 pdu = pdu_408_build(session, lg_srcv);
2018 if (!pdu)
2019 continue;
2020 }
2021 block++;
2022 for (; block < (int32_t)lg_srcv->rec_blocks.range[i].begin; block++) {
2023 if (!add_408_block(pdu, block)) {
2024 break;
2025 }
2026 count++;
2027 }
2028 }
2029 if (block < (int32_t)lg_srcv->rec_blocks.range[i].end) {
2030 block = lg_srcv->rec_blocks.range[i].end;
2031 }
2032 }
2033 if (inc_to_block == end_block && block < (int32_t)inc_to_block) {
2034 /* Need to fill to the end */
2035 if (pdu == NULL) {
2036 pdu = pdu_408_build(session, lg_srcv);
2037 if (!pdu)
2038 goto retry;
2039 }
2040 block++;
2041 for (; block <= (int32_t)inc_to_block && count < COAP_MAX_PAYLOADS(session); block++) {
2042 if (!add_408_block(pdu, block)) {
2043 break;
2044 }
2045 count++;
2046 }
2047 }
2048 if (pdu)
2049 coap_send_internal(session, pdu, NULL);
2050retry:
2051 lg_srcv->rec_blocks.retry++;
2052 coap_ticks(&lg_srcv->rec_blocks.last_seen);
2053 return 1;
2054}
2055#endif /* COAP_Q_BLOCK_SUPPORT */
2056
2057/*
2058 * return 1 if there is a future expire time, else 0.
2059 * update tim_rem with remaining value if return is 1.
2060 */
2061int
2062coap_block_check_lg_srcv_timeouts(coap_session_t *session, coap_tick_t now,
2063 coap_tick_t *tim_rem) {
2064 coap_lg_srcv_t *lg_srcv;
2065 coap_lg_srcv_t *q;
2066 coap_tick_t partial_timeout;
2067#if COAP_Q_BLOCK_SUPPORT
2068 coap_tick_t receive_timeout = COAP_NON_RECEIVE_TIMEOUT_TICKS(session);
2069#endif /* COAP_Q_BLOCK_SUPPORT */
2070 int ret = 0;
2071
2072 *tim_rem = COAP_MAX_DELAY_TICKS;
2073#if COAP_Q_BLOCK_SUPPORT
2074 if (COAP_PROTO_NOT_RELIABLE(session->proto) &&
2075 session->block_mode & COAP_BLOCK_HAS_Q_BLOCK)
2076 partial_timeout = COAP_NON_PARTIAL_TIMEOUT_TICKS(session);
2077 else
2078#endif /* COAP_Q_BLOCK_SUPPORT */
2079 partial_timeout = COAP_MAX_TRANSMIT_WAIT_TICKS(session);
2080
2081 LL_FOREACH_SAFE(session->lg_srcv, lg_srcv, q) {
2082 if (lg_srcv->dont_timeout) {
2083 /* Not safe to timeout at present */
2084 continue;
2085 }
2086 if (COAP_PROTO_RELIABLE(session->proto) || lg_srcv->block_option != COAP_OPTION_Q_BLOCK1)
2087 goto check_expire;
2088
2089#if COAP_Q_BLOCK_SUPPORT
2090 if (lg_srcv->block_option == COAP_OPTION_Q_BLOCK1 && lg_srcv->rec_blocks.used) {
2091 size_t scaled_timeout = receive_timeout *
2092 ((size_t)1 << lg_srcv->rec_blocks.retry);
2093
2094 if (lg_srcv->rec_blocks.retry >= COAP_NON_MAX_RETRANSMIT(session)) {
2095 /* Done NON_MAX_RETRANSMIT retries */
2096 goto expire;
2097 }
2098 if (lg_srcv->rec_blocks.last_seen + scaled_timeout <= now) {
2099 uint32_t block_size = (size_t)1 << (lg_srcv->szx + 4);
2100 coap_log_debug("** %s: lg_srcv %p timeout\n",
2101 coap_session_str(session), (void *)lg_srcv);
2102 if (!coap_request_missing_q_block1(session, lg_srcv,
2103 ((uint32_t)lg_srcv->total_len + block_size - 1) / block_size - 1))
2104 goto expire;
2105 }
2106 if (*tim_rem > lg_srcv->rec_blocks.last_seen + scaled_timeout - now) {
2107 *tim_rem = lg_srcv->rec_blocks.last_seen + scaled_timeout - now;
2108 ret = 1;
2109 }
2110 }
2111#endif /* COAP_Q_BLOCK_SUPPORT */
2112 /* Used for Block1 and Q-Block1 */
2113check_expire:
2114 if (lg_srcv->no_more_seen)
2115 partial_timeout = 10 * COAP_TICKS_PER_SECOND;
2116 if (lg_srcv->last_used && lg_srcv->last_used + partial_timeout <= now) {
2117#if COAP_Q_BLOCK_SUPPORT
2118expire:
2119#endif /* COAP_Q_BLOCK_SUPPORT */
2120 /* Expire this entry */
2121 if (lg_srcv->no_more_seen && lg_srcv->block_option == COAP_OPTION_BLOCK1) {
2122 /*
2123 * Need to send a separate 4.08 to indicate missing blocks
2124 * Using NON is permissible as per
2125 * https://datatracker.ietf.org/doc/html/rfc7252#section-5.2.3
2126 */
2127 coap_pdu_t *pdu;
2128
2130 COAP_RESPONSE_CODE(408),
2131 coap_new_message_id_lkd(session),
2133 if (pdu) {
2134 if (lg_srcv->last_token)
2135 coap_add_token(pdu, lg_srcv->last_token->length, lg_srcv->last_token->s);
2136 coap_add_data(pdu, sizeof("Missing interim block")-1,
2137 (const uint8_t *)"Missing interim block");
2138 coap_send_internal(session, pdu, NULL);
2139 }
2140 }
2141 LL_DELETE(session->lg_srcv, lg_srcv);
2142 coap_block_delete_lg_srcv(session, lg_srcv);
2143 } else if (lg_srcv->last_used) {
2144 /* Delay until the lg_srcv needs to expire */
2145 if (*tim_rem > lg_srcv->last_used + partial_timeout - now) {
2146 *tim_rem = lg_srcv->last_used + partial_timeout - now;
2147 ret = 1;
2148 }
2149 }
2150 }
2151 return ret;
2152}
2153#endif /* COAP_SERVER_SUPPORT */
2154
2155#if COAP_Q_BLOCK_SUPPORT
2156static coap_pdu_t *
2157coap_next_block_to_send(coap_session_t *session,
2158 coap_lg_xmit_t *lg_xmit,
2159 coap_block_b_t *block,
2160 coap_pdu_t *pdu,
2161 uint32_t delayqueue_cnt,
2162 int is_first) {
2163 const uint8_t *ptoken;
2164 uint8_t ltoken[8];
2165 size_t ltoken_length;
2166 coap_pdu_t *block_pdu = NULL;
2167 uint64_t token;
2168 coap_opt_filter_t drop_options;
2169 size_t chunk = ((size_t)1 << (lg_xmit->blk_size + 4));
2170 size_t offset;
2171 uint8_t buf[8];
2172 int need_block = 0;
2173
2174 if (COAP_MAX_PAYLOADS(session) == 0)
2175 return NULL;
2176 /* Get the next block to transmit (which could be a retry */
2177 block->num = lg_xmit->send_blocks.range[0].begin;
2178
2179 offset = block->num * chunk;
2180 block->m = offset + chunk < lg_xmit->data_info->length;
2181
2182 if (!(block->m || lg_xmit->send_blocks.used) && COAP_MAX_PAYLOADS(session)) {
2183 return NULL;
2184 }
2185 if (is_first &&
2186 ((pdu->type == COAP_MESSAGE_ACK && lg_xmit->option == COAP_OPTION_Q_BLOCK2) ||
2187 (pdu->type == COAP_MESSAGE_CON && delayqueue_cnt < COAP_NSTART(session)))) {
2188 need_block = 1;
2189 }
2190 if (COAP_PROTO_RELIABLE(session->proto)) {
2191 need_block = 1;
2192 }
2193
2194 if (need_block ||
2195 (pdu->type == COAP_MESSAGE_NON &&
2196 (lg_xmit->send_blocks.used > 1 ||
2197 (block->num % COAP_MAX_PAYLOADS(session) != 0) ||
2198 is_first))) {
2199 if (!is_first && block->num % COAP_MAX_PAYLOADS(session) == 0 &&
2200 lg_xmit->send_blocks.used == 1 && !COAP_PROTO_RELIABLE(session->proto)) {
2201 coap_log_debug("Q-Block: Stopping at block %d\n", block->num);
2202 } else {
2203 /*
2204 * Allocate next block pdu if there is headroom and if one of
2205 * NON and more in MAX_PAYLOADS
2206 * CON and NSTART allows it (based on number in delayqueue)
2207 * Reliable transport
2208 */
2209 coap_log_debug("Q-Block: %s block %d\n", is_first ? "First" : "Next", block->num);
2210 if (COAP_PDU_IS_RESPONSE(pdu)) {
2211 ptoken = pdu->actual_token.s;
2212 ltoken_length = pdu->actual_token.length;
2213 } else {
2214 token = STATE_TOKEN_FULL(lg_xmit->b.b1.state_token,++lg_xmit->b.b1.count);
2215 ltoken_length = coap_encode_var_safe8(ltoken, sizeof(token), token);
2216 ptoken = ltoken;
2217 }
2218
2219 memset(&drop_options, 0, sizeof(coap_opt_filter_t));
2220 coap_option_filter_set(&drop_options, lg_xmit->option);
2221 block_pdu = coap_pdu_duplicate_lkd(pdu, session,
2222 ltoken_length,
2223 ptoken, &drop_options, COAP_BOOL_FALSE);
2224 if (block_pdu->type == COAP_MESSAGE_ACK)
2225 block_pdu->type = COAP_MESSAGE_CON;
2226
2227 if (!coap_update_option(block_pdu, lg_xmit->option,
2229 sizeof(buf),
2230 ((block->num) << 4) |
2231 (block->m << 3) |
2232 block->szx),
2233 buf)) {
2234 coap_log_warn("Internal update issue option\n");
2235 coap_delete_pdu_lkd(block_pdu);
2236 return NULL;
2237 }
2238 }
2239 }
2240 return block_pdu;
2241}
2242
2243/*
2244 * pdu is always released before return IF COAP_SEND_INC_PDU
2245 */
2247coap_send_q_blocks(coap_session_t *session,
2248 coap_lg_xmit_t *lg_xmit,
2249 coap_block_b_t block,
2250 coap_pdu_t *pdu,
2251 coap_send_pdu_t send_pdu) {
2252 coap_pdu_t *block_pdu = NULL; /* The next block to send after any initial PDU */
2254 uint32_t delayqueue_cnt = 0;
2255 coap_block_b_t l_block;
2256 int is_non;
2257
2258 if (!pdu)
2259 return COAP_INVALID_MID;
2260
2261 is_non = pdu->type == COAP_MESSAGE_NON ? 1 : 0;
2262
2263 if (!lg_xmit || session->is_rate_limiting) {
2264 if (send_pdu == COAP_SEND_INC_PDU) {
2265 if (lg_xmit &&
2266 (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &l_block) ||
2267 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &l_block))) {
2268 mid = coap_send_internal(session, pdu, NULL);
2269 if (mid != COAP_INVALID_MID) {
2270 blocks_delete_entry(&lg_xmit->send_blocks, l_block.num);
2271 }
2272 } else {
2273 return coap_send_internal(session, pdu, NULL);
2274 }
2275 }
2276 return COAP_INVALID_MID;
2277 }
2278
2279 if (pdu->type == COAP_MESSAGE_CON) {
2280 coap_queue_t *delayqueue;
2281
2282 delayqueue_cnt = session->con_active +
2283 (send_pdu == COAP_SEND_INC_PDU ? 1 : 0);
2284 LL_FOREACH(session->delayqueue, delayqueue) {
2285 delayqueue_cnt++;
2286 }
2287 }
2288 pdu->lg_xmit = lg_xmit;
2289
2290 /* Send initial pdu (which deletes 'pdu') */
2291 if (send_pdu == COAP_SEND_INC_PDU) {
2292 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &l_block) ||
2293 coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &l_block)) {
2294 mid = coap_send_internal(session, pdu, NULL);
2295 if (mid != COAP_INVALID_MID) {
2296 blocks_delete_entry(&lg_xmit->send_blocks, l_block.num);
2297 }
2298 } else {
2299 mid = coap_send_internal(session, pdu, NULL);
2300 }
2301 if (mid == COAP_INVALID_MID) {
2302 /* Not expected, underlying issue somewhere */
2303 coap_delete_pdu_lkd(block_pdu);
2304 return COAP_INVALID_MID;
2305 }
2306 coap_ticks(&lg_xmit->last_sent);
2307 }
2308 /* Unsafe to use pdu in later code */
2309
2311 l_block = block;
2312 block_pdu = coap_next_block_to_send(session, lg_xmit, &l_block, pdu, delayqueue_cnt, 1);
2313 if (block_pdu) {
2314 block = l_block;
2315 }
2316
2317 while (block_pdu && lg_xmit->send_blocks.used) {
2318 coap_pdu_t *t_pdu = NULL;
2319
2320 if (lg_xmit->data_info->get_func) {
2321#if COAP_CONSTRAINED_STACK
2322 /* Protected by global_lock if needed */
2323 static uint8_t l_data[1024];
2324#else /* ! COAP_CONSTRAINED_STACK */
2325 uint8_t l_data[1024];
2326#endif /* ! COAP_CONSTRAINED_STACK */
2327 size_t l_length;
2328 size_t chunk = ((size_t)1 << (lg_xmit->blk_size + 4));
2329
2330 (void)chunk;
2331 assert(chunk <= 1024);
2332 if (lg_xmit->data_info->get_func(session, chunk,
2333 block.num * chunk, l_data, &l_length,
2334 lg_xmit->data_info->app_ptr)) {
2335 if (!coap_add_data(block_pdu, l_length, l_data)) {
2336 coap_log_warn("Internal update issue data (1)\n");
2337 coap_delete_pdu_lkd(block_pdu);
2338 block_pdu = NULL;
2339 break;
2340 }
2341 }
2342 } else {
2343 if (!coap_add_block(block_pdu,
2344 lg_xmit->data_info->length,
2345 lg_xmit->data_info->data,
2346 block.num,
2347 block.szx)) {
2348 coap_log_warn("Internal update issue data (2)\n");
2349 coap_delete_pdu_lkd(block_pdu);
2350 block_pdu = NULL;
2351 break;
2352 }
2353 }
2354 if (COAP_PDU_IS_RESPONSE(block_pdu)) {
2355 lg_xmit->last_block = block.num;
2356 }
2357 /* This block will now be transmitted */
2358 blocks_delete_entry(&lg_xmit->send_blocks, block.num);
2359
2360 if (block_pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) {
2361 /* Get the next block to transmit (which could be a retry) */
2362 l_block = block;
2363 t_pdu = coap_next_block_to_send(session, lg_xmit, &l_block, block_pdu, delayqueue_cnt, 0);
2364 if (t_pdu) {
2365 block = l_block;
2366 }
2367 }
2368
2369 mid = coap_send_internal(session, block_pdu, NULL);
2370 if (mid == COAP_INVALID_MID) {
2371 /* Need to resent this one ... */
2372 blocks_add_entry(&lg_xmit->send_blocks, block.num, block.m);
2373 /* Not expected, underlying issue somewhere */
2374 coap_lg_xmit_release_lkd(session, lg_xmit);
2375 coap_delete_pdu_lkd(t_pdu);
2376 return COAP_INVALID_MID;
2377 }
2378 coap_ticks(&lg_xmit->last_sent);
2379 block_pdu = t_pdu;
2380 }
2381 if (is_non) {
2382 coap_log_debug("Q-Block: Current MAX_PAYLOAD sent\n");
2383 }
2384 coap_delete_pdu_lkd(block_pdu);
2385 if (!block.m) {
2386 lg_xmit->last_payload = 0;
2387 coap_ticks(&lg_xmit->last_all_sent);
2388 } else
2389 coap_ticks(&lg_xmit->last_payload);
2390 coap_lg_xmit_release_lkd(session, lg_xmit);
2391 return mid;
2392}
2393
2394#if COAP_CLIENT_SUPPORT
2395/*
2396 * Return 1 if there is a future expire time, else 0.
2397 * Update tim_rem with remaining value if return is 1.
2398 */
2399int
2400coap_block_check_q_block1_xmit(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem) {
2401 coap_lg_xmit_t *lg_xmit;
2402 coap_lg_xmit_t *q;
2403 coap_tick_t timed_out;
2404 int ret = 0;
2405
2406 *tim_rem = COAP_MAX_DELAY_TICKS;
2407 LL_FOREACH_SAFE(session->lg_xmit, lg_xmit, q) {
2408 coap_tick_t non_timeout = lg_xmit->non_timeout_random_ticks;
2409
2410 if (lg_xmit->sent_pdu->type != COAP_MESSAGE_NON)
2411 continue;
2412 if (now <= non_timeout) {
2413 /* Too early in the startup cycle to have an accurate response */
2414 *tim_rem = non_timeout - now;
2415 return 1;
2416 }
2417 timed_out = now - non_timeout;
2418
2419 if (lg_xmit->last_payload && lg_xmit->send_blocks.used) {
2420 if (lg_xmit->last_payload <= timed_out) {
2421 /* Send off the next MAX_PAYLOAD set */
2422 coap_block_b_t block;
2423 size_t chunk = (size_t)1 << (lg_xmit->blk_size + 4);
2424 size_t offset;
2425
2426 coap_log_debug("Q-Block: Timeout - start next MAX_PAYLOADS_SET\n");
2427 memset(&block, 0, sizeof(block));
2428 block.num = lg_xmit->send_blocks.range[0].begin;
2429 offset = block.num * chunk;
2430 block.m = offset + chunk < lg_xmit->data_info->length;
2431 block.szx = lg_xmit->blk_size;
2432 coap_send_q_blocks(session, lg_xmit, block, lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
2433 if (*tim_rem > non_timeout) {
2434 *tim_rem = non_timeout;
2435 ret = 1;
2436 }
2437 } else {
2438 /* Delay until the next MAX_PAYLOAD needs to be sent off */
2439 if (*tim_rem > lg_xmit->last_payload - timed_out) {
2440 *tim_rem = lg_xmit->last_payload - timed_out;
2441 ret = 1;
2442 }
2443 }
2444 } else if (lg_xmit->last_all_sent) {
2445 non_timeout = COAP_NON_TIMEOUT_TICKS(session);
2446 if (lg_xmit->last_all_sent + COAP_LG_XMIT_TXT_SCALAR * non_timeout <= now) {
2447 /* Expire this entry */
2448 LL_DELETE(session->lg_xmit, lg_xmit);
2449 coap_block_delete_lg_xmit(session, lg_xmit);
2450 } else {
2451 /* Delay until the lg_xmit needs to expire */
2452 if (*tim_rem > lg_xmit->last_all_sent + COAP_LG_XMIT_TXT_SCALAR * non_timeout - now) {
2453 *tim_rem = lg_xmit->last_all_sent + COAP_LG_XMIT_TXT_SCALAR * non_timeout - now;
2454 ret = 1;
2455 }
2456 }
2457 }
2458 }
2459 return ret;
2460}
2461#endif /* COAP_CLIENT_SUPPORT */
2462
2463#if COAP_SERVER_SUPPORT
2464/*
2465 * Return 1 if there is a future expire time, else 0.
2466 * Update tim_rem with remaining value if return is 1.
2467 */
2468int
2469coap_block_check_q_block2_xmit(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem) {
2470 coap_lg_xmit_t *lg_xmit;
2471 coap_lg_xmit_t *q;
2472 coap_tick_t timed_out;
2473 int ret = 0;
2474
2475 *tim_rem = (coap_tick_t)-1;
2476 LL_FOREACH_SAFE(session->lg_xmit, lg_xmit, q) {
2477 coap_tick_t non_timeout = lg_xmit->non_timeout_random_ticks;
2478
2479 if (now <= non_timeout) {
2480 /* Too early in the startup cycle to have an accurate response */
2481 *tim_rem = non_timeout - now;
2482 return 1;
2483 }
2484 timed_out = now - non_timeout;
2485
2486 if (lg_xmit->last_payload && lg_xmit->send_blocks.used) {
2487 if (lg_xmit->last_payload <= timed_out) {
2488 /* Send off the next MAX_PAYLOAD set */
2489 coap_block_b_t block;
2490 size_t chunk = (size_t)1 << (lg_xmit->blk_size + 4);
2491 size_t offset;
2492
2493 memset(&block, 0, sizeof(block));
2494 block.num = lg_xmit->send_blocks.range[0].begin;
2495 offset = block.num * chunk;
2496 block.m = offset + chunk < lg_xmit->data_info->length;
2497 block.szx = lg_xmit->blk_size;
2498 if (block.num == (uint32_t)lg_xmit->last_block)
2499 coap_send_q_blocks(session, lg_xmit, block, lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
2500 if (*tim_rem > non_timeout) {
2501 *tim_rem = non_timeout;
2502 ret = 1;
2503 }
2504 } else {
2505 /* Delay until the next MAX_PAYLOAD needs to be sent off */
2506 if (*tim_rem > lg_xmit->last_payload - timed_out) {
2507 *tim_rem = lg_xmit->last_payload - timed_out;
2508 ret = 1;
2509 }
2510 }
2511 } else if (lg_xmit->last_all_sent) {
2512 non_timeout = COAP_NON_TIMEOUT_TICKS(session);
2513 if (lg_xmit->last_all_sent + 4 * non_timeout <= now) {
2514 /* Expire this entry */
2515 LL_DELETE(session->lg_xmit, lg_xmit);
2516 coap_block_delete_lg_xmit(session, lg_xmit);
2517 } else {
2518 /* Delay until the lg_xmit needs to expire */
2519 if (*tim_rem > lg_xmit->last_all_sent + 4 * non_timeout - now) {
2520 *tim_rem = lg_xmit->last_all_sent + 4 * non_timeout - now;
2521 ret = 1;
2522 }
2523 }
2524 }
2525 }
2526 return ret;
2527}
2528#endif /* COAP_SERVER_SUPPORT */
2529#endif /* COAP_Q_BLOCK_SUPPORT */
2530
2531#if COAP_CLIENT_SUPPORT
2532/*
2533 * If Observe = 0, save the token away and return NULL
2534 * Else If Observe = 1, return the saved token for this block
2535 * Else, return NULL
2536 */
2537static coap_bin_const_t *
2538track_fetch_observe(coap_pdu_t *pdu, coap_lg_crcv_t *lg_crcv,
2539 uint32_t block_num, coap_bin_const_t *token) {
2540 /* Need to handle Observe for large FETCH */
2541 coap_opt_iterator_t opt_iter;
2543 &opt_iter);
2544
2545 if (opt && lg_crcv) {
2546 int observe_action = -1;
2547 coap_bin_const_t **tmp;
2548
2549 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
2550 coap_opt_length(opt));
2551 if (observe_action == COAP_OBSERVE_ESTABLISH) {
2552 /* Save the token in lg_crcv */
2553 if (lg_crcv->obs_token_cnt <= block_num) {
2554 size_t i;
2555
2556 tmp = coap_realloc_type(COAP_STRING, lg_crcv->obs_token,
2557 (block_num + 1) * sizeof(lg_crcv->obs_token[0]));
2558 if (tmp == NULL)
2559 return NULL;
2560 lg_crcv->obs_token = tmp;
2561 for (i = lg_crcv->obs_token_cnt; i < block_num + 1; i++) {
2562 lg_crcv->obs_token[i] = NULL;
2563 }
2564 }
2565 coap_delete_bin_const(lg_crcv->obs_token[block_num]);
2566
2567 if (lg_crcv->obs_token_cnt <= block_num)
2568 lg_crcv->obs_token_cnt = block_num + 1;
2569 lg_crcv->obs_token[block_num] = coap_new_bin_const(token->s,
2570 token->length);
2571 if (lg_crcv->obs_token[block_num] == NULL)
2572 return NULL;
2573 } else if (observe_action == COAP_OBSERVE_CANCEL) {
2574 /* Use the token in lg_crcv */
2575 if (block_num < lg_crcv->obs_token_cnt) {
2576 return lg_crcv->obs_token[block_num];
2577 }
2578 }
2579 }
2580 return NULL;
2581}
2582
2583#if COAP_Q_BLOCK_SUPPORT
2585coap_send_q_block1(coap_session_t *session,
2586 coap_block_b_t block,
2587 coap_pdu_t *request,
2588 coap_send_pdu_t send_request) {
2589 /* Need to send up to MAX_PAYLOAD blocks if this is a Q_BLOCK1 */
2590 coap_lg_xmit_t *lg_xmit;
2591 uint64_t token_match =
2593 request->actual_token.length));
2594
2595 LL_FOREACH(session->lg_xmit, lg_xmit) {
2596 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1 &&
2597 (token_match == STATE_TOKEN_BASE(lg_xmit->b.b1.state_token) ||
2598 token_match ==
2600 lg_xmit->b.b1.app_token->length))))
2601 break;
2602 /* try out the next one */
2603 }
2604 return coap_send_q_blocks(session, lg_xmit, block, request, send_request);
2605}
2606#endif /* COAP_Q_BLOCK_SUPPORT */
2607#endif /* COAP_CLIENT_SUPPORT */
2608
2609#if COAP_SERVER_SUPPORT
2610#if COAP_Q_BLOCK_SUPPORT
2611/*
2612 * response is always released before return IF COAP_SEND_INC_PDU
2613 */
2615coap_send_q_block2(coap_session_t *session,
2616 coap_resource_t *resource,
2617 const coap_string_t *query,
2618 coap_pdu_code_t request_method,
2619 coap_block_b_t block,
2620 coap_pdu_t *response,
2621 coap_send_pdu_t send_response) {
2622 /* Need to send up to MAX_PAYLOAD blocks if this is a Q_BLOCK2 */
2623 coap_lg_xmit_t *lg_xmit;
2624 coap_string_t empty = { 0, NULL};
2625
2626 LL_FOREACH(session->lg_xmit, lg_xmit) {
2627 if (lg_xmit->option == COAP_OPTION_Q_BLOCK2 &&
2628 resource == lg_xmit->b.b2.resource &&
2629 request_method == lg_xmit->b.b2.request_method &&
2630 coap_string_equal(query ? query : &empty,
2631 lg_xmit->b.b2.query ? lg_xmit->b.b2.query : &empty))
2632 break;
2633 }
2634 return coap_send_q_blocks(session, lg_xmit, block, response, send_response);
2635}
2636#endif /* COAP_Q_BLOCK_SUPPORT */
2637#endif /* COAP_SERVER_SUPPORT */
2638
2639static void
2641 coap_lg_xmit_data_t *data_info) {
2642 if (!data_info)
2643 return;
2644 if (data_info->ref > 0) {
2645 data_info->ref--;
2646 return;
2647 }
2648 if (data_info->release_func) {
2649 coap_lock_callback(data_info->release_func(session,
2650 data_info->app_ptr));
2651 data_info->release_func = NULL;
2652 }
2653 coap_free_type(COAP_STRING, data_info);
2654}
2655
2656#if COAP_CLIENT_SUPPORT
2657#if COAP_Q_BLOCK_SUPPORT
2658/*
2659 * Send out a test PDU for Q-Block.
2660 */
2662coap_block_test_q_block(coap_session_t *session, coap_pdu_t *actual) {
2663 coap_pdu_t *pdu;
2664 uint8_t token[8];
2665 size_t token_len;
2666 uint8_t buf[4];
2667 coap_mid_t mid;
2668 coap_bin_const_t *k_token;
2669
2670#if NDEBUG
2671 (void)actual;
2672#endif /* NDEBUG */
2673 assert(session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
2674 session->type == COAP_SESSION_TYPE_CLIENT &&
2675 COAP_PDU_IS_REQUEST(actual));
2676
2677 coap_log_debug("Testing for Q-Block support\n");
2678 /* RFC9177 Section 4.1 when checking if available */
2680 coap_new_message_id_lkd(session),
2682 if (!pdu) {
2683 return COAP_INVALID_MID;
2684 }
2685
2686 coap_session_new_token(session, &token_len, token);
2687 coap_add_token(pdu, token_len, token);
2688 /* Use a resource that the server MUST support (.well-known/core) */
2690 11, (const uint8_t *)".well-known");
2692 4, (const uint8_t *)"core");
2693 /*
2694 * M needs to be unset as 'asking' for only the first block using
2695 * Q-Block2 as a test for server support.
2696 * See RFC9177 Section 4.4 Using the Q-Block2 Option.
2697 *
2698 * As the client is asking for 16 byte chunks, it is unlikely that
2699 * the .well-known/core response will be 16 bytes or less, so
2700 * if the server supports Q-Block, it will be forced to respond with
2701 * a Q-Block2, so the client can detect the server Q-Block support.
2702 */
2704 coap_encode_var_safe(buf, sizeof(buf),
2705 (0 << 4) | (0 << 3) | 0),
2706 buf);
2707 k_token = coap_new_bin_const(pdu->actual_token.s, pdu->actual_token.length);
2708 set_block_mode_probe_q(session->block_mode);
2709 mid = coap_send_internal(session, pdu, NULL);
2710 if (mid == COAP_INVALID_MID) {
2711 coap_delete_bin_const(k_token);
2712 return COAP_INVALID_MID;
2713 }
2714 session->remote_test_mid = mid;
2716 session->last_token = k_token;
2717 return mid;
2718}
2719#endif /* COAP_Q_BLOCK_SUPPORT */
2720
2722coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu,
2723 coap_lg_xmit_t *lg_xmit) {
2724 coap_block_b_t block;
2725 coap_lg_crcv_t *lg_crcv;
2726 uint64_t state_token = STATE_TOKEN_FULL(++session->tx_token, 1);
2727
2728 lg_crcv = coap_malloc_type(COAP_LG_CRCV, sizeof(coap_lg_crcv_t));
2729
2730 if (lg_crcv == NULL)
2731 return NULL;
2732
2733 coap_log_debug("** %s: lg_crcv %p initialized - stateless token xxxxx%011llx\n",
2734 coap_session_str(session), (void *)lg_crcv,
2735 STATE_TOKEN_BASE(state_token));
2736 memset(lg_crcv, 0, sizeof(coap_lg_crcv_t));
2737 lg_crcv->initial = 1;
2738 coap_ticks(&lg_crcv->last_used);
2739 /* Keep a copy of the sent pdu */
2740 lg_crcv->sent_pdu = coap_pdu_reference_lkd(pdu);
2741 if (lg_xmit) {
2742 coap_opt_iterator_t opt_iter;
2743 coap_opt_t *opt;
2744
2745 opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2746
2747 if (opt) {
2748 int observe_action;
2749
2750 observe_action = coap_decode_var_bytes(coap_opt_value(opt),
2751 coap_opt_length(opt));
2752 if (observe_action == COAP_OBSERVE_ESTABLISH) {
2753 /* Need to keep information for Observe Cancel */
2754 size_t data_len;
2755 const uint8_t *data;
2756
2757 if (coap_get_data(pdu, &data_len, &data)) {
2758 if (data_len < lg_xmit->data_info->length) {
2759 lg_xmit->data_info->ref++;
2760 lg_crcv->obs_data = lg_xmit->data_info;
2761 }
2762 }
2763 }
2764 }
2765 }
2766
2767 /* Need to keep original token for updating response PDUs */
2768 lg_crcv->app_token = coap_new_binary(pdu->actual_token.length);
2769 if (!lg_crcv->app_token) {
2770 coap_block_delete_lg_crcv(session, lg_crcv);
2771 return NULL;
2772 }
2773 memcpy(lg_crcv->app_token->s, pdu->actual_token.s, pdu->actual_token.length);
2774
2775 /* Need to set up a base token for actual communications if retries needed */
2776 lg_crcv->retry_counter = 1;
2777 lg_crcv->state_token = state_token;
2778 coap_address_copy(&lg_crcv->upstream, &session->addr_info.remote);
2779
2780 if (pdu->code == COAP_REQUEST_CODE_FETCH) {
2781 coap_bin_const_t *new_token;
2782
2783 /* Need to save/restore Observe Token for large FETCH */
2784 new_token = track_fetch_observe(pdu, lg_crcv, 0, &pdu->actual_token);
2785 if (new_token)
2786 coap_update_token(pdu, new_token->length, new_token->s);
2787 }
2788
2789 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block)) {
2790 /* In case it is there - must not be in continuing request PDUs */
2791 lg_crcv->o_block_option = COAP_OPTION_BLOCK1;
2792 lg_crcv->o_blk_size = block.aszx;
2793 }
2794
2795 return lg_crcv;
2796}
2797
2798void
2799coap_block_delete_lg_crcv(coap_session_t *session,
2800 coap_lg_crcv_t *lg_crcv) {
2801 size_t i;
2802
2803#if (COAP_MAX_LOGGING_LEVEL < _COAP_LOG_DEBUG)
2804 (void)session;
2805#endif
2806 if (lg_crcv == NULL)
2807 return;
2808
2809 if (lg_crcv->ref > 0) {
2810 lg_crcv->ref--;
2811 return;
2812 }
2813
2814 coap_free_type(COAP_STRING, lg_crcv->body_data);
2815 if (lg_crcv->obs_data) {
2816 coap_block_release_lg_xmit_data(session, lg_crcv->obs_data);
2817 lg_crcv->obs_data = NULL;
2818 }
2819 coap_address_copy(&session->addr_info.remote, &lg_crcv->upstream);
2820 coap_log_debug("** %s: lg_crcv %p released\n",
2821 coap_session_str(session), (void *)lg_crcv);
2822 coap_delete_binary(lg_crcv->app_token);
2823 for (i = 0; i < lg_crcv->obs_token_cnt; i++) {
2824 coap_delete_bin_const(lg_crcv->obs_token[i]);
2825 }
2826 coap_free_type(COAP_STRING, lg_crcv->obs_token);
2827 coap_delete_pdu_lkd(lg_crcv->sent_pdu);
2828 coap_free_type(COAP_LG_CRCV, lg_crcv);
2829}
2830#endif /* COAP_CLIENT_SUPPORT */
2831
2832#if COAP_SERVER_SUPPORT
2833void
2834coap_block_delete_lg_srcv(coap_session_t *session,
2835 coap_lg_srcv_t *lg_srcv) {
2836#if (COAP_MAX_LOGGING_LEVEL < _COAP_LOG_DEBUG)
2837 (void)session;
2838#endif
2839 if (lg_srcv == NULL)
2840 return;
2841
2842 if (lg_srcv->ref > 0) {
2843 lg_srcv->ref--;
2844 return;
2845 }
2846
2847 coap_delete_str_const(lg_srcv->uri_path);
2848 coap_delete_bin_const(lg_srcv->last_token);
2849 coap_free_type(COAP_STRING, lg_srcv->body_data);
2850 coap_log_debug("** %s: lg_srcv %p released\n",
2851 coap_session_str(session), (void *)lg_srcv);
2852 coap_free_type(COAP_LG_SRCV, lg_srcv);
2853}
2854#endif /* COAP_SERVER_SUPPORT */
2855
2856void
2858 coap_lg_xmit_t *lg_xmit) {
2859 if (lg_xmit == NULL)
2860 return;
2861
2862 if (lg_xmit->ref > 0) {
2863 lg_xmit->ref--;
2864 return;
2865 }
2866
2867 coap_block_release_lg_xmit_data(session, lg_xmit->data_info);
2868 if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu))
2869 coap_delete_binary(lg_xmit->b.b1.app_token);
2870 else
2871 coap_delete_string(lg_xmit->b.b2.query);
2872 coap_delete_pdu_lkd(lg_xmit->sent_pdu);
2873
2874 coap_log_debug("** %s: lg_xmit %p released\n",
2875 coap_session_str(session), (void *)lg_xmit);
2876 coap_free_type(COAP_LG_XMIT, lg_xmit);
2877}
2878
2879#if COAP_SERVER_SUPPORT
2880typedef struct {
2881 uint32_t num;
2882 int is_continue;
2883} send_track;
2884
2885static int
2886add_block_send(uint32_t num, int is_continue, send_track *out_blocks,
2887 uint32_t *count, uint32_t max_count) {
2888 uint32_t i;
2889
2890 for (i = 0; i < *count && *count < max_count; i++) {
2891 if (num == out_blocks[i].num)
2892 return 0;
2893 else if (num < out_blocks[i].num) {
2894 if (*count - i > 1)
2895 memmove(&out_blocks[i], &out_blocks[i+1], *count - i -1);
2896 out_blocks[i].num = num;
2897 out_blocks[i].is_continue = is_continue;
2898 (*count)++;
2899 return 1;
2900 }
2901 }
2902 if (*count < max_count) {
2903 out_blocks[i].num = num;
2904 out_blocks[i].is_continue = is_continue;
2905 (*count)++;
2906 return 1;
2907 }
2908 return 0;
2909}
2910
2911/*
2912 * Need to see if this is a request for the next block of a large body
2913 * transfer. If so, need to initiate the response with the next blocks
2914 * and not trouble the application.
2915 *
2916 * If additional responses needed, then these are explicitly sent out and
2917 * 'response' is updated to be the last response to be sent. There can be
2918 * multiple Q-Block2 in the request, as well as the 'Continue' Q-Block2
2919 * request.
2920 *
2921 * This is set up using coap_add_data_large_response_lkd()
2922 *
2923 * Server is sending a large data response to GET / observe (Block2)
2924 *
2925 * Return: 0 Call application handler
2926 * 1 Do not call application handler - just send the built response
2927 */
2928int
2929coap_handle_request_send_block(coap_session_t *session,
2930 coap_pdu_t *pdu,
2931 coap_pdu_t *response,
2932 coap_resource_t *resource,
2933 coap_string_t *query) {
2934 coap_lg_xmit_t *lg_xmit = NULL;
2935 coap_block_b_t block;
2936 coap_block_b_t alt_block;
2937 uint16_t block_opt = 0;
2938 send_track *out_blocks = NULL;
2939 const char *error_phrase;
2940 coap_opt_iterator_t opt_iter;
2941 size_t chunk;
2942 coap_opt_iterator_t opt_b_iter;
2943 coap_opt_t *option;
2944 uint32_t request_cnt, i;
2945 coap_opt_t *etag_opt = NULL;
2946 coap_pdu_t *out_pdu = response;
2947#if COAP_Q_BLOCK_SUPPORT
2948 size_t max_block;
2949
2950 /* Is client indicating that it supports Q_BLOCK2 ? */
2951 if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
2952 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
2953 set_block_mode_has_q(session->block_mode);
2954 block_opt = COAP_OPTION_Q_BLOCK2;
2955 }
2956#endif /* COAP_Q_BLOCK_SUPPORT */
2957 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &alt_block)) {
2958 if (block_opt) {
2959 coap_log_warn("Block2 and Q-Block2 cannot be in the same request\n");
2960 coap_add_data(response, sizeof("Both Block2 and Q-Block2 invalid")-1,
2961 (const uint8_t *)"Both Block2 and Q-Block2 invalid");
2962 response->code = COAP_RESPONSE_CODE(400);
2963 goto skip_app_handler;
2964 }
2965 block = alt_block;
2966 block_opt = COAP_OPTION_BLOCK2;
2967 }
2968 if (block_opt == 0)
2969 return 0;
2970 if (block.num == 0) {
2971#if COAP_Q_BLOCK_SUPPORT
2972 if (block_opt == COAP_OPTION_Q_BLOCK2) {
2973 if (block.m) {
2974 return 0;
2975 }
2976 } else
2977#endif /* COAP_Q_BLOCK_SUPPORT */
2978 /* Get a fresh copy of the data */
2979 return 0;
2980 }
2981 lg_xmit = coap_find_lg_xmit_response(session, pdu, resource, query);
2982 if (lg_xmit == NULL)
2983 return 0;
2984
2985#if COAP_Q_BLOCK_SUPPORT
2986 out_blocks = coap_malloc_type(COAP_STRING, sizeof(send_track) * COAP_MAX_PAYLOADS(session));
2987#else /* ! COAP_Q_BLOCK_SUPPORT */
2988 out_blocks = coap_malloc_type(COAP_STRING, sizeof(send_track));
2989#endif /* ! COAP_Q_BLOCK_SUPPORT */
2990 if (!out_blocks) {
2991 goto internal_issue;
2992 }
2993
2994 /* lg_xmit (response) found */
2995
2996 etag_opt = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter);
2997 if (etag_opt) {
2998 /* There may be multiple ETag - need to check each one */
2999 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
3000 while ((etag_opt = coap_option_next(&opt_iter))) {
3001 if (opt_iter.number == COAP_OPTION_ETAG) {
3002 uint64_t etag = coap_decode_var_bytes8(coap_opt_value(etag_opt),
3003 coap_opt_length(etag_opt));
3004 if (etag == lg_xmit->b.b2.etag) {
3005 break;
3006 }
3007 }
3008 }
3009 if (!etag_opt) {
3010 /* Not a match - pass up to a higher level */
3011 return 0;
3012 }
3013 }
3014 out_pdu->code = lg_xmit->sent_pdu->code;
3015 coap_ticks(&lg_xmit->last_obs);
3016
3017 chunk = (size_t)1 << (lg_xmit->blk_size + 4);
3018 if (block_opt) {
3019 if (block.bert) {
3020 coap_log_debug("found Block option, block is BERT, block nr. %u, M %d\n",
3021 block.num, block.m);
3022 } else {
3023 coap_log_debug("found Block option, block size is %u, block nr. %u, M %d\n",
3024 1 << (block.szx + 4), block.num, block.m);
3025 }
3026 if (block.bert == 0 && block.szx != lg_xmit->blk_size) {
3027 if (block.num == 0) {
3028 if (block.szx < lg_xmit->blk_size) {
3029 /*
3030 * Recompute the block number of the previous packet given
3031 * the new block size
3032 */
3033 block.num = (uint32_t)((chunk >> (block.szx + 4)) - 1);
3034 chunk = (size_t)1 << (lg_xmit->blk_size + 4);
3035#if COAP_Q_BLOCK_SUPPORT
3036 lg_xmit->send_blocks.range[0].begin = block.num;
3037 lg_xmit->send_blocks.range[0].end = (uint32_t)((lg_xmit->data_info->length - 1) / chunk);
3038#endif /* COAP_Q_BLOCK_SUPPORT */
3039 lg_xmit->blk_size = block.szx;
3040 coap_log_debug("new Block size is %u, block number %u completed\n",
3041 (1 << (block.szx + 4)), block.num);
3042 } else {
3043 coap_log_debug("ignoring request to increase Block size from %u to %u\n",
3044 (1 << (lg_xmit->blk_size + 4)), (1 << (lg_xmit->blk_size + 4)));
3045 }
3046 } else {
3047 coap_log_debug("ignoring request to change Block size from %u to %u\n",
3048 (1 << (lg_xmit->blk_size + 4)), (1 << (block.szx + 4)));
3049 block.szx = block.aszx = lg_xmit->blk_size;
3050 }
3051 }
3052 }
3053
3054 /*
3055 * Need to check if there are multiple Q-Block2 requests. If so, they
3056 * need to be sent out in order of requests with the final request being
3057 * handled as per singular Block 2 request.
3058 */
3059 request_cnt = 0;
3060#if COAP_Q_BLOCK_SUPPORT
3061 max_block = (lg_xmit->data_info->length + chunk - 1)/chunk;
3062#endif /* COAP_Q_BLOCK_SUPPORT */
3063 coap_option_iterator_init(pdu, &opt_b_iter, COAP_OPT_ALL);
3064 while ((option = coap_option_next(&opt_b_iter))) {
3065 uint32_t num;
3066 if (opt_b_iter.number != lg_xmit->option)
3067 continue;
3068 num = coap_opt_block_num(option);
3069 if (num > 0xFFFFF) /* 20 bits max for num */
3070 continue;
3071 if (block.aszx != COAP_OPT_BLOCK_SZX(option)) {
3072 coap_add_data(response,
3073 sizeof("Changing blocksize during request invalid")-1,
3074 (const uint8_t *)"Changing blocksize during request invalid");
3075 response->code = COAP_RESPONSE_CODE(400);
3076 goto skip_app_handler;
3077 }
3078#if COAP_Q_BLOCK_SUPPORT
3079 if (COAP_OPT_BLOCK_MORE(option) && lg_xmit->option == COAP_OPTION_Q_BLOCK2) {
3080 if ((num % COAP_MAX_PAYLOADS(session)) == 0) {
3081 if (num == 0) {
3082 /* This is a repeat request for everything - hmm */
3083 goto call_app_handler;
3084 }
3085 /* 'Continue' request */
3086 for (i = 0; i < COAP_MAX_PAYLOADS(session) &&
3087 num + i < max_block; i++) {
3088 add_block_send(num + i, 1, out_blocks, &request_cnt,
3089 COAP_MAX_PAYLOADS(session));
3090 lg_xmit->last_block = num + i;
3091 }
3092 } else {
3093 /* Requesting remaining payloads in this MAX_PAYLOADS */
3094 for (i = 0; i < COAP_MAX_PAYLOADS(session) -
3095 num % COAP_MAX_PAYLOADS(session) &&
3096 num + i < max_block; i++) {
3097 add_block_send(num + i, 0, out_blocks, &request_cnt,
3098 COAP_MAX_PAYLOADS(session));
3099 }
3100 }
3101 } else
3102 add_block_send(num, 0, out_blocks, &request_cnt,
3103 COAP_MAX_PAYLOADS(session));
3104#else /* ! COAP_Q_BLOCK_SUPPORT */
3105 add_block_send(num, 0, out_blocks, &request_cnt, 1);
3106 break;
3107#endif /* ! COAP_Q_BLOCK_SUPPORT */
3108 }
3109 if (request_cnt == 0) {
3110 /* Block2 or Q-Block2 not found - give them the first block */
3111 block.szx = lg_xmit->blk_size;
3112 out_blocks[0].num = 0;
3113 out_blocks[0].is_continue = 0;
3114 request_cnt = 1;
3115 }
3116
3117 for (i = 0; i < request_cnt; i++) {
3118 uint8_t buf[8];
3119 size_t offset;
3120
3121 block.num = out_blocks[i].num;
3122
3123 if (i + 1 < request_cnt) {
3124 /* Need to set up a copy of the pdu to send */
3125 coap_opt_filter_t drop_options;
3126
3127 memset(&drop_options, 0, sizeof(coap_opt_filter_t));
3128 if (block.num != 0)
3130 if (out_blocks[i].is_continue) {
3131 out_pdu = coap_pdu_duplicate_lkd(lg_xmit->sent_pdu, session,
3132 lg_xmit->sent_pdu->actual_token.length,
3133 lg_xmit->sent_pdu->actual_token.s,
3134 &drop_options, COAP_BOOL_FALSE);
3135 } else {
3136 out_pdu = coap_pdu_duplicate_lkd(lg_xmit->sent_pdu, session,
3137 pdu->actual_token.length,
3138 pdu->actual_token.s,
3139 &drop_options, COAP_BOOL_FALSE);
3140 }
3141 if (!out_pdu) {
3142 goto internal_issue;
3143 }
3144 } else {
3145 if (out_blocks[i].is_continue)
3146 coap_update_token(response, lg_xmit->sent_pdu->actual_token.length,
3147 lg_xmit->sent_pdu->actual_token.s);
3148 /*
3149 * Copy the options across and then fix the block option
3150 *
3151 * Need to drop Observe option if Block2 and block.num != 0
3152 */
3153 coap_option_iterator_init(lg_xmit->sent_pdu, &opt_iter, COAP_OPT_ALL);
3154 while ((option = coap_option_next(&opt_iter))) {
3155 if (opt_iter.number == COAP_OPTION_OBSERVE && block.num != 0)
3156 continue;
3157 if (!coap_insert_option(response, opt_iter.number,
3158 coap_opt_length(option),
3159 coap_opt_value(option))) {
3160 goto internal_issue;
3161 }
3162 }
3163 out_pdu = response;
3164 }
3165 if (pdu->type == COAP_MESSAGE_NON)
3166 out_pdu->type = COAP_MESSAGE_NON;
3167 offset = block.num * chunk;
3168 if (block.bert) {
3169 size_t token_options = pdu->data ? (size_t)(pdu->data - pdu->token) : pdu->used_size;
3170 block.m = (lg_xmit->data_info->length - offset) >
3171 ((out_pdu->max_size - token_options) /1024) * 1024;
3172 } else {
3173 block.m = (offset + chunk) < lg_xmit->data_info->length;
3174 }
3175 if (!coap_update_option(out_pdu, lg_xmit->option,
3177 sizeof(buf),
3178 (block.num << 4) |
3179 (block.m << 3) |
3180 block.aszx),
3181 buf)) {
3182 goto internal_issue;
3183 }
3184 if (!(offset + chunk < lg_xmit->data_info->length)) {
3185 /* Last block - keep in cache for 4 * ACK_TIMOUT */
3186 coap_ticks(&lg_xmit->last_all_sent);
3187 }
3188 if (lg_xmit->b.b2.maxage_expire) {
3189 coap_tick_t now;
3190 coap_time_t rem;
3191
3192 if (!(offset + chunk < lg_xmit->data_info->length)) {
3193 /* Last block - keep in cache for 4 * ACK_TIMOUT */
3194 coap_ticks(&lg_xmit->last_all_sent);
3195 }
3196 coap_ticks(&now);
3197 rem = coap_ticks_to_rt(now);
3198 if (lg_xmit->b.b2.maxage_expire > rem) {
3199 rem = lg_xmit->b.b2.maxage_expire - rem;
3200 } else {
3201 rem = 0;
3202 /* Entry needs to be expired */
3203 coap_ticks(&lg_xmit->last_all_sent);
3204 }
3207 sizeof(buf),
3208 rem),
3209 buf)) {
3210 goto internal_issue;
3211 }
3212 }
3213
3214 if (!coap_add_block_b_data(out_pdu,
3215 lg_xmit->data_info->length,
3216 lg_xmit->data_info->data,
3217 &block)) {
3218 goto internal_issue;
3219 }
3220 if (i + 1 < request_cnt) {
3221 coap_ticks(&lg_xmit->last_sent);
3222 coap_send_internal(session, out_pdu, NULL);
3223 }
3224 }
3225 coap_ticks(&lg_xmit->last_payload);
3226 coap_ticks(&lg_xmit->last_sent);
3227 if (lg_xmit->last_all_sent) {
3228 coap_ticks(&lg_xmit->last_all_sent);
3229 }
3230 goto skip_app_handler;
3231#if COAP_Q_BLOCK_SUPPORT
3232call_app_handler:
3233 coap_free_type(COAP_STRING, out_blocks);
3234 return 0;
3235#endif /* COAP_Q_BLOCK_SUPPORT */
3236
3237internal_issue:
3238 response->code = COAP_RESPONSE_CODE(500);
3239 error_phrase = coap_response_phrase(response->code);
3240 coap_add_data(response, strlen(error_phrase),
3241 (const uint8_t *)error_phrase);
3242 /* Keep in cache for 4 * ACK_TIMOUT in case of retry */
3243 if (lg_xmit)
3244 coap_ticks(&lg_xmit->last_all_sent);
3245
3246skip_app_handler:
3247 coap_free_type(COAP_STRING, out_blocks);
3248 return 1;
3249}
3250#endif /* COAP_SERVER_SUPPORT */
3251
3252#if COAP_Q_BLOCK_SUPPORT
3253static int
3254blocks_delete_entry(coap_rblock_t *rec_blocks, uint32_t block_num) {
3255 uint32_t i;
3256
3257 if (rec_blocks->total_blocks && block_num + 1 > rec_blocks->total_blocks) {
3258 /* received block number greater than Block No defined when More bit unset */
3259 return 0;
3260 }
3261
3262 for (i = 0; i < rec_blocks->used; i++) {
3263 if (block_num >= rec_blocks->range[i].begin &&
3264 block_num <= rec_blocks->range[i].end) {
3265 /* In this block */
3266 if (block_num == rec_blocks->range[i].begin) {
3267 if (block_num == rec_blocks->range[i].end) {
3268 /* Need to delete this range */
3269 if (i + 1 < rec_blocks->used) {
3270 memmove(&rec_blocks->range[i], &rec_blocks->range[i+1],
3271 (rec_blocks->used - i) * sizeof(rec_blocks->range[0]));
3272 }
3273 rec_blocks->used--;
3274 break;
3275 }
3276 rec_blocks->range[i].begin++;
3277 } else if (block_num == rec_blocks->range[i].end) {
3278 rec_blocks->range[i].end--;
3279 if (rec_blocks->range[i].begin == rec_blocks->range[i].end) {
3280 /* Need to delete this range */
3281 rec_blocks->used--;
3282 if (i == rec_blocks->used)
3283 break;
3284 memmove(&rec_blocks->range[i], &rec_blocks->range[i+1],
3285 sizeof(rec_blocks->range[i]) * (rec_blocks->used - i));
3286 }
3287 } else {
3288 /* Need to split the range */
3289 if (rec_blocks->used == COAP_RBLOCK_CNT)
3290 /* Too many losses */
3291 return 0;
3292 memmove(&rec_blocks->range[i+1], &rec_blocks->range[i],
3293 (rec_blocks->used - i) * sizeof(rec_blocks->range[0]));
3294 rec_blocks->range[i].end = block_num - 1;
3295 rec_blocks->range[i+1].begin = block_num + 1;
3296 rec_blocks->used++;
3297 }
3298 break;
3299 }
3300 }
3301 coap_ticks(&rec_blocks->last_seen);
3302 return 1;
3303}
3304#endif /* COAP_Q_BLOCK_SUPPORT */
3305
3306static int
3307blocks_add_entry(coap_rblock_t *rec_blocks, uint32_t block_num, uint32_t block_m) {
3308 uint32_t i;
3309
3310 if (rec_blocks->total_blocks && block_num + 1 > rec_blocks->total_blocks) {
3311 /* received block number greater than Block No defined when More bit unset */
3312 return 0;
3313 }
3314
3315 /* Reset as there is activity */
3316 rec_blocks->retry = 0;
3317
3318 for (i = 0; i < rec_blocks->used; i++) {
3319 if (block_num >= rec_blocks->range[i].begin &&
3320 block_num <= rec_blocks->range[i].end)
3321 break;
3322
3323 if (block_num < rec_blocks->range[i].begin) {
3324 if (block_num + 1 == rec_blocks->range[i].begin) {
3325 rec_blocks->range[i].begin = block_num;
3326 } else {
3327 /* Need to insert a new range */
3328 if (rec_blocks->used == COAP_RBLOCK_CNT)
3329 /* Too many losses */
3330 return 0;
3331 memmove(&rec_blocks->range[i+1], &rec_blocks->range[i],
3332 (rec_blocks->used - i) * sizeof(rec_blocks->range[0]));
3333 rec_blocks->range[i].begin = rec_blocks->range[i].end = block_num;
3334 rec_blocks->used++;
3335 }
3336 break;
3337 }
3338 if (block_num == rec_blocks->range[i].end + 1) {
3339 rec_blocks->range[i].end = block_num;
3340 if (i + 1 < rec_blocks->used) {
3341 if (rec_blocks->range[i+1].begin == block_num + 1) {
3342 /* Merge the 2 ranges */
3343 rec_blocks->range[i].end = rec_blocks->range[i+1].end;
3344 if (i+2 < rec_blocks->used) {
3345 memmove(&rec_blocks->range[i+1], &rec_blocks->range[i+2],
3346 (rec_blocks->used - (i+2)) * sizeof(rec_blocks->range[0]));
3347 }
3348 rec_blocks->used--;
3349 }
3350 }
3351 break;
3352 }
3353 }
3354 if (i == rec_blocks->used) {
3355 if (rec_blocks->used == COAP_RBLOCK_CNT) {
3356 /* Too many losses */
3357 return 0;
3358 }
3359 rec_blocks->range[i].begin = rec_blocks->range[i].end = block_num;
3360 rec_blocks->used++;
3361 }
3362 if (!block_m)
3363 rec_blocks->total_blocks = block_num + 1;
3364
3365 coap_ticks(&rec_blocks->last_seen);
3366 return 1;
3367}
3368
3369#if COAP_SERVER_SUPPORT
3370/*
3371 * Need to check if this is a large PUT / POST etc. using multiple blocks
3372 *
3373 * Server receiving PUT/POST etc. of a large amount of data (Block1)
3374 *
3375 * Return: 0 Call application handler
3376 * 1 Do not call application handler - just send the built response
3377 */
3378int
3379coap_handle_request_put_block(coap_context_t *context,
3380 coap_session_t *session,
3381 coap_pdu_t *pdu,
3382 coap_pdu_t *response,
3383 coap_resource_t *resource,
3384 coap_string_t *uri_path,
3385 coap_opt_t *observe,
3386 int *added_block,
3387 coap_lg_srcv_t **pfree_lg_srcv) {
3388 size_t length = 0;
3389 const uint8_t *data = NULL;
3390 size_t offset = 0;
3391 size_t total = 0;
3392 coap_block_b_t block;
3393 coap_opt_iterator_t opt_iter;
3394 uint16_t block_option = 0;
3395 coap_lg_srcv_t *lg_srcv;
3396 coap_opt_t *size_opt;
3397 coap_opt_t *fmt_opt;
3398 uint16_t fmt;
3399 coap_opt_t *rtag_opt;
3400 size_t rtag_length;
3401 const uint8_t *rtag;
3402 uint32_t max_block_szx;
3403 int update_data;
3404 unsigned int saved_num;
3405 size_t saved_offset;
3406 int lg_srcv_is_refed = 0;
3407#if COAP_Q_BLOCK_SUPPORT
3408 int request_missing = 0;
3409#endif /* COAP_Q_BLOCK_SUPPORT */
3410
3411 *added_block = 0;
3412 *pfree_lg_srcv = NULL;
3413 coap_get_data_large(pdu, &length, &data, &offset, &total);
3414 pdu->body_offset = 0;
3415 pdu->body_total = length;
3416
3417 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block)) {
3418 block_option = COAP_OPTION_BLOCK1;
3419#if COAP_Q_BLOCK_SUPPORT
3420 if (coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter)) {
3421 /* Cannot handle Q-Block1 as well */
3422 coap_add_data(response, sizeof("Block1 + Q-Block1 together")-1,
3423 (const uint8_t *)"Block1 + Q-Block1 together");
3424 response->code = COAP_RESPONSE_CODE(402);
3425 goto skip_app_handler;
3426 }
3427#endif /* COAP_Q_BLOCK_SUPPORT */
3428 }
3429#if COAP_Q_BLOCK_SUPPORT
3430 else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
3431 block_option = COAP_OPTION_Q_BLOCK1;
3432 set_block_mode_has_q(session->block_mode);
3433 }
3434#endif /* COAP_Q_BLOCK_SUPPORT */
3435 if (!block_option ||
3436 (block_option == COAP_OPTION_BLOCK1 && block.num == 0 && block.m == 0)) {
3437 /* Not blocked, or a single block */
3438 if (context->max_body_size && total > context->max_body_size) {
3439 uint8_t buf[4];
3440
3441 coap_update_option(response,
3443 coap_encode_var_safe((uint8_t *)buf, sizeof(buf),
3444 context->max_body_size),
3445 (uint8_t *)buf);
3446 response->code = COAP_RESPONSE_CODE(413);
3447 coap_log_warn("Unable to handle data size %" PRIuS " (max %" PRIu32 ")\n", total,
3448 context->max_body_size);
3449 goto skip_app_handler;
3450 }
3451 goto call_app_handler;
3452 }
3453
3454 size_opt = coap_check_option(pdu,
3456 &opt_iter);
3457 fmt_opt = coap_check_option(pdu,
3459 &opt_iter);
3460 fmt = fmt_opt ? coap_decode_var_bytes(coap_opt_value(fmt_opt),
3461 coap_opt_length(fmt_opt)) :
3463 rtag_opt = coap_check_option(pdu,
3465 &opt_iter);
3466#if COAP_Q_BLOCK_SUPPORT
3467 if (block_option == COAP_OPTION_Q_BLOCK1 && (!size_opt || !rtag_opt)) {
3468 /* RFC9177 section-4.3 */
3469 coap_log_info("Q-Block1: Size1 and RTag options required\n");
3470 response->code = COAP_RESPONSE_CODE(400);
3471 goto skip_app_handler;
3472 }
3473#endif /* COAP_Q_BLOCK_SUPPORT */
3474 rtag_length = rtag_opt ? coap_opt_length(rtag_opt) : 0;
3475 rtag_length = min(rtag_length, 8);
3476 rtag = rtag_opt ? coap_opt_value(rtag_opt) : NULL;
3477
3478 if (length > block.chunk_size) {
3479 coap_log_debug("block: Oversized packet - reduced to %"PRIu32" from %" PRIuS "\n",
3480 block.chunk_size, length);
3481 length = block.chunk_size;
3482 } else if (!block.bert && block.m && length != block.chunk_size) {
3483 coap_log_info("block: Undersized packet chunk %"PRIu32" got %" PRIuS "\n",
3484 block.chunk_size, length);
3485 response->code = COAP_RESPONSE_CODE(400);
3486 goto skip_app_handler;
3487 }
3488 total = size_opt ? coap_decode_var_bytes(coap_opt_value(size_opt),
3489 coap_opt_length(size_opt)) : 0;
3490 if (total) {
3491 uint32_t max_body;
3492
3493 max_block_szx = COAP_BLOCK_MAX_SIZE_GET(session->block_mode);
3494 if (max_block_szx == 0 || max_block_szx > block.szx) {
3495 max_block_szx = block.szx;
3496 }
3497 max_body = ((1UL << 20) * (1 << (max_block_szx + 4)));
3498 if (max_body > MAX_BLK_LEN)
3499 max_body = MAX_BLK_LEN;
3500 if ((context->max_body_size && total > context->max_body_size) ||
3501 (total > max_body)) {
3502 /* Suggested body size larger than allowed */
3503 char buf[32];
3504 uint32_t max_body_size = context->max_body_size;
3505
3506 if (max_body_size == 0 || max_body < max_body_size) {
3507 max_body_size = max_body;
3508 }
3509 coap_update_option(response,
3511 coap_encode_var_safe((uint8_t *)buf, sizeof(buf),
3512 max_body_size),
3513 (uint8_t *)buf);
3514 snprintf(buf, sizeof(buf), "Max body size %" PRIu32, max_body_size);
3515 coap_add_data(response, strlen(buf), (uint8_t *)buf);
3516 response->code = COAP_RESPONSE_CODE(413);
3517 coap_log_warn("Unable to handle body size %" PRIuS " (max %" PRIu32 ")\n", total, max_body_size);
3518 goto skip_app_handler;
3519 }
3520 }
3521 offset = block.num << (block.szx + 4);
3522
3523 if (!(session->block_mode &
3524#if COAP_Q_BLOCK_SUPPORT
3526#else /* COAP_Q_BLOCK_SUPPORT */
3528#endif /* COAP_Q_BLOCK_SUPPORT */
3529 && !block.bert) {
3530 uint8_t buf[4];
3531
3532 /* Ask for the next block */
3533 coap_insert_option(response, block_option,
3534 coap_encode_var_safe(buf, sizeof(buf),
3535 (block.num << 4) |
3536 (block.m << 3) |
3537 block.aszx),
3538 buf);
3539 /* Not re-assembling or checking for receipt order */
3540 pdu->body_data = data;
3541 pdu->body_length = length;
3542 pdu->body_offset = offset;
3543 if (total < (length + offset + (block.m ? 1 : 0)))
3544 total = length + offset + (block.m ? 1 : 0);
3545 pdu->body_total = total;
3546 *added_block = block.m;
3547 /* The application is responsible for returning the correct 2.01/2.04/2.31 etc. */
3548 goto call_app_handler;
3549 }
3550
3551 /*
3552 * locate the lg_srcv
3553 */
3554 LL_FOREACH(session->lg_srcv, lg_srcv) {
3555 if (rtag_opt || lg_srcv->rtag_set == 1) {
3556 if (!(rtag_opt && lg_srcv->rtag_set == 1))
3557 continue;
3558 if (lg_srcv->rtag_length != rtag_length ||
3559 memcmp(lg_srcv->rtag, rtag, rtag_length) != 0)
3560 continue;
3561 }
3562 if (resource == lg_srcv->resource) {
3563 break;
3564 }
3565 if ((lg_srcv->resource == context->unknown_resource ||
3566 resource == context->proxy_uri_resource) &&
3567 coap_string_equal(uri_path, lg_srcv->uri_path))
3568 break;
3569 }
3570
3571 if (!lg_srcv && block.num != 0 && session->block_mode & COAP_BLOCK_NOT_RANDOM_BLOCK1) {
3572 coap_add_data(response, sizeof("Missing block 0")-1,
3573 (const uint8_t *)"Missing block 0");
3574 response->code = COAP_RESPONSE_CODE(408);
3575 goto skip_app_handler;
3576 }
3577
3578 if (!lg_srcv) {
3579 /* Allocate lg_srcv to use for tracking */
3580 lg_srcv = coap_malloc_type(COAP_LG_SRCV, sizeof(coap_lg_srcv_t));
3581 if (lg_srcv == NULL) {
3582 coap_add_data(response, sizeof("Memory issue")-1,
3583 (const uint8_t *)"Memory issue");
3584 response->code = COAP_RESPONSE_CODE(500);
3585 goto skip_app_handler;
3586 }
3587 coap_log_debug("** %s: lg_srcv %p initialized\n",
3588 coap_session_str(session), (void *)lg_srcv);
3589 memset(lg_srcv, 0, sizeof(coap_lg_srcv_t));
3590 lg_srcv->resource = resource;
3591 if (resource == context->unknown_resource ||
3592 resource == context->proxy_uri_resource)
3593 lg_srcv->uri_path = coap_new_str_const(uri_path->s, uri_path->length);
3594 lg_srcv->content_format = fmt;
3595 lg_srcv->total_len = total;
3596 max_block_szx = COAP_BLOCK_MAX_SIZE_GET(session->block_mode);
3597 if (!block.bert && block.num == 0 && max_block_szx != 0 &&
3598 max_block_szx < block.szx) {
3599 lg_srcv->szx = max_block_szx;
3600 } else {
3601 lg_srcv->szx = block.szx;
3602 }
3603 lg_srcv->block_option = block_option;
3604 if (observe) {
3605 lg_srcv->observe_length = min(coap_opt_length(observe), 3);
3606 memcpy(lg_srcv->observe, coap_opt_value(observe), lg_srcv->observe_length);
3607 lg_srcv->observe_set = 1;
3608 }
3609 if (rtag_opt) {
3610 lg_srcv->rtag_length = (uint8_t)rtag_length;
3611 memcpy(lg_srcv->rtag, coap_opt_value(rtag_opt), lg_srcv->rtag_length);
3612 lg_srcv->rtag_set = 1;
3613 }
3614 lg_srcv->body_data = NULL;
3615#if COAP_Q_BLOCK_SUPPORT
3616 lg_srcv->r_m_payload_set = -1;
3617#endif /* COAP_Q_BLOCK_SUPPORT */
3618 LL_PREPEND(session->lg_srcv, lg_srcv);
3619 }
3620 coap_ticks(&lg_srcv->last_used);
3621 coap_lg_srcv_reference_lkd(lg_srcv);
3622 lg_srcv_is_refed = 1;
3623
3624 if (block_option == COAP_OPTION_BLOCK1 &&
3626 !check_if_next_block(&lg_srcv->rec_blocks, block.num)) {
3627 coap_add_data(response, sizeof("Missing interim block")-1,
3628 (const uint8_t *)"Missing interim block");
3629 response->code = COAP_RESPONSE_CODE(408);
3630 goto skip_app_handler;
3631 }
3632
3633 if (fmt != lg_srcv->content_format) {
3634 coap_add_data(response, sizeof("Content-Format mismatch")-1,
3635 (const uint8_t *)"Content-Format mismatch");
3636 response->code = COAP_RESPONSE_CODE(408);
3637 goto free_lg_srcv;
3638 }
3639
3640#if COAP_Q_BLOCK_SUPPORT
3641 if (block_option == COAP_OPTION_Q_BLOCK1) {
3642 if (total != lg_srcv->total_len) {
3643 coap_add_data(response, sizeof("Size1 mismatch")-1,
3644 (const uint8_t *)"Size1 mismatch");
3645 response->code = COAP_RESPONSE_CODE(408);
3646 goto free_lg_srcv;
3647 }
3648 coap_delete_bin_const(lg_srcv->last_token);
3649 lg_srcv->last_token = coap_new_bin_const(pdu->actual_token.s,
3650 pdu->actual_token.length);
3651 }
3652#endif /* COAP_Q_BLOCK_SUPPORT */
3653
3654 lg_srcv->last_type = pdu->type;
3655
3656 update_data = 0;
3657 saved_num = block.num;
3658 saved_offset = offset;
3659
3660 while (offset < saved_offset + length) {
3661 uint32_t block_m = block.m;
3662
3663 /*
3664 * A BERT payload contains multiple logical 1024-byte blocks, but its
3665 * Block1 M bit describes the complete BERT payload. Mark intermediate
3666 * logical blocks as having more data so total_blocks is only set by the
3667 * final logical block.
3668 */
3669 if (block.bert && offset + 1024 < saved_offset + length)
3670 block_m = 1;
3671 if (!check_if_received_block(&lg_srcv->rec_blocks, block.num)) {
3672 /* Update list of blocks received */
3673 if (blocks_add_entry(&lg_srcv->rec_blocks, block.num, block_m)) {
3674 update_data = 1;
3675 } else {
3676 coap_ticks(&lg_srcv->rec_blocks.last_seen);
3677 coap_log_debug("Block nr %u ignored (too many missing blocks)\n", block.num);
3678#if COAP_Q_BLOCK_SUPPORT
3679 if (block_option == COAP_OPTION_Q_BLOCK1)
3680 request_missing = 1;
3681#endif /* COAP_Q_BLOCK_SUPPORT */
3682 }
3683 } else {
3684 coap_ticks(&lg_srcv->rec_blocks.last_seen);
3685 coap_log_debug("Duplicate block nr %u\n", block.num);
3686 }
3687 block.num++;
3688 offset = block.num << (block.szx + 4);
3689 }
3690 if (length)
3691 block.num--;
3692
3693#if COAP_Q_BLOCK_SUPPORT
3694 if (request_missing) {
3695 coap_request_missing_q_block1(session, lg_srcv, block.num);
3696 goto skip_app_handler;
3697 }
3698#endif /* COAP_Q_BLOCK_SUPPORT */
3699
3700 if (update_data) {
3701 /* Update saved data */
3702#if COAP_Q_BLOCK_SUPPORT
3703 lg_srcv->rec_blocks.processing_payload_set =
3704 block.num / COAP_MAX_PAYLOADS(session);
3705#endif /* COAP_Q_BLOCK_SUPPORT */
3706 if (lg_srcv->total_len < saved_offset + length) {
3707 lg_srcv->total_len = saved_offset + length;
3708 }
3709
3710#define USE_BLOCK_DATA_HANDLER (context && context->block_data_cb && \
3711 !resource->is_proxy_uri && \
3712 !resource->is_reverse_proxy && \
3713 ((session->block_mode & COAP_SINGLE_BLOCK_OR_Q) || block.bert) && \
3714 (resource->flags & COAP_RESOURCE_USE_BLOCK_DATA_HANDLER))
3715
3716 if (USE_BLOCK_DATA_HANDLER) {
3717 coap_response_t resp;
3718
3720 context->block_data_cb(session, pdu, resource,
3721 &lg_srcv->body_data,
3722 length, data, saved_offset,
3723 lg_srcv->total_len));
3724 if (resp != COAP_RESPONSE_OK) {
3725 response->code = COAP_RESPONSE_CODE(500);
3726 goto skip_app_handler;
3727 }
3728 } else {
3729 lg_srcv->body_data = coap_block_build_body_lkd(lg_srcv->body_data, length, data,
3730 saved_offset, lg_srcv->total_len);
3731 if (!lg_srcv->body_data) {
3732 coap_add_data(response, sizeof("Memory issue")-1,
3733 (const uint8_t *)"Memory issue");
3734 response->code = COAP_RESPONSE_CODE(500);
3735 goto skip_app_handler;
3736 }
3737 }
3738 } else {
3739#if COAP_Q_BLOCK_SUPPORT
3740 if (block_option == COAP_OPTION_Q_BLOCK1) {
3741 goto q_block_1_check;
3742 }
3743#endif /* COAP_Q_BLOCK_SUPPORT */
3744 /*
3745 * Every block carried by this request had already been received, so there
3746 * is no new data and the application must not see the request twice
3747 * (RFC7252 4.5). The request still has to be answered: falling straight
3748 * through to skip_app_handler leaves response->code at 0, which goes out
3749 * as an Empty ACK.
3750 * Re-issue the 2.31 Continue this block was given the first time.
3751 */
3752 if (block.m) {
3753 uint8_t buf[4];
3754
3755 coap_insert_option(response, block_option,
3756 coap_encode_var_safe(buf, sizeof(buf),
3757 (saved_num << 4) |
3758 (1 << 3) |
3759 lg_srcv->szx),
3760 buf);
3761 response->code = COAP_RESPONSE_CODE(231);
3762 }
3763 goto skip_app_handler;
3764 }
3765#if COAP_Q_BLOCK_SUPPORT
3766q_block_1_check:
3767#endif /* COAP_Q_BLOCK_SUPPORT */
3768
3769 if (block.m ||
3770 !check_all_blocks_in(&lg_srcv->rec_blocks)) {
3771 /* Not all the payloads of the body have arrived */
3772 if (block.m) {
3773 uint8_t buf[4];
3774
3775#if COAP_Q_BLOCK_SUPPORT
3776 if (block_option == COAP_OPTION_Q_BLOCK1) {
3777 if (check_all_blocks_in(&lg_srcv->rec_blocks)) {
3778 goto give_app_data;
3779 }
3780 if (lg_srcv->rec_blocks.used == 1 &&
3781 (lg_srcv->rec_blocks.range[0].end % COAP_MAX_PAYLOADS(session)) + 1
3782 == COAP_MAX_PAYLOADS(session)) {
3783 /* Seen all packets of this PAYLOAD_SET */
3784 if (block.num != lg_srcv->rec_blocks.range[0].end) {
3785 /* Blocks could arrive in wrong order but still need to send 2.31 */
3786 saved_num = block.num = lg_srcv->rec_blocks.range[0].end;
3787 }
3788 } else if (lg_srcv->rec_blocks.used > 1 &&
3789 (block.num % COAP_MAX_PAYLOADS(session)) + 1 == COAP_MAX_PAYLOADS(session) &&
3790 lg_srcv->rec_blocks.range[lg_srcv->rec_blocks.used-1].begin <
3791 lg_srcv->rec_blocks.range[lg_srcv->rec_blocks.used-1].end &&
3792 (lg_srcv->rec_blocks.range[lg_srcv->rec_blocks.used-1].end % COAP_MAX_PAYLOADS(session)) + 1
3793 == COAP_MAX_PAYLOADS(session)) {
3794 /*
3795 * At least the last 2 of a payload set have been received, but some
3796 * missing packets, but have seen the emd of a payload set.
3797 */
3798 coap_log_debug("Fast recovery for block %u\n", block.num);
3799 coap_request_missing_q_block1(session, lg_srcv, block.num);
3800 goto skip_app_handler;
3801 } else if (lg_srcv->rec_blocks.used > 1 &&
3802 (block.num / COAP_MAX_PAYLOADS(session)) >
3803 (lg_srcv->rec_blocks.range[0].end / COAP_MAX_PAYLOADS(session))) {
3804 /*
3805 * Current MAX_PAYLOAD chunk is different to last MAX_PAYLOAD chunk
3806 * with some missing packets in last MAX_PAYLOAD chunk.
3807 * client has timed out and starting transmission of next PAYLOAD_SET.
3808 */
3809 coap_request_missing_q_block1(session, lg_srcv, block.num);
3810 goto skip_app_handler;
3811 } else {
3812 /* The remote end will be sending the next one unless this
3813 is a MAX_PAYLOADS and all previous have been received
3814 as caught above */
3815 goto skip_app_handler;
3816 }
3817 if (COAP_PROTO_RELIABLE(session->proto) ||
3818 pdu->type != COAP_MESSAGE_NON)
3819 goto skip_app_handler;
3820 }
3821#endif /* COAP_Q_BLOCK_SUPPORT */
3822
3823 /* Check to see if block size is getting forced down */
3824 max_block_szx = COAP_BLOCK_MAX_SIZE_GET(session->block_mode);
3825 if (!block.bert && saved_num == 0 && max_block_szx != 0 &&
3826 max_block_szx < block.aszx) {
3827 block.aszx = max_block_szx;
3828 }
3829
3830 /*
3831 * If the last block has been seen, packets are coming in in
3832 * random order. If all blocks are now in, then need to send
3833 * complete payload to application and acknowledge this current
3834 * block.
3835 */
3836 if ((total == 0 && block.m) || !check_all_blocks_in(&lg_srcv->rec_blocks)) {
3837 /* Ask for the next block */
3838 coap_insert_option(response, block_option,
3839 coap_encode_var_safe(buf, sizeof(buf),
3840 (saved_num << 4) |
3841 (block.m << 3) |
3842 block.aszx),
3843 buf);
3844 response->code = COAP_RESPONSE_CODE(231);
3845 } else {
3846 /* Need to separately respond to this request */
3847 coap_pdu_t *tmp_pdu = coap_pdu_duplicate_lkd(response,
3848 session,
3849 response->actual_token.length,
3850 response->actual_token.s,
3852 if (tmp_pdu) {
3853 tmp_pdu->code = COAP_RESPONSE_CODE(231);
3854 if (coap_send_internal(session, tmp_pdu, NULL) == COAP_INVALID_MID) {
3855 /* lg_srcv may have got deleted */
3856 coap_lg_srcv_t *sg;
3857
3858 LL_FOREACH(session->lg_srcv, sg) {
3859 if (lg_srcv == sg) {
3860 /* Still there */
3861 break;
3862 }
3863 }
3864 if (!sg)
3865 goto skip_app_handler;
3866 }
3867 }
3868 if (lg_srcv->last_token) {
3869 coap_update_token(response, lg_srcv->last_token->length, lg_srcv->last_token->s);
3870 coap_update_token(pdu, lg_srcv->last_token->length, lg_srcv->last_token->s);
3871 }
3872 /* Pass the assembled pdu and body to the application */
3873 goto give_app_data;
3874 }
3875 } else {
3876 /* block.m Block More option not set. Some outstanding blocks */
3877#if COAP_Q_BLOCK_SUPPORT
3878 if (block_option != COAP_OPTION_Q_BLOCK1) {
3879#endif /* COAP_Q_BLOCK_SUPPORT */
3880 /* Last chunk - but not all in */
3881 coap_ticks(&lg_srcv->last_used);
3882 lg_srcv->no_more_seen = 1;
3883 coap_delete_bin_const(lg_srcv->last_token);
3884 lg_srcv->last_token = coap_new_bin_const(pdu->actual_token.s,
3885 pdu->actual_token.length);
3886
3887 /*
3888 * Need to just ACK (no response code) to handle client's NSTART.
3889 * When final missing block comes in, we will pass all the data
3890 * for processing so a 2.01, 2.04 etc. code can be generated
3891 * and responded to as a separate response "RFC7252 5.2.2. Separate"
3892 * If missing block(s) do not come in, then will generate a 4.08
3893 * when lg_srcv times out.
3894 * Fall through to skip_app_handler.
3895 */
3896#if COAP_Q_BLOCK_SUPPORT
3897 } else {
3898 coap_request_missing_q_block1(session, lg_srcv, block.num);
3899 }
3900#endif /* COAP_Q_BLOCK_SUPPORT */
3901 }
3902 goto skip_app_handler;
3903 }
3904
3905 /*
3906 * Entire payload received.
3907 * Remove the Block1 option as passing all of the data to
3908 * application layer. Add back in observe option if appropriate.
3909 * Adjust all other information.
3910 */
3911give_app_data:
3912 if (lg_srcv->observe_set) {
3914 lg_srcv->observe_length, lg_srcv->observe);
3915 }
3916 coap_remove_option(pdu, block_option);
3917 if (lg_srcv->body_data) {
3918 pdu->body_data = lg_srcv->body_data->s;
3919 pdu->body_length = lg_srcv->total_len;
3920 } else {
3921 pdu->body_data = NULL;
3922 pdu->body_length = 0;
3923 }
3924 pdu->body_offset = 0;
3925 pdu->body_total = lg_srcv->total_len;
3926 if (USE_BLOCK_DATA_HANDLER) {
3927 /* Data has already been provided - do not duplicate */
3928 if (pdu->data) {
3929 pdu->used_size = pdu->data - pdu->token - 1;
3930 pdu->data = NULL;
3931 }
3932 }
3933 coap_log_debug("Server app version of updated PDU\n");
3935 lg_srcv->dont_timeout = 1;
3936 *pfree_lg_srcv = lg_srcv;
3937
3938call_app_handler:
3939 if (lg_srcv_is_refed)
3940 coap_lg_srcv_release_lkd(session, lg_srcv);
3941 return 0;
3942
3943free_lg_srcv:
3944 LL_DELETE(session->lg_srcv, lg_srcv);
3945 coap_block_delete_lg_srcv(session, lg_srcv);
3946
3947skip_app_handler:
3948 if (lg_srcv_is_refed)
3949 coap_lg_srcv_release_lkd(session, lg_srcv);
3950 return 1;
3951}
3952#endif /* COAP_SERVER_SUPPORT */
3953
3954#if COAP_CLIENT_SUPPORT
3955#if COAP_Q_BLOCK_SUPPORT
3956static uint32_t
3957derive_cbor_value(const uint8_t **bp, size_t rem_len) {
3958 uint32_t value = **bp & 0x1f;
3959 (*bp)++;
3960 if (value < 24) {
3961 return value;
3962 } else if (value == 24) {
3963 if (rem_len < 2)
3964 return (uint32_t)-1;
3965 value = **bp;
3966 (*bp)++;
3967 return value;
3968 } else if (value == 25) {
3969 if (rem_len < 3)
3970 return (uint32_t)-1;
3971 value = **bp << 8;
3972 (*bp)++;
3973 value |= **bp;
3974 (*bp)++;
3975 return value;
3976 }
3977 if (rem_len < 5)
3978 return (uint32_t)-1;
3979 value = (uint32_t)(**bp) << 24;
3980 (*bp)++;
3981 value |= **bp << 16;
3982 (*bp)++;
3983 value |= **bp << 8;
3984 (*bp)++;
3985 value |= **bp;
3986 (*bp)++;
3987 return value;
3988}
3989#endif /* COAP_Q_BLOCK_SUPPORT */
3990
3991static int
3992check_freshness(coap_session_t *session, coap_pdu_t *rcvd, coap_pdu_t *sent,
3993 coap_lg_xmit_t *lg_xmit, coap_lg_crcv_t *lg_crcv) {
3994 /* Check for Echo option for freshness */
3995 coap_opt_iterator_t opt_iter;
3996 coap_opt_t *opt = coap_check_option(rcvd, COAP_OPTION_ECHO, &opt_iter);
3997
3998 if (opt) {
3999 if (sent || lg_xmit || lg_crcv) {
4000 /* Need to retransmit original request with Echo option added */
4001 coap_pdu_t *echo_pdu;
4002 coap_mid_t mid;
4003 const uint8_t *data;
4004 size_t data_len;
4005 int have_data = 0;
4006 uint8_t ltoken[8];
4007 size_t ltoken_len;
4008 uint64_t token;
4009
4010 if (sent) {
4011 if (coap_get_data(sent, &data_len, &data))
4012 have_data = 1;
4013 } else if (lg_xmit) {
4014 sent = lg_xmit->sent_pdu;
4015 if (lg_xmit->data_info->length) {
4016 size_t blk_size = (size_t)1 << (lg_xmit->blk_size + 4);
4017 size_t offset = (lg_xmit->last_block + 1) * blk_size;
4018 have_data = 1;
4019 data = &lg_xmit->data_info->data[offset];
4020 data_len = (lg_xmit->data_info->length - offset) > blk_size ? blk_size :
4021 lg_xmit->data_info->length - offset;
4022 }
4023 } else { /* lg_crcv */
4024 sent = lg_crcv->sent_pdu;
4025 if (coap_get_data(sent, &data_len, &data))
4026 have_data = 1;
4027 }
4028 if (lg_xmit) {
4029 token = STATE_TOKEN_FULL(lg_xmit->b.b1.state_token,
4030 ++lg_xmit->b.b1.count);
4031 } else {
4032 token = STATE_TOKEN_FULL(lg_crcv->state_token,
4033 ++lg_crcv->retry_counter);
4034 }
4035 ltoken_len = coap_encode_var_safe8(ltoken, sizeof(token), token);
4036 echo_pdu = coap_pdu_duplicate_lkd(sent, session, ltoken_len, ltoken,
4038 if (!echo_pdu)
4039 return 0;
4040 if (!coap_insert_option(echo_pdu, COAP_OPTION_ECHO,
4041 coap_opt_length(opt), coap_opt_value(opt)))
4042 goto not_sent;
4043 if (have_data) {
4044 coap_add_data(echo_pdu, data_len, data);
4045 }
4046 /* Need to track Observe token change if Observe */
4047 track_fetch_observe(echo_pdu, lg_crcv, 0, &echo_pdu->actual_token);
4048#if COAP_OSCORE_SUPPORT
4049 if (session->oscore_encryption &&
4050 (opt = coap_check_option(echo_pdu, COAP_OPTION_OBSERVE, &opt_iter)) &&
4052 /* Need to update the base PDU's Token for closing down Observe */
4053 if (lg_xmit) {
4054 lg_xmit->b.b1.state_token = token;
4055 } else {
4056 lg_crcv->state_token = token;
4057 }
4058 }
4059#endif /* COAP_OSCORE_SUPPORT */
4060 mid = coap_send_internal(session, echo_pdu, NULL);
4061 if (mid == COAP_INVALID_MID)
4062 goto not_sent;
4063 return 1;
4064 } else {
4065 /* Need to save Echo option value to add to next reansmission */
4066not_sent:
4067 coap_delete_bin_const(session->echo);
4068 session->echo = coap_new_bin_const(coap_opt_value(opt),
4069 coap_opt_length(opt));
4070 }
4071 }
4072 return 0;
4073}
4074
4075static void
4076track_echo(coap_session_t *session, coap_pdu_t *rcvd) {
4077 coap_opt_iterator_t opt_iter;
4078 coap_opt_t *opt = coap_check_option(rcvd, COAP_OPTION_ECHO, &opt_iter);
4079
4080 if (opt) {
4081 coap_delete_bin_const(session->echo);
4082 session->echo = coap_new_bin_const(coap_opt_value(opt),
4083 coap_opt_length(opt));
4084 }
4085}
4086
4087/*
4088 * Need to see if this is a response to a large body request transfer. If so,
4089 * need to initiate the request containing the next block and not trouble the
4090 * application. Note that Token must unique per request/response.
4091 *
4092 * Client receives large data acknowledgement from server (Block1)
4093 *
4094 * This is set up using coap_add_data_large_request_lkd()
4095 *
4096 * Client is using GET etc.
4097 *
4098 * Return: 0 Call application handler
4099 * 1 Do not call application handler - just send the built response
4100 */
4101int
4102coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *sent,
4103 coap_pdu_t *rcvd) {
4104 coap_lg_xmit_t *lg_xmit;
4105 coap_lg_crcv_t *lg_crcv = NULL;
4106 int lg_crcv_is_refed = 0;
4107
4108 lg_xmit = coap_find_lg_xmit(session, rcvd);
4109 if (lg_xmit) {
4110 /* lg_xmit found */
4111 size_t chunk = (size_t)1 << (lg_xmit->blk_size + 4);
4112 coap_block_b_t block;
4113
4114 lg_crcv = coap_find_lg_crcv(session, rcvd);
4115 if (lg_crcv) {
4116 coap_ticks(&lg_crcv->last_used);
4117 coap_lg_crcv_reference_lkd(lg_crcv);
4118 lg_crcv_is_refed = 1;
4119 }
4120
4121 if (COAP_RESPONSE_CLASS(rcvd->code) == 2 &&
4122 coap_get_block_b(session, rcvd, lg_xmit->option, &block)) {
4123
4124 if (block.bert) {
4125 coap_log_debug("found Block option, block is BERT, block nr. %u (%" PRIuS ")\n",
4126 block.num, lg_xmit->b.b1.bert_size);
4127 } else {
4128 coap_log_debug("found Block option, block size is %u, block nr. %u\n",
4129 1 << (block.szx + 4), block.num);
4130 }
4131 if (block.szx != lg_xmit->blk_size) {
4132 if (block.szx > lg_xmit->blk_size) {
4133 coap_log_info("ignoring request to increase Block size, "
4134 "(%u > %u)\n",
4135 1 << (block.szx + 4), 1 << (lg_xmit->blk_size + 4));
4136 } else {
4137 /*
4138 * Recompute the block number of the previous packet given the
4139 * new block size
4140 */
4141 block.num = (uint32_t)((chunk >> (block.szx + 4)) - 1);
4142 chunk = (size_t)1 << (lg_xmit->blk_size + 4);
4143#if COAP_Q_BLOCK_SUPPORT
4144 lg_xmit->send_blocks.range[0].begin = block.num;
4145 lg_xmit->send_blocks.range[0].end = (uint32_t)((lg_xmit->data_info->length -1) / chunk);
4146#endif /* COAP_Q_BLOCK_SUPPORT */
4147 lg_xmit->blk_size = block.szx;
4148 coap_log_debug("new Block size is %u, block number %u completed\n",
4149 1 << (block.szx + 4), block.num);
4150 block.bert = 0;
4151 block.aszx = block.szx;
4152 }
4153 }
4154 track_echo(session, rcvd);
4155#if COAP_Q_BLOCK_SUPPORT
4156 if (rcvd->code == COAP_RESPONSE_CODE(231) &&
4157 lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4158 coap_send_q_blocks(session, lg_xmit, block, lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
4159 goto skip_app_handler;
4160 }
4161#endif /* COAP_Q_BLOCK_SUPPORT */
4162 if (lg_xmit->last_block == (int)block.num &&
4163 lg_xmit->option != COAP_OPTION_Q_BLOCK1) {
4164 /*
4165 * Duplicate Block1 ACK
4166 *
4167 * RFCs not clear here, but on a lossy connection, there could
4168 * be multiple Block1 ACKs, causing the client to retransmit the
4169 * same block multiple times, or the server retransmitting the
4170 * same ACK.
4171 *
4172 * Once a block has been ACKd, there is no need to retransmit it.
4173 */
4174 goto skip_app_handler;
4175 }
4176 if (block.bert)
4177 block.num += (unsigned int)(lg_xmit->b.b1.bert_size / 1024 - 1);
4178 lg_xmit->last_block = block.num;
4179 if ((block.num + 1) * chunk < lg_xmit->data_info->length) {
4180 /* Build the next PDU request based off the skeletal PDU */
4181 uint8_t buf[8];
4182 coap_pdu_t *pdu;
4183 uint64_t token = STATE_TOKEN_FULL(lg_xmit->b.b1.state_token, ++lg_xmit->b.b1.count);
4184 size_t len = coap_encode_var_safe8(buf, sizeof(token), token);
4185 size_t offset;
4186
4187 if (lg_xmit->sent_pdu->code == COAP_REQUEST_CODE_FETCH) {
4188 /* Need to handle Observe for large FETCH */
4189 if (lg_crcv) {
4190 if (coap_binary_equal(lg_xmit->b.b1.app_token, lg_crcv->app_token)) {
4191 coap_bin_const_t *new_token;
4192 coap_bin_const_t ctoken = { len, buf };
4193
4194 /* Need to save/restore Observe Token for large FETCH */
4195 new_token = track_fetch_observe(lg_xmit->sent_pdu, lg_crcv, block.num + 1,
4196 &ctoken);
4197 if (new_token) {
4198 assert(len <= sizeof(buf));
4199 len = new_token->length;
4200 memcpy(buf, new_token->s, len);
4201 }
4202 }
4203 }
4204 }
4205 pdu = coap_pdu_duplicate_lkd(lg_xmit->sent_pdu, session,
4206 len, buf, NULL, COAP_BOOL_FALSE);
4207 if (!pdu)
4208 goto fail_body;
4209
4210 /*
4211 * If initial transmit was multicast, that would have been NON.
4212 * Make subsequent traffic CON for reliability.
4213 */
4214 if (session->sock.flags & COAP_SOCKET_MULTICAST) {
4215 pdu->type = COAP_MESSAGE_CON;
4216 }
4217
4218 block.num++;
4219 offset = block.num * chunk;
4220 if (block.bert) {
4221 size_t token_options = pdu->data ? (size_t)(pdu->data - pdu->token) :
4222 pdu->used_size;
4223 block.m = (lg_xmit->data_info->length - offset) >
4224 ((pdu->max_size - token_options) /1024) * 1024;
4225 } else {
4226 block.m = (offset + chunk) < lg_xmit->data_info->length;
4227 }
4228 coap_update_option(pdu, lg_xmit->option,
4229 coap_encode_var_safe(buf, sizeof(buf),
4230 (block.num << 4) |
4231 (block.m << 3) |
4232 block.aszx),
4233 buf);
4234
4235 if (lg_xmit->data_info->get_func) {
4236#if COAP_CONSTRAINED_STACK
4237 /* Protected by global_lock if needed */
4238 static uint8_t l_data[1024];
4239#else /* ! COAP_CONSTRAINED_STACK */
4240 uint8_t l_data[1024];
4241#endif /* ! COAP_CONSTRAINED_STACK */
4242 size_t l_length;
4243
4244 assert(chunk <= 1024);
4245 if (lg_xmit->data_info->get_func(session, chunk,
4246 block.num * chunk, l_data, &l_length,
4247 lg_xmit->data_info->app_ptr)) {
4248 if (!coap_add_data(pdu, l_length, l_data)) {
4249 goto fail_body;
4250 }
4251 }
4252 } else {
4253 if (!coap_add_block_b_data(pdu,
4254 lg_xmit->data_info->length,
4255 lg_xmit->data_info->data,
4256 &block))
4257 goto fail_body;
4258 }
4259 lg_xmit->b.b1.bert_size = block.chunk_size;
4260 coap_ticks(&lg_xmit->last_sent);
4261#if COAP_Q_BLOCK_SUPPORT
4262 if (lg_xmit->option == COAP_OPTION_Q_BLOCK1 &&
4263 pdu->type == COAP_MESSAGE_NON) {
4264 if (coap_send_q_block1(session, block, pdu,
4265 COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4266 goto fail_body;
4267 goto skip_app_handler;
4268 } else if (coap_send_internal(session, pdu, NULL) == COAP_INVALID_MID)
4269 goto fail_body;
4270#else /* ! COAP_Q_BLOCK_SUPPORT */
4271 if (coap_send_internal(session, pdu, NULL) == COAP_INVALID_MID)
4272 goto fail_body;
4273#endif /* ! COAP_Q_BLOCK_SUPPORT */
4274 goto skip_app_handler;
4275 }
4276 } else if (COAP_RESPONSE_CLASS(rcvd->code) == 2) {
4277 /*
4278 * Not a block response asking for the next block.
4279 * Could be an Observe response overlapping with block FETCH doing
4280 * Observe cancellation.
4281 */
4282 coap_opt_iterator_t opt_iter;
4283 coap_opt_t *obs_opt;
4284 int observe_action = -1;
4285
4286 if (lg_xmit->sent_pdu->code != COAP_REQUEST_CODE_FETCH) {
4287 goto lg_xmit_finished;
4288 }
4289 obs_opt = coap_check_option(lg_xmit->sent_pdu,
4291 &opt_iter);
4292 if (obs_opt) {
4293 observe_action = coap_decode_var_bytes(coap_opt_value(obs_opt),
4294 coap_opt_length(obs_opt));
4295 }
4296 if (observe_action != COAP_OBSERVE_CANCEL) {
4297 goto lg_xmit_finished;
4298 }
4299 obs_opt = coap_check_option(rcvd,
4301 &opt_iter);
4302 if (obs_opt) {
4303 goto call_app_handler;
4304 }
4305 goto lg_xmit_finished;
4306 } else if (rcvd->code == COAP_RESPONSE_CODE(401)) {
4307 if (check_freshness(session, rcvd, sent, lg_xmit, NULL))
4308 goto skip_app_handler;
4309#if COAP_Q_BLOCK_SUPPORT
4310 } else if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4311 /* Q-Block1 or Q-Block2 not present in p - duplicate error ? */
4312 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &block) ||
4313 coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK1, &block))
4314 goto skip_app_handler;
4315 } else if (rcvd->code == COAP_RESPONSE_CODE(408) &&
4316 lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
4317 size_t length;
4318 const uint8_t *data;
4319 coap_opt_iterator_t opt_iter;
4320 coap_opt_t *fmt_opt = coap_check_option(rcvd,
4322 &opt_iter);
4323 uint16_t fmt = fmt_opt ?
4325 coap_opt_length(fmt_opt)) :
4327
4329 goto fail_body;
4330
4331 if (COAP_PROTO_RELIABLE(session->proto) ||
4332 rcvd->type != COAP_MESSAGE_NON) {
4333 coap_log_debug("Unexpected 4.08 - protocol violation - ignore\n");
4334 goto skip_app_handler;
4335 }
4336
4337 if (coap_get_data(rcvd, &length, &data)) {
4338 /* Need to decode CBOR to work out what blocks to re-send */
4339 const uint8_t *bp = data;
4340 uint32_t i;
4341
4342 for (i = 0; (bp < data + length) &&
4343 i < COAP_MAX_PAYLOADS(session); i++) {
4344 if ((*bp & 0xc0) != 0x00) /* uint(value) */
4345 goto fail_cbor;
4346 block.num = derive_cbor_value(&bp, data + length - bp);
4347 coap_log_debug("Q-Block1: Missing block %d\n", block.num);
4348 if (block.num > (1 << 20) -1)
4349 goto fail_cbor;
4350 block.m = (block.num + 1) * chunk < lg_xmit->data_info->length;
4351 block.szx = lg_xmit->blk_size;
4352
4353 blocks_add_entry(&lg_xmit->send_blocks, block.num, block.m);
4354 }
4355 if (lg_xmit->send_blocks.used) {
4356 /* Flush out the first one */
4357 block.num = lg_xmit->send_blocks.range[0].begin;
4358 block.m = (block.num + 1) * chunk < lg_xmit->data_info->length;
4359 coap_send_q_blocks(session, lg_xmit, block, lg_xmit->sent_pdu, COAP_SEND_MISSING);
4360 }
4361 goto skip_app_handler;
4362 }
4363fail_cbor:
4364 coap_log_info("Invalid application/missing-blocks+cbor-seq\n");
4365#endif /* COAP_Q_BLOCK_SUPPORT */
4366 }
4367 goto lg_xmit_finished;
4368 }
4369 goto call_app_handler;
4370
4371fail_body:
4373 /* There has been an internal error of some sort */
4374 rcvd->code = COAP_RESPONSE_CODE(500);
4375lg_xmit_finished:
4376 if (lg_crcv) {
4377 if (STATE_TOKEN_BASE(lg_xmit->b.b1.state_token) ==
4378 STATE_TOKEN_BASE(lg_crcv->state_token)) {
4379 /* In case of observe */
4380 lg_crcv->state_token = lg_xmit->b.b1.state_token;
4381 lg_crcv->retry_counter = lg_xmit->b.b1.count;
4382 }
4383 }
4384 if (!lg_crcv) {
4385 /* need to put back original token into rcvd */
4386 if (lg_xmit->b.b1.app_token)
4387 coap_update_token(rcvd, lg_xmit->b.b1.app_token->length,
4388 lg_xmit->b.b1.app_token->s);
4389 coap_log_debug("Client app version of updated PDU (1)\n");
4391 } else {
4392 lg_crcv->sent_pdu->lg_xmit = 0;
4393 }
4394
4395 if (sent) {
4396 /* need to put back original token into sent */
4397 if (lg_xmit->b.b1.app_token)
4398 coap_update_token(sent, lg_xmit->b.b1.app_token->length,
4399 lg_xmit->b.b1.app_token->s);
4400 if (sent->lg_xmit)
4401 coap_remove_option(sent, sent->lg_xmit->option);
4402 sent->lg_xmit = NULL;
4403 }
4404 LL_DELETE(session->lg_xmit, lg_xmit);
4405 coap_block_delete_lg_xmit(session, lg_xmit);
4406
4407call_app_handler:
4408 if (lg_crcv_is_refed)
4409 coap_lg_crcv_release_lkd(session, lg_crcv);
4410 return 0;
4411
4412skip_app_handler:
4413 if (lg_crcv_is_refed)
4414 coap_lg_crcv_release_lkd(session, lg_crcv);
4415 return 1;
4416}
4417#endif /* COAP_CLIENT_SUPPORT */
4418
4419void
4421 coap_block_data_handler_t block_data_handler) {
4422 context->block_data_cb = block_data_handler;
4423}
4424
4426coap_block_build_body(coap_binary_t *body_data, size_t length,
4427 const uint8_t *data, size_t offset, size_t total) {
4428 coap_binary_t *ret;
4429
4430 coap_lock_lock(return NULL);
4431 ret = coap_block_build_body_lkd(body_data, length, data, offset, total);
4433 return ret;
4434}
4435/*
4436 * Re-assemble payloads into a body
4437 */
4440 const uint8_t *data, size_t offset, size_t total) {
4441 if (data == NULL)
4442 return NULL;
4443 if (body_data == NULL && total) {
4444 body_data = coap_new_binary(total);
4445 }
4446 if (body_data == NULL)
4447 return NULL;
4448
4449 /* Check no overflow (including a 8 byte small headroom) */
4450 if (SIZE_MAX - length < 8 || offset > SIZE_MAX - length - 8) {
4451 coap_delete_binary(body_data);
4452 return NULL;
4453 }
4454
4455 /* Update saved data */
4456 if (offset + length <= total && body_data->length >= total) {
4457 memcpy(&body_data->s[offset], data, length);
4458 } else {
4459 /*
4460 * total may be inaccurate as per
4461 * https://rfc-editor.org/rfc/rfc7959#section-4
4462 * o In a request carrying a Block1 Option, to indicate the current
4463 * estimate the client has of the total size of the resource
4464 * representation, measured in bytes ("size indication").
4465 * o In a response carrying a Block2 Option, to indicate the current
4466 * estimate the server has of the total size of the resource
4467 * representation, measured in bytes ("size indication").
4468 */
4469 coap_binary_t *new = coap_resize_binary(body_data, offset + length);
4470
4471 if (new) {
4472 body_data = new;
4473 memcpy(&body_data->s[offset], data, length);
4474 } else {
4475 coap_delete_binary(body_data);
4476 return NULL;
4477 }
4478 }
4479 return body_data;
4480}
4481
4482#if COAP_CLIENT_SUPPORT
4483/*
4484 * Need to see if this is a large body response to a request. If so,
4485 * need to initiate the request for the next block and not trouble the
4486 * application. Note that Token must be unique per request/response.
4487 *
4488 * This is set up using coap_send()
4489 * Client receives large data from server ((Q-)Block2)
4490 *
4491 * Return: 0 Call application handler
4492 * 1 Do not call application handler - just sent the next request
4493 */
4494int
4495coap_handle_response_get_block(coap_context_t *context,
4496 coap_session_t *session,
4497 coap_pdu_t *sent,
4498 coap_pdu_t *rcvd,
4499 coap_recurse_t recursive) {
4500 coap_lg_crcv_t *lg_crcv;
4501 coap_block_b_t block;
4502#if COAP_Q_BLOCK_SUPPORT
4503 coap_block_b_t qblock;
4504#endif /* COAP_Q_BLOCK_SUPPORT */
4505 int have_block = 0;
4506 uint16_t block_opt = 0;
4507 size_t offset;
4508 int ack_rst_sent = 0;
4509 coap_opt_iterator_t opt_iter;
4510
4512 memset(&block, 0, sizeof(block));
4513#if COAP_Q_BLOCK_SUPPORT
4514 memset(&qblock, 0, sizeof(qblock));
4515#endif /* COAP_Q_BLOCK_SUPPORT */
4516 lg_crcv = coap_find_lg_crcv(session, rcvd);
4517 if (lg_crcv) {
4518 size_t chunk = 0;
4519 uint8_t buf[8];
4520 coap_tick_t adjust;
4521
4522 if (COAP_RESPONSE_CLASS(rcvd->code) == 2) {
4523 size_t length;
4524 const uint8_t *data;
4526 &opt_iter);
4527 size_t size2 = size_opt ?
4529 coap_opt_length(size_opt)) : 0;
4530
4531 /* length and data are cleared on error */
4532 (void)coap_get_data(rcvd, &length, &data);
4533 rcvd->body_offset = 0;
4534 rcvd->body_total = length;
4535 if (coap_get_block_b(session, rcvd, COAP_OPTION_BLOCK2, &block)) {
4536 have_block = 1;
4537 block_opt = COAP_OPTION_BLOCK2;
4538 }
4539#if COAP_Q_BLOCK_SUPPORT
4540 if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4541 if (have_block) {
4542 coap_log_warn("Both Block1 and Q-Block1 not supported in a response\n");
4543 }
4544 have_block = 1;
4545 block_opt = COAP_OPTION_Q_BLOCK2;
4546 block = qblock;
4547 /* server indicating that it supports Q_BLOCK */
4548 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK)) {
4549 set_block_mode_has_q(session->block_mode);
4550 }
4551 }
4552#endif /* COAP_Q_BLOCK_SUPPORT */
4553 track_echo(session, rcvd);
4554 if (have_block && (block.m || length)) {
4555 coap_opt_t *fmt_opt = coap_check_option(rcvd,
4557 &opt_iter);
4558 uint16_t fmt = fmt_opt ?
4560 coap_opt_length(fmt_opt)) :
4562 coap_opt_t *etag_opt = coap_check_option(rcvd,
4564 &opt_iter);
4565 size_t saved_offset;
4566 int updated_block;
4567
4568#if COAP_Q_BLOCK_SUPPORT
4569 if (block_opt == COAP_OPTION_Q_BLOCK2 && (!size_opt || !etag_opt)) {
4570 /* RFC9177 section-4.4 */
4571 coap_log_info("Q-Block2: Size2 and ETag options required\n");
4572 /* Try to hint to the server there is an issue */
4573 coap_send_rst_lkd(session, rcvd);
4575 return 1;
4576 }
4577#endif /* COAP_Q_BLOCK_SUPPORT */
4578 if (length > block.chunk_size) {
4579 coap_log_debug("block: Oversized packet - reduced to %"PRIu32" from %" PRIuS "\n",
4580 block.chunk_size, length);
4581 length = block.chunk_size;
4582 }
4583 if (block.m && length != block.chunk_size) {
4584 coap_log_warn("block: Undersized packet - expected %"PRIu32", got %" PRIuS "\n",
4585 block.chunk_size, length);
4586 /* Unclear how to properly handle this */
4587 rcvd->code = COAP_RESPONSE_CODE(402);
4588 goto expire_lg_crcv;
4589 }
4590 /* Possibility that Size2 not sent, or is too small */
4591 chunk = (size_t)1 << (block.szx + 4);
4592 offset = block.num * chunk;
4593 if (size2 < (offset + length)) {
4594 if (block.m)
4595 size2 = offset + length + 1;
4596 else
4597 size2 = offset + length;
4598 }
4599 saved_offset = offset;
4600
4601 if (lg_crcv->initial) {
4602#if COAP_Q_BLOCK_SUPPORT
4603reinit:
4604#endif /* COAP_Q_BLOCK_SUPPORT */
4605 lg_crcv->initial = 0;
4606 if (lg_crcv->body_data) {
4607 coap_free_type(COAP_STRING, lg_crcv->body_data);
4608 lg_crcv->body_data = NULL;
4609 }
4610 if (etag_opt) {
4611 lg_crcv->etag_length = (uint8_t)min(coap_opt_length(etag_opt), sizeof(lg_crcv->etag));
4612 memcpy(lg_crcv->etag, coap_opt_value(etag_opt), lg_crcv->etag_length);
4613 lg_crcv->etag_set = 1;
4614 } else {
4615 lg_crcv->etag_set = 0;
4616 }
4617 lg_crcv->total_len = size2;
4618 lg_crcv->content_format = fmt;
4619 lg_crcv->szx = block.szx;
4620 lg_crcv->block_option = block_opt;
4621 lg_crcv->last_type = rcvd->type;
4622 lg_crcv->rec_blocks.used = 0;
4623 lg_crcv->rec_blocks.total_blocks = 0;
4624#if COAP_Q_BLOCK_SUPPORT
4625 lg_crcv->rec_blocks.processing_payload_set = 0;
4626#endif /* COAP_Q_BLOCK_SUPPORT */
4627 }
4628 if (lg_crcv->total_len < size2)
4629 lg_crcv->total_len = size2;
4630
4631 /* Check whether we can handle this size */
4632 uint32_t max_body;
4633 uint8_t max_block_szx;
4634
4635 max_block_szx = COAP_BLOCK_MAX_SIZE_GET(session->block_mode);
4636 if (max_block_szx == 0 || max_block_szx > block.szx) {
4637 max_block_szx = block.szx;
4638 }
4639 max_body = ((1UL << 20) * (1 << (max_block_szx + 4)));
4640 if (max_body > MAX_BLK_LEN)
4641 max_body = MAX_BLK_LEN;
4642 if ((context->max_body_size && size2 > context->max_body_size) ||
4643 (size2 > max_body)) {
4644 uint32_t max_body_size = context->max_body_size;
4645
4646 if (max_body_size == 0 || max_body < max_body_size) {
4647 max_body_size = max_body;
4648 }
4649 coap_log_warn("Unable to handle body size %" PRIuS " (max %" PRIu32 ")\n", size2, max_body_size);
4650 /* Try to hint to the server there is an issue */
4651 coap_send_rst_lkd(session, rcvd);
4653 return 1;
4654 }
4655
4656 if (etag_opt) {
4657 if (!full_match(coap_opt_value(etag_opt),
4658 coap_opt_length(etag_opt),
4659 lg_crcv->etag, lg_crcv->etag_length)) {
4660 /* body of data has changed - need to restart request */
4661 coap_pdu_t *pdu;
4662 uint64_t token = STATE_TOKEN_FULL(lg_crcv->state_token,
4663 ++lg_crcv->retry_counter);
4664 size_t len = coap_encode_var_safe8(buf, sizeof(token), token);
4665 coap_opt_filter_t drop_options;
4666
4667#if COAP_Q_BLOCK_SUPPORT
4668 if (block_opt == COAP_OPTION_Q_BLOCK2)
4669 goto reinit;
4670#endif /* COAP_Q_BLOCK_SUPPORT */
4671
4672 coap_log_warn("Data body updated during receipt - new request started\n");
4673 if (!(session->block_mode & COAP_BLOCK_SINGLE_BODY))
4675
4676 lg_crcv->initial = 1;
4677 coap_free_type(COAP_STRING, lg_crcv->body_data);
4678 lg_crcv->body_data = NULL;
4679
4680 coap_session_new_token(session, &len, buf);
4681 memset(&drop_options, 0, sizeof(coap_opt_filter_t));
4684 pdu = coap_pdu_duplicate_lkd(lg_crcv->sent_pdu, session, len, buf,
4685 &drop_options, COAP_BOOL_FALSE);
4686 if (!pdu)
4687 goto fail_resp;
4688
4689 coap_update_option(pdu, block_opt,
4690 coap_encode_var_safe(buf, sizeof(buf),
4691 (0 << 4) | (0 << 3) | block.aszx),
4692 buf);
4693
4694 if (coap_send_internal(session, pdu, NULL) == COAP_INVALID_MID)
4695 goto fail_resp;
4696
4697 goto skip_app_handler;
4698 }
4699 } else if (lg_crcv->etag_set) {
4700 /* Cannot handle this change in ETag to not being there */
4701 coap_log_warn("Not all blocks have ETag option\n");
4702 goto fail_resp;
4703 }
4704
4705 if (fmt != lg_crcv->content_format) {
4706 coap_log_warn("Content-Format option mismatch\n");
4707 goto fail_resp;
4708 }
4709#if COAP_Q_BLOCK_SUPPORT
4710 if (block_opt == COAP_OPTION_Q_BLOCK2 && size2 != lg_crcv->total_len) {
4711 coap_log_warn("Size2 option mismatch (%"PRIuS " != %" PRIuS ")\n",
4712 size2, lg_crcv->total_len);
4713 goto fail_resp;
4714 }
4715#endif /* COAP_Q_BLOCK_SUPPORT */
4716 if (block.num == 0) {
4717 coap_opt_t *obs_opt = coap_check_option(rcvd,
4719 &opt_iter);
4720 if (obs_opt) {
4721 lg_crcv->observe_length = min(coap_opt_length(obs_opt), 3);
4722 memcpy(lg_crcv->observe, coap_opt_value(obs_opt), lg_crcv->observe_length);
4723 lg_crcv->observe_set = 1;
4724 } else {
4725 lg_crcv->observe_set = 0;
4726 }
4727 }
4728 updated_block = 0;
4729 while (offset < saved_offset + length) {
4730 if (!check_if_received_block(&lg_crcv->rec_blocks, block.num)) {
4731#if COAP_Q_BLOCK_SUPPORT
4732 uint32_t this_payload_set = block.num / COAP_MAX_PAYLOADS(session);
4733#endif /* COAP_Q_BLOCK_SUPPORT */
4734
4735 coap_log_debug("found Block option, block size is %u, block nr. %u\n",
4736 1 << (block.szx + 4), block.num);
4737 /* Update list of blocks received */
4738 if (blocks_add_entry(&lg_crcv->rec_blocks, block.num, block.m)) {
4739 updated_block = 1;
4740 } else {
4741 coap_log_debug("Block nr %u ignored (too many missing blocks)\n", block.num);
4742 }
4743#if COAP_Q_BLOCK_SUPPORT
4744 if (block_opt == COAP_OPTION_Q_BLOCK2) {
4745 if (lg_crcv->rec_blocks.used > 1 &&
4746 (block.num == lg_crcv->rec_blocks.range[lg_crcv->rec_blocks.used-1].end ||
4747 block.num == lg_crcv->rec_blocks.range[lg_crcv->rec_blocks.used-1].end - 1) &&
4748 lg_crcv->rec_blocks.range[lg_crcv->rec_blocks.used-1].begin <
4749 lg_crcv->rec_blocks.range[lg_crcv->rec_blocks.used-1].end &&
4750 (lg_crcv->rec_blocks.range[lg_crcv->rec_blocks.used-1].end % COAP_MAX_PAYLOADS(session)) + 1
4751 == COAP_MAX_PAYLOADS(session)) {
4752 /*
4753 * At least the last 2 of a PAYLOAD_SET have been received, but some
4754 * missing packets, but have seen the emd of a PAYLOAD_SET.
4755 */
4756 coap_log_debug("Fast recovery for block %u\n", block.num);
4757 coap_request_missing_q_block2(session, lg_crcv);
4758 } else if (lg_crcv->rec_blocks.used &&
4759 this_payload_set > lg_crcv->rec_blocks.processing_payload_set &&
4760 this_payload_set != lg_crcv->rec_blocks.latest_payload_set) {
4761 coap_request_missing_q_block2(session, lg_crcv);
4762 }
4763 }
4764 lg_crcv->rec_blocks.latest_payload_set = this_payload_set;
4765#endif /* COAP_Q_BLOCK_SUPPORT */
4766 } else {
4767 coap_log_debug("Duplicate block nr %u\n", block.num);
4768 }
4769 block.num++;
4770 offset = block.num << (block.szx + 4);
4771 if (!block.bert && block_opt != COAP_OPTION_Q_BLOCK2)
4772 break;
4773 }
4774 block.num--;
4775 /* Only process if not duplicate block */
4776 if (updated_block) {
4777 void *body_free;
4778
4779 /* Update last_used to prevent premature timeout during long transfers */
4780 coap_ticks(&lg_crcv->last_used);
4781
4782 if ((session->block_mode & COAP_SINGLE_BLOCK_OR_Q) || block.bert) {
4783 if (size2 < saved_offset + length) {
4784 size2 = saved_offset + length;
4785 }
4786 if (context && context->block_data_cb) {
4787 coap_response_t resp;
4788
4790 context->block_data_cb(session, rcvd, 0,
4791 &lg_crcv->body_data,
4792 length, data,
4793 saved_offset, size2));
4794 if (resp != COAP_RESPONSE_OK) {
4795 goto fail_resp;
4796 }
4797 } else {
4798 lg_crcv->body_data = coap_block_build_body_lkd(lg_crcv->body_data, length, data,
4799 saved_offset, size2);
4800 if (lg_crcv->body_data == NULL) {
4801 goto fail_resp;
4802 }
4803 }
4804 }
4805 if (block.m || !check_all_blocks_in(&lg_crcv->rec_blocks)) {
4806 /* Not all the payloads of the body have arrived */
4807 size_t len;
4808 coap_pdu_t *pdu;
4809 uint64_t token;
4810 coap_opt_filter_t drop_options;
4811
4812 if (block.m) {
4813#if COAP_Q_BLOCK_SUPPORT
4814 if (block_opt == COAP_OPTION_Q_BLOCK2) {
4815 /* Blocks could arrive in wrong order */
4816 if (check_all_blocks_in(&lg_crcv->rec_blocks)) {
4817 goto give_to_app;
4818 }
4819 if (check_all_blocks_in_for_payload_set(session,
4820 &lg_crcv->rec_blocks)) {
4821 block.num = lg_crcv->rec_blocks.range[0].end;
4822 /* Now requesting next payload */
4823 lg_crcv->rec_blocks.processing_payload_set =
4824 block.num / COAP_MAX_PAYLOADS(session) + 1;
4825 if (check_any_blocks_next_payload_set(session,
4826 &lg_crcv->rec_blocks)) {
4827 /* Need to ask for them individually */
4828 coap_request_missing_q_block2(session, lg_crcv);
4829 goto skip_app_handler;
4830 }
4831 } else {
4832 /* The remote end will be sending the next one unless this
4833 is a MAX_PAYLOADS and all previous have been received */
4834 goto skip_app_handler;
4835 }
4836 if (COAP_PROTO_RELIABLE(session->proto) ||
4837 rcvd->type != COAP_MESSAGE_NON)
4838 goto skip_app_handler;
4839
4840 } else
4841#endif /* COAP_Q_BLOCK_SUPPORT */
4842 block.m = 0;
4843
4844 /* Ask for the next block */
4845 token = STATE_TOKEN_FULL(lg_crcv->state_token, ++lg_crcv->retry_counter);
4846 len = coap_encode_var_safe8(buf, sizeof(token), token);
4847 memset(&drop_options, 0, sizeof(coap_opt_filter_t));
4849 pdu = coap_pdu_duplicate_lkd(lg_crcv->sent_pdu, session, len, buf,
4850 &drop_options, COAP_BOOL_FALSE);
4851 if (!pdu)
4852 goto fail_resp;
4853
4854 if (rcvd->type == COAP_MESSAGE_NON)
4855 pdu->type = COAP_MESSAGE_NON; /* Server is using NON */
4856
4857 /* Only sent with the first block */
4859
4860 coap_update_option(pdu, block_opt,
4861 coap_encode_var_safe(buf, sizeof(buf),
4862 ((block.num + 1) << 4) |
4863 (block.m << 3) | block.aszx),
4864 buf);
4865
4867 (void)coap_get_data(lg_crcv->sent_pdu, &length, &data);
4868 coap_add_data_large_internal(session, NULL, pdu, NULL, NULL, -1, 0, length, data, NULL, NULL, NULL,
4869 0, 0);
4870 }
4871 if (coap_send_internal(session, pdu, NULL) == COAP_INVALID_MID)
4872 /* Session could now be disconnected, so no lg_crcv */
4873 goto skip_app_handler;
4874 }
4875 if ((session->block_mode & COAP_SINGLE_BLOCK_OR_Q) || block.bert)
4876 goto skip_app_handler;
4877
4878 /* need to put back original token into rcvd */
4879 coap_update_token(rcvd, lg_crcv->app_token->length, lg_crcv->app_token->s);
4880 rcvd->body_offset = saved_offset;
4881#if COAP_Q_BLOCK_SUPPORT
4882 rcvd->body_total = block_opt == COAP_OPTION_Q_BLOCK2 ?
4883 lg_crcv->total_len : size2;
4884#else /* ! COAP_Q_BLOCK_SUPPORT */
4885 rcvd->body_total = size2;
4886#endif /* ! COAP_Q_BLOCK_SUPPORT */
4887 coap_log_debug("Client app version of updated PDU (2)\n");
4889
4890 if (sent) {
4891 /* need to put back original token into sent */
4892 if (lg_crcv->app_token)
4893 coap_update_token(sent, lg_crcv->app_token->length,
4894 lg_crcv->app_token->s);
4895 coap_remove_option(sent, lg_crcv->block_option);
4896 }
4897 goto call_app_handler;
4898 }
4899#if COAP_Q_BLOCK_SUPPORT
4900give_to_app:
4901#endif /* COAP_Q_BLOCK_SUPPORT */
4902 if ((session->block_mode & COAP_SINGLE_BLOCK_OR_Q) || block.bert) {
4903 /* Pretend that there is no block */
4904 coap_remove_option(rcvd, block_opt);
4905 if (lg_crcv->observe_set) {
4907 lg_crcv->observe_length, lg_crcv->observe);
4908 }
4909 rcvd->body_data = lg_crcv->body_data ? lg_crcv->body_data->s : NULL;
4910#if COAP_Q_BLOCK_SUPPORT
4911 if (context && context->block_data_cb) {
4912 /* Data has already been provided - do not duplicate */
4913 if (rcvd->data) {
4914 rcvd->used_size = rcvd->data - rcvd->token - 1;
4915 rcvd->data = NULL;
4916 }
4917 }
4918 rcvd->body_length = block_opt == COAP_OPTION_Q_BLOCK2 ?
4919 lg_crcv->total_len : saved_offset + length;
4920#else /* ! COAP_Q_BLOCK_SUPPORT */
4921 rcvd->body_length = saved_offset + length;
4922#endif /* ! COAP_Q_BLOCK_SUPPORT */
4923 rcvd->body_offset = 0;
4924 rcvd->body_total = rcvd->body_length;
4925 } else {
4926 rcvd->body_offset = saved_offset;
4927#if COAP_Q_BLOCK_SUPPORT
4928 rcvd->body_total = block_opt == COAP_OPTION_Q_BLOCK2 ?
4929 lg_crcv->total_len : size2;
4930#else /* ! COAP_Q_BLOCK_SUPPORT */
4931 rcvd->body_total = size2;
4932#endif /* ! COAP_Q_BLOCK_SUPPORT */
4933 }
4934 /* need to put back original token into rcvd */
4935 if (!coap_binary_equal(&rcvd->actual_token, lg_crcv->app_token)) {
4936 coap_update_token(rcvd, lg_crcv->app_token->length, lg_crcv->app_token->s);
4937 coap_log_debug("Client app version of updated PDU (3)\n");
4939 }
4940 if (sent) {
4941 /* need to put back original token into sent */
4942 if (lg_crcv->app_token)
4943 coap_update_token(sent, lg_crcv->app_token->length,
4944 lg_crcv->app_token->s);
4945 coap_remove_option(sent, lg_crcv->block_option);
4946 }
4947 body_free = lg_crcv->body_data;
4948 lg_crcv->body_data = NULL;
4949 coap_call_response_handler(session, sent, rcvd, body_free);
4950
4951 ack_rst_sent = 1;
4952 if (lg_crcv->observe_set == 0) {
4953 /* Expire this entry */
4954 LL_DELETE(session->lg_crcv, lg_crcv);
4955 coap_block_delete_lg_crcv(session, lg_crcv);
4956 goto skip_app_handler;
4957 }
4958 /* Set up for the next data body as observing */
4959 lg_crcv->initial = 1;
4960 }
4961 coap_ticks(&lg_crcv->last_used);
4962 goto skip_app_handler;
4963 } else {
4964 coap_opt_t *obs_opt = coap_check_option(rcvd,
4966 &opt_iter);
4967 if (context->max_body_size && length > context->max_body_size) {
4968 coap_log_warn("Unable to handle body size %" PRIuS " (max %" PRIu32 ")\n", length,
4969 context->max_body_size);
4970 /* Try to hint to the server there is an issue */
4971 coap_send_rst_lkd(session, rcvd);
4973 return 1;
4974 }
4975 if (obs_opt) {
4976 lg_crcv->observe_length = min(coap_opt_length(obs_opt), 3);
4977 memcpy(lg_crcv->observe, coap_opt_value(obs_opt), lg_crcv->observe_length);
4978 lg_crcv->observe_set = 1;
4979 } else {
4980 lg_crcv->observe_set = 0;
4981 if (!coap_binary_equal(&rcvd->actual_token, lg_crcv->app_token)) {
4982 /* need to put back original token into rcvd */
4983 coap_update_token(rcvd, lg_crcv->app_token->length, lg_crcv->app_token->s);
4985 coap_log_debug("PDU presented to app.\n");
4987 }
4988 /* Expire this entry */
4989 goto expire_lg_crcv;
4990 }
4991 }
4992 coap_ticks(&lg_crcv->last_used);
4993 } else if (rcvd->code == COAP_RESPONSE_CODE(401)) {
4994#if COAP_OSCORE_SUPPORT
4995 if (check_freshness(session, rcvd,
4996 (session->oscore_encryption == 0) ? sent : NULL,
4997 NULL, lg_crcv))
4998#else /* !COAP_OSCORE_SUPPORT */
4999 if (check_freshness(session, rcvd, sent, NULL, lg_crcv))
5000#endif /* !COAP_OSCORE_SUPPORT */
5001 goto skip_app_handler;
5002 goto expire_lg_crcv;
5003 } else if (rcvd->code == COAP_RESPONSE_CODE(402)) {
5004 coap_opt_t *abb_opt = sent ? coap_check_option(sent,
5006 &opt_iter) : NULL;
5007 if (abb_opt) {
5008 /* Send the request again with the Uri-Path-Abbrev expanded out */
5009 coap_pdu_t *pdu;
5010 size_t data_len;
5011 const uint8_t *data;
5012 uint64_t token;
5013 uint8_t ltoken[8];
5014 size_t ltoken_len;
5015
5016 session->no_path_abbrev = 1;
5017 token = STATE_TOKEN_FULL(lg_crcv->state_token,
5018 ++lg_crcv->retry_counter);
5019 ltoken_len = coap_encode_var_safe8(ltoken, sizeof(token), token);
5020 pdu = coap_pdu_duplicate_lkd(lg_crcv->sent_pdu, session, ltoken_len,
5021 ltoken, NULL, COAP_BOOL_TRUE);
5022 if (pdu) {
5023 if (coap_get_data(lg_crcv->sent_pdu, &data_len, &data)) {
5024 coap_add_data(pdu, data_len, data);
5025 }
5026#if COAP_PROXY_SUPPORT
5027 coap_proxy_req_t *proxy_req = session->context->proxy_list_count ?
5028 coap_proxy_map_outgoing_request(session, rcvd, NULL) : NULL;
5029
5030 if (proxy_req) {
5031 coap_bin_const_t *new = coap_new_bin_const(ltoken, ltoken_len);
5032 if (new) {
5033 coap_delete_bin_const(proxy_req->token_used);
5034 proxy_req->token_used = new;
5035 coap_proxy_log_entry(proxy_req->incoming, proxy_req->pdu, proxy_req->token_used, "upd");
5036 }
5037 }
5038#endif /* COAP_PROXY_SUPPORT */
5039 coap_log_debug("* Retransmitting PDU with Uri-Path-Abbrev replaced (1)\n");
5040 coap_delete_pdu_lkd(lg_crcv->sent_pdu);
5041 lg_crcv->sent_pdu = coap_pdu_reference_lkd(pdu);
5042 coap_send_internal(session, pdu, NULL);
5043 goto skip_app_handler;
5044 }
5045 }
5046 goto expire_lg_crcv;
5047 } else {
5048 /* Not 2.xx, 4.01 or 4.02 - assume it is a failure of some sort */
5049 goto expire_lg_crcv;
5050 }
5051 if (!block.m && !lg_crcv->observe_set) {
5052fail_resp:
5053
5054 /* lg_crcv no longer required - cache it for 1 sec */
5057 } else {
5058 adjust = 0;
5059 }
5060 coap_ticks(&lg_crcv->last_used);
5061 lg_crcv->last_used -= adjust;
5062 }
5063 /* need to put back original token into rcvd */
5064 if (!coap_binary_equal(&rcvd->actual_token, lg_crcv->app_token)) {
5065 coap_update_token(rcvd, lg_crcv->app_token->length, lg_crcv->app_token->s);
5066 coap_log_debug("Client app version of updated PDU (4)\n");
5068 }
5069 }
5070
5071 /* Check if receiving a block response and if blocks can be set up */
5072 if (recursive == COAP_RECURSE_OK && !lg_crcv) {
5073 if (!sent) {
5074 if (coap_get_block_b(session, rcvd, COAP_OPTION_BLOCK2, &block)
5075#if COAP_Q_BLOCK_SUPPORT
5076 ||
5077 coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &block)
5078#endif /* COAP_Q_BLOCK_SUPPORT */
5079 ) {
5080 coap_log_debug("** %s: large body receive internal issue\n",
5081 coap_session_str(session));
5082 goto skip_app_handler;
5083 }
5084 } else if (COAP_RESPONSE_CLASS(rcvd->code) == 2) {
5085 const uint8_t *data;
5086 size_t length;
5087
5088 if (coap_get_block_b(session, rcvd, COAP_OPTION_BLOCK2, &block)) {
5089#if COAP_Q_BLOCK_SUPPORT
5090 if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
5091 set_block_mode_drop_q(session->block_mode);
5092 coap_log_debug("Q-Block support disabled\n");
5093 }
5094#endif /* COAP_Q_BLOCK_SUPPORT */
5095 have_block = 1;
5096 if (block.num != 0) {
5097 /* Assume random access and just give the single response to app */
5098 size_t chunk = (size_t)1 << (block.szx + 4);
5099
5100 coap_get_data(rcvd, &length, &data);
5101 rcvd->body_offset = block.num*chunk;
5102 rcvd->body_total = block.num*chunk + length + (block.m ? 1 : 0);
5103 goto call_app_handler;
5104 }
5105 }
5106#if COAP_Q_BLOCK_SUPPORT
5107 else if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &block)) {
5108 have_block = 1;
5109 /* server indicating that it supports Q_BLOCK2 */
5110 if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK)) {
5111 set_block_mode_has_q(session->block_mode);
5112 }
5113 }
5114#endif /* COAP_Q_BLOCK_SUPPORT */
5115 if (have_block) {
5116 lg_crcv = coap_block_new_lg_crcv(session, sent, NULL);
5117
5118 if (lg_crcv) {
5119 LL_PREPEND(session->lg_crcv, lg_crcv);
5120 return coap_handle_response_get_block(context, session, sent, rcvd,
5122 }
5123 }
5124 coap_get_data(rcvd, &length, &data);
5125 if (context->max_body_size && length > context->max_body_size) {
5126 coap_log_warn("Unable to handle body size %" PRIuS " (max %" PRIu32 ")\n", length,
5127 context->max_body_size);
5128 /* Try to hint to the server there is an issue */
5129 coap_send_rst_lkd(session, rcvd);
5131 return 1;
5132 }
5133 track_echo(session, rcvd);
5134 } else if (rcvd->code == COAP_RESPONSE_CODE(401)) {
5135 lg_crcv = coap_block_new_lg_crcv(session, sent, NULL);
5136
5137 if (lg_crcv) {
5138 LL_PREPEND(session->lg_crcv, lg_crcv);
5139 return coap_handle_response_get_block(context, session, sent, rcvd,
5141 }
5142 } else if (rcvd->code == COAP_RESPONSE_CODE(402)) {
5143 coap_opt_t *abb_opt = coap_check_option(sent,
5145 &opt_iter);
5146 if (abb_opt) {
5147 /*
5148 * Send the request again with the Uri-Path-Abbrev expanded out, but need
5149 lg_crcv in place to handle the token update.
5150 */
5151 lg_crcv = coap_block_new_lg_crcv(session, sent, NULL);
5152
5153 if (lg_crcv) {
5154 LL_PREPEND(session->lg_crcv, lg_crcv);
5155 return coap_handle_response_get_block(context, session, sent, rcvd,
5157 }
5158 }
5159 }
5160 }
5161 return 0;
5162
5163expire_lg_crcv:
5164 /* need to put back original token into rcvd */
5165 if (!coap_binary_equal(&rcvd->actual_token, lg_crcv->app_token)) {
5166 coap_update_token(rcvd, lg_crcv->app_token->length, lg_crcv->app_token->s);
5167 coap_log_debug("Client app version of updated PDU (5)\n");
5169 }
5170
5171 if (sent) {
5172 /* need to put back original token into sent */
5173 if (lg_crcv->app_token)
5174 coap_update_token(sent, lg_crcv->app_token->length,
5175 lg_crcv->app_token->s);
5176 coap_remove_option(sent, lg_crcv->block_option);
5177 }
5178 /* Expire this entry */
5179 LL_DELETE(session->lg_crcv, lg_crcv);
5180 coap_block_delete_lg_crcv(session, lg_crcv);
5181
5182call_app_handler:
5183 return 0;
5184
5185skip_app_handler:
5186 if (!ack_rst_sent)
5187 coap_send_ack_lkd(session, rcvd);
5188 return 1;
5189}
5190#endif /* COAP_CLIENT_SUPPORT */
5191
5192#if COAP_SERVER_SUPPORT
5193/* Check if lg_xmit generated and update PDU code if so */
5194void
5196 const coap_pdu_t *request,
5197 coap_pdu_t *response, const coap_resource_t *resource,
5198 const coap_string_t *query) {
5199 coap_lg_xmit_t *lg_xmit;
5200
5201 if (response->code == 0)
5202 return;
5203 lg_xmit = coap_find_lg_xmit_response(session, request, resource, query);
5204 if (lg_xmit && lg_xmit->sent_pdu && lg_xmit->sent_pdu->code == 0) {
5205 lg_xmit->sent_pdu->code = response->code;
5206 return;
5207 }
5208}
5209#endif /* COAP_SERVER_SUPPORT */
5210
5211#if COAP_CLIENT_SUPPORT
5212void
5214 uint64_t token_match =
5216 pdu->actual_token.length));
5217 coap_lg_xmit_t *lg_xmit;
5218 coap_lg_crcv_t *lg_crcv;
5219
5220 if (session->lg_crcv) {
5221 LL_FOREACH(session->lg_crcv, lg_crcv) {
5222 if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token))
5223 return;
5224 if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token)) {
5225 coap_update_token(pdu, lg_crcv->app_token->length,
5226 lg_crcv->app_token->s);
5227 coap_log_debug("Client app version of updated PDU (6)\n");
5229 return;
5230 }
5231 }
5232 }
5233 if (COAP_PDU_IS_REQUEST(pdu) && session->lg_xmit) {
5234 LL_FOREACH(session->lg_xmit, lg_xmit) {
5235 if (coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token))
5236 return;
5237 if (token_match == STATE_TOKEN_BASE(lg_xmit->b.b1.state_token)) {
5238 coap_update_token(pdu, lg_xmit->b.b1.app_token->length,
5239 lg_xmit->b.b1.app_token->s);
5240 coap_log_debug("Client app version of updated PDU (7)\n");
5242 return;
5243 }
5244 }
5245 }
5246}
5247#endif /* ! COAP_CLIENT_SUPPORT */
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
Compares given address objects a and b.
static void coap_block_release_lg_xmit_data(coap_session_t *session, coap_lg_xmit_data_t *data_info)
#define COAP_ETAG_MAX_BYTES
Definition coap_block.c:26
COAP_STATIC_INLINE int full_match(const uint8_t *a, size_t alen, const uint8_t *b, size_t blen)
Definition coap_block.c:479
#define MAX_BLK_LEN
static int coap_add_data_large_internal(coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *pdu, coap_resource_t *resource, const coap_string_t *query, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, coap_get_large_data_t get_func, void *app_ptr, int single_request, coap_pdu_code_t request_method)
Definition coap_block.c:801
static int blocks_add_entry(coap_rblock_t *rec_blocks, uint32_t block_num, uint32_t block_m)
static int check_all_blocks_in(coap_rblock_t *rec_blocks)
static int setup_block_b(coap_session_t *session, coap_pdu_t *pdu, coap_block_b_t *block, unsigned int num, unsigned int blk_size, size_t total)
Definition coap_block.c:141
#define min(a, b)
Definition coap_block.c:21
#define COAP_LG_XMIT_TXT_SCALAR
Definition coap_block.c:32
static int check_if_received_block(coap_rblock_t *rec_blocks, uint32_t block_num)
int coap_flsll(long long j)
Definition coap_encode.c:28
int coap_fls(unsigned int i)
Definition coap_encode.c:21
struct coap_lg_crcv_t coap_lg_crcv_t
struct coap_resource_t coap_resource_t
struct coap_lg_srcv_t coap_lg_srcv_t
#define PRIuS
#define PRIu32
@ COAP_NACK_TOO_MANY_RETRIES
Definition coap_io.h:65
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
Library specific build wrapper for coap_internal.h.
#define COAP_API
@ COAP_LG_XMIT
Definition coap_mem.h:49
@ COAP_LG_CRCV
Definition coap_mem.h:50
@ COAP_LG_SRCV
Definition coap_mem.h:51
@ COAP_STRING
Definition coap_mem.h:33
void * coap_realloc_type(coap_memory_tag_t type, void *p, size_t size)
Reallocates a chunk p of bytes created by coap_malloc_type() or coap_realloc_type() and returns a poi...
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
uint8_t coap_unique_id[8]
Definition coap_net.c:5431
#define NULL
Definition coap_option.h:30
uint16_t coap_option_num_t
Definition coap_option.h:37
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
#define COAP_OPTION_CONTENT_TYPE
@ COAP_OPTION_OBSERVE
Definition coap_option.h:75
@ COAP_OPTION_ETAG
Definition coap_option.h:73
@ COAP_OPTION_MAXAGE
Definition coap_option.h:83
@ COAP_OPTION_SIZE2
Definition coap_option.h:92
@ COAP_OPTION_Q_BLOCK2
Definition coap_option.h:93
@ COAP_OPTION_BLOCK2
Definition coap_option.h:90
@ COAP_OPTION_SIZE1
Definition coap_option.h:96
@ COAP_OPTION_ECHO
Definition coap_option.h:97
@ COAP_OPTION_RTAG
Definition coap_option.h:99
@ COAP_OPTION_BLOCK1
Definition coap_option.h:91
@ COAP_OPTION_URI_PATH
Definition coap_option.h:79
@ COAP_OPTION_Q_BLOCK1
Definition coap_option.h:87
@ COAP_OPTION_CONTENT_FORMAT
Definition coap_option.h:80
@ COAP_OPTION_URI_PATH_ABB
Definition coap_option.h:81
coap_mid_t coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition coap_net.c:1205
void coap_call_response_handler(coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, void *body_free)
coap_mid_t coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition coap_net.c:1220
#define COAP_BLOCK_MAX_SIZE_MASK
#define coap_check_update_token(a, b)
int coap_context_set_max_block_size_lkd(coap_context_t *context, size_t max_block_size)
Set the context level maximum block size that the server supports when sending or receiving packets w...
Definition coap_block.c:455
void coap_context_set_block_mode_lkd(coap_context_t *context, uint32_t block_mode)
Set the context level CoAP block handling bits for handling RFC7959.
Definition coap_block.c:430
#define COAP_BLOCK_MAX_SIZE_SET(a)
#define COAP_RBLOCK_CNT
void coap_check_code_lg_xmit(const coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_resource_t *resource, const coap_string_t *query)
The function checks that the code in a newly formed lg_xmit created by coap_add_data_large_response_l...
COAP_STATIC_INLINE void coap_lg_xmit_reference_lkd(coap_lg_xmit_t *lg_xmit)
Increment reference counter on a lg_xmit.
void coap_block_delete_lg_xmit(coap_session_t *session, coap_lg_xmit_t *lg_xmit)
Remove a lg_xmit.
#define STATE_TOKEN_FULL(t, r)
#define COAP_SINGLE_BLOCK_OR_Q
#define STATE_TOKEN_BASE(t)
coap_binary_t * coap_block_build_body_lkd(coap_binary_t *body_data, size_t length, const uint8_t *data, size_t offset, size_t total)
Re-assemble payloads into a body.
#define COAP_BLOCK_SET_MASK
COAP_STATIC_INLINE void coap_lg_xmit_release_lkd(coap_session_t *session, coap_lg_xmit_t *lg_xmit)
Decrement reference counter on a lg_xmit.
coap_lg_xmit_t * coap_find_lg_xmit(coap_session_t *session, coap_pdu_t *pdu)
Find the current lg_xmit for the session that matches the pdu.
Definition coap_block.c:485
#define COAP_BLOCK_MAX_SIZE_GET(a)
int coap_block_check_lg_xmit_timeouts(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem)
@ COAP_RECURSE_OK
@ COAP_RECURSE_NO
COAP_API void coap_context_set_block_mode(coap_context_t *context, uint32_t block_mode)
Set the context level CoAP block handling bits for handling RFC7959.
Definition coap_block.c:422
COAP_API int coap_add_data_large_response(coap_resource_t *resource, coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response, const coap_string_t *query, uint16_t media_type, int maxage, uint64_t etag, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the response pdu that is passed as fourth parameter.
int(* coap_get_large_data_t)(coap_session_t *session, size_t max, size_t offset, uint8_t *data, size_t *length, void *app_ptr)
Callback handler for getting the data based on app_ptr provided to coap_add_data_large_request_app() ...
Definition coap_block.h:360
#define COAP_BLOCK_USE_M_Q_BLOCK
Definition coap_block.h:68
#define COAP_OPT_BLOCK_SZX(opt)
Returns the value of the SZX-field of a Block option opt.
Definition coap_block.h:94
#define COAP_BLOCK_STLESS_BLOCK2
Definition coap_block.h:71
COAP_API int coap_add_data_large_request(coap_session_t *session, coap_pdu_t *pdu, size_t length, const uint8_t *data, coap_release_large_data_t release_func, void *app_ptr)
Associates given data with the pdu that is passed as second parameter.
#define COAP_BLOCK_TRY_Q_BLOCK
Definition coap_block.h:67
#define COAP_BLOCK_STLESS_FETCH
Definition coap_block.h:70
COAP_API int coap_context_set_max_block_size(coap_context_t *context, size_t max_block_size)
Set the context level maximum block size that the server supports when sending or receiving packets w...
Definition coap_block.c:444
int coap_add_block_b_data(coap_pdu_t *pdu, size_t len, const uint8_t *data, coap_block_b_t *block)
Adds the appropriate payload data of the body to the pdu.
Definition coap_block.c:261
#define COAP_BLOCK_SINGLE_BODY
Definition coap_block.h:66
int coap_write_block_b_opt(coap_session_t *session, coap_block_b_t *block, coap_option_num_t number, coap_pdu_t *pdu, size_t data_length)
Writes a block option of type number to message pdu.
Definition coap_block.c:216
int coap_add_block(coap_pdu_t *pdu, size_t len, const uint8_t *data, unsigned int block_num, unsigned char block_szx)
Adds the block_num block of size 1 << (block_szx + 4) from source data to pdu.
Definition coap_block.c:247
COAP_API coap_binary_t * coap_block_build_body(coap_binary_t *body_data, size_t length, const uint8_t *data, size_t offset, size_t total)
Re-assemble payloads into a body.
void(* coap_release_large_data_t)(coap_session_t *session, void *app_ptr)
Callback handler for de-allocating the data based on app_ptr provided to coap_add_data_large_*() func...
Definition coap_block.h:291
void coap_add_data_blocked_response(const coap_pdu_t *request, coap_pdu_t *response, uint16_t media_type, int maxage, size_t length, const uint8_t *data)
Adds the appropriate part of data to the response pdu.
Definition coap_block.c:286
int coap_get_block_b(const coap_session_t *session, const coap_pdu_t *pdu, coap_option_num_t number, coap_block_b_t *block)
Initializes block from pdu.
Definition coap_block.c:71
#define COAP_OPT_BLOCK_MORE(opt)
Returns the value of the More-bit of a Block option opt.
Definition coap_block.h:90
unsigned int coap_opt_block_num(const coap_opt_t *block_opt)
Returns the value of field num in the given block option block_opt.
Definition coap_block.c:52
int coap_get_block(const coap_pdu_t *pdu, coap_option_num_t number, coap_block_t *block)
Initializes block from pdu.
Definition coap_block.c:124
#define COAP_BLOCK_NOT_RANDOM_BLOCK1
Definition coap_block.h:72
#define COAP_OPT_BLOCK_END_BYTE(opt)
Returns the value of the last byte of opt.
Definition coap_block.h:85
int coap_write_block_opt(coap_block_t *block, coap_option_num_t number, coap_pdu_t *pdu, size_t data_length)
Writes a block option of type number to message pdu.
Definition coap_block.c:183
COAP_API int coap_add_data_large_request_app(coap_session_t *session, coap_pdu_t *pdu, size_t length, coap_release_large_data_t release_func, coap_get_large_data_t get_func, void *app_ptr)
Associates given data callback with the pdu that is passed as second parameter.
#define COAP_BLOCK_FORCE_Q_BLOCK
Definition coap_block.h:73
#define COAP_BLOCK_USE_LIBCOAP
Definition coap_block.h:65
time_t coap_time_t
CoAP time in seconds since epoch.
Definition coap_time.h:154
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:149
coap_time_t coap_ticks_to_rt(coap_tick_t t)
Helper function that converts coap ticks to wallclock time.
Definition coap_time.c:123
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:164
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:231
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:5269
uint16_t coap_new_message_id_lkd(coap_session_t *session)
Returns a new message id and updates session->tx_mid accordingly.
int coap_client_delay_first(coap_session_t *session)
Delay the sending of the first client request until some other negotiation has completed.
Definition coap_net.c:1478
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu)
Sends a CoAP message to given peer.
Definition coap_net.c:2097
void coap_register_block_data_handler(coap_context_t *context, coap_block_data_handler_t block_data_handler)
Sets up a handler that is called for each received block during a block-wise transfer when COAP_BLOCK...
coap_response_t
Definition coap_net.h:51
coap_response_t(* coap_block_data_handler_t)(coap_session_t *session, coap_pdu_t *pdu, coap_resource_t *resource, coap_binary_t **body_data, size_t length, const uint8_t *data, size_t offset, size_t total)
Definition of the block data handler function.
Definition coap_net.h:133
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
@ COAP_RESPONSE_OK
Response is fine.
Definition coap_net.h:53
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:47
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:38
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:71
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:81
@ COAP_EVENT_BLOCK_ISSUE
Triggered when a block transfer could not be handled.
Definition coap_event.h:77
@ COAP_EVENT_PARTIAL_BLOCK
Triggered when not all of a large body has been received.
Definition coap_event.h:73
@ COAP_EVENT_XMIT_BLOCK_FAIL
Triggered when not all of a large body has been transmitted.
Definition coap_event.h:75
#define coap_lock_callback(func)
Dummy for no thread-safe code.
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:126
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition coap_debug.c:812
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:114
#define coap_log_warn(...)
Definition coap_debug.h:108
@ COAP_LOG_DEBUG
Definition coap_debug.h:64
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET/FETCH request option COAP_OPTION_OBSERVE indicates that the ob...
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET/FETCH request option COAP_OPTION_OBSERVE indicates a new ob...
COAP_API int coap_cancel_observe(coap_session_t *session, coap_binary_t *token, coap_pdu_type_t message_type)
Cancel an observe that is being tracked by the client large receive logic.
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
coap_opt_iterator_t * coap_option_iterator_init(const coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t *filter)
Initializes the given option iterator oi to point to the beginning of the pdu's option list.
size_t coap_opt_encode_size(uint16_t delta, size_t length)
Compute storage bytes needed for an option with given delta and length.
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
int coap_rebuild_pdu_for_proxy(coap_pdu_t *pdu)
Convert PDU to use Proxy-Scheme option if Proxy-Uri option is present.
size_t coap_oscore_overhead(coap_session_t *session, coap_pdu_t *pdu)
Determine the additional data size requirements for adding in OSCORE.
#define COAP_PDU_IS_RESPONSE(pdu)
coap_pdu_t * coap_pdu_reference_lkd(coap_pdu_t *pdu)
Increment reference counter on a pdu to stop it prematurely getting freed off when coap_delete_pdu() ...
Definition coap_pdu.c:1756
void coap_delete_pdu_lkd(coap_pdu_t *pdu)
Dispose of an CoAP PDU and free off associated storage.
Definition coap_pdu.c:197
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition coap_pdu.c:692
int coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number)
Removes (first) option of given number from the pdu.
Definition coap_pdu.c:546
int coap_update_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Updates token in pdu with length len and data.
Definition coap_pdu.c:470
coap_pdu_t * coap_pdu_duplicate_lkd(const coap_pdu_t *old_pdu, coap_session_t *session, size_t token_length, const uint8_t *token, coap_opt_filter_t *drop_options, coap_bool_t expand_opt_abb)
Duplicate an existing PDU.
Definition coap_pdu.c:237
size_t coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Updates existing first option of given number in the pdu with the new data.
Definition coap_pdu.c:797
#define COAP_PAYLOAD_START
int coap_pdu_check_resize(coap_pdu_t *pdu, size_t size)
Dynamically grows the size of pdu to new_size if needed.
Definition coap_pdu.c:396
#define COAP_PDU_IS_REQUEST(pdu)
size_t coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:859
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition coap_pdu.c:1037
#define COAP_MEDIATYPE_APPLICATION_MB_CBOR_SEQ
Definition coap_pdu.h:175
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:184
#define COAP_RESPONSE_CODE(N)
Definition coap_pdu.h:96
#define COAP_RESPONSE_CLASS(C)
Definition coap_pdu.h:99
coap_pdu_code_t
Set of codes available for a PDU.
Definition coap_pdu.h:248
coap_pdu_type_t
CoAP PDU message type definitions.
Definition coap_pdu.h:70
#define COAP_MEDIATYPE_TEXT_PLAIN
Definition coap_pdu.h:134
int coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds token of length len to pdu.
Definition coap_pdu.c:413
size_t coap_add_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition coap_pdu.c:849
int coap_get_data(const coap_pdu_t *pdu, size_t *len, const uint8_t **data)
Retrieves the length and data pointer of specified PDU.
Definition coap_pdu.c:962
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition coap_pdu.c:104
int coap_get_data_large(const coap_pdu_t *pdu, size_t *len, const uint8_t **data, size_t *offset, size_t *total)
Retrieves the data from a PDU, with support for large bodies of data that spans multiple PDUs.
Definition coap_pdu.c:970
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:187
int coap_add_data(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Adds given data to the pdu that is passed as first parameter.
Definition coap_pdu.c:931
@ COAP_BOOL_FALSE
Definition coap_pdu.h:295
@ COAP_BOOL_TRUE
Definition coap_pdu.h:296
@ COAP_REQUEST_CODE_GET
Definition coap_pdu.h:251
@ COAP_REQUEST_CODE_FETCH
Definition coap_pdu.h:255
@ COAP_MESSAGE_NON
Definition coap_pdu.h:72
@ COAP_MESSAGE_ACK
Definition coap_pdu.h:73
@ COAP_MESSAGE_CON
Definition coap_pdu.h:71
#define COAP_NON_RECEIVE_TIMEOUT_TICKS(s)
The NON_RECEIVE_TIMEOUT definition for the session (s).
#define COAP_NON_TIMEOUT_TICKS(s)
void coap_handle_nack(coap_session_t *session, coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
#define COAP_MAX_TRANSMIT_WAIT_TICKS(s)
#define COAP_NON_PARTIAL_TIMEOUT_TICKS(s)
The NON_PARTIAL_TIMEOUT definition for the session (s).
coap_tick_t coap_get_non_timeout_random_ticks(coap_session_t *session)
#define COAP_NSTART(s)
#define COAP_MAX_PAYLOADS(s)
size_t coap_session_max_pdu_size_lkd(const coap_session_t *session)
Get maximum acceptable PDU size.
#define COAP_NON_MAX_RETRANSMIT(s)
#define COAP_PROTO_NOT_RELIABLE(p)
#define COAP_PROTO_RELIABLE(p)
void coap_session_new_token(coap_session_t *session, size_t *len, uint8_t *data)
Creates a new token for use.
@ COAP_SESSION_TYPE_CLIENT
client-side
void coap_delete_bin_const(coap_bin_const_t *s)
Deletes the given const binary data and releases any memory allocated.
Definition coap_str.c:130
void coap_delete_str_const(coap_str_const_t *s)
Deletes the given const string and releases any memory allocated.
Definition coap_str.c:65
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:81
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:119
coap_binary_t * coap_resize_binary(coap_binary_t *s, size_t size)
Resizes the given coap_binary_t object.
Definition coap_str.c:86
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:114
#define coap_binary_equal(binary1, binary2)
Compares the two binary data for equality.
Definition coap_str.h:222
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition coap_str.h:208
coap_string_t * coap_new_string(size_t size)
Returns a new string object with at least size+1 bytes storage allocated.
Definition coap_str.c:21
coap_str_const_t * coap_new_str_const(const uint8_t *data, size_t size)
Returns a new const string object with at least size+1 bytes storage allocated, and the provided data...
Definition coap_str.c:55
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition coap_str.c:50
int coap_q_block_is_supported(void)
Check whether Q-BlockX is available.
Definition coap_block.c:46
#define COAP_STATIC_INLINE
Definition libcoap.h:57
coap_address_t remote
remote address and port
Definition coap_io.h:58
coap_address_t local
local address and port
Definition coap_io.h:59
CoAP binary data definition with const data.
Definition coap_str.h:65
size_t length
length of binary data
Definition coap_str.h:66
const uint8_t * s
read-only binary data
Definition coap_str.h:67
CoAP binary data definition.
Definition coap_str.h:57
size_t length
length of binary data
Definition coap_str.h:58
uint8_t * s
binary data
Definition coap_str.h:59
Structure of Block options with BERT support.
Definition coap_block.h:55
unsigned int num
block number
Definition coap_block.h:56
uint32_t chunk_size
Definition coap_block.h:62
unsigned int bert
Operating as BERT.
Definition coap_block.h:61
unsigned int aszx
block size (0-7 including BERT
Definition coap_block.h:59
unsigned int defined
Set if block found.
Definition coap_block.h:60
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:57
unsigned int szx
block size (0-6)
Definition coap_block.h:58
Structure of Block options.
Definition coap_block.h:46
unsigned int num
block number
Definition coap_block.h:47
unsigned int szx
block size
Definition coap_block.h:49
unsigned int m
1 if more blocks follow, 0 otherwise
Definition coap_block.h:48
The CoAP stack's global state is stored in a coap_context_t object.
coap_block_data_handler_t block_data_cb
Called with each block data during block transfers.
uint32_t max_body_size
Max supported body size or 0 is unlimited.
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
uint64_t state_token
state token
size_t bert_size
size of last BERT block
coap_address_t upstream
uint32_t count
the number of packets sent for payload
coap_binary_t * app_token
original PDU token
coap_pdu_code_t request_method
Method used to request this data.
uint8_t rtag_length
RTag length.
coap_string_t * query
Associated query for the resource.
uint64_t etag
ETag value.
coap_resource_t * resource
associated resource
coap_time_t maxage_expire
When this entry expires.
uint8_t rtag_set
Set if RTag is in receive PDU.
uint8_t rtag[8]
RTag for block checking.
coap_get_large_data_t get_func
Where to get data id needed.
void * app_ptr
application provided ptr for de-alloc function
uint32_t ref
Reference count.
const uint8_t * data
large data ptr
size_t length
large data length
coap_release_large_data_t release_func
large data de-alloc function
Structure to hold large body (many blocks) transmission information.
coap_tick_t last_all_sent
Last time all data sent or 0.
uint8_t blk_size
large block transmission size
coap_tick_t last_sent
Last time any data sent.
coap_lg_xmit_data_t * data_info
Pointer to large data information.
int last_block
last acknowledged block number Block1 last transmitted Q-Block2
union coap_lg_xmit_t::@065323167333303053164351157057215157001006370010 b
coap_tick_t last_payload
Last time MAX_PAYLOAD was sent or 0.
coap_pdu_t * sent_pdu
The sent pdu with all the data.
coap_l_block1_t b1
coap_l_block2_t b2
uint32_t ref
Reference count.
uint16_t option
large block transmission CoAP option
struct coap_lg_xmit_t * next
coap_tick_t last_obs
Last time used (Observe tracking) or 0.
Iterator to run through PDU options.
coap_option_num_t number
decoded option number
structure for CoAP PDUs
uint8_t * token
first byte of token (or extended length bytes prefix), if any, or options
coap_lg_xmit_t * lg_xmit
Holds ptr to lg_xmit if sending a set of blocks.
size_t body_length
Holds body data length.
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
const uint8_t * body_data
Holds ptr to re-assembled data or NULL.
size_t body_offset
Holds body data offset.
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
coap_bin_const_t actual_token
Actual token in pdu.
uint8_t * data
first byte of payload, if any
size_t used_size
used bytes of storage for token, options and payload
coap_session_t * session
Session responsible for PDU or NULL.
size_t body_total
Holds body data total size.
coap_pdu_type_t type
message type
Queue entry.
Structure to keep track of received blocks.
uint32_t total_blocks
Set to block no + 1 when More bit unset.
uint32_t used
Number of range blocks in use.
struct coap_lg_range range[COAP_RBLOCK_CNT]
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
uint32_t block_mode
Zero or more COAP_BLOCK_ or'd options.
coap_socket_t sock
socket object for the session, if any
uint8_t csm_bert_rem_support
CSM TCP BERT blocks supported (remote).
uint64_t tx_token
Next token number to use.
uint8_t is_rate_limiting
Currently NON rate limiting.
coap_mid_t remote_test_mid
mid used for checking remote support
uint8_t csm_bert_loc_support
CSM TCP BERT blocks supported (local).
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
coap_bin_const_t * last_token
uint8_t no_path_abbrev
Set is remote does not support Uri-Path-Abbrev.
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
uint32_t tx_rtag
Next Request-Tag number to use.
coap_session_type_t type
client or server side socket
coap_context_t * context
session's context
coap_bin_const_t * echo
last token used to make a request
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
CoAP string data definition.
Definition coap_str.h:39
uint8_t * s
string data
Definition coap_str.h:41
size_t length
length of string
Definition coap_str.h:40