Coverage Report

Created: 2026-11-12 06:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libcoap/src/coap_net.c
Line
Count
Source
1
/* coap_net.c -- CoAP context interface
2
 *
3
 * Copyright (C) 2010--2026 Olaf Bergmann <bergmann@tzi.org> and others
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 *
7
 * This file is part of the CoAP library libcoap. Please see
8
 * README for terms of use.
9
 */
10
11
/**
12
 * @file coap_net.c
13
 * @brief CoAP context functions
14
 */
15
16
#include "coap3/coap_libcoap_build.h"
17
#include "coap3/coap_mutex_internal.h"
18
19
#include <ctype.h>
20
#include <stdio.h>
21
#ifdef HAVE_LIMITS_H
22
#include <limits.h>
23
#endif
24
25
#ifndef __ZEPHYR__
26
#ifdef HAVE_UNISTD_H
27
#include <unistd.h>
28
#else
29
#ifdef HAVE_SYS_UNISTD_H
30
#include <sys/unistd.h>
31
#endif
32
#endif
33
#ifdef HAVE_SYS_TYPES_H
34
#include <sys/types.h>
35
#endif
36
#ifdef HAVE_SYS_SOCKET_H
37
#include <sys/socket.h>
38
#endif
39
#ifdef HAVE_SYS_IOCTL_H
40
#include <sys/ioctl.h>
41
#endif
42
#ifdef HAVE_NETINET_IN_H
43
#include <netinet/in.h>
44
#endif
45
#ifdef HAVE_ARPA_INET_H
46
#include <arpa/inet.h>
47
#endif
48
#ifdef HAVE_NET_IF_H
49
#include <net/if.h>
50
#endif
51
#ifdef COAP_EPOLL_SUPPORT
52
#include <sys/epoll.h>
53
#include <sys/timerfd.h>
54
#endif /* COAP_EPOLL_SUPPORT */
55
#ifdef HAVE_WS2TCPIP_H
56
#include <ws2tcpip.h>
57
#endif
58
59
#ifdef HAVE_NETDB_H
60
#include <netdb.h>
61
#endif
62
#endif /* !__ZEPHYR__ */
63
64
#ifdef WITH_LWIP
65
#include <lwip/pbuf.h>
66
#include <lwip/udp.h>
67
#include <lwip/timeouts.h>
68
#include <lwip/tcpip.h>
69
#endif
70
71
#ifndef INET6_ADDRSTRLEN
72
#define INET6_ADDRSTRLEN 40
73
#endif
74
75
#ifndef min
76
0
#define min(a,b) ((a) < (b) ? (a) : (b))
77
#endif
78
79
/**
80
 * The number of bits for the fractional part of ACK_TIMEOUT and
81
 * ACK_RANDOM_FACTOR. Must be less or equal 8.
82
 */
83
#define FRAC_BITS 6
84
85
/**
86
 * The maximum number of bits for fixed point integers that are used
87
 * for retransmission time calculation. Currently this must be @c 8.
88
 */
89
#define MAX_BITS 8
90
91
#if FRAC_BITS > 8
92
#error FRAC_BITS must be less or equal 8
93
#endif
94
95
/** creates a Qx.frac from fval in coap_fixed_point_t */
96
#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
97
                                 ((1 << (frac)) * fval.fractional_part + 500)/1000))
98
99
/** creates a Qx.FRAC_BITS from session's 'ack_random_factor' */
100
#define ACK_RANDOM_FACTOR                                        \
101
  Q(FRAC_BITS, session->ack_random_factor)
102
103
/** creates a Qx.FRAC_BITS from session's 'ack_timeout' */
104
#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
105
106
static int send_recv_terminate = 0;
107
108
COAP_STATIC_INLINE coap_queue_t *
109
2.29k
coap_malloc_node(void) {
110
2.29k
  return (coap_queue_t *)coap_malloc_type(COAP_NODE, sizeof(coap_queue_t));
111
2.29k
}
112
113
COAP_STATIC_INLINE void
114
2.29k
coap_free_node(coap_queue_t *node) {
115
2.29k
  coap_free_type(COAP_NODE, node);
116
2.29k
}
117
118
unsigned int
119
0
coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
120
0
  unsigned int result = 0;
121
0
  coap_tick_diff_t delta = (coap_tick_diff_t)now - (coap_tick_diff_t)ctx->sendqueue_basetime;
122
123
0
  if (ctx->sendqueue) {
124
    /* delta < 0 means that the new time stamp is before the old. */
125
0
    if (delta <= 0) {
126
0
      ctx->sendqueue->t = (coap_tick_diff_t)ctx->sendqueue->t - delta;
127
0
    } else {
128
      /* This case is more complex: The time must be advanced forward,
129
       * thus possibly leading to timed out elements at the queue's
130
       * start. For every element that has timed out, its relative
131
       * time is set to zero and the result counter is increased. */
132
133
0
      coap_queue_t *q = ctx->sendqueue;
134
0
      coap_tick_t t = 0;
135
0
      while (q && (t + q->t < (coap_tick_t)delta)) {
136
0
        t += q->t;
137
0
        q->t = 0;
138
0
        result++;
139
0
        q = q->next;
140
0
      }
141
142
      /* finally adjust the first element that has not expired */
143
0
      if (q) {
144
0
        q->t = (coap_tick_t)delta - t;
145
0
      }
146
0
    }
147
0
  }
148
149
  /* adjust basetime */
150
0
  ctx->sendqueue_basetime = (coap_tick_diff_t)ctx->sendqueue_basetime + delta;
151
152
0
  return result;
153
0
}
154
155
int
156
1.81k
coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
157
1.81k
  coap_queue_t *p, *q;
158
1.81k
  if (!queue || !node)
159
0
    return 0;
160
161
  /* set queue head if empty */
162
1.81k
  if (!*queue) {
163
1.81k
    *queue = node;
164
1.81k
    return 1;
165
1.81k
  }
166
167
  /* replace queue head if PDU's time is less than head's time */
168
0
  q = *queue;
169
0
  if (node->t < q->t) {
170
0
    node->next = q;
171
0
    *queue = node;
172
0
    q->t -= node->t;                /* make q->t relative to node->t */
173
0
    return 1;
174
0
  }
175
176
  /* search for right place to insert */
177
0
  do {
178
0
    node->t -= q->t;                /* make node-> relative to q->t */
179
0
    p = q;
180
0
    q = q->next;
181
0
  } while (q && q->t <= node->t);
182
183
  /* insert new item */
184
0
  if (q) {
185
0
    q->t -= node->t;                /* make q->t relative to node->t */
186
0
  }
187
0
  node->next = q;
188
0
  p->next = node;
189
0
  return 1;
190
0
}
191
192
COAP_API int
193
1.80k
coap_delete_node(coap_queue_t *node) {
194
1.80k
  int ret;
195
196
1.80k
  if (!node)
197
0
    return 0;
198
199
1.80k
  coap_lock_lock(return 0);
200
1.80k
  ret = coap_delete_node_lkd(node);
201
1.80k
  coap_lock_unlock();
202
1.80k
  return ret;
203
1.80k
}
204
205
int
206
5.67k
coap_delete_node_lkd(coap_queue_t *node) {
207
5.67k
  if (!node)
208
3.38k
    return 0;
209
210
2.29k
  coap_delete_pdu_lkd(node->pdu);
211
2.29k
  if (node->session) {
212
    /*
213
     * Need to remove out of context->sendqueue as added in by coap_wait_ack()
214
     */
215
1.81k
    if (node->session->context->sendqueue) {
216
8
      LL_DELETE(node->session->context->sendqueue, node);
217
8
    }
218
1.81k
    coap_session_release_lkd(node->session);
219
1.81k
  }
220
2.29k
  coap_free_node(node);
221
222
2.29k
  return 1;
223
5.67k
}
224
225
void
226
5.57k
coap_delete_all(coap_queue_t *queue) {
227
5.57k
  if (!queue)
228
5.57k
    return;
229
230
8
  coap_delete_all(queue->next);
231
8
  coap_delete_node_lkd(queue);
232
8
}
233
234
coap_queue_t *
235
2.29k
coap_new_node(void) {
236
2.29k
  coap_queue_t *node;
237
2.29k
  node = coap_malloc_node();
238
239
2.29k
  if (!node) {
240
0
    coap_log_warn("coap_new_node: malloc failed\n");
241
0
    return NULL;
242
0
  }
243
244
2.29k
  memset(node, 0, sizeof(*node));
245
2.29k
  return node;
246
2.29k
}
247
248
coap_queue_t *
249
1.85k
coap_peek_next(coap_context_t *context) {
250
1.85k
  if (!context || !context->sendqueue)
251
52
    return NULL;
252
253
1.80k
  return context->sendqueue;
254
1.85k
}
255
256
coap_queue_t *
257
1.80k
coap_pop_next(coap_context_t *context) {
258
1.80k
  coap_queue_t *next;
259
260
1.80k
  if (!context || !context->sendqueue)
261
0
    return NULL;
262
263
1.80k
  next = context->sendqueue;
264
1.80k
  context->sendqueue = context->sendqueue->next;
265
1.80k
  if (context->sendqueue) {
266
0
    context->sendqueue->t += next->t;
267
0
  }
268
1.80k
  next->next = NULL;
269
1.80k
  return next;
270
1.80k
}
271
272
#if COAP_CLIENT_SUPPORT
273
const coap_bin_const_t *
274
0
coap_get_session_client_psk_key(const coap_session_t *session) {
275
276
0
  if (session->psk_key) {
277
0
    return session->psk_key;
278
0
  }
279
0
  if (session->cpsk_setup_data.psk_info.key.length)
280
0
    return &session->cpsk_setup_data.psk_info.key;
281
282
  /* Not defined in coap_new_client_session_psk2() */
283
0
  return NULL;
284
0
}
285
286
const coap_bin_const_t *
287
0
coap_get_session_client_psk_identity(const coap_session_t *session) {
288
289
0
  if (session->psk_identity) {
290
0
    return session->psk_identity;
291
0
  }
292
0
  if (session->cpsk_setup_data.psk_info.identity.length)
293
0
    return &session->cpsk_setup_data.psk_info.identity;
294
295
  /* Not defined in coap_new_client_session_psk2() */
296
0
  return NULL;
297
0
}
298
#endif /* COAP_CLIENT_SUPPORT */
299
300
#if COAP_SERVER_SUPPORT
301
const coap_bin_const_t *
302
0
coap_get_session_server_psk_key(const coap_session_t *session) {
303
304
0
  if (session->psk_key)
305
0
    return session->psk_key;
306
307
0
  if (session->context->spsk_setup_data.psk_info.key.length)
308
0
    return &session->context->spsk_setup_data.psk_info.key;
309
310
  /* Not defined in coap_context_set_psk2() */
311
0
  return NULL;
312
0
}
313
314
const coap_bin_const_t *
315
0
coap_get_session_server_psk_hint(const coap_session_t *session) {
316
317
0
  if (session->psk_hint)
318
0
    return session->psk_hint;
319
320
0
  if (session->context->spsk_setup_data.psk_info.hint.length)
321
0
    return &session->context->spsk_setup_data.psk_info.hint;
322
323
  /* Not defined in coap_context_set_psk2() */
324
0
  return NULL;
325
0
}
326
327
COAP_API int
328
coap_context_set_psk(coap_context_t *ctx,
329
                     const char *hint,
330
                     const uint8_t *key,
331
1.02k
                     size_t key_len) {
332
1.02k
  int ret;
333
334
1.02k
  coap_lock_lock(return 0);
335
1.02k
  ret = coap_context_set_psk_lkd(ctx, hint, key, key_len);
336
1.02k
  coap_lock_unlock();
337
1.02k
  return ret;
338
1.02k
}
339
340
int
341
coap_context_set_psk_lkd(coap_context_t *ctx,
342
                         const char *hint,
343
                         const uint8_t *key,
344
1.02k
                         size_t key_len) {
345
1.02k
  coap_dtls_spsk_t setup_data;
346
347
1.02k
  coap_lock_check_locked();
348
1.02k
  memset(&setup_data, 0, sizeof(setup_data));
349
1.02k
  if (hint) {
350
1.02k
    setup_data.psk_info.hint.s = (const uint8_t *)hint;
351
1.02k
    setup_data.psk_info.hint.length = strlen(hint);
352
1.02k
  }
353
354
1.02k
  if (key && key_len > 0) {
355
1.02k
    setup_data.psk_info.key.s = key;
356
1.02k
    setup_data.psk_info.key.length = key_len;
357
1.02k
  }
358
359
1.02k
  return coap_context_set_psk2_lkd(ctx, &setup_data);
360
1.02k
}
361
362
COAP_API int
363
0
coap_context_set_psk2(coap_context_t *ctx, coap_dtls_spsk_t *setup_data) {
364
0
  int ret;
365
366
0
  coap_lock_lock(return 0);
367
0
  ret = coap_context_set_psk2_lkd(ctx, setup_data);
368
0
  coap_lock_unlock();
369
0
  return ret;
370
0
}
371
372
int
373
1.02k
coap_context_set_psk2_lkd(coap_context_t *ctx, coap_dtls_spsk_t *setup_data) {
374
1.02k
  if (!setup_data)
375
0
    return 0;
376
377
1.02k
  coap_lock_check_locked();
378
1.02k
  ctx->spsk_setup_data = *setup_data;
379
380
1.02k
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
381
1.02k
    return coap_dtls_context_set_spsk(ctx, setup_data);
382
1.02k
  }
383
0
  return 0;
384
1.02k
}
385
386
COAP_API int
387
coap_context_set_pki(coap_context_t *ctx,
388
0
                     const coap_dtls_pki_t *setup_data) {
389
0
  int ret;
390
391
0
  coap_lock_lock(return 0);
392
0
  ret = coap_context_set_pki_lkd(ctx, setup_data);
393
0
  coap_lock_unlock();
394
0
  return ret;
395
0
}
396
397
int
398
coap_context_set_pki_lkd(coap_context_t *ctx,
399
0
                         const coap_dtls_pki_t *setup_data) {
400
0
  coap_lock_check_locked();
401
0
  if (!setup_data)
402
0
    return 0;
403
0
  if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
404
0
    coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
405
0
    return 0;
406
0
  }
407
0
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
408
0
    return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
409
0
  }
410
0
  return 0;
411
0
}
412
#endif /* ! COAP_SERVER_SUPPORT */
413
414
COAP_API int
415
coap_context_set_pki_root_cas(coap_context_t *ctx,
416
                              const char *ca_file,
417
0
                              const char *ca_dir) {
418
0
  int ret;
419
420
0
  coap_lock_lock(return 0);
421
0
  ret = coap_context_set_pki_root_cas_lkd(ctx, ca_file, ca_dir);
422
0
  coap_lock_unlock();
423
0
  return ret;
424
0
}
425
426
int
427
coap_context_set_pki_root_cas_lkd(coap_context_t *ctx,
428
                                  const char *ca_file,
429
0
                                  const char *ca_dir) {
430
0
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
431
0
    return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
432
0
  }
433
0
  return 0;
434
0
}
435
436
COAP_API int
437
0
coap_context_load_pki_trust_store(coap_context_t *ctx) {
438
0
  int ret;
439
440
0
  coap_lock_lock(return 0);
441
0
  ret = coap_context_load_pki_trust_store_lkd(ctx);
442
0
  coap_lock_unlock();
443
0
  return ret;
444
0
}
445
446
int
447
0
coap_context_load_pki_trust_store_lkd(coap_context_t *ctx) {
448
0
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
449
0
    return coap_dtls_context_load_pki_trust_store(ctx);
450
0
  }
451
0
  return 0;
452
0
}
453
454
455
void
456
1.80k
coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
457
1.80k
  context->ping_timeout = seconds;
458
1.80k
}
459
460
int
461
0
coap_context_set_cid_tuple_change(coap_context_t *context, uint8_t every) {
462
0
#if COAP_CLIENT_SUPPORT
463
0
  return coap_dtls_set_cid_tuple_change(context, every);
464
#else /* ! COAP_CLIENT_SUPPORT */
465
  (void)context;
466
  (void)every;
467
  return 0;
468
#endif /* ! COAP_CLIENT_SUPPORT */
469
0
}
470
471
void
472
coap_context_rate_limit_ppm(coap_context_t *context,
473
0
                            uint64_t rate_limit_ppm) {
474
0
  if (rate_limit_ppm) {
475
0
    context->rl_ticks_per_packet = (60ULL * COAP_TICKS_PER_SECOND) / rate_limit_ppm;
476
0
  } else {
477
0
    context->rl_ticks_per_packet = 0;
478
0
  }
479
0
}
480
481
void
482
coap_context_set_max_body_size(coap_context_t *context,
483
0
                               size_t max_body_size) {
484
0
  assert(max_body_size == 0 || max_body_size > 1024);
485
0
  if (max_body_size == 0 || max_body_size > 1024) {
486
0
    context->max_body_size = max_body_size;
487
0
  }
488
0
}
489
490
void
491
coap_context_set_max_bodies_ram(coap_context_t *context,
492
0
                                size_t max_bodies_ram) {
493
0
#if COAP_SERVER_SUPPORT
494
0
  assert(max_bodies_ram == 0 || max_bodies_ram > 1024);
495
0
  if (max_bodies_ram == 0 || max_bodies_ram > 1024) {
496
0
    context->max_bodies_ram = max_bodies_ram;
497
0
  }
498
  /* Cannot let a single session keep failing if it is larger then max_bodies_ram */
499
0
  if (context->max_body_size == 0)
500
0
    context->max_body_size = max_bodies_ram;
501
#else
502
  (void)context;
503
  (void)max_bodies_ram;
504
#endif /* COAP_SERVER_SUPPORT */
505
0
}
506
507
void
508
coap_context_set_max_token_size(coap_context_t *context,
509
1.80k
                                size_t max_token_size) {
510
1.80k
  assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
511
1.80k
         max_token_size <= COAP_TOKEN_EXT_MAX);
512
1.80k
  if (max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
513
1.80k
      max_token_size <= COAP_TOKEN_EXT_MAX) {
514
1.80k
    context->max_token_size = (uint32_t)max_token_size;
515
1.80k
  }
516
1.80k
}
517
518
void
519
coap_context_set_max_idle_sessions(coap_context_t *context,
520
1.80k
                                   unsigned int max_idle_sessions) {
521
1.80k
  context->max_idle_sessions = max_idle_sessions;
522
1.80k
}
523
524
unsigned int
525
0
coap_context_get_max_idle_sessions(const coap_context_t *context) {
526
0
  return context->max_idle_sessions;
527
0
}
528
529
void
530
coap_context_set_max_handshake_sessions(coap_context_t *context,
531
1.80k
                                        unsigned int max_handshake_sessions) {
532
1.80k
  context->max_handshake_sessions = max_handshake_sessions;
533
1.80k
}
534
535
unsigned int
536
0
coap_context_get_max_handshake_sessions(const coap_context_t *context) {
537
0
  return context->max_handshake_sessions;
538
0
}
539
540
static unsigned int s_csm_timeout = 30;
541
542
void
543
coap_context_set_csm_timeout(coap_context_t *context,
544
0
                             unsigned int csm_timeout) {
545
0
  s_csm_timeout = csm_timeout;
546
0
  coap_context_set_csm_timeout_ms(context, csm_timeout * 1000);
547
0
}
548
549
unsigned int
550
0
coap_context_get_csm_timeout(const coap_context_t *context) {
551
0
  (void)context;
552
0
  return s_csm_timeout;
553
0
}
554
555
void
556
coap_context_set_csm_timeout_ms(coap_context_t *context,
557
1.66k
                                unsigned int csm_timeout_ms) {
558
1.66k
  if (csm_timeout_ms < 10)
559
38
    csm_timeout_ms = 10;
560
1.66k
  if (csm_timeout_ms > 10000)
561
1.60k
    csm_timeout_ms = 10000;
562
1.66k
  context->csm_timeout_ms = csm_timeout_ms;
563
1.66k
}
564
565
unsigned int
566
0
coap_context_get_csm_timeout_ms(const coap_context_t *context) {
567
0
  return context->csm_timeout_ms;
568
0
}
569
570
void
571
coap_context_set_csm_max_message_size(coap_context_t *context,
572
1.32k
                                      uint32_t csm_max_message_size) {
573
1.32k
  assert(csm_max_message_size >= 64);
574
1.32k
  if (csm_max_message_size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
575
1.11k
    csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
576
1.11k
    coap_log_debug("Restricting CSM Max-Message-Size size to %" PRIu32 "\n",
577
1.11k
                   csm_max_message_size);
578
1.11k
  }
579
580
1.32k
  context->csm_max_message_size = csm_max_message_size;
581
1.32k
}
582
583
uint32_t
584
0
coap_context_get_csm_max_message_size(const coap_context_t *context) {
585
0
  return context->csm_max_message_size;
586
0
}
587
588
void
589
coap_context_set_session_timeout(coap_context_t *context,
590
1.80k
                                 unsigned int session_timeout) {
591
1.80k
  context->session_timeout = session_timeout;
592
1.80k
}
593
594
void
595
coap_context_set_session_reconnect_time(coap_context_t *context,
596
0
                                        unsigned int reconnect_time) {
597
0
  coap_context_set_session_reconnect_time2(context, reconnect_time, 0);
598
0
}
599
600
void
601
coap_context_set_session_reconnect_time2(coap_context_t *context,
602
                                         unsigned int reconnect_time,
603
0
                                         uint8_t retry_count) {
604
0
#if COAP_CLIENT_SUPPORT
605
0
  context->reconnect_time = reconnect_time;
606
0
  context->retry_count = retry_count;
607
#else /* ! COAP_CLIENT_SUPPORT */
608
  (void)context;
609
  (void)reconnect_time;
610
  (void)retry_count;
611
#endif /* ! COAP_CLIENT_SUPPORT */
612
0
}
613
614
unsigned int
615
0
coap_context_get_session_timeout(const coap_context_t *context) {
616
0
  return context->session_timeout;
617
0
}
618
619
void
620
0
coap_context_set_shutdown_no_observe(coap_context_t *context) {
621
0
#if COAP_SERVER_SUPPORT
622
0
  context->shutdown_no_send_observe = 1;
623
#else /* ! COAP_SERVER_SUPPORT */
624
  (void)context;
625
#endif /* ! COAP_SERVER_SUPPORT */
626
0
}
627
628
int
629
0
coap_context_get_coap_fd(const coap_context_t *context) {
630
0
#if COAP_EPOLL_SUPPORT
631
0
  return context->epfd;
632
#else /* ! COAP_EPOLL_SUPPORT */
633
  (void)context;
634
  return -1;
635
#endif /* ! COAP_EPOLL_SUPPORT */
636
0
}
637
638
int
639
0
coap_epoll_is_supported(void) {
640
0
#if COAP_EPOLL_SUPPORT
641
0
  return 1;
642
#else /* ! COAP_EPOLL_SUPPORT */
643
  return 0;
644
#endif /* ! COAP_EPOLL_SUPPORT */
645
0
}
646
647
int
648
0
coap_threadsafe_is_supported(void) {
649
#if COAP_THREAD_SAFE
650
  return 1;
651
#else /* ! COAP_THREAD_SAFE */
652
0
  return 0;
653
0
#endif /* ! COAP_THREAD_SAFE */
654
0
}
655
656
int
657
0
coap_ipv4_is_supported(void) {
658
0
#if COAP_IPV4_SUPPORT
659
0
  return 1;
660
#else /* ! COAP_IPV4_SUPPORT */
661
  return 0;
662
#endif /* ! COAP_IPV4_SUPPORT */
663
0
}
664
665
int
666
0
coap_ipv6_is_supported(void) {
667
0
#if COAP_IPV6_SUPPORT
668
0
  return 1;
669
#else /* ! COAP_IPV6_SUPPORT */
670
  return 0;
671
#endif /* ! COAP_IPV6_SUPPORT */
672
0
}
673
674
int
675
0
coap_client_is_supported(void) {
676
0
#if COAP_CLIENT_SUPPORT
677
0
  return 1;
678
#else /* ! COAP_CLIENT_SUPPORT */
679
  return 0;
680
#endif /* ! COAP_CLIENT_SUPPORT */
681
0
}
682
683
int
684
0
coap_server_is_supported(void) {
685
0
#if COAP_SERVER_SUPPORT
686
0
  return 1;
687
#else /* ! COAP_SERVER_SUPPORT */
688
  return 0;
689
#endif /* ! COAP_SERVER_SUPPORT */
690
0
}
691
692
int
693
0
coap_af_unix_is_supported(void) {
694
0
#if COAP_AF_UNIX_SUPPORT
695
0
  return 1;
696
#else /* ! COAP_AF_UNIX_SUPPORT */
697
  return 0;
698
#endif /* ! COAP_AF_UNIX_SUPPORT */
699
0
}
700
701
COAP_API void
702
0
coap_context_set_app_data(coap_context_t *context, void *app_data) {
703
0
  assert(context);
704
0
  coap_lock_lock(return);
705
0
  coap_context_set_app_data2_lkd(context, app_data, NULL);
706
0
  coap_lock_unlock();
707
0
}
708
709
void *
710
0
coap_context_get_app_data(const coap_context_t *context) {
711
0
  assert(context);
712
0
  return context->app_data;
713
0
}
714
715
COAP_API void *
716
coap_context_set_app_data2(coap_context_t *context, void *app_data,
717
0
                           coap_app_data_free_callback_t callback) {
718
0
  void *old_data;
719
720
0
  coap_lock_lock(return NULL);
721
0
  old_data = coap_context_set_app_data2_lkd(context, app_data, callback);
722
0
  coap_lock_unlock();
723
0
  return old_data;
724
0
}
725
726
void *
727
coap_context_set_app_data2_lkd(coap_context_t *context, void *app_data,
728
0
                               coap_app_data_free_callback_t callback) {
729
0
  void *old_data = context->app_data;
730
731
0
  context->app_data = app_data;
732
0
  context->app_cb = app_data ? callback : NULL;
733
0
  return old_data;
734
0
}
735
736
coap_context_t *
737
5.57k
coap_new_context(const coap_address_t *listen_addr) {
738
5.57k
  coap_context_t *c;
739
740
#if ! COAP_SERVER_SUPPORT
741
  (void)listen_addr;
742
#endif /* COAP_SERVER_SUPPORT */
743
744
5.57k
  if (!coap_started) {
745
0
    coap_startup();
746
0
    coap_log_warn("coap_startup() should be called before any other "
747
0
                  "coap_*() functions are called\n");
748
0
  }
749
750
5.57k
  c = coap_malloc_type(COAP_CONTEXT, sizeof(coap_context_t));
751
5.57k
  if (!c) {
752
0
    coap_log_emerg("coap_init: malloc: failed\n");
753
0
    return NULL;
754
0
  }
755
5.57k
  memset(c, 0, sizeof(coap_context_t));
756
757
5.57k
  coap_lock_lock(coap_free_type(COAP_CONTEXT, c); return NULL);
758
5.57k
#ifdef COAP_EPOLL_SUPPORT
759
5.57k
  c->epfd = epoll_create1(0);
760
5.57k
  if (c->epfd == -1) {
761
0
    coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
762
0
                 coap_socket_strerror(),
763
0
                 errno);
764
0
    goto onerror;
765
0
  }
766
5.57k
  if (c->epfd != -1) {
767
5.57k
    c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
768
5.57k
    if (c->eptimerfd == -1) {
769
0
      coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
770
0
                   coap_socket_strerror(),
771
0
                   errno);
772
0
      goto onerror;
773
5.57k
    } else {
774
5.57k
      int ret;
775
5.57k
      struct epoll_event event;
776
777
      /* Needed if running 32bit as ptr is only 32bit */
778
5.57k
      memset(&event, 0, sizeof(event));
779
5.57k
      event.events = EPOLLIN;
780
      /* We special case this event by setting to NULL */
781
5.57k
      event.data.ptr = NULL;
782
783
5.57k
      ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
784
5.57k
      if (ret == -1) {
785
0
        coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
786
0
                     "coap_new_context",
787
0
                     coap_socket_strerror(), errno);
788
0
        goto onerror;
789
0
      }
790
5.57k
    }
791
5.57k
  }
792
5.57k
#endif /* COAP_EPOLL_SUPPORT */
793
794
5.57k
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
795
5.57k
    c->dtls_context = coap_dtls_new_context(c);
796
5.57k
    if (!c->dtls_context) {
797
0
      coap_log_emerg("coap_init: no DTLS context available\n");
798
0
      goto onerror;
799
0
    }
800
5.57k
  }
801
802
  /* set default CSM values */
803
5.57k
  c->csm_timeout_ms = 1000;
804
5.57k
  c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
805
806
5.57k
#if COAP_SERVER_SUPPORT
807
5.57k
  if (listen_addr) {
808
0
    coap_endpoint_t *endpoint = coap_new_endpoint_lkd(c, listen_addr, COAP_PROTO_UDP);
809
0
    if (endpoint == NULL) {
810
0
      goto onerror;
811
0
    }
812
0
  }
813
5.57k
#endif /* COAP_SERVER_SUPPORT */
814
815
5.57k
  c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
816
817
#if defined(WITH_LWIP)
818
#if NO_SYS == 0
819
  if (sys_sem_new(&c->coap_io_timeout_sem, 0) != ERR_OK)
820
    coap_log_warn("coap_new_context: Failed to set up semaphore\n");
821
#endif /* NO_SYS == 0 */
822
#endif /* ! WITH_LWIP */
823
5.57k
  coap_lock_unlock();
824
5.57k
  return c;
825
826
0
onerror:
827
0
  coap_lock_unlock();
828
0
  coap_free_type(COAP_CONTEXT, c);
829
0
  return NULL;
830
5.57k
}
831
832
COAP_API void
833
0
coap_set_app_data(coap_context_t *context, void *app_data) {
834
0
  assert(context);
835
0
  coap_lock_lock(return);
836
0
  coap_context_set_app_data2_lkd(context, app_data, NULL);
837
0
  coap_lock_unlock();
838
0
}
839
840
void *
841
0
coap_get_app_data(const coap_context_t *ctx) {
842
0
  assert(ctx);
843
0
  return ctx->app_data;
844
0
}
845
846
COAP_API void
847
5.57k
coap_free_context(coap_context_t *context) {
848
5.57k
  if (!context)
849
0
    return;
850
5.57k
  coap_lock_lock(return);
851
5.57k
  coap_free_context_lkd(context);
852
5.57k
  coap_lock_unlock();
853
5.57k
}
854
855
void
856
5.57k
coap_free_context_lkd(coap_context_t *context) {
857
5.57k
  if (!context)
858
0
    return;
859
860
5.57k
  coap_lock_check_locked();
861
5.57k
#if COAP_SERVER_SUPPORT
862
  /* Removing a resource may cause a NON unsolicited observe to be sent */
863
5.57k
  context->context_going_away = 1;
864
5.57k
  if (context->shutdown_no_send_observe)
865
0
    context->observe_no_clear = 1;
866
5.57k
  coap_delete_all_resources(context);
867
5.57k
#endif /* COAP_SERVER_SUPPORT */
868
5.57k
#if COAP_CLIENT_SUPPORT
869
  /* Stop any attempts at reconnection */
870
5.57k
  context->reconnect_time = 0;
871
5.57k
#endif /* COAP_CLIENT_SUPPORT */
872
873
5.57k
  coap_delete_all(context->sendqueue);
874
5.57k
  context->sendqueue = NULL;
875
876
#ifdef WITH_LWIP
877
  if (context->timer_configured) {
878
    LOCK_TCPIP_CORE();
879
    sys_untimeout(coap_io_process_timeout, (void *)context);
880
    UNLOCK_TCPIP_CORE();
881
    context->timer_configured = 0;
882
  }
883
#endif /* WITH_LWIP */
884
885
5.57k
#if COAP_ASYNC_SUPPORT
886
5.57k
  coap_delete_all_async(context);
887
5.57k
#endif /* COAP_ASYNC_SUPPORT */
888
889
5.57k
#if COAP_SERVER_SUPPORT
890
5.57k
  coap_cache_entry_t *cp, *ctmp;
891
5.57k
  coap_endpoint_t *ep, *tmp;
892
893
5.57k
  HASH_ITER(hh, context->cache, cp, ctmp) {
894
0
    coap_delete_cache_entry(context, cp);
895
0
  }
896
5.57k
  if (context->cache_ignore_count) {
897
0
    coap_free_type(COAP_STRING, context->cache_ignore_options);
898
0
  }
899
900
5.57k
  LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
901
2.54k
    coap_free_endpoint_lkd(ep);
902
2.54k
  }
903
5.57k
#endif /* COAP_SERVER_SUPPORT */
904
905
5.57k
#if COAP_CLIENT_SUPPORT
906
5.57k
  coap_session_t *sp, *rtmp;
907
908
5.57k
  SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
909
2.61k
    coap_session_release_lkd(sp);
910
2.61k
  }
911
5.57k
#endif /* COAP_CLIENT_SUPPORT */
912
913
5.57k
#if COAP_OSCORE_SUPPORT
914
5.57k
  coap_delete_all_oscore(context);
