Coverage Report

Created: 2026-09-28 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libcoap/src/coap_session.c
Line
Count
Source
1
/* coap_session.c -- Session management for libcoap
2
 *
3
 * Copyright (C) 2017      Jean-Claue Michelou <jcm@spinetix.com>
4
 * Copyright (C) 2022-2026 Jon Shallow <supjps-libcoap@jpshallow.com>
5
 *
6
 * SPDX-License-Identifier: BSD-2-Clause
7
 *
8
 * This file is part of the CoAP library libcoap. Please see
9
 * README for terms of use.
10
 */
11
12
/**
13
 * @file coap_session.c
14
 * @brief Session handling functions
15
 */
16
17
#include "coap3/coap_libcoap_build.h"
18
19
#ifndef COAP_SESSION_C_
20
#define COAP_SESSION_C_
21
22
#include <stdio.h>
23
24
#ifdef COAP_EPOLL_SUPPORT
25
#include <sys/epoll.h>
26
#include <sys/timerfd.h>
27
#endif /* COAP_EPOLL_SUPPORT */
28
29
coap_fixed_point_t
30
5.06k
coap_multi_fixed_fixed(coap_fixed_point_t fp1, coap_fixed_point_t fp2) {
31
5.06k
  coap_fixed_point_t res;
32
5.06k
  uint32_t fr = fp1.fractional_part * fp2.fractional_part;
33
34
5.06k
  res.integer_part = fp1.integer_part * fp2.integer_part + fr/1000;
35
5.06k
  res.fractional_part = fr % 1000;
36
5.06k
  return res;
37
5.06k
}
38
39
coap_fixed_point_t
40
5.06k
coap_multi_fixed_uint(coap_fixed_point_t fp1, uint32_t u2) {
41
5.06k
  coap_fixed_point_t res;
42
5.06k
  uint32_t fr = fp1.fractional_part * u2;
43
44
5.06k
  res.integer_part = fp1.integer_part * u2 + fr/1000;
45
5.06k
  res.fractional_part = fr % 1000;
46
5.06k
  return res;
47
5.06k
}
48
49
coap_fixed_point_t
50
2.53k
coap_add_fixed_fixed(coap_fixed_point_t fp1, coap_fixed_point_t fp2) {
51
2.53k
  coap_fixed_point_t res;
52
2.53k
  uint32_t fr = fp1.fractional_part + fp2.fractional_part;
53
54
2.53k
  res.integer_part = fp1.integer_part + fp2.integer_part + fr/1000;
55
2.53k
  res.fractional_part = fr % 1000;
56
2.53k
  return res;
57
2.53k
}
58
59
coap_fixed_point_t
60
5.06k
coap_add_fixed_uint(coap_fixed_point_t fp1, uint32_t u2) {
61
5.06k
  coap_fixed_point_t res = fp1;
62
63
5.06k
  res.integer_part += u2;
64
5.06k
  return res;
65
5.06k
}
66
67
coap_fixed_point_t
68
0
coap_sub_fixed_uint(coap_fixed_point_t fp1, uint32_t u2) {
69
0
  coap_fixed_point_t res = fp1;
70
71
0
  res.integer_part -= u2;
72
0
  return res;
73
0
}
74
75
coap_fixed_point_t
76
0
coap_div_fixed_uint(coap_fixed_point_t fp1, uint32_t u2) {
77
0
  coap_fixed_point_t res;
78
0
  uint32_t num = (fp1.integer_part * 1000 + fp1.fractional_part) / u2;
79
80
0
  res.integer_part = num / 1000;
81
0
  res.fractional_part = num % 1000;
82
0
  return res;
83
0
}
84
85
#if COAP_Q_BLOCK_SUPPORT
86
coap_fixed_point_t
87
0
coap_get_non_timeout_random(coap_session_t *session) {
88
0
  coap_fixed_point_t res;
89
0
  uint8_t ran;
90
91
0
  coap_prng_lkd(&ran, sizeof(ran));
92
0
  res = coap_sub_fixed_uint(COAP_ACK_RANDOM_FACTOR(session), 1);
93
0
  res = coap_multi_fixed_uint(res, ran);
94
0
  res = coap_div_fixed_uint(res, 0xff);
95
0
  res = coap_add_fixed_fixed(COAP_NON_TIMEOUT(session), res);
96
0
  return res;
97
0
}
98
99
coap_tick_t
100
0
coap_get_non_timeout_random_ticks(coap_session_t *session) {
101
0
  coap_fixed_point_t res = coap_get_non_timeout_random(session);
102
0
  coap_tick_t ticks = (res.integer_part * COAP_TICKS_PER_SECOND +
103
0
                       res.fractional_part * COAP_TICKS_PER_SECOND / 1000);
104
105
0
  return ticks;
106
0
}
107
108
/*
109
 * Save away derived Congestion Control parameters for speed of access.
110
 * They will get updated whenever a component variable is updated.
111
 */
112
113
/*
114
 * NON_PROBING_WAIT = NON_TIMEOUT * ((2 ** NON_MAX_RETRANSMIT) - 1) *
115
 * ACK_RANDOM_FACTOR + (2 * MAX_LATENCY) + NON_TIMEOUT_RANDOM
116
 *
117
 * Do not include NON_TIMEOUT_RANDOM as that changes
118
 */
119
static void
120
2.53k
coap_session_fix_non_probing_wait_base(coap_session_t *s) {
121
2.53k
  coap_fixed_point_t res;
122
123
2.53k
  res = coap_multi_fixed_uint(COAP_NON_TIMEOUT(s),
124
2.53k
                              ((1 << (COAP_NON_MAX_RETRANSMIT(s) + 1)) -1));
125
2.53k
  res = coap_multi_fixed_fixed(res, COAP_ACK_RANDOM_FACTOR(s));
126
2.53k
  res = coap_add_fixed_uint(res, 2 * COAP_DEFAULT_MAX_LATENCY);
127
2.53k
  COAP_NON_PROBING_WAIT_BASE(s) = res;
128
2.53k
}
129
130
/*
131
 * NON_PARTIAL_TIMEOUT = NON_TIMEOUT * ((2 ** NON_MAX_RETRANSMIT) - 1) *
132
 * ACK_RANDOM_FACTOR + (2 * MAX_LATENCY) + NON_TIMEOUT
133
 */
