Coverage Report

Created: 2026-11-12 06:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libcoap/src/coap_uri.c
Line
Count
Source
1
/* coap_uri.c -- helper functions for URI treatment
2
 *
3
 * Copyright (C) 2010--2012,2015-2016,2022-2026 Olaf Bergmann <bergmann@tzi.org>
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 *
7
 * This file is part of the CoAP library libcoap. Please see
8
 * README for terms of use.
9
 */
10
11
/**
12
 * @file coap_uri.c
13
 * @brief URI handling functions
14
 */
15
16
#include "coap3/coap_libcoap_build.h"
17
18
#if defined(HAVE_LIMITS_H)
19
#include <limits.h>
20
#endif
21
22
#include <stdint.h>
23
#include <stdio.h>
24
#include <string.h>
25
#include <ctype.h>
26
27
#ifdef _WIN32
28
#define strcasecmp _stricmp
29
#define strncasecmp _strnicmp
30
#endif
31
32
coap_upa_chain_t *coap_upa_client_fallback_chain = NULL;
33
coap_upa_chain_t *coap_upa_server_mapping_chain = NULL;
34
35
/**
36
 * A length-safe version of strchr(). This function returns a pointer
37
 * to the first occurrence of @p c  in @p s, or @c NULL if not found.
38
 *
39
 * @param s   The string to search for @p c.
40
 * @param len The length of @p s.
41
 * @param c   The character to search.
42
 *
43
 * @return A pointer to the first occurrence of @p c, or @c NULL
44
 * if not found.
45
 */
46
COAP_STATIC_INLINE const uint8_t *
47
0
strnchr(const uint8_t *s, size_t len, unsigned char c) {
48
0
  while (len && *s++ != c)
49
0
    --len;
50
51
0
  return len ? s : NULL;
52
0
}
53
54
typedef enum coap_uri_check_t {
55
  COAP_URI_CHECK_URI,
56
  COAP_URI_CHECK_PROXY
57
} coap_uri_check_t;
58
59
coap_uri_info_t coap_uri_scheme[COAP_URI_SCHEME_LAST] = {
60
  { "coap",       COAP_DEFAULT_PORT,  0, COAP_URI_SCHEME_COAP },
61
  { "coaps",      COAPS_DEFAULT_PORT, 0, COAP_URI_SCHEME_COAPS },
62
  { "coap+tcp",   COAP_DEFAULT_PORT,  0, COAP_URI_SCHEME_COAP_TCP },
63
  { "coaps+tcp",  COAPS_DEFAULT_PORT, 0, COAP_URI_SCHEME_COAPS_TCP },
64
  { "http",         80,               1, COAP_URI_SCHEME_HTTP },
65
  { "https",       443,               1, COAP_URI_SCHEME_HTTPS },
66
  { "coap+ws",      80,               0, COAP_URI_SCHEME_COAP_WS },
67
  { "coaps+ws",    443,               0, COAP_URI_SCHEME_COAPS_WS }
68
};
69
70
/*
71
 * Returns  0 All OK
72
 *         -1 Insufficient / Invalid parameters
73
 *         -2 No '://'
74
 *         -3 Ipv6 definition error or no host defined after scheme://
75
 *         -4 Invalid port value
76
 *         -5 Port defined for Unix domain or LLC host
77
 *         -6 Hostname > 255 chars
78
 *         -7 Invalid LLC address
79
 */
