Coverage Report

Created: 2023-06-07 06:06

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