1 /* block.c -- block transfer
3 * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
5 * This file is part of the CoAP library libcoap. Please see
6 * README for terms of use.
11 #if defined(HAVE_ASSERT_H) && !defined(assert)
18 #define min(a,b) ((a) < (b) ? (a) : (b))
21 unsigned int coap_opt_block_num(const coap_opt_t *block_opt)
26 len = coap_opt_length(block_opt);
35 num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt), COAP_OPT_LENGTH(block_opt) - 1);
38 return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4);
41 int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block)
43 coap_opt_iterator_t opt_iter;
47 memset(block, 0, sizeof(coap_block_t));
49 if (pdu && (option = coap_check_option(pdu, type, &opt_iter)))
51 block->szx = COAP_OPT_BLOCK_SZX(option);
52 if (COAP_OPT_BLOCK_MORE(option))
54 block->num = coap_opt_block_num(option);
61 int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *pdu,
64 size_t start, want, avail;
70 if (type != COAP_OPTION_BLOCK2)
72 warn("coap_write_block_opt: skipped unknown option\n");
76 start = block->num << (block->szx + 4);
77 if (data_length <= start)
79 debug("illegal block requested\n");
83 avail = pdu->max_size - pdu->length - 4;
84 want = 1 << (block->szx + 4);
86 /* check if entire block fits in message */
89 block->m = want < data_length - start;
93 /* Sender has requested a block that is larger than the remaining
94 * space in pdu. This is ok if the remaining data fits into the pdu
95 * anyway. The block size needs to be adjusted only if there is more
96 * data left that cannot be delivered in this message. */
98 if (data_length - start <= avail)
101 /* it's the final block and everything fits in the message */
108 /* we need to decrease the block size */
110 { /* bad luck, this is the smallest block size */
111 debug("not enough space, even the smallest block does not fit");
114 debug("decrease block size for %d to %d\n", avail, coap_fls(avail) - 5);
116 block->szx = coap_fls(avail) - 5;
118 block->num <<= szx - block->szx;
122 /* to re-encode the block option */
123 coap_add_option(pdu, type,
124 coap_encode_var_bytes(buf, ((block->num << 4) | (block->m << 3) | block->szx)), buf);
129 int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
130 unsigned int block_num, unsigned char block_szx)
133 start = block_num << (block_szx + 4);
138 return coap_add_data(pdu, min(len - start, (unsigned int)(1 << (block_szx + 4))), data + start);
140 #endif /* WITHOUT_BLOCK */