80
static int
81
coap_split_uri_sub(const uint8_t *str_var,
82
                   size_t len,
83
                   coap_uri_t *uri,
84
0
                   coap_uri_check_t check_proxy) {
85
0
  const uint8_t *p, *q;
86
0
  int res = 0;
87
0
  size_t i;
88
0
  int is_unix_domain = 0;
89
0
  int is_llc = 0;
90
91
0
  if (!str_var || !uri || len == 0)
92
0
    return -1;
93
94
0
  memset(uri, 0, sizeof(coap_uri_t));
95
0
  uri->port = COAP_DEFAULT_PORT;
96
97
  /* search for scheme */
98
0
  p = str_var;
99
0
  if (*p == '/') {
100
    /* no scheme, host or port */
101
0
    if (check_proxy == COAP_URI_CHECK_PROXY) {
102
      /* Must have ongoing host if proxy definition */
103
0
      return -1;
104
0
    }
105
0
    q = p;
106
0
    goto path;
107
0
  }
108
109
  /* find scheme terminating :// */
110
0
  while (len >= 3 && !(p[0] == ':' && p[1] == '/' && p[2] == '/')) {
111
0
    ++p;
112
0
    --len;
113
0
  }
114
0
  if (len < 3) {
115
    /* scheme not defined with a :// terminator */
116
0
    res = -2;
117
0
    goto error;
118
0
  }
119
0
  for (i = 0; i < COAP_URI_SCHEME_LAST; i++) {
120
0
    if ((p - str_var) == (int)strlen(coap_uri_scheme[i].name) &&
121
0
        memcmp(str_var, coap_uri_scheme[i].name, p - str_var) == 0) {
122
0
      if (check_proxy != COAP_URI_CHECK_PROXY && coap_uri_scheme[i].proxy_only) {
123
0
        coap_log_err("%.*s URI scheme not enabled (not a proxy)\n",
124
0
                     (int)(p - str_var), str_var);
125
0
        return -1;
126
0
      }
127
0
      uri->scheme = coap_uri_scheme[i].scheme;
128
0
      uri->port = coap_uri_scheme[i].port;
129
0
      break;
130
0
    }
131
0
  }
132
0
  if (i == COAP_URI_SCHEME_LAST) {
133
    /* scheme unknown */
134
0
    coap_log_err("%.*s URI scheme unknown\n", (int)(p - str_var), str_var);
135
0
    res = -1;
136
0
    goto error;
137
0
  }
138
0
  switch (uri->scheme) {
139
0
  case COAP_URI_SCHEME_COAP:
140
0
    break;
141
0
  case COAP_URI_SCHEME_COAPS:
142
0
    if (!coap_dtls_is_supported()) {
143
0
      coap_log_err("coaps URI scheme not supported in this version of libcoap\n");
144
0
      return -1;
145
0
    }
146
0
    break;
147
0
  case COAP_URI_SCHEME_COAP_TCP:
148
0
    if (!coap_tcp_is_supported()) {
149
0
      coap_log_err("coap+tcp URI scheme not supported in this version of libcoap\n");
150
0
      return -1;
151
0
    }
152
0
    break;
153
0
  case COAP_URI_SCHEME_COAPS_TCP:
154
0
    if (!coap_tls_is_supported()) {
155
0
      coap_log_err("coaps+tcp URI scheme not supported in this version of libcoap\n");
156
0
      return -1;
157
0
    }
158
0
    break;
159
0
  case COAP_URI_SCHEME_COAP_WS:
160
0
    if (!coap_ws_is_supported()) {
161
0
      coap_log_err("coap+ws URI scheme not supported in this version of libcoap\n");
162
0
      return -1;
163
0
    }
164
0
    break;
165
0
  case COAP_URI_SCHEME_COAPS_WS:
166
0
    if (!coap_wss_is_supported()) {
167
0
      coap_log_err("coaps+ws URI scheme not supported in this version of libcoap\n");
168
0
      return -1;
169
0
    }
170
0
    break;
171
0
  case COAP_URI_SCHEME_HTTP:
172
0
  case COAP_URI_SCHEME_HTTPS:
173
    /* Not proxy, caught above.  For proxy, assume app is doing CoAP <> HTTP mapping. */
174
0
    break;
175
0
  case COAP_URI_SCHEME_LAST:
176
0
  default:
177
0
    coap_log_warn("Unsupported URI type %d\n", uri->scheme);
178
0
    return -1;
179
0
  }
180
  /* skip :// */
181
0
  p += 3;
182
0
  len -= 3;
183
184
  /* p points to beginning of Uri-Host */
185
0
  q = p;
186
187
0
  if (len && *p == '[') {
188
    /* IPv6 address reference or Unix domain */
189
0
    ++p;
190
0
    ++q;
191
0
    --len;
192
193
0
    while (len && *q != ']') {
194
0
      ++q;
195
0
      --len;
196
0
    }
197
198
0
    if (!len || *q != ']' || p == q) {
199
0
      res = -3;
200
0
      goto error;
201
0
    }
202
203
0
    if ((int)(q - p) > 255) {
204
0
      coap_log_warn("Host name length too long (%d > 255)\n", (int)(q - p));
205
0
      res = -6;
206
0
      goto error;
207
0
    }
208
209
0
    COAP_SET_STR(&uri->host, q - p, p);
210
0
    ++q;
211
0
    --len;
212
0
#if COAP_AF_LLC_SUPPORT
213
0
  } else if ((len >= LLC_HOST_LEN) && strncmp((const char *)p, "llc[", 4) == 0) {
214
0
    unsigned long sap = 0;
215
216
0
    is_llc = 1;
217
218
0
    while (len && *q != ']') {
219
0
      ++q;
220
0
      --len;
221
0
    }
222
223
0
    if (!len || *q != ']' || p == q) {
224
0
      res = -7;
225
0
      goto error;
226
0
    }
227
228
0
    ++q;
229
0
    --len;
230
231
0
    if (!len || *q != ':') {
232
0
      coap_log_warn("LLC SAP missing in URI\n");
233
0
      res = -7;
234
0
      goto error;
235
0
    }
236
237
0
    ++q;
238
0
    --len;
239
240
0
    while (len && isxdigit(*q)) {
241
0
      if (*q >= 'a' && *q <= 'f')
242
0
        sap = sap * 16 + (*q - 'a' + 10);
243
0
      else if (*q >= 'A' && *q <= 'F')
244
0
        sap = sap * 16 + (*q - 'A' + 10);
245
246
0
      ++q;
247
0
      --len;
248
0
    }
249
250
0
    if (sap > UINT8_MAX) {
251
0
      coap_log_warn("LLC SAP invalid (%lu > 255)\n", sap);
252
0
      res = -7;
253
0
      goto error;
254
0
    }
255
256
0
    COAP_SET_STR(&uri->host, q - p, p);
257
0
#endif /* COAP_AF_LLC_SUPPORT */
258
0
  } else {
259
    /* IPv4 address, FQDN or Unix domain socket */
260
0
    if (len >= 3 && p[0] == '%' && p[1] == '2' &&
261
0
        (p[2] == 'F' || p[2] == 'f')) {
262
      /* Unix domain definition */
263
0
      uri->port = 0;
264
0
      is_unix_domain = 1;
265
0
    }
266
0
    while (len && *q != ':' && *q != '/' && *q != '?') {
267
0
      ++q;
268
0
      --len;
269
0
    }
270
271
0
    if (p == q) {
272
0
      res = -3;
273
0
      goto error;
274
0
    }
275
276
0
    if ((int)(q - p) > 255) {
277
0
      coap_log_warn("Host name length too long (%d > 255)\n", (int)(q - p));
278
0
      res = -6;
279
0
      goto error;
280
0
    }
281
282
0
    COAP_SET_STR(&uri->host, q - p, p);
283
0
  }
284
285
  /* check for Uri-Port (invalid for Unix) */
286
0
  if (len && *q == ':') {
287
0
    if (is_unix_domain || is_llc) {
288
0
      res = -5;
289
0
      goto error;
290
0
    }
291
0
    p = ++q;
292
0
    --len;
293
294
0
    while (len && isdigit(*q)) {
295
0
      ++q;
296
0
      --len;
297
0
    }
298
299
0
    if (p < q) {                /* explicit port number given */
300
0
      long uri_port = 0;
301
302
0
      while ((p < q) && (uri_port <= UINT16_MAX))
303
0
        uri_port = uri_port * 10 + (*p++ - '0');
304
305
      /* check if port number is in allowed range */
306
0
      if (uri_port > UINT16_MAX) {
307
0
        coap_log_warn("Port number too big (%ld > 65535)\n", uri_port);
308
0
        res = -4;
309
0
        goto error;
310
0
      }
311
312
0
      uri->port = (uint16_t)uri_port;
313
0
    }
314
0
  }
315
316
0
path:                 /* at this point, p must point to an absolute path */
317
318
0
  if (!len)
319
0
    goto end;
320
321
0
  if (*q == '/') {
322
0
    p = ++q;
323
0
    --len;
324
325
0
    while (len && *q != '?') {
326
0
      ++q;
327
0
      --len;
328
0
    }
329
330
0
    if (p < q) {
331
0
      COAP_SET_STR(&uri->path, q - p, p);
332
0
      p = q;
333
0
    }
334
0
  }
335
336
  /* Uri_Query */
337
0
  if (len && *p == '?') {
338
0
    ++p;
339
0
    --len;
340
0
    COAP_SET_STR(&uri->query, len, p);
341
0
    len = 0;
342
0
  }
343
344
0
end:
345
0
  return len ? -1 : 0;
346
347
0
error:
348
0
  return res;
349
0
}
350
351
int
352
0
coap_split_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri) {
353
0
  return coap_split_uri_sub(str_var, len, uri, COAP_URI_CHECK_URI);
354
0
}
355
356
int
357
0
coap_split_proxy_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri) {
358
0
  return coap_split_uri_sub(str_var, len, uri, COAP_URI_CHECK_PROXY);
359
0
}
360
361
static void
362
0
coap_replace_upper_lower(coap_optlist_t *optlist) {
363
0
  size_t i;
364
365
0
  for (i = 0; i < optlist->length; i++) {
366
0
    if (optlist->data[i] >= 'A' && optlist->data[i] <= 'Z') {
367
0
      optlist->data[i] += 'a' - 'A';
368
0
    }
369
0
  }
370
0
}
371
372
int
373
coap_uri_into_options(const coap_uri_t *uri, const coap_address_t *dst,
374
                      coap_optlist_t **optlist_chain, int create_port_host_opt,
375
0
                      uint8_t *_buf COAP_UNUSED, size_t buflen COAP_UNUSED) {
376
0
  return !coap_uri_into_optlist(uri, dst, optlist_chain, create_port_host_opt) ? -1 : 0;
377
0
}
378
379
int
380
coap_uri_into_optlist(const coap_uri_t *uri, const coap_address_t *dst,
381
0
                      coap_optlist_t **optlist_chain, int create_port_host_opt) {
382
0
  return coap_uri_into_optlist_abbrev(uri, dst, optlist_chain, create_port_host_opt, NULL, 0);
383
0
}
384
385
int
386
coap_uri_into_optlist_abbrev(const coap_uri_t *uri, const coap_address_t *dst,
387
                             coap_optlist_t **optlist_chain, int create_port_host_opt,
388
0
                             coap_upa_abbrev_t *mapping, uint32_t count) {
389
0
  if (create_port_host_opt && !coap_host_is_unix_domain(&uri->host)) {
390
0
    int add_option = 0;
391
392
0
    if (dst && uri->host.length) {
393
0
#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
394
0
      char addr[INET6_ADDRSTRLEN];
395
#else /* WITH_LWIP || WITH_CONTIKI */
396
      char addr[40];
397
#endif /* WITH_LWIP || WITH_CONTIKI */
398
0
      coap_optlist_t *optlist;
399
400
      /* Add in Uri-Host if not match (need to strip off %iface) */
401
0
      size_t uri_host_len = uri->host.length;
402
0
      const uint8_t *cp = uri->host.s;
403
404
      /* Unfortunately not null terminated */
405
0
      for (size_t i = 0; i < uri_host_len; i++) {
406
0
        if (cp[i] == '%') {
407
          /* %iface specified in host name */
408
0
          uri_host_len = i;
409
0
          break;
410
0
        }
411
0
      }
412
413
0
      if (coap_print_ip_addr(dst, addr, sizeof(addr)) &&
414
0
          (strlen(addr) != uri_host_len ||
415
0
           strncasecmp(addr, (const char *)uri->host.s, uri_host_len) != 0)) {
416
        /* add Uri-Host */
417
0
        optlist = coap_new_optlist(COAP_OPTION_URI_HOST, uri_host_len,
418
0
                                   uri->host.s);
419
0
        if (!optlist)
420
0
          return 0;
421
0
        if (!coap_host_is_unix_domain(&uri->host)) {
422
0
          coap_replace_percents(optlist);
423
0
          coap_replace_upper_lower(optlist);
424
0
        }
425
0
        if (!coap_insert_optlist(optlist_chain, optlist)) {
426
0
          return 0;
427
0
        }
428
0
      }
429
0
    }
430
    /* Add in UriPort if not default */
431
0
    switch ((int)uri->scheme) {
432
0
    case COAP_URI_SCHEME_HTTP:
433
0
    case COAP_URI_SCHEME_COAP_WS:
434
0
      if (uri->port != 80)
435
0
        add_option = 1;
436
0
      break;
437
0
    case COAP_URI_SCHEME_HTTPS:
438
0
    case COAP_URI_SCHEME_COAPS_WS:
439
0
      if (uri->port != 443)
440
0
        add_option = 1;
441
0
      break;
442
0
    default:
443
0
      if (uri->port != (coap_uri_scheme_is_secure(uri) ? COAPS_DEFAULT_PORT :
444
0
                        COAP_DEFAULT_PORT))
445
0
        add_option = 1;
446
0
      break;
447
0
    }
448
0
    if (add_option) {
449
0
      uint8_t tbuf[4];
450
451
0
      coap_insert_optlist(optlist_chain,
452
0
                          coap_new_optlist(COAP_OPTION_URI_PORT,
453
0
                                           coap_encode_var_safe(tbuf, 4,
454
0
                                                                (uri->port & 0xffff)),
455
0
                                           tbuf));
456
0
    }
457
0
  }
458
459
0
  if (uri->path.length) {
460
0
    if (!coap_path_into_optlist_abbrev(uri->path.s, uri->path.length, COAP_OPTION_URI_PATH,
461
0
                                       optlist_chain, mapping, count))
462
0
      return 0;
463
0
  }
464
465
0
  if (uri->query.length) {
466
0
    if (!coap_query_into_optlist(uri->query.s, uri->query.length, COAP_OPTION_URI_QUERY,
467
0
                                 optlist_chain))
468
0
      return 0;
469
0
  }
470
0
  return 1;
471
0
}
472
473
int
474
0
coap_host_is_unix_domain(const coap_str_const_t *host) {
475
0
  if (host->length >= 3 && host->s[0] == '%' &&
476
0
      host->s[1] == '2' &&
477
0
      (host->s[2] == 'F' || host->s[2] == 'f')) {
478
0
    return 1;
479
0
  }
480
0
  if (host->length >= 1 && host->s[0] == '/')
481
0
    return 1;
482
0
  return 0;
483
0
}
484
485
int
486
0
coap_host_is_llc(const coap_str_const_t *host) {
487
0
#if COAP_AF_LLC_SUPPORT
488
0
  size_t length;
489
0
  const uint8_t *s = NULL;
490
0
  int i = 0;
491
492
0
  length = host->length;
493
0
  if (length != LLC_HOST_LEN)
494
0
    return 0;
495
496
0
  s = host->s;
497
498
0
  if (strncmp((const char *)s, "llc[", 4) != 0)
499
0
    return 0;
500
501
0
  length -= 4;
502
0
  s += 4;
503
504
0
  while (length) {
505
0
    if (!isxdigit(s[0]) || !isxdigit(s[1]))
506
0
      return 0;
507
508
0
    length -= 2;
509
0
    s += 2;
510
511
0
    i++;
512
513
0
    if (length <= 0 || i >= 6)
514
0
      break;
515
516
0
    if (s[0] != ':')
517
0
      return 0;
518
519
0
    length--;
520
0
    s++;
521
0
  }
522
523
0
  if (s[0] != ']' || s[1] != ':' || !isxdigit(s[2]) || !isxdigit(s[3]))
524
0
    return 0;
525
526
0
  return 1;
527
#else /* COAP_AF_LLC_SUPPORT */
528
  (void)host;
529
  return 0;
530
#endif /* COAP_AF_LLC_SUPPORT */
531
0
}
532
533
/**
534
 * Calculates decimal value from hexadecimal ASCII character given in
535
 * @p c. The caller must ensure that @p c actually represents a valid
536
 * heaxdecimal character, e.g. with isxdigit(3).
537
 *
538
 * @hideinitializer
539
 */
