1 /* coap_pdu.c -- CoAP PDU handling
2 *
3 * Copyright (C) 2010--2023 Olaf Bergmann <bergmann@tzi.org>
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
11 /**
12 * @file coap_pdu.c
13 * @brief CoAP PDU handling
14 */
15
16 #include "coap3/coap_internal.h"
17
18 #if defined(HAVE_LIMITS_H)
19 #include <limits.h>
20 #endif
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #ifdef HAVE_ARPA_INET_H
26 #include <arpa/inet.h>
27 #endif
28 #ifdef HAVE_WINSOCK2_H
29 #include <winsock2.h>
30 #endif
31 #include <ctype.h>
32
33 #ifndef min
34 #define min(a,b) ((a) < (b) ? (a) : (b))
35 #endif
36
37 #ifndef max
38 #define max(a,b) ((a) > (b) ? (a) : (b))
39 #endif
40
41 void
coap_pdu_clear(coap_pdu_t * pdu,size_t size)42 coap_pdu_clear(coap_pdu_t *pdu, size_t size) {
43 assert(pdu);
44 assert(pdu->token);
45 assert(pdu->max_hdr_size >= COAP_PDU_MAX_UDP_HEADER_SIZE);
46 if (pdu->alloc_size > size)
47 pdu->alloc_size = size;
48 pdu->type = 0;
49 pdu->code = 0;
50 pdu->hdr_size = 0;
51 pdu->actual_token.length = 0;
52 pdu->e_token_length = 0;
53 pdu->crit_opt = 0;
54 pdu->mid = 0;
55 pdu->max_opt = 0;
56 pdu->max_size = size;
57 pdu->used_size = 0;
58 pdu->data = NULL;
59 pdu->body_data = NULL;
60 pdu->body_length = 0;
61 pdu->body_offset = 0;
62 pdu->body_total = 0;
63 pdu->lg_xmit = NULL;
64 pdu->session = NULL;
65 }
66
67 #ifdef WITH_LWIP
68 coap_pdu_t *
coap_pdu_from_pbuf(struct pbuf * pbuf)69 coap_pdu_from_pbuf(struct pbuf *pbuf) {
70 coap_pdu_t *pdu;
71
72 if (pbuf == NULL)
73 return NULL;
74
75 LWIP_ASSERT("Can only deal with contiguous PBUFs (increase PBUF_POOL_BUFSIZE)",
76 pbuf->tot_len == pbuf->len);
77 LWIP_ASSERT("coap_io_do_io needs to receive an exclusive copy of the incoming pbuf",
78 pbuf->ref == 1);
79
80 pdu = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t));
81 if (!pdu) {
82 pbuf_free(pbuf);
83 return NULL;
84 }
85
86 pdu->max_hdr_size = COAP_PDU_MAX_UDP_HEADER_SIZE;
87 pdu->pbuf = pbuf;
88 pdu->token = (uint8_t *)pbuf->payload + pdu->max_hdr_size;
89 pdu->alloc_size = pbuf->tot_len - pdu->max_hdr_size;
90 coap_pdu_clear(pdu, pdu->alloc_size);
91
92 return pdu;
93 }
94 #endif /* LWIP */
95
96 coap_pdu_t *
coap_pdu_init(coap_pdu_type_t type,coap_pdu_code_t code,coap_mid_t mid,size_t size)97 coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid,
98 size_t size) {
99 coap_pdu_t *pdu;
100
101 assert(type <= 0x3);
102 assert(code <= 0xff);
103 assert(mid >= 0 && mid <= 0xffff);
104
105 #ifdef WITH_LWIP
106 #if MEMP_STATS
107 /* Reserve 1 PDU for a response packet */
108 if (memp_pools[MEMP_COAP_PDU]->stats->used + 1 >=
109 memp_pools[MEMP_COAP_PDU]->stats->avail) {
110 memp_pools[MEMP_COAP_PDU]->stats->err++;
111 return NULL;
112 }
113 #endif /* MEMP_STATS */
114 #endif /* LWIP */
115 pdu = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t));
116 if (!pdu)
117 return NULL;
118
119 #if defined(WITH_CONTIKI) || defined(WITH_LWIP)
120 assert(size <= COAP_DEFAULT_MAX_PDU_RX_SIZE);
121 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE)
122 return NULL;
123 pdu->max_hdr_size = COAP_PDU_MAX_UDP_HEADER_SIZE;
124 #else
125 pdu->max_hdr_size = COAP_PDU_MAX_TCP_HEADER_SIZE;
126 #endif
127
128 #ifdef WITH_LWIP
129 pdu->pbuf = pbuf_alloc(PBUF_TRANSPORT, size + pdu->max_hdr_size, PBUF_RAM);
130 if (pdu->pbuf == NULL) {
131 coap_free_type(COAP_PDU, pdu);
132 return NULL;
133 }
134 pdu->token = (uint8_t *)pdu->pbuf->payload + pdu->max_hdr_size;
135 #else /* WITH_LWIP */
136 uint8_t *buf;
137 pdu->alloc_size = min(size, 256);
138 buf = coap_malloc_type(COAP_PDU_BUF, pdu->alloc_size + pdu->max_hdr_size);
139 if (buf == NULL) {
140 coap_free_type(COAP_PDU, pdu);
141 return NULL;
142 }
143 pdu->token = buf + pdu->max_hdr_size;
144 #endif /* WITH_LWIP */
145 coap_pdu_clear(pdu, size);
146 pdu->mid = mid;
147 pdu->type = type;
148 pdu->code = code;
149 return pdu;
150 }
151
152 coap_pdu_t *
coap_new_pdu(coap_pdu_type_t type,coap_pdu_code_t code,coap_session_t * session)153 coap_new_pdu(coap_pdu_type_t type, coap_pdu_code_t code,
154 coap_session_t *session) {
155 coap_pdu_t *pdu = coap_pdu_init(type, code, coap_new_message_id(session),
156 coap_session_max_pdu_size(session));
157 if (!pdu)
158 coap_log_crit("coap_new_pdu: cannot allocate memory for new PDU\n");
159 return pdu;
160 }
161
162 void
coap_delete_pdu(coap_pdu_t * pdu)163 coap_delete_pdu(coap_pdu_t *pdu) {
164 if (pdu != NULL) {
165 #ifdef WITH_LWIP
166 pbuf_free(pdu->pbuf);
167 #else
168 if (pdu->token != NULL)
169 coap_free_type(COAP_PDU_BUF, pdu->token - pdu->max_hdr_size);
170 #endif
171 coap_free_type(COAP_PDU, pdu);
172 }
173 }
174
175 /*
176 * Note: This does not include any data, just the token and options
177 */
178 coap_pdu_t *
coap_pdu_duplicate(const coap_pdu_t * old_pdu,coap_session_t * session,size_t token_length,const uint8_t * token,coap_opt_filter_t * drop_options)179 coap_pdu_duplicate(const coap_pdu_t *old_pdu,
180 coap_session_t *session,
181 size_t token_length,
182 const uint8_t *token,
183 coap_opt_filter_t *drop_options) {
184 uint8_t doing_first = session->doing_first;
185 coap_pdu_t *pdu;
186
187 /*
188 * Need to make sure that coap_session_max_pdu_size() immediately
189 * returns, rather than wait for the first CSM response from remote
190 * that indicates BERT size (TCP/TLS only) as this may be called early
191 * the OSCORE logic.
192 */
193 session->doing_first = 0;
194 pdu = coap_pdu_init(old_pdu->type, old_pdu->code,
195 coap_new_message_id(session),
196 max(old_pdu->max_size,
197 coap_session_max_pdu_size(session)));
198 /* Restore any pending waits */
199 session->doing_first = doing_first;
200 if (pdu == NULL)
201 return NULL;
202
203 coap_add_token(pdu, token_length, token);
204 pdu->lg_xmit = old_pdu->lg_xmit;
205
206 if (drop_options == NULL) {
207 /* Drop COAP_PAYLOAD_START as well if data */
208 size_t length = old_pdu->used_size - old_pdu->e_token_length -
209 (old_pdu->data ?
210 old_pdu->used_size - (old_pdu->data - old_pdu->token) +1 : 0);
211 if (!coap_pdu_resize(pdu, length + pdu->e_token_length))
212 goto fail;
213 /* Copy the options but not any data across */
214 memcpy(pdu->token + pdu->e_token_length,
215 old_pdu->token + old_pdu->e_token_length, length);
216 pdu->used_size += length;
217 pdu->max_opt = old_pdu->max_opt;
218 } else {
219 /* Copy across all the options the slow way */
220 coap_opt_iterator_t opt_iter;
221 coap_opt_t *option;
222
223 coap_option_iterator_init(old_pdu, &opt_iter, COAP_OPT_ALL);
224 while ((option = coap_option_next(&opt_iter))) {
225 if (drop_options && coap_option_filter_get(drop_options, opt_iter.number))
226 continue;
227 if (!coap_add_option_internal(pdu, opt_iter.number,
228 coap_opt_length(option),
229 coap_opt_value(option)))
230 goto fail;
231 }
232 }
233 return pdu;
234
235 fail:
236 coap_delete_pdu(pdu);
237 return NULL;
238 }
239
240
241 /*
242 * The new size does not include the coap header (max_hdr_size)
243 */
244 int
coap_pdu_resize(coap_pdu_t * pdu,size_t new_size)245 coap_pdu_resize(coap_pdu_t *pdu, size_t new_size) {
246 if (new_size > pdu->alloc_size) {
247 #if !defined(WITH_LWIP)
248 uint8_t *new_hdr;
249 size_t offset;
250 #endif
251 if (pdu->max_size && new_size > pdu->max_size) {
252 coap_log_warn("coap_pdu_resize: pdu too big\n");
253 return 0;
254 }
255 #if !defined(WITH_LWIP)
256 if (pdu->data != NULL) {
257 assert(pdu->data > pdu->token);
258 offset = pdu->data - pdu->token;
259 } else {
260 offset = 0;
261 }
262 new_hdr = (uint8_t *)coap_realloc_type(COAP_PDU_BUF,
263 pdu->token - pdu->max_hdr_size,
264 new_size + pdu->max_hdr_size);
265 if (new_hdr == NULL) {
266 coap_log_warn("coap_pdu_resize: realloc failed\n");
267 return 0;
268 }
269 pdu->token = new_hdr + pdu->max_hdr_size;
270 if (offset > 0)
271 pdu->data = pdu->token + offset;
272 else
273 pdu->data = NULL;
274 if (pdu->actual_token.length < COAP_TOKEN_EXT_1B_BIAS)
275 pdu->actual_token.s = &pdu->token[0];
276 else if (pdu->actual_token.length < COAP_TOKEN_EXT_2B_BIAS)
277 pdu->actual_token.s = &pdu->token[1];
278 else
279 pdu->actual_token.s = &pdu->token[2];
280 #endif
281 }
282 pdu->alloc_size = new_size;
283 return 1;
284 }
285
286 int
coap_pdu_check_resize(coap_pdu_t * pdu,size_t size)287 coap_pdu_check_resize(coap_pdu_t *pdu, size_t size) {
288 if (size > pdu->alloc_size) {
289 size_t new_size = max(256, pdu->alloc_size * 2);
290 while (size > new_size)
291 new_size *= 2;
292 if (pdu->max_size && new_size > pdu->max_size) {
293 new_size = pdu->max_size;
294 if (new_size < size)
295 return 0;
296 }
297 if (!coap_pdu_resize(pdu, new_size))
298 return 0;
299 }
300 return 1;
301 }
302
303 int
coap_add_token(coap_pdu_t * pdu,size_t len,const uint8_t * data)304 coap_add_token(coap_pdu_t *pdu, size_t len, const uint8_t *data) {
305 size_t bias = 0;
306
307 /* must allow for pdu == NULL as callers may rely on this */
308 if (!pdu)
309 return 0;
310
311 if (pdu->used_size) {
312 coap_log_warn("coap_add_token: The token must defined first. Token ignored\n");
313 return 0;
314 }
315 pdu->actual_token.length = len;
316 if (len < COAP_TOKEN_EXT_1B_BIAS) {
317 bias = 0;
318 } else if (len < COAP_TOKEN_EXT_2B_BIAS) {
319 bias = 1;
320 } else if (len <= COAP_TOKEN_EXT_MAX) {
321 bias = 2;
322 } else {
323 coap_log_warn("coap_add_token: Token size too large. Token ignored\n");
324 return 0;
325 }
326 if (!coap_pdu_check_resize(pdu, len + bias)) {
327 coap_log_warn("coap_add_token: Insufficient space for token. Token ignored\n");
328 return 0;
329 }
330
331 pdu->actual_token.length = len;
332 pdu->actual_token.s = &pdu->token[bias];
333 pdu->e_token_length = (uint32_t)(len + bias);
334 if (len) {
335 switch (bias) {
336 case 0:
337 memcpy(pdu->token, data, len);
338 break;
339 case 1:
340 pdu->token[0] = (uint8_t)(len - COAP_TOKEN_EXT_1B_BIAS);
341 memcpy(&pdu->token[1], data, len);
342 break;
343 case 2:
344 pdu->token[0] = (uint8_t)((len - COAP_TOKEN_EXT_2B_BIAS) >> 8);
345 pdu->token[1] = (uint8_t)((len - COAP_TOKEN_EXT_2B_BIAS) & 0xff);
346 memcpy(&pdu->token[2], data, len);
347 break;
348 default:
349 break;
350 }
351 }
352 pdu->max_opt = 0;
353 pdu->used_size = len + bias;
354 pdu->data = NULL;
355
356 return 1;
357 }
358
359 /* It is assumed that coap_encode_var_safe8() has been called to reduce data */
360 int
coap_update_token(coap_pdu_t * pdu,size_t len,const uint8_t * data)361 coap_update_token(coap_pdu_t *pdu, size_t len, const uint8_t *data) {
362 size_t bias = 0;
363
364 /* must allow for pdu == NULL as callers may rely on this */
365 if (!pdu)
366 return 0;
367
368 if (pdu->used_size == 0) {
369 return coap_add_token(pdu, len, data);
370 }
371 if (len < COAP_TOKEN_EXT_1B_BIAS) {
372 bias = 0;
373 } else if (len < COAP_TOKEN_EXT_2B_BIAS) {
374 bias = 1;
375 } else if (len <= COAP_TOKEN_EXT_MAX) {
376 bias = 2;
377 } else {
378 coap_log_warn("coap_add_token: Token size too large. Token ignored\n");
379 return 0;
380 }
381 if ((len + bias) == pdu->e_token_length) {
382 /* Easy case - just data has changed */
383 } else if ((len + bias) > pdu->e_token_length) {
384 if (!coap_pdu_check_resize(pdu,
385 pdu->used_size + (len + bias) - pdu->e_token_length)) {
386 coap_log_warn("Failed to update token\n");
387 return 0;
388 }
389 memmove(&pdu->token[(len + bias) - pdu->e_token_length],
390 pdu->token, pdu->used_size);
391 pdu->used_size += len + bias - pdu->e_token_length;
392 } else {
393 pdu->used_size -= pdu->e_token_length - (len + bias);
394 memmove(pdu->token, &pdu->token[pdu->e_token_length - (len + bias)], pdu->used_size);
395 }
396 if (pdu->data) {
397 pdu->data += (len + bias) - pdu->e_token_length;
398 }
399
400 pdu->actual_token.length = len;
401 pdu->actual_token.s = &pdu->token[bias];
402 pdu->e_token_length = (uint8_t)(len + bias);
403 if (len) {
404 switch (bias) {
405 case 0:
406 if (memcmp(pdu->token, data, len) != 0)
407 memcpy(pdu->token, data, len);
408 break;
409 case 1:
410 pdu->token[0] = (uint8_t)(len - COAP_TOKEN_EXT_1B_BIAS);
411 memcpy(&pdu->token[1], data, len);
412 break;
413 case 2:
414 pdu->token[0] = (uint8_t)((len - COAP_TOKEN_EXT_2B_BIAS) >> 8);
415 pdu->token[1] = (uint8_t)((len - COAP_TOKEN_EXT_2B_BIAS) & 0xff);
416 memcpy(&pdu->token[2], data, len);
417 break;
418 default:
419 break;
420 }
421 }
422 return 1;
423 }
424
425 int
coap_remove_option(coap_pdu_t * pdu,coap_option_num_t number)426 coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number) {
427 coap_opt_iterator_t opt_iter;
428 coap_opt_t *option;
429 coap_opt_t *next_option = NULL;
430 size_t opt_delta;
431 coap_option_t decode_this;
432 coap_option_t decode_next;
433
434 /* Need to locate where in current options to remove this one */
435 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
436 while ((option = coap_option_next(&opt_iter))) {
437 if (opt_iter.number == number) {
438 /* Found option to delete */
439 break;
440 }
441 }
442 if (!option)
443 return 0;
444
445 if (!coap_opt_parse(option, pdu->used_size - (option - pdu->token),
446 &decode_this))
447 return 0;
448
449 next_option = coap_option_next(&opt_iter);
450 if (next_option) {
451 if (!coap_opt_parse(next_option,
452 pdu->used_size - (next_option - pdu->token),
453 &decode_next))
454 return 0;
455 opt_delta = decode_this.delta + decode_next.delta;
456 if (opt_delta < 13) {
457 /* can simply update the delta of next option */
458 next_option[0] = (next_option[0] & 0x0f) + (coap_opt_t)(opt_delta << 4);
459 } else if (opt_delta < 269 && decode_next.delta < 13) {
460 /* next option delta size increase */
461 next_option -= 1;
462 next_option[0] = (next_option[1] & 0x0f) + (13 << 4);
463 next_option[1] = (coap_opt_t)(opt_delta - 13);
464 } else if (opt_delta < 269) {
465 /* can simply update the delta of next option */
466 next_option[1] = (coap_opt_t)(opt_delta - 13);
467 } else if (decode_next.delta < 13) { /* opt_delta >= 269 */
468 /* next option delta size increase */
469 if (next_option - option < 2) {
470 /* Need to shuffle everything up by 1 before decrement */
471 if (!coap_pdu_check_resize(pdu, pdu->used_size + 1))
472 return 0;
473 /* Possible a re-size took place with a realloc() */
474 /* Need to rediscover this and next options */
475 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
476 while ((option = coap_option_next(&opt_iter))) {
477 if (opt_iter.number == number) {
478 /* Found option to delete */
479 break;
480 }
481 }
482 next_option = coap_option_next(&opt_iter);
483 assert(option != NULL);
484 assert(next_option != NULL);
485 memmove(&next_option[1], next_option,
486 pdu->used_size - (next_option - pdu->token));
487 pdu->used_size++;
488 if (pdu->data)
489 pdu->data++;
490 next_option++;
491 }
492 next_option -= 2;
493 next_option[0] = (next_option[2] & 0x0f) + (14 << 4);
494 next_option[1] = (coap_opt_t)((opt_delta - 269) >> 8);
495 next_option[2] = (opt_delta - 269) & 0xff;
496 } else if (decode_next.delta < 269) { /* opt_delta >= 269 */
497 /* next option delta size increase */
498 next_option -= 1;
499 next_option[0] = (next_option[1] & 0x0f) + (14 << 4);
500 next_option[1] = (coap_opt_t)((opt_delta - 269) >> 8);
501 next_option[2] = (opt_delta - 269) & 0xff;
502 } else { /* decode_next.delta >= 269 && opt_delta >= 269 */
503 next_option[1] = (coap_opt_t)((opt_delta - 269) >> 8);
504 next_option[2] = (opt_delta - 269) & 0xff;
505 }
506 } else {
507 next_option = option + coap_opt_encode_size(decode_this.delta,
508 coap_opt_length(option));
509 pdu->max_opt -= decode_this.delta;
510 }
511 if (pdu->used_size - (next_option - pdu->token))
512 memmove(option, next_option, pdu->used_size - (next_option - pdu->token));
513 pdu->used_size -= next_option - option;
514 if (pdu->data)
515 pdu->data -= next_option - option;
516 return 1;
517 }
518
519 int
coap_option_check_repeatable(coap_option_num_t number)520 coap_option_check_repeatable(coap_option_num_t number) {
521 /* Validate that the option is repeatable */
522 switch (number) {
523 /* Ignore list of genuine repeatable */
524 case COAP_OPTION_IF_MATCH:
525 case COAP_OPTION_ETAG:
526 case COAP_OPTION_LOCATION_PATH:
527 case COAP_OPTION_URI_PATH:
528 case COAP_OPTION_URI_QUERY:
529 case COAP_OPTION_LOCATION_QUERY:
530 case COAP_OPTION_RTAG:
531 break;
532 /* Protest at the known non-repeatable options and ignore them */
533 case COAP_OPTION_URI_HOST:
534 case COAP_OPTION_IF_NONE_MATCH:
535 case COAP_OPTION_OBSERVE:
536 case COAP_OPTION_URI_PORT:
537 case COAP_OPTION_OSCORE:
538 case COAP_OPTION_CONTENT_FORMAT:
539 case COAP_OPTION_MAXAGE:
540 case COAP_OPTION_HOP_LIMIT:
541 case COAP_OPTION_ACCEPT:
542 case COAP_OPTION_BLOCK2:
543 case COAP_OPTION_BLOCK1:
544 case COAP_OPTION_SIZE2:
545 case COAP_OPTION_PROXY_URI:
546 case COAP_OPTION_PROXY_SCHEME:
547 case COAP_OPTION_SIZE1:
548 case COAP_OPTION_ECHO:
549 case COAP_OPTION_NORESPONSE:
550 coap_log_info("Option number %d is not defined as repeatable - dropped\n",
551 number);
552 return 0;
553 default:
554 coap_log_info("Option number %d is not defined as repeatable\n",
555 number);
556 /* Accepting it after warning as there may be user defineable options */
557 break;
558 }
559 return 1;
560 }
561
562 size_t
coap_insert_option(coap_pdu_t * pdu,coap_option_num_t number,size_t len,const uint8_t * data)563 coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len,
564 const uint8_t *data) {
565 coap_opt_iterator_t opt_iter;
566 coap_opt_t *option;
567 uint16_t prev_number = 0;
568 size_t shift;
569 size_t opt_delta;
570 coap_option_t decode;
571 size_t shrink = 0;
572
573 if (number >= pdu->max_opt)
574 return coap_add_option_internal(pdu, number, len, data);
575
576 /* Need to locate where in current options to insert this one */
577 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
578 while ((option = coap_option_next(&opt_iter))) {
579 if (opt_iter.number > number) {
580 /* Found where to insert */
581 break;
582 }
583 prev_number = opt_iter.number;
584 }
585 assert(option != NULL);
586 /* size of option inc header to insert */
587 shift = coap_opt_encode_size(number - prev_number, len);
588
589 /* size of next option (header may shrink in size as delta changes */
590 if (!coap_opt_parse(option, pdu->used_size - (option - pdu->token), &decode))
591 return 0;
592 opt_delta = opt_iter.number - number;
593 if (opt_delta == 0) {
594 if (!coap_option_check_repeatable(number))
595 return 0;
596 }
597
598 if (!coap_pdu_check_resize(pdu,
599 pdu->used_size + shift - shrink))
600 return 0;
601
602 /* Possible a re-size took place with a realloc() */
603 /* Need to locate where in current options to insert this one */
604 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
605 while ((option = coap_option_next(&opt_iter))) {
606 if (opt_iter.number > number) {
607 /* Found where to insert */
608 break;
609 }
610 }
611 assert(option != NULL);
612
613 if (decode.delta < 13) {
614 /* can simply patch in the new delta of next option */
615 option[0] = (option[0] & 0x0f) + (coap_opt_t)(opt_delta << 4);
616 } else if (decode.delta < 269 && opt_delta < 13) {
617 /* option header is going to shrink by one byte */
618 option[1] = (option[0] & 0x0f) + (coap_opt_t)(opt_delta << 4);
619 shrink = 1;
620 } else if (decode.delta < 269 && opt_delta < 269) {
621 /* can simply patch in the new delta of next option */
622 option[1] = (coap_opt_t)(opt_delta - 13);
623 } else if (opt_delta < 13) {
624 /* option header is going to shrink by two bytes */
625 option[2] = (option[0] & 0x0f) + (coap_opt_t)(opt_delta << 4);
626 shrink = 2;
627 } else if (opt_delta < 269) {
628 /* option header is going to shrink by one bytes */
629 option[1] = (option[0] & 0x0f) + 0xd0;
630 option[2] = (coap_opt_t)(opt_delta - 13);
631 shrink = 1;
632 } else {
633 /* can simply patch in the new delta of next option */
634 option[1] = (coap_opt_t)((opt_delta - 269) >> 8);
635 option[2] = (opt_delta - 269) & 0xff;
636 }
637
638 memmove(&option[shift], &option[shrink],
639 pdu->used_size - (option - pdu->token) - shrink);
640 if (!coap_opt_encode(option, pdu->alloc_size - pdu->used_size,
641 number - prev_number, data, len))
642 return 0;
643
644 pdu->used_size += shift - shrink;
645 if (pdu->data)
646 pdu->data += shift - shrink;
647 return shift;
648 }
649
650 size_t
coap_update_option(coap_pdu_t * pdu,coap_option_num_t number,size_t len,const uint8_t * data)651 coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len,
652 const uint8_t *data) {
653 coap_opt_iterator_t opt_iter;
654 coap_opt_t *option;
655 coap_option_t decode;
656 size_t new_length = 0;
657 size_t old_length = 0;
658
659 option = coap_check_option(pdu, number, &opt_iter);
660 if (!option)
661 return coap_insert_option(pdu, number, len, data);
662
663 old_length = coap_opt_parse(option, (size_t)-1, &decode);
664 if (old_length == 0)
665 return 0;
666 new_length = coap_opt_encode_size(decode.delta, len);
667
668 if (new_length > old_length) {
669 if (!coap_pdu_check_resize(pdu,
670 pdu->used_size + new_length - old_length))
671 return 0;
672 /* Possible a re-size took place with a realloc() */
673 option = coap_check_option(pdu, number, &opt_iter);
674 }
675
676 if (new_length != old_length)
677 memmove(&option[new_length], &option[old_length],
678 pdu->used_size - (option - pdu->token) - old_length);
679
680 if (!coap_opt_encode(option, new_length,
681 decode.delta, data, len))
682 return 0;
683
684 pdu->used_size += new_length - old_length;
685 if (pdu->data)
686 pdu->data += new_length - old_length;
687 return 1;
688 }
689
690 size_t
coap_add_option(coap_pdu_t * pdu,coap_option_num_t number,size_t len,const uint8_t * data)691 coap_add_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len,
692 const uint8_t *data) {
693 if (pdu->data) {
694 coap_log_warn("coap_add_optlist_pdu: PDU already contains data\n");
695 return 0;
696 }
697 return coap_add_option_internal(pdu, number, len, data);
698 }
699
700 size_t
coap_add_option_internal(coap_pdu_t * pdu,coap_option_num_t number,size_t len,const uint8_t * data)701 coap_add_option_internal(coap_pdu_t *pdu, coap_option_num_t number, size_t len,
702 const uint8_t *data) {
703 size_t optsize;
704 coap_opt_t *opt;
705
706 assert(pdu);
707
708 if (number == pdu->max_opt) {
709 if (!coap_option_check_repeatable(number))
710 return 0;
711 }
712
713 if (COAP_PDU_IS_REQUEST(pdu) &&
714 (number == COAP_OPTION_PROXY_URI ||
715 number == COAP_OPTION_PROXY_SCHEME)) {
716 /*
717 * Need to check whether there is a hop-limit option. If not, it needs
718 * to be inserted by default (RFC 8768).
719 */
720 coap_opt_iterator_t opt_iter;
721
722 if (coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter) == NULL) {
723 size_t hop_limit = COAP_OPTION_HOP_LIMIT;
724
725 coap_insert_option(pdu, COAP_OPTION_HOP_LIMIT, 1, (uint8_t *)&hop_limit);
726 }
727 }
728
729 if (number < pdu->max_opt) {
730 coap_log_debug("coap_add_option: options are not in correct order\n");
731 return coap_insert_option(pdu, number, len, data);
732 }
733
734 optsize = coap_opt_encode_size(number - pdu->max_opt, len);
735 if (!coap_pdu_check_resize(pdu,
736 pdu->used_size + optsize))
737 return 0;
738
739 if (pdu->data) {
740 /* include option delimiter */
741 memmove(&pdu->data[optsize-1], &pdu->data[-1],
742 pdu->used_size - (pdu->data - pdu->token) + 1);
743 opt = pdu->data -1;
744 pdu->data += optsize;
745 } else {
746 opt = pdu->token + pdu->used_size;
747 }
748
749 /* encode option and check length */
750 optsize = coap_opt_encode(opt, pdu->alloc_size - pdu->used_size,
751 number - pdu->max_opt, data, len);
752
753 if (!optsize) {
754 coap_log_warn("coap_add_option: cannot add option\n");
755 /* error */
756 return 0;
757 } else {
758 pdu->max_opt = number;
759 pdu->used_size += optsize;
760 }
761
762 return optsize;
763 }
764
765 int
coap_add_data(coap_pdu_t * pdu,size_t len,const uint8_t * data)766 coap_add_data(coap_pdu_t *pdu, size_t len, const uint8_t *data) {
767 if (len == 0) {
768 return 1;
769 } else {
770 uint8_t *payload = coap_add_data_after(pdu, len);
771 if (payload != NULL)
772 memcpy(payload, data, len);
773 return payload != NULL;
774 }
775 }
776
777 uint8_t *
coap_add_data_after(coap_pdu_t * pdu,size_t len)778 coap_add_data_after(coap_pdu_t *pdu, size_t len) {
779 assert(pdu);
780 if (pdu->data) {
781 coap_log_warn("coap_add_data: PDU already contains data\n");
782 return 0;
783 }
784
785 if (len == 0)
786 return NULL;
787
788 if (!coap_pdu_resize(pdu, pdu->used_size + len + 1))
789 return 0;
790 pdu->token[pdu->used_size++] = COAP_PAYLOAD_START;
791 pdu->data = pdu->token + pdu->used_size;
792 pdu->used_size += len;
793 return pdu->data;
794 }
795
796 int
coap_get_data(const coap_pdu_t * pdu,size_t * len,const uint8_t ** data)797 coap_get_data(const coap_pdu_t *pdu, size_t *len, const uint8_t **data) {
798 size_t offset;
799 size_t total;
800
801 return coap_get_data_large(pdu, len, data, &offset, &total);
802 }
803
804 int
coap_get_data_large(const coap_pdu_t * pdu,size_t * len,const uint8_t ** data,size_t * offset,size_t * total)805 coap_get_data_large(const coap_pdu_t *pdu, size_t *len, const uint8_t **data,
806 size_t *offset, size_t *total) {
807 assert(pdu);
808 assert(len);
809 assert(data);
810
811 *offset = pdu->body_offset;
812 *total = pdu->body_total;
813 if (pdu->body_data) {
814 *data = pdu->body_data;
815 *len = pdu->body_length;
816 return 1;
817 }
818 *data = pdu->data;
819 if (pdu->data == NULL) {
820 *len = 0;
821 *total = 0;
822 return 0;
823 }
824
825 *len = pdu->used_size - (pdu->data - pdu->token);
826 if (*total == 0)
827 *total = *len;
828
829 return 1;
830 }
831
832 #ifndef SHORT_ERROR_RESPONSE
833 typedef struct {
834 unsigned char code;
835 const char *phrase;
836 } error_desc_t;
837
838 /* if you change anything here, make sure, that the longest string does not
839 * exceed COAP_ERROR_PHRASE_LENGTH. */
840 error_desc_t coap_error[] = {
841 { COAP_RESPONSE_CODE(201), "Created" },
842 { COAP_RESPONSE_CODE(202), "Deleted" },
843 { COAP_RESPONSE_CODE(203), "Valid" },
844 { COAP_RESPONSE_CODE(204), "Changed" },
845 { COAP_RESPONSE_CODE(205), "Content" },
846 { COAP_RESPONSE_CODE(231), "Continue" },
847 { COAP_RESPONSE_CODE(400), "Bad Request" },
848 { COAP_RESPONSE_CODE(401), "Unauthorized" },
849 { COAP_RESPONSE_CODE(402), "Bad Option" },
850 { COAP_RESPONSE_CODE(403), "Forbidden" },
851 { COAP_RESPONSE_CODE(404), "Not Found" },
852 { COAP_RESPONSE_CODE(405), "Method Not Allowed" },
853 { COAP_RESPONSE_CODE(406), "Not Acceptable" },
854 { COAP_RESPONSE_CODE(408), "Request Entity Incomplete" },
855 { COAP_RESPONSE_CODE(409), "Conflict" },
856 { COAP_RESPONSE_CODE(412), "Precondition Failed" },
857 { COAP_RESPONSE_CODE(413), "Request Entity Too Large" },
858 { COAP_RESPONSE_CODE(415), "Unsupported Content-Format" },
859 { COAP_RESPONSE_CODE(422), "Unprocessable" },
860 { COAP_RESPONSE_CODE(429), "Too Many Requests" },
861 { COAP_RESPONSE_CODE(500), "Internal Server Error" },
862 { COAP_RESPONSE_CODE(501), "Not Implemented" },
863 { COAP_RESPONSE_CODE(502), "Bad Gateway" },
864 { COAP_RESPONSE_CODE(503), "Service Unavailable" },
865 { COAP_RESPONSE_CODE(504), "Gateway Timeout" },
866 { COAP_RESPONSE_CODE(505), "Proxying Not Supported" },
867 { COAP_RESPONSE_CODE(508), "Hop Limit Reached" },
868 { 0, NULL } /* end marker */
869 };
870
871 const char *
coap_response_phrase(unsigned char code)872 coap_response_phrase(unsigned char code) {
873 int i;
874 for (i = 0; coap_error[i].code; ++i) {
875 if (coap_error[i].code == code)
876 return coap_error[i].phrase;
877 }
878 return NULL;
879 }
880 #endif
881
882 /**
883 * Advances *optp to next option if still in PDU. This function
884 * returns the number of bytes opt has been advanced or @c 0
885 * on error.
886 */
887 static size_t
next_option_safe(coap_opt_t ** optp,size_t * length,uint16_t * max_opt)888 next_option_safe(coap_opt_t **optp, size_t *length, uint16_t *max_opt) {
889 coap_option_t option;
890 size_t optsize;
891
892 assert(optp);
893 assert(*optp);
894 assert(length);
895
896 optsize = coap_opt_parse(*optp, *length, &option);
897 if (optsize) {
898 assert(optsize <= *length);
899
900 /* signal an error if this option would exceed the
901 * allowed number space */
902 if (*max_opt + option.delta > COAP_MAX_OPT) {
903 return 0;
904 }
905 *max_opt += option.delta;
906 *optp += optsize;
907 *length -= optsize;
908 }
909
910 return optsize;
911 }
912
913 size_t
coap_pdu_parse_header_size(coap_proto_t proto,const uint8_t * data)914 coap_pdu_parse_header_size(coap_proto_t proto,
915 const uint8_t *data) {
916 assert(data);
917 size_t header_size = 0;
918
919 if (proto == COAP_PROTO_TCP || proto==COAP_PROTO_TLS) {
920 uint8_t len = *data >> 4;
921 if (len < 13)
922 header_size = 2;
923 else if (len==13)
924 header_size = 3;
925 else if (len==14)
926 header_size = 4;
927 else
928 header_size = 6;
929 } else if (proto == COAP_PROTO_WS || proto==COAP_PROTO_WSS) {
930 header_size = 2;
931 } else if (proto == COAP_PROTO_UDP || proto==COAP_PROTO_DTLS) {
932 header_size = 4;
933 }
934
935 return header_size;
936 }
937
938 /*
939 * strm
940 * return +ve PDU size including token
941 * 0 PDU does not parse
942 */
943 size_t
coap_pdu_parse_size(coap_proto_t proto,const uint8_t * data,size_t length)944 coap_pdu_parse_size(coap_proto_t proto,
945 const uint8_t *data,
946 size_t length) {
947 assert(data);
948 assert(proto == COAP_PROTO_TCP || proto == COAP_PROTO_TLS ||
949 proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS);
950 assert(coap_pdu_parse_header_size(proto, data) <= length);
951
952 size_t size = 0;
953 const uint8_t *token_start = NULL;
954
955 if ((proto == COAP_PROTO_TCP || proto==COAP_PROTO_TLS) && length >= 1) {
956 uint8_t len = *data >> 4;
957 uint8_t tkl = *data & 0x0f;
958
959 if (len < 13) {
960 size = len;
961 token_start = &data[2];
962 } else if (length >= 2) {
963 if (len==13) {
964 size = (size_t)data[1] + COAP_MESSAGE_SIZE_OFFSET_TCP8;
965 token_start = &data[3];
966 } else if (length >= 3) {
967 if (len==14) {
968 size = ((size_t)data[1] << 8) + data[2] + COAP_MESSAGE_SIZE_OFFSET_TCP16;
969 token_start = &data[4];
970 } else if (length >= 5) {
971 size = ((size_t)data[1] << 24) + ((size_t)data[2] << 16)
972 + ((size_t)data[3] << 8) + data[4] + COAP_MESSAGE_SIZE_OFFSET_TCP32;
973 token_start = &data[6];
974 }
975 }
976 }
977 if (token_start) {
978 /* account for the token length */
979 if (tkl < COAP_TOKEN_EXT_1B_TKL) {
980 size += tkl;
981 } else if (tkl == COAP_TOKEN_EXT_1B_TKL) {
982 size += token_start[0] + COAP_TOKEN_EXT_1B_BIAS + 1;
983 } else if (tkl == COAP_TOKEN_EXT_2B_TKL) {
984 size += ((uint16_t)token_start[0] << 8) + token_start[1] +
985 COAP_TOKEN_EXT_2B_BIAS + 2;
986 } else {
987 /* Invalid at this point - caught later as undersized */
988 }
989 }
990 }
991
992 return size;
993 }
994
995 int
coap_pdu_parse_header(coap_pdu_t * pdu,coap_proto_t proto)996 coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto) {
997 uint8_t *hdr = pdu->token - pdu->hdr_size;
998 uint8_t e_token_length;
999
1000 if (proto == COAP_PROTO_UDP || proto == COAP_PROTO_DTLS) {
1001 assert(pdu->hdr_size == 4);
1002 if ((hdr[0] >> 6) != COAP_DEFAULT_VERSION) {
1003 coap_log_debug("coap_pdu_parse: UDP version not supported\n");
1004 return 0;
1005 }
1006 pdu->type = (hdr[0] >> 4) & 0x03;
1007 pdu->code = hdr[1];
1008 pdu->mid = (uint16_t)hdr[2] << 8 | hdr[3];
1009 } else if (proto == COAP_PROTO_TCP || proto == COAP_PROTO_TLS) {
1010 assert(pdu->hdr_size >= 2 && pdu->hdr_size <= 6);
1011 pdu->type = COAP_MESSAGE_CON;
1012 pdu->code = hdr[pdu->hdr_size-1];
1013 pdu->mid = 0;
1014 } else if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) {
1015 assert(pdu->hdr_size == 2);
1016 pdu->type = COAP_MESSAGE_CON;
1017 pdu->code = hdr[pdu->hdr_size-1];
1018 pdu->mid = 0;
1019 } else {
1020 coap_log_debug("coap_pdu_parse: unsupported protocol\n");
1021 return 0;
1022 }
1023
1024 e_token_length = hdr[0] & 0x0f;
1025 if (e_token_length < COAP_TOKEN_EXT_1B_TKL) {
1026 pdu->e_token_length = e_token_length;
1027 pdu->actual_token.length = pdu->e_token_length;
1028 pdu->actual_token.s = &pdu->token[0];
1029 } else if (e_token_length == COAP_TOKEN_EXT_1B_TKL) {
1030 pdu->e_token_length = pdu->token[0] + COAP_TOKEN_EXT_1B_BIAS + 1;
1031 pdu->actual_token.length = pdu->e_token_length - 1;
1032 pdu->actual_token.s = &pdu->token[1];
1033 } else if (e_token_length == COAP_TOKEN_EXT_2B_TKL) {
1034 pdu->e_token_length = ((uint16_t)pdu->token[0] << 8) + pdu->token[1] +
1035 COAP_TOKEN_EXT_2B_BIAS + 2;
1036 pdu->actual_token.length = pdu->e_token_length - 2;
1037 pdu->actual_token.s = &pdu->token[2];
1038 }
1039 if (pdu->e_token_length > pdu->alloc_size || e_token_length == 15) {
1040 /* Invalid PDU provided - not wise to assert here though */
1041 coap_log_debug("coap_pdu_parse: PDU header token size broken\n");
1042 pdu->e_token_length = 0;
1043 pdu->actual_token.length = 0;
1044 return 0;
1045 }
1046 return 1;
1047 }
1048
1049 static int
coap_pdu_parse_opt_csm(coap_pdu_t * pdu,uint16_t len)1050 coap_pdu_parse_opt_csm(coap_pdu_t *pdu, uint16_t len) {
1051 switch ((coap_pdu_signaling_proto_t)pdu->code) {
1052 case COAP_SIGNALING_CSM:
1053 switch (pdu->max_opt) {
1054 case COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE:
1055 if (len > 4)
1056 goto bad;
1057 break;
1058 case COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER:
1059 if (len > 0)
1060 goto bad;
1061 break;
1062 case COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH:
1063 if (len > 3)
1064 goto bad;
1065 break;
1066 default:
1067 if (pdu->max_opt & 0x01)
1068 goto bad; /* Critical */
1069 }
1070 break;
1071 case COAP_SIGNALING_PING:
1072 case COAP_SIGNALING_PONG:
1073 switch (pdu->max_opt) {
1074 case COAP_SIGNALING_OPTION_CUSTODY:
1075 if (len > 0)
1076 goto bad;
1077 break;
1078 default:
1079 if (pdu->max_opt & 0x01)
1080 goto bad; /* Critical */
1081 }
1082 break;
1083 case COAP_SIGNALING_RELEASE:
1084 switch (pdu->max_opt) {
1085 case COAP_SIGNALING_OPTION_ALTERNATIVE_ADDRESS:
1086 if (len < 1 || len > 255)
1087 goto bad;
1088 break;
1089 case COAP_SIGNALING_OPTION_HOLD_OFF:
1090 if (len > 3)
1091 goto bad;
1092 break;
1093 default:
1094 if (pdu->max_opt & 0x01)
1095 goto bad; /* Critical */
1096 }
1097 break;
1098 case COAP_SIGNALING_ABORT:
1099 switch (pdu->max_opt) {
1100 case COAP_SIGNALING_OPTION_BAD_CSM_OPTION:
1101 if (len > 2)
1102 goto bad;
1103 break;
1104 default:
1105 if (pdu->max_opt & 0x01)
1106 goto bad; /* Critical */
1107 }
1108 break;
1109 default:
1110 ;
1111 }
1112 return 1;
1113 bad:
1114 return 0;
1115 }
1116
1117 static int
coap_pdu_parse_opt_base(coap_pdu_t * pdu,uint16_t len)1118 coap_pdu_parse_opt_base(coap_pdu_t *pdu, uint16_t len) {
1119 int res = 1;
1120
1121 switch (pdu->max_opt) {
1122 case COAP_OPTION_IF_MATCH:
1123 if (len > 8)
1124 res = 0;
1125 break;
1126 case COAP_OPTION_URI_HOST:
1127 if (len < 1 || len > 255)
1128 res = 0;
1129 break;
1130 case COAP_OPTION_ETAG:
1131 if (len < 1 || len > 8)
1132 res = 0;
1133 break;
1134 case COAP_OPTION_IF_NONE_MATCH:
1135 if (len != 0)
1136 res = 0;
1137 break;
1138 case COAP_OPTION_OBSERVE:
1139 if (len > 3)
1140 res = 0;
1141 break;
1142 case COAP_OPTION_URI_PORT:
1143 if (len > 2)
1144 res = 0;
1145 break;
1146 case COAP_OPTION_LOCATION_PATH:
1147 if (len > 255)
1148 res = 0;
1149 break;
1150 case COAP_OPTION_OSCORE:
1151 if (len > 255)
1152 res = 0;
1153 break;
1154 case COAP_OPTION_URI_PATH:
1155 if (len > 255)
1156 res = 0;
1157 break;
1158 case COAP_OPTION_CONTENT_FORMAT:
1159 if (len > 2)
1160 res = 0;
1161 break;
1162 case COAP_OPTION_MAXAGE:
1163 if (len > 4)
1164 res = 0;
1165 break;
1166 case COAP_OPTION_URI_QUERY:
1167 if (len < 1 || len > 255)
1168 res = 0;
1169 break;
1170 case COAP_OPTION_HOP_LIMIT:
1171 if (len != 1)
1172 res = 0;
1173 break;
1174 case COAP_OPTION_ACCEPT:
1175 if (len > 2)
1176 res = 0;
1177 break;
1178 case COAP_OPTION_LOCATION_QUERY:
1179 if (len > 255)
1180 res = 0;
1181 break;
1182 case COAP_OPTION_BLOCK2:
1183 if (len > 3)
1184 res = 0;
1185 break;
1186 case COAP_OPTION_BLOCK1:
1187 if (len > 3)
1188 res = 0;
1189 break;
1190 case COAP_OPTION_SIZE2:
1191 if (len > 4)
1192 res = 0;
1193 break;
1194 case COAP_OPTION_PROXY_URI:
1195 if (len < 1 || len > 1034)
1196 res = 0;
1197 break;
1198 case COAP_OPTION_PROXY_SCHEME:
1199 if (len < 1 || len > 255)
1200 res = 0;
1201 break;
1202 case COAP_OPTION_SIZE1:
1203 if (len > 4)
1204 res = 0;
1205 break;
1206 case COAP_OPTION_ECHO:
1207 if (len > 40)
1208 res = 0;
1209 break;
1210 case COAP_OPTION_NORESPONSE:
1211 if (len > 1)
1212 res = 0;
1213 break;
1214 case COAP_OPTION_RTAG:
1215 if (len > 8)
1216 res = 0;
1217 break;
1218 default:
1219 ;
1220 }
1221 return res;
1222 }
1223
1224 static int
write_prefix(char ** obp,size_t * len,const char * prf,size_t prflen)1225 write_prefix(char **obp, size_t *len, const char *prf, size_t prflen) {
1226 /* Make sure space for null terminating byte */
1227 if (*len < prflen +1) {
1228 return 0;
1229 }
1230
1231 memcpy(*obp, prf, prflen);
1232 *obp += prflen;
1233 *len -= prflen;
1234 return 1;
1235 }
1236
1237 static int
write_char(char ** obp,size_t * len,char c,int printable)1238 write_char(char **obp, size_t *len, char c, int printable) {
1239 /* Make sure space for null terminating byte */
1240 if (*len < 2 +1) {
1241 return 0;
1242 }
1243
1244 if (!printable) {
1245 const uint8_t hex[] = "0123456789abcdef";
1246 (*obp)[0] = hex[(c & 0xf0) >> 4];
1247 (*obp)[1] = hex[c & 0x0f];
1248 } else {
1249 (*obp)[0] = isprint(c) ? c : '.';
1250 (*obp)[1] = ' ';
1251 }
1252 *obp += 2;
1253 *len -= 2;
1254 return 1;
1255 }
1256
1257 int
coap_pdu_parse_opt(coap_pdu_t * pdu)1258 coap_pdu_parse_opt(coap_pdu_t *pdu) {
1259
1260 int good = 1;
1261 /* sanity checks */
1262 if (pdu->code == 0) {
1263 if (pdu->used_size != 0 || pdu->e_token_length) {
1264 coap_log_debug("coap_pdu_parse: empty message is not empty\n");
1265 return 0;
1266 }
1267 }
1268
1269 if (pdu->e_token_length > pdu->used_size) {
1270 coap_log_debug("coap_pdu_parse: invalid Token\n");
1271 return 0;
1272 }
1273
1274 pdu->max_opt = 0;
1275 if (pdu->code == 0) {
1276 /* empty packet */
1277 pdu->used_size = 0;
1278 pdu->data = NULL;
1279 } else {
1280 /* skip header + token */
1281 coap_opt_t *opt = pdu->token + pdu->e_token_length;
1282 size_t length = pdu->used_size - pdu->e_token_length;
1283
1284 while (length > 0 && *opt != COAP_PAYLOAD_START) {
1285 #if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_WARN)
1286 coap_opt_t *opt_last = opt;
1287 #endif
1288 size_t optsize = next_option_safe(&opt, &length, &pdu->max_opt);
1289 const uint32_t len =
1290 optsize ? coap_opt_length((const uint8_t *)opt - optsize) : 0;
1291 if (optsize == 0) {
1292 coap_log_debug("coap_pdu_parse: %d.%02d: offset %u malformed option\n",
1293 pdu->code >> 5, pdu->code & 0x1F,
1294 (int)(opt_last - pdu->token - pdu->e_token_length));
1295 good = 0;
1296 break;
1297 }
1298 if (COAP_PDU_IS_SIGNALING(pdu) ?
1299 !coap_pdu_parse_opt_csm(pdu, len) :
1300 !coap_pdu_parse_opt_base(pdu, len)) {
1301 coap_log_warn("coap_pdu_parse: %d.%02d: offset %u option %u has bad length %" PRIu32 "\n",
1302 pdu->code >> 5, pdu->code & 0x1F,
1303 (int)(opt_last - pdu->token - pdu->e_token_length), pdu->max_opt,
1304 len);
1305 good = 0;
1306 }
1307 }
1308
1309 if (!good) {
1310 /*
1311 * Dump the options in the PDU for analysis, space separated except
1312 * error options which are prefixed by *
1313 * Two rows - hex and ascii (if printable)
1314 */
1315 static char outbuf[COAP_DEBUG_BUF_SIZE];
1316 char *obp;
1317 size_t tlen;
1318 size_t outbuflen;
1319 int i;
1320 int ok;
1321
1322 for (i = 0; i < 2; i++) {
1323 opt = pdu->token + pdu->e_token_length;
1324 length = pdu->used_size - pdu->e_token_length;
1325 pdu->max_opt = 0;
1326
1327 outbuflen = sizeof(outbuf);
1328 obp = outbuf;
1329 ok = write_prefix(&obp, &outbuflen, "O: ", 3);
1330 while (length > 0 && *opt != COAP_PAYLOAD_START) {
1331 coap_opt_t *opt_last = opt;
1332 size_t optsize = next_option_safe(&opt, &length, &pdu->max_opt);
1333 const uint32_t len =
1334 optsize ? coap_opt_length((const uint8_t *)opt - optsize) : 0;
1335 if (!optsize || (COAP_PDU_IS_SIGNALING(pdu) ?
1336 !coap_pdu_parse_opt_csm(pdu, len) :
1337 !coap_pdu_parse_opt_base(pdu, len))) {
1338 ok = ok && write_prefix(&obp, &outbuflen, "*", 1);
1339 if (!optsize) {
1340 /* Skip to end of options to output all data */
1341 opt = pdu->token + pdu->used_size;
1342 length = 0;
1343 }
1344 } else {
1345 ok = ok && write_prefix(&obp, &outbuflen, " ", 1);
1346 }
1347 tlen = opt - opt_last;
1348 while (tlen--) {
1349 ok = ok && write_char(&obp, &outbuflen, *opt_last, i);
1350 opt_last++;
1351 }
1352 }
1353 if (length && *opt == COAP_PAYLOAD_START) {
1354 ok = ok && write_char(&obp, &outbuflen, *opt, i);
1355 }
1356 /* write_*() always leaves a spare byte to null terminate */
1357 *obp = '\000';
1358 coap_log_debug("%s\n", outbuf);
1359 }
1360 }
1361
1362 if (length > 0) {
1363 assert(*opt == COAP_PAYLOAD_START);
1364 opt++;
1365 length--;
1366
1367 if (length == 0) {
1368 coap_log_debug("coap_pdu_parse: message ending in payload start marker\n");
1369 return 0;
1370 }
1371 }
1372 if (length > 0)
1373 pdu->data = (uint8_t *)opt;
1374 else
1375 pdu->data = NULL;
1376 }
1377
1378 return good;
1379 }
1380
1381 int
coap_pdu_parse(coap_proto_t proto,const uint8_t * data,size_t length,coap_pdu_t * pdu)1382 coap_pdu_parse(coap_proto_t proto,
1383 const uint8_t *data,
1384 size_t length,
1385 coap_pdu_t *pdu) {
1386 size_t hdr_size;
1387
1388 if (length == 0)
1389 return 0;
1390 hdr_size = coap_pdu_parse_header_size(proto, data);
1391 if (!hdr_size || hdr_size > length)
1392 return 0;
1393 if (hdr_size > pdu->max_hdr_size)
1394 return 0;
1395 if (!coap_pdu_resize(pdu, length - hdr_size))
1396 return 0;
1397 if (pdu->token - hdr_size != data)
1398 memcpy(pdu->token - hdr_size, data, length);
1399 pdu->hdr_size = (uint8_t)hdr_size;
1400 pdu->used_size = length - hdr_size;
1401 return coap_pdu_parse_header(pdu, proto) && coap_pdu_parse_opt(pdu);
1402 }
1403
1404 size_t
coap_pdu_encode_header(coap_pdu_t * pdu,coap_proto_t proto)1405 coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto) {
1406 if (pdu == NULL || pdu->token == NULL)
1407 return 0;
1408
1409 uint8_t e_token_length;
1410
1411 if (pdu->actual_token.length < COAP_TOKEN_EXT_1B_BIAS) {
1412 e_token_length = (uint8_t)pdu->actual_token.length;
1413 } else if (pdu->actual_token.length < COAP_TOKEN_EXT_2B_BIAS) {
1414 e_token_length = COAP_TOKEN_EXT_1B_TKL;
1415 } else if (pdu->actual_token.length <= COAP_TOKEN_EXT_MAX) {
1416 e_token_length = COAP_TOKEN_EXT_2B_TKL;
1417 } else {
1418 coap_log_warn("coap_add_token: Token size too large. PDU ignored\n");
1419 return 0;
1420 }
1421 if (COAP_PROTO_NOT_RELIABLE(proto)) {
1422 assert(pdu->max_hdr_size >= 4);
1423 if (pdu->max_hdr_size < 4) {
1424 coap_log_warn("coap_pdu_encode_header: not enough space for UDP-style header\n");
1425 return 0;
1426 }
1427 pdu->token[-4] = COAP_DEFAULT_VERSION << 6
1428 | pdu->type << 4
1429 | e_token_length;
1430 pdu->token[-3] = pdu->code;
1431 pdu->token[-2] = (uint8_t)(pdu->mid >> 8);
1432 pdu->token[-1] = (uint8_t)(pdu->mid);
1433 pdu->hdr_size = 4;
1434 } else if (COAP_PROTO_RELIABLE(proto)) {
1435 size_t len;
1436 assert(pdu->used_size >= pdu->e_token_length);
1437 if (pdu->used_size < pdu->e_token_length) {
1438 coap_log_warn("coap_pdu_encode_header: corrupted PDU\n");
1439 return 0;
1440 }
1441 if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS)
1442 len = 0;
1443 else
1444 len = pdu->used_size - pdu->e_token_length;
1445 if (len <= COAP_MAX_MESSAGE_SIZE_TCP0) {
1446 assert(pdu->max_hdr_size >= 2);
1447 if (pdu->max_hdr_size < 2) {
1448 coap_log_warn("coap_pdu_encode_header: not enough space for TCP0 header\n");
1449 return 0;
1450 }
1451 pdu->token[-2] = (uint8_t)len << 4
1452 | e_token_length;
1453 pdu->token[-1] = pdu->code;
1454 pdu->hdr_size = 2;
1455 } else if (len <= COAP_MAX_MESSAGE_SIZE_TCP8) {
1456 assert(pdu->max_hdr_size >= 3);
1457 if (pdu->max_hdr_size < 3) {
1458 coap_log_warn("coap_pdu_encode_header: not enough space for TCP8 header\n");
1459 return 0;
1460 }
1461 pdu->token[-3] = 13 << 4 | e_token_length;
1462 pdu->token[-2] = (uint8_t)(len - COAP_MESSAGE_SIZE_OFFSET_TCP8);
1463 pdu->token[-1] = pdu->code;
1464 pdu->hdr_size = 3;
1465 } else if (len <= COAP_MAX_MESSAGE_SIZE_TCP16) {
1466 assert(pdu->max_hdr_size >= 4);
1467 if (pdu->max_hdr_size < 4) {
1468 coap_log_warn("coap_pdu_encode_header: not enough space for TCP16 header\n");
1469 return 0;
1470 }
1471 pdu->token[-4] = 14 << 4 | e_token_length;
1472 pdu->token[-3] = (uint8_t)((len - COAP_MESSAGE_SIZE_OFFSET_TCP16) >> 8);
1473 pdu->token[-2] = (uint8_t)(len - COAP_MESSAGE_SIZE_OFFSET_TCP16);
1474 pdu->token[-1] = pdu->code;
1475 pdu->hdr_size = 4;
1476 } else {
1477 assert(pdu->max_hdr_size >= 6);
1478 if (pdu->max_hdr_size < 6) {
1479 coap_log_warn("coap_pdu_encode_header: not enough space for TCP32 header\n");
1480 return 0;
1481 }
1482 pdu->token[-6] = 15 << 4 | e_token_length;
1483 pdu->token[-5] = (uint8_t)((len - COAP_MESSAGE_SIZE_OFFSET_TCP32) >> 24);
1484 pdu->token[-4] = (uint8_t)((len - COAP_MESSAGE_SIZE_OFFSET_TCP32) >> 16);
1485 pdu->token[-3] = (uint8_t)((len - COAP_MESSAGE_SIZE_OFFSET_TCP32) >> 8);
1486 pdu->token[-2] = (uint8_t)(len - COAP_MESSAGE_SIZE_OFFSET_TCP32);
1487 pdu->token[-1] = pdu->code;
1488 pdu->hdr_size = 6;
1489 }
1490 } else {
1491 coap_log_warn("coap_pdu_encode_header: unsupported protocol\n");
1492 }
1493 return pdu->hdr_size;
1494 }
1495
1496 coap_pdu_code_t
coap_pdu_get_code(const coap_pdu_t * pdu)1497 coap_pdu_get_code(const coap_pdu_t *pdu) {
1498 return pdu->code;
1499 }
1500
1501 void
coap_pdu_set_code(coap_pdu_t * pdu,coap_pdu_code_t code)1502 coap_pdu_set_code(coap_pdu_t *pdu, coap_pdu_code_t code) {
1503 assert(code <= 0xff);
1504 pdu->code = code;
1505 }
1506
1507 coap_pdu_type_t
coap_pdu_get_type(const coap_pdu_t * pdu)1508 coap_pdu_get_type(const coap_pdu_t *pdu) {
1509 return pdu->type;
1510 }
1511
1512 void
coap_pdu_set_type(coap_pdu_t * pdu,coap_pdu_type_t type)1513 coap_pdu_set_type(coap_pdu_t *pdu, coap_pdu_type_t type) {
1514 assert(type <= 0x3);
1515 pdu->type = type;
1516 }
1517
1518 coap_bin_const_t
coap_pdu_get_token(const coap_pdu_t * pdu)1519 coap_pdu_get_token(const coap_pdu_t *pdu) {
1520 return pdu->actual_token;
1521 }
1522
1523 coap_mid_t
coap_pdu_get_mid(const coap_pdu_t * pdu)1524 coap_pdu_get_mid(const coap_pdu_t *pdu) {
1525 return pdu->mid;
1526 }
1527
1528 void
coap_pdu_set_mid(coap_pdu_t * pdu,coap_mid_t mid)1529 coap_pdu_set_mid(coap_pdu_t *pdu, coap_mid_t mid) {
1530 assert(mid >= 0 && mid <= 0xffff);
1531 pdu->mid = mid;
1532 }
1533