915
5.57k
#endif /* COAP_OSCORE_SUPPORT */
916
917
5.57k
  if (context->dtls_context)
918
5.57k
    coap_dtls_free_context(context->dtls_context);
919
5.57k
#ifdef COAP_EPOLL_SUPPORT
920
5.57k
  if (context->eptimerfd != -1) {
921
5.57k
    int ret;
922
5.57k
    struct epoll_event event;
923
924
    /* Kernels prior to 2.6.9 expect non NULL event parameter */
925
5.57k
    ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
926
5.57k
    if (ret == -1) {
927
0
      coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
928
0
                   "coap_free_context",
929
0
                   coap_socket_strerror(), errno);
930
0
    }
931
5.57k
    close(context->eptimerfd);
932
5.57k
    context->eptimerfd = -1;
933
5.57k
  }
934
5.57k
  if (context->epfd != -1) {
935
5.57k
    close(context->epfd);
936
5.57k
    context->epfd = -1;
937
5.57k
  }
938
5.57k
#endif /* COAP_EPOLL_SUPPORT */
939
5.57k
#if COAP_SERVER_SUPPORT
940
5.57k
#if COAP_WITH_OBSERVE_PERSIST
941
5.57k
  coap_persist_cleanup(context);
942
5.57k
#endif /* COAP_WITH_OBSERVE_PERSIST */
943
5.57k
#endif /* COAP_SERVER_SUPPORT */
944
5.57k
#if COAP_PROXY_SUPPORT
945
5.57k
  coap_proxy_cleanup(context);
946
5.57k
#endif /* COAP_PROXY_SUPPORT */
947
948
5.57k
  if (context->app_cb) {
949
0
    coap_lock_callback(context->app_cb(context->app_data));
950
0
  }
951
#if defined(WITH_LWIP)
952
#if NO_SYS == 0
953
  sys_sem_free(&context->coap_io_timeout_sem);
954
#endif /* NO_SYS == 0 */
955
#endif /* ! WITH_LWIP */
956
#if COAP_THREAD_SAFE && !WITH_LWIP
957
  coap_io_process_remove_threads_lkd(context);
958
#endif /* COAP_THREAD_SAFE && !WITH_LWIP */
959
5.57k
  coap_free_type(COAP_CONTEXT, context);
960
5.57k
  coap_dump_memory_type_counts(COAP_LOG_DEBUG);
961
5.57k
}
962
963
static coap_crit_type_t
964
1.98k
coap_is_session_proxy(coap_session_t *session, coap_pdu_t *pdu) {
965
1.98k
#if COAP_SERVER_SUPPORT
966
1.98k
  coap_opt_iterator_t t_iter;
967
1.98k
  coap_opt_t *proxy_uri = NULL;
968
1.98k
  coap_opt_t *proxy_scheme = NULL;
969
970
1.98k
  if (session->proxy_session) {
971
0
    return COAP_CRIT_PROXY;
972
1.98k
  } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->unknown_resource &&
973
0
             session->context->unknown_resource->is_reverse_proxy) {
974
0
    return COAP_CRIT_PROXY;
975
1.98k
  } else if (COAP_PDU_IS_REQUEST(pdu) && session->context->proxy_uri_resource &&
976
0
             ((proxy_uri = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter)) ||
977
0
              (proxy_scheme = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &t_iter)))) {
978
0
    if (proxy_uri || proxy_scheme) {
979
0
      coap_uri_t uri;
980
981
      /* Duplicates some of the code in handle_request() */
982
0
      if (proxy_uri) {
983
0
        if (coap_split_proxy_uri(coap_opt_value(proxy_uri),
984
0
                                 coap_opt_length(proxy_uri), &uri) < 0) {
985
0
          return COAP_CRIT_PROXY;
986
0
        }
987
0
      } else {
988
0
        coap_opt_t *opt;
989
0
        coap_resource_t *resource;
990
991
0
        memset(&uri, 0, sizeof(uri));
992
0
        opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &t_iter);
993
0
        if (opt) {
994
0
          uri.host.length = coap_opt_length(opt);
995
0
          uri.host.s = coap_opt_value(opt);
996
0
        } else {
997
0
          uri.host.length = 0;
998
0
        }
999
        /* See if we are the endpoint */
1000
0
        resource = session->context->proxy_uri_resource;
1001
0
        if (uri.host.length && resource->proxy_name_count &&
1002
0
            resource->proxy_name_list) {
1003
0
          size_t i;
1004
1005
0
          if (resource->proxy_name_count == 1 &&
1006
0
              resource->proxy_name_list[0]->length == 0) {
1007
            /* If proxy_name_list[0] is zero length, then this is the endpoint */
1008
0
            i = 0;
1009
0
          } else {
1010
0
            for (i = 0; i < resource->proxy_name_count; i++) {
1011
0
              if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
1012
0
                break;
1013
0
              }
1014
0
            }
1015
0
          }
1016
0
          if (i != resource->proxy_name_count) {
1017
0
            return COAP_CRIT_NOT_PROXY;
1018
0
          }
1019
0
        }
1020
0
      }
1021
0
      return COAP_CRIT_PROXY;
1022
0
    }
1023
0
  }
1024
1.98k
  return COAP_CRIT_NOT_PROXY;
1025
#else /* ! COAP_SERVER_SUPPORT */
1026
#endif /* ! COAP_SERVER_SUPPORT */
1027
0
  (void)session;
1028
0
  (void)pdu;
1029
0
  return COAP_CRIT_NOT_PROXY;
1030
1.98k
}
1031
1032
int
1033
coap_option_check_critical(coap_session_t *session,
1034
                           coap_pdu_t *pdu,
1035
                           coap_opt_filter_t *unknown,
1036
2.50k
                           coap_crit_type_t is_proxy) {
1037
2.50k
  coap_context_t *ctx = session->context;
1038
2.50k
  coap_opt_iterator_t opt_iter;
1039
2.50k
  coap_opt_t *option;
1040
2.50k
  int ok = 1;
1041
2.50k
  coap_option_num_t last_number = -1;
1042
1043
2.50k
  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1044
1045
25.8k
  while ((option = coap_option_next(&opt_iter))) {
1046
    /* Check for explicitly reserved option RFC 5272 12.2 Table 7 */
1047
    /* Need to check reserved options */
1048
23.3k
    switch (opt_iter.number) {
1049
334
    case 0:
1050
557
    case 128:
1051
753
    case 132:
1052
949
    case 136:
1053
1.14k
    case 140:
1054
1.14k
      if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1055
1.14k
        coap_log_debug("Unknown reserved option %d\n", opt_iter.number);
1056
1.14k
        ok = 0;
1057
1058
        /* When opt_iter.number cannot be set in unknown, all of the appropriate
1059
         * slots have been used up and no more options can be tracked.
1060
         * Safe to break out of this loop as ok is already set. */
1061
1.14k
        if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1062
2
          goto overflow;
1063
2
        }
1064
1.14k
      }
1065
1.14k
      break;
1066
22.2k
    default:
1067
22.2k
      break;
1068
23.3k
    }
1069
23.3k
    if (opt_iter.number & 0x01) {
1070
      /* first check the known built-in critical options */
1071
15.8k
      switch (opt_iter.number) {
1072
0
#if COAP_Q_BLOCK_SUPPORT
1073
474
      case COAP_OPTION_Q_BLOCK1:
1074
866
      case COAP_OPTION_Q_BLOCK2:
1075
866
        if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
1076
866
          coap_log_debug("Critical option '%s' (%d) disabled - not supported\n",
1077
866
                         coap_option_string(pdu->code, opt_iter.number), opt_iter.number);
1078
866
          ok = 0;
1079
          /* When opt_iter.number cannot be set in unknown, all of the appropriate
1080
           * slots have been used up and no more options can be tracked.
1081
           * Safe to break out of this loop as ok is already set. */
1082
866
          if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1083
1
            goto overflow;
1084
1
          }
1085
866
        }
1086
865
        break;
1087
865
#endif /* COAP_Q_BLOCK_SUPPORT */
1088
865
      case COAP_OPTION_IF_MATCH:
1089
591
      case COAP_OPTION_URI_HOST:
1090
957
      case COAP_OPTION_IF_NONE_MATCH:
1091
1.18k
      case COAP_OPTION_URI_PORT:
1092
8.89k
      case COAP_OPTION_URI_PATH:
1093
9.56k
      case COAP_OPTION_URI_PATH_ABB:
1094
10.2k
      case COAP_OPTION_URI_QUERY:
1095
10.6k
      case COAP_OPTION_ACCEPT:
1096
11.3k
      case COAP_OPTION_BLOCK2:
1097
11.7k
      case COAP_OPTION_BLOCK1:
1098
12.1k
      case COAP_OPTION_PROXY_URI:
1099
12.5k
      case COAP_OPTION_PROXY_SCHEME:
1100
12.5k
        break;
1101
522
      case COAP_OPTION_OSCORE:
1102
        /* Valid critical if doing OSCORE */
1103
522
#if COAP_OSCORE_SUPPORT
1104
        /* Generally configured or has coap oscore enabled helper function */
1105
522
        if (ctx->p_osc_ctx || ctx->oscore_find_cb)
1106
0
          break;
1107
522
#endif /* COAP_OSCORE_SUPPORT */
1108
      /* Fall Through */
1109
2.47k
      default:
1110
2.47k
        if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1111
2.47k
#if COAP_SERVER_SUPPORT
1112
2.47k
          if ((opt_iter.number & 0x02) == 0) {
1113
            /* Safe to forward critical? - check if proxy pdu */
1114
2.11k
            if (is_proxy == COAP_CRIT_UNKNOWN) {
1115
81
              is_proxy = coap_is_session_proxy(session, pdu);
1116
81
            }
1117
2.11k
            if (is_proxy == COAP_CRIT_PROXY) {
1118
0
              pdu->crit_opt = 1;
1119
0
              break;
1120
0
            }
1121
2.11k
          }
1122
2.47k
#endif /* COAP_SERVER_SUPPORT */
1123
2.47k
          coap_log_debug("Critical option %u dropped\n", opt_iter.number);
1124
2.47k
          ok = 0;
1125
1126
          /* When opt_iter.number cannot be set in unknown, all of the appropriate
1127
           * slots have been used up and no more options can be tracked.
1128
           * Safe to break out of this loop as ok is already set. */
1129
2.47k
          if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1130
2
            goto overflow;
1131
2
          }
1132
2.47k
        }
1133
15.8k
      }
1134
15.8k
    }
1135
23.3k
    if (opt_iter.number & 0x02) {
1136
      /* Check for safe to forward for a proxy */
1137
15.1k
      if (is_proxy == COAP_CRIT_UNKNOWN) {
1138
1.90k
        is_proxy = coap_is_session_proxy(session, pdu);
1139
1.90k
      }
1140
15.1k
      if (is_proxy == COAP_CRIT_PROXY) {
1141
0
        switch (opt_iter.number) {
1142
0
        case COAP_OPTION_URI_HOST:
1143
0
        case COAP_OPTION_OBSERVE:
1144
0
        case COAP_OPTION_URI_PORT:
1145
0
        case COAP_OPTION_URI_PATH:
1146
0
        case COAP_OPTION_MAXAGE:
1147
0
        case COAP_OPTION_URI_QUERY:
1148
0
        case COAP_OPTION_Q_BLOCK1:
1149
0
        case COAP_OPTION_BLOCK2:
1150
0
        case COAP_OPTION_BLOCK1:
1151
0
        case COAP_OPTION_Q_BLOCK2:
1152
0
        case COAP_OPTION_PROXY_URI:
1153
0
        case COAP_OPTION_PROXY_SCHEME:
1154
0
          break;
1155
0
        default:
1156
0
          coap_log_debug("Not Safe option %u cannot be forwarded - dropped\n",
1157
0
                         opt_iter.number);
1158
0
          ok = 0;
1159
1160
          /* When opt_iter.number cannot be set in unknown, all of the appropriate
1161
           * slots have been used up and no more options can be tracked.
1162
           * Safe to break out of this loop as ok is already set. */
1163
0
          if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1164
0
            goto overflow;
1165
0
          }
1166
0
        }
1167
0
      }
1168
15.1k
    }
1169
23.3k
    if (last_number == opt_iter.number) {
1170
      /* Check for duplicated option RFC 5272 5.4.5 */
1171
19.1k
      if (!coap_option_check_repeatable(pdu, opt_iter.number)) {
1172
6.73k
        if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
1173
6.73k
          if (opt_iter.number & 0x01) {
1174
4.64k
            ok = 0;
1175
4.64k
            if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
1176
1
              goto overflow;
1177
1
            }
1178
4.64k
          } else {
1179
2.08k
            size_t opt_size = opt_iter.next_option - option;
1180
1181
            /* RFC 7252 5.4.5: ignore supernumerary elective options.
1182
             * A duplicate has delta zero, so the next delta is unchanged. */
1183
2.08k
            memmove(option, opt_iter.next_option, opt_iter.length);
1184
2.08k
            pdu->used_size -= opt_size;
1185
2.08k
            if (pdu->data)
1186
202
              pdu->data -= opt_size;
1187
2.08k
            opt_iter.next_option = option;
1188
2.08k
          }
1189
6.73k
        }
1190
6.73k
      }
1191
19.1k
    } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
1192
274
               COAP_PDU_IS_REQUEST(pdu)) {
1193
      /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
1194
231
      coap_block_b_t block;
1195
1196
231
      if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
1197
225
        if (block.m) {
1198
90
          size_t used_size = pdu->used_size;
1199
90
          unsigned char buf[4];
1200
1201
90
          coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
1202
90
          block.m = 0;
1203
90
          coap_update_option(pdu, opt_iter.number,
1204
90
                             coap_encode_var_safe(buf, sizeof(buf),
1205
90
                                                  ((block.num << 4) |
1206
90
                                                   (block.m << 3) |
1207
90
                                                   block.aszx)),
1208
90
                             buf);
1209
90
          if (used_size != pdu->used_size) {
1210
            /* Unfortunately need to restart the scan */
1211
49
            coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
1212
49
            last_number = -1;
1213
49
            continue;
1214
49
          }
1215
90
        }
1216
225
      }
1217
231
    }
1218
23.3k
    last_number = opt_iter.number;
1219
23.3k
  }
1220
2.50k
overflow:
1221
2.50k
  return ok;
1222
2.50k
}
1223
1224
COAP_API coap_mid_t
1225
266
coap_send_rst(coap_session_t *session, const coap_pdu_t *request) {
1226
266
  coap_mid_t mid;
1227
1228
266
  coap_lock_lock(return COAP_INVALID_MID);
1229
266
  mid = coap_send_rst_lkd(session, request);
1230
266
  coap_lock_unlock();
1231
266
  return mid;
1232
266
}
1233
1234
coap_mid_t
1235
1.57k
coap_send_rst_lkd(coap_session_t *session, const coap_pdu_t *request) {
1236
1.57k
  if (request->type == COAP_MESSAGE_CON || request->type == COAP_MESSAGE_NON)
1237
1.34k
    return coap_send_message_type_lkd(session, request, COAP_MESSAGE_RST);
1238
230
  return COAP_INVALID_MID;
1239
1.57k
}
1240
1241
COAP_API coap_mid_t
1242
266
coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
1243
266
  coap_mid_t mid;
1244
1245
266
  coap_lock_lock(return COAP_INVALID_MID);
1246
266
  mid = coap_send_ack_lkd(session, request);
1247
266
  coap_lock_unlock();
1248
266
  return mid;
1249
266
}
1250
1251
coap_mid_t
1252
266
coap_send_ack_lkd(coap_session_t *session, const coap_pdu_t *request) {
1253
266
  coap_pdu_t *response;
1254
266
  coap_mid_t result = COAP_INVALID_MID;
1255
1256
266
  coap_lock_check_locked();
1257
266
  if (request && request->type == COAP_MESSAGE_CON &&
1258
266
      COAP_PROTO_NOT_RELIABLE(session->proto)) {
1259
0
    response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
1260
0
    if (response)
1261
0
      result = coap_send_internal(session, response, NULL);
1262
0
  }
1263
266
  return result;
1264
266
}
1265
1266
ssize_t
1267
5.21k
coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu) {
1268
5.21k
  ssize_t bytes_written = -1;
1269
5.21k
  assert(pdu->hdr_size > 0);
1270
1271
  /* Caller handles partial writes */
1272
5.21k
  bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1273
5.21k
                  pdu->token - pdu->hdr_size,
1274
5.21k
                  pdu->used_size + pdu->hdr_size);
1275
5.21k
  coap_show_pdu(COAP_LOG_DEBUG, pdu);
1276
5.21k
  return bytes_written;
1277
5.21k
}
1278
1279
static ssize_t
1280
5.88k
coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node) {
1281
5.88k
  ssize_t bytes_written;
1282
1283
5.88k
  if (session->state == COAP_SESSION_STATE_NONE) {
1284
#if ! COAP_CLIENT_SUPPORT
1285
    return -1;
1286
#else /* COAP_CLIENT_SUPPORT */
1287
479
    if (session->type != COAP_SESSION_TYPE_CLIENT)
1288
0
      return -1;
1289
479
#endif /* COAP_CLIENT_SUPPORT */
1290
479
  }
1291
1292
5.88k
  if (pdu->type == COAP_MESSAGE_CON &&
1293
806
      (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1294
230
      coap_is_mcast(&session->addr_info.remote)) {
1295
    /* Violates RFC72522 8.1 */
1296
199
    coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
1297
199
    return -1;
1298
199
  }
1299
1300
5.69k
  if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
1301
5.21k
      (pdu->type == COAP_MESSAGE_CON &&
1302
479
       session->con_active >= COAP_NSTART(session))) {
1303
479
    return coap_session_delay_pdu(session, pdu, node);
1304
479
  }
1305
1306
5.21k
  if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
1307
4.91k
      (session->sock.flags & COAP_SOCKET_WANT_WRITE))
1308
0
    return coap_session_delay_pdu(session, pdu, node);
1309
1310
5.21k
  bytes_written = coap_session_send_pdu(session, pdu);
1311
5.21k
  if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
1312
73
      COAP_PROTO_NOT_RELIABLE(session->proto))
1313
8
    session->con_active++;
1314
1315
5.21k
  return bytes_written;
1316
5.21k
}
1317
1318
COAP_API coap_mid_t
1319
coap_send_error(coap_session_t *session,
1320
                const coap_pdu_t *request,
1321
                coap_pdu_code_t code,
1322
798
                coap_opt_filter_t *opts) {
1323
798
  coap_mid_t mid;
1324
1325
798
  coap_lock_lock(return COAP_INVALID_MID);
1326
798
  mid = coap_send_error_lkd(session, request, code, opts);
1327
798
  coap_lock_unlock();
1328
798
  return mid;
1329
798
}
1330
1331
coap_mid_t
1332
coap_send_error_lkd(coap_session_t *session,
1333
                    const coap_pdu_t *request,
1334
                    coap_pdu_code_t code,
1335
798
                    coap_opt_filter_t *opts) {
1336
798
  coap_pdu_t *response;
1337
798
  coap_mid_t result = COAP_INVALID_MID;
1338
1339
798
  assert(request);
1340
798
  assert(session);
1341
1342
798
  response = coap_new_error_response(request, code, opts);
1343
798
  if (response)
1344
798
    result = coap_send_internal(session, response, NULL);
1345
1346
798
  return result;
1347
798
}
1348
1349
COAP_API coap_mid_t
1350
coap_send_message_type(coap_session_t *session, const coap_pdu_t *request,
1351
0
                       coap_pdu_type_t type) {
1352
0
  coap_mid_t mid;
1353
1354
0
  coap_lock_lock(return COAP_INVALID_MID);
1355
0
  mid = coap_send_message_type_lkd(session, request, type);
1356
0
  coap_lock_unlock();
1357
0
  return mid;
1358
0
}
1359
1360
coap_mid_t
1361
coap_send_message_type_lkd(coap_session_t *session, const coap_pdu_t *request,
1362
1.37k
                           coap_pdu_type_t type) {
1363
1.37k
  coap_pdu_t *response;
1364
1.37k
  coap_mid_t result = COAP_INVALID_MID;
1365
1366
1.37k
  coap_lock_check_locked();
1367
1.37k
  if (request && COAP_PROTO_NOT_RELIABLE(session->proto) &&
1368
1.11k
      !(type == COAP_MESSAGE_RST && coap_is_mcast(&session->addr_info.local))) {
1369
1.11k
    response = coap_pdu_init(type, 0, request->mid, 0);
1370
1.11k
    if (response)
1371
1.11k
      result = coap_send_internal(session, response, NULL);
1372
1.11k
  }
1373
1.37k
  return result;
1374
1.37k
}
1375
1376
/**
1377
 * Calculates the initial timeout based on the session CoAP transmission
1378
 * parameters 'ack_timeout', 'ack_random_factor', and COAP_TICKS_PER_SECOND.
1379
 * The calculation requires 'ack_timeout' and 'ack_random_factor' to be in
1380
 * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r
1381
 * is interpreted as the fractional part of a Q0.MAX_BITS random value.
1382
 *
1383
 * @param session session timeout is associated with
1384
 * @param r  random value as fractional part of a Q0.MAX_BITS fixed point
1385
 *           value
1386
 * @return   COAP_TICKS_PER_SECOND * 'ack_timeout' *
1387
 *           (1 + ('ack_random_factor' - 1) * r)
1388
 */
1389
unsigned int
1390
8
coap_calc_timeout(coap_session_t *session, unsigned char r) {
1391
8
  unsigned int result;
1392
1393
  /* The integer 1.0 as a Qx.FRAC_BITS */
1394
8
#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
1395
1396
  /* rounds val up and right shifts by frac positions */
1397
24
#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
1398
1399
  /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
1400
   * make the result a rounded Qx.FRAC_BITS */
1401
8
  result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
1402
1403
  /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
1404
   * make the result a rounded Qx.FRAC_BITS */
1405
8
  result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
1406
1407
  /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
1408
   * (yields a Qx.FRAC_BITS) and shift to get an integer */
1409
8
  return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
1410
1411
8
#undef FP1
1412
8
#undef SHR_FP
1413
8
}
1414
1415
coap_mid_t
1416
coap_wait_ack(coap_context_t *context, coap_session_t *session,
1417
1.81k
              coap_queue_t *node) {
1418
1.81k
  coap_tick_t now;
1419
1420
1.81k
  node->session = coap_session_reference_lkd(session);
1421
1422
  /* Set timer for pdu retransmission. If this is the first element in
1423
  * the retransmission queue, the base time is set to the current
1424
  * time and the retransmission time is node->timeout. If there is
1425
  * already an entry in the sendqueue, we must check if this node is
1426
  * to be retransmitted earlier. Therefore, node->timeout is first
1427
  * normalized to the base time and then inserted into the queue with
1428
  * an adjusted relative time.
1429
  */
1430
1.81k
  coap_ticks(&now);
1431
1.81k
  if (context->sendqueue == NULL) {
1432
1.81k
    node->t = node->timeout << node->retransmit_cnt;
1433
1.81k
    context->sendqueue_basetime = now;
1434
1.81k
  } else {
1435
    /* make node->t relative to context->sendqueue_basetime */
1436
0
    node->t = (now - context->sendqueue_basetime) +
1437
0
              (node->timeout << node->retransmit_cnt);
1438
0
  }
1439
1.81k
  coap_address_copy(&node->remote, &session->addr_info.remote);
1440
1441
1.81k
  coap_insert_node(&context->sendqueue, node);
1442
1443
1.81k
  coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
1444
1.81k
                 coap_session_str(node->session), node->id,
1445
1.81k
                 (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
1446
1.81k
                            COAP_TICKS_PER_SECOND));
1447
1448
1.81k
  coap_update_io_timer(context, node->t);
1449
1450
1.81k
  return node->id;
1451
1.81k
}
1452
1453
#if COAP_CLIENT_SUPPORT
1454
/*
1455
 * Sent out a test PDU for Extended Token
1456
 */
1457
static coap_mid_t
1458
0
coap_send_test_extended_token(coap_session_t *session) {
1459
0
  coap_pdu_t *pdu;
1460
0
  coap_mid_t mid = COAP_INVALID_MID;
1461
0
  size_t i;
1462
0
  coap_binary_t *token;
1463
0
  coap_lg_crcv_t *lg_crcv;
1464
1465
0
  coap_log_debug("Testing for Extended Token support\n");
1466
  /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
1467
0
  pdu = coap_pdu_init(COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET,
1468
0
                      coap_new_message_id_lkd(session),
1469
0
                      coap_session_max_pdu_size_lkd(session));
1470
0
  if (!pdu)
1471
0
    return COAP_INVALID_MID;
1472
1473
0
  token = coap_new_binary(session->max_token_size);
1474
0
  if (token == NULL) {
1475
0
    coap_delete_pdu_lkd(pdu);
1476
0
    return COAP_INVALID_MID;
1477
0
  }
1478
0
  for (i = 0; i < session->max_token_size; i++) {
1479
0
    token->s[i] = (uint8_t)(i + 1);
1480
0
  }
1481
0
  coap_add_token(pdu, session->max_token_size, token->s);
1482
0
  coap_delete_binary(token);
1483
1484
0
  coap_delete_bin_const(session->last_token);
1485
0
  session->last_token = coap_new_bin_const(pdu->actual_token.s,
1486
0
                                           pdu->actual_token.length);
1487
1488
0
  coap_insert_option(pdu, COAP_OPTION_IF_NONE_MATCH, 0, NULL);
1489
1490
0
  session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
1491
1492
  /* Need to track in case OSCORE / Echo etc. comes back after non-piggy-backed ACK */
1493
0
  lg_crcv = coap_block_new_lg_crcv(session, pdu, NULL);
1494
0
  if (lg_crcv) {
1495
0
    LL_PREPEND(session->lg_crcv, lg_crcv);
1496
0
  }
1497
0
  mid = coap_send_internal(session, pdu, NULL);
1498
0
  if (mid == COAP_INVALID_MID)
1499
0
    return COAP_INVALID_MID;
1500
0
  session->remote_test_mid = mid;
1501
0
  return mid;
1502
0
}
1503
#endif /* COAP_CLIENT_SUPPORT */
1504
1505
/*
1506
 * Return:  0  Something failed
1507
 *          1  Success
1508
 */
1509
int
1510
53
coap_client_delay_first(coap_session_t *session) {
1511
53
#if COAP_CLIENT_SUPPORT
1512
53
  if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
1513
0
    int timeout_ms = 5000;
1514
0
    coap_session_state_t current_state = session->state;
1515
1516
0
    if (session->delay_recursive) {
1517
0
      return 0;
1518
0
    } else {
1519
0
      session->delay_recursive = 1;
1520
0
    }
1521
    /*
1522
     * Need to wait for first request to get out and response back before
1523
     * continuing.. Response handler has to clear doing_first if not an error.
1524
     */
1525
0
    coap_session_reference_lkd(session);
1526
0
    while (session->doing_first != 0) {
1527
0
      int result = coap_io_process_lkd(session->context, 1000);
1528
1529
0
      if (result < 0) {
1530
0
        coap_reset_doing_first(session);
1531
0
        session->delay_recursive = 0;
1532
0
        coap_session_release_lkd(session);
1533
0
        return 0;
1534
0
      }
1535
1536
      /* coap_io_process_lkd() may have updated session state */
1537
0
      if (session->state == COAP_SESSION_STATE_CSM &&
1538
0
          current_state != COAP_SESSION_STATE_CSM) {
1539
        /* Update timeout and restart the clock for CSM timeout */
1540
0
        current_state = COAP_SESSION_STATE_CSM;
1541
0
        timeout_ms = session->context->csm_timeout_ms;
1542
0
        result = 0;
1543
0
      }
1544
1545
0
      if (result < timeout_ms) {
1546
0
        timeout_ms -= result;
1547
0
      } else {
1548
0
        if (session->doing_first == 1) {
1549
          /* Timeout failure of some sort with first request */
1550
0
          if (session->state == COAP_SESSION_STATE_CSM) {
1551
0
            coap_log_debug("** %s: timeout waiting for CSM response\n",
1552
0
                           coap_session_str(session));
1553
0
            session->csm_not_seen = 1;
1554
0
          } else {
1555
0
            coap_log_debug("** %s: timeout waiting for first response\n",
1556
0
                           coap_session_str(session));
1557
0
          }
1558
0
          coap_reset_doing_first(session);
1559
0
          coap_session_connected(session);
1560
0
        }
1561
0
      }
1562
0
    }
1563
0
    session->delay_recursive = 0;
1564
0
    coap_session_release_lkd(session);
1565
0
  }
1566
#else /* ! COAP_CLIENT_SUPPORT */
1567
  (void)session;
1568
#endif /* ! COAP_CLIENT_SUPPORT */
1569
53
  return 1;
1570
53
}
1571
1572
/*
1573
 * return  0 Invalid
1574
 *         1 Valid
1575
 */
1576
int
1577
6.19k
coap_check_code_class(coap_session_t *session, coap_pdu_t *pdu) {
1578
1579
  /* Check validity of sending code */
1580
6.19k
  switch (COAP_RESPONSE_CLASS(pdu->code)) {
1581
1.15k
  case 0: /* Empty or request */
1582
4.10k
  case 2: /* Success */
1583
4.17k
  case 3: /* Reserved for future use */
1584
4.22k
  case 4: /* Client error */
1585
4.31k
  case 5: /* Server error */
1586
4.31k
    break;
1587
1.86k
  case 7: /* Reliable signalling */
1588
1.86k
    if (COAP_PROTO_RELIABLE(session->proto))
1589
1.80k
      break;
1590
  /* Not valid if UDP */
1591
  /* Fall through */
1592
68
  case 1: /* Invalid */
1593
71
  case 6: /* Invalid */
1594
71
  default:
1595
71
    return 0;
1596
6.19k
  }
1597
6.12k
  return 1;
1598
6.19k
}
1599
1600
#if COAP_CLIENT_SUPPORT
1601
/*
1602
 * If type is CON and protocol is not reliable, there is no need to set up
1603
 * lg_crcv if it can be built up based on sent PDU if there is a
1604
 * (Q-)Block2 in the response.  However, still need it for Observe, Oscore and
1605
 * (Q-)Block1.
1606
 */
1607
static int
1608
0
coap_check_send_need_lg_crcv(coap_session_t *session, coap_pdu_t *pdu) {
1609
0
  coap_opt_iterator_t opt_iter;
1610
1611
0
  if (!COAP_PDU_IS_REQUEST(pdu))
1612
0
    return 0;
1613
1614
0
  if (
1615
0
#if COAP_OSCORE_SUPPORT
1616
0
      session->oscore_encryption ||
1617
0
#endif /* COAP_OSCORE_SUPPORT */
1618
0
      pdu->type == COAP_MESSAGE_NON ||
1619
0
      COAP_PROTO_RELIABLE(session->proto) ||
1620
0
      coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) ||
1621
0
#if COAP_Q_BLOCK_SUPPORT
1622
0
      coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter) ||
1623
0
#endif /* COAP_Q_BLOCK_SUPPORT */
1624
0
      coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter)) {
1625
0
    return 1;
1626
0
  }
1627
0
  return 0;
1628
0
}
1629
#endif /* COAP_CLIENT_SUPPORT */
1630
1631
COAP_API coap_mid_t
1632
0
coap_send(coap_session_t *session, coap_pdu_t *pdu) {
1633
0
  coap_mid_t mid;
1634
1635
0
  coap_lock_lock(return COAP_INVALID_MID);
1636
0
  mid = coap_send_lkd(session, pdu);
1637
0
  coap_lock_unlock();
1638
0
  return mid;
1639
0
}
1640
1641
coap_mid_t
1642
9
coap_send_lkd(coap_session_t *session, coap_pdu_t *pdu) {
1643
9
  coap_mid_t mid = COAP_INVALID_MID;
1644
9
#if COAP_CLIENT_SUPPORT
1645
9
  coap_lg_crcv_t *lg_crcv = NULL;
1646
9
  coap_opt_iterator_t opt_iter;
1647
9
  coap_block_b_t block;
1648
9
  int observe_action = -1;
1649
9
  int have_block1 = 0;
1650
9
  coap_opt_t *opt;
1651
9
#endif /* COAP_CLIENT_SUPPORT */
1652
1653
9
  assert(pdu);
1654
1655
9
  coap_lock_check_locked();
1656
1657
  /* Check validity of sending code */
1658
9
  if (!coap_check_code_class(session, pdu)) {
1659
0
    coap_log_err("coap_send: Invalid PDU code (%d.%02d)\n",
1660
0
                 COAP_RESPONSE_CLASS(pdu->code),
1661
0
                 pdu->code & 0x1f);
1662
0
    goto error;
1663
0
  }
1664
9
  pdu->session = session;
1665
9
#if COAP_CLIENT_SUPPORT
1666
9
  if (session->type == COAP_SESSION_TYPE_CLIENT &&
1667
9
      !coap_netif_available(session) && !session->session_failed) {
1668
0
    coap_log_debug("coap_send: Socket closed\n");
1669
0
    goto error;
1670
0
  }
1671
1672
9
  if (session->doing_first) {
1673
0
    unsigned int depth = 0;
1674
0
    coap_pdu_t *q_pdu;
1675
1676
0
    LL_FOREACH(session->doing_first_pdu, q_pdu)
1677
0
    depth++;
1678
0
    if (depth >= COAP_DOING_FIRST_MAX_QUEUE) {
1679
0
      coap_log_warn("** %s: mid=0x%04x: doing_first queue full (%u) - dropped\n",
1680
0
                    coap_session_str(session), pdu->mid, depth);
1681
0
      goto error;
1682
0
    }
1683
0
    LL_APPEND(session->doing_first_pdu, pdu);
1684
0
    coap_show_pdu(COAP_LOG_DEBUG, pdu);
1685
0
    coap_log_debug("** %s: mid=0x%04x: queued\n",
1686
0
                   coap_session_str(session), pdu->mid);
1687
0
    return  pdu->mid;
1688
0
  }
1689
1690
  /* Indicate support for Extended Tokens if appropriate */
1691
9
  if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1692
9
      session->max_token_size > COAP_TOKEN_DEFAULT_MAX &&
1693
0
      session->type == COAP_SESSION_TYPE_CLIENT &&
1694
0
      COAP_PDU_IS_REQUEST(pdu)) {
1695
0
    if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1696
      /*
1697
       * When the pass / fail response for Extended Token is received, this PDU
1698
       * will get transmitted.
1699
       */
1700
0
      if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1701
0
        goto error;
1702
0
      }