540
0
#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
541
542
/**
543
 * Decodes percent-encoded characters while copying the string @p seg
544
 * of size @p length to @p buf. The caller of this function must
545
 * ensure that the percent-encodings are correct (i.e. the character
546
 * '%' is always followed by two hex digits. and that @p buf provides
547
 * sufficient space to hold the result. This function is supposed to
548
 * be called by make_decoded_option() only.
549
 *
550
 * @param seg     The segment to decode and copy.
551
 * @param length  Length of @p seg.
552
 * @param buf     The result buffer.
553
 */
554
static void
555
0
decode_segment(const uint8_t *seg, size_t length, unsigned char *buf) {
556
557
0
  while (length) {
558
0
    length--;
559
560
0
    if (*seg == '%') {
561
0
      if (length < 2)
562
0
        return;
563
0
      *buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
564
565
0
      seg += 2;
566
0
      length -= 2;
567
0
    } else {
568
0
      *buf = *seg;
569
0
    }
570
571
0
    ++buf;
572
0
    ++seg;
573
0
  }
574
0
}
575
576
/**
577
 * Runs through the given path (or query) segment and checks if
578
 * percent-encodings are correct. This function returns @c 0 on success
579
 * and @c -1 on error.
580
 */
581
static int
582
0
check_segment(const uint8_t *s, size_t length, size_t *segment_size) {
583
0
  size_t n = 0;
584
585
0
  while (length) {
586
0
    if (*s == '%') {
587
0
      if (length < 3 || !(isxdigit(s[1]) && isxdigit(s[2])))
588
0
        return -1;
589
590
0
      s += 2;
591
0
      length -= 2;
592
0
    }
593
594
0
    ++s;
595
0
    ++n;
596
0
    --length;
597
0
  }
598
599
0
  *segment_size = n;
600
601
0
  return 0;
602
0
}
603
604
/**
605
 * Writes a coap option from given string @p s to @p buf. @p s should
606
 * point to a (percent-encoded) path or query segment of a coap_uri_t
607
 * object.  The created option will have type @c 0, and the length
608
 * parameter will be set according to the size of the decoded string.
609
 * On success, this function returns @c 0 and sets @p optionsize to the option's
610
 * size. On error the function returns a value less than zero. This function
611
 * must be called from coap_split_path_impl() only.
612
 *
613
 * @param s           The string to decode.
614
 * @param length      The size of the percent-encoded string @p s.
615
 * @param buf         The buffer to store the new coap option.
616
 * @param buflen      The maximum size of @p buf.
617
 * @param optionsize  The option's size.
618
 *
619
 * @return @c 0 on success and @c -1 on error.
620
 *
621
 * @bug This function does not split segments that are bigger than 270
622
 * bytes.
623
 */
