Debian Codegraph @

src/basic/device-nodes.c

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