134
static void
135
2.53k
coap_session_fix_non_partial_timeout(coap_session_t *s) {
136
2.53k
  coap_fixed_point_t res;
137
138
2.53k
  res = coap_multi_fixed_uint(COAP_NON_TIMEOUT(s),
139
2.53k
                              ((1 << (COAP_NON_MAX_RETRANSMIT(s) + 1)) -1));
140
2.53k
  res = coap_multi_fixed_fixed(res, COAP_ACK_RANDOM_FACTOR(s));
141
2.53k
  res = coap_add_fixed_uint(res, 2 * COAP_DEFAULT_MAX_LATENCY);
142
2.53k
  res = coap_add_fixed_fixed(res, COAP_NON_TIMEOUT(s));
143
2.53k
  COAP_NON_PARTIAL_TIMEOUT(s) = res;
144
2.53k
}
145
#endif /* COAP_Q_BLOCK_SUPPORT */
146
147
void
148
0
coap_session_set_ack_timeout(coap_session_t *session, coap_fixed_point_t value) {
149
0
  if (value.integer_part > 0 && value.fractional_part < 1000) {
150
0
    session->ack_timeout = value;
151
0
    coap_log_debug("***%s: session ack_timeout set to %u.%03u\n",
152
0
                   coap_session_str(session), session->ack_timeout.integer_part,
153
0
                   session->ack_timeout.fractional_part);
154
0
  }
155
0
}
156
157
void
158
coap_session_set_ack_random_factor(coap_session_t *session,
159
0
                                   coap_fixed_point_t value) {
160
0
  if (value.integer_part > 0 && value.fractional_part < 1000) {
161
0
    session->ack_random_factor = value;
162
0
    coap_log_debug("***%s: session ack_random_factor set to %u.%03u\n",
163
0
                   coap_session_str(session), session->ack_random_factor.integer_part,
164
0
                   session->ack_random_factor.fractional_part);
165
0
#if COAP_Q_BLOCK_SUPPORT
166
0
    coap_session_fix_non_probing_wait_base(session);
167
0
    coap_session_fix_non_partial_timeout(session);
168
0
#endif /* COAP_Q_BLOCK_SUPPORT */
169
0
  }
170
0
  return;
171
0
}
172
173
void
174
0
coap_session_set_max_retransmit(coap_session_t *session, uint16_t value) {
175
0
  if (value > 0xff)
176
0
    value = 0xff;
177
0
  if (value > 0) {
178
0
    session->max_retransmit = value;
179
0
    coap_log_debug("***%s: session max_retransmit set to %u\n",
180
0
                   coap_session_str(session), session->max_retransmit);
181
0
  }
182
0
}
183
184
void
185
0
coap_session_set_nstart(coap_session_t *session, uint16_t value) {
186
0
  if (value > 0) {
187
0
    session->nstart = value;
188
0
    coap_log_debug("***%s: session nstart set to %u\n",
189
0
                   coap_session_str(session), session->nstart);
190
0
  }
191
0
}
192
193
void
194
coap_session_set_default_leisure(coap_session_t *session,
195
0
                                 coap_fixed_point_t value) {
196
0
  if (value.integer_part > 0 && value.fractional_part < 1000) {
197
0
    session->default_leisure = value;
198
0
    coap_log_debug("***%s: session default_leisure set to %u.%03u\n",
199
0
                   coap_session_str(session), session->default_leisure.integer_part,
200
0
                   session->default_leisure.fractional_part);
201
0
  }
202
0
}
203
204
void
205
0
coap_session_set_probing_rate(coap_session_t *session, uint32_t value) {
206
0
  if (value > 0) {
207
0
    session->probing_rate = value;
208
0
    coap_log_debug("***%s: session probing_rate set to %" PRIu32 "\n",
209
0
                   coap_session_str(session), session->probing_rate);
210
0
  }
211
0
}
212
213
void
214
0
coap_session_set_max_payloads(coap_session_t *session, uint16_t value) {
215
0
#if COAP_Q_BLOCK_SUPPORT
216
0
  if (value > 0) {
217
0
    session->max_payloads = value;
218
0
    coap_log_debug("***%s: session max_payloads set to %u\n",
219
0
                   coap_session_str(session), session->max_payloads);
220
0
    coap_session_fix_non_probing_wait_base(session);
221
0
    coap_session_fix_non_partial_timeout(session);
222
0
  }
223
#else /* ! COAP_Q_BLOCK_SUPPORT */
224
  (void)session;
225
  (void)value;
226
#endif /* ! COAP_Q_BLOCK_SUPPORT */
227
0
}
228
229
void
230
0
coap_session_set_non_max_retransmit(coap_session_t *session, uint16_t value) {
231
0
#if COAP_Q_BLOCK_SUPPORT
232
0
  if (value > 0) {
233
0
    session->non_max_retransmit = value;
234
0
    coap_log_debug("***%s: session non_max_retransmit set to %u\n",
235
0
                   coap_session_str(session), session->non_max_retransmit);
236
0
    coap_session_fix_non_probing_wait_base(session);
237
0
    coap_session_fix_non_partial_timeout(session);
238
0
  }
239
#else /* ! COAP_Q_BLOCK_SUPPORT */
240
  (void)session;
241
  (void)value;
242
#endif /* ! COAP_Q_BLOCK_SUPPORT */
243
0
}
244
245
void
246
coap_session_set_non_timeout(coap_session_t *session,
247
0
                             coap_fixed_point_t value) {
248
0
#if COAP_Q_BLOCK_SUPPORT
249
0
  if (value.integer_part > 0 && value.fractional_part < 1000) {
250
0
    session->non_timeout = value;
251
0
    coap_log_debug("***%s: session non_timeout set to %u.%03u\n",
252
0
                   coap_session_str(session), session->non_timeout.integer_part,
253
0
                   session->non_timeout.fractional_part);
254
0
    coap_session_fix_non_probing_wait_base(session);
255
0
    coap_session_fix_non_partial_timeout(session);
256
0
  }
257
#else /* ! COAP_Q_BLOCK_SUPPORT */
258
  (void)session;
259
  (void)value;
260
#endif /* ! COAP_Q_BLOCK_SUPPORT */
261
0
}
262
263
void
264
coap_session_set_non_receive_timeout(coap_session_t *session,
265
0
                                     coap_fixed_point_t value) {
266
0
#if COAP_Q_BLOCK_SUPPORT
267
0
  if (value.integer_part > 0 && value.fractional_part < 1000)
268
0
    session->non_receive_timeout = value;
269
0
  coap_log_debug("***%s: session non_receive_timeout set to %u.%03u\n",
270
0
                 coap_session_str(session),
271
0
                 session->non_receive_timeout.integer_part,
272
0
                 session->non_receive_timeout.fractional_part);
273
#else /* ! COAP_Q_BLOCK_SUPPORT */
274
  (void)session;
275
  (void)value;
276
#endif /* ! COAP_Q_BLOCK_SUPPORT */
277
0
}
278
279
coap_fixed_point_t
280
0
coap_session_get_ack_timeout(const coap_session_t *session) {
281
0
  return session->ack_timeout;
282
0
}
283
284
coap_fixed_point_t
285
0
coap_session_get_ack_random_factor(const coap_session_t *session) {
286
0
  return session->ack_random_factor;
287
0
}
288
289
uint16_t
290
0
coap_session_get_max_retransmit(const coap_session_t *session) {
291
0
  return session->max_retransmit;
292
0
}
293
294
uint16_t
295
0
coap_session_get_nstart(const coap_session_t *session) {
296
0
  return session->nstart;
297
0
}
298
299
coap_fixed_point_t
300
0
coap_session_get_default_leisure(const coap_session_t *session) {
301
0
  return session->default_leisure;
302
0
}
303
304
uint32_t
305
0
coap_session_get_probing_rate(const coap_session_t *session) {
306
0
  return session->probing_rate;
307
0
}
308
309
uint16_t
310
0
coap_session_get_max_payloads(const coap_session_t *session) {
311
0
#if COAP_Q_BLOCK_SUPPORT
312
0
  return session->max_payloads;
313
#else /* ! COAP_Q_BLOCK_SUPPORT */
314
  (void)session;
315
  return COAP_DEFAULT_MAX_PAYLOADS;
316
#endif /* ! COAP_Q_BLOCK_SUPPORT */
317
0
}
318
319
uint16_t
320
0
coap_session_get_non_max_retransmit(const coap_session_t *session) {
321
0
#if COAP_Q_BLOCK_SUPPORT
322
0
  return session->non_max_retransmit;
323
#else /* ! COAP_Q_BLOCK_SUPPORT */
324
  (void)session;
325
  return COAP_DEFAULT_NON_MAX_RETRANSMIT;
326
#endif /* ! COAP_Q_BLOCK_SUPPORT */
327
0
}
328
329
coap_fixed_point_t
330
0
coap_session_get_non_timeout(const coap_session_t *session) {
331
0
#if COAP_Q_BLOCK_SUPPORT
332
0
  return session->non_timeout;
333
#else /* ! COAP_Q_BLOCK_SUPPORT */
334
  (void)session;
335
  return COAP_DEFAULT_NON_TIMEOUT;
336
#endif /* ! COAP_Q_BLOCK_SUPPORT */
337
0
}
338
339
coap_fixed_point_t
340
0
coap_session_get_non_receive_timeout(const coap_session_t *session) {
341
0
#if COAP_Q_BLOCK_SUPPORT
342
0
  return session->non_receive_timeout;
343
#else /* ! COAP_Q_BLOCK_SUPPORT */
344
  (void)session;
345
  return COAP_DEFAULT_NON_RECEIVE_TIMEOUT;
346
#endif /* ! COAP_Q_BLOCK_SUPPORT */
347
0
}
348
349
COAP_API coap_session_t *
350
0
coap_session_reference(coap_session_t *session) {
351
0
  coap_lock_lock(return NULL);
352
0
  coap_session_reference_lkd(session);
353
0
  coap_lock_unlock();
354
0
  return session;
355
0
}
356
357
coap_session_t *
358
10.1k
coap_session_reference_lkd(coap_session_t *session) {
359
10.1k
  ++session->ref;
360
10.1k
  return session;
361
10.1k
}
362
363
COAP_API void
364
0
coap_session_release(coap_session_t *session) {
365
0
  if (session) {
366
#if COAP_THREAD_SAFE
367
    coap_context_t *context = session->context;
368
    (void)context;
369
#endif /* COAP_THREAD_SAFE */
370
371
0
    coap_lock_lock(return);
372
0
    coap_session_release_lkd(session);
373
0
    coap_lock_unlock();
374
0
  }
375
0
}
376
377
void
378
7.59k
coap_session_release_lkd(coap_session_t *session) {
379
7.59k
  if (session) {
380
7.59k
    coap_lock_check_locked();
381
7.59k
#ifndef __COVERITY__
382
7.59k
    assert(session->ref > 0);
383
7.59k
    if (session->ref > 0)
384
7.59k
      --session->ref;
385
7.59k
    if (session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT)
386
2.53k
      coap_session_free(session);
387
#else /* __COVERITY__ */
388
    /* Coverity scan is fooled by the reference counter leading to
389
     * false positives for USE_AFTER_FREE. */
390
    --session->ref;
391
    __coverity_negative_sink__(session->ref);
392
    /* Indicate that resources are released properly. */
393
    if (session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT) {
394
      __coverity_free__(session);
395
    }
396
#endif /* __COVERITY__ */
397
7.59k
  }
398
7.59k
}
399
400
COAP_API void
401
0
coap_session_set_app_data(coap_session_t *session, void *app_data) {
402
0
  assert(session);
403
0
  coap_lock_lock(return);
404
0
  coap_session_set_app_data2_lkd(session, app_data, NULL);
405
0
  coap_lock_unlock();
406
0
}
407
408
void *
409
0
coap_session_get_app_data(const coap_session_t *session) {
410
0
  assert(session);
411
0
  return session->app_data;
412
0
}
413
414
COAP_API void *
415
coap_session_set_app_data2(coap_session_t *session, void *app_data,
416
0
                           coap_app_data_free_callback_t callback) {
417
0
  void *old_data;
418
419
0
  coap_lock_lock(return NULL);
420
0
  old_data = coap_session_set_app_data2_lkd(session, app_data, callback);
421
0
  coap_lock_unlock();
422
0
  return old_data;
423
0
}
424
425
void *
426
coap_session_set_app_data2_lkd(coap_session_t *session, void *app_data,
427
0
                               coap_app_data_free_callback_t callback) {
428
0
  void *old_data = session->app_data;
429
430
0
  session->app_data = app_data;
431
0
  session->app_cb = app_data ? callback : NULL;
432
0
  return old_data;
433
0
}
434
435
static coap_session_t *
436
coap_make_session(coap_proto_t proto, coap_session_type_t type,
437
                  const coap_addr_hash_t *addr_hash,
438
                  const coap_address_t *local_addr,
439
                  const coap_address_t *remote_addr, int ifindex,
440
2.53k
                  coap_context_t *context, coap_endpoint_t *endpoint) {
441
2.53k
  coap_session_t *session = (coap_session_t *)coap_malloc_type(COAP_SESSION,
442
2.53k
                            sizeof(coap_session_t));
443
#if ! COAP_SERVER_SUPPORT
444
  (void)endpoint;
445
#endif /* ! COAP_SERVER_SUPPORT */
446
2.53k
  if (!session)
447
0
    return NULL;
448
2.53k
  memset(session, 0, sizeof(*session));
449
2.53k
  session->proto = proto;
450
2.53k
  session->type = type;
451
2.53k
  if (addr_hash)
452
0
    memcpy(&session->addr_hash, addr_hash, sizeof(session->addr_hash));
453
2.53k
  else
454
2.53k
    memset(&session->addr_hash, 0, sizeof(session->addr_hash));
455
2.53k
  if (local_addr) {
456
0
    coap_address_copy(&session->addr_info.local, local_addr);
457
0
#if COAP_CLIENT_SUPPORT
458
0
    coap_address_copy(&session->local_reconnect, local_addr);
459
0
#endif /* COAP_CLIENT_SUPPORT */
460
2.53k
  } else {
461
2.53k
    coap_address_init(&session->addr_info.local);
462
2.53k
#if COAP_CLIENT_SUPPORT
463
2.53k
    coap_address_init(&session->local_reconnect);
464
2.53k
#endif /* COAP_CLIENT_SUPPORT */
465
2.53k
  }
466
2.53k
  if (remote_addr)
467
2.53k
    coap_address_copy(&session->addr_info.remote, remote_addr);
468
0
  else
469
0
    coap_address_init(&session->addr_info.remote);
470
2.53k
  session->ifindex = ifindex;
471
2.53k
  session->context = context;
472
2.53k
#if COAP_CLIENT_SUPPORT
473
2.53k
  if (type == COAP_SESSION_TYPE_CLIENT) {
474
2.53k
    session->client_initiated = 1;
475
2.53k
  }
476
2.53k
#endif /* COAP_CLIENT_SUPPORT */
477
2.53k
#if COAP_SERVER_SUPPORT
478
2.53k
  session->endpoint = endpoint;
479
2.53k
  if (endpoint)
480
0
    session->mtu = endpoint->default_mtu;
481
2.53k
  else
482
2.53k
#endif /* COAP_SERVER_SUPPORT */
483
2.53k
    coap_session_set_mtu(session, COAP_DEFAULT_MTU);
484
2.53k
  session->block_mode = context->block_mode;
485
2.53k
#if COAP_Q_BLOCK_SUPPORT
486
2.53k
  if (session->block_mode & COAP_BLOCK_FORCE_Q_BLOCK) {
487
0
    set_block_mode_has_q(session->block_mode);
488
0
  }
489
2.53k
#endif
490
2.53k
  if (proto == COAP_PROTO_DTLS) {
491
0
    session->tls_overhead = 29;
492
0
    if (session->tls_overhead >= session->mtu) {
493
0
      session->tls_overhead = session->mtu;
494
0
      coap_log_err("DTLS overhead exceeds MTU\n");
495
0
    }
496
0
  }
497
2.53k
  session->rl_ticks_per_packet = context->rl_ticks_per_packet;
498
2.53k
  session->ack_timeout = COAP_DEFAULT_ACK_TIMEOUT;
499
2.53k
  session->ack_random_factor = COAP_DEFAULT_ACK_RANDOM_FACTOR;
500
2.53k
  session->max_retransmit = COAP_DEFAULT_MAX_RETRANSMIT;
501
2.53k
  session->nstart = COAP_DEFAULT_NSTART;
502
2.53k
  session->default_leisure = COAP_DEFAULT_DEFAULT_LEISURE;
503
2.53k
  session->probing_rate = COAP_DEFAULT_PROBING_RATE;
504
2.53k
#if COAP_Q_BLOCK_SUPPORT
505
2.53k
  session->max_payloads = COAP_DEFAULT_MAX_PAYLOADS;
506
2.53k
  session->non_max_retransmit = COAP_DEFAULT_NON_MAX_RETRANSMIT;
507
2.53k
  session->non_timeout = COAP_DEFAULT_NON_TIMEOUT;
508
2.53k
  session->non_receive_timeout = COAP_DEFAULT_NON_RECEIVE_TIMEOUT;
509
2.53k
  coap_session_fix_non_probing_wait_base(session);
510
2.53k
  coap_session_fix_non_partial_timeout(session);
511
2.53k
#endif /* COAP_Q_BLOCK_SUPPORT */
512
2.53k
  session->dtls_event = -1;
513
2.53k
  session->last_ping_mid = COAP_INVALID_MID;
514
2.53k
  session->last_resp_mid = COAP_INVALID_MID;
515
2.53k
  session->last_con_handler_res = COAP_RESPONSE_OK;
516
2.53k
  session->max_token_size = context->max_token_size; /* RFC8974 */
517
2.53k
  if (session->type != COAP_SESSION_TYPE_CLIENT)
518
0
    session->max_token_checked = COAP_EXT_T_CHECKED;
519
520
  /* Randomly initialize */
521
  /* TCP/TLS have no notion of mid */
522
2.53k
  if (COAP_PROTO_NOT_RELIABLE(session->proto))
523
2.53k
    coap_prng_lkd((unsigned char *)&session->tx_mid, sizeof(session->tx_mid));
524
2.53k
  coap_prng_lkd((unsigned char *)&session->tx_rtag, sizeof(session->tx_rtag));
525
526
2.53k
  return session;
527
2.53k
}
528
529
void
530
2.53k
coap_session_mfree(coap_session_t *session) {
531
2.53k
  coap_queue_t *q;
532
2.53k
  coap_lg_xmit_t *lq, *ltmp;
533
534
2.53k
#if COAP_PROXY_SUPPORT
535
2.53k
  if (session->ref_proxy_subs)
536
0
    coap_delete_proxy_subscriber(session, NULL, 0, COAP_PROXY_SUBS_ALL);
537
2.53k
#endif /* COAP_PROXY_SUPPORT */
538
2.53k
#if COAP_CLIENT_SUPPORT
539
2.53k
  coap_lg_crcv_t *lg_crcv, *etmp;
540
541
  /* Need to do this before (D)TLS and socket is closed down */
542
2.53k
  LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, etmp) {
543
0
    if (lg_crcv->observe_set && session->no_observe_cancel == 0) {
544
      /* Need to close down observe */
545
0
      if (coap_cancel_observe_lkd(session, lg_crcv->app_token, COAP_MESSAGE_NON)) {
546
        /* Need to delete node we set up for NON */
547
0
        coap_queue_t *queue = session->context->sendqueue;
548
549
0
        while (queue) {
550
0
          if (queue->session == session) {
551
0
            coap_delete_node_lkd(queue);
552
0
            break;
553
0
          }
554
0
          queue = queue->next;
555
0
        }
556
0
      }
557
0
    }
558
    /* In case coap_cancel_observe_lkd() failure, which could clear down lg_crcv */
559
0
    if (!session->lg_crcv)
560
0
      break;
561
0
    LL_DELETE(session->lg_crcv, lg_crcv);
562
0
    coap_block_delete_lg_crcv(session, lg_crcv);
563
0
  }
564
2.53k
#endif /* COAP_CLIENT_SUPPORT */
565
566
2.53k
  while ((q = coap_remove_first_from_delayq(session)) != NULL) {
567
0
    if (q->pdu->type==COAP_MESSAGE_CON) {
568
0
      coap_handle_nack(session, q->pdu,
569
0
                       session->proto == COAP_PROTO_DTLS ?
570
0
                       COAP_NACK_TLS_FAILED : COAP_NACK_NOT_DELIVERABLE,
571
0
                       q->id);
572
0
    }
573
0
    coap_delete_node_lkd(q);
574
0
  }
575
576
2.53k
#if COAP_CLIENT_SUPPORT
577
2.53k
  coap_pdu_t *p, *ptmp;
578
579
2.53k
  LL_FOREACH_SAFE(session->doing_first_pdu, p, ptmp) {
580
0
    if (p->type==COAP_MESSAGE_CON) {
581
0
      coap_handle_nack(session, p,
582
0
                       session->proto == COAP_PROTO_DTLS ?
583
0
                       COAP_NACK_TLS_FAILED : COAP_NACK_NOT_DELIVERABLE,
584
0
                       p->mid);
585
0
    }
586
0
    coap_delete_pdu_lkd(p);
587
0
  }
588
2.53k
#endif /* COAP_CLIENT_SUPPORT */
589
590
2.53k
  if (session->partial_pdu)
591
0
    coap_delete_pdu_lkd(session->partial_pdu);
592
2.53k
  if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
593
2.53k
    session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
594
2.53k
  if (session->psk_identity)
595
0
    coap_delete_bin_const(session->psk_identity);
596
2.53k
  if (session->psk_key)
597
0
    coap_delete_bin_const(session->psk_key);
598
2.53k
  if (session->psk_hint)
599
0
    coap_delete_bin_const(session->psk_hint);
600
601
2.53k
#ifdef HAVE_LINUX_ERRQUEUE_H
602
2.53k
  coap_delete_str_const(session->last_data_write);
603
2.53k
#endif /* HAVE_LINUX_ERRQUEUE_H */
604
605
2.53k
#if COAP_SERVER_SUPPORT
606
2.53k
  coap_cache_entry_t *cp, *ctmp;
607
2.53k
  HASH_ITER(hh, session->context->cache, cp, ctmp) {
608
    /* cp->session is NULL if not session based */
609
0
    if (cp->session == session) {
610
0
      coap_delete_cache_entry(session->context, cp);
611
0
    }
612
0
  }
613
2.53k
#endif /* COAP_PROXY_SUPPORT */
614
2.53k
  LL_FOREACH_SAFE(session->lg_xmit, lq, ltmp) {
615
0
    LL_DELETE(session->lg_xmit, lq);
616
0
    coap_block_delete_lg_xmit(session, lq);
617
0
  }
618
2.53k
#if COAP_SERVER_SUPPORT
619
2.53k
  coap_lg_srcv_t *sq, *stmp;
620
621
2.53k
  LL_FOREACH_SAFE(session->lg_srcv, sq, stmp) {
622
0
    LL_DELETE(session->lg_srcv, sq);
623
0
    coap_block_delete_lg_srcv(session, sq);
624
0
  }
625
2.53k
#endif /* COAP_SERVER_SUPPORT */
626
2.53k
#if COAP_OSCORE_SUPPORT
627
2.53k
  coap_delete_oscore_associations(session);
628
2.53k
  oscore_release_recipient_ctx(&session->recipient_ctx);
629
2.53k
  coap_delete_str_const(session->b_2_retransmit_token);
630
2.53k
#endif /* COAP_OSCORE_SUPPORT */
631
2.53k
#if COAP_WS_SUPPORT
632
2.53k
  coap_free_type(COAP_STRING, session->ws);
633
2.53k
  coap_delete_str_const(session->ws_host);
