chiark / gitweb /
bus: add new sd_bus_creds object to encapsulate process credentials
[elogind.git] / src / shared / device-nodes.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2008-2011 Kay Sievers
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdint.h>
25 #include <sys/types.h>
26
27 #include "device-nodes.h"
28 #include "utf8.h"
29
30 int whitelisted_char_for_devnode(char c, const char *white) {
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         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 -1;
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                         if (len-j < (size_t)seqlen)
52                                 goto err;
53                         memcpy(&str_enc[j], &str[i], seqlen);
54                         j += seqlen;
55                         i += (seqlen-1);
56                 } else if (str[i] == '\\' || !whitelisted_char_for_devnode(str[i], NULL)) {
57                         if (len-j < 4)
58                                 goto err;
59                         sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
60                         j += 4;
61                 } else {
62                         if (len-j < 1)
63                                 goto err;
64                         str_enc[j] = str[i];
65                         j++;
66                 }
67         }
68         if (len-j < 1)
69                 goto err;
70         str_enc[j] = '\0';
71         return 0;
72 err:
73         return -1;
74 }