Coverage Report

Created: 2026-12-01 07:02

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