634
2.53k
#endif /* COAP_WS_SUPPORT */
635
2.53k
}
636
637
void
638
2.53k
coap_session_free(coap_session_t *session) {
639
2.53k
  if (!session)
640
0
    return;
641
2.53k
  coap_lock_check_locked();
642
2.53k
  assert(session->ref == 0);
643
2.53k
  if (session->ref)
644
0
    return;
645
  /* Make sure nothing gets deleted under our feet */
646
2.53k
  coap_session_reference_lkd(session);
647
2.53k
  coap_session_mfree(session);
648
2.53k
#if COAP_SERVER_SUPPORT
649
2.53k
  coap_delete_bin_const(session->client_cid);
650
2.53k
  if (session->endpoint) {
651
0
    if (session->endpoint->sessions)
652
0
      SESSIONS_DELETE(session->endpoint->sessions, session);
653
0
  } else
654
2.53k
#endif /* COAP_SERVER_SUPPORT */
655
2.53k
#if COAP_CLIENT_SUPPORT
656
2.53k
    if (session->context) {
657
2.53k
      if (session->context->sessions)
658
2.53k
        SESSIONS_DELETE(session->context->sessions, session);
659
2.53k
    }
660
2.53k
  coap_delete_bin_const(session->req_token);
661
2.53k
#endif /* COAP_CLIENT_SUPPORT */
662
2.53k
  coap_delete_bin_const(session->last_token);
663
2.53k
  coap_delete_bin_const(session->echo);
664
2.53k
#if COAP_SERVER_SUPPORT
665
2.53k
  coap_delete_pdu_lkd(session->last_resp_pdu);
666
2.53k
#endif /* COAP_SERVER_SUPPORT */
667
668
2.53k
  if (session->app_cb) {
669
0
    coap_lock_callback(session->app_cb(session->app_data));
670
0
  }
671
2.53k
  coap_log_debug("***%s: session %p: closed\n", coap_session_str(session),
672
2.53k
                 (void *)session);
673
2.53k
  assert(session->ref == 1);
674
2.53k
  coap_free_type(COAP_SESSION, session);
675
2.53k
}
676
677
#if COAP_SERVER_SUPPORT
678
void
679
0
coap_session_server_keepalive_failed(coap_session_t *session) {
680
0
  int i;
681
0
  coap_queue_t *q;
682
683
0
  coap_session_reference_lkd(session);
684
0
  coap_handle_event_lkd(session->context, COAP_EVENT_KEEPALIVE_FAILURE, session);
685
0
  coap_cancel_all_messages(session->context, session, NULL);
686
0
  RESOURCES_ITER(session->context->resources, r) {
687
    /* In case code is broken somewhere */
688
0
    for (i = 0; i < 1000; i++) {
689
0
      if (!coap_delete_observer(r, session, NULL))
690
0
        break;
691
0
    }
692
0
  }
693
0
  if (session->context->unknown_resource) {
694
    /* In case code is broken somewhere */
695
0
    for (i = 0; i < 1000; i++) {
696
0
      if (!coap_delete_observer(session->context->unknown_resource, session, NULL))
697
0
        break;
698
0
    }
699
0
  }
700
0
  if (session->context->proxy_uri_resource) {
701
    /* In case code is broken somewhere */
702
0
    for (i = 0; i < 1000; i++) {
703
0
      if (!coap_delete_observer(session->context->proxy_uri_resource, session, NULL))
704
0
        break;
705
0
    }
706
0
  }
707
0
  while ((q = coap_remove_first_from_delayq(session)) != NULL) {
708
0
    coap_delete_node_lkd(q);
709
0
  }
710
  /* Force session to go away */
711
0
  coap_session_set_type_client_lkd(session, 0);
712
0
  coap_session_release_lkd(session);
713
714
0
  coap_session_release_lkd(session);
715
0
}
716
#endif /* COAP_SERVER_SUPPORT */
717
718
static size_t
719
coap_session_max_pdu_size_internal(const coap_session_t *session,
720
2.53k
                                   size_t max_with_header) {
721
#if COAP_DISABLE_TCP
722
  (void)session;
723
  return max_with_header > COAP_PDU_MAX_UDP_HEADER_SIZE
724
         ? max_with_header - COAP_PDU_MAX_UDP_HEADER_SIZE
725
         : 0;
726
#else /* !COAP_DISABLE_TCP */
727
2.53k
  if (COAP_PROTO_NOT_RELIABLE(session->proto))
728
2.53k
    return max_with_header > COAP_PDU_MAX_UDP_HEADER_SIZE
729
2.53k
           ? max_with_header - COAP_PDU_MAX_UDP_HEADER_SIZE
730
2.53k
           : 0;
731
  /* we must assume there is no token to be on the safe side */
732
0
  if (max_with_header <= 2)
733
0
    return 0;
734
0
  else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP0 + 2)
735
0
    return max_with_header - 2;
736
0
  else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP8 + 3)
737
0
    return max_with_header - 3;
738
0
  else if (max_with_header <= COAP_MAX_MESSAGE_SIZE_TCP16 + 4)
739
0
    return max_with_header - 4;
740
0
  else
741
0
    return max_with_header - COAP_PDU_MAX_TCP_HEADER_SIZE;
742
0
#endif /* !COAP_DISABLE_TCP */
743
0
}
744
745
size_t
746
0
coap_session_max_pdu_rcv_size(const coap_session_t *session) {
747
0
  if (session->csm_rcv_mtu)
748
0
    return coap_session_max_pdu_size_internal(session,
749
0
                                              (size_t)(session->csm_rcv_mtu));
750
751
0
  return coap_session_max_pdu_size_internal(session,
752
0
                                            (size_t)(session->mtu - session->tls_overhead));
753
0
}
754
755
COAP_API size_t
756
0
coap_session_max_pdu_size(const coap_session_t *session) {
757
0
  size_t size;
758
0
  coap_session_t *session_rw;
759
760
  /*
761
   * Need to do this to not get a compiler warning about const parameters
762
   * but need to maintain source code backward compatibility
763
   */
764
0
  memcpy(&session_rw, &session, sizeof(session_rw));
765
0
  coap_lock_lock(return 0);
766
0
  size = coap_session_max_pdu_size_lkd(session_rw);
767
0
  coap_lock_unlock();
768
0
  return size;
769
0
}
770
771
size_t
772
2.53k
coap_session_max_pdu_size_lkd(const coap_session_t *session) {
773
2.53k
  size_t max_with_header;
774
775
2.53k
  coap_lock_check_locked();
776
2.53k
#if COAP_CLIENT_SUPPORT
777
2.53k
  if (COAP_PROTO_RELIABLE(session->proto) &&
778
0
      session->type == COAP_SESSION_TYPE_CLIENT &&
779
0
      session->doing_first) {
780
    /*
781
     * Delay if session->doing_first is set.
782
     * E.g. Reliable and CSM not in yet for checking block support
783
     */
784
0
    coap_session_t *session_rw;
785
786
    /*
787
     * Need to do this to not get a compiler warning about const parameters
788
     * but need to maintain source code backward compatibility
789
     */
790
0
    memcpy(&session_rw, &session, sizeof(session_rw));
791
0
    if (coap_client_delay_first(session_rw) == 0) {
792
0
      coap_log_debug("coap_client_delay_first: timeout\n");
793
      /* Have to go with the defaults */
794
0
    }
795
0
  }
796
2.53k
#endif /* COAP_CLIENT_SUPPORT */
797
798
2.53k
  max_with_header = (size_t)(session->mtu - session->tls_overhead);
799
800
2.53k
  return coap_session_max_pdu_size_internal(session, max_with_header);
801
2.53k
}
802
803
void
804
2.53k
coap_session_set_mtu(coap_session_t *session, unsigned mtu) {
805
2.53k
  if (mtu > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
806
0
    mtu = COAP_DEFAULT_MAX_PDU_RX_SIZE;
807
0
    coap_log_debug("*  %s: Restricting MTU size to %u\n",
808
0
                   coap_session_str(session), mtu);
809
0
  }
810
2.53k
  if (mtu < 64)
811
0
    mtu = 64;
812
2.53k
  session->mtu = mtu;
813
2.53k
  if (session->tls_overhead >= session->mtu) {
814
0
    session->tls_overhead = session->mtu;
815
0
    coap_log_err("DTLS overhead exceeds MTU\n");
816
0
  }
817
2.53k
}
818
819
ssize_t
820
coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu,
821
0
                       coap_queue_t *node) {
822
0
  if (node) {
823
0
    coap_queue_t *removed = NULL;
824
    /* Nodes are per ID, no notion of token */
825
0
    coap_remove_from_queue(&session->context->sendqueue, session, node->id,
826
0
                           NULL, &removed);
827
0
    assert(removed == node);
828
    /* reuse node */
829
0
    coap_session_release_lkd(node->session);
830
0
    node->session = NULL;
831
0
    node->t = 0;
832
0
  } else {
833
0
    if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
834
0
      coap_queue_t *q = NULL;
835
      /* Check same mid is not getting reused in violation of RFC7252 */
836
0
      LL_FOREACH(session->delayqueue, q) {
837
0
        if (q->id == pdu->mid) {
838
0
          coap_log_err("** %s: mid=0x%04x: already in-use - dropped\n",
839
0
                       coap_session_str(session), pdu->mid);
840
0
          return COAP_INVALID_MID;
841
0
        }
842
0
      }
843
0
    }
844
0
    node = coap_new_node();
845
0
    if (node == NULL)
846
0
      return COAP_INVALID_MID;
847
0
    node->id = pdu->mid;
848
0
    node->pdu = pdu;
849
0
    if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
850
0
      uint8_t r;
851
0
      coap_prng_lkd(&r, sizeof(r));
852
      /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
853
0
      node->timeout = coap_calc_timeout(session, r);
854
0
    }
855
0
    coap_address_copy(&node->remote, &session->addr_info.remote);
856
0
  }
857
0
  coap_add_to_tail_delayq(session, node);
858
0
  coap_show_pdu(COAP_LOG_DEBUG, node->pdu);
859
0
  coap_log_debug("** %s: mid=0x%04x: delayed\n",
860
0
                 coap_session_str(session), node->id);
861
0
  return COAP_PDU_DELAYED;
862
0
}
863
864
#if !COAP_DISABLE_TCP
865
void
866
0
coap_session_send_csm(coap_session_t *session) {
867
0
  coap_pdu_t *pdu;
868
0
  uint8_t buf[4];
869
0
  assert(COAP_PROTO_RELIABLE(session->proto));
870
0
  coap_log_debug("***%s: sending CSM\n", coap_session_str(session));
871
0
  session->state = COAP_SESSION_STATE_CSM;
872
0
  session->partial_write = 0;
873
0
  if (session->mtu == 0)
874
0
    coap_session_set_mtu(session, COAP_DEFAULT_MTU);  /* base value */
875
0
  pdu = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_CSM, 0, 20);
876
0
  if (pdu == NULL
877
0
      || coap_add_option_internal(pdu, (coap_option_num_t)COAP_SIG_OPT_MAX_MESSAGE_SIZE,
878
0
                                  coap_encode_var_safe(buf, sizeof(buf),
879
0
                                                       session->context->csm_max_message_size), buf) == 0
880
0
      || coap_add_option_internal(pdu, (coap_option_num_t)COAP_SIG_OPT_BLOCK_WISE_TRANSFER,
881
0
                                  coap_encode_var_safe(buf, sizeof(buf),
882
0
                                                       0), buf) == 0
883
0
      || (session->max_token_size > COAP_TOKEN_DEFAULT_MAX &&
884
0
          coap_add_option_internal(pdu,
885
0
                                   (coap_option_num_t)COAP_SIG_OPT_EXTENDED_TOKEN_LENGTH,
886
0
                                   coap_encode_var_safe(buf, sizeof(buf),
887
0
                                                        session->max_token_size),
888
0
                                   buf) == 0)
889
0
      || coap_pdu_encode_header(pdu, session->proto) == 0
890
0
     ) {
891
0
    coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
892
0
  } else {
893
0
    ssize_t bytes_written;
894
895
0
    pdu->session = session;
896
0
    bytes_written = coap_session_send_pdu(session, pdu);
897
0
    if (bytes_written != (ssize_t)pdu->used_size + pdu->hdr_size) {
898
0
      coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
899
0
    } else {
900
0
      session->csm_rcv_mtu = session->context->csm_max_message_size;
901
0
      if (session->csm_rcv_mtu > COAP_BERT_BASE)
902
0
        session->csm_bert_loc_support = 1;
903
0
      else
904
0
        session->csm_bert_loc_support = 0;
905
0
    }
906
0
  }
907
0
  if (pdu)
908
0
    coap_delete_pdu_lkd(pdu);
909
0
}
910
#endif /* !COAP_DISABLE_TCP */
911
912
COAP_API coap_mid_t
913
0
coap_session_send_ping(coap_session_t *session) {
914
0
  coap_mid_t mid;
915
916
0
  coap_lock_lock(return COAP_INVALID_MID);
917
0
  mid = coap_session_send_ping_lkd(session);
918
0
  if (mid != COAP_INVALID_MID) {
919
0
    coap_tick_t now;
920
921
0
    coap_ticks(&now);
922
0
    session->last_ping_mid = mid;
923
0
    session->last_rx_tx = now;
924
0
    session->last_ping = now;
925
0
  }
926
0
  coap_lock_unlock();
927
0
  return mid;
928
0
}
929
930
coap_mid_t
931
0
coap_session_send_ping_lkd(coap_session_t *session) {
932
0
  coap_pdu_t *ping = NULL;
933
934
0
  coap_lock_check_locked();
935
0
  if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
936
0
      session->con_active)
937
0
    return COAP_INVALID_MID;
938
0
  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
939
0
    uint16_t mid = coap_new_message_id_lkd(session);
940
0
    ping = coap_pdu_init(COAP_MESSAGE_CON, 0, mid, 0);
941
0
  }
942
0
#if !COAP_DISABLE_TCP
943
0
  else {
944
0
    ping = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PING, 0, 1);
945
0
  }
946
0
#endif /* !COAP_DISABLE_TCP */
947
0
  if (!ping)
948
0
    return COAP_INVALID_MID;
949
0
  return coap_send_internal(session, ping, NULL);
950
0
}
951
952
void
953
2.53k
coap_session_connected(coap_session_t *session) {
954
2.53k
  if (session->state != COAP_SESSION_STATE_ESTABLISHED) {
955
2.53k
    coap_log_debug("***%s: session connected\n",
956
2.53k
                   coap_session_str(session));
957
2.53k
    if (session->state == COAP_SESSION_STATE_CSM) {
958
0
      coap_handle_event_lkd(session->context, COAP_EVENT_SESSION_CONNECTED, session);
959
0
#if COAP_CLIENT_SUPPORT
960
0
      coap_session_reestablished(session);
961
0
      coap_reset_doing_first(session);
962
0
#endif /* COAP_CLIENT_SUPPORT */
963
0
    }
964
2.53k
  }
965
966
2.53k
  session->state = COAP_SESSION_STATE_ESTABLISHED;
967
2.53k
  session->partial_write = 0;
968
969
2.53k
  if (session->proto==COAP_PROTO_DTLS) {
970
0
    session->tls_overhead = coap_dtls_get_overhead(session);
971
0
    if (session->tls_overhead >= session->mtu) {
972
0
      session->tls_overhead = session->mtu;
973
0
      coap_log_err("DTLS overhead exceeds MTU\n");
974
0
    }
975
0
  }
976
977
2.53k
  while (session->delayqueue && session->state == COAP_SESSION_STATE_ESTABLISHED) {
978
0
    ssize_t bytes_written;
979
0
    coap_queue_t *q = session->delayqueue;
980
0
    coap_address_t remote;
981
982
0
    if (q->pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
983
0
      if (session->con_active >= COAP_NSTART(session))
984
0
        break;
985
0
      session->con_active++;
986
0
    }
987
    /* Take entry off the queue */
988
0
    q = coap_remove_first_from_delayq(session);
989
990
0
    coap_address_copy(&remote, &session->addr_info.remote);
991
0
    coap_address_copy(&session->addr_info.remote, &q->remote);
992
0
    coap_log_debug("** %s: mid=0x%04x: transmitted after delay (2)\n",
993
0
                   coap_session_str(session), (int)q->id);
994
0
    bytes_written = coap_session_send_pdu(session, q->pdu);
995
0
    if (q->pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto)) {
996
0
      if (coap_wait_ack(session->context, session, q) >= 0)
997
0
        q = NULL;
998
0
    }
999
0
    coap_address_copy(&session->addr_info.remote, &remote);
1000
0
    if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1001
0
      if (q)
1002
0
        coap_delete_node_lkd(q);
1003
0
      if (bytes_written < 0)
1004
0
        break;
1005
0
    } else if (q) {
1006
0
      if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size) {
1007
0
        coap_add_to_head_delayq(session, q);
1008
0
        if (bytes_written > 0)
1009
0
          session->partial_write = (size_t)bytes_written;
1010
0
        break;
1011
0
      } else {
1012
0
        coap_delete_node_lkd(q);
1013
0
      }
1014
0
    }
1015
0
  }