1703
0
    }
1704
    /*
1705
     * For reliable protocols, this will get cleared after CSM exchanged
1706
     * in coap_session_connected() where Token size support is indicated in the CSM.
1707
     */
1708
0
    session->doing_first = 1;
1709
0
    coap_ticks(&session->doing_first_timeout);
1710
0
    LL_PREPEND(session->doing_first_pdu, pdu);
1711
0
    if (session->proto != COAP_PROTO_UDP) {
1712
      /* In case the next handshake / CSM is already in */
1713
0
      coap_io_process_lkd(session->context, COAP_IO_NO_WAIT);
1714
0
    }
1715
    /*
1716
     * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1717
     * will get called again.
1718
     */
1719
0
    coap_show_pdu(COAP_LOG_DEBUG, pdu);
1720
0
    coap_log_debug("** %s: mid=0x%04x: queued\n",
1721
0
                   coap_session_str(session), pdu->mid);
1722
0
    return pdu->mid;
1723
0
  }
1724
9
#if COAP_Q_BLOCK_SUPPORT
1725
  /* Indicate support for Q-Block if appropriate */
1726
9
  if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1727
0
      session->type == COAP_SESSION_TYPE_CLIENT &&
1728
0
      COAP_PDU_IS_REQUEST(pdu)) {
1729
0
    if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1730
0
      goto error;
1731
0
    }
1732
0
    session->doing_first = 1;
1733
0
    coap_ticks(&session->doing_first_timeout);
1734
0
    LL_PREPEND(session->doing_first_pdu, pdu);
1735
0
    if (session->proto != COAP_PROTO_UDP) {
1736
      /* In case the next handshake / CSM is already in */
1737
0
      coap_io_process_lkd(session->context, COAP_IO_NO_WAIT);
1738
0
    }
1739
    /*
1740
     * Once Extended Token support size is determined, coap_send_lkd(session, pdu)
1741
     * will get called again.
1742
     */
1743
0
    coap_show_pdu(COAP_LOG_DEBUG, pdu);
1744
0
    coap_log_debug("** %s: mid=0x%04x: queued\n",
1745
0
                   coap_session_str(session), pdu->mid);
1746
0
    return pdu->mid;
1747
0
  }
1748
9
#endif /* COAP_Q_BLOCK_SUPPORT */
1749
1750
  /*
1751
   * Check validity of token length
1752
   */
1753
9
  if (COAP_PDU_IS_REQUEST(pdu) &&
1754
9
      pdu->actual_token.length > session->max_token_size) {
1755
0
    coap_log_warn("coap_send: PDU dropped as token too long (%" PRIuS " > %" PRIu32 ")\n",
1756
0
                  pdu->actual_token.length, session->max_token_size);
1757
0
    goto error;
1758
0
  }
1759
1760
  /* A lot of the reliable code assumes type is CON */
1761
9
  if (COAP_PROTO_RELIABLE(session->proto) && pdu->type != COAP_MESSAGE_CON)
1762
0
    pdu->type = COAP_MESSAGE_CON;
1763
1764
9
#if COAP_OSCORE_SUPPORT
1765
9
  if (session->oscore_encryption) {
1766
0
    if (session->recipient_ctx->initial_state == 1 &&
1767
0
        !session->recipient_ctx->silent_server) {
1768
      /*
1769
       * Not sure if remote supports OSCORE, or is going to send us a
1770
       * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1771
       * is OK. Continue sending current pdu to test things.
1772
       *
1773
       * Record when we started waiting so coap_io_prepare_io_lkd() can time
1774
       * out (same 5s window as Extended Token / Q-Block) and call
1775
       * coap_reset_doing_first(). Without doing_first_timeout set, UDP clients
1776
       * could stall forever if no response arrives (e.g. observe resubscribe
1777
       * while recipient_ctx->initial_state is still 1).
1778
       */
1779
0
      session->doing_first = 1;
1780
0
      coap_ticks(&session->doing_first_timeout);
1781
0
    }
1782
    /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1783
0
    if (COAP_PDU_IS_REQUEST(pdu) && !coap_rebuild_pdu_for_proxy(pdu)) {
1784
0
      goto error;
1785
0
    }
1786
0
  }
1787
9
#endif /* COAP_OSCORE_SUPPORT */
1788
1789
9
  if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1790
9
    return coap_send_internal(session, pdu, NULL);
1791
9
  }
1792
1793
0
  if (session->no_path_abbrev) {
1794
0
    opt = coap_check_option(pdu, COAP_OPTION_URI_PATH_ABB, &opt_iter);
1795
0
    if (opt) {
1796
      /* Server cannot handle Uri-Path-Abbrev */
1797
0
      coap_pdu_t *new;
1798
0
      size_t data_len;
1799
0
      const uint8_t *data;
1800
1801
0
      new = coap_pdu_duplicate_lkd(pdu, session, pdu->actual_token.length,
1802
0
                                   pdu->actual_token.s, NULL, COAP_BOOL_TRUE);
1803
0
      if (new) {
1804
0
        if (coap_get_data(pdu, &data_len, &data)) {
1805
0
          coap_add_data(pdu, data_len, data);
1806
0
        }
1807
0
        coap_log_debug("*  Retransmitting PDU with Uri-Path-Abbrev replaced (3)\n");
1808
0
        coap_delete_pdu_lkd(pdu);
1809
0
        pdu = new;
1810
0
      }
1811
0
    }
1812
0
  }
1813
1814
0
  if (COAP_PDU_IS_REQUEST(pdu)) {
1815
0
    uint8_t buf[4];
1816
1817
0
    opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1818
1819
0
    if (opt) {
1820
0
      observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1821
0
                                             coap_opt_length(opt));
1822
0
    }
1823
1824
0
    if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1825
0
        (block.m == 1 || block.bert == 1)) {
1826
0
      have_block1 = 1;
1827
0
    }
1828
0
#if COAP_Q_BLOCK_SUPPORT
1829
0
    if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1830
0
        (block.m == 1 || block.bert == 1)) {
1831
0
      if (have_block1) {
1832
0
        coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1833
0
        coap_remove_option(pdu, COAP_OPTION_BLOCK1);
1834
0
      }
1835
0
      have_block1 = 1;
1836
0
    }
1837
0
#endif /* COAP_Q_BLOCK_SUPPORT */
1838
0
    if (observe_action != COAP_OBSERVE_CANCEL) {
1839
      /* Warn about reuse of tokens */
1840
0
      if (session->last_token &&
1841
0
          coap_binary_equal(&pdu->actual_token, session->last_token)) {
1842
0
        if (coap_get_log_level() >= COAP_LOG_DEBUG) {
1843
0
          char scratch[24];
1844
0
          size_t size;
1845
0
          size_t i;
1846
1847
0
          scratch[0] = '\000';
1848
0
          for (i = 0; i < pdu->actual_token.length; i++) {
1849
0
            size = strlen(scratch);
1850
0
            snprintf(&scratch[size], sizeof(scratch)-size,
1851
0
                     "%02x", pdu->actual_token.s[i]);
1852
0
          }
1853
0
          coap_log_debug("Token {%s} reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n",
1854
0
                         scratch);
1855
0
        }
1856
0
      }
1857
0
      coap_delete_bin_const(session->last_token);
1858
0
      session->last_token = coap_new_bin_const(pdu->actual_token.s,
1859
0
                                               pdu->actual_token.length);
1860
0
    } else {
1861
      /* observe_action == COAP_OBSERVE_CANCEL */
1862
0
      coap_binary_t tmp;
1863
0
      int ret;
1864
1865
0
      coap_log_debug("coap_send: Using coap_cancel_observe() to do OBSERVE cancellation\n");
1866
      /* Unfortunately need to change the ptr type to be r/w */
1867
0
      memcpy(&tmp.s, &pdu->actual_token.s, sizeof(tmp.s));
1868
0
      tmp.length = pdu->actual_token.length;
1869
0
      ret = coap_cancel_observe_lkd(session, &tmp, pdu->type);
1870
0
      if (ret == 1) {
1871
        /* Observe Cancel successfully sent */
1872
0
        coap_delete_pdu_lkd(pdu);
1873
0
        return ret;
1874
0
      }
1875
      /* Some mismatch somewhere - continue to send original packet */
1876
0
    }
1877
0
    if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1878
0
        (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1879
0
        pdu->code != COAP_REQUEST_CODE_DELETE)
1880
0
      coap_insert_option(pdu,
1881
0
                         COAP_OPTION_RTAG,
1882
0
                         coap_encode_var_safe(buf, sizeof(buf),
1883
0
                                              ++session->tx_rtag),
1884
0
                         buf);
1885
0
  } else {
1886
0
    memset(&block, 0, sizeof(block));
1887
0
  }
1888
1889
0
#if COAP_Q_BLOCK_SUPPORT
1890
0
  if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1891
0
#endif /* COAP_Q_BLOCK_SUPPORT */
1892
0
  {
1893
    /* Need to check if we need to reset Q-Block to Block */
1894
0
    uint8_t buf[4];
1895
1896
0
    if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1897
0
      coap_remove_option(pdu, COAP_OPTION_Q_BLOCK2);
1898
0
      coap_insert_option(pdu, COAP_OPTION_BLOCK2,
1899
0
                         coap_encode_var_safe(buf, sizeof(buf),
1900
0
                                              (block.num << 4) | (0 << 3) | block.szx),
1901
0
                         buf);
1902
0
      coap_log_debug("Replaced option Q-Block2 with Block2\n");
1903
      /* Need to update associated lg_xmit */
1904
0
      coap_lg_xmit_t *lg_xmit;
1905
1906
0
      LL_FOREACH(session->lg_xmit, lg_xmit) {
1907
0
        if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1908
0
            lg_xmit->b.b1.app_token &&
1909
0
            coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1910
          /* Update the skeletal PDU with the block1 option */
1911
0
          coap_remove_option(lg_xmit->sent_pdu, COAP_OPTION_Q_BLOCK2);
1912
0
          coap_update_option(lg_xmit->sent_pdu, COAP_OPTION_BLOCK2,
1913
0
                             coap_encode_var_safe(buf, sizeof(buf),
1914
0
                                                  (block.num << 4) | (0 << 3) | block.szx),
1915
0
                             buf);
1916
0
          break;
1917
0
        }
1918
0
      }
1919
0
    }
1920
0
    if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1921
0
      coap_remove_option(pdu, COAP_OPTION_Q_BLOCK1);
1922
0
      coap_insert_option(pdu, COAP_OPTION_BLOCK1,
1923
0
                         coap_encode_var_safe(buf, sizeof(buf),
1924
0
                                              (block.num << 4) | (block.m << 3) | block.szx),
1925
0
                         buf);
1926
0
      coap_log_debug("Replaced option Q-Block1 with Block1\n");
1927
      /* Need to update associated lg_xmit */
1928
0
      coap_lg_xmit_t *lg_xmit;
1929
1930
0
      LL_FOREACH(session->lg_xmit, lg_xmit) {
1931
0
        if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1932
0
            lg_xmit->b.b1.app_token &&
1933
0
            coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1934
          /* Update the skeletal PDU with the block1 option */
1935
0
          coap_remove_option(lg_xmit->sent_pdu, COAP_OPTION_Q_BLOCK1);
1936
0
          coap_update_option(lg_xmit->sent_pdu, COAP_OPTION_BLOCK1,
1937
0
                             coap_encode_var_safe(buf, sizeof(buf),
1938
0
                                                  (block.num << 4) |
1939
0
                                                  (block.m << 3) |
1940
0
                                                  block.szx),
1941
0
                             buf);
1942
          /* Update as this is a Request */
1943
0
          lg_xmit->option = COAP_OPTION_BLOCK1;
1944
0
          break;
1945
0
        }
1946
0
      }
1947
0
    }
1948
0
  }
1949
1950
0
#if COAP_Q_BLOCK_SUPPORT
1951
0
  if (COAP_PDU_IS_REQUEST(pdu) &&
1952
0
      coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1953
0
    if (block.num == 0 && block.m == 0) {
1954
0
      uint8_t buf[4];
1955
1956
      /* M needs to be set as asking for all the blocks */
1957
0
      coap_update_option(pdu, COAP_OPTION_Q_BLOCK2,
1958
0
                         coap_encode_var_safe(buf, sizeof(buf),
1959
0
                                              (0 << 4) | (1 << 3) | block.szx),
1960
0
                         buf);
1961
0
    }
1962
0
  }
1963
0
#endif /* COAP_Q_BLOCK_SUPPORT */
1964
1965
  /*
1966
   * If type is CON and protocol is not reliable, there is no need to set up
1967
   * lg_crcv here as it can be built up based on sent PDU if there is a
1968
   * (Q-)Block2 in the response.  However, still need it for Observe, Oscore and
1969
   * (Q-)Block1.
1970
   */
1971
0
  if (coap_check_send_need_lg_crcv(session, pdu)) {
1972
0
    coap_lg_xmit_t *lg_xmit = NULL;
1973
1974
0
    if (!session->lg_xmit && have_block1) {
1975
0
      coap_log_debug("PDU presented by app\n");
1976
0
      coap_show_pdu(COAP_LOG_DEBUG, pdu);
1977
0
    }
1978
    /* See if this token is already in use for large body responses */
1979
0
    LL_FOREACH(session->lg_crcv, lg_crcv) {
1980
0
      if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1981
        /* Need to terminate and clean up previous response setup */
1982
0
        LL_DELETE(session->lg_crcv, lg_crcv);
1983
0
        coap_block_delete_lg_crcv(session, lg_crcv);
1984
0
        break;
1985
0
      }
1986
0
    }
1987
1988
0
    if (have_block1 && session->lg_xmit) {
1989
0
      LL_FOREACH(session->lg_xmit, lg_xmit) {
1990
0
        if (COAP_PDU_IS_REQUEST(lg_xmit->sent_pdu) &&
1991
0
            lg_xmit->b.b1.app_token &&
1992
0
            coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1993
0
          break;
1994
0
        }
1995
0
      }
1996
0
    }
1997
0
    lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1998
0
    if (lg_crcv == NULL) {
1999
0
      goto error;
2000
0
    }
2001
0
    if (lg_xmit) {
2002
      /* Need to update the token as set up in the session->lg_xmit */
2003
0
      lg_xmit->b.b1.state_token = lg_crcv->state_token;
2004
0
    }
2005
0
  }
2006
0
  if (session->sock.flags & COAP_SOCKET_MULTICAST)
2007
0
    coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
2008
2009
0
#if COAP_Q_BLOCK_SUPPORT
2010
  /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
2011
0
  if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
2012
0
    mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
2013
0
  } else
2014
0
#endif /* COAP_Q_BLOCK_SUPPORT */
2015
0
    mid = coap_send_internal(session, pdu, NULL);
2016
#else /* !COAP_CLIENT_SUPPORT */
2017
  mid = coap_send_internal(session, pdu, NULL);
2018
#endif /* !COAP_CLIENT_SUPPORT */
2019
0
#if COAP_CLIENT_SUPPORT
2020
0
  if (lg_crcv) {
2021
0
    if (mid != COAP_INVALID_MID) {
2022
0
      LL_PREPEND(session->lg_crcv, lg_crcv);
2023
0
    } else {
2024
0
      coap_block_delete_lg_crcv(session, lg_crcv);
2025
0
    }
2026
0
  }
2027
0
#endif /* COAP_CLIENT_SUPPORT */
2028
0
  return mid;
2029
2030
0
error:
2031
0
  coap_delete_pdu_lkd(pdu);
2032
0
  return COAP_INVALID_MID;
2033
0
}
2034
2035
static int
2036
0
prepend_508_ip(coap_session_t *session, coap_pdu_t *pdu) {
2037
0
  char addr_str[INET6_ADDRSTRLEN + 8 + 1];
2038
0
  coap_opt_t *opt;
2039
0
  coap_opt_iterator_t opt_iter;
2040
0
  size_t hop_limit;
2041
2042
0
  addr_str[sizeof(addr_str)-1] = '\000';
2043
0
  if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
2044
0
                      sizeof(addr_str) - 1)) {
2045
0
    char *cp;
2046
0
    size_t len;
2047
2048
0
    if (addr_str[0] == '[') {
2049
0
      cp = strchr(addr_str, ']');
2050
0
      if (cp)
2051
0
        *cp = '\000';
2052
0
      if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
2053
        /* IPv4 embedded into IPv6 */
2054
0
        cp = &addr_str[8];
2055
0
      } else {
2056
0
        cp = &addr_str[1];
2057
0
      }
2058
0
    } else {
2059
0
      cp = strchr(addr_str, ':');
2060
0
      if (cp)
2061
0
        *cp = '\000';
2062
0
      cp = addr_str;
2063
0
    }
2064
0
    len = strlen(cp);
2065
2066
    /* See if Hop Limit option is being used in return path */
2067
0
    opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2068
0
    if (opt) {
2069
0
      uint8_t buf[4];
2070
2071
0
      hop_limit =
2072
0
          coap_decode_var_bytes(coap_opt_value(opt), coap_opt_length(opt));
2073
0
      if (hop_limit == 1) {
2074
0
        size_t data_len;
2075
0
        const uint8_t *data;
2076
2077
0
        if (!coap_get_data(pdu, &data_len, &data))
2078
0
          data = (const uint8_t *)"";
2079
0
        coap_log_warn("Proxy loop detected '%.*s'\n",
2080
0
                      (int)data_len, (const char *)data);
2081
0
        coap_delete_pdu_lkd(pdu);
2082
0
        return 0;
2083
0
      } else if (hop_limit < 1 || hop_limit > 255) {
2084
        /* Something is bad - need to drop this pdu (TODO or delete option) */
2085
0
        coap_log_warn("Proxy return has bad hop limit count '%" PRIuS "'\n",
2086
0
                      hop_limit);
2087
0
        coap_delete_pdu_lkd(pdu);
2088
0
        return 0;
2089
0
      }
2090
0
      hop_limit--;
2091
0
      coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
2092
0
                         coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2093
0
                         buf);
2094
0
    }
2095
2096
    /* Need to check that we are not seeing this proxy in the return loop */
2097
0
    if (pdu->data && opt == NULL) {
2098
0
      char *a_match;
2099
0
      size_t data_len;
2100
2101
0
      if (pdu->used_size + 1 > pdu->max_size) {
2102
        /* No space */
2103
0
        coap_delete_pdu_lkd(pdu);
2104
0
        return 0;
2105
0
      }
2106
0
      if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
2107
        /* Internal error */
2108
0
        coap_delete_pdu_lkd(pdu);
2109
0
        return 0;
2110
0
      }
2111
0
      data_len = pdu->used_size - (pdu->data - pdu->token);
2112
0
      pdu->data[data_len] = '\000';
2113
0
      a_match = strstr((char *)pdu->data, cp);
2114
0
      if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
2115
0
          ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
2116
0
           a_match[len] == ' ')) {
2117
0
        coap_log_warn("Proxy loop detected '%s'\n",
2118
0
                      (char *)pdu->data);
2119
0
        coap_delete_pdu_lkd(pdu);
2120
0
        return 0;
2121
0
      }
2122
0
    }
2123
0
    if (pdu->used_size + len + 1 <= pdu->max_size) {
2124
0
      size_t old_size = pdu->used_size;
2125
0
      if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
2126
0
        if (pdu->data == NULL) {
2127
          /*
2128
           * Set Hop Limit to max for return path.  If this libcoap is in
2129
           * a proxy loop path, it will always decrement hop limit in code
2130
           * above and hence timeout / drop the response as appropriate
2131
           */
2132
0
          hop_limit = 255;
2133
0
          coap_insert_option(pdu, COAP_OPTION_HOP_LIMIT, 1,
2134
0
                             (uint8_t *)&hop_limit);
2135
0
          coap_add_data(pdu, len, (uint8_t *)cp);
2136
0
        } else {
2137
          /* prepend with space separator, leaving hop limit "as is" */
2138
0
          memmove(pdu->data + len + 1, pdu->data,
2139
0
                  old_size - (pdu->data - pdu->token));
2140
0
          memcpy(pdu->data, cp, len);
2141
0
          pdu->data[len] = ' ';
2142
0
          pdu->used_size += len + 1;
2143
0
        }
2144
0
      }
2145
0
    }
2146
0
  }
2147
0
  return 1;
2148
0
}
2149
2150
coap_mid_t
2151
5.88k
coap_send_internal(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *request_pdu) {
2152
5.88k
  uint8_t r;
2153
5.88k
  ssize_t bytes_written;
2154
2155
#if ! COAP_SERVER_SUPPORT
2156
  (void)request_pdu;
2157
#endif /* COAP_SERVER_SUPPORT */
2158
5.88k
  pdu->session = session;
2159
5.88k
#if COAP_CLIENT_SUPPORT
2160
5.88k
  if (session->session_failed) {
2161
0
    coap_session_reconnect(session);
2162
0
    if (session->session_failed)
2163
0
      goto error;
2164
0
  }
2165
5.88k
#endif /* COAP_CLIENT_SUPPORT */
2166
5.88k
  if (pdu->type == COAP_MESSAGE_NON && session->rl_ticks_per_packet) {
2167
0
    coap_tick_t now;
2168
2169
0
    if (!session->is_rate_limiting) {
2170
0
      coap_ticks(&now);
2171
0
#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
2172
0
      if (now - session->last_tx < session->rl_ticks_per_packet) {
2173
0
        uint32_t rem = (uint32_t)(session->rl_ticks_per_packet -
2174
0
                                  (now - session->last_tx)) * 1000 / COAP_TICKS_PER_SECOND;
2175
0
        coap_log_debug("** %s: mid 0x%04x: delaying transmission (%" PRIu32 ".%03" PRIu32 "s)\n",
2176
0
                       coap_session_str(session), pdu->mid, rem / 1000, rem %1000);
2177
0
        coap_show_pdu(COAP_LOG_DEBUG, pdu);
2178
0
      }
2179
0
#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
2180
0
      while (1) {
2181
0
        uint32_t timeout_ms;
2182
2183
0
        if (send_recv_terminate) {
2184
0
          goto error;
2185
0
        }
2186
2187
0
        if (now - session->last_tx >= session->rl_ticks_per_packet) {
2188
0
          break;
2189
0
        }
2190
0
        timeout_ms = (uint32_t)(((session->rl_ticks_per_packet - (now - session->last_tx)) *
2191
0
                                 1000) / COAP_TICKS_PER_SECOND);
2192
2193
0
        if (timeout_ms == 0) {
2194
0
          timeout_ms = COAP_IO_NO_WAIT;
2195
0
        }
2196
2197
0
        session->is_rate_limiting = 1;
2198
0
        coap_io_process_lkd(session->context, timeout_ms);
2199
0
        session->is_rate_limiting = 0;
2200
0
        coap_ticks(&now);
2201
0
      }
2202
0
      coap_log_debug("** %s: mid 0x%04x: now transmitting\n",
2203
0
                     coap_session_str(session), pdu->mid);
2204
0
      session->last_tx = now;
2205
0
    }
2206
0
  }
2207
5.88k
#if COAP_PROXY_SUPPORT
2208
5.88k
  if (session->server_list) {
2209
    /* Local session wanting to use proxy logic */
2210
0
    return coap_proxy_local_write(session, pdu);
2211
0
  }
2212
5.88k
#endif /* COAP_PROXY_SUPPORT */
2213
5.88k
  if (pdu->code == COAP_RESPONSE_CODE(508)) {
2214
    /*
2215
     * Need to prepend our IP identifier to the data as per
2216
     * https://rfc-editor.org/rfc/rfc8768.html#section-4
2217
     */
2218
0
    if (!prepend_508_ip(session, pdu)) {
2219
0
      return (coap_mid_t)COAP_DROPPED_RESPONSE;
2220
0
    }
2221
0
  }
2222
2223
5.88k
  if (session->echo) {
2224
0
    if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
2225
0
                            session->echo->s))
2226
0
      goto error;
2227
0
    coap_delete_bin_const(session->echo);
2228
0
    session->echo = NULL;
2229
0
  }
2230
5.88k
#if COAP_OSCORE_SUPPORT
2231
5.88k
  if (session->oscore_encryption) {
2232
    /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
2233
0
    if (COAP_PDU_IS_REQUEST(pdu) && !coap_rebuild_pdu_for_proxy(pdu))
2234
0
      goto error;
2235
0
  }
2236
5.88k
#endif /* COAP_OSCORE_SUPPORT */
2237
2238
5.88k
  if (!coap_pdu_encode_header(pdu, session->proto)) {
2239
0
    goto error;
2240
0
  }
2241
2242
5.88k
#if !COAP_DISABLE_TCP
2243
5.88k
  if (COAP_PROTO_RELIABLE(session->proto) &&
2244
798
      session->state == COAP_SESSION_STATE_ESTABLISHED) {
2245
319
    coap_opt_iterator_t opt_iter;
2246
2247
319
    if (!session->csm_block_supported) {
2248
      /*
2249
       * Need to check that this instance is not sending any block options as
2250
       * the remote end via CSM has not informed us that there is support
2251
       * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
2252
       * This includes potential BERT blocks.
2253
       */
2254
319
      if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
2255
0
        coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
2256
0
      }
2257
319
      if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
2258
0
        coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
2259
0
      }
2260
319
    } else if (!session->csm_bert_rem_support) {
2261
0
      coap_opt_t *opt;
2262
2263
0
      opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
2264
0
      if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2265
0
        coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
2266
0
      }
2267
0
      opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
2268
0
      if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
2269
0
        coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
2270
0
      }
2271
0
    }
2272
319
  }
2273
5.88k
#endif /* !COAP_DISABLE_TCP */
2274
2275
5.88k
#if COAP_OSCORE_SUPPORT
2276
5.88k
  if (session->oscore_encryption &&
2277
0
      pdu->type != COAP_MESSAGE_RST &&
2278
0
      !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE) &&
2279
0
      !(COAP_PROTO_RELIABLE(session->proto) && pdu->code == COAP_SIGNALING_CODE_PONG)) {
2280
    /* Refactor PDU as appropriate RFC8613 */
2281
0
    coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted_lkd(session, pdu, NULL, 0);
2282
2283
0
    if (osc_pdu == NULL) {
2284
0
      coap_log_warn("OSCORE: PDU could not be encrypted\n");
2285
0
      if (coap_get_log_level() < COAP_LOG_DEBUG)
2286
0
        coap_show_pdu(COAP_LOG_WARN, pdu);
2287
0
      goto error;
2288
0
    }
2289
0
    bytes_written = coap_send_pdu(session, osc_pdu, NULL);
2290
0
    coap_delete_pdu_lkd(pdu);
2291
0
    pdu = osc_pdu;
2292
0
  } else
2293
5.88k
#endif /* COAP_OSCORE_SUPPORT */
2294
5.88k
    bytes_written = coap_send_pdu(session, pdu, NULL);
2295
2296
5.88k
#if COAP_SERVER_SUPPORT
2297
5.88k
  if (session->last_resp_pdu != pdu &&
2298
5.88k
      request_pdu && COAP_PROTO_NOT_RELIABLE(session->proto) &&
2299
829
      COAP_PDU_IS_REQUEST(request_pdu) &&
2300
829
      COAP_PDU_IS_RESPONSE(pdu) && pdu->type == COAP_MESSAGE_ACK) {
2301
408
    coap_delete_pdu_lkd(session->last_resp_pdu);
2302
408
    session->last_resp_pdu = pdu;
2303
408
    coap_pdu_reference_lkd(session->last_resp_pdu);
2304
408
  }
2305
5.88k
#endif /* COAP_SERVER_SUPPORT */
2306
2307
5.88k
  if (bytes_written == COAP_PDU_DELAYED) {
2308
    /* do not free pdu as it is stored with session for later use */
2309
479
    return pdu->mid;
2310
479
  }
2311
5.41k
  if (bytes_written < 0) {
2312
1.53k
    if (pdu->code != 0)
2313
985
      coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
2314
1.53k
    goto error;
2315
1.53k
  }
2316
2317
3.87k
#if !COAP_DISABLE_TCP
2318
3.87k
  if (COAP_PROTO_RELIABLE(session->proto) &&
2319
65
      (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
2320
3
    if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
2321
3
      session->partial_write = (size_t)bytes_written;
2322
      /* do not free pdu as it is stored with session for later use */
2323
3
      return pdu->mid;
2324
3
    } else {
2325
0
      goto error;
2326
0
    }
2327
3
  }
2328
3.87k
#endif /* !COAP_DISABLE_TCP */
2329
2330
3.87k
  if (pdu->type != COAP_MESSAGE_CON
2331
3.86k
      || COAP_PROTO_RELIABLE(session->proto)) {
2332
3.86k
    coap_mid_t id = pdu->mid;
2333
3.86k
    coap_delete_pdu_lkd(pdu);
2334
3.86k
    return id;
2335
3.86k
  }
2336
2337
8
  coap_queue_t *node = coap_new_node();
2338
8
  if (!node) {
2339
0
    coap_log_debug("coap_wait_ack: insufficient memory\n");
2340
0
    goto error;
2341
0
  }
2342
2343
8
  node->id = pdu->mid;
2344
8
  node->pdu = pdu;
2345
8
  coap_prng_lkd(&r, sizeof(r));
2346
  /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
2347
8
  node->timeout = coap_calc_timeout(session, r);
2348
8
  return coap_wait_ack(session->context, session, node);
2349
1.53k
error:
2350
1.53k
  coap_delete_pdu_lkd(pdu);
2351
1.53k
  return COAP_INVALID_MID;
2352
8
}
2353
2354
void
2355
0
coap_send_recv_terminate(void) {
2356
0
  send_recv_terminate = 1;
2357
0
}
2358
2359
COAP_API int
2360
coap_send_recv(coap_session_t *session, coap_pdu_t *request_pdu,
2361
0
               coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2362
0
  int ret;
2363
2364
0
  coap_lock_lock(return 0);
2365
0
  ret = coap_send_recv_lkd(session, request_pdu, response_pdu, timeout_ms);
2366
0
  coap_lock_unlock();
2367
0
  return ret;
2368
0
}
2369
2370
/*
2371
 * Return 0 or +ve Time in function in ms after successful transfer
2372
 *              -1 Invalid timeout parameter
2373
 *              -2 Failed to transmit PDU
2374
 *              -3 Nack or Event handler invoked, cancelling request
2375
 *              -4 coap_io_process returned error (fail to re-lock or select())
2376
 *              -5 Response not received in the given time
2377
 *              -6 Terminated by user
2378
 *              -7 Client mode code not enabled
2379
 */
2380
int
2381
coap_send_recv_lkd(coap_session_t *session, coap_pdu_t *request_pdu,
2382
0
                   coap_pdu_t **response_pdu, uint32_t timeout_ms) {
2383
0
#if COAP_CLIENT_SUPPORT
2384
0
  coap_mid_t mid = COAP_INVALID_MID;
2385
0
  uint32_t rem_timeout = timeout_ms;
2386
0
  uint32_t block_mode = session->block_mode;
2387
0
  int ret = 0;
2388
0
  coap_tick_t now;
2389
0
  coap_tick_t start;
2390
0
  coap_tick_t ticks_so_far;
2391
0
  uint32_t time_so_far_ms;
2392
2393
0
  coap_ticks(&start);
2394
0
  assert(request_pdu);
2395
2396
0
  coap_lock_check_locked();
2397
2398
0
  session->resp_pdu = NULL;
2399
0
  session->req_token = coap_new_bin_const(request_pdu->actual_token.s,
2400
0
                                          request_pdu->actual_token.length);
2401
2402
0
  if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2403
0
    ret = -1;
2404
0
    goto fail;
2405
0
  }
