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