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