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