]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/device-nodes.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / basic / device-nodes.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2008-2011 Kay Sievers
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <errno.h>
22 #include <stdio.h>
23 #include <string.h>
24
25 #include "device-nodes.h"
26 #include "utf8.h"
27
28 int whitelisted_char_for_devnode(char c, const char *white) {
29
30 if ((c >= '0' && c <= '9') ||
31 (c >= 'A' && c <= 'Z') ||
32 (c >= 'a' && c <= 'z') ||
33 strchr("#+-.:=@_", c) != NULL ||
34 (white != NULL && strchr(white, c) != NULL))
35 return 1;
36
37 return 0;
38 }
39
40 int encode_devnode_name(const char *str, char *str_enc, size_t len) {
41 size_t i, j;
42
43 if (str == NULL || str_enc == NULL)
44 return -EINVAL;
45
46 for (i = 0, j = 0; str[i] != '\0'; i++) {
47 int seqlen;
48
49 seqlen = utf8_encoded_valid_unichar(&str[i]);
50 if (seqlen > 1) {
51
52 if (len-j < (size_t)seqlen)
53 return -EINVAL;
54
55 memcpy(&str_enc[j], &str[i], seqlen);
56 j += seqlen;
57 i += (seqlen-1);
58
59 } else if (str[i] == '\\' || !whitelisted_char_for_devnode(str[i], NULL)) {
60
61 if (len-j < 4)
62 return -EINVAL;
63
64 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
65 j += 4;
66
67 } else {
68 if (len-j < 1)
69 return -EINVAL;
70
71 str_enc[j] = str[i];
72 j++;
73 }
74 }
75
76 if (len-j < 1)
77 return -EINVAL;
78
79 str_enc[j] = '\0';
80 return 0;
81 }