2406
0
  if (session->state == COAP_SESSION_STATE_NONE) {
2407
0
    ret = -3;
2408
0
    goto fail;
2409
0
  }
2410
2411
0
  session->block_mode |= COAP_BLOCK_SINGLE_BODY;
2412
0
  if (coap_is_mcast(&session->addr_info.remote))
2413
0
    block_mode = session->block_mode;
2414
2415
0
  session->doing_send_recv = 1;
2416
  /* So the user needs to delete the PDU */
2417
0
  coap_pdu_reference_lkd(request_pdu);
2418
0
  mid = coap_send_lkd(session, request_pdu);
2419
0
  if (mid == COAP_INVALID_MID) {
2420
0
    if (!session->doing_send_recv)
2421
0
      ret = -3;
2422
0
    else
2423
0
      ret = -2;
2424
0
    goto fail;
2425
0
  }
2426
2427
  /* Wait for the response to come in */
2428
0
  while (rem_timeout > 0 && session->doing_send_recv && !session->resp_pdu) {
2429
0
    if (send_recv_terminate) {
2430
0
      ret = -6;
2431
0
      goto fail;
2432
0
    }
2433
0
    ret = coap_io_process_lkd(session->context, rem_timeout);
2434
0
    if (ret < 0) {
2435
0
      ret = -4;
2436
0
      goto fail;
2437
0
    }
2438
    /* timeout_ms is for timeout between specific request and response */
2439
0
    coap_ticks(&now);
2440
0
    ticks_so_far = now - session->last_rx_tx;
2441
0
    time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2442
0
    if (time_so_far_ms >= timeout_ms) {
2443
0
      rem_timeout = 0;
2444
0
    } else {
2445
0
      rem_timeout = timeout_ms - time_so_far_ms;
2446
0
    }
2447
0
    if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
2448
      /* To pick up on (D)TLS setup issues */
2449
0
      coap_ticks(&now);
2450
0
      ticks_so_far = now - start;
2451
0
      time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2452
0
      if (time_so_far_ms >= timeout_ms) {
2453
0
        rem_timeout = 0;
2454
0
      } else {
2455
0
        rem_timeout = timeout_ms - time_so_far_ms;
2456
0
      }
2457
0
    }
2458
0
  }
2459
2460
0
  if (rem_timeout) {
2461
0
    coap_ticks(&now);
2462
0
    ticks_so_far = now - start;
2463
0
    time_so_far_ms = (uint32_t)((ticks_so_far * 1000) / COAP_TICKS_PER_SECOND);
2464
0
    ret = time_so_far_ms;
2465
    /* Give PDU to user who will be calling coap_delete_pdu() */
2466
0
    *response_pdu = session->resp_pdu;
2467
0
    session->resp_pdu = NULL;
2468
0
    if (*response_pdu == NULL) {
2469
0
      ret = -3;
2470
0
    }
2471
0
  } else {
2472
    /* If there is a resp_pdu, it will get cleared below */
2473
0
    ret = -5;
2474
0
  }
2475
2476
0
fail:
2477
0
  session->block_mode = block_mode;
2478
0
  session->doing_send_recv = 0;
2479
  /* delete referenced copy */
2480
0
  coap_delete_pdu_lkd(session->resp_pdu);
2481
0
  session->resp_pdu = NULL;
2482
0
  coap_delete_bin_const(session->req_token);
2483
0
  session->req_token = NULL;
2484
0
  return ret;
2485
2486
#else /* !COAP_CLIENT_SUPPORT */
2487
2488
  (void)session;
2489
  (void)timeout_ms;
2490
  (void)request_pdu;
2491
  coap_log_warn("coap_send_recv: Client mode not supported\n");
2492
  *response_pdu =  NULL;
2493
  return -7;
2494
2495
#endif /* ! COAP_CLIENT_SUPPORT */
2496
0
}
2497
2498
coap_mid_t
2499
0
coap_retransmit(coap_context_t *context, coap_queue_t *node) {
2500
0
  if (!context || !node || !node->session)
2501
0
    return COAP_INVALID_MID;
2502
2503
0
#if COAP_CLIENT_SUPPORT
2504
0
  if (node->session->session_failed) {
2505
    /* Force failure */
2506
0
    node->retransmit_cnt = (unsigned char)node->session->max_retransmit;
2507
0
  }
2508
0
#endif /* COAP_CLIENT_SUPPORT */
2509
2510
  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
2511
0
  if (node->retransmit_cnt < node->session->max_retransmit) {
2512
0
    ssize_t bytes_written;
2513
0
    coap_tick_t now;
2514
0
    coap_tick_t next_delay;
2515
0
    coap_address_t remote;
2516
2517
0
    node->retransmit_cnt++;
2518
0
    coap_handle_event_lkd(context, COAP_EVENT_MSG_RETRANSMITTED, node->session);
2519
2520
0
    next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
2521
0
    if (context->ping_timeout &&
2522
0
        context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
2523
0
      uint8_t byte;
2524
2525
0
      coap_prng_lkd(&byte, sizeof(byte));
2526
      /* Don't exceed the ping timeout value */
2527
0
      next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
2528
0
    }
2529
2530
0
    coap_ticks(&now);
2531
0
    if (context->sendqueue == NULL) {
2532
0
      node->t = next_delay;
2533
0
      context->sendqueue_basetime = now;
2534
0
    } else {
2535
      /* make node->t relative to context->sendqueue_basetime */
2536
0
      node->t = (now - context->sendqueue_basetime) + next_delay;
2537
0
    }
2538
0
    coap_insert_node(&context->sendqueue, node);
2539
0
    coap_address_copy(&remote, &node->session->addr_info.remote);
2540
0
    coap_address_copy(&node->session->addr_info.remote, &node->remote);
2541
2542
0
    if (node->is_mcast) {
2543
0
      coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
2544
0
                     coap_session_str(node->session), node->id);
2545
0
    } else {
2546
0
      coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
2547
0
                     coap_session_str(node->session), node->id,
2548
0
                     node->retransmit_cnt,
2549
0
                     (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
2550
0
    }
2551
2552
0
    if (node->session->con_active)
2553
0
      node->session->con_active--;
2554
0
    bytes_written = coap_send_pdu(node->session, node->pdu, node);
2555
2556
0
    if (bytes_written == COAP_PDU_DELAYED) {
2557
      /* PDU was not retransmitted immediately because a new handshake is
2558
         in progress. node was moved to the send queue of the session. */
2559
0
      return node->id;
2560
0
    }
2561
2562
0
    coap_address_copy(&node->session->addr_info.remote, &remote);
2563
0
    if (node->is_mcast) {
2564
0
      coap_session_connected(node->session);
2565
0
      coap_delete_node_lkd(node);
2566
0
      return COAP_INVALID_MID;
2567
0
    }
2568
2569
0
    if (bytes_written < 0)
2570
0
      return (int)bytes_written;
2571
2572
0
    return node->id;
2573
0
  }
2574
2575
0
#if COAP_CLIENT_SUPPORT
2576
0
  if (node->session->session_failed) {
2577
0
    coap_log_info("** %s: mid=0x%04x: deleted due to reconnection issue\n",
2578
0
                  coap_session_str(node->session), node->id);
2579
0
  } else {
2580
0
#endif /* COAP_CLIENT_SUPPORT */
2581
    /* no more retransmissions, remove node from system */
2582
0
    coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
2583
0
                  coap_session_str(node->session), node->id, node->retransmit_cnt);
2584
0
#if COAP_CLIENT_SUPPORT
2585
0
  }
2586
0
#endif /* COAP_CLIENT_SUPPORT */
2587
2588
0
#if COAP_SERVER_SUPPORT
2589
  /* Check if subscriptions exist that should be canceled after
2590
     COAP_OBS_MAX_FAIL */
2591
0
  if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2 &&
2592
0
      (node->session->ref_subscriptions || node->session->ref_proxy_subs)) {
2593
0
    if (context->ping_timeout) {
2594
0
      coap_session_server_keepalive_failed(node->session);
2595
0
      coap_delete_node_lkd(node);
2596
0
      return COAP_INVALID_MID;
2597
0
    } else {
2598
0
      if (node->session->ref_subscriptions)
2599
0
        coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
2600
0
#if COAP_PROXY_SUPPORT
2601
      /* Need to check is there is a proxy subscription active and delete it */
2602
0
      if (node->session->ref_proxy_subs)
2603
0
        coap_delete_proxy_subscriber(node->session, &node->pdu->actual_token,
2604
0
                                     0, COAP_PROXY_SUBS_TOKEN);
2605
0
#endif /* COAP_PROXY_SUPPORT */
2606
0
    }
2607
0
  }
2608
0
#endif /* COAP_SERVER_SUPPORT */
2609
0
  if (node->session->con_active) {
2610
0
    node->session->con_active--;
2611
0
    if (node->session->state == COAP_SESSION_STATE_ESTABLISHED) {
2612
      /*
2613
       * As there may be another CON in a different queue entry on the same
2614
       * session that needs to be immediately released,
2615
       * coap_session_connected() is called.
2616
       * However, there is the possibility coap_wait_ack() may be called for
2617
       * this node (queue) and re-added to context->sendqueue.
2618
       * coap_delete_node_lkd(node) called shortly will handle this and
2619
       * remove it.
2620
       */
2621
0
      coap_session_connected(node->session);
2622
0
    }
2623
0
  }
2624
2625
0
  if (node->pdu->type == COAP_MESSAGE_CON) {
2626
0
    coap_handle_nack(node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
2627
0
  }
2628
0
#if COAP_CLIENT_SUPPORT
2629
0
  node->session->doing_send_recv = 0;
2630
0
#endif /* COAP_CLIENT_SUPPORT */
2631
  /* And finally delete the node */
2632
0
  coap_delete_node_lkd(node);
2633
0
  return COAP_INVALID_MID;
2634
0
}
2635
2636
static int
2637
0
coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) {
2638
0
  uint8_t *data;
2639
0
  size_t data_len;
2640
0
  int result = -1;
2641
2642
0
  coap_packet_get_memmapped(packet, &data, &data_len);
2643
0
  if (session->proto == COAP_PROTO_DTLS) {
2644
0
#if COAP_SERVER_SUPPORT
2645
0
    if (session->type == COAP_SESSION_TYPE_HELLO)
2646
0
      result = coap_dtls_hello(session, data, data_len);
2647
0
    else
2648
0
#endif /* COAP_SERVER_SUPPORT */
2649
0
      if (session->tls)
2650
0
        result = coap_dtls_receive(session, data, data_len);
2651
0
  } else if (session->proto == COAP_PROTO_UDP) {
2652
0
    result = coap_handle_dgram(ctx, session, data, data_len);
2653
0
  }
2654
0
  return result;
2655
0
}
2656
2657
#if COAP_CLIENT_SUPPORT
2658
void
2659
0
coap_connect_session(coap_session_t *session, coap_tick_t now) {
2660
#if COAP_DISABLE_TCP
2661
  (void)now;
2662
2663
  session->sock.flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CAN_CONNECT);
2664
#else /* !COAP_DISABLE_TCP */
2665
0
  if (coap_netif_strm_connect2(session)) {
2666
0
    session->last_rx_tx = now;
2667
0
    coap_handle_event_lkd(session->context, COAP_EVENT_TCP_CONNECTED, session);
2668
0
    session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2669
0
  } else {
2670
0
    coap_handle_event_lkd(session->context, COAP_EVENT_TCP_FAILED, session);
2671
0
    coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
2672
0
  }
2673
0
#endif /* !COAP_DISABLE_TCP */
2674
0
}
2675
#endif /* COAP_CLIENT_SUPPORT */
2676
2677
static void
2678
0
coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
2679
0
  coap_queue_t *q;
2680
2681
0
  (void)ctx;
2682
0
  assert(session->sock.flags & COAP_SOCKET_CONNECTED);
2683
2684
0
  while ((q = coap_remove_first_from_delayq(session)) != NULL) {
2685
0
    ssize_t bytes_written;
2686
2687
0
    coap_address_copy(&session->addr_info.remote, &q->remote);
2688
0
    coap_log_debug("** %s: mid=0x%04x: transmitted after delay (1)\n",
2689
0
                   coap_session_str(session), (int)q->id);
2690
0
    assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
2691
0
    bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
2692
0
                    q->pdu->token - q->pdu->hdr_size + session->partial_write,
2693
0
                    q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
2694
0
    if (bytes_written > 0)
2695
0
      session->last_rx_tx = now;
2696
0
    if (bytes_written <= 0 ||
2697
0
        (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
2698
0
      if (bytes_written > 0)
2699
0
        session->partial_write += (size_t)bytes_written;
2700
0
      coap_add_to_head_delayq(session, q);
2701
0
      break;
2702
0
    }
2703
0
    session->partial_write = 0;
2704
0
    coap_delete_node_lkd(q);
2705
0
  }
2706
0
}
2707
2708
void
2709
0
coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
2710
#if COAP_CONSTRAINED_STACK
2711
  /* payload and packet can be protected by global_lock if needed */
2712
  static unsigned char payload[COAP_RXBUFFER_SIZE];
2713
  static coap_packet_t s_packet;
2714
#else /* ! COAP_CONSTRAINED_STACK */
2715
0
  unsigned char payload[COAP_RXBUFFER_SIZE];
2716
0
  coap_packet_t s_packet;
2717
0
#endif /* ! COAP_CONSTRAINED_STACK */
2718
0
  coap_packet_t *packet = &s_packet;
2719
2720
0
  assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
2721
2722
0
  packet->length = sizeof(payload);
2723
0
  packet->payload = payload;
2724
2725
0
  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2726
0
    ssize_t bytes_read;
2727
0
    coap_address_t remote;
2728
2729
0
    coap_address_copy(&remote, &session->addr_info.remote);
2730
0
    memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
2731
0
    bytes_read = coap_netif_dgrm_read(session, packet);
2732
2733
0
    if (bytes_read < 0) {
2734
0
      if (bytes_read == -2) {
2735
0
        coap_address_copy(&session->addr_info.remote, &remote);
2736
        /* Reset the session back to startup defaults */
2737
0
        coap_session_disconnected_lkd(session, COAP_NACK_ICMP_ISSUE);
2738
0
      }
2739
0
    } else if (bytes_read > 0) {
2740
0
      session->last_rx_tx = now;
2741
0
#if COAP_CLIENT_SUPPORT
2742
0
      if (session->session_failed) {
2743
0
        session->session_failed = 0;
2744
0
        coap_handle_event_lkd(session->context, COAP_EVENT_RECONNECT_SUCCESS, session);
2745
0
      }
2746
0
#endif /* COAP_CLIENT_SUPPORT */
2747
      /* coap_netif_dgrm_read() updates session->addr_info from packet->addr_info */
2748
0
      coap_handle_dgram_for_proto(ctx, session, packet);
2749
0
    } else {
2750
0
      coap_address_copy(&session->addr_info.remote, &remote);
2751
0
    }
2752
0
#if !COAP_DISABLE_TCP
2753
0
  } else if (session->proto == COAP_PROTO_WS ||
2754
0
             session->proto == COAP_PROTO_WSS) {
2755
0
    ssize_t bytes_read = 0;
2756
2757
    /* WebSocket layer passes us the whole packet */
2758
0
    bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2759
0
                                                                packet->payload,
2760
0
                                                                packet->length);
2761
0
    if (bytes_read < 0) {
2762
0
      coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
2763
0
    } else if (bytes_read > 2) {
2764
0
      coap_pdu_t *pdu;
2765
2766
0
      session->last_rx_tx = now;
2767
      /* Need max space in case PDU is updated with updated token etc. */
2768
0
      pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2769
0
      if (!pdu) {
2770
0
        return;
2771
0
      }
2772
2773
0
      if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
2774
0
        coap_handle_event_lkd(session->context, COAP_EVENT_BAD_PACKET, session);
2775
0
        coap_log_warn("discard malformed PDU\n");
2776
0
        coap_delete_pdu_lkd(pdu);
2777
0
        return;
2778
0
      }
2779
2780
0
      coap_dispatch(ctx, session, pdu);
2781
0
      coap_delete_pdu_lkd(pdu);
2782
0
      return;
2783
0
    }
2784
0
  } else {
2785
0
    ssize_t bytes_read = 0;
2786
0
    const uint8_t *p;
2787
0
    int retry;
2788
2789
0
    do {
2790
0
      bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
2791
0
                                                                  packet->payload,
2792
0
                                                                  packet->length);
2793
0
      if (bytes_read > 0) {
2794
0
        session->last_rx_tx = now;
2795
0
      }
2796
0
      p = packet->payload;
2797
0
      retry = bytes_read == (ssize_t)packet->length;
2798
0
      while (bytes_read > 0) {
2799
0
        if (session->partial_pdu) {
2800
0
          size_t len = session->partial_pdu->used_size
2801
0
                       + session->partial_pdu->hdr_size
2802
0
                       - session->partial_read;
2803
0
          size_t n = min(len, (size_t)bytes_read);
2804
2805
0
          assert(n <= session->partial_pdu->alloc_size + session->partial_pdu->hdr_size -
2806
0
                 session->partial_read);
2807
0
          if (n > session->partial_pdu->alloc_size + session->partial_pdu->hdr_size -
2808
0
              session->partial_read) {
2809
0
            bytes_read = -1;
2810
0
            break;
2811
0
          }
2812
2813
0
          memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
2814
0
                 + session->partial_read, p, n);
2815
0
          p += n;
2816
0
          bytes_read -= n;
2817
0
          if (n == len) {
2818
0
            coap_opt_filter_t error_opts;
2819
0
            coap_pdu_t *pdu = session->partial_pdu;
2820
2821
0
            session->partial_pdu = NULL;
2822
0
            session->partial_read = 0;
2823
2824
0
            coap_option_filter_clear(&error_opts);
2825
0
            if (coap_pdu_parse_header(pdu, session->proto)
2826
0
                && coap_pdu_parse_opt(pdu, &error_opts)) {
2827
0
              coap_dispatch(ctx, session, pdu);
2828
0
            } else if (error_opts.mask) {
2829
0
              coap_pdu_t *response =
2830
0
                  coap_new_error_response(pdu,
2831
0
                                          COAP_RESPONSE_CODE(402), &error_opts);
2832
0
              if (!response) {
2833
0
                coap_log_warn("coap_read_session: cannot create error response\n");
2834
0
              } else {
2835
0
                if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
2836
0
                  coap_log_warn("coap_read_session: error sending response\n");
2837
0
              }
2838
0
            }
2839
0
            coap_delete_pdu_lkd(pdu);
2840
0
          } else {
2841
0
            session->partial_read += n;
2842
0
          }
2843
0
        } else if (session->partial_read > 0) {
2844
0
          size_t hdr_size = coap_pdu_parse_header_size(session->proto,
2845
0
                                                       session->read_header);
2846
0
          size_t tkl = session->read_header[0] & 0x0f;
2847
0
          size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
2848
0
                                 tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
2849
0
          size_t len = hdr_size + tok_ext_bytes - session->partial_read;
2850
0
          size_t n = min(len, (size_t)bytes_read);
2851
0
          memcpy(session->read_header + session->partial_read, p, n);
2852
0
          p += n;
2853
0
          bytes_read -= n;
2854
0
          if (n == len) {
2855
            /* Header now all in */
2856
0
            size_t size = coap_pdu_parse_size(session->proto, session->read_header,
2857
0
                                              hdr_size + tok_ext_bytes);
2858
0
            if (size > session->context->csm_max_message_size) {
2859
0
              coap_log_warn("** %s: incoming PDU length too large (%" PRIuS " > %u)\n",
2860
0
                            coap_session_str(session),
2861
0
                            size, session->context->csm_max_message_size);
2862
0
              bytes_read = -1;
2863
0
              break;
2864
0
            }
2865
            /* Need max space in case PDU is updated with updated token etc. */
2866
0
            session->partial_pdu = coap_pdu_init(0, 0, 0,
2867
0
                                                 coap_session_max_pdu_rcv_size(session));
2868
0
            if (session->partial_pdu == NULL) {
2869
0
              bytes_read = -1;
2870
0
              break;
2871
0
            }
2872
0
            if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
2873
0
              bytes_read = -1;
2874
0
              break;
2875
0
            }
2876
0
            session->partial_pdu->hdr_size = (uint8_t)hdr_size;
2877
0
            session->partial_pdu->used_size = size;
2878
0
            memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
2879
0
            session->partial_read = hdr_size + tok_ext_bytes;
2880
0
            if (size == 0) {
2881
0
              coap_pdu_t *pdu = session->partial_pdu;
2882
2883
0
              session->partial_pdu = NULL;
2884
0
              session->partial_read = 0;
2885
0
              if (coap_pdu_parse_header(pdu, session->proto)) {
2886
0
                coap_dispatch(ctx, session, pdu);
2887
0
              }
2888
0
              coap_delete_pdu_lkd(pdu);
2889
0
            }
2890
0
          } else {
2891
            /* More of the header to go */
2892
0
            session->partial_read += n;
2893
0
          }
2894
0
        } else {
2895
          /* Get in first byte of the header */
2896
0
          session->read_header[0] = *p++;
2897
0
          bytes_read -= 1;
2898
0
          if (!coap_pdu_parse_header_size(session->proto,
2899
0
                                          session->read_header)) {
2900
0
            bytes_read = -1;
2901
0
            break;
2902
0
          }
2903
0
          session->partial_read = 1;
2904
0
        }
2905
0
      }
2906
0
    } while (bytes_read == 0 && retry);
2907
0
    if (bytes_read < 0)
2908
0
      coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
2909
0
#endif /* !COAP_DISABLE_TCP */
2910
0
  }
2911
0
}
2912
2913
#if COAP_SERVER_SUPPORT
2914
static int
2915
0
coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2916
0
  ssize_t bytes_read = -1;
2917
0
  int result = -1;                /* the value to be returned */
2918
#if COAP_CONSTRAINED_STACK
2919
  /* payload and e_packet can be protected by global_lock if needed */
2920
  static unsigned char payload[COAP_RXBUFFER_SIZE];
2921
  static coap_packet_t e_packet;
2922
#else /* ! COAP_CONSTRAINED_STACK */
2923
0
  unsigned char payload[COAP_RXBUFFER_SIZE];
2924
0
  coap_packet_t e_packet;
2925
0
#endif /* ! COAP_CONSTRAINED_STACK */
2926
0
  coap_packet_t *packet = &e_packet;
2927
2928
0
  assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
2929
0
  assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
2930
2931
  /* Need to do this as there may be holes in addr_info */
2932
0
  memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2933
0
  packet->length = sizeof(payload);
2934
0
  packet->payload = payload;
2935
0
  coap_address_init(&packet->addr_info.remote);
2936
0
  coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2937
2938
0
  bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2939
0
  if (bytes_read < 0) {
2940
0
    if (errno != EAGAIN) {
2941
0
      coap_log_warn("*  %s: read failed\n", coap_endpoint_str(endpoint));
2942
0
    }
2943
0
  } else if (bytes_read > 0) {
2944
0
    coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2945
0
    if (session) {
2946
0
      coap_session_reference_lkd(session);
2947
0
      coap_log_debug("*  %s: netif: recv %4" PRIdS " bytes\n",
2948
0
                     coap_session_str(session), bytes_read);
2949
0
      result = coap_handle_dgram_for_proto(ctx, session, packet);
2950
0
      if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2951
0
        coap_session_new_dtls_session(session, now);
2952
0
      coap_session_release_lkd(session);
2953
0
    }
2954
0
  }
2955
0
  return result;
2956
0
}
2957
2958
static int
2959
0
coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2960
0
  (void)ctx;
2961
0
  (void)endpoint;
2962
0
  (void)now;
2963
0
  return 0;
2964
0
}
2965
2966
#if !COAP_DISABLE_TCP
2967
static int
2968
coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2969
0
                     coap_tick_t now, void *extra) {
2970
0
  coap_session_t *session = coap_new_server_session(ctx, endpoint, extra);
2971
0
  if (session)
2972
0
    session->last_rx_tx = now;
2973
0
  return session != NULL;
2974
0
}
2975
#endif /* !COAP_DISABLE_TCP */
2976
#endif /* COAP_SERVER_SUPPORT */
2977
2978
COAP_API void
2979
0
coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
2980
0
  coap_lock_lock(return);
2981
0
  coap_io_do_io_lkd(ctx, now);
2982
0
  coap_lock_unlock();
2983
0
}
2984
2985
void
2986
0
coap_io_do_io_lkd(coap_context_t *ctx, coap_tick_t now) {
2987
0
#ifdef COAP_EPOLL_SUPPORT
2988
0
  (void)ctx;
2989
0
  (void)now;
2990
0
  coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2991
#else /* ! COAP_EPOLL_SUPPORT */
2992
  coap_session_t *s, *rtmp;
2993
2994
  coap_lock_check_locked();
2995
#if COAP_SERVER_SUPPORT
2996
  coap_endpoint_t *ep, *tmp;
2997
  LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2998
    if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2999
      coap_read_endpoint(ctx, ep, now);
3000
    if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
3001
      coap_write_endpoint(ctx, ep, now);
3002
#if !COAP_DISABLE_TCP
3003
    if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
3004
      coap_accept_endpoint(ctx, ep, now, NULL);
3005
#endif /* !COAP_DISABLE_TCP */
3006
    SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
3007
      /* Make sure the session object is not deleted in one of the callbacks  */
3008
      coap_session_reference_lkd(s);
3009
#if COAP_CLIENT_SUPPORT
3010
      if (s->client_initiated && (s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
3011
        coap_connect_session(s, now);
3012
      }
3013
#endif /* COAP_CLIENT_SUPPORT */
3014
      if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
3015
        coap_read_session(ctx, s, now);
3016
      }
3017
      if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
3018
        coap_write_session(ctx, s, now);
3019
      }
3020
      coap_session_release_lkd(s);
3021
    }
3022
  }
3023
#endif /* COAP_SERVER_SUPPORT */
3024
3025
#if COAP_CLIENT_SUPPORT
3026
  SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
3027
    /* Make sure the session object is not deleted in one of the callbacks  */
3028
    coap_session_reference_lkd(s);
3029
    if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
3030
      coap_connect_session(s, now);
3031
    }
3032
    if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
3033
      coap_read_session(ctx, s, now);
3034
    }
3035
    if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
3036
      coap_write_session(ctx, s, now);
3037
    }
3038
    coap_session_release_lkd(s);
3039
  }
3040
#endif /* COAP_CLIENT_SUPPORT */
3041
#endif /* ! COAP_EPOLL_SUPPORT */
3042
0
}
3043
3044
COAP_API void
3045
0
coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
3046
0
  coap_lock_lock(return);
3047
0
  coap_io_do_epoll_lkd(ctx, events, nevents);
3048
0
  coap_lock_unlock();
3049
0
}
3050
3051
/*
3052
 * While this code in part replicates coap_io_do_io_lkd(), doing the functions
3053
 * directly saves having to iterate through the endpoints / sessions.
3054
 */
3055
void
3056
26
coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
3057
#ifndef COAP_EPOLL_SUPPORT
3058
  (void)ctx;
3059
  (void)events;
3060
  (void)nevents;
3061
  coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
3062
#else /* COAP_EPOLL_SUPPORT */
3063
26
  coap_tick_t now;
3064
26
  size_t j;
3065
3066
26
  coap_lock_check_locked();
3067
26
  coap_ticks(&now);
3068
26
  for (j = 0; j < nevents; j++) {
3069
0
    coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
3070
3071
    /* Ignore 'timer trigger' ptr  which is NULL */
3072
0
    if (sock) {
3073
0
#if COAP_SERVER_SUPPORT
3074
0
      if (sock->endpoint) {
3075
0
        coap_endpoint_t *endpoint = sock->endpoint;
3076
0
        if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3077
0
            (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3078
0
          sock->flags |= COAP_SOCKET_CAN_READ;
3079
0
          coap_read_endpoint(endpoint->context, endpoint, now);
3080
0
        }
3081
3082
0
        if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3083
0
            (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3084
          /*
3085
           * Need to update this to EPOLLIN as EPOLLOUT will normally always
3086
           * be true causing epoll_wait to return early
3087
           */
3088
0
          coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3089
0
          sock->flags |= COAP_SOCKET_CAN_WRITE;
3090
0
          coap_write_endpoint(endpoint->context, endpoint, now);
3091
0
        }
3092
3093
0
#if !COAP_DISABLE_TCP
3094
0
        if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
3095
0
            (events[j].events & EPOLLIN)) {
3096
0
          sock->flags |= COAP_SOCKET_CAN_ACCEPT;
3097
0
          coap_accept_endpoint(endpoint->context, endpoint, now, NULL);
3098
0
        }
3099
0
#endif /* !COAP_DISABLE_TCP */
3100
3101
0
      } else
3102
0
#endif /* COAP_SERVER_SUPPORT */
3103
0
        if (sock->session) {
3104
0
          coap_session_t *session = sock->session;
3105
3106
          /* Make sure the session object is not deleted
3107
             in one of the callbacks  */
3108
0
          coap_session_reference_lkd(session);
3109
0
#if COAP_CLIENT_SUPPORT
3110
0
          if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
3111
0
              (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3112
0
            sock->flags |= COAP_SOCKET_CAN_CONNECT;
3113
0
            coap_connect_session(session, now);
3114
0
            if (coap_netif_available(session) &&
3115
0
                !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
3116
0
              coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3117
0
            }
3118
0
          }
3119
0
#endif /* COAP_CLIENT_SUPPORT */
3120
3121
0
          if ((sock->flags & COAP_SOCKET_WANT_READ) &&
3122
0
              (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3123
0
            sock->flags |= COAP_SOCKET_CAN_READ;
3124
0
            coap_read_session(session->context, session, now);
3125
0
          }
3126
3127
0
          if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
3128
0
              (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
3129
            /*
3130
             * Need to update this to EPOLLIN as EPOLLOUT will normally always
3131
             * be true causing epoll_wait to return early
3132
             */
3133
0
            coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
3134
0
            sock->flags |= COAP_SOCKET_CAN_WRITE;
3135
0
            coap_write_session(session->context, session, now);
3136
0
          }
3137
          /* Now dereference session so it can go away if needed */
3138
0
          coap_session_release_lkd(session);
3139
0
        }
3140
0
    } else if (ctx->eptimerfd != -1) {
3141
      /*
3142
       * 'timer trigger' must have fired. eptimerfd needs to be read to clear
3143
       *  it so that it does not set EPOLLIN in the next epoll_wait().
3144
       */
3145
0
      uint64_t count;
3146
3147
      /* Check the result from read() to suppress the warning on
3148
       * systems that declare read() with warn_unused_result. */
3149
0
      if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
3150
0
        /* do nothing */;
3151
0
      }
3152
0
    }
3153
0
  }
3154
  /* And update eptimerfd as to when to next trigger */
3155
26
  coap_ticks(&now);
3156
26
  coap_io_prepare_epoll_lkd(ctx, now);
3157
26
#endif /* COAP_EPOLL_SUPPORT */
3158
26
}
3159
3160
int
3161
coap_handle_dgram(coap_context_t *ctx, coap_session_t *session,
3162
2.85k
                  uint8_t *msg, size_t msg_len) {
3163
3164
2.85k
  coap_pdu_t *pdu = NULL;
3165
2.85k
  coap_opt_filter_t error_opts;
3166
3167
2.85k
  assert(COAP_PROTO_NOT_RELIABLE(session->proto));
3168
2.85k
  if (msg_len < 4) {
3169
    /* Minimum size of CoAP header - ignore runt */
3170
0
    return -1;
3171
0
  }
3172
2.85k
  if ((msg[0] >> 6) != COAP_DEFAULT_VERSION) {
3173
    /*
3174
     * As per https://datatracker.ietf.org/doc/html/rfc7252#section-3,
3175
     * this MUST be silently ignored.
3176
     */
3177
205
    coap_log_debug("coap_handle_dgram: UDP version not supported\n");
3178
205
    return -1;
3179
205
  }
3180
3181
  /* Need max space in case PDU is updated with updated token etc. */
3182
2.64k
  pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
3183
2.64k
  if (!pdu)
3184
0
    goto error;
3185
3186
2.64k
  coap_option_filter_clear(&error_opts);
3187
2.64k
  if (!coap_pdu_parse2(session->proto, msg, msg_len, pdu, &error_opts)) {
3188
1.32k
    coap_handle_event_lkd(session->context, COAP_EVENT_BAD_PACKET, session);
3189
1.32k
    coap_log_warn("discard malformed PDU\n");
3190
1.32k
    if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) {
3191
337
      coap_pdu_t *response =
3192
337
          coap_new_error_response(pdu,
3193
337
                                  COAP_RESPONSE_CODE(402), &error_opts);
3194
337
      if (!response) {
3195
53
        coap_log_warn("coap_handle_dgram: cannot create error response\n");
3196
284
      } else {
3197
284
        if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
3198
284
          coap_log_warn("coap_handle_dgram: error sending response\n");
3199
284
      }
3200
337
      coap_delete_pdu_lkd(pdu);
3201
337
      return -1;
3202
989
    } else {
3203
989
      goto error;
3204
989
    }
3205
1.32k
  }
