]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/device-nodes.c
tree-wide: use UINT64_MAX or friends
[thirdparty/systemd.git] / src / basic / device-nodes.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <string.h>
6
7 #include "device-nodes.h"
8 #include "utf8.h"
9
10 int allow_listed_char_for_devnode(char c, const char *white) {
11
12 if ((c >= '0' && c <= '9') ||
13 (c >= 'A' && c <= 'Z') ||
14 (c >= 'a' && c <= 'z') ||
15 strchr("#+-.:=@_", c) != NULL ||
16 (white != NULL && strchr(white, c) != NULL))
17 return 1;
18
19 return 0;
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 < 4)
44 return -EINVAL;
45
46 sprintf(&str_enc[j], "\\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 }