1016
2.53k
}
1017
1018
#if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
1019
static const char *
1020
0
coap_nack_name(coap_nack_reason_t reason) {
1021
0
  switch (reason) {
1022
0
  case COAP_NACK_TOO_MANY_RETRIES:
1023
0
    return "COAP_NACK_TOO_MANY_RETRIES";
1024
0
  case COAP_NACK_NOT_DELIVERABLE:
1025
0
    return "COAP_NACK_NOT_DELIVERABLE";
1026
0
  case COAP_NACK_RST:
1027
0
    return "COAP_NACK_RST";
1028
0
  case COAP_NACK_TLS_FAILED:
1029
0
    return "COAP_NACK_TLS_FAILED";
1030
0
  case COAP_NACK_ICMP_ISSUE:
1031
0
    return "COAP_NACK_ICMP_ISSUE";
1032
0
  case COAP_NACK_BAD_RESPONSE:
1033
0
    return "COAP_NACK_BAD_RESPONSE";
1034
0
  case COAP_NACK_TLS_LAYER_FAILED:
1035
0
    return "COAP_NACK_TLS_LAYER_FAILED";
1036
0
  case COAP_NACK_WS_LAYER_FAILED:
1037
0
    return "COAP_NACK_WS_LAYER_FAILED";
1038
0
  case COAP_NACK_WS_FAILED:
1039
0
    return "COAP_NACK_WS_FAILED";
1040
0
  default:
1041
0
    return "???";
1042
0
  }
1043
0
}
1044
#endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
1045
1046
void
1047
coap_handle_nack(coap_session_t *session,
1048
                 coap_pdu_t *sent,
1049
                 const coap_nack_reason_t reason,
1050
0
                 const coap_mid_t mid) {
1051
0
  if (session->context->nack_cb
1052
0
#if COAP_CLIENT_SUPPORT
1053
0
      && !session->doing_first_pdu
1054
0
#endif /* COAP_CLIENT_SUPPORT */
1055
0
     ) {
1056
0
    coap_bin_const_t token = {0, NULL};
1057
1058
0
    if (sent) {
1059
0
      coap_check_update_token(session, sent);
1060
0
      token = sent->actual_token;
1061
0
    }
1062
0
    coap_lock_callback(session->context->nack_cb(session, sent, reason, mid));
1063
0
    if (sent) {
1064
0
      coap_update_token(sent, token.length, token.s);
1065
0
    }
1066
0
  }
1067
0
#if COAP_CLIENT_SUPPORT
1068
0
  if (reason != COAP_NACK_ICMP_ISSUE) {
1069
0
    session->doing_send_recv = 0;
1070
0
  }
1071
0
#endif /* COAP_CLIENT_SUPPORT */
1072
0
}
1073
1074
COAP_API void
1075
0
coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason) {
1076
0
  coap_lock_lock(return);
1077
0
  coap_session_disconnected_lkd(session, reason);
1078
0
  coap_lock_unlock();
1079
0
}
1080
1081
void
1082
0
coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason) {
1083
0
#if !COAP_DISABLE_TCP
1084
0
  coap_session_state_t state = session->state;
1085
0
#endif /* !COAP_DISABLE_TCP */
1086
0
  coap_lg_xmit_t *lq, *ltmp;
1087
0
#if COAP_SERVER_SUPPORT
1088
0
  coap_lg_srcv_t *sq, *stmp;
1089
0
#endif /* COAP_SERVER_SUPPORT */
1090
0
#if COAP_CLIENT_SUPPORT
1091
0
  coap_lg_crcv_t *cq, *etmp;
1092
0
#endif /* COAP_CLIENT_SUPPORT */
1093
0
  int sent_nack = 0;
1094
0
  coap_queue_t *q;
1095
1096
0
  coap_lock_check_locked();
1097
0
#if COAP_CLIENT_SUPPORT
1098
0
  coap_session_failed(session);
1099
0
#endif /* COAP_CLIENT_SUPPORT */
1100
1101
0
  q = session->context->sendqueue;
1102
0
  while (q) {
1103
0
    if (q->session == session) {
1104
      /* Take the first one */
1105
0
      coap_handle_nack(session, q->pdu, reason, q->id);
1106
0
      sent_nack = 1;
1107
0
      break;
1108
0
    }
1109
0
    q = q->next;
1110
0
  }
1111
1112
0
  while ((q = coap_remove_first_from_delayq(session)) != NULL) {
1113
0
    coap_log_debug("** %s: mid=0x%04x: not transmitted after disconnect\n",
1114
0
                   coap_session_str(session), q->id);
1115
0
    if (q->pdu->type == COAP_MESSAGE_CON) {
1116
0
      coap_handle_nack(session, q->pdu, reason, q->id);
1117
0
      sent_nack = 1;
1118
0
    }
1119
1120
0
    coap_delete_node_lkd(q);
1121
0
  }
1122
0
#if COAP_CLIENT_SUPPORT
1123
0
  session->doing_send_recv = 0;
1124
0
#endif /* COAP_CLIENT_SUPPORT */
1125
0
#if COAP_CLIENT_SUPPORT
1126
0
  if (!sent_nack && session->lg_crcv) {
1127
    /* Take the first one */
1128
0
    coap_handle_nack(session, session->lg_crcv->sent_pdu, reason,
1129
0
                     session->lg_crcv->sent_pdu->mid);
1130
0
    sent_nack = 1;
1131
0
  }
1132
0
#endif /* COAP_CLIENT_SUPPORT */
1133
0
  if (!sent_nack) {
1134
    /* Unable to determine which request disconnection was for */
1135
0
    coap_handle_nack(session, NULL, reason, 0);
1136
0
  }
1137
0
  coap_log_debug("***%s: session disconnected (%s)\n",
1138
0
                 coap_session_str(session), coap_nack_name(reason));
1139
0
#if COAP_SERVER_SUPPORT
1140
0
  coap_delete_observers(session->context, session);
1141
0
#endif /* COAP_SERVER_SUPPORT */
1142
1143
0
  if (session->proto == COAP_PROTO_UDP)
1144
0
    session->state = COAP_SESSION_STATE_ESTABLISHED;
1145
0
  else
1146
0
    session->state = COAP_SESSION_STATE_NONE;
1147
1148
0
  session->con_active = 0;
1149
1150
0
  if (session->partial_pdu) {
1151
0
    coap_delete_pdu_lkd(session->partial_pdu);
1152
0
    session->partial_pdu = NULL;
1153
0
  }
1154
0
  session->partial_read = 0;
1155
1156
  /* Not done if nack handler called above */
1157
0
  while ((q = coap_remove_first_from_delayq(session)) != NULL) {
1158
0
    coap_log_debug("** %s: mid=0x%04x: not transmitted after disconnect\n",
1159
0
                   coap_session_str(session), q->id);
1160
0
#if COAP_CLIENT_SUPPORT
1161
0
    session->doing_send_recv = 0;
1162
0
#endif /* COAP_CLIENT_SUPPORT */
1163
0
    coap_delete_node_lkd(q);
1164
0
  }
1165
1166
0
#if COAP_CLIENT_SUPPORT
1167
0
  if (!session->session_failed) {
1168
    /* Need to do this before (D)TLS and socket is closed down */
1169
0
    LL_FOREACH_SAFE(session->lg_crcv, cq, etmp) {
1170
0
      LL_DELETE(session->lg_crcv, cq);
1171
0
      coap_block_delete_lg_crcv(session, cq);
1172
0
    }
1173
0
  }
1174
0
#endif /* COAP_CLIENT_SUPPORT */
1175
0
  LL_FOREACH_SAFE(session->lg_xmit, lq, ltmp) {
1176
0
    LL_DELETE(session->lg_xmit, lq);
1177
0
    coap_block_delete_lg_xmit(session, lq);
1178
0
  }
1179
0
#if COAP_SERVER_SUPPORT
1180
0
  LL_FOREACH_SAFE(session->lg_srcv, sq, stmp) {
1181
0
    LL_DELETE(session->lg_srcv, sq);
1182
0
    coap_block_delete_lg_srcv(session, sq);
1183
0
  }
1184
0
#endif /* COAP_SERVER_SUPPORT */
1185
0
  coap_cancel_session_messages(session->context, session, reason);
1186
1187
0
#if !COAP_DISABLE_TCP
1188
0
  if (COAP_PROTO_RELIABLE(session->proto)) {
1189
0
    if (coap_netif_available(session)) {
1190
0
      coap_handle_event_lkd(session->context,
1191
0
                            state == COAP_SESSION_STATE_CONNECTING ?
1192
0
                            COAP_EVENT_TCP_FAILED : COAP_EVENT_TCP_CLOSED, session);
1193
0
    }
1194
0
#if COAP_CLIENT_SUPPORT
1195
0
    if (state != COAP_SESSION_STATE_NONE && !session->session_failed) {
1196
0
      coap_handle_event_lkd(session->context,
1197
0
                            state == COAP_SESSION_STATE_ESTABLISHED ?
1198
0
                            COAP_EVENT_SESSION_CLOSED : COAP_EVENT_SESSION_FAILED, session);
1199
0
    }
1200
0
    coap_reset_doing_first(session);
1201
0
#endif /* COAP_CLIENT_SUPPORT */
1202
0
  }
1203
0
#endif /* !COAP_DISABLE_TCP */
1204
0
  if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
1205
0
    session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1206
0
}
1207
1208
#if COAP_CLIENT_SUPPORT
1209
void
1210
0
coap_session_failed(coap_session_t *session) {
1211
0
  if (session->context->reconnect_time && session->client_initiated) {
1212
0
    if (session->sock.lfunc[COAP_LAYER_SESSION].l_close)
1213
0
      session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1214
0
    session->session_failed = 1;
1215
0
    coap_handle_event_lkd(session->context, COAP_EVENT_RECONNECT_FAILED, session);
1216
0
    session->retry_count++;
1217
0
    if (session->context->retry_count && session->retry_count >= session->context->retry_count) {
1218
0
      coap_handle_event_lkd(session->context, COAP_EVENT_RECONNECT_NO_MORE, session);
1219
0
      if (session->type != COAP_SESSION_TYPE_CLIENT) {
1220
0
        coap_session_set_type_client_lkd(session, 0);
1221
0
        coap_session_release_lkd(session);
1222
0
      }
1223
0
    }
1224
0
    coap_ticks(&session->last_rx_tx);
1225
0
  }
1226
0
}
1227
#endif /* COAP_CLIENT_SUPPORT */
1228
1229
#if COAP_SERVER_SUPPORT
1230
static void
1231
coap_make_addr_hash(coap_addr_hash_t *addr_hash, coap_proto_t proto,
1232
0
                    const coap_addr_tuple_t *addr_info) {
1233
0
  memset(addr_hash, 0, sizeof(coap_addr_hash_t));
1234
0
  coap_address_copy(&addr_hash->remote, &addr_info->remote);
1235
0
  addr_hash->lport = coap_address_get_port(&addr_info->local);
1236
0
  addr_hash->proto = proto;
1237
0
}
1238
1239
/* Aids debugging when session is created */
1240
static coap_session_t *debug_session;
1241
1242
coap_session_t *
1243
coap_endpoint_get_session(coap_endpoint_t *endpoint,
1244
0
                          const coap_packet_t *packet, coap_tick_t now) {
1245
0
  coap_session_t *session;
1246
0
  coap_session_t *rtmp;
1247
0
  unsigned int num_idle = 0;
1248
0
  unsigned int num_hs = 0;
1249
0
  coap_session_t *oldest = NULL;
1250
0
  coap_session_t *oldest_hs = NULL;
1251
0
  coap_addr_hash_t addr_hash;
1252
1253
0
  coap_make_addr_hash(&addr_hash, endpoint->proto, &packet->addr_info);
1254
0
  SESSIONS_FIND(endpoint->sessions, addr_hash, session);
1255
0
  if (session) {
1256
    /* Maybe mcast or unicast IP address which is not in the hash */
1257
0
    coap_address_copy(&session->addr_info.local, &packet->addr_info.local);
1258
0
    session->ifindex = packet->ifindex;
1259
0
    session->last_rx_tx = now;
1260
0
    return session;
1261
0
  }
1262
1263
0
#if COAP_CLIENT_SUPPORT
1264
0
  SESSIONS_FIND(endpoint->context->sessions, addr_hash, session);
1265
0
  if (session) {
1266
    /* Maybe mcast or unicast IP address which is not in the hash */
1267
0
    coap_address_copy(&session->addr_info.local, &packet->addr_info.local);
1268
0
    session->ifindex = packet->ifindex;
1269
0
    session->last_rx_tx = now;
1270
0
    return session;
1271
0
  }
1272
1273
0
  if (coap_is_mcast(&packet->addr_info.local)) {
1274
    /* Check if this a proxy client packet we sent on another socket */
1275
0
    SESSIONS_ITER(endpoint->context->sessions, session, rtmp) {
1276
0
      if (coap_address_equals(&session->addr_info.remote, &packet->addr_info.local) &&
1277
0
          coap_address_get_port(&session->addr_info.local) ==
1278
0
          coap_address_get_port(&packet->addr_info.remote)) {
1279
        /* Drop looped back packet to stop recursion / confusion */
1280
0
        return NULL;
1281
0
      }
1282
0
    }
1283
0
  }
1284
0
#endif /* COAP_CLIENT_SUPPORT */
1285
0
  SESSIONS_ITER(endpoint->sessions, session, rtmp) {
1286
0
    if (session->ref == 0 && session->delayqueue == NULL &&
1287
0
        session->lg_srcv == NULL && session->lg_xmit == NULL) {
1288
0
      if (
1289
0
#if COAP_CLIENT_SUPPORT
1290
0
          !(session->client_initiated && endpoint->context->reconnect_time) &&
1291
0
#endif /* COAP_CLIENT_SUPPORT */
1292
0
          session->type == COAP_SESSION_TYPE_SERVER) {
1293
0
        ++num_idle;
1294
0
        if (oldest==NULL || session->last_rx_tx < oldest->last_rx_tx)
1295
0
          oldest = session;
1296
1297
0
        if (session->state == COAP_SESSION_STATE_HANDSHAKE) {
1298
0
          ++num_hs;
1299
          /* See if this is a partial (D)TLS session set up
1300
             which needs to be cleared down to prevent DOS */
1301
0
          if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
1302
0
            if (oldest_hs == NULL ||
1303
0
                session->last_rx_tx < oldest_hs->last_rx_tx)
1304
0
              oldest_hs = session;
1305
0
          }
1306
0
        }
1307
0
      } else if (session->type == COAP_SESSION_TYPE_HELLO) {
1308
0
        ++num_hs;
1309
        /* See if this is a partial (D)TLS session set up for Client Hello
1310
           which needs to be cleared down to prevent DOS */
1311
0
        if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
1312
0
          if (oldest_hs == NULL ||
1313
0
              session->last_rx_tx < oldest_hs->last_rx_tx)
1314
0
            oldest_hs = session;
1315
0
        }
1316
0
      }
1317
0
    }
1318
0
  }
1319
1320
0
  if (endpoint->context->max_idle_sessions > 0 &&
1321
0
      num_idle >= endpoint->context->max_idle_sessions) {
1322
0
    coap_handle_event_lkd(oldest->context, COAP_EVENT_SERVER_SESSION_DEL, oldest);
1323
0
    coap_session_free(oldest);
1324
0
  } else if (oldest_hs) {
1325
0
    coap_log_warn("***%s: Incomplete session timed out\n",
1326
0
                  coap_session_str(oldest_hs));
1327
0
    coap_handle_event_lkd(oldest_hs->context, COAP_EVENT_SERVER_SESSION_DEL, oldest_hs);
1328
0
    coap_session_free(oldest_hs);
1329
0
  }
1330
1331
0
  if (num_hs > (endpoint->context->max_handshake_sessions ?
1332
0
                endpoint->context->max_handshake_sessions :
1333
0
                COAP_DEFAULT_MAX_HANDSHAKE_SESSIONS)) {
1334
    /* Maxed out on number of sessions in (D)TLS negotiation state */
1335
0
    coap_log_debug("Outstanding sessions in COAP_SESSION_STATE_HANDSHAKE too "
1336
0
                   "large.  New request ignored\n");
1337
0
    return NULL;
1338
0
  }