3206
3207
1.31k
  if (coap_debug_recv_packet()) {
3208
1.31k
    coap_dispatch(ctx, session, pdu);
3209
1.31k
  } else {
3210
0
    coap_show_pdu(COAP_LOG_DEBUG, pdu);
3211
0
  }
3212
1.31k
  coap_delete_pdu_lkd(pdu);
3213
1.31k
  return 0;
3214
3215
989
error:
3216
  /*
3217
   * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
3218
   * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
3219
   */
3220
989
  coap_send_rst_lkd(session, pdu);
3221
989
  coap_delete_pdu_lkd(pdu);
3222
989
  return -1;
3223
2.64k
}
3224
3225
coap_queue_t *
3226
0
coap_remove_mid_from_delayq(coap_session_t *session, coap_mid_t mid) {
3227
0
  coap_queue_t *p = NULL;
3228
0
  coap_queue_t *q;
3229
3230
0
  LL_FOREACH(session->delayqueue, q) {
3231
0
    if (q->id == mid) {
3232
0
      if (p) {
3233
0
        p->next = q->next;
3234
0
      } else {
3235
0
        session->delayqueue = q->next;
3236
0
      }
3237
0
      if (session->delayqueue_tail == q)
3238
0
        session->delayqueue_tail = p;
3239
0
      q->next = NULL;
3240
0
      return q;
3241
0
    }
3242
0
    p = q;
3243
0
  }
3244
0
  return NULL;
3245
0
}
3246
3247
coap_queue_t *
3248
8.05k
coap_remove_first_from_delayq(coap_session_t *session) {
3249
8.05k
  coap_queue_t *q = session->delayqueue;
3250
3251
8.05k
  if (q) {
3252
482
    session->delayqueue = q->next;
3253
482
    if (session->delayqueue == NULL)
3254
249
      session->delayqueue_tail = NULL;
3255
482
    q->next = NULL;
3256
482
  }
3257
8.05k
  return q;
3258
8.05k
}
3259
3260
void
3261
482
coap_add_to_tail_delayq(coap_session_t *session, coap_queue_t *node) {
3262
482
  node->next = NULL;
3263
482
  if (session->delayqueue_tail) {
3264
233
    session->delayqueue_tail->next = node;
3265
249
  } else {
3266
249
    session->delayqueue = node;
3267
249
  }
3268
482
  session->delayqueue_tail = node;
3269
482
}
3270
3271
void
3272
0
coap_add_to_head_delayq(coap_session_t *session, coap_queue_t *node) {
3273
0
  node->next = session->delayqueue;
3274
0
  session->delayqueue = node;
3275
0
  if (node->next == NULL)
3276
0
    session->delayqueue_tail = node;
3277
0
}
3278
3279
int
3280
coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t mid,
3281
193
                       coap_bin_const_t *token, coap_queue_t **node) {
3282
193
  coap_queue_t *p, *q;
3283
3284
193
  if (!queue || !*queue) {
3285
193
    *node = NULL;
3286
193
    return 0;
3287
193
  }
3288
3289
  /* replace queue head if PDU's time is less than head's time */
3290
3291
0
  if (session == (*queue)->session && mid == (*queue)->id &&
3292
0
      (!token || coap_binary_equal(token, &(*queue)->pdu->actual_token))) { /* found message id */
3293
0
    *node = *queue;
3294
0
    *queue = (*queue)->next;
3295
0
    if (*queue) {          /* adjust relative time of new queue head */
3296
0
      (*queue)->t += (*node)->t;
3297
0
    }
3298
0
    (*node)->next = NULL;
3299
0
    coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
3300
0
                   coap_session_str(session), mid);
3301
0
    return 1;
3302
0
  }
3303
3304
  /* search message id in queue to remove (only first occurrence will be removed) */
3305
0
  q = *queue;
3306
0
  do {
3307
0
    p = q;
3308
0
    q = q->next;
3309
0
  } while (q && (session != q->session || mid != q->id ||
3310
0
                 (token && ! coap_binary_equal(token, &q->pdu->actual_token))));
3311
3312
0
  if (q) {                        /* found message id */
3313
0
    p->next = q->next;
3314
0
    if (p->next) {                /* must update relative time of p->next */
3315
0
      p->next->t += q->t;
3316
0
    }
3317
0
    q->next = NULL;
3318
0
    *node = q;
3319
0
    coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
3320
0
                   coap_session_str(session), mid);
3321
0
    return 1;
3322
0
  }
3323
3324
0
  *node = NULL;
3325
0
  return 0;
3326
3327
0
}
3328
3329
static int
3330
coap_remove_from_queue_token(coap_queue_t **queue, coap_session_t *session,
3331
2.26k
                             coap_bin_const_t *token, coap_queue_t **node) {
3332
2.26k
  coap_queue_t *p, *q;
3333
3334
2.26k
  if (!queue || !*queue)
3335
2.26k
    return 0;
3336
3337
  /* replace queue head if PDU's time is less than head's time */
3338
3339
0
  if (session == (*queue)->session &&
3340
0
      (!token || coap_binary_equal(&(*queue)->pdu->actual_token, token))) { /* found token */
3341
0
    *node = *queue;
3342
0
    *queue = (*queue)->next;
3343
0
    if (*queue) {          /* adjust relative time of new queue head */
3344
0
      (*queue)->t += (*node)->t;
3345
0
    }
3346
0
    (*node)->next = NULL;
3347
0
    coap_log_debug("** %s: mid=0x%04x: removed (7)\n",
3348
0
                   coap_session_str(session), (*node)->id);
3349
0
    if ((*node)->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3350
0
      session->con_active--;
3351
0
      if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3352
        /* Flush out any entries on session->delayqueue */
3353
0
        coap_session_connected(session);
3354
0
    }
3355
0
    return 1;
3356
0
  }
3357
3358
  /* search token in queue to remove (only first occurrence will be removed) */
3359
0
  q = *queue;
3360
0
  do {
3361
0
    p = q;
3362
0
    q = q->next;
3363
0
  } while (q && (session != q->session ||
3364
0
                 !(!token || coap_binary_equal(&q->pdu->actual_token, token))));
3365
3366
0
  if (q) {                        /* found token */
3367
0
    p->next = q->next;
3368
0
    if (p->next) {                /* must update relative time of p->next */
3369
0
      p->next->t += q->t;
3370
0
    }
3371
0
    q->next = NULL;
3372
0
    *node = q;
3373
0
    coap_log_debug("** %s: mid=0x%04x: removed (8)\n",
3374
0
                   coap_session_str(session), (*node)->id);
3375
0
    if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3376
0
      session->con_active--;
3377
0
      if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3378
        /* Flush out any entries on session->delayqueue */
3379
0
        coap_session_connected(session);
3380
0
    }
3381
0
    return 1;
3382
0
  }
3383
3384
0
  return 0;
3385
3386
0
}
3387
3388
void
3389
coap_cancel_session_messages(coap_context_t *context, coap_session_t *session,
3390
995
                             coap_nack_reason_t reason) {
3391
995
  coap_queue_t *p, *q;
3392
3393
995
  while (context->sendqueue && context->sendqueue->session == session) {
3394
0
    q = context->sendqueue;
3395
0
    context->sendqueue = q->next;
3396
0
    coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
3397
0
                   coap_session_str(session), q->id);
3398
0
    if (q->pdu->type == COAP_MESSAGE_CON) {
3399
0
      coap_handle_nack(session, q->pdu, reason, q->id);
3400
0
    }
3401
0
    coap_delete_node_lkd(q);
3402
0
  }
3403
3404
995
  if (!context->sendqueue)
3405
995
    return;
3406
3407
0
  p = context->sendqueue;
3408
0
  q = p->next;
3409
3410
0
  while (q) {
3411
0
    if (q->session == session) {
3412
0
      p->next = q->next;
3413
0
      coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
3414
0
                     coap_session_str(session), q->id);
3415
0
      if (q->pdu->type == COAP_MESSAGE_CON) {
3416
0
        coap_handle_nack(session, q->pdu, reason, q->id);
3417
0
      }
3418
0
      coap_delete_node_lkd(q);
3419
0
      q = p->next;
3420
0
    } else {
3421
0
      p = q;
3422
0
      q = q->next;
3423
0
    }
3424
0
  }
3425
0
}
3426
3427
void
3428
coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
3429
0
                         coap_bin_const_t *token) {
3430
  /* cancel all messages in sendqueue that belong to session
3431
   * and use the specified token */
3432
0
  coap_queue_t **p, *q;
3433
3434
0
  if (!context->sendqueue)
3435
0
    return;
3436
3437
0
  p = &context->sendqueue;
3438
0
  q = *p;
3439
3440
0
  while (q) {
3441
0
    if (q->session == session &&
3442
0
        (!token || coap_binary_equal(&q->pdu->actual_token, token))) {
3443
0
      *p = q->next;
3444
0
      coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
3445
0
                     coap_session_str(session), q->id);
3446
0
      if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
3447
0
        session->con_active--;
3448
0
        if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3449
          /* Flush out any entries on session->delayqueue */
3450
0
          coap_session_connected(session);
3451
0
      }
3452
0
      coap_delete_node_lkd(q);
3453
0
    } else {
3454
0
      p = &(q->next);
3455
0
    }
3456
0
    q = *p;
3457
0
  }
3458
0
}
3459
3460
coap_pdu_t *
3461
coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code,
3462
2.01k
                        coap_opt_filter_t *opts) {
3463
2.01k
  coap_opt_iterator_t opt_iter;
3464
2.01k
  coap_pdu_t *response;
3465
2.01k
  unsigned char type;
3466
3467
2.01k
#if COAP_ERROR_PHRASE_LENGTH > 0
3468
2.01k
  const char *phrase;
3469
2.01k
  if (code != COAP_RESPONSE_CODE(508)) {
3470
2.01k
    phrase = coap_response_phrase(code);
3471
2.01k
  } else {
3472
0
    phrase = NULL;
3473
0
  }
3474
2.01k
#endif
3475
3476
2.01k
  assert(request);
3477
3478
2.01k
  if (request->type != COAP_MESSAGE_NON && request->type != COAP_MESSAGE_CON)
3479
35
    return NULL;
3480
3481
  /* cannot send ACK if original request was not confirmable */
3482
1.97k
  type = request->type == COAP_MESSAGE_CON ?
3483
1.24k
         COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
3484
3485
  /* Now create the response and fill with options and payload data. */
3486
1.97k
  response = coap_pdu_init(type, code, request->mid,
3487
1.97k
                           request->session ?
3488
1.10k
                           coap_session_max_pdu_size_lkd(request->session) : 512);
3489
1.97k
  if (response) {
3490
    /* copy token */
3491
1.97k
    if (request->actual_token.length &&
3492
1.02k
        !coap_add_token(response, request->actual_token.length,
3493
1.02k
                        request->actual_token.s)) {
3494
18
      coap_log_debug("cannot add token to error response\n");
3495
18
      coap_delete_pdu_lkd(response);
3496
18
      return NULL;
3497
18
    }
3498
1.96k
    if (response->code == COAP_RESPONSE_CODE(402)) {
3499
483
      char buf[128];
3500
483
      int first = 1;
3501
483
      int i;
3502
483
      size_t len;
3503
3504
483
#if COAP_ERROR_PHRASE_LENGTH > 0
3505
483
      snprintf(buf, sizeof(buf), "%s", phrase ? phrase : "");
3506
#else
3507
      buf[0] = '\000';
3508
#endif
3509
      /* copy all reported options into diagnostic message */
3510
3.38k
      for (i = COAP_OPT_FILTER_SHORT - 1; i >= 0; i--) {
3511
2.89k
        if (opts->mask & (1 << (COAP_OPT_FILTER_LONG + i))) {
3512
535
          len = strlen(buf);
3513
535
          snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3514
535
                   opts->short_opts[i]);
3515
535
          first = 0;
3516
535
        }
3517
2.89k
      }
3518
1.44k
      for (i = COAP_OPT_FILTER_LONG - 1; i >= 0; i--) {
3519
966
        if (opts->mask & (1 << i)) {
3520
96
          len = strlen(buf);
3521
96
          snprintf(&buf[len], sizeof(buf) - len, "%s%d", first ? " " : ",",
3522
96
                   opts->long_opts[i]);
3523
96
          first = 0;
3524
96
        }
3525
966
      }
3526
483
      coap_add_data(response, (size_t)strlen(buf), (const uint8_t *)buf);
3527
1.47k
    } else if (opts && opts->mask) {
3528
0
      coap_opt_t *option;
3529
3530
      /* copy all options */
3531
0
      coap_option_iterator_init(request, &opt_iter, opts);
3532
0
      while ((option = coap_option_next(&opt_iter))) {
3533
0
        coap_add_option_internal(response, opt_iter.number,
3534
0
                                 coap_opt_length(option),
3535
0
                                 coap_opt_value(option));
3536
0
      }
3537
0
#if COAP_ERROR_PHRASE_LENGTH > 0
3538
0
      if (phrase)
3539
0
        coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3540
1.47k
    } else {
3541
      /* note that diagnostic messages do not need a Content-Format option. */
3542
1.47k
      if (phrase)
3543
1.47k
        coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
3544
1.47k
#endif
3545
1.47k
    }
3546
1.96k
  }
3547
3548
1.96k
  return response;
3549
1.97k
}
3550
3551
#if COAP_SERVER_SUPPORT
3552
#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
3553
3554
static void
3555
28
free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
3556
28
  coap_delete_string(app_ptr);
3557
28
}
3558
3559
/*
3560
 * Caution: As this handler is in libcoap space, it is called with
3561
 * context locked.
3562
 */
3563
static void
3564
hnd_get_wellknown_lkd(coap_resource_t *resource,
3565
                      coap_session_t *session,
3566
                      const coap_pdu_t *request,
3567
                      const coap_string_t *query,
3568
78
                      coap_pdu_t *response) {
3569
78
  size_t len = 0;
3570
78
  coap_string_t *data_string = NULL;
3571
78
  coap_print_status_t result = 0;
3572
78
  size_t wkc_len = 0;
3573
78
  uint8_t buf[4];
3574
3575
  /*
3576
   * Quick hack to determine the size of the resource descriptions for
3577
   * .well-known/core.
3578
   */
3579
78
  result = coap_print_wellknown_lkd(session->context, buf, &wkc_len, UINT_MAX, query);
3580
78
  if (result & COAP_PRINT_STATUS_ERROR) {
3581
0
    coap_log_warn("cannot determine length of /.well-known/core\n");
3582
0
    goto error;
3583
0
  }
3584
3585
78
  if (wkc_len > 0) {
3586
28
    data_string = coap_new_string(wkc_len);
3587
28
    if (!data_string)
3588
0
      goto error;
3589
3590
28
    len = wkc_len;
3591
28
    result = coap_print_wellknown_lkd(session->context, data_string->s, &len, 0, query);
3592
28
    if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
3593
0
      coap_log_debug("coap_print_wellknown failed\n");
3594
0
      goto error;
3595
0
    }
3596
28
    assert(len <= (size_t)wkc_len);
3597
28
    data_string->length = len;
3598
3599
28
    if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
3600
10
      if (!coap_insert_option(response, COAP_OPTION_CONTENT_FORMAT,
3601
10
                              coap_encode_var_safe(buf, sizeof(buf),
3602
10
                                                   COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf)) {
3603
0
        goto error;
3604
0
      }
3605
10
      if (response->used_size + len + 1 > response->max_size) {
3606
        /*
3607
         * Data does not fit into a packet and no libcoap block support
3608
         * +1 for end of options marker
3609
         */
3610
0
        coap_log_debug(".well-known/core: truncating data length to %" PRIuS " from %" PRIuS "\n",
3611
0
                       len, response->max_size  - response->used_size - 1);
3612
0
        len = response->max_size - response->used_size - 1;
3613
0
      }
3614
10
      if (!coap_add_data(response, len, data_string->s)) {
3615
0
        goto error;
3616
0
      }
3617
10
      free_wellknown_response(session, data_string);
3618
18
    } else if (!coap_add_data_large_response_lkd(resource, session, request,
3619
18
                                                 response, query,
3620
18
                                                 COAP_MEDIATYPE_APPLICATION_LINK_FORMAT,
3621
18
                                                 -1, 0, data_string->length,
3622
18
                                                 data_string->s,
3623
18
                                                 free_wellknown_response,
3624
18
                                                 data_string)) {
3625
0
      goto error_released;
3626
0
    }
3627
50
  } else {
3628
50
    if (!coap_insert_option(response, COAP_OPTION_CONTENT_FORMAT,
3629
50
                            coap_encode_var_safe(buf, sizeof(buf),
3630
50
                                                 COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf)) {
3631
0
      goto error;
3632
0
    }
3633
50
  }
3634
78
  response->code = COAP_RESPONSE_CODE(205);
3635
78
  return;
3636
3637
0
error:
3638
0
  free_wellknown_response(session, data_string);
3639
0
error_released:
3640
0
  if (response->code == 0) {
3641
    /* set error code 5.03 and remove all options and data from response */
3642
0
    response->code = COAP_RESPONSE_CODE(503);
3643
0
    response->used_size = response->e_token_length;
3644
0
    response->data = NULL;
3645
0
  }
3646
0
}
3647
#endif /* COAP_SERVER_SUPPORT */
3648
3649
/**
3650
 * This function cancels outstanding messages for the session and
3651
 * token specified in @p sent. Any observation relationship for
3652
 * sent->session and the token are removed. Calling this function is
3653
 * required when receiving an RST message (usually in response to a
3654
 * notification) or a GET request with the Observe option set to 1.
3655
 *
3656
 * This function returns @c 0 when the token is unknown with this
3657
 * peer, or a value greater than zero otherwise.
3658
 */
3659
static int
3660
0
coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
3661
0
  int num_cancelled = 0;    /* the number of observers cancelled */
3662
3663
#ifndef COAP_SERVER_SUPPORT
3664
  (void)sent;
3665
#endif /* ! COAP_SERVER_SUPPORT */
3666
0
  (void)context;
3667
3668
0
#if COAP_SERVER_SUPPORT
3669
  /* remove observer for this resource, if any
3670
   * Use token from sent and try to find a matching resource. Uh!
3671
   */
3672
0
  RESOURCES_ITER(context->resources, r) {
3673
0
    coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
3674
0
    num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
3675
0
  }
3676
0
#endif /* COAP_SERVER_SUPPORT */
3677
3678
0
  return num_cancelled;
3679
0
}
3680
3681
#if COAP_SERVER_SUPPORT
3682
/**
3683
 * Internal flags to control the treatment of responses (specifically
3684
 * in presence of the No-Response option).
3685
 */
3686
enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
3687
3688
/*
3689
 * Checks for No-Response option in given @p request and
3690
 * returns @c RESPONSE_DROP if @p response should be suppressed
3691
 * according to RFC 7967.
3692
 *
3693
 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
3694
 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
3695
 * on retrying.
3696
 *
3697
 * Checks if the response code is 0.00 and if the response is confirmable,
3698
 * non-confirmable, or the session is reliable, @c RESPONSE_DROP is also
3699
 * returned.  An Empty confirmable message is a ping, not a response.
3700
 *
3701
 * Multicast response checking is also carried out.
3702
 *
3703
 * NOTE: It is the responsibility of the application to determine whether
3704
 * a delayed separate response should be sent as the original requesting packet
3705
 * containing the No-Response option has long since gone.
3706
 *
3707
 * The value of the No-Response option is encoded as
3708
 * follows:
3709
 *
3710
 * @verbatim
3711
 *  +-------+-----------------------+-----------------------------------+
3712
 *  | Value | Binary Representation |          Description              |
3713
 *  +-------+-----------------------+-----------------------------------+
3714
 *  |   0   |      <empty>          | Interested in all responses.      |
3715
 *  +-------+-----------------------+-----------------------------------+
3716
 *  |   2   |      00000010         | Not interested in 2.xx responses. |
3717
 *  +-------+-----------------------+-----------------------------------+
3718
 *  |   8   |      00001000         | Not interested in 4.xx responses. |
3719
 *  +-------+-----------------------+-----------------------------------+
3720
 *  |  16   |      00010000         | Not interested in 5.xx responses. |
3721
 *  +-------+-----------------------+-----------------------------------+
3722
 * @endverbatim
3723
 *
3724
 * @param request  The CoAP request to check for the No-Response option.
3725
 *                 This parameter must not be NULL.
3726
 * @param response The response that is potentially suppressed.
3727
 *                 This parameter must not be NULL.
3728
 * @param session  The session this request/response are associated with.
3729
 *                 This parameter must not be NULL.
3730
 * @return RESPONSE_DEFAULT when no special treatment is requested,
3731
 *         RESPONSE_DROP    when the response must be discarded, or
3732
 *         RESPONSE_SEND    when the response must be sent.
3733
 */
3734
static enum respond_t
3735
no_response(coap_pdu_t *request, coap_pdu_t *response,
3736
837
            coap_session_t *session, coap_resource_t *resource) {
3737
837
  coap_opt_t *nores;
3738
837
  coap_opt_iterator_t opt_iter;
3739
837
  unsigned int val = 0;
3740
3741
837
  assert(request);
3742
837
  assert(response);
3743
3744
837
  if (COAP_RESPONSE_CLASS(response->code) > 0) {
3745
827
    nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
3746
3747
827
    if (nores) {
3748
22
      val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
3749
3750
      /* The response should be dropped when the bit corresponding to
3751
       * the response class is set (cf. table in function
3752
       * documentation). When a No-Response option is present and the
3753
       * bit is not set, the sender explicitly indicates interest in
3754
       * this response. */
3755
22
      if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
3756
        /* Should be dropping the response */
3757
4
        if (response->type == COAP_MESSAGE_ACK &&
3758
1
            COAP_PROTO_NOT_RELIABLE(session->proto)) {
3759
          /* Still need to ACK the request */
3760
1
          response->code = 0;
3761
          /* Remove token/data from piggybacked acknowledgment PDU */
3762
1
          response->actual_token.length = 0;
3763
1
          response->e_token_length = 0;
3764
1
          response->used_size = 0;
3765
1
          response->data = NULL;
3766
1
          return RESPONSE_SEND;
3767
3
        } else {
3768
3
          return RESPONSE_DROP;
3769
3
        }
3770
18
      } else {
3771
        /* True for mcast as well RFC7967 2.1 */
3772
18
        return RESPONSE_SEND;
3773
18
      }
3774
805
    } else if (resource && session->context->mcast_per_resource &&
3775
0
               coap_is_mcast(&session->addr_info.local)) {
3776
      /* Handle any mcast suppression specifics if no NoResponse option */
3777
0
      if ((resource->flags &
3778
0
           COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX) &&
3779
0
          COAP_RESPONSE_CLASS(response->code) == 2) {
3780
0
        return RESPONSE_DROP;
3781
0
      } else if ((resource->flags &
3782
0
                  COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05) &&
3783
0
                 response->code == COAP_RESPONSE_CODE(205)) {
3784
0
        if (response->data == NULL)
3785
0
          return RESPONSE_DROP;
3786
0
      } else if ((resource->flags &
3787
0
                  COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX) == 0 &&
3788
0
                 COAP_RESPONSE_CLASS(response->code) == 4) {
3789
0
        return RESPONSE_DROP;
3790
0
      } else if ((resource->flags &
3791
0
                  COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX) == 0 &&
3792
0
                 COAP_RESPONSE_CLASS(response->code) == 5) {
3793
0
        return RESPONSE_DROP;
3794
0
      }
3795
0
    }
3796
827
  } else if (COAP_PDU_IS_EMPTY(response) &&
3797
10
             (response->type == COAP_MESSAGE_NON ||
3798
5
              response->type == COAP_MESSAGE_CON ||
3799
5
              COAP_PROTO_RELIABLE(session->proto))) {
3800
    /* Response is 0.00, and this is reliable, non-confirmable, or a separate
3801
     * (confirmable) response.  An Empty CON is a ping (RFC 7252 4.2), not a
3802
     * response, and the PDU still has the request's token attached, which
3803
     * RFC 7252 4.1 does not allow.  A CON would then get retransmitted up to
3804
     * MAX_RETRANSMIT times. */
3805
5
    return RESPONSE_DROP;
3806
5
  }
3807
3808
  /*
3809
   * Do not send error responses for requests that were received via
3810
   * IP multicast.  RFC7252 8.1
3811
   */
3812
3813
810
  if (coap_is_mcast(&session->addr_info.local)) {
3814
0
    if (request->type == COAP_MESSAGE_NON &&
3815
0
        response->type == COAP_MESSAGE_RST)
3816
0
      return RESPONSE_DROP;
3817
3818
0
    if ((!resource || session->context->mcast_per_resource == 0) &&
3819
0
        COAP_RESPONSE_CLASS(response->code) > 2)
3820
0
      return RESPONSE_DROP;
3821
0
  }
3822
3823
  /* Default behavior applies when we are not dealing with a response
3824
   * (class == 0) or the request did not contain a No-Response option.
3825
   */
3826
810
  return RESPONSE_DEFAULT;
3827
810
}
3828
3829
static coap_str_const_t coap_default_uri_wellknown = {
3830
  sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
3831
  (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
3832
};
3833
3834
/* Initialized in coap_startup() */
3835
static coap_resource_t resource_uri_wellknown;
3836
3837
static void
3838
handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu,
3839
837
               coap_pdu_t *orig_pdu) {
3840
837
  coap_method_handler_t h = NULL;
3841
837
  coap_pdu_t *response = NULL;
3842
837
  coap_opt_filter_t opt_filter;
3843
837
  coap_resource_t *resource = NULL;
3844
  /* The respond field indicates whether a response must be treated
3845
   * specially due to a No-Response option that declares disinterest
3846
   * or interest in a specific response class. DEFAULT indicates that
3847
   * No-Response has not been specified. */
3848
837
  enum respond_t respond = RESPONSE_DEFAULT;
3849
837
  coap_opt_iterator_t opt_iter;
3850
837
  coap_opt_t *opt;
3851
837
  int is_proxy_uri = 0;
3852
837
  int is_proxy_scheme = 0;
3853
837
  int hop_limit = -1;
3854
837
  int resp = 0;
3855
837
  coap_string_t *query = NULL;
3856
837
  coap_opt_t *observe = NULL;
3857
837
  coap_string_t *uri_path = NULL;
3858
837
  int observe_action = COAP_OBSERVE_CANCEL;
3859
837
  coap_block_b_t block;
3860
837
  int added_block = 0;
3861
837
  coap_lg_srcv_t *free_lg_srcv = NULL;
3862
837
#if COAP_Q_BLOCK_SUPPORT
3863
837
  int lg_xmit_ctrl = 0;
3864
837
#endif /* COAP_Q_BLOCK_SUPPORT */
3865
837
#if COAP_ASYNC_SUPPORT
3866
837
  coap_async_t *async;
3867
837
#endif /* COAP_ASYNC_SUPPORT */
3868
3869
837
#if COAP_ASYNC_SUPPORT
3870
837
  async = coap_find_async_lkd(session, pdu->actual_token);
3871
837
  if (async) {
3872
0
    coap_tick_t now;
3873
3874
0
    coap_ticks(&now);
3875
0
    if (async->delay == 0 || async->delay > now) {
3876
      /* re-transmit missing ACK (only if CON) */
3877
0
      coap_log_info("Retransmit async response\n");
3878
0
      coap_send_ack_lkd(session, pdu);
3879
      /* and do not pass on to the upper layers */
3880
0
      return;
3881
0
    }
3882
0
  }
3883
837
#endif /* COAP_ASYNC_SUPPORT */
3884
3885
837
  coap_option_filter_clear(&opt_filter);
3886
837
  if (!(context->unknown_resource && context->unknown_resource->is_reverse_proxy)) {
3887
837
    opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
3888
837
    if (opt) {
3889
4
      opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3890
4
      if (!opt) {
3891
3
        coap_log_debug("Proxy-Scheme requires Uri-Host\n");
3892
3
        resp = 402;
3893
3
        goto fail_response;
3894
3
      }
3895
1
      is_proxy_scheme = 1;
3896
1
    }
3897
3898
834
    opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
3899
834
    if (opt)
3900
7
      is_proxy_uri = 1;
3901
834
  }
3902
3903
834
  if (is_proxy_scheme || is_proxy_uri) {
3904
8
    coap_uri_t uri;
3905
3906
8
    if (!context->proxy_uri_resource) {
3907
      /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3908
8
      coap_log_debug("Proxy-%s support not configured\n",
3909
8
                     is_proxy_scheme ? "Scheme" : "Uri");
3910
8
      resp = 505;
3911
8
      goto fail_response;
3912
8
    }
3913
0
    if (((size_t)pdu->code - 1 <
3914
0
         (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
3915
0
        !(context->proxy_uri_resource->handler[pdu->code - 1])) {
3916
      /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3917
0
      coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
3918
0
                     is_proxy_scheme ? "Scheme" : "Uri",
3919
0
                     pdu->code/100,  pdu->code%100);
3920
0
      resp = 505;
3921
0
      goto fail_response;
3922
0
    }
3923
3924
    /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
3925
0
    if (is_proxy_uri) {
3926
0
      if (coap_split_proxy_uri(coap_opt_value(opt),
3927
0
                               coap_opt_length(opt), &uri) < 0) {
3928
        /* Need to return a 5.05 RFC7252 Section 5.7.2 */
3929
0
        coap_log_debug("Proxy-URI not decodable\n");
3930
0
        resp = 505;
3931
0
        goto fail_response;
3932
0
      }
3933
0
    } else {
3934
0
      memset(&uri, 0, sizeof(uri));
3935
0
      opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
3936
0
      if (opt) {
3937
0
        uri.host.length = coap_opt_length(opt);
3938
0
        uri.host.s = coap_opt_value(opt);
3939
0
      } else
3940
0
        uri.host.length = 0;
3941
0
    }
3942
3943
0
    resource = context->proxy_uri_resource;
3944
0
    if (uri.host.length && resource->proxy_name_count &&
3945
0
        resource->proxy_name_list) {
3946
0
      size_t i;
3947
3948
0
      if (resource->proxy_name_count == 1 &&
3949
0
          resource->proxy_name_list[0]->length == 0) {
3950
        /* If proxy_name_list[0] is zero length, then this is the endpoint */
3951
0
        i = 0;
3952
0
      } else {
3953
0
        for (i = 0; i < resource->proxy_name_count; i++) {
3954
0
          if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3955
0
            break;
3956
0
          }
3957
0
        }
3958
0
      }
3959
0
      if (i != resource->proxy_name_count) {
3960
        /* This server is hosting the proxy connection endpoint */
3961
0
        if (pdu->crit_opt) {
3962
          /* Cannot handle critical option */
3963
0
          pdu->crit_opt = 0;
3964
0
          resp = 402;
3965
0
          resource = NULL;
3966
0
          goto fail_response;
3967
0
        }
3968
0
        is_proxy_uri = 0;
3969
0
        is_proxy_scheme = 0;
3970
0
      }
3971
0
    }
3972
0
    resource = NULL;
3973
0
  }
3974
834
  assert(resource == NULL);
3975
3976
826
  opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
3977
826
  if (opt) {
3978
19
    hop_limit =
3979
19
        coap_decode_var_bytes(coap_opt_value(opt), coap_opt_length(opt));
3980
19
    if (hop_limit < 1 || hop_limit > 255) {
3981
      /* Need to return a 4.00 RFC8768 Section 3 */
3982
3
      coap_log_info("Invalid Hop Limit\n");
3983
3
      resp = 400;
3984
3
      goto fail_response;
3985
3
    }
3986
19
  }
3987
3988
823
  uri_path = coap_get_uri_path(pdu);
3989
823
  if (!uri_path) {
3990
8
    resp = 402;
3991
8
    goto fail_response;
3992
8
  }
3993
3994
815
  if (!is_proxy_uri && !is_proxy_scheme) {
3995
    /* try to find the resource from the request URI */
3996
815
    coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
3997
815
    resource = coap_get_resource_from_uri_path_lkd(context, &uri_path_c);
3998
815
  }
3999
4000
815
  if ((resource == NULL) || (resource->is_unknown == 1) ||
4001
633
      (resource->is_proxy_uri == 1)) {
4002
    /* The resource was not found or there is an unexpected match against the
4003
     * resource defined for handling unknown or proxy URIs.
4004
     */
4005
633
    if (resource != NULL)
4006
      /* Close down unexpected match */
4007
0
      resource = NULL;
4008
    /*
4009
     * Check if the request URI happens to be the well-known URI, or if the
4010
     * unknown resource handler is defined, a PUT or optionally other methods,
4011
     * if configured, for the unknown handler.
4012
     *
4013
     * if a PROXY URI/Scheme request and proxy URI handler defined, call the
4014
     *  proxy URI handler.
4015
     *
4016
     * else if unknown URI handler defined and COAP_RESOURCE_HANDLE_WELLKNOWN_CORE
4017
     *  set, call the unknown URI handler with any unknown URI (including
4018
     *  .well-known/core) if the appropriate method is defined.
4019
     *
4020
     * else if well-known URI generate a default response.
4021
     *
4022
     * else if unknown URI handler defined, call the unknown
4023
     *  URI handler (to allow for potential generation of resource
4024
     *  [RFC7272 5.8.3]) if the appropriate method is defined.
4025
     *
4026
     * else if DELETE return 2.02 (RFC7252: 5.8.4.  DELETE).
4027
     *
4028
     * else return 4.04.
4029
     */
4030
4031
633
    if (is_proxy_uri || is_proxy_scheme) {
4032
0
      resource = context->proxy_uri_resource;
4033
633
    } else if (context->unknown_resource != NULL &&
4034
0
               context->unknown_resource->flags & COAP_RESOURCE_HANDLE_WELLKNOWN_CORE &&
4035
0
               ((size_t)pdu->code - 1 <
4036
0
                (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
4037
0
               (context->unknown_resource->handler[pdu->code - 1])) {
4038
0
      resource = context->unknown_resource;
4039
633
    } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
4040
      /* request for .well-known/core */
4041
78
      resource = &resource_uri_wellknown;
4042
555
    } else if ((context->unknown_resource != NULL) &&
4043
0
               ((size_t)pdu->code - 1 <
4044
0
                (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
4045
0
               (context->unknown_resource->handler[pdu->code - 1])) {
4046
      /*
4047
       * The unknown_resource can be used to handle undefined resources
4048
       * for a PUT request and can support any other registered handler
4049
       * defined for it
4050
       * Example set up code:-
4051
       *   r = coap_resource_unknown_init(hnd_put_unknown);
4052
       *   coap_register_request_handler(r, COAP_REQUEST_POST,
4053
       *                                 hnd_post_unknown);
4054
       *   coap_register_request_handler(r, COAP_REQUEST_GET,
4055
       *                                 hnd_get_unknown);
4056
       *   coap_register_request_handler(r, COAP_REQUEST_DELETE,
4057
       *                                 hnd_delete_unknown);
4058
       *   coap_add_resource(ctx, r);
4059
       *
4060
       * Note: It is not possible to observe the unknown_resource, a separate
4061
       *       resource must be created (by PUT or POST) which has a GET
4062
       *       handler to be observed
4063
       */
4064
0
      resource = context->unknown_resource;
4065
555
    } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
4066
      /*
4067
       * Request for DELETE on non-existent resource (RFC7252: 5.8.4.  DELETE)
4068
       */
4069
20
      coap_log_debug("request for unknown resource '%*.*s',"
4070
20
                     " return 2.02\n",
4071
20
                     (int)uri_path->length,
4072
20
                     (int)uri_path->length,
4073
20
                     uri_path->s);
4074
20
      resp = 202;
4075
20
      goto fail_response;
4076
535
    } else if (context->dyn_create_handler != NULL) {
4077
0
      resource = coap_add_dynamic_resource(session, pdu);
4078
0
      if (!resource) {
4079
0
        resp = 406;
4080
0
        goto fail_response;
4081
0
      }
4082
535
    } else { /* request for any another resource, return 4.04 */
4083
4084
535
      coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
4085
535
                     (int)uri_path->length, (int)uri_path->length, uri_path->s);
4086
535
      resp = 404;
4087
535
      goto fail_response;
4088
535
    }
4089
4090
633
  }
4091
4092
260
  coap_resource_reference_lkd(resource);
4093
4094
260
  if (hop_limit >= 0 &&
4095
0
      (is_proxy_scheme || is_proxy_uri ||
4096
0
       (resource == context->unknown_resource && resource->is_reverse_proxy))) {
4097
0
    uint8_t buf[4];
4098
4099
0
    if (hop_limit == 1) {
4100
0
      coap_log_info("Hop Limit expired\n");
4101
0
      if (resource == context->unknown_resource && resource->is_reverse_proxy) {
4102
        /* Need to hide this is a reverse proxy */
4103
0
        resp = 404;
4104
0
      } else {
4105
        /* coap_send_internal() will fill in the IP address for us */
4106
0
        resp = 508;
4107
0
      }
4108
0
      goto fail_response;
4109
0
    }
4110
    /* hop_limit == 0 or > 255 checked earlier */
4111
0
    hop_limit--;
4112
0
    coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
4113
0
                       coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
4114
0
                       buf);
4115
0
  }
4116
4117
260
#if COAP_OSCORE_SUPPORT
4118
260
  if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
4119
0
    coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
4120
0
                   (int)uri_path->length, (int)uri_path->length, uri_path->s);
