Debian Codegraph @

src/util/systemd.c

raw
1 /*
2 * Systemd Utilities
3 */
4
5 #include <c-stdaux.h>
6 #include <stdlib.h>
7 #include "util/error.h"
8 #include "util/systemd.h"
9
10 static bool needs_escape(char c) {
11 return !strchr("0123456789"
12 "abcdefghijklmnopqrstuvwxyz"
13 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
14 ":_.", c);
15 }
16
17 static char *escape_char(char *t, char c) {
18 // Include terminating NUL to silence warnings about truncated strings.
19 static const char table[17] = "0123456789abcdef";
20
21 *t++ = '\\';
22 *t++ = 'x';
23 *t++ = table[(c >> 4) & 0x0f];
24 *t++ = table[c & 0x0f];
25
26 return t;
27 }
28
29 /**
30 * systemd_escape_unit() - escape unit name
31 * @escapedp: output argument for escaped unit name
32 * @unescaped: unescaped unit name to operate with
33 *
34 * This escapes the specified systemd unit name and returns it in the specified
35 * output pointer.
36 *
37 * Return: 0 on success, negative error code on failure.
38 */
39 int systemd_escape_unit(char **escapedp, const char *unescaped) {
40 char *buffer, *dst;
41 const char *src;
42
43 buffer = malloc(strlen(unescaped) * 4 + 1);
44 if (!buffer)
45 return error_origin(-ENOMEM);
46
47 src = unescaped;
48 dst = buffer;
49
50 if (*src == '.')
51 dst = escape_char(dst, *src++);
52
53 for ( ; *src; ++src) {
54 if (*src == '/')
55 *dst++ = '-';
56 else if (needs_escape(*src))
57 dst = escape_char(dst, *src);
58 else
59 *dst++ = *src;
60 }
61
62 *dst = 0;
63 *escapedp = buffer;
64 return 0;
65 }