624
static int
625
make_decoded_option(const uint8_t *s, size_t length,
626
0
                    unsigned char *buf, size_t buflen, size_t *optionsize) {
627
0
  int res;
628
0
  size_t segmentlen;
629
0
  size_t written;
630
631
0
  if (!buflen) {
632
0
    coap_log_debug("make_decoded_option(): buflen is 0!\n");
633
0
    return -1;
634
0
  }
635
636
0
  res = check_segment(s, length, &segmentlen);
637
0
  if (res < 0)
638
0
    return -1;
639
640
  /* write option header using delta 0 and length res */
641
0
  written = coap_opt_setheader(buf, buflen, 0, segmentlen);
642
643
0
  assert(written <= buflen);
644
645
0
  if (!written)                        /* encoding error */
646
0
    return -1;
647
648
0
  buf += written;                /* advance past option type/length */
649
0
  buflen -= written;
650
651
0
  if (buflen < segmentlen) {
652
0
    coap_log_debug("buffer too small for option\n");
653
0
    return -1;
654
0
  }
655
656
0
  decode_segment(s, length, buf);
657
658
0
  *optionsize = written + segmentlen;
659
660
0
  return 0;
661
0
}
662
663
664
#ifndef min
665
#define min(a,b) ((a) < (b) ? (a) : (b))
666
#endif
667
668
typedef void (*segment_handler_t)(const uint8_t *, size_t, void *);
669
670
/**
671
 * Checks if path segment @p s consists of one or two dots.
672
 *
673
 * returns 1 if . , 2 if .. else 0.
674
 */