4121
0
    resp = 401;
4122
0
    goto fail_response;
4123
0
  }
4124
260
#endif /* COAP_OSCORE_SUPPORT */
4125
260
  if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
4126
    /* Check for existing resource and If-Non-Match */
4127
260
    opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
4128
260
    if (opt) {
4129
0
      resp = 412;
4130
0
      goto fail_response;
4131
0
    }
4132
260
  }
4133
4134
  /* the resource was found, check if there is a registered handler */
4135
260
  if ((size_t)pdu->code - 1 <
4136
260
      sizeof(resource->handler) / sizeof(coap_method_handler_t))
4137
260
    h = resource->handler[pdu->code - 1];
4138
4139
260
  if (h == NULL) {
4140
70
    resp = 405;
4141
70
    goto fail_response;
4142
70
  }
4143
190
  if (pdu->code == COAP_REQUEST_CODE_FETCH) {
4144
0
    if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) == NULL) {
4145
0
      opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4146
0
      if (opt == NULL) {
4147
        /* RFC 8132 2.3.1 */
4148
0
        resp = 415;
4149
0
        goto fail_response;
4150
0
      }
4151
0
    }
4152
0
  }
4153
190
  if (context->mcast_per_resource &&
4154
0
      (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
4155
0
      coap_is_mcast(&session->addr_info.local)) {
4156
0
    resp = 405;
4157
0
    goto fail_response;
4158
0
  }
4159
4160
190
  if (pdu->type == COAP_MESSAGE_CON) {
4161
167
    response = coap_pdu_init(COAP_MESSAGE_ACK, 0, pdu->mid,
4162
167
                             coap_session_max_pdu_size_lkd(session));
4163
167
  } else {
4164
23
    response = coap_pdu_init(COAP_MESSAGE_NON, 0, coap_new_message_id_lkd(session),
4165
23
                             coap_session_max_pdu_size_lkd(session));
4166
23
  }
4167
190
  if (!response) {
4168
0
    coap_log_err("could not create response PDU\n");
4169
0
    resp = 500;
4170
0
    goto fail_response;
4171
0
  }
4172
190
  response->session = session;
4173
190
#if COAP_ASYNC_SUPPORT
4174
  /* If handling a separate response, need CON, not ACK response */
4175
190
  if (async && pdu->type == COAP_MESSAGE_CON)
4176
0
    response->type = COAP_MESSAGE_CON;
4177
190
#endif /* COAP_ASYNC_SUPPORT */
4178
  /* A lot of the reliable code assumes type is CON */
4179
190
  if (COAP_PROTO_RELIABLE(session->proto) && response->type != COAP_MESSAGE_CON)
4180
0
    response->type = COAP_MESSAGE_CON;
4181
4182
190
  if (!coap_add_token(response, pdu->actual_token.length,
4183
190
                      pdu->actual_token.s)) {
4184
0
    resp = 500;
4185
0
    goto fail_response;
4186
0
  }
4187
4188
  /*
4189
   * RFC7959 2.2: the SZX value 7 "is reserved, i.e., MUST NOT be sent and
4190
   * MUST lead to a 4.00 Bad Request response code upon reception in a
4191
   * request".  SZX 7 is only meaningful as the BERT escape (RFC8323 6),
4192
   * which needs a reliable transport with BERT negotiated in both CSMs.
4193
   * Anywhere else it must be rejected here: coap_get_block_b() reports a
4194
   * reserved SZX as "no Block option present", which is indistinguishable
4195
   * further down from a request that never carried one.
4196
   */
4197
190
  if (COAP_PROTO_NOT_RELIABLE(session->proto) ||
4198
190
      !(session->csm_bert_rem_support && session->csm_bert_loc_support)) {
4199
190
    static const coap_option_num_t block_nums[] = {
4200
190
      COAP_OPTION_BLOCK1, COAP_OPTION_BLOCK2, COAP_OPTION_Q_BLOCK1, COAP_OPTION_Q_BLOCK2
4201
190
    };
4202
190
    size_t bn;
4203
4204
950
    for (bn = 0; bn < sizeof(block_nums)/sizeof(block_nums[0]); bn++) {
4205
760
      coap_opt_t *block_opt = coap_check_option(pdu, block_nums[bn], &opt_iter);
4206
4207
760
      if (block_opt && COAP_OPT_BLOCK_SZX(block_opt) == 7) {
4208
0
        coap_log_debug("request: reserved Block SZX 7 (RFC7959 2.2)\n");
4209
0
        resp = 400;
4210
0
        goto fail_response;
4211
0
      }
4212
760
    }
4213
190
  }
4214
4215
190
  query = coap_get_query(pdu);
4216
4217
  /* check for Observe option RFC7641 and RFC8132 */
4218
190
  if (resource->observable &&
4219
61
      (pdu->code == COAP_REQUEST_CODE_GET ||
4220
61
       pdu->code == COAP_REQUEST_CODE_FETCH)) {
4221
61
    observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
4222
61
  }
4223
4224
  /*
4225
   * See if blocks need to be aggregated or next requests sent off
4226
   * before invoking application request handler
4227
   */
4228
190
  if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4229
58
    uint32_t block_mode = session->block_mode;
4230
4231
58
    if (observe ||
4232
58
        resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
4233
0
      session->block_mode |= COAP_BLOCK_SINGLE_BODY;
4234
58
    if (coap_handle_request_put_block(context, session, pdu, response,
4235
58
                                      resource, observe,
4236
58
                                      &added_block, &free_lg_srcv)) {
4237
3
      session->block_mode = block_mode;
4238
3
      goto skip_handler;
4239
3
    }
4240
55
    session->block_mode = block_mode;
4241
4242
55
    if (coap_handle_request_send_block(session, pdu, response, resource,
4243
55
                                       query)) {
4244
0
#if COAP_Q_BLOCK_SUPPORT
4245
0
      lg_xmit_ctrl = 1;
4246
0
#endif /* COAP_Q_BLOCK_SUPPORT */
4247
0
      goto skip_handler;
4248
0
    }
4249
55
  }
4250
4251
187
  if (observe) {
4252
56
    observe_action =
4253
56
        coap_decode_var_bytes(coap_opt_value(observe),
4254
56
                              coap_opt_length(observe));
4255
4256
56
    if (observe_action == COAP_OBSERVE_ESTABLISH) {
4257
28
      coap_subscription_t *subscription;
4258
4259
28
      if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
4260
0
        if (block.num != 0) {
4261
0
          response->code = COAP_RESPONSE_CODE(400);
4262
0
          goto skip_handler;
4263
0
        }
4264
0
#if COAP_Q_BLOCK_SUPPORT
4265
28
      } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
4266
28
                                  &block)) {
4267
0
        if (block.num != 0) {
4268
0
          response->code = COAP_RESPONSE_CODE(400);
4269
0
          goto skip_handler;
4270
0
        }
4271
0
#endif /* COAP_Q_BLOCK_SUPPORT */
4272
0
      }
4273
28
      subscription = coap_add_observer(resource, session, &pdu->actual_token,
4274
28
                                       pdu);
4275
28
      if (subscription) {
4276
28
        uint8_t buf[4];
4277
4278
28
        coap_touch_observer(context, session, &pdu->actual_token);
4279
28
        coap_insert_option(response, COAP_OPTION_OBSERVE,
4280
28
                           coap_encode_var_safe(buf, sizeof(buf),
4281
28
                                                resource->observe),
4282
28
                           buf);
4283
28
      }
4284
28
    } else if (observe_action == COAP_OBSERVE_CANCEL) {
4285
28
      coap_delete_observer_request(resource, session, &pdu->actual_token, pdu, free_lg_srcv != NULL);
4286
28
    } else {
4287
0
      coap_log_info("observe: unexpected action %d\n", observe_action);
4288
0
    }
4289
56
  }
4290
4291
187
#if COAP_WITH_OBSERVE_PERSIST
4292
  /* If we are maintaining Observe persist */
4293
187
  if (resource == context->unknown_resource) {
4294
0
    context->unknown_pdu = pdu;
4295
0
    context->unknown_session = session;
4296
0
  } else
4297
187
    context->unknown_pdu = NULL;
4298
187
#endif /* COAP_WITH_OBSERVE_PERSIST */
4299
4300
  /*
4301
   * Call the request handler with everything set up
4302
   */
4303
187
  if (resource == &resource_uri_wellknown) {
4304
    /* Leave context locked */
4305
78
    coap_log_debug("call handler for pseudo resource '%*.*s' (3)\n",
4306
78
                   (int)resource->uri_path->length, (int)resource->uri_path->length,
4307
78
                   resource->uri_path->s);
4308
78
    h(resource, session, pdu, query, response);
4309
78
    if (COAP_RESPONSE_CLASS(response->code) == 2 && response->data == NULL &&
4310
50
        coap_is_mcast(&session->addr_info.local)) {
4311
0
      goto drop_it_debug;
4312
0
    }
4313
109
  } else {
4314
109
    coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
4315
109
                   (int)resource->uri_path->length, (int)resource->uri_path->length,
4316
109
                   resource->uri_path->s);
4317
109
    if (resource->flags & COAP_RESOURCE_SAFE_REQUEST_HANDLER) {
4318
0
      coap_lock_callback_release(h(resource, session, pdu, query, response),
4319
                                 /* context is being freed off */
4320
0
                                 goto finish);
4321
109
    } else {
4322
109
      coap_lock_specific_callback_release(&resource->lock,
4323
109
                                          h(resource, session, pdu, query, response),
4324
                                          /* context is being freed off */
4325
109
                                          goto finish);
4326
109
    }
4327
109
  }
4328
4329
  /* Check validity of response code */
4330
187
  if (!coap_check_code_class(session, response)) {
4331
0
    coap_log_warn("handle_request: Invalid PDU response code (%d.%02d)\n",
4332
0
                  COAP_RESPONSE_CLASS(response->code),
4333
0
                  response->code & 0x1f);
4334
0
    goto drop_it_no_debug;
4335
0
  }
4336
4337
  /* Check correct content type returned by application */
4338
187
  if (response->code != 0 && (opt = coap_check_option(pdu, COAP_OPTION_ACCEPT, &opt_iter)) &&
4339
3
      !(COAP_RESPONSE_CLASS(response->code) == 4 || COAP_RESPONSE_CLASS(response->code) == 5)) {
4340
3
    coap_opt_t *ropt = coap_check_option(response, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
4341
4342
3
    if (!ropt) {
4343
0
      coap_add_option_internal(response, COAP_OPTION_CONTENT_FORMAT,
4344
0
                               coap_opt_length(opt), coap_opt_value(opt));
4345
3
    } else if (coap_opt_length(opt) != coap_opt_length(ropt) ||
4346
2
               memcmp(coap_opt_value(opt), coap_opt_value(ropt), coap_opt_length(opt)) != 0) {
4347
2
      coap_show_pdu(COAP_LOG_DEBUG, response);
4348
2
      coap_log_debug("handle_request: response: Invalid Content-Format\n");
4349
      /* Need to convert response to 4.06 as incorrect content type */
4350
2
      response->code = COAP_RESPONSE_CODE(406);
4351
2
      response->used_size = response->e_token_length;
4352
2
      response->data = NULL;
4353
2
      response->max_opt = 0;
4354
2
      coap_add_option_internal(response, COAP_OPTION_ACCEPT,
4355
2
                               coap_opt_length(opt),
4356
2
                               coap_opt_value(opt));
4357
2
      coap_add_data(response, sizeof("Not Acceptable")-1, (const uint8_t *)"Not Acceptable");
4358
2
    }
4359
3
  }
4360
4361
  /* Check if lg_xmit generated and update PDU code if so */
4362
187
  coap_check_code_lg_xmit(session, pdu, response, resource, query);
4363
4364
187
  if (free_lg_srcv) {
4365
    /* Check to see if the server is doing a 4.01 + Echo response */
4366
0
    if (response->code ==  COAP_RESPONSE_CODE(401) &&
4367
0
        coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
4368
      /* Need to keep lg_srcv around for client's response */
4369
0
    } else {
4370
0
      coap_lg_srcv_t *lg_srcv;
4371
      /*
4372
       * Need to check free_lg_srcv still exists in case of error or timing window
4373
       */
4374
0
      LL_FOREACH(session->lg_srcv, lg_srcv) {
4375
0
        if (lg_srcv == free_lg_srcv) {
4376
0
#if COAP_Q_BLOCK_SUPPORT
4377
0
          if (lg_srcv->block_option == COAP_OPTION_Q_BLOCK1) {
4378
0
            coap_tick_t adjust;
4379
4380
            /* cache the lg_srcv for 1 second */
4381
0
            if (COAP_NON_RECEIVE_TIMEOUT_TICKS(session) >= COAP_TICKS_PER_SECOND) {
4382
0
              adjust = COAP_NON_RECEIVE_TIMEOUT_TICKS(session) - COAP_TICKS_PER_SECOND;
4383
0
            } else {
4384
0
              adjust = 0;
4385
0
            }
4386
0
            coap_ticks(&free_lg_srcv->rec_blocks.last_seen);
4387
0
            if (free_lg_srcv->rec_blocks.last_seen > adjust) {
4388
0
              free_lg_srcv->rec_blocks.last_seen -= adjust;
4389
0
            }
4390
0
            free_lg_srcv->dont_timeout = 0;
4391
0
            break;
4392
0
          }
4393
0
#endif /* COAP_Q_BLOCK_SUPPORT */
4394
0
          LL_DELETE(session->lg_srcv, free_lg_srcv);
4395
0
          coap_block_delete_lg_srcv(session, free_lg_srcv);
4396
0
          break;
4397
0
        }
4398
0
      }
4399
0
    }
4400
0
  }
4401
187
  if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
4402
    /* Just in case, as there are more to go */
4403
0
    response->code = COAP_RESPONSE_CODE(231);
4404
0
  }
4405
4406
837
skip_handler:
4407
837
  respond = no_response(pdu, response, session, resource);
4408
837
  if (respond != RESPONSE_DROP) {
4409
829
#if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
4410
829
    coap_mid_t mid = pdu->mid;
4411
829
#endif
4412
829
    if (COAP_RESPONSE_CLASS(response->code) != 2) {
4413
634
      if (observe) {
4414
0
        coap_remove_option(response, COAP_OPTION_OBSERVE);
4415
0
      }
4416
634
    }
4417
829
    if (COAP_RESPONSE_CLASS(response->code) > 2) {
4418
628
      if (observe)
4419
0
        coap_delete_observer(resource, session, &pdu->actual_token);
4420
628
      if (response->code != COAP_RESPONSE_CODE(413))
4421
628
        coap_remove_option(response, COAP_OPTION_BLOCK1);
4422
628
    }
4423
4424
    /* If original request contained a token, and the registered
4425
     * application handler made no changes to the response, then
4426
     * this is an empty ACK with a token, which is a malformed
4427
     * PDU */
4428
829
    if ((response->type == COAP_MESSAGE_ACK)
4429
414
        && (response->code == 0)) {
4430
      /* Remove token from otherwise-empty acknowledgment PDU */
4431
6
      response->actual_token.length = 0;
4432
6
      response->e_token_length = 0;
4433
6
      response->used_size = 0;
4434
6
      response->data = NULL;
4435
6
    }
4436
4437
829
    if (!coap_is_mcast(&session->addr_info.local) ||
4438
0
        (context->mcast_per_resource &&
4439
0
         resource &&
4440
829
         (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
4441
      /* No delays to response */
4442
829
#if COAP_Q_BLOCK_SUPPORT
4443
829
      if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
4444
74
          !lg_xmit_ctrl && COAP_RESPONSE_CLASS(response->code) == 2 &&
4445
53
          coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
4446
0
          block.m) {
4447
0
        if (coap_send_q_block2(session, resource, query, pdu->code, block,
4448
0
                               response,
4449
0
                               COAP_SEND_INC_PDU) == COAP_INVALID_MID)
4450
0
          coap_log_debug("cannot send response for mid=0x%x\n", mid);
4451
0
        response = NULL;
4452
0
        goto finish;
4453
0
      }
4454
829
#endif /* COAP_Q_BLOCK_SUPPORT */
4455
829
      if (coap_send_internal(session, response, orig_pdu ? orig_pdu : pdu) == COAP_INVALID_MID) {
4456
430
        coap_log_debug("cannot send response for mid=0x%04x\n", mid);
4457
430
        goto finish;
4458
430
      }
4459
829
    } else {
4460
      /* Need to delay mcast response */
4461
0
      coap_queue_t *node = coap_new_node();
4462
0
      uint8_t r;
4463
0
      coap_tick_t delay;
4464
4465
0
      if (!node) {
4466
0
        coap_log_debug("mcast delay: insufficient memory\n");
4467
0
        goto drop_it_no_debug;
4468
0
      }
4469
0
      if (!coap_pdu_encode_header(response, session->proto)) {
4470
0
        coap_delete_node_lkd(node);
4471
0
        goto drop_it_no_debug;
4472
0
      }
4473
4474
0
      node->id = response->mid;
4475
0
      node->pdu = response;
4476
0
      node->is_mcast = 1;
4477
0
      coap_prng_lkd(&r, sizeof(r));
4478
0
      delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
4479
0
      coap_log_debug("   %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
4480
0
                     coap_session_str(session),
4481
0
                     response->mid,
4482
0
                     (unsigned int)(delay / COAP_TICKS_PER_SECOND),
4483
0
                     (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
4484
0
                                    1000 / COAP_TICKS_PER_SECOND));
4485
0
      node->timeout = (unsigned int)delay;
4486
      /* Use this to delay transmission */
4487
0
      coap_wait_ack(session->context, session, node);
4488
0
    }
4489
829
  } else if (COAP_PDU_IS_EMPTY(response) &&
4490
5
             (response->type == COAP_MESSAGE_NON ||
4491
0
              response->type == COAP_MESSAGE_CON ||
4492
5
              COAP_PROTO_RELIABLE(session->proto))) {
4493
5
    coap_delete_pdu_lkd(response);
4494
5
  } else {
4495
3
drop_it_debug:
4496
3
    coap_log_debug("   %s: mid=0x%04x: response dropped\n",
4497
3
                   coap_session_str(session),
4498
3
                   response->mid);
4499
3
    coap_show_pdu(COAP_LOG_DEBUG, response);
4500
3
drop_it_no_debug:
4501
3
    coap_delete_pdu_lkd(response);
4502
3
  }
4503
407
#if COAP_Q_BLOCK_SUPPORT
4504
407
  if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
4505
0
    if (COAP_PROTO_RELIABLE(session->proto)) {
4506
0
      if (block.m) {
4507
        /* All of the sequence not in yet */
4508
0
        goto finish;
4509
0
      }
4510
0
    } else if (pdu->type == COAP_MESSAGE_NON) {
4511
      /* More to go and not at a payload break */
4512
0
      if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
4513
0
        goto finish;
4514
0
      }
4515
0
    }
4516
0
  }
4517
407
#endif /* COAP_Q_BLOCK_SUPPORT */
4518
4519
837
finish:
4520
837
  if (query)
4521
55
    coap_delete_string(query);
4522
837
  if (resource)
4523
260
    coap_resource_release_lkd(resource);
4524
837
  coap_delete_string(uri_path);
4525
837
  return;
4526
4527
647
fail_response:
4528
647
  coap_delete_pdu_lkd(response);
4529
647
  response =
4530
647
      coap_new_error_response(pdu, COAP_RESPONSE_CODE(resp),
4531
647
                              &opt_filter);
4532
647
  if (response)
4533
647
    goto skip_handler;
4534
0
  if (resource)
4535
0
    coap_resource_release_lkd(resource);
4536
0
  coap_delete_string(uri_path);
4537
0
}
4538
#endif /* COAP_SERVER_SUPPORT */
4539
4540
#if COAP_CLIENT_SUPPORT
4541
/* Call application-specific response handler when available. */
4542
void
4543
coap_call_response_handler(coap_session_t *session,
4544
                           coap_pdu_t *sent, coap_pdu_t *rcvd,
4545
181
                           void *body_data) {
4546
181
  coap_context_t *context = session->context;
4547
181
  coap_response_t ret;
4548
4549
181
#if COAP_PROXY_SUPPORT
4550
181
  if (context->proxy_response_cb) {
4551
0
    coap_proxy_entry_t *proxy_entry;
4552
0
    coap_proxy_req_t *proxy_req = coap_proxy_map_outgoing_request(session,
4553
0
                                  rcvd,
4554
0
                                  &proxy_entry);
4555
4556
0
    if (proxy_req && proxy_req->incoming && !proxy_req->incoming->server_list) {
4557
0
      coap_proxy_process_incoming(session, rcvd, body_data, proxy_req,
4558
0
                                  proxy_entry);
4559
0
      return;
4560
0
    }
4561
0
  }
4562
181
#endif /* COAP_PROXY_SUPPORT */
4563
181
  if (session->doing_send_recv && session->req_token &&
4564
0
      coap_binary_equal(session->req_token, &rcvd->actual_token)) {
4565
    /* processing coap_send_recv() call */
4566
0
    session->resp_pdu = rcvd;
4567
0
    coap_pdu_reference_lkd(rcvd);
4568
    /* Will get freed off when PDU is freed off */
4569
0
    rcvd->data_free = body_data;
4570
0
    coap_send_ack_lkd(session, rcvd);
4571
0
    session->last_con_handler_res = COAP_RESPONSE_OK;
4572
0
    return;
4573
181
  } else if (context->response_cb) {
4574
0
    coap_lock_callback_ret_release(ret,
4575
0
                                   context->response_cb(session,
4576
0
                                                        sent,
4577
0
                                                        rcvd,
4578
0
                                                        rcvd->mid),
4579
                                   /* context is being freed off */
4580
0
                                   return);
4581
181
  } else {
4582
    /*
4583
     * RFC7252 4.2
4584
     * (b) reject the message if the recipient lacks context to process the
4585
     *  message properly
4586
     */
4587
181
    ret = COAP_RESPONSE_FAIL;
4588
181
  }
4589
181
  if (ret == COAP_RESPONSE_FAIL) {
4590
181
    coap_send_rst_lkd(session, rcvd);
4591
181
    session->last_con_handler_res = COAP_RESPONSE_FAIL;
4592
181
  } else {
4593
0
    coap_send_ack_lkd(session, rcvd);
4594
0
    session->last_con_handler_res = COAP_RESPONSE_OK;
4595
0
  }
4596
181
  coap_free_type(COAP_STRING, body_data);
4597
181
}
4598
4599
static void
4600
handle_response(coap_context_t *context, coap_session_t *session,
4601
188
                coap_pdu_t *sent, coap_pdu_t *rcvd) {
4602
4603
  /* Set in case there is a later call to coap_update_token() */
4604
188
  rcvd->session = session;
4605
4606
  /* Check for message duplication */
4607
188
  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
4608
188
    if (rcvd->type == COAP_MESSAGE_CON) {
4609
49
      if (rcvd->mid == session->last_resp_mid) {
4610
        /* Duplicate response: send ACK/RST, but don't process */
4611
0
        if (session->last_con_handler_res == COAP_RESPONSE_OK)
4612
0
          coap_send_ack_lkd(session, rcvd);
4613
0
        else
4614
0
          coap_send_rst_lkd(session, rcvd);
4615
0
        return;
4616
0
      }
4617
139
    } else if (rcvd->type == COAP_MESSAGE_ACK) {
4618
56
      if (rcvd->mid == session->last_resp_mid) {
4619
        /* Duplicate response */
4620
0
        return;
4621
0
      }
4622
56
    }
4623
188
    session->last_resp_mid = rcvd->mid;
4624
188
  }
4625
  /* Check to see if checking out extended token support */
4626
188
  if (session->max_token_checked == COAP_EXT_T_CHECKING &&
4627
0
      session->last_token) {
4628
0
    coap_lg_crcv_t *lg_crcv;
4629
4630
0
    if (!coap_binary_equal(session->last_token, &rcvd->actual_token) ||
4631
0
        rcvd->actual_token.length != session->max_token_size ||
4632
0
        rcvd->code == COAP_RESPONSE_CODE(400) ||
4633
0
        rcvd->code == COAP_RESPONSE_CODE(503)) {
4634
0
      coap_log_debug("Extended Token requested size support not available\n");
4635
0
      session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
4636
0
    } else {
4637
0
      coap_log_debug("Extended Token support available\n");
4638
0
    }
4639
0
    session->max_token_checked = COAP_EXT_T_CHECKED;
4640
    /* Need to remove lg_crcv set up for this test */
4641
0
    lg_crcv = coap_find_lg_crcv(session, rcvd);
4642
0
    if (lg_crcv) {
4643
0
      LL_DELETE(session->lg_crcv, lg_crcv);
4644
0
      coap_block_delete_lg_crcv(session, lg_crcv);
4645
0
    }
4646
0
    coap_send_ack_lkd(session, rcvd);
4647
0
    coap_reset_doing_first(session);
4648
0
    return;
4649
0
  }
4650
188
#if COAP_Q_BLOCK_SUPPORT
4651
  /* Check to see if checking out Q-Block support */
4652
188
  if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK) {
4653
0
    if (rcvd->code == COAP_RESPONSE_CODE(402)) {
4654
0
      coap_log_debug("Q-Block support not available\n");
4655
0
      set_block_mode_drop_q(session->block_mode);
4656
0
    } else {
4657
0
      coap_block_b_t qblock;
4658
4659
0
      if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
4660
0
        coap_log_debug("Q-Block support available\n");
4661
0
        set_block_mode_has_q(session->block_mode);
4662
0
        if (session->state == COAP_SESSION_STATE_ESTABLISHED)
4663
          /* Flush out any entries on session->delayqueue */
4664
0
          coap_session_connected(session);
4665
0
      } else {
4666
0
        coap_log_debug("Q-Block support not available\n");
4667
0
        set_block_mode_drop_q(session->block_mode);
4668
0
      }
4669
0
    }
4670
0
    coap_send_ack_lkd(session, rcvd);
4671
0
    coap_reset_doing_first(session);
4672
0
    return;
4673
0
  }
4674
188
#endif /* COAP_Q_BLOCK_SUPPORT */
4675
4676
  /* See if the server is struggling */
4677
188
  if (rcvd->code == COAP_RESPONSE_CODE(503) || rcvd->code == COAP_RESPONSE_CODE(429)) {
4678
7
    if (!sent && session->lg_crcv)
4679
0
      sent = session->lg_crcv->sent_pdu;
4680
4681
7
    if (sent) {
4682
      /* sent is not active, so safe to reuse */
4683
0
      uint8_t buf[4];
4684
      /* Need to resend request in max_age seconds */
4685
0
      size_t max_age = 60;
4686
0
      coap_opt_iterator_t opt_iter;
4687
0
      coap_opt_t *option = coap_check_option(rcvd, COAP_OPTION_MAXAGE, &opt_iter);
4688
0
      coap_queue_t *node = coap_new_node();
4689
0
      if (option)
4690
0
        max_age = coap_decode_var_bytes(coap_opt_value(option),
4691
0
                                        coap_opt_length(option));
4692
4693
0
      if (!node) {
4694
0
        coap_log_debug("retransmit delay: insufficient memory\n");
4695
0
        return;
4696
0
      }
4697
4698
0
      coap_pdu_reference_lkd(sent);
4699
0
      sent->mid = coap_new_message_id_lkd(session);
4700
0
      coap_update_option(sent,
4701
0
                         COAP_OPTION_RTAG,
4702
0
                         coap_encode_var_safe(buf, sizeof(buf),
4703
0
                                              ++session->tx_rtag),
4704
0
                         buf);
4705
0
      coap_pdu_encode_header(sent, session->proto);
4706
0
      node->id = sent->mid;
4707
0
      node->pdu = sent;
4708
0
      coap_log_debug("   %s: mid=0x%04x: re-request delayed for %u secs\n",
4709
0
                     coap_session_str(session),
4710
0
                     sent->mid,
4711
0
                     (unsigned int)max_age);
4712
0
      node->timeout = (unsigned int)max_age * COAP_TICKS_PER_SECOND;
4713
      /* Use this to delay transmission */
4714
0
      coap_wait_ack(session->context, session, node);
4715
0
    }
4716
7
    return;
4717
7
  }
4718
4719
181
  if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
4720
    /* See if need to send next block to server */
