Coverage Report

Created: 2025-08-29 06:10

/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
20.4k
{
7
20.4k
  size_t ret = strlen(key);
8
9
20.4k
  if (!*val)
10
5.43k
    return ret;
11
12
15.0k
  ret += strlen(val);
13
15.0k
  ret++;
14
15
15.0k
  return ret;
16
20.4k
}
17
18
static void _sd2txt_count(xht_t *h, char *key, void *val, void *arg)
19
10.2k
{
20
10.2k
  int *count = (int *)arg;
21
22
10.2k
  *count += (int)_sd2txt_len(key, (char *)val) + 1;
23
10.2k
}
24
25
static void _sd2txt_write(xht_t *h, char *key, void *val, void *arg)
26
10.2k
{
27
10.2k
  unsigned char **txtp = (unsigned char **)arg;
28
10.2k
  char *cval = (char *)val;
29
30
  /* Copy in lengths, then strings */
31
10.2k
  **txtp = (unsigned char)_sd2txt_len(key, (char *)val);
32
10.2k
  (*txtp)++;
33
10.2k
  memcpy(*txtp, key, strlen(key));
34
10.2k
  *txtp += strlen(key);
35
10.2k
  if (!*cval)
36
2.71k
    return;
37
38
7.51k
  **txtp = '=';
39
7.51k
  (*txtp)++;
40
7.51k
  memcpy(*txtp, cval, strlen(cval));
41
7.51k
  *txtp += strlen(cval);
42
7.51k
}
43
44
unsigned char *sd2txt(xht_t *h, int *len)
45
610
{
46
610
  unsigned char *buf, *raw;
47
48
610
  *len = 0;
49
50
610
  xht_walk(h, _sd2txt_count, (void *)len);
51
610
  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
608
  raw = buf = (unsigned char *)MDNSD_malloc((size_t)(*len));
59
608
  xht_walk(h, _sd2txt_write, &buf);
60
61
608
  return raw;
62
610
}
63
64
xht_t *txt2sd(const unsigned char *txt, int len)
65
357
{
66
357
  char key[256];
67
357
  xht_t *h = NULL;
68
69
357
  if (txt == 0 || len == 0 || *txt == 0)
70
2
    return NULL;
71
72
355
  h = xht_new(23);
73
74
  /* Loop through data breaking out each block, storing into hashtable */
75
43.4k
  for (; len > 0 && *txt <= len; len -= *txt, txt += *txt + 1) {
76
43.3k
    char* val;
77
43.3k
    if (*txt == 0)
78
16
      break;
79
80
43.3k
    memcpy(key, txt + 1, *txt);
81
43.3k
    key[*txt] = 0;
82
43.3k
    if ((val = strchr(key, '=')) != 0) {
83
14.5k
      *val = 0;
84
14.5k
      val++;
85
14.5k
    }
86
43.3k
    if (val != NULL)
87
14.5k
      xht_store(h, key, (int)strlen(key), val, (int)strlen(val));
88
43.3k
    if (*txt +1 > len)
89
209
        break;
90
43.3k
  }
91
92
355
  return h;
93
357
}