675
int
676
487
coap_check_dots(const uint8_t *s, size_t len) {
677
487
  uint8_t p;
678
679
487
  if (!len)
680
206
    return 0;
681
682
281
  p = *s;
683
684
  /* Check 'first' char */
685
281
  if (p == '%' && len >=3) {
686
0
    if (s[1] == '2' && (s[2] == 'E' || s[2] == 'e')) {
687
0
      s += 2;
688
0
      len -= 2;
689
0
    }
690
0
    p = '.';
691
0
  }
692
281
  if (p != '.')
693
203
    return 0;
694
78
  if (len == 1)
695
0
    return 1;
696
697
  /* Check 'second' char, first is '.' */
698
78
  s++;
699
78
  len--;
700
78
  assert(len);
701
78
  p = *s;
702
78
  if (p == '%' && len >=3) {
703
0
    if (s[1] == '2' && (s[2] == 'E' || s[2] == 'e')) {
704
0
      len -= 2;
705
0
    }
706
0
    p = '.';
707
0
  }
708
78
  if (p != '.')
709
78
    return 0;
710
0
  if (len == 1)
711
0
    return 2;
712
713
0
  return 0;
714
0
}
715
716
struct cnt_str {
717
  coap_string_t base_buf;
718
  coap_string_t buf;
719
  int n;
720
};
721
722
static void
723
0
backup_segment(void *data) {
724
0
  struct cnt_str *state = (struct cnt_str *)data;
725
0
  int i;
726
0
  uint8_t *buf;
727
728
0
  if (state->n == 0)
729
0
    return;
730
731
0
  state->n--;
732
0
  buf = state->base_buf.s;
733
0
  for (i = 0; i < state->n; i++) {
734
0
    buf += coap_opt_size(buf);
735
0
  }
736
0
  state->buf.s = buf;
737
0
  state->buf.length = state->base_buf.length - (buf - state->base_buf.s);
738
0
}
739
740
/**
741
 * Splits the given string into segments. You should call one of the
742
 * functions coap_split_path() or coap_split_query() instead.
743
 *
744
 * @param path   The URI path string to be tokenized.
745
 * @param len    The length of @p path.
746
 * @param h      A handler that is called with every token.
747
 * @param data   Opaque data that is passed to @p h when called.
748
 *
749
 * @return The number of characters that have been parsed from @p s.
750
 */
