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