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