4721
2
    if (coap_handle_response_send_block(session, sent, rcvd)) {
4722
      /* Next block transmitted, no need to inform app */
4723
0
      coap_send_ack_lkd(session, rcvd);
4724
0
      return;
4725
0
    }
4726
4727
    /* Need to see if needing to request next block */
4728
2
    if (coap_handle_response_get_block(context, session, sent, rcvd,
4729
2
                                       COAP_RECURSE_OK)) {
4730
      /* Next block transmitted, ack sent no need to inform app */
4731
0
      return;
4732
0
    }
4733
2
  }
4734
181
  coap_reset_doing_first(session);
4735
4736
  /* Call application-specific response handler when available. */
4737
181
  coap_call_response_handler(session, sent, rcvd, NULL);
4738
181
}
4739
#endif /* COAP_CLIENT_SUPPORT */
4740
4741
#if !COAP_DISABLE_TCP
4742
static void
4743
handle_signaling(coap_context_t *context, coap_session_t *session,
4744
1.80k
                 coap_pdu_t *pdu) {
4745
1.80k
  coap_opt_iterator_t opt_iter;
4746
1.80k
  coap_opt_t *option;
4747
1.80k
  int set_mtu = 0;
4748
4749
1.80k
  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
4750
4751
1.80k
  if (pdu->code == COAP_SIGNALING_CODE_CSM) {
4752
1.80k
    if (session->csm_not_seen) {
4753
0
      coap_tick_t now;
4754
4755
0
      coap_ticks(&now);
4756
      /* CSM timeout before CSM seen */
4757
0
      coap_log_warn("***%s: CSM received after CSM timeout\n",
4758
0
                    coap_session_str(session));
4759
0
      coap_log_warn("***%s: Increase timeout in coap_context_set_csm_timeout_ms() to > %d\n",
4760
0
                    coap_session_str(session),
4761
0
                    (int)(((now - session->csm_tx) * 1000) / COAP_TICKS_PER_SECOND));
4762
0
    }
4763
1.80k
    if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
4764
1.80k
      session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
4765
1.80k
    }
4766
3.56k
    while ((option = coap_option_next(&opt_iter))) {
4767
1.76k
      unsigned max_recv;
4768
4769
1.76k
      switch ((coap_sig_csm_opt_t)opt_iter.number) {
4770
1.76k
      case COAP_SIG_OPT_MAX_MESSAGE_SIZE:
4771
1.76k
        max_recv = coap_decode_var_bytes(coap_opt_value(option), coap_opt_length(option));
4772
1.76k
        if (max_recv > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
4773
1.46k
          max_recv = COAP_DEFAULT_MAX_PDU_RX_SIZE;
4774
1.46k
          coap_log_debug("*  %s: Restricting CSM Max-Message-Size size to %u\n",
4775
1.46k
                         coap_session_str(session), max_recv);
4776
1.46k
        }
4777
1.76k
        coap_session_set_mtu(session, max_recv);
4778
1.76k
        set_mtu = 1;
4779
1.76k
        break;
4780
0
      case COAP_SIG_OPT_BLOCK_WISE_TRANSFER:
4781
0
        session->csm_block_supported = 1;
4782
0
        break;
4783
0
      case COAP_SIG_OPT_EXTENDED_TOKEN_LENGTH:
4784
0
        session->max_token_size =
4785
0
            coap_decode_var_bytes(coap_opt_value(option),
4786
0
                                  coap_opt_length(option));
4787
0
        if (session->max_token_size < COAP_TOKEN_DEFAULT_MAX)
4788
0
          session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
4789
0
        else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
4790
0
          session->max_token_size = COAP_TOKEN_EXT_MAX;
4791
0
        session->max_token_checked = COAP_EXT_T_CHECKED;
4792
0
        break;
4793
0
      default:
4794
0
        break;
4795
1.76k
      }
4796
1.76k
    }
4797
1.80k
    if (set_mtu) {
4798
1.76k
      if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
4799
0
        session->csm_bert_rem_support = 1;
4800
1.76k
      else
4801
1.76k
        session->csm_bert_rem_support = 0;
4802
1.76k
    }
4803
1.80k
    if (session->state == COAP_SESSION_STATE_CSM)
4804
0
      coap_session_connected(session);
4805
1.80k
  } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
4806
0
    coap_pdu_t *pong = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PONG, 0, 1);
4807
0
    if (context->ping_cb) {
4808
0
      coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
4809
0
    }
4810
0
    if (pong) {
4811
0
      coap_add_option_internal(pong, (coap_option_num_t)COAP_SIG_OPT_CUSTODY,
4812
0
                               0, NULL);
4813
0
      coap_send_internal(session, pong, NULL);
4814
0
    }
4815
0
  } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
4816
0
    session->last_pong = session->last_rx_tx;
4817
0
    session->ping_failed = 0;
4818
0
    if (context->pong_cb) {
4819
0
      coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
4820
0
    }
4821
0
  } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
4822
0
             || pdu->code == COAP_SIGNALING_CODE_ABORT) {
4823
0
    coap_session_disconnected_lkd(session, COAP_NACK_RST);
4824
0
  } else {
4825
0
    coap_log_debug("PDU signaling code %u.%02u unknown\n", (pdu->code >> 5) & 0x7, pdu->code & 0x1f);
4826
0
  }
4827
1.80k
}
4828
#endif /* !COAP_DISABLE_TCP */
4829
4830
static int
4831
3.14k
check_token_size(coap_session_t *session, const coap_pdu_t *pdu, int is_local_mcast) {
4832
3.14k
  if (COAP_PDU_IS_REQUEST(pdu) &&
4833
1.07k
      pdu->actual_token.length >
4834
1.07k
      (session->type == COAP_SESSION_TYPE_CLIENT ?
4835
1.07k
       session->max_token_size : session->context->max_token_size)) {
4836
    /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
4837
48
    if (is_local_mcast)
4838
0
      return 0;
4839
48
    if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
4840
43
      coap_opt_filter_t opt_filter;
4841
43
      coap_pdu_t *response;
4842
4843
43
      memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
4844
43
      response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
4845
43
                                         &opt_filter);
4846
43
      if (!response) {
4847
0
        coap_log_warn("coap_dispatch: cannot create error response\n");
4848
43
      } else {
4849
        /*
4850
         * Note - have to leave in oversize token as per
4851
         * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
4852
         */
4853
43
        if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4854
43
          coap_log_warn("coap_dispatch: error sending response\n");
4855
43
      }
4856
43
    } else {
4857
      /* Indicate no extended token support */
4858
5
      coap_send_rst_lkd(session, pdu);
4859
5
    }
4860
48
    return 0;
4861
48
  }
4862
3.09k
  return 1;
4863
3.14k
}
4864
4865
void
4866
coap_dispatch(coap_context_t *context, coap_session_t *session,
4867
3.38k
              coap_pdu_t *pdu) {
4868
3.38k
  coap_queue_t *sent = NULL;
4869
3.38k
  coap_pdu_t *response;
4870
3.38k
  coap_pdu_t *orig_pdu = NULL;
4871
3.38k
  coap_opt_filter_t opt_filter;
4872
3.38k
  int is_ping_rst;
4873
3.38k
  int packet_is_bad = 0;
4874
3.38k
#if COAP_OSCORE_SUPPORT
4875
3.38k
  coap_opt_iterator_t opt_iter;
4876
3.38k
  coap_pdu_t *dec_pdu = NULL;
4877
3.38k
#endif /* COAP_OSCORE_SUPPORT */
4878
3.38k
  int is_ext_token_rst = 0;
4879
3.38k
  int oscore_invalid = 0;
4880
3.38k
  int is_local_mcast = 0;
4881
4882
3.38k
  coap_pdu_reference_lkd(pdu);
4883
3.38k
  pdu->session = session;
4884
3.38k
  coap_show_pdu(COAP_LOG_DEBUG, pdu);
4885
4886
3.38k
  if (COAP_PDU_IS_REQUEST(pdu) && coap_is_mcast(&session->addr_info.local)) {
4887
    /* Need to be careful with responses to multicast requests */
4888
0
    is_local_mcast = 1;
4889
0
    if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
4890
0
      coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
4891
0
      return;
4892
0
    }
4893
0
  }
4894
4895
  /* Check validity of received code */
4896
3.38k
  if (!coap_check_code_class(session, pdu)) {
4897
71
    coap_log_info("coap_dispatch: Received invalid PDU code (%d.%02d)\n",
4898
71
                  COAP_RESPONSE_CLASS(pdu->code),
4899
71
                  pdu->code & 0x1f);
4900
71
    packet_is_bad = 1;
4901
71
    if (pdu->type == COAP_MESSAGE_CON) {
4902
32
      coap_send_message_type_lkd(session, pdu, COAP_MESSAGE_RST);
4903
32
    }
4904
    /* find message id in sendqueue to stop retransmission (code is not 0.00) */
4905
71
    coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
4906
71
    goto cleanup;
4907
71
  }
4908
4909
3.31k
  coap_option_filter_clear(&opt_filter);
4910
4911
3.31k
#if COAP_SERVER_SUPPORT
4912
  /* See if this a repeat request */
4913
3.31k
  if (COAP_PDU_IS_REQUEST(pdu) && session->last_resp_pdu &&
4914
104
      pdu->mid == session->last_resp_pdu->mid) {
4915
0
#if COAP_OSCORE_SUPPORT
4916
0
    uint8_t oscore_encryption = session->oscore_encryption;
4917
4918
0
    session->oscore_encryption = 0;
4919
0
#endif /* COAP_OSCORE_SUPPORT */
4920
    /* Account for coap_send_internal() doing a coap_delete_pdu() and
4921
       last_resp_pdu must not be removed */
4922
0
    coap_pdu_reference_lkd(session->last_resp_pdu);
4923
0
    coap_log_debug("Retransmit response to duplicate request\n");
4924
0
    if (coap_send_internal(session, session->last_resp_pdu, NULL) != COAP_INVALID_MID) {
4925
0
#if COAP_OSCORE_SUPPORT
4926
0
      session->oscore_encryption = oscore_encryption;
4927
0
#endif /* COAP_OSCORE_SUPPORT */
4928
0
      goto finish;
4929
0
    }
4930
0
#if COAP_OSCORE_SUPPORT
4931
0
    session->oscore_encryption = oscore_encryption;
4932
0
#endif /* COAP_OSCORE_SUPPORT */
4933
0
  }
4934
3.31k
#endif /* COAP_SERVER_SUPPORT */
4935
3.31k
  if (pdu->type == COAP_MESSAGE_NON || pdu->type == COAP_MESSAGE_CON) {
4936
3.14k
    if (!check_token_size(session, pdu, is_local_mcast)) {
4937
48
      goto cleanup;
4938
48
    }
4939
3.14k
  }
4940
3.26k
#if COAP_OSCORE_SUPPORT
4941
3.26k
  if (!COAP_PDU_IS_SIGNALING(pdu) &&
4942
1.46k
      coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
4943
366
    if (!is_local_mcast && (pdu->type == COAP_MESSAGE_CON || pdu->type == COAP_MESSAGE_NON)) {
4944
320
      if (COAP_PDU_IS_REQUEST(pdu)) {
4945
188
        response =
4946
188
            coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
4947
4948
188
        if (!response) {
4949
0
          coap_log_warn("coap_dispatch: cannot create error response\n");
4950
188
        } else {
4951
188
          if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
4952
188
            coap_log_warn("coap_dispatch: error sending response\n");
4953
188
        }
4954
188
      } else {
4955
132
        coap_send_rst_lkd(session, pdu);
4956
132
      }
4957
320
    }
4958
366
    goto cleanup;
4959
366
  }
4960
4961
2.89k
  if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
4962
0
    int decrypt = 1;
4963
0
#if COAP_SERVER_SUPPORT
4964
0
    coap_opt_t *opt;
4965
0
    coap_resource_t *resource;
4966
0
    coap_uri_t uri;
4967
0
#endif /* COAP_SERVER_SUPPORT */
4968
4969
0
    if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
4970
0
      decrypt = 0;
4971
4972
0
#if COAP_SERVER_SUPPORT
4973
0
    if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
4974
0
        coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
4975
0
        (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
4976
0
        != NULL) {
4977
      /* Need to check whether this is a direct or proxy session */
4978
0
      memset(&uri, 0, sizeof(uri));
4979
0
      uri.host.length = coap_opt_length(opt);
4980
0
      uri.host.s = coap_opt_value(opt);
4981
0
      resource = context->proxy_uri_resource;
4982
0
      if (uri.host.length && resource && resource->proxy_name_count &&
4983
0
          resource->proxy_name_list) {
4984
0
        size_t i;
4985
0
        for (i = 0; i < resource->proxy_name_count; i++) {
4986
0
          if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
4987
0
            break;
4988
0
          }
4989
0
        }
4990
0
        if (i == resource->proxy_name_count) {
4991
          /* This server is not hosting the proxy connection endpoint */
4992
0
          decrypt = 0;
4993
0
        }
4994
0
      }
4995
0
    }
4996
0
#endif /* COAP_SERVER_SUPPORT */
4997
0
    if (decrypt) {
4998
0
#if COAP_ASYNC_SUPPORT
4999
      /*
5000
       * RFC7252 request deduplication must run before OSCORE replay checks
5001
       * (RFC8613).  A retransmitted CON for a request with a pending separate
5002
       * (async) response carries the same Sender Sequence Number and would
5003
       * otherwise be rejected during decrypt with an unprotected 4.01 instead
5004
       * of retransmitting the empty ACK.  The outer token matches the pending
5005
       * async entry (see handle_request()).
5006
       */
5007
0
      if (COAP_PDU_IS_REQUEST(pdu) && pdu->type == COAP_MESSAGE_CON) {
5008
0
        coap_async_t *dup_async = coap_find_async_lkd(session, pdu->actual_token);
5009
5010
0
        if (dup_async) {
5011
0
          coap_tick_t now;
5012
5013
0
          coap_ticks(&now);
5014
0
          if (dup_async->delay == 0 || dup_async->delay > now) {
5015
0
            coap_log_info("Duplicate request, async response pending\n");
5016
0
            coap_send_ack_lkd(session, pdu);
5017
0
            goto finish;
5018
0
          }
5019
0
        }
5020
0
      }
5021
0
#endif /* COAP_ASYNC_SUPPORT */
5022
      /* find message id in sendqueue to stop retransmission and get sent (not empty packet) */
5023
0
      coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &pdu->actual_token, &sent);
5024
      /* Bump ref so pdu is not freed of, and keep a pointer to it */
5025
0
      orig_pdu = pdu;
5026
0
      coap_pdu_reference_lkd(orig_pdu);
5027
0
      if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
5028
0
        if (session->recipient_ctx == NULL ||
5029
0
            (session->recipient_ctx->initial_state == 0 &&
5030
0
             session->b_2_step == COAP_OSCORE_B_2_NONE)) {
5031
0
          coap_log_warn("OSCORE: PDU could not be decrypted\n");
5032
0
        }
5033
0
        coap_delete_node_lkd(sent);
5034
0
        coap_delete_pdu_lkd(orig_pdu);
5035
0
        goto finish;
5036
0
      } else {
5037
0
        session->oscore_encryption = 1;
5038
0
        coap_pdu_reference_lkd(dec_pdu);
5039
0
        coap_pdu_release_lkd(pdu);
5040
0
        pdu = dec_pdu;
5041
0
      }
5042
0
      coap_log_debug("Decrypted PDU\n");
5043
0
      coap_show_pdu(COAP_LOG_DEBUG, pdu);
5044
0
    }
5045
2.89k
  } else if (COAP_PDU_IS_RESPONSE(pdu) &&
5046
213
             session->oscore_encryption &&
5047
0
             pdu->type != COAP_MESSAGE_RST) {
5048
0
    if (COAP_RESPONSE_CLASS(pdu->code) == 2) {
5049
      /* Violates RFC 8613 2 */
5050
0
      coap_log_err("received an invalid response to the OSCORE request\n");
5051
0
      oscore_invalid = 1;
5052
0
    }
5053
0
  }
5054
2.89k
#endif /* COAP_OSCORE_SUPPORT */
5055
5056
2.89k
  switch (pdu->type) {
5057
73
  case COAP_MESSAGE_ACK:
5058
73
    if (NULL == sent) {
5059
      /* find message id in sendqueue to stop retransmission (no token if empty) */
5060
73
      coap_remove_from_queue(&context->sendqueue, session, pdu->mid,
5061
73
                             pdu->code == 0 ? NULL : &pdu->actual_token, &sent);
5062
73
    }
5063
5064
73
    if (sent && session->con_active) {
5065
0
      session->con_active--;
5066
0
      if (session->state == COAP_SESSION_STATE_ESTABLISHED)
5067
        /* Flush out any entries on session->delayqueue */
5068
0
        coap_session_connected(session);
5069
0
    }
5070
73
    if (oscore_invalid ||
5071
73
        coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
5072
0
      packet_is_bad = 1;
5073
0
      goto cleanup;
5074
0
    }
5075
5076
73
#if COAP_SERVER_SUPPORT
5077
    /* if sent code was >= 64 the message might have been a
5078
     * notification. Then, we must flag the observer to be alive
5079
     * by setting obs->fail_cnt = 0. */
5080
73
    if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
5081
0
      coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
5082
0
    }
5083
73
#endif /* COAP_SERVER_SUPPORT */
5084
5085
73
#if COAP_Q_BLOCK_SUPPORT
5086
73
    if (session->lg_xmit && sent && sent->pdu && sent->pdu->type == COAP_MESSAGE_CON &&
5087
0
        !(session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK)) {
5088
0
      int doing_q_block = 0;
5089
0
      coap_lg_xmit_t *lg_xmit = NULL;
5090
5091
0
      LL_FOREACH(session->lg_xmit, lg_xmit) {
5092
0
        if ((lg_xmit->option == COAP_OPTION_Q_BLOCK1 || lg_xmit->option == COAP_OPTION_Q_BLOCK2) &&
5093
0
            lg_xmit->last_all_sent == 0 && lg_xmit->sent_pdu->type != COAP_MESSAGE_NON) {
5094
0
          doing_q_block = 1;
5095
0
          break;
5096
0
        }
5097
0
      }
5098
0
      if (doing_q_block && lg_xmit) {
5099
0
        coap_block_b_t block;
5100
5101
0
        memset(&block, 0, sizeof(block));
5102
0
        if (lg_xmit->option == COAP_OPTION_Q_BLOCK1) {
5103
0
          block.num = lg_xmit->last_block + lg_xmit->b.b1.count;
5104
0
        } else {
5105
0
          block.num = lg_xmit->last_block;
5106
0
        }
5107
0
        block.m = 1;
5108
0
        block.szx = block.aszx = lg_xmit->blk_size;
5109
0
        block.defined = 1;
5110
0
        block.bert = 0;
5111
0
        block.chunk_size = 1024;
5112
5113
0
        coap_send_q_blocks(session, lg_xmit, block,
5114
0
                           lg_xmit->sent_pdu, COAP_SEND_SKIP_PDU);
5115
0
      }
5116
0
    }
5117
73
#endif /* COAP_Q_BLOCK_SUPPORT */
5118
73
    if (pdu->code == 0) {
5119
0
#if COAP_CLIENT_SUPPORT
5120
      /*
5121
       * In coap_send(), lg_crcv was not set up if type is CON and protocol is not
5122
       * reliable to save overhead as this can be set up on detection of a (Q)-Block2
5123
       * response if the response was piggy-backed. Here, a separate response
5124
       * detected and so the lg_crcv needs to be set up before the sent PDU
5125
       * information is lost.
5126
       *
5127
       * lg_crcv was not set up if not a CoAP request.
5128
       *
5129
       * lg_crcv was always set up in coap_send() if Observe, Oscore and (Q)-Block1
5130
       * options.
5131
       */
5132
0
      if (sent &&
5133
0
          !coap_check_send_need_lg_crcv(session, sent->pdu) &&
5134
0
          COAP_PDU_IS_REQUEST(sent->pdu)) {
5135
        /*
5136
         * lg_crcv was not set up in coap_send(). It could have been set up
5137
         * the first separate response.
5138
         * See if there already is a lg_crcv set up.
5139
         */
5140
0
        coap_lg_crcv_t *lg_crcv;
5141
0
        uint64_t token_match =
5142
0
            STATE_TOKEN_BASE(coap_decode_var_bytes8(sent->pdu->actual_token.s,
5143
0
                                                    sent->pdu->actual_token.length));
5144
5145
0
        LL_FOREACH(session->lg_crcv, lg_crcv) {
5146
0
          if (token_match == STATE_TOKEN_BASE(lg_crcv->state_token) ||
5147
0
              coap_binary_equal(&sent->pdu->actual_token, lg_crcv->app_token)) {
5148
0
            break;
5149
0
          }
5150
0
        }
5151
0
        if (!lg_crcv) {
5152
          /*
5153
           * Need to set up a lg_crcv as it was not set up in coap_send()
5154
           * to save time, but server has not sent back a piggy-back response.
5155
           */
5156
0
          lg_crcv = coap_block_new_lg_crcv(session, sent->pdu, NULL);
5157
0
          if (lg_crcv) {
5158
0
            LL_PREPEND(session->lg_crcv, lg_crcv);
5159
0
          }
5160
0
        }
5161
0
      }
5162
0
#endif /* COAP_CLIENT_SUPPORT */
5163
      /* an empty ACK needs no further handling */
5164
0
      goto cleanup;
5165
73
    } else if (COAP_PDU_IS_REQUEST(pdu)) {
5166
      /* This is not legitimate - Request using ACK - ignore */
5167
17
      coap_log_debug("dropped ACK with request code (%d.%02d)\n",
5168
17
                     COAP_RESPONSE_CLASS(pdu->code),
5169
17
                     pdu->code & 0x1f);
5170
17
      packet_is_bad = 1;
5171
17
      goto cleanup;
5172
17
    }
5173
5174
56
    break;
5175
5176
56
  case COAP_MESSAGE_RST:
5177
    /* We have sent something the receiver disliked, so we remove
5178
     * not only the message id but also the subscriptions we might
5179
     * have. */
5180
49
    is_ping_rst = 0;
5181
49
    if (pdu->mid == session->last_ping_mid &&
5182
0
        session->last_ping > 0)
5183
0
      is_ping_rst = 1;
5184
5185
49
#if COAP_CLIENT_SUPPORT
5186
49
#if COAP_Q_BLOCK_SUPPORT
5187
    /* Check to see if checking out Q-Block support */
5188
49
    if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
5189
0
        session->remote_test_mid == pdu->mid) {
5190
0
      coap_log_debug("Q-Block support not available\n");
5191
0
      set_block_mode_drop_q(session->block_mode);
5192
0
      coap_reset_doing_first(session);
5193
0
    }
5194
49
#endif /* COAP_Q_BLOCK_SUPPORT */
5195
5196
    /* Check to see if checking out extended token support */
5197
49
    if (session->max_token_checked == COAP_EXT_T_CHECKING &&
5198
0
        session->remote_test_mid == pdu->mid) {
5199
0
      coap_log_debug("Extended Token support not available\n");
5200
0
      session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
5201
0
      session->max_token_checked = COAP_EXT_T_CHECKED;
5202
0
      coap_reset_doing_first(session);
5203
0
      is_ext_token_rst = 1;
5204
0
    }
5205
49
#endif /* COAP_CLIENT_SUPPORT */
5206
5207
49
    if (!is_ping_rst && !is_ext_token_rst)
5208
49
      coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
5209
5210
49
    if (session->con_active) {
5211
0
      session->con_active--;
5212
0
      if (session->state == COAP_SESSION_STATE_ESTABLISHED)
5213
        /* Flush out any entries on session->delayqueue */
5214
0
        coap_session_connected(session);
5215
0
    }
5216
5217
    /* find message id in sendqueue to stop retransmission (no token as RST) */
5218
49
    coap_remove_from_queue(&context->sendqueue, session, pdu->mid, NULL, &sent);
5219
5220
49
    if (sent) {
5221
0
      if (!is_ping_rst)
5222
0
        coap_cancel(context, sent);
5223
5224
0
      if (!is_ping_rst && !is_ext_token_rst) {
5225
0
        if (sent->pdu->type==COAP_MESSAGE_CON) {
5226
0
          coap_handle_nack(sent->session, sent->pdu, COAP_NACK_RST, sent->id);
5227
0
        }
5228
0
      } else if (is_ping_rst) {
5229
0
        if (context->pong_cb) {
5230
0
          coap_lock_callback(context->pong_cb(session, pdu, pdu->mid));
5231
0
        }
5232
0
        session->last_pong = session->last_rx_tx;
5233
0
        session->ping_failed = 0;
5234
0
        session->last_ping_mid = COAP_INVALID_MID;
5235
0
      }
5236
49
    } else {
5237
49
#if COAP_SERVER_SUPPORT
5238
      /* Need to check is there is a subscription active and delete it */
5239
49
      RESOURCES_ITER(context->resources, r) {
5240
1
        coap_subscription_t *obs, *tmp;
5241
1
        LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
5242
0
          if (obs->pdu->mid == pdu->mid && obs->session == session) {
5243
            /* Need to do this now as session may get de-referenced */
5244
0
            coap_session_reference_lkd(session);
5245
0
            coap_delete_observer(r, session, &obs->pdu->actual_token);
5246
0
            coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5247
0
            coap_session_release_lkd(session);
5248
0
            goto cleanup;
5249
0
          }
5250
0
        }
5251
1
      }
5252
49
#endif /* COAP_SERVER_SUPPORT */
5253
49
      coap_handle_nack(session, NULL, COAP_NACK_RST, pdu->mid);
5254
49
    }
5255
49
#if COAP_PROXY_SUPPORT
5256
49
    if (!is_ping_rst) {
5257
      /* Need to check is there is a proxy subscription active and delete it */
5258
49
      coap_delete_proxy_subscriber(session, NULL, pdu->mid, COAP_PROXY_SUBS_MID);
5259
49
    }
5260
49
#endif /* COAP_PROXY_SUPPORT */
5261
49
    goto cleanup;
5262
5263
509
  case COAP_MESSAGE_NON:
5264
    /* check for oscore issue or unknown critical options */
5265
509
    if (oscore_invalid ||
5266
509
        coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0) {
5267
0
      packet_is_bad = 1;
5268
0
      if (COAP_PDU_IS_REQUEST(pdu)) {
5269
0
        response =
5270
0
            coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5271
5272
0
        if (!response) {
5273
0
          coap_log_warn("coap_dispatch: cannot create error response\n");
5274
0
        } else {
5275
0
          if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5276
0
            coap_log_warn("coap_dispatch: error sending response\n");
5277
0
        }
5278
0
      } else {
5279
0
        coap_send_rst_lkd(session, pdu);
5280
0
      }
5281
0
      goto cleanup;
5282
0
    }
5283
509
    break;
5284
5285
2.26k
  case COAP_MESSAGE_CON:
5286
    /* In a lossy context, the ACK of a separate response may have
5287
     * been lost, so we need to stop retransmitting requests with the
5288
     * same token. Matching on token potentially containing ext length bytes.
5289
     */
5290
    /* find message token in sendqueue to stop retransmission */
5291
2.26k
    if (pdu->code != 0)
5292
2.26k
      coap_remove_from_queue_token(&context->sendqueue, session, &pdu->actual_token, &sent);
5293
5294
    /* check for oscore issue or unknown critical options in non-signaling messages */
5295
2.26k
    if (oscore_invalid ||
5296
2.26k
        (!COAP_PDU_IS_SIGNALING(pdu) &&
5297
463
         coap_option_check_critical(session, pdu, &opt_filter, COAP_CRIT_UNKNOWN) == 0)) {
5298
0
      packet_is_bad = 1;
5299
0
      if (COAP_PDU_IS_REQUEST(pdu)) {
5300
0
        response =
5301
0
            coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
5302
5303
0
        if (!response) {
5304
0
          coap_log_warn("coap_dispatch: cannot create error response\n");
5305
0
        } else {
5306
0
          if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID)
5307
0
            coap_log_warn("coap_dispatch: error sending response\n");
5308
0
        }
5309
0
      } else {
5310
0
        coap_send_rst_lkd(session, pdu);
5311
0
      }
5312
0
      goto cleanup;
5313
0
    }
5314
2.26k
    break;
5315
2.26k
  default:
5316
0
    break;
5317
2.89k
  }
5318
5319
  /* Pass message to upper layer if a specific handler was
5320
    * registered for a request that should be handled locally. */
5321
2.83k
#if !COAP_DISABLE_TCP
5322
2.83k
  if (COAP_PDU_IS_SIGNALING(pdu))
5323
1.80k
    handle_signaling(context, session, pdu);
5324
1.02k
  else
5325
1.02k
#endif /* !COAP_DISABLE_TCP */
5326
1.02k
#if COAP_SERVER_SUPPORT
5327
1.02k
    if (COAP_PDU_IS_REQUEST(pdu))
5328
837
      handle_request(context, session, pdu, orig_pdu);
5329
191
    else
5330
191
#endif /* COAP_SERVER_SUPPORT */
5331
191
#if COAP_CLIENT_SUPPORT
5332
191
      if (COAP_PDU_IS_RESPONSE(pdu))
5333
188
        handle_response(context, session, sent ? sent->pdu : NULL, pdu);
5334
3
      else
5335
3
#endif /* COAP_CLIENT_SUPPORT */
5336
3
      {
5337
3
        if (COAP_PDU_IS_EMPTY(pdu)) {
5338
3
          if (context->ping_cb) {
5339
0
            coap_lock_callback(context->ping_cb(session, pdu, pdu->mid));
5340
0
          }
5341
3
        } else {
5342
0
          packet_is_bad = 1;
5343
0
        }
5344
3
        coap_log_debug("dropped message with invalid code (%d.%02d)\n",
5345
3
                       COAP_RESPONSE_CLASS(pdu->code),
5346
3
                       pdu->code & 0x1f);
5347
5348
3
        if (!coap_is_mcast(&session->addr_info.local)) {
5349
3
          if (COAP_PDU_IS_EMPTY(pdu)) {
5350
3
            if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
5351
3
              coap_tick_t now;
5352
3
              coap_ticks(&now);
5353
3
              if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
5354
3
                coap_send_message_type_lkd(session, pdu, COAP_MESSAGE_RST);
5355
3
                session->last_tx_rst = now;
5356
3
              }
5357
3
            }
5358
3
          } else {
5359
0
            if (pdu->type == COAP_MESSAGE_CON)
5360
0
              coap_send_message_type_lkd(session, pdu, COAP_MESSAGE_RST);
5361
0
          }
5362
3
        }
5363
3
      }