1339
1340
0
  if (endpoint->proto == COAP_PROTO_DTLS) {
1341
    /*
1342
     * Need to check that this actually is a Client Hello before wasting
1343
     * time allocating and then freeing off session.
1344
     */
1345
1346
    /*
1347
     * Generic header structure of the DTLS record layer.
1348
     * typedef struct __attribute__((__packed__)) {
1349
     *   uint8_t content_type;           content type of the included message
1350
     *   uint16_t version;               Protocol version
1351
     *   uint16_t epoch;                 counter for cipher state changes
1352
     *   uint8_t sequence_number[6];     sequence number
1353
     *   uint16_t length;                length of the following fragment
1354
     *   uint8_t handshake;              If content_type == DTLS_CT_HANDSHAKE
1355
     * } dtls_record_handshake_t;
1356
     */
1357
0
#define OFF_CONTENT_TYPE      0  /* offset of content_type in dtls_record_handshake_t */
1358
0
#define DTLS_CT_ALERT        21  /* Content Type Alert */
1359
0
#define DTLS_CT_HANDSHAKE    22  /* Content Type Handshake */
1360
0
#define OFF_HANDSHAKE_TYPE   13  /* offset of handshake in dtls_record_handshake_t */
1361
0
#define DTLS_HT_CLIENT_HELLO  1  /* Client Hello handshake type */
1362
0
#define DTLS_CT_CID          25  /* Content Type Connection ID */
1363
0
#define OFF_CID              11  /* offset of CID in dtls_record_handshake_t */
1364
0
#define OFF_CID_DTLS13        1  /* offset of CID in DTLS1.3 Unified Header */
1365
1366
0
    const uint8_t *payload = (const uint8_t *)packet->payload;
1367
0
    size_t length = packet->length;
1368
0
    if (length < (OFF_HANDSHAKE_TYPE + 1)) {
1369
0
      coap_log_debug("coap_dtls_hello: ContentType %d Short Packet (%" PRIuS " < %d) dropped\n",
1370
0
                     payload[OFF_CONTENT_TYPE], length,
1371
0
                     OFF_HANDSHAKE_TYPE + 1);
1372
0
      return NULL;
1373
0
    }
1374
0
    if ((payload[OFF_CONTENT_TYPE] & 0x30) == 0x30 ||
1375
0
        payload[OFF_CONTENT_TYPE] == DTLS_CT_CID) {
1376
      /* Client may have changed its IP address */
1377
0
      int changed = 0;
1378
1379
0
      SESSIONS_ITER(endpoint->sessions, session, rtmp) {
1380
0
        if (session->client_cid) {
1381
0
          if ((session->is_dtls13 && (payload[OFF_CONTENT_TYPE] & 0x30) == 0x30 &&
1382
0
               length > (OFF_CID_DTLS13 + session->client_cid->length) &&
1383
0
               memcmp(session->client_cid->s, &payload[OFF_CID_DTLS13],
1384
0
                      session->client_cid->length) == 0) ||
1385
0
              (!session->is_dtls13 && payload[OFF_CONTENT_TYPE] == DTLS_CT_CID &&
1386
0
               length > (OFF_CID + session->client_cid->length) &&
1387
0
               memcmp(session->client_cid->s, &payload[OFF_CID],
1388
0
                      session->client_cid->length) == 0)) {
1389
            /* Updating IP address */
1390
0
            coap_log_info("***%s: CID: Old Client Session\n", coap_session_str(session));
1391
0
            SESSIONS_DELETE(endpoint->sessions, session);
1392
0
            session->addr_info = packet->addr_info;
1393
0
            memcpy(&session->addr_hash, &addr_hash, sizeof(session->addr_hash));
1394
0
            SESSIONS_ADD(endpoint->sessions, session);
1395
0
            coap_log_info("***%s: CID: New Client Session\n", coap_session_str(session));
1396
0
            return session;
1397
0
          }
1398
0
        }
1399
0
      }
1400
0
      if (!changed) {
1401
0
        coap_log_debug("coap_dtls_hello: ContentType Connection-IS dropped\n");
1402
0
        return NULL;
1403
0
      }
1404
0
    } else if (payload[OFF_CONTENT_TYPE] != DTLS_CT_HANDSHAKE ||
1405
0
               payload[OFF_HANDSHAKE_TYPE] != DTLS_HT_CLIENT_HELLO) {
1406
      /* only log if not a late alert */
1407
0
      if (payload[OFF_CONTENT_TYPE] != DTLS_CT_ALERT)
1408
0
        coap_log_debug("coap_dtls_hello: ContentType %d Handshake %d dropped\n",
1409
0
                       payload[OFF_CONTENT_TYPE],
1410
0
                       payload[OFF_HANDSHAKE_TYPE]);
1411
0
      return NULL;
1412
0
    }
1413
0
  }
1414
1415
0
  session = coap_make_session(endpoint->proto, COAP_SESSION_TYPE_SERVER,
1416
0
                              &addr_hash, &packet->addr_info.local,
1417
0
                              &packet->addr_info.remote,
1418
0
                              packet->ifindex, endpoint->context, endpoint);
1419
  /* Aids debugging endpoint created session */
1420
0
  debug_session = session;
1421
0
  if (session) {
1422
0
    session->last_rx_tx = now;
1423
0
    memcpy(session->sock.lfunc, endpoint->sock.lfunc,
1424
0
           sizeof(session->sock.lfunc));
1425
0
    if (endpoint->proto == COAP_PROTO_UDP)
1426
0
      session->state = COAP_SESSION_STATE_ESTABLISHED;
1427
0
    else if (endpoint->proto == COAP_PROTO_DTLS) {
1428
0
      session->type = COAP_SESSION_TYPE_HELLO;
1429
0
    }
1430
0
    SESSIONS_ADD(endpoint->sessions, session);
1431
0
    coap_log_debug("***%s: session %p: new incoming session\n",
1432
0
                   coap_session_str(session), (void *)session);
1433
0
    coap_handle_event_lkd(session->context, COAP_EVENT_SERVER_SESSION_NEW, session);
1434
0
  }
1435
0
  return session;
1436
0
}
1437
1438
coap_session_t *
1439
coap_session_new_dtls_session(coap_session_t *session,
1440
0
                              coap_tick_t now) {
1441
0
  if (session) {
1442
0
    session->last_rx_tx = now;
1443
0
    session->type = COAP_SESSION_TYPE_SERVER;
1444
0
    coap_dtls_establish(session);
1445
0
  }
1446
0
  return session;
1447
0
}
1448
#endif /* COAP_SERVER_SUPPORT */
1449
1450
#if COAP_CLIENT_SUPPORT
1451
static coap_session_t *
1452
coap_session_create_client(coap_context_t *ctx,
1453
                           const coap_address_t *local_if,
1454
                           const coap_address_t *server,
1455
                           coap_proto_t proto,
1456
                           void *app_data,
1457
                           coap_app_data_free_callback_t callback,
1458
2.53k
                           coap_str_const_t *ws_host) {
1459
2.53k
  coap_session_t *session = NULL;
1460
2.53k
  int default_port = COAP_DEFAULT_PORT;
1461
1462
2.53k
  assert(server);
1463
1464
2.53k
  switch (proto) {
1465
2.53k
  case COAP_PROTO_UDP:
1466
2.53k
    default_port = COAP_DEFAULT_PORT;
1467
2.53k
    break;
1468
0
  case COAP_PROTO_DTLS:
1469
0
    if (!coap_dtls_is_supported()) {
1470
0
      coap_log_crit("coap_new_client_session*: DTLS not supported\n");
1471
0
      return NULL;
1472
0
    }
1473
0
    default_port = COAPS_DEFAULT_PORT;
1474
0
    break;
1475
0
  case COAP_PROTO_TCP:
1476
0
    if (!coap_tcp_is_supported()) {
1477
0
      coap_log_crit("coap_new_client_session*: TCP not supported\n");
1478
0
      return NULL;
1479
0
    }
1480
0
    default_port = COAP_DEFAULT_PORT;
1481
0
    break;
1482
0
  case COAP_PROTO_TLS:
1483
0
    if (!coap_tls_is_supported()) {
1484
0
      coap_log_crit("coap_new_client_session*: TLS not supported\n");
1485
0
      return NULL;
1486
0
    }
1487
0
    default_port = COAPS_DEFAULT_PORT;
1488
0
    break;
1489
0
  case COAP_PROTO_WS:
1490
0
    if (!coap_ws_is_supported()) {
1491
0
      coap_log_crit("coap_new_client_session*: WS not supported\n");
1492
0
      return NULL;
1493
0
    }
1494
0
    default_port = 80;
1495
0
    break;
1496
0
  case COAP_PROTO_WSS:
1497
0
    if (!coap_wss_is_supported()) {
1498
0
      coap_log_crit("coap_new_client_session*: WSS not supported\n");
1499
0
      return NULL;
1500
0
    }
1501
0
    default_port = 443;
1502
0
    break;
1503
0
  case COAP_PROTO_NONE:
1504
0
  case COAP_PROTO_LAST:
1505
0
  default:
1506
0
    assert(0);
1507
0
    return NULL;
1508
2.53k
  }
1509
2.53k
  session = coap_make_session(proto, COAP_SESSION_TYPE_CLIENT, NULL,
1510
2.53k
                              local_if, server, 0, ctx, NULL);
1511
2.53k
  if (!session)
1512
0
    goto error;
1513
1514
2.53k
  coap_session_reference_lkd(session);
1515
2.53k
  session->sock.session = session;
1516
2.53k
  memcpy(&session->sock.lfunc, coap_layers_coap[proto],
1517
2.53k
         sizeof(session->sock.lfunc));
1518
1519
2.53k
  session->app_data = app_data;
1520
2.53k
  session->app_cb = app_data ? callback : NULL;
1521
2.53k
#if COAP_WS_SUPPORT
1522
2.53k
  if (ws_host) {
1523
0
    session->ws_host = coap_new_str_const(ws_host->s, ws_host->length);
1524
0
  }
1525
#else /* ! COAP_WS_SUPPORT */
1526
  (void)ws_host;
1527
#endif /* ! COAP_WS_SUPPORT */
1528
1529
2.53k
  if (COAP_PROTO_NOT_RELIABLE(proto)) {
1530
2.53k
    coap_session_t *s, *rtmp;
1531
2.53k
    if (!coap_netif_dgrm_connect(session, local_if, server, default_port)) {
1532
0
      goto error;
1533
0
    }
1534
    /* Check that this is not a duplicate 4-tuple */
1535
2.53k
    SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1536
0
      if (COAP_PROTO_NOT_RELIABLE(s->proto) &&
1537
0
          coap_address_equals(&session->addr_info.local,
1538
0
                              &s->addr_info.local) &&
1539
0
          coap_address_equals(&session->addr_info.remote,
1540
0
                              &s->addr_info.remote)) {
1541
0
        coap_log_warn("***%s: session %p: duplicate - already exists\n",
1542
0
                      coap_session_str(session), (void *)session);
1543
0
        goto error;
1544
0
      }
1545
0
    }
1546
#ifdef WITH_CONTIKI
1547
    session->sock.context = ctx;
1548
#endif /* WITH_CONTIKI */
1549
2.53k
#if !COAP_DISABLE_TCP
1550
2.53k
  } else if (COAP_PROTO_RELIABLE(proto)) {
1551
0
    if (!coap_netif_strm_connect1(session, local_if, server, default_port)) {
1552
0
      goto error;
1553
0
    }
1554
0
#endif /* !COAP_DISABLE_TCP */
1555
0
  }
1556
1557
2.53k
  session->sock.session = session;
1558
2.53k
#ifdef COAP_EPOLL_SUPPORT
1559
2.53k
  coap_epoll_ctl_add(&session->sock,
1560
2.53k
                     EPOLLIN |
1561
2.53k
                     ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
1562
2.53k
                      EPOLLOUT : 0),
1563
2.53k
                     __func__);
1564
2.53k
#endif /* COAP_EPOLL_SUPPORT */
1565
1566
2.53k
  session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_WANT_READ;
1567
2.53k
  if (local_if)
1568
0
    session->sock.flags |= COAP_SOCKET_BOUND;
1569
2.53k
#if COAP_SERVER_SUPPORT
1570
2.53k
  if (ctx->proxy_uri_resource)
1571
0
    session->proxy_session = 1;
1572
2.53k
#endif /* COAP_SERVER_SUPPORT */
1573
2.53k
  SESSIONS_ADD(ctx->sessions, session);
1574
2.53k
  return session;
1575
1576
0
error:
1577
  /*
1578
   * Need to add in the session as coap_session_release_lkd()
1579
   * will call SESSIONS_DELETE in coap_session_free().
1580
   */
1581
0
  if (session)
1582
0
    SESSIONS_ADD(ctx->sessions, session);
1583
0
  coap_session_release_lkd(session);
1584
0
  return NULL;
1585
0
}
1586
1587
static void
1588
2.53k
coap_session_check_connect(coap_session_t *session) {
1589
2.53k
  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1590
2.53k
    session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
1591
2.53k
  }
1592
2.53k
#if !COAP_DISABLE_TCP
1593
2.53k
  if (COAP_PROTO_RELIABLE(session->proto)) {
1594
0
    if (session->sock.flags & COAP_SOCKET_WANT_CONNECT) {
1595
0
      session->state = COAP_SESSION_STATE_CONNECTING;
1596
0
      if (session->client_initiated) {
1597
0
        session->doing_first = 1;
1598
0
      }
1599
0
    } else {
1600
      /* Initial connect worked immediately */
1601
0
      session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
1602
0
    }
1603
0
  }
1604
2.53k
#endif /* !COAP_DISABLE_TCP */
1605
2.53k
  coap_ticks(&session->last_rx_tx);
1606
2.53k
}
1607
#endif /* COAP_CLIENT_SUPPORT */
1608
1609
void
1610
2.53k
coap_session_establish(coap_session_t *session) {
1611
2.53k
  if (COAP_PROTO_NOT_RELIABLE(session->proto))
1612
2.53k
    coap_session_connected(session);
1613
2.53k
#if !COAP_DISABLE_TCP
1614
2.53k
  if (COAP_PROTO_RELIABLE(session->proto))
1615
0
    coap_session_send_csm(session);
1616
2.53k
#endif /* !COAP_DISABLE_TCP */
1617
2.53k
}
1618
1619
#if COAP_CLIENT_SUPPORT
1620
int
1621
0
coap_session_reconnect(coap_session_t *session) {
1622
0
  int default_port = COAP_DEFAULT_PORT;
1623
1624
0
  if (session->sock.lfunc[COAP_LAYER_SESSION].l_close && !session->session_failed)
1625
0
    session->sock.lfunc[COAP_LAYER_SESSION].l_close(session);
1626
1627
0
  switch (session->proto) {
1628
0
  case COAP_PROTO_UDP:
1629
0
    default_port = COAP_DEFAULT_PORT;
1630
0
    break;
1631
0
  case COAP_PROTO_DTLS:
1632
0
    default_port = COAPS_DEFAULT_PORT;
1633
0
    break;
1634
0
  case COAP_PROTO_TCP:
1635
0
    default_port = COAP_DEFAULT_PORT;
1636
0
    break;
1637
0
  case COAP_PROTO_TLS:
1638
0
    default_port = COAPS_DEFAULT_PORT;
1639
0
    break;
1640
0
  case COAP_PROTO_WS:
1641
0
    default_port = 80;
1642
0
    break;
1643
0
  case COAP_PROTO_WSS:
1644
0
    default_port = 443;
1645
0
    break;
1646
0
  case COAP_PROTO_NONE:
1647
0
  case COAP_PROTO_LAST:
1648
0
  default:
1649
0
    assert(0);
1650
0
    return 0;
1651
0
  }
1652
0
  session->sock.session = session;
1653
0
  coap_log_debug("***%s: trying to reconnect\n", coap_session_str(session));
1654
0
  coap_handle_event_lkd(session->context, COAP_EVENT_RECONNECT_STARTED, session);
1655
0
  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1656
0
    session->state = COAP_SESSION_STATE_NONE;
1657
0
    if (!coap_netif_dgrm_connect(session, &session->local_reconnect, &session->addr_info.remote,
1658
0
                                 default_port)) {
1659
0
      goto error;
1660
0
    }
1661
0
    coap_session_reestablished(session);
1662
#ifdef WITH_CONTIKI
1663
    session->sock.context = session->context;
1664
#endif /* WITH_CONTIKI */
1665
0
#if !COAP_DISABLE_TCP
1666
0
  } else if (COAP_PROTO_RELIABLE(session->proto)) {
1667
0
    if (!coap_netif_strm_connect1(session, &session->local_reconnect, &session->addr_info.remote,
1668
0
                                  default_port)) {
1669
0
      goto error;
1670
0
    }
1671
0
#endif /* !COAP_DISABLE_TCP */
1672
0
  } else {
1673
0
    goto error;
1674
0
  }
1675
0
#ifdef COAP_EPOLL_SUPPORT
1676
0
  coap_epoll_ctl_add(&session->sock,
1677
0
                     EPOLLIN |
1678
0
                     ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
1679
0
                      EPOLLOUT : 0),
1680
0
                     __func__);
1681
0
#endif /* COAP_EPOLL_SUPPORT */
1682
1683
0
  session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_WANT_READ;
1684
0
  session->sock.flags |= COAP_SOCKET_BOUND;
1685
0
  coap_session_check_connect(session);
1686
0
  return 1;
1687
0
error:
1688
0
  return 0;
