1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
10 #include "alloc-util.h"
11 #include "bus-label.h"
12 #include "hexdecoct.h"
15 char *bus_label_escape(const char *s) {
19 assert_return(s, NULL);
21 /* Escapes all chars that D-Bus' object path cannot deal
22 * with. Can be reversed with bus_path_unescape(). We special
23 * case the empty string. */
28 r = new(char, strlen(s)*3 + 1);
32 for (f = s, t = r; *f; f++) {
34 /* Escape everything that is not a-zA-Z0-9. We also
35 * escape 0-9 if it's the first character */
37 if (!(*f >= 'A' && *f <= 'Z') &&
38 !(*f >= 'a' && *f <= 'z') &&
39 !(f > s && *f >= '0' && *f <= '9')) {
41 *(t++) = hexchar(*f >> 4);
52 char *bus_label_unescape_n(const char *f, size_t l) {
56 assert_return(f, NULL);
58 /* Special case for the empty string */
59 if (l == 1 && *f == '_')
66 for (i = 0, t = r; i < l; ++i) {
71 (a = unhexchar(f[i + 1])) < 0 ||
72 (b = unhexchar(f[i + 2])) < 0) {
73 /* Invalid escape code, let's take it literal then */
76 *(t++) = (char) ((a << 4) | b);