]>
Commit | Line | Data |
---|---|---|
f01de965 KS |
1 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ |
2 | ||
3 | /*** | |
4 | This file is part of systemd. | |
5 | ||
6 | Copyright 2013 Lennart Poettering | |
7 | ||
8 | systemd is free software; you can redistribute it and/or modify it | |
9 | under the terms of the GNU Lesser General Public License as published by | |
10 | the Free Software Foundation; either version 2.1 of the License, or | |
11 | (at your option) any later version. | |
12 | ||
13 | systemd is distributed in the hope that it will be useful, but | |
14 | WITHOUT ANY WARRANTY; without even the implied warranty of | |
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
16 | Lesser General Public License for more details. | |
17 | ||
18 | You should have received a copy of the GNU Lesser General Public License | |
19 | along with systemd; If not, see <http://www.gnu.org/licenses/>. | |
20 | ***/ | |
21 | ||
22 | #include <assert.h> | |
23 | #include <stdlib.h> | |
24 | #include <unistd.h> | |
25 | ||
26 | #include "util.h" | |
27 | #include "macro.h" | |
28 | #include "def.h" | |
29 | ||
30 | #include "bus-label.h" | |
31 | ||
32 | char *bus_label_escape(const char *s) { | |
33 | char *r, *t; | |
34 | const char *f; | |
35 | ||
36 | assert_return(s, NULL); | |
37 | ||
38 | /* Escapes all chars that D-Bus' object path cannot deal | |
39 | * with. Can be reversed with bus_path_unescape(). We special | |
40 | * case the empty string. */ | |
41 | ||
42 | if (*s == 0) | |
43 | return strdup("_"); | |
44 | ||
45 | r = new(char, strlen(s)*3 + 1); | |
46 | if (!r) | |
47 | return NULL; | |
48 | ||
49 | for (f = s, t = r; *f; f++) { | |
50 | ||
51 | /* Escape everything that is not a-zA-Z0-9. We also | |
52 | * escape 0-9 if it's the first character */ | |
53 | ||
54 | if (!(*f >= 'A' && *f <= 'Z') && | |
55 | !(*f >= 'a' && *f <= 'z') && | |
56 | !(f > s && *f >= '0' && *f <= '9')) { | |
57 | *(t++) = '_'; | |
58 | *(t++) = hexchar(*f >> 4); | |
59 | *(t++) = hexchar(*f); | |
60 | } else | |
61 | *(t++) = *f; | |
62 | } | |
63 | ||
64 | *t = 0; | |
65 | ||
66 | return r; | |
67 | } | |
68 | ||
69 | char *bus_label_unescape(const char *f) { | |
70 | char *r, *t; | |
71 | ||
72 | assert_return(f, NULL); | |
73 | ||
74 | /* Special case for the empty string */ | |
75 | if (streq(f, "_")) | |
76 | return strdup(""); | |
77 | ||
78 | r = new(char, strlen(f) + 1); | |
79 | if (!r) | |
80 | return NULL; | |
81 | ||
82 | for (t = r; *f; f++) { | |
83 | ||
84 | if (*f == '_') { | |
85 | int a, b; | |
86 | ||
87 | if ((a = unhexchar(f[1])) < 0 || | |
88 | (b = unhexchar(f[2])) < 0) { | |
89 | /* Invalid escape code, let's take it literal then */ | |
90 | *(t++) = '_'; | |
91 | } else { | |
92 | *(t++) = (char) ((a << 4) | b); | |
93 | f += 2; | |
94 | } | |
95 | } else | |
96 | *(t++) = *f; | |
97 | } | |
98 | ||
99 | *t = 0; | |
100 | ||
101 | return r; | |
102 | } |