1689
0
}
1690
1691
void
1692
0
coap_session_reestablished(coap_session_t *session) {
1693
0
  coap_lg_crcv_t *lg_crcv, *etmp;
1694
1695
0
  if (!session->session_failed)
1696
0
    return;
1697
0
  coap_log_debug("***%s: session re-established\n",
1698
0
                 coap_session_str(session));
1699
0
  session->session_failed = 0;
1700
0
  session->retry_count = 0;
1701
0
  coap_handle_event_lkd(session->context, COAP_EVENT_RECONNECT_SUCCESS, session);
1702
0
  LL_FOREACH_SAFE(session->lg_crcv, lg_crcv, etmp) {
1703
0
    coap_pdu_reference_lkd(lg_crcv->sent_pdu);
1704
0
    coap_send_internal(session, lg_crcv->sent_pdu, NULL);
1705
0
  }
1706
0
}
1707
1708
COAP_API coap_session_t *
1709
coap_new_client_session(coap_context_t *ctx,
1710
                        const coap_address_t *local_if,
1711
                        const coap_address_t *server,
1712
2.53k
                        coap_proto_t proto) {
1713
2.53k
  coap_session_t *session;
1714
1715
2.53k
  coap_lock_lock(return NULL);
1716
2.53k
  session = coap_new_client_session3_lkd(ctx, local_if, server, proto, NULL, NULL, NULL);
1717
2.53k
  coap_lock_unlock();
1718
2.53k
  return session;
1719
2.53k
}
1720
1721
COAP_API coap_session_t *
1722
coap_new_client_session3(coap_context_t *ctx,
1723
                         const coap_address_t *local_if,
1724
                         const coap_address_t *server,
1725
                         coap_proto_t proto,
1726
                         void *app_data,
1727
                         coap_app_data_free_callback_t callback,
1728
0
                         coap_str_const_t *ws_host) {
1729
0
  coap_session_t *session;
1730
1731
0
  coap_lock_lock(return NULL);
1732
0
  session = coap_new_client_session3_lkd(ctx, local_if, server, proto, app_data, callback, ws_host);
1733
0
  coap_lock_unlock();
1734
0
  return session;
1735
0
}
1736
1737
coap_session_t *
1738
coap_new_client_session3_lkd(coap_context_t *ctx,
1739
                             const coap_address_t *local_if,
1740
                             const coap_address_t *server,
1741
                             coap_proto_t proto,
1742
                             void *app_data,
1743
                             coap_app_data_free_callback_t callback,
1744
2.53k
                             coap_str_const_t *ws_host) {
1745
2.53k
  coap_session_t *session;
1746
1747
2.53k
  coap_lock_check_locked();
1748
2.53k
  session = coap_session_create_client(ctx, local_if, server,
1749
2.53k
                                       proto, app_data, callback, ws_host);
1750
2.53k
  if (session) {
1751
2.53k
    coap_log_debug("***%s: session %p: created outgoing session\n",
1752
2.53k
                   coap_session_str(session), (void *)session);
1753
2.53k
    coap_session_check_connect(session);
1754
2.53k
  }
1755
2.53k
  return session;
1756
2.53k
}
1757
1758
COAP_API coap_session_t *
1759
coap_new_client_session_psk(coap_context_t *ctx,
1760
                            const coap_address_t *local_if,
1761
                            const coap_address_t *server,
1762
                            coap_proto_t proto, const char *identity,
1763
0
                            const uint8_t *key, unsigned key_len) {
1764
0
  coap_session_t *session;
1765
1766
0
  coap_lock_lock(return NULL);
1767
0
  session = coap_new_client_session_psk_lkd(ctx, local_if, server, proto, identity, key, key_len);
1768
0
  coap_lock_unlock();
1769
0
  return session;
1770
0
}
1771
1772
coap_session_t *
1773
coap_new_client_session_psk_lkd(coap_context_t *ctx,
1774
                                const coap_address_t *local_if,
1775
                                const coap_address_t *server,
1776
                                coap_proto_t proto, const char *identity,
1777
0
                                const uint8_t *key, unsigned key_len) {
1778
0
  coap_dtls_cpsk_t setup_data;
1779
1780
0
  coap_lock_check_locked();
1781
0
  memset(&setup_data, 0, sizeof(setup_data));
1782
0
  setup_data.version = COAP_DTLS_CPSK_SETUP_VERSION;
1783
1784
0
  if (identity) {
1785
0
    setup_data.psk_info.identity.s = (const uint8_t *)identity;
1786
0
    setup_data.psk_info.identity.length = strlen(identity);
1787
0
  }
1788
1789
0
  if (key && key_len > 0) {
1790
0
    setup_data.psk_info.key.s = key;
1791
0
    setup_data.psk_info.key.length = key_len;
1792
0
  }
1793
1794
0
  return coap_new_client_session_psk3_lkd(ctx, local_if, server,
1795
0
                                          proto, &setup_data, NULL, NULL, NULL);
1796
0
}
1797
1798
/*
1799
 * Check the validity of the SNI to send to the server.
1800
 *
1801
 * https://datatracker.ietf.org/doc/html/rfc6066#section-3
1802
 *  Literal IPv4 and IPv6 addresses are not permitted in "HostName".
1803
 */
1804
static void
1805
0
coap_sanitize_client_sni(char **client_sni) {
1806
0
  char *cp;
1807
1808
0
  if (*client_sni == NULL)
1809
0
    return;
1810
1811
0
  cp = *client_sni;
1812
0
  switch (*cp) {
1813
0
  case '0':
1814
0
  case '1':
1815
0
  case '2':
1816
0
  case '3':
1817
0
  case '4':
1818
0
  case '5':
1819
0
  case '6':
1820
0
  case '7':
1821
0
  case '8':
1822
0
  case '9':
1823
0
  case 'a':
1824
0
  case 'b':
1825
0
  case 'c':
1826
0
  case 'd':
1827
0
  case 'e':
1828
0
  case 'f':
1829
0
  case 'A':
1830
0
  case 'B':
1831
0
  case 'C':
1832
0
  case 'D':
1833
0
  case 'E':
1834
0
  case 'F':
1835
0
  case ':':
1836
0
    break;
1837
0
  case '\000':
1838
    /* Empty entry invalid */
1839
0
    *client_sni = NULL;
1840
0
    return;
1841
0
  default:
1842
    /* Does not start with a hex digit or : - not literal IP. */
1843
0
    return;
1844
0
  }
1845
  /* Check for IPv4 */
1846
0
  while (*cp) {
1847
0
    switch (*cp) {
1848
0
    case '0':
1849
0
    case '1':
1850
0
    case '2':
1851
0
    case '3':
1852
0
    case '4':
1853
0
    case '5':
1854
0
    case '6':
1855
0
    case '7':
1856
0
    case '8':
1857
0
    case '9':
1858
0
    case '.':
1859
0
      break;
1860
0
    default:
1861
      /* Not of format nnn.nnn.nnn.nnn. Could be IPv6 */
1862
0
      goto check_ipv6;
1863
0
    }
1864
0
    cp++;
1865
0
  }
1866
  /* IPv4 address - not allowed. */
1867
0
  *client_sni = NULL;
1868
0
  return;
1869
1870
0
check_ipv6:
1871
  /* Check for IPv6 */
1872
0
  cp = *client_sni;
1873
0
  while (*cp) {
1874
0
    switch (*cp) {
1875
0
    case '0':
1876
0
    case '1':
1877
0
    case '2':
1878
0
    case '3':
1879
0
    case '4':
1880
0
    case '5':
1881
0
    case '6':
1882
0
    case '7':
1883
0
    case '8':
1884
0
    case '9':
1885
0
    case 'a':
1886
0
    case 'b':
1887
0
    case 'c':
1888
0
    case 'd':
1889
0
    case 'e':
1890
0
    case 'f':
1891
0
    case 'A':
1892
0
    case 'B':
1893
0
    case 'C':
1894
0
    case 'D':
1895
0
    case 'E':
1896
0
    case 'F':
1897
0
    case ':':
1898
0
      break;
1899
0
    case '%':
1900
      /* Start of i/f specification,  Previous is IPv6 */
1901
0
      *client_sni = NULL;
1902
0
      return;
1903
0
    default:
1904
      /* Not of format xx:xx::xx. */
1905
0
      return;
1906
0
    }
1907
0
    cp++;
1908
0
  }
1909
0
  *client_sni = NULL;
1910
0
  return;
1911
0
}
1912
1913
COAP_API coap_session_t *
1914
coap_new_client_session_psk2(coap_context_t *ctx,
1915
                             const coap_address_t *local_if,
1916
                             const coap_address_t *server,
1917
                             coap_proto_t proto,
1918
0
                             coap_dtls_cpsk_t *setup_data) {
1919
0
  coap_session_t *session;
1920
1921
0
  coap_lock_lock(return NULL);
1922
0
  session = coap_new_client_session_psk3_lkd(ctx, local_if, server, proto, setup_data,
1923
0
                                             NULL, NULL, NULL);
1924
0
  coap_lock_unlock();
1925
0
  return session;
1926
0
}
1927
1928
COAP_API coap_session_t *
1929
coap_new_client_session_psk3(coap_context_t *ctx,
1930
                             const coap_address_t *local_if,
1931
                             const coap_address_t *server,
1932
                             coap_proto_t proto,
1933
                             coap_dtls_cpsk_t *setup_data,
1934
                             void *app_data,
1935
                             coap_app_data_free_callback_t callback,
1936
0
                             coap_str_const_t *ws_host) {
1937
0
  coap_session_t *session;
1938
1939
0
  coap_lock_lock(return NULL);
1940
0
  session = coap_new_client_session_psk3_lkd(ctx, local_if, server, proto,
1941
0
                                             setup_data, app_data, callback, ws_host);
1942
0
  coap_lock_unlock();
1943
0
  return session;
1944
0
}
1945
1946
coap_session_t *
1947
coap_new_client_session_psk3_lkd(coap_context_t *ctx,
1948
                                 const coap_address_t *local_if,
1949
                                 const coap_address_t *server,
1950
                                 coap_proto_t proto,
1951
                                 coap_dtls_cpsk_t *setup_data,
1952
                                 void *app_data,
1953
                                 coap_app_data_free_callback_t callback,
1954
0
                                 coap_str_const_t *ws_host) {
1955
0
  coap_session_t *session;
1956
1957
0
  coap_lock_check_locked();
1958
0
  session = coap_session_create_client(ctx, local_if, server, proto, app_data, callback, ws_host);
1959
1960
0
  if (!session || !setup_data)
1961
0
    return NULL;
1962
1963
0
  session->cpsk_setup_data = *setup_data;
1964
0
  if (setup_data->psk_info.identity.s) {
1965
0
    session->psk_identity =
1966
0
        coap_new_bin_const(setup_data->psk_info.identity.s,
1967
0
                           setup_data->psk_info.identity.length);
1968
0
    if (!session->psk_identity) {
1969
0
      coap_log_warn("Cannot store session Identity (PSK)\n");
1970
0
      coap_session_release_lkd(session);
1971
0
      return NULL;
1972
0
    }
1973
0
  } else if (coap_dtls_is_supported() || coap_tls_is_supported()) {
1974
0
    coap_log_warn("Identity (PSK) not defined\n");
1975
0
    coap_session_release_lkd(session);
1976
0
    return NULL;
1977
0
  }
1978
1979
0
  if (setup_data->psk_info.key.s && setup_data->psk_info.key.length > 0) {
1980
0
    session->psk_key = coap_new_bin_const(setup_data->psk_info.key.s,
1981
0
                                          setup_data->psk_info.key.length);
1982
0
    if (!session->psk_key) {
1983
0
      coap_log_warn("Cannot store session pre-shared key (PSK)\n");
1984
0
      coap_session_release_lkd(session);
1985
0
      return NULL;
1986
0
    }
1987
0
  } else if (coap_dtls_is_supported() || coap_tls_is_supported()) {
1988
0
    coap_log_warn("Pre-shared key (PSK) not defined\n");
1989
0
    coap_session_release_lkd(session);
1990
0
    return NULL;
1991
0
  }
1992
1993
0
  coap_sanitize_client_sni(&session->cpsk_setup_data.client_sni);
1994
1995
0
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
1996
0
    if (!coap_dtls_context_set_cpsk(ctx, &session->cpsk_setup_data)) {
1997
0
      coap_session_release_lkd(session);
1998
0
      return NULL;
1999
0
    }
2000
0
  }
2001
0
  coap_log_debug("***%s: new outgoing session\n",
2002
0
                 coap_session_str(session));
2003
0
  coap_session_check_connect(session);
2004
0
  return session;
2005
0
}
2006
#endif /* COAP_CLIENT_SUPPORT */
2007
2008
int
2009
coap_session_refresh_psk_hint(coap_session_t *session,
2010
                              const coap_bin_const_t *psk_hint
2011
0
                             ) {
2012
  /* We may be refreshing the hint with the same hint */
2013
0
  coap_bin_const_t *old_psk_hint = session->psk_hint;
2014
2015
0
  if (psk_hint && psk_hint->s) {
2016
0
    if (session->psk_hint) {
2017
0
      if (coap_binary_equal(session->psk_hint, psk_hint))
2018
0
        return 1;
2019
0
    }
2020
0
    session->psk_hint = coap_new_bin_const(psk_hint->s,
2021
0
                                           psk_hint->length);
2022
0
    if (!session->psk_hint) {
2023
0
      coap_log_err("No memory to store identity hint (PSK)\n");
2024
0
      if (old_psk_hint)
2025
0
        coap_delete_bin_const(old_psk_hint);
2026
0
      return 0;
2027
0
    }
2028
0
  } else {
2029
0
    session->psk_hint = NULL;
2030
0
  }
2031
0
  if (old_psk_hint)
2032
0
    coap_delete_bin_const(old_psk_hint);
2033
2034
0
  return 1;
2035
0
}
2036
2037
int
2038
coap_session_refresh_psk_key(coap_session_t *session,
2039
                             const coap_bin_const_t *psk_key
2040
0
                            ) {
2041
  /* We may be refreshing the key with the same key */
2042
0
  coap_bin_const_t *old_psk_key = session->psk_key;
2043
2044
0
  if (psk_key && psk_key->s) {
2045
0
    if (session->psk_key) {
2046
0
      if (coap_binary_equal(session->psk_key, psk_key))
2047
0
        return 1;
2048
0
    }
2049
0
    session->psk_key = coap_new_bin_const(psk_key->s, psk_key->length);
2050
0
    if (!session->psk_key) {
2051
0
      coap_log_err("No memory to store pre-shared key (PSK)\n");
2052
0
      if (old_psk_key)
2053
0
        coap_delete_bin_const(old_psk_key);
2054
0
      return 0;
2055
0
    }
2056
0
  } else {
2057
0
    session->psk_key = NULL;
2058
0
  }
2059
0
  if (old_psk_key)
2060
0
    coap_delete_bin_const(old_psk_key);
2061
2062
0
  return 1;
2063
0
}
2064
2065
int
2066
coap_session_refresh_psk_identity(coap_session_t *session,
2067
                                  const coap_bin_const_t *psk_identity
2068
0
                                 ) {
2069
  /* We may be refreshing the identity with the same identity */
2070
0
  coap_bin_const_t *old_psk_identity = session->psk_identity;
2071
2072
0
  if (psk_identity && psk_identity->s) {
2073
0
    if (session->psk_identity) {
2074
0
      if (coap_binary_equal(session->psk_identity, psk_identity))
2075
0
        return 1;
2076
0
    }
2077
0
    session->psk_identity = coap_new_bin_const(psk_identity->s,
2078
0
                                               psk_identity->length);
2079
0
    if (!session->psk_identity) {
2080
0
      coap_log_err("No memory to store pre-shared key identity (PSK)\n");
2081
0
      if (old_psk_identity)
2082
0
        coap_delete_bin_const(old_psk_identity);
2083
0
      return 0;
2084
0
    }
2085
0
  } else {
2086
0
    session->psk_identity = NULL;
2087
0
  }
2088
0
  if (old_psk_identity)
2089
0
    coap_delete_bin_const(old_psk_identity);
2090
2091
0
  return 1;
2092
0
}
2093
2094
#if COAP_SERVER_SUPPORT
2095
const coap_bin_const_t *
2096
0
coap_session_get_psk_hint(const coap_session_t *session) {
2097
0
  if (session)
2098
0
    return session->psk_hint;
2099
0
  return NULL;
2100
0
}
2101
#endif /* COAP_SERVER_SUPPORT */
2102
2103
const coap_bin_const_t *
2104
0
coap_session_get_psk_identity(const coap_session_t *session) {
2105
0
  const coap_bin_const_t *psk_identity = NULL;
2106
0
  if (session) {
2107
0
    psk_identity = session->psk_identity;
2108
0
    if (psk_identity == NULL) {
2109
0
      psk_identity = &session->cpsk_setup_data.psk_info.identity;
2110
0
    }
2111
0
  }
2112
0
  return psk_identity;
2113
0
}
2114
2115
const coap_bin_const_t *
2116
0
coap_session_get_psk_key(const coap_session_t *session) {
2117
0
  if (session)
2118
0
    return session->psk_key;
2119
0
  return NULL;
2120
0
}
2121
2122
#if COAP_CLIENT_SUPPORT
2123
COAP_API coap_session_t *
2124
coap_new_client_session_pki(coap_context_t *ctx,
2125
                            const coap_address_t *local_if,
2126
                            const coap_address_t *server,
2127
                            coap_proto_t proto,
2128
0
                            coap_dtls_pki_t *setup_data) {
2129
0
  coap_session_t *session;
2130
2131
0
  coap_lock_lock(return NULL);
2132
0
  session = coap_new_client_session_pki3_lkd(ctx, local_if, server, proto, setup_data,
2133
0
                                             NULL, NULL, NULL);
2134
0
  coap_lock_unlock();
2135
0
  return session;
2136
0
}
2137
2138
COAP_API coap_session_t *
2139
coap_new_client_session_pki3(coap_context_t *ctx,
2140
                             const coap_address_t *local_if,
2141
                             const coap_address_t *server,
2142
                             coap_proto_t proto,
2143
                             coap_dtls_pki_t *setup_data,
2144
                             void *app_data,
2145
                             coap_app_data_free_callback_t callback,
2146
0
                             coap_str_const_t *ws_host) {
2147
0
  coap_session_t *session;
2148
2149
0
  coap_lock_lock(return NULL);
2150
0
  session = coap_new_client_session_pki3_lkd(ctx, local_if, server, proto, setup_data,
2151
0
                                             app_data, callback, ws_host);
2152
0
  coap_lock_unlock();
2153
0
  return session;
2154
0
}
2155
2156
coap_session_t *
2157
coap_new_client_session_pki3_lkd(coap_context_t *ctx,
2158
                                 const coap_address_t *local_if,
2159
                                 const coap_address_t *server,
2160
                                 coap_proto_t proto,
2161
                                 coap_dtls_pki_t *setup_data,
2162
                                 void *app_data,
2163
                                 coap_app_data_free_callback_t callback,
2164
0
                                 coap_str_const_t *ws_host) {
2165
0
  coap_session_t *session;
2166
0
  coap_dtls_pki_t l_setup_data;
2167
2168
0
  if (!setup_data)
2169
0
    return NULL;
2170
0
  if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
2171
0
    coap_log_err("coap_new_client_session_pki: Wrong version of setup_data\n");
2172
0
    return NULL;
2173
0
  }