5364
5365
3.38k
cleanup:
5366
3.38k
  if (packet_is_bad) {
5367
88
    if (sent) {
5368
0
      coap_handle_nack(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
5369
88
    } else {
5370
88
      coap_handle_event_lkd(context, COAP_EVENT_BAD_PACKET, session);
5371
88
    }
5372
88
  }
5373
3.38k
  coap_delete_pdu_lkd(orig_pdu);
5374
3.38k
  coap_delete_node_lkd(sent);
5375
3.38k
#if COAP_OSCORE_SUPPORT
5376
3.38k
  coap_delete_pdu_lkd(dec_pdu);
5377
3.38k
#endif /* COAP_OSCORE_SUPPORT */
5378
5379
3.38k
#if COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT
5380
3.38k
finish:
5381
3.38k
#endif /* COAP_SERVER_SUPPORT || COAP_OSCORE_SUPPORT */
5382
3.38k
  coap_pdu_release_lkd(pdu);
5383
3.38k
}
5384
5385
#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
5386
static const char *
5387
0
coap_event_name(coap_event_t event) {
5388
0
  switch (event) {
5389
0
  case COAP_EVENT_DTLS_CLOSED:
5390
0
    return "COAP_EVENT_DTLS_CLOSED";
5391
0
  case COAP_EVENT_DTLS_CONNECTED:
5392
0
    return "COAP_EVENT_DTLS_CONNECTED";
5393
0
  case COAP_EVENT_DTLS_RENEGOTIATE:
5394
0
    return "COAP_EVENT_DTLS_RENEGOTIATE";
5395
0
  case COAP_EVENT_DTLS_ERROR:
5396
0
    return "COAP_EVENT_DTLS_ERROR";
5397
0
  case COAP_EVENT_TCP_CONNECTED:
5398
0
    return "COAP_EVENT_TCP_CONNECTED";
5399
0
  case COAP_EVENT_TCP_CLOSED:
5400
0
    return "COAP_EVENT_TCP_CLOSED";
5401
0
  case COAP_EVENT_TCP_FAILED:
5402
0
    return "COAP_EVENT_TCP_FAILED";
5403
0
  case COAP_EVENT_SESSION_CONNECTED:
5404
0
    return "COAP_EVENT_SESSION_CONNECTED";
5405
0
  case COAP_EVENT_SESSION_CLOSED:
5406
0
    return "COAP_EVENT_SESSION_CLOSED";
5407
0
  case COAP_EVENT_SESSION_FAILED:
5408
0
    return "COAP_EVENT_SESSION_FAILED";
5409
0
  case COAP_EVENT_PARTIAL_BLOCK:
5410
0
    return "COAP_EVENT_PARTIAL_BLOCK";
5411
0
  case COAP_EVENT_XMIT_BLOCK_FAIL:
5412
0
    return "COAP_EVENT_XMIT_BLOCK_FAIL";
5413
0
  case COAP_EVENT_BLOCK_ISSUE:
5414
0
    return "COAP_EVENT_BLOCK_ISSUE";
5415
0
  case COAP_EVENT_SERVER_SESSION_NEW:
5416
0
    return "COAP_EVENT_SERVER_SESSION_NEW";
5417
0
  case COAP_EVENT_SERVER_SESSION_DEL:
5418
0
    return "COAP_EVENT_SERVER_SESSION_DEL";
5419
0
  case COAP_EVENT_SERVER_SESSION_CONNECTED:
5420
0
    return "COAP_EVENT_SERVER_SESSION_CONNECTED";
5421
0
  case COAP_EVENT_BAD_PACKET:
5422
0
    return "COAP_EVENT_BAD_PACKET";
5423
0
  case COAP_EVENT_MSG_RETRANSMITTED:
5424
0
    return "COAP_EVENT_MSG_RETRANSMITTED";
5425
0
  case COAP_EVENT_FIRST_PDU_FAIL:
5426
0
    return "COAP_EVENT_FIRST_PDU_FAIL";
5427
0
  case COAP_EVENT_OSCORE_DECRYPTION_FAILURE:
5428
0
    return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
5429
0
  case COAP_EVENT_OSCORE_NOT_ENABLED:
5430
0
    return "COAP_EVENT_OSCORE_NOT_ENABLED";
5431
0
  case COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD:
5432
0
    return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
5433
0
  case COAP_EVENT_OSCORE_NO_SECURITY:
5434
0
    return "COAP_EVENT_OSCORE_NO_SECURITY";
5435
0
  case COAP_EVENT_OSCORE_INTERNAL_ERROR:
5436
0
    return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
5437
0
  case COAP_EVENT_OSCORE_DECODE_ERROR:
5438
0
    return "COAP_EVENT_OSCORE_DECODE_ERROR";
5439
0
  case COAP_EVENT_OSCORE_RECIPIENT_CHANGED:
5440
0
    return "COAP_EVENT_OSCORE_RECIPIENT_CHANGED";
5441
0
  case COAP_EVENT_WS_PACKET_SIZE:
5442
0
    return "COAP_EVENT_WS_PACKET_SIZE";
5443
0
  case COAP_EVENT_WS_CONNECTED:
5444
0
    return "COAP_EVENT_WS_CONNECTED";
5445
0
  case COAP_EVENT_WS_CLOSED:
5446
0
    return "COAP_EVENT_WS_CLOSED";
5447
0
  case COAP_EVENT_KEEPALIVE_FAILURE:
5448
0
    return "COAP_EVENT_KEEPALIVE_FAILURE";
5449
0
  case COAP_EVENT_RECONNECT_FAILED:
5450
0
    return "COAP_EVENT_RECONNECT_FAILED";
5451
0
  case COAP_EVENT_RECONNECT_SUCCESS:
5452
0
    return "COAP_EVENT_RECONNECT_SUCCESS";
5453
0
  case COAP_EVENT_RECONNECT_NO_MORE:
5454
0
    return "COAP_EVENT_RECONNECT_NO_MORE";
5455
0
  case COAP_EVENT_RECONNECT_STARTED:
5456
0
    return "COAP_EVENT_RECONNECT_STARTED";
5457
0
  default:
5458
0
    return "???";
5459
0
  }
5460
0
}
5461
#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
5462
5463
COAP_API int
5464
coap_handle_event(coap_context_t *context, coap_event_t event,
5465
0
                  coap_session_t *session) {
5466
0
  int ret;
5467
5468
0
  coap_lock_lock(return 0);
5469
0
  ret = coap_handle_event_lkd(context, event, session);
5470
0
  coap_lock_unlock();
5471
0
  return ret;
5472
0
}
5473
5474
int
5475
coap_handle_event_lkd(coap_context_t *context, coap_event_t event,
5476
1.93k
                      coap_session_t *session) {
5477
1.93k
  int ret = 0;
5478
5479
1.93k
  coap_log_debug("***EVENT: %s\n", coap_event_name(event));
5480
5481
1.93k
#if COAP_PROXY_SUPPORT
5482
1.93k
  if (event == COAP_EVENT_SERVER_SESSION_DEL)
5483
0
    coap_proxy_remove_association(session, 0);
5484
1.93k
#endif /* COAP_PROXY_SUPPORT */
5485
5486
1.93k
  if (context->event_cb) {
5487
72
    coap_lock_callback_ret(ret, context->event_cb(session, event));
5488
72
#if COAP_CLIENT_SUPPORT
5489
72
    switch (event) {
5490
0
    case COAP_EVENT_DTLS_CLOSED:
5491
0
    case COAP_EVENT_TCP_CLOSED:
5492
0
    case COAP_EVENT_SESSION_CLOSED:
5493
0
    case COAP_EVENT_OSCORE_DECRYPTION_FAILURE:
5494
0
    case COAP_EVENT_OSCORE_NOT_ENABLED:
5495
0
    case COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD:
5496
0
    case COAP_EVENT_OSCORE_NO_SECURITY:
5497
0
    case COAP_EVENT_OSCORE_INTERNAL_ERROR:
5498
0
    case COAP_EVENT_OSCORE_DECODE_ERROR:
5499
0
    case COAP_EVENT_WS_PACKET_SIZE:
5500
4
    case COAP_EVENT_WS_CLOSED:
5501
51
    case COAP_EVENT_BAD_PACKET:
5502
51
    case COAP_EVENT_FIRST_PDU_FAIL:
5503
51
    case COAP_EVENT_RECONNECT_NO_MORE:
5504
      /* Those that are deemed fatal to end sending a request */
5505
51
      session->doing_send_recv = 0;
5506
51
      break;
5507
0
    case COAP_EVENT_DTLS_CONNECTED:
5508
      /* Session will now be available as well - for call-home */
5509
0
      if (session->type == COAP_SESSION_TYPE_SERVER && session->proto == COAP_PROTO_DTLS) {
5510
0
        coap_handle_event_lkd(context, COAP_EVENT_SERVER_SESSION_CONNECTED,
5511
0
                              session);
5512
0
      }
5513
0
      break;
5514
0
    case COAP_EVENT_DTLS_RENEGOTIATE:
5515
0
    case COAP_EVENT_DTLS_ERROR:
5516
0
    case COAP_EVENT_TCP_CONNECTED:
5517
0
    case COAP_EVENT_TCP_FAILED:
5518
0
    case COAP_EVENT_RECONNECT_FAILED:
5519
0
      break;
5520
0
    case COAP_EVENT_SESSION_CONNECTED:
5521
      /* Session will now be available as well - for call-home if not (D)TLS */
5522
0
      if (session->type == COAP_SESSION_TYPE_SERVER &&
5523
0
          (session->proto == COAP_PROTO_TCP || session->proto == COAP_PROTO_TLS)) {
5524
0
        coap_handle_event_lkd(context, COAP_EVENT_SERVER_SESSION_CONNECTED,
5525
0
                              session);
5526
0
      }
5527
0
      break;
5528
0
    case COAP_EVENT_SESSION_FAILED:
5529
0
    case COAP_EVENT_PARTIAL_BLOCK:
5530
21
    case COAP_EVENT_XMIT_BLOCK_FAIL:
5531
21
    case COAP_EVENT_BLOCK_ISSUE:
5532
21
      break;
5533
0
    case COAP_EVENT_SERVER_SESSION_NEW:
5534
      /* Session will now be available as well - for call-home if not (D)TLS */
5535
0
      if (session->proto == COAP_PROTO_UDP) {
5536
0
        coap_handle_event_lkd(context, COAP_EVENT_SERVER_SESSION_CONNECTED,
5537
0
                              session);
5538
0
      }
5539
0
      break;
5540
0
    case COAP_EVENT_SERVER_SESSION_DEL:
5541
0
    case COAP_EVENT_SERVER_SESSION_CONNECTED:
5542
0
    case COAP_EVENT_OSCORE_RECIPIENT_CHANGED:
5543
0
    case COAP_EVENT_MSG_RETRANSMITTED:
5544
0
    case COAP_EVENT_WS_CONNECTED:
5545
0
    case COAP_EVENT_KEEPALIVE_FAILURE:
5546
0
    case COAP_EVENT_RECONNECT_SUCCESS:
5547
0
    case COAP_EVENT_RECONNECT_STARTED:
5548
0
    default:
5549
0
      break;
5550
72
    }
5551
72
#endif /* COAP_CLIENT_SUPPORT */
5552
72
  }
5553
1.93k
  return ret;
5554
1.93k
}
5555
5556
COAP_API int
5557
0
coap_can_exit(coap_context_t *context) {
5558
0
  int ret;
5559
5560
0
  coap_lock_lock(return 0);
5561
0
  ret = coap_can_exit_lkd(context);
5562
0
  coap_lock_unlock();
5563
0
  return ret;
5564
0
}
5565
5566
int
5567
0
coap_can_exit_lkd(coap_context_t *context) {
5568
0
  coap_session_t *s, *rtmp;
5569
0
  if (!context)
5570
0
    return 1;
5571
0
  coap_lock_check_locked();
5572
0
  if (context->sendqueue)
5573
0
    return 0;
5574
0
#if COAP_SERVER_SUPPORT
5575
0
  coap_endpoint_t *ep;
5576
5577
0
  LL_FOREACH(context->endpoint, ep) {
5578
0
    SESSIONS_ITER(ep->sessions, s, rtmp) {
5579
0
      if (s->delayqueue)
5580
0
        return 0;
5581
0
      if (s->lg_xmit)
5582
0
        return 0;
5583
0
    }
5584
0
  }
5585
0
#endif /* COAP_SERVER_SUPPORT */
5586
0
#if COAP_CLIENT_SUPPORT
5587
0
  SESSIONS_ITER(context->sessions, s, rtmp) {
5588
0
    if (s->delayqueue)
5589
0
      return 0;
5590
0
    if (s->lg_xmit)
5591
0
      return 0;
5592
0
  }
5593
0
#endif /* COAP_CLIENT_SUPPORT */
5594
0
  return 1;
5595
0
}
5596
#if COAP_SERVER_SUPPORT
5597
#if COAP_ASYNC_SUPPORT
5598
/*
5599
 * Return 1 if there is a future expire time, else 0.
5600
 * Update tim_rem with remaining value if return is 1.
5601
 */
5602
int
5603
78
coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) {
5604
78
  coap_tick_t next_due = COAP_MAX_DELAY_TICKS;
5605
78
  coap_async_t *async, *tmp;
5606
78
  int ret = 0;
5607
5608
78
  if (context->async_state_traversing)
5609
0
    return 0;
5610
78
  context->async_state_traversing = 1;
5611
78
  LL_FOREACH_SAFE(context->async_state, async, tmp) {
5612
0
    if (async->delay != 0 && !async->session->is_rate_limiting) {
5613
0
      if (async->delay <= now) {
5614
        /* Restore the local address the request was received on */
5615
0
        coap_address_copy(&async->session->addr_info.local, &async->local_if);
5616
        /* Send off the request to the application */
5617
0
        coap_log_debug("Async PDU presented to app.\n");
5618
0
        coap_show_pdu(COAP_LOG_DEBUG, async->pdu);
5619
0
        handle_request(context, async->session, async->pdu, NULL);
5620
5621
        /* Remove this async entry as it has now fired */
5622
0
        coap_free_async_lkd(async->session, async);
5623
0
      } else {
5624
0
        next_due = async->delay - now;
5625
0
        ret = 1;
5626
0
      }
5627
0
    }
5628
0
  }
5629
78
  if (tim_rem)
5630
52
    *tim_rem = next_due;
5631
78
  context->async_state_traversing = 0;
5632
78
  return ret;
5633
78
}
5634
#endif /* COAP_ASYNC_SUPPORT */
5635
#endif /* COAP_SERVER_SUPPORT */
5636
5637
int coap_started = 0;
5638
uint8_t coap_unique_id[8] = { 0 };
5639
5640
#if COAP_THREAD_SAFE
5641
/*
5642
 * Global lock for multi-thread support
5643
 */
5644
coap_lock_t global_lock;
5645
/*
5646
 * low level protection mutex
5647
 */
5648
coap_mutex_t m_show_pdu;
5649
coap_mutex_t m_log_impl;
5650
coap_mutex_t m_io_threads;
5651
#endif /* COAP_THREAD_SAFE */
5652
5653
void
5654
18.4k
coap_startup(void) {
5655
18.4k
  coap_tick_t now;
5656
18.4k
#ifndef WITH_CONTIKI
5657
18.4k
  uint64_t us;
5658
18.4k
#endif /* !WITH_CONTIKI */
5659
5660
18.4k
  if (coap_started)
5661
0
    return;
5662
18.4k
  coap_started = 1;
5663
5664
#if COAP_THREAD_SAFE
5665
  coap_lock_init(&global_lock);
5666
  coap_mutex_init(&m_show_pdu);
5667
  coap_mutex_init(&m_log_impl);
5668
  coap_mutex_init(&m_io_threads);
5669
#endif /* COAP_THREAD_SAFE */
5670
5671
#if defined(HAVE_WINSOCK2_H)
5672
  WORD wVersionRequested = MAKEWORD(2, 2);
5673
  WSADATA wsaData;
5674
  WSAStartup(wVersionRequested, &wsaData);
5675
#endif
5676
18.4k
  coap_clock_init();
5677
18.4k
  coap_ticks(&now);
5678
18.4k
#ifndef WITH_CONTIKI
5679
18.4k
  us = coap_ticks_to_rt_us(now);
5680
  /* Be accurate to the nearest (approx) us */
5681
18.4k
  coap_prng_init_lkd((unsigned int)us);
5682
#else /* WITH_CONTIKI */
5683
  coap_start_io_process();
5684
#endif /* WITH_CONTIKI */
5685
18.4k
  coap_memory_init();
5686
18.4k
  coap_dtls_startup();
5687
#ifdef WITH_LWIP
5688
  coap_io_lwip_init();
5689
#endif /* WITH_LWIP */
5690
18.4k
#if COAP_SERVER_SUPPORT
5691
18.4k
  static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
5692
18.4k
                                         (const uint8_t *)".well-known/core"
5693
18.4k
                                       };
5694
18.4k
  memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
5695
18.4k
  resource_uri_wellknown.ref = 1;
5696
18.4k
  resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown_lkd;
5697
18.4k
  resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
5698
18.4k
  resource_uri_wellknown.uri_path = &well_known;
5699
18.4k
#endif /* COAP_SERVER_SUPPORT */
5700
18.4k
  send_recv_terminate = 0;
5701
18.4k
  coap_prng_lkd(&coap_unique_id, sizeof(coap_unique_id));
5702
18.4k
}
5703
5704
void
5705
18.4k
coap_cleanup(void) {
5706
18.4k
  if (!coap_started)
5707
0
    return;
5708
18.4k
  coap_started = 0;
5709
#if defined(HAVE_WINSOCK2_H)
5710
  WSACleanup();
5711
#elif defined(WITH_CONTIKI)
5712
  coap_stop_io_process();
5713
#endif
5714
#ifdef WITH_LWIP
5715
  coap_io_lwip_cleanup();
5716
#endif /* WITH_LWIP */
5717
18.4k
  coap_dtls_shutdown();
5718
5719
18.4k
  coap_delete_upa_chain(coap_upa_client_fallback_chain);
5720
18.4k
  coap_upa_client_fallback_chain = NULL;
5721
18.4k
  coap_delete_upa_chain(coap_upa_server_mapping_chain);
5722
18.4k
  coap_upa_server_mapping_chain = NULL;
5723
#if COAP_THREAD_SAFE
5724
  coap_mutex_destroy(&m_show_pdu);
5725
  coap_mutex_destroy(&m_log_impl);
5726
  coap_mutex_destroy(&m_io_threads);
5727
#endif /* COAP_THREAD_SAFE */
5728
5729
18.4k
  coap_debug_reset();
5730
18.4k
}
5731
5732
void
5733
coap_register_response_handler(coap_context_t *context,
5734
0
                               coap_response_handler_t handler) {
5735
0
#if COAP_CLIENT_SUPPORT
5736
0
  context->response_cb = handler;
5737
#else /* ! COAP_CLIENT_SUPPORT */
5738
  (void)context;
5739
  (void)handler;
5740
#endif /* ! COAP_CLIENT_SUPPORT */
5741
0
}
5742
5743
void
5744
coap_register_proxy_response_handler(coap_context_t *context,
5745
0
                                     coap_proxy_response_handler_t handler) {
5746
0
#if COAP_PROXY_SUPPORT
5747
0
  context->proxy_response_cb = handler;
5748
#else /* ! COAP_PROXY_SUPPORT */
5749
  (void)context;
5750
  (void)handler;
5751
#endif /* ! COAP_PROXY_SUPPORT */
5752
0
}
5753
5754
void
5755
coap_register_nack_handler(coap_context_t *context,
5756
0
                           coap_nack_handler_t handler) {
5757
0
  context->nack_cb = handler;
5758
0
}
5759
5760
void
5761
coap_register_ping_handler(coap_context_t *context,
5762
0
                           coap_ping_handler_t handler) {
5763
0
  context->ping_cb = handler;
5764
0
}
5765
5766
void
5767
coap_register_pong_handler(coap_context_t *context,
5768
0
                           coap_pong_handler_t handler) {
5769
0
  context->pong_cb = handler;
5770
0
}
5771
5772
void
5773
coap_register_dynamic_resource_handler(coap_context_t *context,
5774
                                       coap_resource_dynamic_create_t dyn_create_handler,
5775
0
                                       uint32_t dynamic_max) {
5776
0
  context->dyn_create_handler = dyn_create_handler;
5777
0
  context->dynamic_max = dynamic_max;
5778
0
  return;
5779
0
}
5780
5781
COAP_API void
5782
0
coap_register_option(coap_context_t *ctx, coap_option_num_t type) {
5783
0
  coap_lock_lock(return);
5784
0
  coap_register_option_lkd(ctx, type);
5785
0
  coap_lock_unlock();
5786
0
}
5787
5788
void
5789
0
coap_register_option_lkd(coap_context_t *ctx, coap_option_num_t type) {
5790
0
  coap_option_filter_set(&ctx->known_options, type);
5791
0
}
5792
5793
#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION && !defined(__ZEPHYR__)
5794
#if COAP_SERVER_SUPPORT
5795
COAP_API int
5796
coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
5797
0
                           const char *ifname) {
5798
0
  int ret;
5799
5800
0
  coap_lock_lock(return -1);
5801
0
  ret = coap_join_mcast_group_intf_lkd(ctx, NULL, group_name, ifname);
5802
0
  coap_lock_unlock();
5803
0
  return ret;
5804
0
}
5805
5806
int
5807
coap_join_mcast_group_intf_lkd(coap_context_t *ctx,
5808
                               coap_endpoint_t *single_endpoint,
5809
                               const char *group_name,
5810
0
                               const char *ifname) {
5811
0
#if COAP_IPV4_SUPPORT
5812
0
  struct ip_mreq mreq4;
5813
0
#endif /* COAP_IPV4_SUPPORT */
5814
0
#if COAP_IPV6_SUPPORT
5815
0
  struct ipv6_mreq mreq6;
5816
0
#endif /* COAP_IPV6_SUPPORT */
5817
0
  struct addrinfo *resmulti = NULL, hints, *ainfo;
5818
0
  int result = -1;
5819
0
  coap_endpoint_t *endpoint;
5820
#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5821
  coap_endpoint_t *lookup_endpoint;
5822
#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5823
0
  int mgroup_setup = 0;
5824
5825
0
  if (single_endpoint) {
5826
0
    if (single_endpoint->proto != COAP_PROTO_UDP)
5827
0
      return -1;
5828
#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5829
    lookup_endpoint = single_endpoint;
5830
#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5831
0
  } else {
5832
    /* Need to have at least one endpoint! */
5833
0
    assert(ctx->endpoint);
5834
0
    if (!ctx->endpoint)
5835
0
      return -1;
5836
#if !defined(ESPIDF_VERSION) && COAP_IPV6_SUPPORT && !defined(HAVE_IF_NAMETOINDEX) && !defined(__QNXNTO__)
5837
    lookup_endpoint = ctx->endpoint;
5838
#endif /* !ESPIDF_VERSION && COAP_IPV6_SUPPORT && !HAVE_IF_NAMETOINDEX && !__QNXNTO__ */
5839
0
  }
5840
5841
  /* Default is let the kernel choose */
5842
0
#if COAP_IPV6_SUPPORT
5843
0
  mreq6.ipv6mr_interface = 0;
5844
0
#endif /* COAP_IPV6_SUPPORT */
5845
0
#if COAP_IPV4_SUPPORT
5846
0
  mreq4.imr_interface.s_addr = INADDR_ANY;
5847
0
#endif /* COAP_IPV4_SUPPORT */
5848
5849
0
  memset(&hints, 0, sizeof(hints));
5850
0
  hints.ai_socktype = SOCK_DGRAM;
5851
5852
  /* resolve the multicast group address */
5853
0
  result = getaddrinfo(group_name, NULL, &hints, &resmulti);
5854
5855
0
  if (result != 0) {
5856
0
    coap_log_err("coap_join_mcast_group_intf: %s: "
5857
0
                 "Cannot resolve multicast address: %s\n",
5858
0
                 group_name, gai_strerror(result));
5859
0
    goto finish;
5860
0
  }
5861
5862
  /* Need to do a windows equivalent at some point */
5863
0
#ifndef _WIN32
5864
0
  if (ifname) {
5865
    /* interface specified - check if we have correct IPv4/IPv6 information */
5866
0
    int done_ip4 = 0;
5867
0
    int done_ip6 = 0;
5868
#if defined(ESPIDF_VERSION)
5869
    struct netif *netif;
5870
#else /* !ESPIDF_VERSION */
5871
0
#if COAP_IPV4_SUPPORT
5872
0
    int ip4fd;
5873
0
#endif /* COAP_IPV4_SUPPORT */
5874
0
    struct ifreq ifr;
5875
0
#endif /* !ESPIDF_VERSION */
5876
5877
    /* See which mcast address family types are being asked for */
5878
0
    for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
5879
0
         ainfo = ainfo->ai_next) {
5880
0
      switch (ainfo->ai_family) {
5881
0
#if COAP_IPV6_SUPPORT
5882
0
      case AF_INET6:
5883
0
        if (done_ip6)
5884
0
          break;
5885
0
        done_ip6 = 1;
5886
#if defined(ESPIDF_VERSION)
5887
        netif = netif_find(ifname);
5888
        if (netif)
5889
          mreq6.ipv6mr_interface = netif_get_index(netif);
5890
        else
5891
          coap_log_err("coap_join_mcast_group_intf: %s: "
5892
                       "Cannot get IPv4 address: %s\n",
5893
                       ifname, coap_socket_strerror());
5894
#else /* !ESPIDF_VERSION */
5895
0
        memset(&ifr, 0, sizeof(ifr));
5896
0
        strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5897
0
        ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5898
5899
0
#ifdef HAVE_IF_NAMETOINDEX
5900
0
        mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
5901
0
        if (mreq6.ipv6mr_interface == 0) {
5902
0
          coap_log_warn("coap_join_mcast_group_intf: "
5903
0
                        "cannot get interface index for '%s'\n",
5904
0
                        ifname);
5905
0
        }
5906
#elif defined(__QNXNTO__)
5907
#else /* !HAVE_IF_NAMETOINDEX */
5908
        result = ioctl(lookup_endpoint->sock.fd, SIOCGIFINDEX, &ifr);
5909
        if (result != 0) {
5910
          coap_log_warn("coap_join_mcast_group_intf: "
5911
                        "cannot get interface index for '%s': %s\n",
5912
                        ifname, coap_socket_strerror());
5913
        } else {
5914
          /* Capture the IPv6 if_index for later */
5915
          mreq6.ipv6mr_interface = ifr.ifr_ifindex;
5916
        }
5917
#endif /* !HAVE_IF_NAMETOINDEX */
5918
0
#endif /* !ESPIDF_VERSION */
5919
0
#endif /* COAP_IPV6_SUPPORT */
5920
0
        break;
5921
0
#if COAP_IPV4_SUPPORT
5922
0
      case AF_INET:
5923
0
        if (done_ip4)
5924
0
          break;
5925
0
        done_ip4 = 1;
5926
#if defined(ESPIDF_VERSION)
5927
        netif = netif_find(ifname);
5928
        if (netif)
5929
          mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
5930
        else
5931
          coap_log_err("coap_join_mcast_group_intf: %s: "
5932
                       "Cannot get IPv4 address: %s\n",
5933
                       ifname, coap_socket_strerror());
5934
#else /* !ESPIDF_VERSION */
5935
        /*
5936
         * Need an AF_INET socket to do this unfortunately to stop
5937
         * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
5938
         */
5939
0
        ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
5940
0
        if (ip4fd == -1) {
5941
0
          coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
5942
0
                       ifname, coap_socket_strerror());
5943
0
          continue;
5944
0
        }
5945
0
        memset(&ifr, 0, sizeof(ifr));
5946
0
        strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
5947
0
        ifr.ifr_name[IFNAMSIZ - 1] = '\000';
5948
0
        result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
5949
0
        if (result != 0) {
5950
0
          coap_log_err("coap_join_mcast_group_intf: %s: "
5951
0
                       "Cannot get IPv4 address: %s\n",
5952
0
                       ifname, coap_socket_strerror());
5953
0
        } else {
5954
          /* Capture the IPv4 address for later */
5955
0
          mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
5956
0
        }
5957
0
        close(ip4fd);
5958
0
#endif /* !ESPIDF_VERSION */
5959
0
        break;
5960
0
#endif /* COAP_IPV4_SUPPORT */
5961
0
      default:
5962
0
        break;
5963
0
      }
5964
0
    }
5965
0
  }
5966
#else /* _WIN32 */
5967
  /*
5968
   * On Windows this function ignores the ifname variable so we unset this
5969
   * variable on this platform in any case in order to enable the interface
5970
   * selection from the bind address below.
5971
   */
5972
  ifname = 0;
5973
#endif /* _WIN32 */
5974
5975
  /* Add in mcast address(es) to appropriate interface */
5976
0
  for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
5977
0
    for (endpoint = single_endpoint ? single_endpoint : ctx->endpoint;
5978
0
         endpoint != NULL;
5979
0
         endpoint = single_endpoint ? NULL : endpoint->next) {
5980
      /* Only UDP currently supported */
5981
0
      if (endpoint->proto == COAP_PROTO_UDP) {
5982
0
        coap_address_t gaddr;
5983
5984
0
        coap_address_init(&gaddr);
5985
0
#if COAP_IPV6_SUPPORT
5986
0
        if (ainfo->ai_family == AF_INET6) {
5987
0
          if (!ifname) {
5988
0
            if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
5989
              /*
5990
               * Do it on the ifindex that the server is listening on
5991
               * (sin6_scope_id could still be 0)
5992
               */
5993
0
              mreq6.ipv6mr_interface =
5994
0
                  endpoint->bind_addr.addr.sin6.sin6_scope_id;
5995
0
            } else {
5996
0
              mreq6.ipv6mr_interface = 0;
5997
0
            }
5998
0
          }
5999
0
          gaddr.addr.sin6.sin6_family = AF_INET6;
6000
0
          gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
6001
0
          gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
6002
0
                                          ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
6003
0
          result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
6004
0
                              (char *)&mreq6, sizeof(mreq6));
6005
0
        }
6006
0
#endif /* COAP_IPV6_SUPPORT */
6007
0
#if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
6008
0
        else
6009
0
#endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
6010
0
#if COAP_IPV4_SUPPORT
6011
0
          if (ainfo->ai_family == AF_INET) {
6012
0
            if (!ifname) {
6013
0
              if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
6014
                /*
6015
                 * Do it on the interface that the server is listening on
6016
                 * (sin_addr could still be INADDR_ANY)
6017
                 */
6018
0
                mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
6019
0
              } else {
6020
0
                mreq4.imr_interface.s_addr = INADDR_ANY;
6021
0
              }
6022
0
            }
6023
0
            gaddr.addr.sin.sin_family = AF_INET;
6024
0
            gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
6025
0
            gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
6026
0
                                                 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
6027
0
            result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
6028
0
                                (char *)&mreq4, sizeof(mreq4));
6029
0
          }
6030
0
#endif /* COAP_IPV4_SUPPORT */
6031
0
          else {
6032
0
            continue;
6033
0
          }
6034
6035
0
        if (result == COAP_SOCKET_ERROR) {
6036
0
          coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
6037
0
                       group_name, coap_socket_strerror());
6038
0
        } else {
6039
0
          char addr_str[INET6_ADDRSTRLEN + 8 + 1];
6040
6041
0
          addr_str[sizeof(addr_str)-1] = '\000';
6042
0
          if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
6043
0
                              sizeof(addr_str) - 1)) {
6044
0
            if (ifname)
6045
0
              coap_log_debug("added mcast group %s i/f %s\n", addr_str,
6046
0
                             ifname);
6047
0
            else
6048
0
              coap_log_debug("added mcast group %s\n", addr_str);
6049
0
          }
6050
0
          mgroup_setup = 1;
6051
0
        }
6052
0
      }
6053
0
    }
6054
0
  }
6055
0
  if (!mgroup_setup) {
6056
0
    result = -1;
6057
0
  }
6058
6059
0
finish:
6060
0
  freeaddrinfo(resmulti);
6061
6062
0
  return result;
6063
0
}
6064
6065
COAP_API int
6066
coap_endpoint_join_mcast_group_intf(coap_endpoint_t *endpoint,
6067
                                    const char *group_name,
6068
0
                                    const char *ifname) {
6069
0
  int ret;
6070
6071
0
  if (!endpoint || !endpoint->context)
6072
0
    return -1;
6073
6074
0
  coap_lock_lock(return -1);
6075
0
  ret = coap_join_mcast_group_intf_lkd(endpoint->context, endpoint, group_name, ifname);
6076
0
  coap_lock_unlock();
6077
0
  return ret;
6078
0
}
6079
6080
void
6081
0
coap_mcast_per_resource(coap_context_t *context) {
6082
0
  context->mcast_per_resource = 1;
6083
0
}
6084
6085
#endif /* ! COAP_SERVER_SUPPORT */
6086
6087
#if COAP_CLIENT_SUPPORT
6088
int
6089
0
coap_mcast_set_hops(coap_session_t *session, size_t hops) {
6090
0
  if (session && coap_is_mcast(&session->addr_info.remote)) {
6091
0
    switch (session->addr_info.remote.addr.sa.sa_family) {
6092
0
#if COAP_IPV4_SUPPORT
6093
0
    case AF_INET:
6094
0
      if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
6095
0
                     (const char *)&hops, sizeof(hops)) < 0) {
6096
0
        coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
6097
0
                      hops, coap_socket_strerror());
6098
0
        return 0;
6099
0
      }
6100
0
      return 1;
6101
0
#endif /* COAP_IPV4_SUPPORT */
6102
0
#if COAP_IPV6_SUPPORT
6103
0
    case AF_INET6:
6104
0
      if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
6105
0
                     (const char *)&hops, sizeof(hops)) < 0) {
6106
0
        coap_log_info("coap_mcast_set_hops: %" PRIuS ": setsockopt: %s\n",
6107
0
                      hops, coap_socket_strerror());
6108
0
        return 0;
6109
0
      }
6110
0
      return 1;
6111
0
#endif /* COAP_IPV6_SUPPORT */
6112
0
    default:
6113
0
      break;
6114
0
    }
6115
0
  }
6116
0
  return 0;
6117
0
}
6118
#endif /* COAP_CLIENT_SUPPORT */
6119
6120
#else /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */
6121
COAP_API int
6122
coap_join_mcast_group_intf(coap_context_t *ctx COAP_UNUSED,
6123
                           const char *group_name COAP_UNUSED,
6124
                           const char *ifname COAP_UNUSED) {
6125
  return -1;
6126
}
6127
6128
COAP_API int
6129
coap_endpoint_join_mcast_group_intf(coap_endpoint_t *endpoint COAP_UNUSED,
6130
                                    const char *group_name COAP_UNUSED,
6131
                                    const char *ifname COAP_UNUSED) {
6132
  return -1;
6133
}
6134
6135
int
6136
coap_mcast_set_hops(coap_session_t *session COAP_UNUSED,
6137
                    size_t hops COAP_UNUSED) {
6138
  return 0;
6139
}
6140
6141
void
6142
coap_mcast_per_resource(coap_context_t *context COAP_UNUSED) {
6143
}
6144
#endif /* defined WITH_CONTIKI || defined WITH_LWIP || defined RIOT_VERSION || defined(__ZEPHYR__) */