]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/device-nodes.c
tree-wide: beautify remaining copyright statements
[thirdparty/systemd.git] / src / basic / device-nodes.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8f6ce71f 2/***
96b2fb93 3 Copyright © 2008-2011 Kay Sievers
8f6ce71f
DR
4***/
5
11c3a366 6#include <errno.h>
8f6ce71f 7#include <stdio.h>
11c3a366 8#include <string.h>
8f6ce71f
DR
9
10#include "device-nodes.h"
11#include "utf8.h"
12
13int whitelisted_char_for_devnode(char c, const char *white) {
f0bc5047 14
8f6ce71f
DR
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;
f0bc5047 21
8f6ce71f
DR
22 return 0;
23}
24
25int encode_devnode_name(const char *str, char *str_enc, size_t len) {
26 size_t i, j;
27
234519ae 28 if (!str || !str_enc)
7e8185ef 29 return -EINVAL;
8f6ce71f
DR
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) {
f0bc5047 36
8f6ce71f 37 if (len-j < (size_t)seqlen)
f0bc5047
LP
38 return -EINVAL;
39
8f6ce71f
DR
40 memcpy(&str_enc[j], &str[i], seqlen);
41 j += seqlen;
42 i += (seqlen-1);
f0bc5047 43
8f6ce71f 44 } else if (str[i] == '\\' || !whitelisted_char_for_devnode(str[i], NULL)) {
f0bc5047 45
8f6ce71f 46 if (len-j < 4)
f0bc5047
LP
47 return -EINVAL;
48
8f6ce71f
DR
49 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
50 j += 4;
f0bc5047 51
8f6ce71f
DR
52 } else {
53 if (len-j < 1)
f0bc5047
LP
54 return -EINVAL;
55
8f6ce71f
DR
56 str_enc[j] = str[i];
57 j++;
58 }
59 }
f0bc5047 60
8f6ce71f 61 if (len-j < 1)
f0bc5047
LP
62 return -EINVAL;
63
8f6ce71f
DR
64 str_enc[j] = '\0';
65 return 0;
8f6ce71f 66}