2174
2175
0
  coap_lock_check_locked();
2176
0
  l_setup_data = *setup_data;
2177
0
  coap_sanitize_client_sni(&l_setup_data.client_sni);
2178
2179
0
  session = coap_session_create_client(ctx, local_if, server, proto, app_data, callback, ws_host);
2180
2181
0
  if (!session) {
2182
0
    return NULL;
2183
0
  }
2184
2185
0
  if (coap_dtls_is_supported() || coap_tls_is_supported()) {
2186
    /* we know that setup_data is not NULL */
2187
0
    if (!coap_dtls_context_set_pki(ctx, &l_setup_data, COAP_DTLS_ROLE_CLIENT)) {
2188
0
      coap_session_release_lkd(session);
2189
0
      return NULL;
2190
0
    }
2191
0
  }
2192
0
  coap_log_debug("***%s: new outgoing session\n",
2193
0
                 coap_session_str(session));
2194
0
  coap_session_check_connect(session);
2195
0
  return session;
2196
0
}
2197
#endif /* ! COAP_CLIENT_SUPPORT */
2198
2199
#if COAP_SERVER_SUPPORT
2200
#if !COAP_DISABLE_TCP
2201
coap_session_t *
2202
0
coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep, void *extra) {
2203
0
  coap_session_t *session;
2204
0
  coap_tick_t now;
2205
2206
0
  session = coap_make_session(ep->proto, COAP_SESSION_TYPE_SERVER,
2207
0
                              NULL, NULL, NULL, 0, ctx, ep);
2208
0
  if (!session)
2209
0
    goto error;
2210
2211
0
  memcpy(session->sock.lfunc, ep->sock.lfunc, sizeof(session->sock.lfunc));
2212
0
  if (!coap_netif_strm_accept(ep, session, extra))
2213
0
    goto error;
2214
2215
0
  coap_make_addr_hash(&session->addr_hash, session->proto, &session->addr_info);
2216
2217
0
  session->sock.session = session;
2218
0
#ifdef COAP_EPOLL_SUPPORT
2219
0
  coap_epoll_ctl_add(&session->sock,
2220
0
                     EPOLLIN,
2221
0
                     __func__);
2222
0
#endif /* COAP_EPOLL_SUPPORT */
2223
0
  SESSIONS_ADD(ep->sessions, session);
2224
0
  if (session) {
2225
0
    coap_ticks(&now);
2226
0
    session->last_rx_tx = now;
2227
0
    coap_log_debug("***%s: session %p: new incoming session\n",
2228
0
                   coap_session_str(session), (void *)session);
2229
0
    coap_handle_event_lkd(session->context, COAP_EVENT_TCP_CONNECTED, session);
2230
0
    coap_handle_event_lkd(session->context, COAP_EVENT_SERVER_SESSION_NEW, session);
2231
0
    session->state = COAP_SESSION_STATE_CONNECTING;
2232
0
    session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
2233
0
  }
2234
0
  return session;
2235
2236
0
error:
2237
  /*
2238
   * Need to add in the session as coap_session_release_lkd()
2239
   * will call SESSIONS_DELETE in coap_session_free().
2240
   */
2241
0
  if (session) {
2242
0
    SESSIONS_ADD(ep->sessions, session);
2243
0
    coap_session_free(session);
2244
0
  }
2245
0
  return NULL;
2246
0
}
2247
#endif /* !COAP_DISABLE_TCP */
2248
#endif /* COAP_SERVER_SUPPORT */
2249
2250
void
2251
coap_session_init_token(coap_session_t *session, size_t len,
2252
0
                        const uint8_t *data) {
2253
0
  session->tx_token = coap_decode_var_bytes8(data, len);
2254
  /*
2255
   * Decrement as when first used by coap_session_new_token() it will
2256
   * get incremented
2257
   */
2258
0
  session->tx_token--;
2259
0
}
2260
2261
void
2262
coap_session_new_token(coap_session_t *session, size_t *len,
2263
0
                       uint8_t *data) {
2264
0
  *len = coap_encode_var_safe8(data,
2265
0
                               sizeof(session->tx_token), ++session->tx_token);
2266
0
}
2267
2268
COAP_API uint16_t
2269
2.53k
coap_new_message_id(coap_session_t *session) {
2270
2.53k
  uint16_t mid;
2271
2272
2.53k
  coap_lock_lock(return 0);
2273
2.53k
  mid = coap_new_message_id_lkd(session);
2274
2.53k
  coap_lock_unlock();
2275
2.53k
  return mid;
2276
2.53k
}
2277
2278
uint16_t
2279
7.59k
coap_new_message_id_lkd(coap_session_t *session) {
2280
7.59k
  coap_lock_check_locked();
2281
7.59k
  if (COAP_PROTO_NOT_RELIABLE(session->proto))
2282
7.59k
    return ++session->tx_mid;
2283
  /* TCP/TLS have no notion of mid */
2284
0
  return 0;
2285
7.59k
}
2286
2287
const coap_address_t *
2288
0
coap_session_get_addr_remote(const coap_session_t *session) {
2289
0
  if (session)
2290
0
    return &session->addr_info.remote;
2291
0
  return NULL;
2292
0
}
2293
2294
const coap_address_t *
2295
0
coap_session_get_addr_local(const coap_session_t *session) {
2296
0
  if (session)
2297
0
    return &session->addr_info.local;
2298
0
  return NULL;
2299
0
}
2300
2301
const coap_address_t *
2302
0
coap_session_get_addr_mcast(const coap_session_t *session) {
2303
0
#if COAP_CLIENT_SUPPORT
2304
0
  if (session && session->type == COAP_SESSION_TYPE_CLIENT &&
2305
0
      session->sock.flags & COAP_SOCKET_MULTICAST)
2306
0
    return &session->sock.mcast_addr;
2307
#else /* ! COAP_CLIENT_SUPPORT */
2308
  (void)session;
2309
#endif /* ! COAP_CLIENT_SUPPORT */
2310
0
  return NULL;
2311
0
}
2312
2313
coap_context_t *
2314
0
coap_session_get_context(const coap_session_t *session) {
2315
0
  if (session)
2316
0
    return session->context;
2317
0
  return NULL;
2318
0
}
2319
2320
coap_proto_t
2321
0
coap_session_get_proto(const coap_session_t *session) {
2322
0
  if (session)
2323
0
    return session->proto;
2324
0
  return 0;
2325
0
}
2326
2327
coap_session_type_t
2328
0
coap_session_get_type(const coap_session_t *session) {
2329
0
  if (session)
2330
0
    return session->type;
2331
0
  return 0;
2332
0
}
2333
2334
int
2335
0
coap_session_is_oscore(const coap_session_t *session) {
2336
0
#if COAP_OSCORE_SUPPORT
2337
0
  return (session && session->oscore_encryption != 0) ? 1 : 0;
2338
#else
2339
  (void)session;
2340
  return 0;
2341
#endif
2342
0
}
2343
2344
COAP_API int
2345
0
coap_session_set_type_client(coap_session_t *session) {
2346
0
  int ret;
2347
2348
0
  coap_lock_lock(return 0);
2349
0
  ret = coap_session_set_type_client_lkd(session, 1);
2350
0
  coap_lock_unlock();
2351
0
  return ret;
2352
0
}
2353
2354
int
2355
0
coap_session_set_type_client_lkd(coap_session_t *session, int report_changed) {
2356
0
#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
2357
0
  if (session && session->type == COAP_SESSION_TYPE_SERVER) {
2358
0
    coap_session_reference_lkd(session);
2359
0
    session->type = COAP_SESSION_TYPE_CLIENT;
2360
0
    if (session->endpoint) {
2361
0
      SESSIONS_DELETE(session->endpoint->sessions, session);
2362
0
      SESSIONS_ADD(session->context->sessions, session);
2363
0
      if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
2364
0
        session->sock = session->endpoint->sock;
2365
0
        session->sock.flags |= COAP_SOCKET_SLAVE;
2366
0
        session->sock.flags &= ~COAP_SOCKET_CAN_READ;
2367
0
        session->sock.flags &= ~COAP_SOCKET_WANT_READ;
2368
0
      } else {
2369
0
        session->sock.endpoint = NULL;
2370
0
      }
2371
0
      session->endpoint = NULL;
2372
0
    }
2373
0
    if (report_changed) {
2374
0
      coap_log_debug("***%s: session now is type Client\n",
2375
0
                     coap_session_str(session));
2376
0
    }
2377
0
    return 1;
2378
0
  }
2379
#else /* ! COAP_CLIENT_SUPPORT || ! COAP_SERVER_SUPPORT */
2380
  (void)session;
2381
  (void)report_changed;
2382
#endif /* ! COAP_CLIENT_SUPPORT || ! COAP_SERVER_SUPPORT */
2383
0
  return 0;
