Coverage Report

Created: 2025-07-18 06:17

/src/open62541/deps/mdnsd/libmdnsd/sdtxt.c
Line
Count
Source
1
#include "sdtxt.h"
2
#include <stdlib.h>
3
#include <string.h>
4
5
static size_t _sd2txt_len(const char *key, char *val)
6
18.5k
{
7
18.5k
  size_t ret = strlen(key);
8
9
18.5k
  if (!*val)
10
4.78k
    return ret;
11
12
13.7k
  ret += strlen(val);
13
13.7k
  ret++;
14
15
13.7k
  return ret;
16
18.5k
}
17
18
static void _sd2txt_count(xht_t *h, char *key, void *val, void *arg)
19
9.26k
{
20
9.26k
  int *count = (int *)arg;
21
22
9.26k
  *count += (int)_sd2txt_len(key, (char *)val) + 1;
23
9.26k
}
24
25
static void _sd2txt_write(xht_t *h, char *key, void *val, void *arg)
26
9.26k
{
27
9.26k
  unsigned char **txtp = (unsigned char **)arg;
28
9.26k
  char *cval = (char *)val;
29
30
  /* Copy in lengths, then strings */
31
9.26k
  **txtp = (unsigned char)_sd2txt_len(key, (char *)val);
32
9.26k
  (*txtp)++;
33
9.26k
  memcpy(*txtp, key, strlen(key));
34
9.26k
  *txtp += strlen(key);
35
9.26k
  if (!*cval)
36
2.39k
    return;
37
38
6.87k
  **txtp = '=';
39
6.87k
  (*txtp)++;
40
6.87k
  memcpy(*txtp, cval, strlen(cval));
41
6.87k
  *txtp += strlen(cval);
42
6.87k
}
43
44
unsigned char *sd2txt(xht_t *h, int *len)
45
611
{
46
611
  unsigned char *buf, *raw;
47
48
611
  *len = 0;
49
50
611
  xht_walk(h, _sd2txt_count, (void *)len);
51
611
  if (!*len) {
52
2
    *len = 1;
53
2
    buf = (unsigned char *)MDNSD_malloc(1);
54
2
    *buf = 0;
55
2
    return buf;
56
2
  }
57
58
609
  raw = buf = (unsigned char *)MDNSD_malloc((size_t)(*len));
59
609
  xht_walk(h, _sd2txt_write, &buf);
60
61
609
  return raw;
62
611
}
63
64
xht_t *txt2sd(const unsigned char *txt, int len)
65
368
{
66
368
  char key[256];
67
368
  xht_t *h = NULL;
68
69
368
  if (txt == 0 || len == 0 || *txt == 0)
70
2
    return NULL;
71
72
366
  h = xht_new(23);
73
74
  /* Loop through data breaking out each block, storing into hashtable */
75
43.2k
  for (; len > 0 && *txt <= len; len -= *txt, txt += *txt + 1) {
76
43.0k
    char* val;
77
43.0k
    if (*txt == 0)
78
23
      break;
79
80
43.0k
    memcpy(key, txt + 1, *txt);
81
43.0k
    key[*txt] = 0;
82
43.0k
    if ((val = strchr(key, '=')) != 0) {
83
12.5k
      *val = 0;
84
12.5k
      val++;
85
12.5k
    }
86
43.0k
    if (val != NULL)
87
12.5k
      xht_store(h, key, (int)strlen(key), val, (int)strlen(val));
88
43.0k
    if (*txt +1 > len)
89
200
        break;
90
43.0k
  }
91
92
366
  return h;
93
368
}