751
static size_t
752
coap_split_path_impl(const uint8_t *path, size_t len,
753
0
                     segment_handler_t h, void *data) {
754
0
  const uint8_t *p, *q;
755
0
  size_t length = len;
756
0
  int num_dots;
757
758
0
  p = q = path;
759
0
  while (length > 0 && !strnchr((const uint8_t *)"?#", 2, *q)) {
760
0
    if (*q == '/') {
761
      /* start new segment */
762
0
      num_dots = coap_check_dots(p, q - p);
763
0
      switch (num_dots) {
764
0
      case 1:
765
        /* drop segment */
766
0
        break;
767
0
      case 2:
768
        /* backup segment */
769
0
        backup_segment(data);
770
0
        break;
771
0
      case 0:
772
0
      default:
773
        /* add segment */
774
0
        h(p, q - p, data);
775
0
        break;
776
0
      }
777
778
0
      p = q + 1;
779
0
    }
780
781
0
    q++;
782
0
    length--;
783
0
  }
784
785
  /* write last segment */
786
0
  num_dots = coap_check_dots(p, q - p);
787
0
  switch (num_dots) {
788
0
  case 1:
789
    /* drop segment */
790
0
    break;
791
0
  case 2:
792
    /* backup segment */
793
0
    backup_segment(data);
794
0
    break;
795
0
  case 0:
796
0
  default:
797
    /* add segment */
798
0
    h(p, q - p, data);
799
0
    break;
800
0
  }
801
802
0
  return q - path;
803
0
}
804
805
static void
806
0
write_option(const uint8_t *s, size_t len, void *data) {
807
0
  struct cnt_str *state = (struct cnt_str *)data;
808
0
  int res;
809
0
  size_t optionsize;
810
0
  assert(state);
811
812
0
  res = make_decoded_option(s, len, state->buf.s, state->buf.length, &optionsize);
813
0
  if (res == 0) {
814
0
    state->buf.s += optionsize;
815
0
    state->buf.length -= optionsize;
816
0
    state->n++;
817
0
  }
818
0
}
819
820
int
821
coap_split_path(const uint8_t *s, size_t length,
822
0
                unsigned char *buf, size_t *buflen) {
823
0
  struct cnt_str tmp = { { *buflen, buf }, { *buflen, buf }, 0 };
824
825
0
  coap_split_path_impl(s, length, write_option, &tmp);
826
827
0
  *buflen = *buflen - tmp.buf.length;
828
829
0
  return tmp.n;
830
0
}
831
832
void
833
0
coap_replace_percents(coap_optlist_t *optlist) {
834
0
  size_t i;
835
0
  size_t o = 0;
836
837
0
  for (i = 0; i < optlist->length; i++) {
838
0
    if (optlist->data[i] == '%' && optlist->length - i >= 3) {
839
0
      optlist->data[o] = (hexchar_to_dec(optlist->data[i+1]) << 4) +
840
0
                         hexchar_to_dec(optlist->data[i+2]);
841
0
      i+= 2;
842
0
    } else if (o != i) {
843
0
      optlist->data[o] = optlist->data[i];
844
0
    }
845
0
    o++;
846
0
  }
847
0
  optlist->length = o;
848
0
}
849
850
static void
851
0
backup_optlist(coap_optlist_t **optlist_begin) {
852
0
  coap_optlist_t *last = NULL;
853
0
  coap_optlist_t *cur = *optlist_begin;
854
855
0
  if (!cur)
856
0
    return;
857
858
0
  while (cur) {
859
0
    if (!cur->next)
860
0
      break;
861
0
    last = cur;
862
0
    cur = cur->next;
863
0
  }
864
0
  coap_delete_optlist(cur);
865
0
  if (last) {
866
0
    last->next = NULL;
867
0
  } else {
868
0
    *optlist_begin = NULL;
869
0
  }
870
0
}
871
872
int
873
coap_path_into_optlist(const uint8_t *s, size_t length, coap_option_num_t optnum,
874
0
                       coap_optlist_t **optlist_chain) {
875
0
  return coap_path_into_optlist_abbrev(s, length, optnum, optlist_chain, NULL, 0);
876
0
}
877
878
int
879
coap_path_into_optlist_abbrev(const uint8_t *s, size_t length, coap_option_num_t optnum,
880
                              coap_optlist_t **optlist_chain, coap_upa_abbrev_t *mapping,
881
0
                              uint32_t count) {
882
0
  const uint8_t *p = s;
883
0
  coap_optlist_t *optlist;
884
0
  int num_dots;
885
0
  coap_optlist_t **optlist_start;
886
887
0
  if (*optlist_chain) {
888
    /* Something previously in optlist_chain. Need to make that the start */
889
0
    optlist_start = &((*optlist_chain)->next);
890
0
  } else {
891
0
    optlist_start = optlist_chain;
892
0
  }
893
894
0
  if (length > 0 && mapping) {
895
0
    uint32_t i;
896
0
    uint8_t buf[4];
897
898
0
    for (i = 0; i < count; i++) {
899
0
      if (strlen(mapping[i].upa_path) == length &&
900
0
          memcmp(mapping[i].upa_path, s, length) == 0) {
901
        /* add in as Uri_path-Abbrev */
902
0
        optlist = coap_new_optlist(COAP_OPTION_URI_PATH_ABB,
903
0
                                   coap_encode_var_safe(buf, sizeof(buf), mapping[i].upa_value), buf);
904
0
        if (!coap_insert_optlist(optlist_chain, optlist)) {
905
0
          return 0;
906
0
        }
907
0
        return 1;
908
0
      }
909
0
    }
910
0
  }
911
0
  while (length > 0 && !strnchr((const uint8_t *)"?#", 2, *s)) {
912
0
    if (*s == '/') {                /* start of new path element */
913
      /* start new segment */
914
0
      num_dots = coap_check_dots(p, s - p);
915
0
      switch (num_dots) {
916
0
      case 1:
917
        /* drop segment */
918
0
        break;
919
0
      case 2:
920
        /* backup segment */
921
0
        backup_optlist(optlist_start);
922
0
        break;
923
0
      case 0:
924
0
      default:
925
        /* add segment */
926
0
        optlist = coap_new_optlist(optnum, s - p, p);
927
0
        if (!optlist) {
928
0
          return 0;
929
0
        }
930
0
        coap_replace_percents(optlist);
931
0
        if (!coap_insert_optlist(optlist_chain, optlist)) {
932
0
          return 0;
933
0
        }
934
0
        break;
935
0
      }
936
0
      p = s + 1;
937
0
    }
938
0
    s++;
939
0
    length--;
940
941
0
  }
942
  /* add last path element */
943
0
  num_dots = coap_check_dots(p, s - p);
944
0
  switch (num_dots) {
945
0
  case 1:
946
    /* drop segment */
947
0
    break;
948
0
  case 2:
949
    /* backup segment */
950
0
    backup_optlist(optlist_start);
951
0
    break;
952
0
  case 0:
953
0
  default:
954
    /* add segment */
955
0
    optlist = coap_new_optlist(optnum, s - p, p);
956
0
    if (!optlist) {
957
0
      return 0;
958
0
    }
959
0
    coap_replace_percents(optlist);
960
0
    if (!coap_insert_optlist(optlist_chain, optlist)) {
961
0
      return 0;
962
0
    }
963
0
    break;
964
0
  }
965
0
  return 1;
966
0
}
967
968
int
969
coap_split_query(const uint8_t *s, size_t length,
970
0
                 unsigned char *buf, size_t *buflen) {
971
0
  struct cnt_str tmp = { { *buflen, buf }, { *buflen, buf }, 0 };
972
0
  const uint8_t *p;
973
974
0
  p = s;
975
0
  while (length > 0 && *s != '#') {
976
0
    if (*s == '&') {                /* start new query element */
977
0
      write_option(p, s - p, &tmp);
978
0
      p = s + 1;
979
0
    }
980
981
0
    s++;
982
0
    length--;
983
0
  }
984
985
  /* write last query element */
986
0
  write_option(p, s - p, &tmp);
987
988
0
  *buflen = *buflen - tmp.buf.length;
989
0
  return tmp.n;
990
0
}
991
992
int
993
coap_query_into_optlist(const uint8_t *s, size_t length, coap_option_num_t optnum,
994
0
                        coap_optlist_t **optlist_chain) {
995
0
  const uint8_t *p = s;
996
0
  coap_optlist_t *optlist;
997
998
0
  while (length > 0 && *s != '#') {
999
0
    if (*s == '&') {                /* start of new query element */
1000
      /* add previous query element */
1001
0
      optlist = coap_new_optlist(optnum, s - p, p);
1002
0
      if (!optlist) {
1003
0
        return 0;
1004
0
      }
1005
0
      coap_replace_percents(optlist);
1006
0
      if (!coap_insert_optlist(optlist_chain, optlist)) {
1007
0
        return 0;
1008
0
      }
1009
0
      p = s + 1;
1010
0
    }
1011
0
    s++;
1012
0
    length--;
1013
0
  }
1014
  /* add last query element */
1015
0
  optlist = coap_new_optlist(optnum, s - p, p);
1016
0
  if (!optlist) {
1017
0
    return 0;
1018
0
  }
1019
0
  coap_replace_percents(optlist);
1020
0
  if (!coap_insert_optlist(optlist_chain, optlist)) {
1021
0
    return 0;
1022
0
  }
1023
0
  return 1;
1024
0
}
1025
1026
0
#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t))
1027
1028
coap_uri_t *
1029
0
coap_new_uri(const uint8_t *uri, unsigned int length) {
1030
0
  uint8_t *result;
1031
0
  coap_uri_t *out_uri;
1032
1033
0
  out_uri = (coap_uri_t *)coap_malloc_type(COAP_STRING, length + 1 + sizeof(coap_uri_t));
1034
1035
0
  if (!out_uri)
1036
0
    return NULL;
1037
1038
0
  result = (uint8_t *)out_uri;
1039
0
  memcpy(URI_DATA(result), uri, length);
1040
0
  URI_DATA(result)[length] = '\0'; /* make it zero-terminated */
1041
1042
0
  if (coap_split_uri(URI_DATA(result), length, out_uri) < 0) {
1043
0
    coap_free_type(COAP_STRING, out_uri);
1044
0
    return NULL;
1045
0
  }
1046
0
  return out_uri;
1047
0
}
1048
1049
coap_uri_t *
1050
0
coap_clone_uri(const coap_uri_t *uri) {
1051
0
  coap_uri_t *result;
1052
0
  uint8_t *p;
1053
1054
0
  if (!uri)
1055
0
    return  NULL;
1056
1057
0
  result = (coap_uri_t *)coap_malloc_type(COAP_STRING,  uri->query.length + uri->host.length +
1058
0
                                          uri->path.length + sizeof(coap_uri_t) + 1);
1059
1060
0
  if (!result)
1061
0
    return NULL;
1062
1063
0
  memset(result, 0, sizeof(coap_uri_t));
1064
1065
0
  result->port = uri->port;
1066
1067
0
  if (uri->host.length) {
1068
0
    result->host.s = p = URI_DATA(result);
1069
0
    result->host.length = uri->host.length;
1070
1071
0
    memcpy(p, uri->host.s, uri->host.length);
1072
0
  }
1073
1074
0
  if (uri->path.length) {
1075
0
    result->path.s = p = URI_DATA(result) + uri->host.length;
1076
0
    result->path.length = uri->path.length;
1077
1078
0
    memcpy(p, uri->path.s, uri->path.length);
1079
0
  }
1080
1081
0
  if (uri->query.length) {
1082
0
    result->query.s = p = URI_DATA(result) + uri->host.length + uri->path.length;
1083
0
    result->query.length = uri->query.length;
1084
1085
0
    memcpy(p, uri->query.s, uri->query.length);
1086
0
  }
1087
1088
0
  return result;
1089
0
}
1090
1091
void
1092
0
coap_delete_uri(coap_uri_t *uri) {
1093
0
  coap_free_type(COAP_STRING, uri);
1094
0
}
1095
1096
static int
1097
3.43k
is_unescaped_in_path(const uint8_t c) {
1098
3.43k
  return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
1099
738
         (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
1100
398
         c == '~' || c == '!' || c == '$' || c == '\'' || c == '(' ||
1101
376
         c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
1102
368
         c=='=' || c==':' || c=='@' || c == '&';
1103
3.43k
}
1104
1105
static int
1106
250
is_unescaped_in_query(const uint8_t c) {
1107
250
  return is_unescaped_in_path(c) || c=='/' || c=='?';
1108
250
}
1109
1110
coap_string_t *
1111
121
coap_get_query(const coap_pdu_t *request) {
1112
121
  coap_opt_iterator_t opt_iter;
1113
121
  coap_opt_filter_t f;
1114
121
  coap_opt_t *q;
1115
121
  coap_string_t *query = NULL;
1116
121
  size_t length = 0;
1117
121
  static const uint8_t hex[] = "0123456789ABCDEF";
1118
1119
121
  coap_option_filter_clear(&f);
1120
121
  coap_option_filter_set(&f, COAP_OPTION_URI_QUERY);
1121
121
  coap_option_iterator_init(request, &opt_iter, &f);
1122
176
  while ((q = coap_option_next(&opt_iter))) {
1123
55
    uint16_t seg_len = coap_opt_length(q), i;
1124
55
    const uint8_t *seg= coap_opt_value(q);
1125
180
    for (i = 0; i < seg_len; i++) {
1126
125
      if (is_unescaped_in_query(seg[i]))
1127
32
        length += 1;
1128
93
      else
1129
93
        length += 3;
1130
125
    }
1131
55
    length += 1;
1132
55
  }
1133
121
  if (length > 0)
1134
55
    length -= 1;
1135
121
  if (length > 0) {
1136
54
    query = coap_new_string(length);
1137
54
    if (query) {
1138
54
      query->length = length;
1139
54
      unsigned char *s = query->s;
1140
54
      coap_option_iterator_init(request, &opt_iter, &f);
1141
108
      while ((q = coap_option_next(&opt_iter))) {
1142
54
        if (s != query->s)
1143
0
          *s++ = '&';
1144
54
        uint16_t seg_len = coap_opt_length(q), i;
1145
54
        const uint8_t *seg= coap_opt_value(q);
1146
179
        for (i = 0; i < seg_len; i++) {
1147
125
          if (is_unescaped_in_query(seg[i])) {
1148
32
            *s++ = seg[i];
1149
93
          } else {
1150
93
            *s++ = '%';
1151
93
            *s++ = hex[seg[i]>>4];
1152
93
            *s++ = hex[seg[i]&0x0F];
1153
93
          }
1154
125
        }
1155
54
      }
1156
54
    }
1157
54
  }
1158
121
  return query;
1159
121
}
1160
1161
const char *
1162
0
coap_map_abbrev_uri_path(coap_upa_chain_t *chain, uint32_t value) {
1163
0
  while (chain) {
1164
0
    coap_upa_chain_t *next = chain->next;
1165
1166
0
    if (chain->upa_value == value) {
1167
0
      return chain->upa_path;
1168
0
    }
1169
0
    chain = next;
1170
0
  }
1171
0
  return NULL;
1172
0
}
1173
1174
int
1175
coap_map_uri_path_abbrev(coap_upa_chain_t *chain, const char *path, size_t length,
1176
0
                         uint32_t *value) {
1177
0
  while (chain) {
1178
0
    coap_upa_chain_t *next = chain->next;
1179
1180
0
    if (strlen(chain->upa_path) == length && memcmp(chain->upa_path, path, length) == 0) {
1181
0
      *value = chain->upa_value;
1182
0
      return 1;
1183
0
    }
1184
0
    chain = next;
1185
0
  }
1186
0
  return 0;
1187
0
}
1188
1189
coap_string_t *
1190
159
coap_get_uri_path(const coap_pdu_t *request) {
1191
159
  coap_opt_iterator_t opt_iter;
1192
159
  coap_opt_filter_t f;
1193
159
  coap_opt_t *q;
1194
159
  coap_string_t *uri_path = NULL;
1195
159
  size_t length = 0;
1196
159
  static const uint8_t hex[] = "0123456789ABCDEF";
1197
1198
159
  q = coap_check_option(request, COAP_OPTION_URI_PATH_ABB, &opt_iter);
1199
159
  if (q) {
1200
0
    uint32_t value;
1201
0
    const char *exp;
1202
0
    if (coap_check_option(request, COAP_OPTION_PROXY_URI, &opt_iter) ||
1203
0
        coap_check_option(request, COAP_OPTION_URI_PATH, &opt_iter)) {
1204
0
      return NULL;
1205
0
    }
1206
0
    value = coap_decode_var_bytes(coap_opt_value(q), coap_opt_length(q));
1207
0
    exp = coap_map_abbrev_uri_path(coap_upa_server_mapping_chain, value);
1208
0
    if (exp) {
1209
0
      uri_path = coap_new_string(strlen(exp));
1210
0
      if (uri_path) {
1211
0
        memcpy(uri_path->s, exp, strlen(exp));
1212
0
      }
1213
0
      return uri_path;
1214
0
    }
1215
0
    return NULL;
1216
0
  }
1217
159
  q = coap_check_option(request, COAP_OPTION_PROXY_URI, &opt_iter);
1218
159
  if (q) {
1219
0
    coap_uri_t uri;
1220
1221
0
    if (coap_split_proxy_uri(coap_opt_value(q),
1222
0
                             coap_opt_length(q), &uri) < 0) {
1223
0
      return NULL;
1224
0
    }
1225
0
    uri_path = coap_new_string(uri.path.length);
1226
0
    if (uri_path && uri.path.length) {
1227
0
      memcpy(uri_path->s, uri.path.s, uri.path.length);
1228
0
    }
1229
0
    return uri_path;
1230
0
  }
1231
1232
159
  coap_option_filter_clear(&f);
1233
159
  coap_option_filter_set(&f, COAP_OPTION_URI_PATH);
1234
159
  coap_option_iterator_init(request, &opt_iter, &f);
1235
394
  while ((q = coap_option_next(&opt_iter))) {
1236
235
    uint16_t seg_len = coap_opt_length(q), i;
1237
235
    const uint8_t *seg = coap_opt_value(q);
1238
1.82k
    for (i = 0; i < seg_len; i++) {
1239
1.59k
      if (is_unescaped_in_path(seg[i]))
1240
1.50k
        length += 1;
1241
86
      else
1242
86
        length += 3;
1243
1.59k
    }
1244
    /* bump for the leading "/" */
1245
235
    length += 1;
1246
235
  }
1247
  /* The first entry does not have a leading "/" */
1248
159
  if (length > 0)
1249
157
    length -= 1;
1250
1251
  /* if 0, either no URI_PATH Option, or the first one was empty */
1252
159
  uri_path = coap_new_string(length);
1253
159
  if (uri_path) {
1254
159
    uri_path->length = length;
1255
159
    unsigned char *s = uri_path->s;
1256
159
    int n = 0;
1257
159
    coap_option_iterator_init(request, &opt_iter, &f);
1258
394
    while ((q = coap_option_next(&opt_iter))) {
1259
235
      if (n++) {
1260
78
        *s++ = '/';
1261
78
      }
1262
235
      uint16_t seg_len = coap_opt_length(q), i;
1263
235
      const uint8_t *seg= coap_opt_value(q);
1264
1.82k
      for (i = 0; i < seg_len; i++) {
1265
1.59k
        if (is_unescaped_in_path(seg[i])) {
1266
1.50k
          *s++ = seg[i];
1267
1.50k
        } else {
1268
86
          *s++ = '%';
1269
86
          *s++ = hex[seg[i]>>4];
1270
86
          *s++ = hex[seg[i]&0x0F];
1271
86
        }
1272
1.59k
      }
1273
235
    }
1274
159
  }
1275
159
  return uri_path;
1276
159
}
1277
1278
void
1279
156
coap_delete_upa_chain(coap_upa_chain_t *chain) {
1280
156
  while (chain) {
1281
0
    coap_upa_chain_t *next = chain->next;
1282
1283
0
    coap_free_type(COAP_STRING, chain);
1284
0
    chain = next;
1285
0
  }
1286
156
}
1287
1288
static coap_upa_chain_t *
1289
0
coap_build_upa_chain(coap_upa_abbrev_t *list, uint32_t count) {
1290
0
  uint32_t i;
1291
0
  coap_upa_chain_t *chain = NULL;
1292
0
  coap_upa_chain_t *next;
1293
1294
0
  for (i = 0; i < count; i++) {
1295
0
    next = coap_malloc_type(COAP_STRING, sizeof(coap_upa_chain_t) + strlen(list[i].upa_path) + 1);
1296
0
    if (next == NULL)
1297
0
      goto cleanup;
1298
1299
0
    next->upa_value = list[i].upa_value;
1300
0
    next->upa_path = (char *)next + sizeof(coap_upa_chain_t);
1301
0
    strcpy(next->upa_path, list[i].upa_path);
1302
0
    next->next = chain;
1303
0
    chain = next;
1304
0
  }
1305
0
  return chain;
1306
1307
0
cleanup:
1308
0
  coap_delete_upa_chain(chain);
1309
0
  return NULL;
1310
0
}
1311
1312
void
1313
0
coap_upa_client_fallback(coap_upa_abbrev_t *list, uint32_t count) {
1314
0
  coap_lock_lock(return);
1315
0
  coap_delete_upa_chain(coap_upa_client_fallback_chain);
1316
0
  coap_upa_client_fallback_chain = coap_build_upa_chain(list, count);
1317
0
  coap_lock_unlock();
1318
0
}
1319
1320
void
1321
0
coap_upa_server_mapping(coap_upa_abbrev_t *list, uint32_t count) {
1322
0
  coap_lock_lock(return);
1323
0
  coap_delete_upa_chain(coap_upa_server_mapping_chain);
1324
0
  coap_upa_server_mapping_chain = coap_build_upa_chain(list, count);
1325
0
  coap_lock_unlock();
1326
0
}