2384
0
}
2385
2386
COAP_API int
2387
0
coap_session_set_type_server(coap_session_t *session) {
2388
0
  int ret;
2389
2390
0
  coap_lock_lock(return 0);
2391
0
  ret = coap_session_set_type_server_lkd(session);
2392
0
  coap_lock_unlock();
2393
0
  return ret;
2394
0
}
2395
2396
int
2397
0
coap_session_set_type_server_lkd(coap_session_t *session) {
2398
0
#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
2399
0
  if (session && session->type == COAP_SESSION_TYPE_CLIENT) {
2400
0
    coap_endpoint_t *ep;
2401
0
    coap_mid_t mid;
2402
0
    coap_pdu_t *ping = NULL;
2403
2404
0
    LL_FOREACH(session->context->endpoint, ep) {
2405
0
      if (session->proto == ep->proto)
2406
0
        break;
2407
0
    }
2408
0
    if (!ep) {
2409
      /* Need a dummy endpoint to 'hang' off as this is now a server */
2410
0
      ep = coap_malloc_endpoint();
2411
0
      if (!ep) {
2412
0
        coap_log_warn("coap_new_endpoint: malloc");
2413
0
        return 0;
2414
0
      }
2415
2416
0
      memset(ep, 0, sizeof(coap_endpoint_t));
2417
0
      ep->context = session->context;
2418
0
      ep->proto = session->proto;
2419
0
      ep->sock.endpoint = ep;
2420
0
      memcpy(&ep->sock.lfunc, coap_layers_coap[session->proto], sizeof(ep->sock.lfunc));
2421
2422
0
      ep->default_mtu = COAP_DEFAULT_MTU;
2423
0
      LL_PREPEND(session->context->endpoint, ep);
2424
0
    }
2425
    /* Need to use coap_send_lkd() here to get traffic flowing */
2426
0
    if (session->proto == COAP_PROTO_UDP) {
2427
0
      ping = coap_pdu_init(COAP_MESSAGE_CON, COAP_EMPTY_CODE,
2428
0
                           coap_new_message_id_lkd(session), 0);
2429
0
      if (!ping) {
2430
0
        session->type = COAP_SESSION_TYPE_SERVER;
2431
0
        return 0;
2432
0
      }
2433
0
      mid = coap_send_lkd(session, ping);
2434
0
      if (mid != COAP_INVALID_MID) {
2435
0
        coap_tick_t now;
2436
2437
0
        coap_ticks(&now);
2438
0
        session->last_ping_mid = mid;
2439
0
        session->last_rx_tx = now;
2440
0
        session->last_ping = now;
2441
0
      }
2442
0
    }
2443
    /*
2444
     * (D)TLS will initiate traffic with handshake.
2445
     * Reliable protocols will be sending a CSM, so no need for Ping.
2446
     */
2447
0
    if (session->context) {
2448
0
      if (session->context->sessions) {
2449
0
        SESSIONS_DELETE(session->context->sessions, session);
2450
0
      }
2451
0
    }
2452
0
    SESSIONS_ADD(ep->sessions, session);
2453
0
    session->endpoint = ep;
2454
0
    session->type = COAP_SESSION_TYPE_SERVER;
2455
0
    coap_session_release_lkd(session);
2456
0
    coap_log_debug("***%s: session now is type Server\n",
2457
0
                   coap_session_str(session));
2458
0
    return 1;
2459
0
  }
2460
#else /* ! COAP_CLIENT_SUPPORT || ! COAP_SERVER_SUPPORT */
2461
  (void)session;
2462
#endif /* ! COAP_CLIENT_SUPPORT || ! COAP_SERVER_SUPPORT */
2463
0
  return 0;
2464
0
}
2465
2466
coap_session_state_t
2467
0
coap_session_get_state(const coap_session_t *session) {
2468
0
  if (session)
2469
0
    return session->state;
2470
0
  return 0;
2471
0
}
2472
2473
coap_endpoint_t *
2474
0
coap_session_get_endpoint(const coap_session_t *session) {
2475
0
#if COAP_SERVER_SUPPORT
2476
0
  if (session)
2477
0
    return session->endpoint;
2478
#else /* ! COAP_SERVER_SUPPORT */
2479
  (void)session;
2480
#endif /* ! COAP_SERVER_SUPPORT */
2481
0
  return 0;
2482
0
}
2483
2484
int
2485
0
coap_session_get_ifindex(const coap_session_t *session) {
2486
0
  if (session)
2487
0
    return session->ifindex;
2488
0
  return -1;
2489
0
}
2490
2491
void *
2492
coap_session_get_tls(const coap_session_t *session,
2493
0
                     coap_tls_library_t *tls_lib) {
2494
0
  if (session)
2495
0
    return coap_dtls_get_tls(session, tls_lib);
2496
0
  return NULL;
2497
0
}
2498
2499
static const char *
2500
0
coap_proto_name(coap_proto_t proto) {
2501
0
  switch (proto) {
2502
0
  case COAP_PROTO_UDP:
2503
0
    return "UDP ";
2504
0
  case COAP_PROTO_DTLS:
2505
0
    return "DTLS";
2506
0
  case COAP_PROTO_TCP:
2507
0
    return "TCP ";
2508
0
  case COAP_PROTO_TLS:
2509
0
    return "TLS ";
2510
0
  case COAP_PROTO_WS:
2511
0
    return "WS  ";
2512
0
  case COAP_PROTO_WSS:
2513
0
    return "WSS ";
2514
0
  case COAP_PROTO_NONE:
2515
0
  case COAP_PROTO_LAST:
2516
0
  default:
2517
0
    return "????" ;
2518
0
    break;
2519
0
  }
2520
0
  return NULL;
2521
0
}
2522
2523
#if COAP_SERVER_SUPPORT
2524
COAP_API coap_endpoint_t *
2525
2.53k
coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto) {
2526
2.53k
  coap_endpoint_t *endpoint;
2527
2528
2.53k
  coap_lock_lock(return NULL);
2529
2.53k
  endpoint = coap_new_endpoint_lkd(context, listen_addr, proto);
2530
2.53k
  coap_lock_unlock();
2531
2.53k
  return endpoint;
2532
2.53k
}
2533
2534
coap_endpoint_t *
2535
coap_new_endpoint_lkd(coap_context_t *context, const coap_address_t *listen_addr,
2536
2.53k
                      coap_proto_t proto) {
2537
2.53k
  coap_endpoint_t *ep = NULL;
2538
2539
2.53k
  if (!context || !listen_addr) {
2540
0
    coap_log_debug("coap_new_endpoint: Both context and listen_addr need to be defined\n");
2541
0
    return NULL;
2542
0
  }
2543
2544
2.53k
  coap_lock_check_locked();
2545
2546
2.53k
  switch (proto) {
2547
2.53k
  case COAP_PROTO_UDP:
2548
2.53k
    break;
2549
0
  case COAP_PROTO_DTLS:
2550
0
    if (!coap_dtls_is_supported()) {
2551
0
      coap_log_warn("coap_new_endpoint: DTLS not supported\n");
2552
0
      return NULL;
2553
0
    }
2554
0
    break;
2555
0
  case COAP_PROTO_TLS:
2556
0
    if (!coap_tls_is_supported()) {
2557
0
      coap_log_warn("coap_new_endpoint: TLS not supported\n");
2558
0
      return NULL;
2559
0
    }
2560
0
    break;
2561
0
  case COAP_PROTO_TCP:
2562
0
    if (!coap_tcp_is_supported()) {
2563
0
      coap_log_warn("coap_new_endpoint: TCP not supported\n");
2564
0
      return NULL;
2565
0
    }
2566
0
    break;
2567
0
  case COAP_PROTO_WS:
2568
0
    if (!coap_ws_is_supported()) {
2569
0
      coap_log_warn("coap_new_endpoint: WS not supported\n");
2570
0
      return NULL;
2571
0
    }
2572
0
    break;
2573
0
  case COAP_PROTO_WSS:
2574
0
    if (!coap_wss_is_supported()) {
2575
0
      coap_log_warn("coap_new_endpoint: WSS not supported\n");
2576
0
      return NULL;
2577
0
    }
2578
0
    break;
2579
0
  case COAP_PROTO_NONE:
2580
0
  case COAP_PROTO_LAST:
2581
0
  default:
2582
0
    coap_log_crit("coap_new_endpoint: Unsupported protocol %d\n", proto);
2583
0
    return NULL;
2584
2.53k
  }
2585
2586
2.53k
  if (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS ||
2587
2.53k
      proto == COAP_PROTO_WSS) {
2588
0
    if (!coap_dtls_context_check_keys_enabled(context)) {
2589
0
      coap_log_info("coap_new_endpoint: one of coap_context_set_psk() or "
2590
0
                    "coap_context_set_pki() not called\n");
2591
0
      return NULL;
2592
0
    }
2593
0
  }
2594
2.53k
  ep = coap_malloc_endpoint();
2595
2.53k
  if (!ep) {
2596
0
    coap_log_warn("coap_new_endpoint: malloc");
2597
0
    return NULL;
2598
0
  }
2599
2600
2.53k
  memset(ep, 0, sizeof(coap_endpoint_t));
2601
2.53k
  ep->context = context;
2602
2.53k
  ep->proto = proto;
2603
2.53k
  ep->sock.endpoint = ep;
2604
2.53k
  if (proto < COAP_PROTO_LAST) {
2605
    /*
2606
     * Should be caught above, but come compilers realize that proto
2607
     * includes COAP_PROTO_LAST, but there is no table entry for that
2608
     */
2609
2.53k
    memcpy(&ep->sock.lfunc, coap_layers_coap[proto], sizeof(ep->sock.lfunc));
2610
2.53k
  }
2611
2612
2.53k
  if (COAP_PROTO_NOT_RELIABLE(proto)) {
2613
2.53k
    if (!coap_netif_dgrm_listen(ep, listen_addr))
2614
0
      goto error;
2615
#ifdef WITH_CONTIKI
2616
    ep->sock.context = context;
2617
#endif /* WITH_CONTIKI */
2618
2.53k
#if !COAP_DISABLE_TCP
2619
2.53k
  } else if (COAP_PROTO_RELIABLE(proto)) {
2620
0
    if (!coap_netif_strm_listen(ep, listen_addr))
2621
0
      goto error;
2622
0
#endif /* !COAP_DISABLE_TCP */
2623
0
  } else {
2624
0
    coap_log_crit("coap_new_endpoint: Protocol type not supported %d\n", proto);
2625
0
    goto error;
2626
0
  }
2627
2628
2.53k
  if (COAP_LOG_DEBUG <= coap_get_log_level()) {
2629
#ifndef INET6_ADDRSTRLEN
2630
#define INET6_ADDRSTRLEN 40
2631
#endif
2632
0
    unsigned char addr_str[INET6_ADDRSTRLEN + 8];
2633
2634
0
    if (coap_print_addr(&ep->bind_addr, addr_str, INET6_ADDRSTRLEN + 8)) {
2635
0
      coap_log_debug("created %s endpoint %s\n", coap_proto_name(ep->proto),
2636
0
                     addr_str);
2637
0
    }
2638
0
  }
2639
2640
2.53k
  ep->default_mtu = COAP_DEFAULT_MTU;
2641
2642
2.53k
#ifdef COAP_EPOLL_SUPPORT
2643
2.53k
  ep->sock.endpoint = ep;
2644
2.53k
  coap_epoll_ctl_add(&ep->sock,
2645
2.53k
                     EPOLLIN,
2646
2.53k
                     __func__);
2647
2.53k
#endif /* COAP_EPOLL_SUPPORT */
2648
2649
2.53k
  LL_PREPEND(context->endpoint, ep);
2650
2.53k
  return ep;
2651
2652
0
error:
2653
0
  coap_free_endpoint_lkd(ep);
2654
0
  return NULL;
2655
2.53k
}
2656
2657
void
2658
0
coap_endpoint_set_default_mtu(coap_endpoint_t *ep, unsigned mtu) {
2659
0
  ep->default_mtu = (uint16_t)mtu;
2660
0
}
2661
2662
COAP_API void
2663
0
coap_free_endpoint(coap_endpoint_t *ep) {
2664
0
  if (ep) {
2665
0
    coap_context_t *context = ep->context;
2666
0
    if (context) {
2667
0
      coap_lock_lock(return);
2668
0
    }
2669
0
    coap_free_endpoint_lkd(ep);
2670
0
    if (context) {
2671
0
      coap_lock_unlock();
2672
0
    }
2673
0
  }
2674
0
}
2675
2676
void
2677
2.53k
coap_free_endpoint_lkd(coap_endpoint_t *ep) {
2678
2.53k
  if (ep) {
2679
2.53k
    coap_session_t *session, *rtmp;
2680
2681
2.53k
    if (ep->context) {
2682
      /* If fully allocated and inserted */
2683
2.53k
      coap_lock_check_locked();
2684
2.53k
      SESSIONS_ITER_SAFE(ep->sessions, session, rtmp) {
2685
0
        if (session->ref > 0) {
2686
0
          coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE);
2687
0
#if COAP_CLIENT_SUPPORT
2688
0
          if (session->client_initiated) {
2689
0
            coap_session_release_lkd(session);
2690
0
          }
2691
0
#endif /* COAP_CLIENT_SUPPORT */
2692
0
        }
2693
0
        assert(session->ref == 0);
2694
0
        if (session->ref == 0) {
2695
0
          coap_handle_event_lkd(ep->context, COAP_EVENT_SERVER_SESSION_DEL, session);
2696
0
          coap_session_free(session);
2697
0
        }
2698
0
      }
2699
2.53k
      if (coap_netif_available_ep(ep)) {
2700
        /*
2701
         * ep->sock.endpoint is set in coap_new_endpoint().
2702
         * ep->sock.session is never set.
2703
         *
2704
         * session->sock.session is set for both clients and servers (when a
2705
         * new session is accepted), but does not affect the endpoint.
2706
         *
2707
         * So, it is safe to call coap_netif_close_ep() after all the sessions
2708
         * have been freed above as we are only working with the endpoint sock.
2709
         */
2710
2.53k
#ifdef COAP_EPOLL_SUPPORT
2711
2.53k
        assert(ep->sock.session == NULL);
2712
2.53k
#endif /* COAP_EPOLL_SUPPORT */
2713
2.53k
        coap_netif_close_ep(ep);
2714
2.53k
      }
2715
2716
2.53k
      if (ep->context->endpoint) {
2717
2.53k
        LL_DELETE(ep->context->endpoint, ep);
2718
2.53k
      }
2719
2.53k
    }
2720
2721
2.53k
    if (ep->app_cb) {
2722
0
      coap_lock_callback(ep->app_cb(ep->app_data));
2723
0
    }
2724
2725
2.53k
    coap_mfree_endpoint(ep);
2726
2.53k
  }
2727
2.53k
}
2728
2729
void *
2730
0
coap_endpoint_get_app_data(const coap_endpoint_t *endpoint) {
2731
0
  assert(endpoint);
2732
0
  return endpoint->app_data;
2733
0
}
2734
2735
COAP_API void *
2736
coap_endpoint_set_app_data(coap_endpoint_t *endpoint, void *app_data,
2737
0
                           coap_app_data_free_callback_t callback) {
2738
0
  void *old_data;
2739
2740
0
  coap_lock_lock(return NULL);
2741
0
  old_data = coap_endpoint_set_app_data_lkd(endpoint, app_data, callback);
2742
0
  coap_lock_unlock();
2743
0
  return old_data;
2744
0
}
2745
2746
void *
2747
coap_endpoint_set_app_data_lkd(coap_endpoint_t *endpoint, void *app_data,
2748
0
                               coap_app_data_free_callback_t callback) {
2749
0
  void *old_data = endpoint->app_data;
2750
2751
0
  endpoint->app_data = app_data;
2752
0
  endpoint->app_cb = app_data ? callback : NULL;
2753
0
  return old_data;
2754
0
}
2755
2756
#endif /* COAP_SERVER_SUPPORT */
2757
2758
coap_session_t *
2759
coap_session_get_by_peer(const coap_context_t *ctx,
2760
                         const coap_address_t *remote_addr,
2761
0
                         int ifindex) {
2762
0
  coap_session_t *s, *rtmp;
2763
0
#if COAP_CLIENT_SUPPORT
2764
0
  SESSIONS_ITER(ctx->sessions, s, rtmp) {
2765
0
    if (s->ifindex == ifindex) {
2766
0
      if (s->sock.flags & COAP_SOCKET_MULTICAST) {
2767
0
        if (coap_address_equals(&s->sock.mcast_addr, remote_addr))
2768
0
          return s;
2769
0
      } else if (coap_address_equals(&s->addr_info.remote, remote_addr))
2770
0
        return s;
2771
0
    }
2772
0
  }
2773
0
#endif /* COAP_CLIENT_SUPPORT */
2774
0
#if COAP_SERVER_SUPPORT
2775
0
  coap_endpoint_t *ep;
2776
2777
0
  LL_FOREACH(ctx->endpoint, ep) {
2778
0
    SESSIONS_ITER(ep->sessions, s, rtmp) {
2779
0
      if (s->ifindex == ifindex && coap_address_equals(&s->addr_info.remote,
2780
0
                                                       remote_addr))
2781
0
        return s;
2782
0
    }
2783
0
  }
2784
0
#endif /* COAP_SERVER_SUPPORT */
2785
0
  return NULL;
2786
0
}
2787
2788
#ifndef INET6_ADDRSTRLEN
2789
#define INET6_ADDRSTRLEN 46
2790
#endif
2791
const char *
2792
0
coap_session_str(const coap_session_t *session) {
2793
0
  static char szSession[2 * (INET6_ADDRSTRLEN + 8) + 24];
2794
0
  char *p = szSession, *end = szSession + sizeof(szSession);
2795
2796
0
  if (!session) {
2797
0
    return "Session not defined";
2798
0
  }
2799
0
  if (coap_print_addr(&session->addr_info.local,
2800
0
                      (unsigned char *)p, end - p) > 0)
2801
0
    p += strlen(p);
2802
0
  if (p + 6 < end) {
2803
0
    strcpy(p, " <-> ");
2804
0
    p += 5;
2805
0
  }
2806
0
  if (p + 1 < end) {
2807
0
    if (coap_print_addr(&session->addr_info.remote,
2808
0
                        (unsigned char *)p, end - p) > 0)
2809
0
      p += strlen(p);
2810
0
  }
2811
0
  if (session->ifindex > 0 && p + 1 < end)
2812
0
    p += snprintf(p, end - p, " (if%d)", session->ifindex);
2813
0
  if (p + 6 < end) {
2814
0
    strcpy(p, " ");
2815
0
    p++;
2816
0
    strcpy(p, coap_proto_name(session->proto));
2817
0
  }
2818
2819
0
  return szSession;
2820
0
}
2821
2822
#if COAP_SERVER_SUPPORT
2823
const char *
2824
0
coap_endpoint_str(const coap_endpoint_t *endpoint) {
2825
0
  static char szEndpoint[128];
2826
0
  char *p = szEndpoint, *end = szEndpoint + sizeof(szEndpoint);
2827
0
  if (coap_print_addr(&endpoint->bind_addr, (unsigned char *)p, end - p) > 0)
2828
0
    p += strlen(p);
2829
0
  if (p + 6 < end) {
2830
0
    if (endpoint->proto == COAP_PROTO_UDP) {
2831
0
      strcpy(p, " UDP");
2832
0
    } else if (endpoint->proto == COAP_PROTO_DTLS) {
2833
0
      strcpy(p, " DTLS");
2834
0
    } else {
2835
0
      strcpy(p, " NONE");
2836
0
    }
2837
0
  }
2838
2839
0
  return szEndpoint;
2840
0
}
2841
#endif /* COAP_SERVER_SUPPORT */
2842
#if COAP_CLIENT_SUPPORT
2843
void
2844
0
coap_session_set_no_observe_cancel(coap_session_t *session) {
2845
0
  session->no_observe_cancel = 1;
2846
0
}
2847
2848
void
2849
0
coap_call_home_stop_reconnecting(coap_session_t *session) {
2850
0
  if (session->type != COAP_SESSION_TYPE_CLIENT) {
2851
0
    coap_lock_lock(return);
2852
0
    coap_session_set_type_client_lkd(session, 0);
2853
0
    coap_session_release_lkd(session);
2854
0
    coap_lock_unlock();
2855
0
  }
2856
0
}
2857
#endif /* COAP_CLIENT_SUPPORT */
2858
#endif  /* COAP_SESSION_C_ */