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