| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <stdlib.h> |
| 4 |
|
| 5 |
#include "alloc-util.h" |
| 6 |
#include "bus-label.h" |
| 7 |
#include "hexdecoct.h" |
| 8 |
#include "string-util.h" |
| 9 |
|
| 10 |
char* bus_label_escape(const char *s) { |
| 11 |
char *r, *t; |
| 12 |
const char *f; |
| 13 |
|
| 14 |
assert_return(s, NULL); |
| 15 |
|
| 16 |
/* Escapes all chars that D-Bus' object path cannot deal |
| 17 |
* with. Can be reversed with bus_path_unescape(). We special |
| 18 |
* case the empty string. */ |
| 19 |
|
| 20 |
if (*s == 0) |
| 21 |
return strdup("_"); |
| 22 |
|
| 23 |
r = new(char, strlen(s)*3 + 1); |
| 24 |
if (!r) |
| 25 |
return NULL; |
| 26 |
|
| 27 |
for (f = s, t = r; *f; f++) { |
| 28 |
|
| 29 |
/* Escape everything that is not a-zA-Z0-9. We also escape 0-9 if it's the first character */ |
| 30 |
|
| 31 |
if (!ascii_isalpha(*f) && |
| 32 |
!(f > s && ascii_isdigit(*f))) { |
| 33 |
*(t++) = '_'; |
| 34 |
*(t++) = hexchar(*f >> 4); |
| 35 |
*(t++) = hexchar(*f); |
| 36 |
} else |
| 37 |
*(t++) = *f; |
| 38 |
} |
| 39 |
|
| 40 |
*t = 0; |
| 41 |
|
| 42 |
return r; |
| 43 |
} |
| 44 |
|
| 45 |
char* bus_label_unescape_n(const char *f, size_t l) { |
| 46 |
char *r, *t; |
| 47 |
size_t i; |
| 48 |
|
| 49 |
assert_return(f, NULL); |
| 50 |
|
| 51 |
if (l == SIZE_MAX) |
| 52 |
l = strlen(f); |
| 53 |
|
| 54 |
/* Special case for the empty string */ |
| 55 |
if (l == 1 && *f == '_') |
| 56 |
return strdup(""); |
| 57 |
|
| 58 |
r = new(char, l + 1); |
| 59 |
if (!r) |
| 60 |
return NULL; |
| 61 |
|
| 62 |
for (i = 0, t = r; i < l; ++i) { |
| 63 |
if (f[i] == '_') { |
| 64 |
int a, b; |
| 65 |
|
| 66 |
if (l - i < 3 || |
| 67 |
(a = unhexchar(f[i + 1])) < 0 || |
| 68 |
(b = unhexchar(f[i + 2])) < 0) { |
| 69 |
/* Invalid escape code, let's take it literal then */ |
| 70 |
*(t++) = '_'; |
| 71 |
} else { |
| 72 |
*(t++) = (char) ((a << 4) | b); |
| 73 |
i += 2; |
| 74 |
} |
| 75 |
} else |
| 76 |
*(t++) = f[i]; |
| 77 |
} |
| 78 |
|
| 79 |
*t = 0; |
| 80 |
|
| 81 |
return r; |
| 82 |
} |