]>
Commit | Line | Data |
---|---|---|
db9ecf05 | 1 | /* SPDX-License-Identifier: LGPL-2.1-or-later */ |
8f6ce71f | 2 | |
8f6ce71f | 3 | #include <stdio.h> |
11c3a366 | 4 | #include <string.h> |
2d5c53fc | 5 | #include <sys/stat.h> |
8f6ce71f DR |
6 | |
7 | #include "device-nodes.h" | |
2d5c53fc | 8 | #include "path-util.h" |
ff25d338 | 9 | #include "string-util.h" |
8f6ce71f DR |
10 | #include "utf8.h" |
11 | ||
8352a29b | 12 | int allow_listed_char_for_devnode(char c, const char *additional) { |
c68ede39 | 13 | return |
ff25d338 LP |
14 | ascii_isdigit(c) || |
15 | ascii_isalpha(c) || | |
c68ede39 | 16 | strchr("#+-.:=@_", c) || |
8352a29b | 17 | (additional && strchr(additional, c)); |
8f6ce71f DR |
18 | } |
19 | ||
20 | int encode_devnode_name(const char *str, char *str_enc, size_t len) { | |
21 | size_t i, j; | |
22 | ||
234519ae | 23 | if (!str || !str_enc) |
7e8185ef | 24 | return -EINVAL; |
8f6ce71f DR |
25 | |
26 | for (i = 0, j = 0; str[i] != '\0'; i++) { | |
27 | int seqlen; | |
28 | ||
f5fbe71d | 29 | seqlen = utf8_encoded_valid_unichar(str + i, SIZE_MAX); |
8f6ce71f | 30 | if (seqlen > 1) { |
f0bc5047 | 31 | |
c68ede39 | 32 | if (len-j < (size_t) seqlen) |
f0bc5047 LP |
33 | return -EINVAL; |
34 | ||
8f6ce71f DR |
35 | memcpy(&str_enc[j], &str[i], seqlen); |
36 | j += seqlen; | |
37 | i += (seqlen-1); | |
f0bc5047 | 38 | |
6b000af4 | 39 | } else if (str[i] == '\\' || !allow_listed_char_for_devnode(str[i], NULL)) { |
f0bc5047 | 40 | |
8f6ce71f | 41 | if (len-j < 4) |
f0bc5047 LP |
42 | return -EINVAL; |
43 | ||
8f6ce71f DR |
44 | sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]); |
45 | j += 4; | |
f0bc5047 | 46 | |
8f6ce71f DR |
47 | } else { |
48 | if (len-j < 1) | |
f0bc5047 LP |
49 | return -EINVAL; |
50 | ||
8f6ce71f DR |
51 | str_enc[j] = str[i]; |
52 | j++; | |
53 | } | |
54 | } | |
f0bc5047 | 55 | |
8f6ce71f | 56 | if (len-j < 1) |
f0bc5047 LP |
57 | return -EINVAL; |
58 | ||
8f6ce71f DR |
59 | str_enc[j] = '\0'; |
60 | return 0; | |
8f6ce71f | 61 | } |
2d5c53fc MY |
62 | |
63 | int devnode_same(const char *a, const char *b) { | |
64 | struct stat sa, sb; | |
65 | ||
66 | assert(a); | |
67 | assert(b); | |
68 | ||
69 | if (!valid_device_node_path(a) || !valid_device_node_path(b)) | |
70 | return -EINVAL; | |
71 | ||
72 | if (stat(a, &sa) < 0) | |
73 | return -errno; | |
74 | if (stat(b, &sb) < 0) | |
75 | return -errno; | |
76 | ||
77 | if (!S_ISBLK(sa.st_mode) && !S_ISCHR(sa.st_mode)) | |
78 | return -ENODEV; | |
79 | if (!S_ISBLK(sb.st_mode) && !S_ISCHR(sb.st_mode)) | |
80 | return -ENODEV; | |
81 | ||
82 | if (((sa.st_mode ^ sb.st_mode) & S_IFMT) != 0) /* both inode same device node type? */ | |
83 | return false; | |
84 | ||
85 | return sa.st_rdev == sb.st_rdev; | |
86 | } |