]>
Commit | Line | Data |
---|---|---|
53e1b683 | 1 | /* SPDX-License-Identifier: LGPL-2.1+ */ |
8f6ce71f DR |
2 | /*** |
3 | This file is part of systemd. | |
4 | ||
036ae95a | 5 | Copyright 2008-2011 Kay Sievers |
8f6ce71f DR |
6 | ***/ |
7 | ||
11c3a366 | 8 | #include <errno.h> |
8f6ce71f | 9 | #include <stdio.h> |
11c3a366 | 10 | #include <string.h> |
8f6ce71f DR |
11 | |
12 | #include "device-nodes.h" | |
13 | #include "utf8.h" | |
14 | ||
15 | int whitelisted_char_for_devnode(char c, const char *white) { | |
f0bc5047 | 16 | |
8f6ce71f DR |
17 | if ((c >= '0' && c <= '9') || |
18 | (c >= 'A' && c <= 'Z') || | |
19 | (c >= 'a' && c <= 'z') || | |
20 | strchr("#+-.:=@_", c) != NULL || | |
21 | (white != NULL && strchr(white, c) != NULL)) | |
22 | return 1; | |
f0bc5047 | 23 | |
8f6ce71f DR |
24 | return 0; |
25 | } | |
26 | ||
27 | int encode_devnode_name(const char *str, char *str_enc, size_t len) { | |
28 | size_t i, j; | |
29 | ||
234519ae | 30 | if (!str || !str_enc) |
7e8185ef | 31 | return -EINVAL; |
8f6ce71f DR |
32 | |
33 | for (i = 0, j = 0; str[i] != '\0'; i++) { | |
34 | int seqlen; | |
35 | ||
36 | seqlen = utf8_encoded_valid_unichar(&str[i]); | |
37 | if (seqlen > 1) { | |
f0bc5047 | 38 | |
8f6ce71f | 39 | if (len-j < (size_t)seqlen) |
f0bc5047 LP |
40 | return -EINVAL; |
41 | ||
8f6ce71f DR |
42 | memcpy(&str_enc[j], &str[i], seqlen); |
43 | j += seqlen; | |
44 | i += (seqlen-1); | |
f0bc5047 | 45 | |
8f6ce71f | 46 | } else if (str[i] == '\\' || !whitelisted_char_for_devnode(str[i], NULL)) { |
f0bc5047 | 47 | |
8f6ce71f | 48 | if (len-j < 4) |
f0bc5047 LP |
49 | return -EINVAL; |
50 | ||
8f6ce71f DR |
51 | sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]); |
52 | j += 4; | |
f0bc5047 | 53 | |
8f6ce71f DR |
54 | } else { |
55 | if (len-j < 1) | |
f0bc5047 LP |
56 | return -EINVAL; |
57 | ||
8f6ce71f DR |
58 | str_enc[j] = str[i]; |
59 | j++; | |
60 | } | |
61 | } | |
f0bc5047 | 62 | |
8f6ce71f | 63 | if (len-j < 1) |
f0bc5047 LP |
64 | return -EINVAL; |
65 | ||
8f6ce71f DR |
66 | str_enc[j] = '\0'; |
67 | return 0; | |
8f6ce71f | 68 | } |