chiark / gitweb /
c940e06f71952b3a66cc468dc4c42700751612ce
[elogind.git] / src / libudev / libudev-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
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 <stdio.h>
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <dirent.h>
27 #include <ctype.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #include <sys/stat.h>
33 #include <sys/param.h>
34
35 #include "device-nodes.h"
36 #include "libudev.h"
37 #include "libudev-private.h"
38 #include "utf8.h"
39 #include "MurmurHash2.h"
40
41 /**
42  * SECTION:libudev-util
43  * @short_description: utils
44  *
45  * Utilities useful when dealing with devices and device node names.
46  */
47
48 int util_delete_path(struct udev *udev, const char *path)
49 {
50         char p[UTIL_PATH_SIZE];
51         char *pos;
52         int err = 0;
53
54         if (path[0] == '/')
55                 while(path[1] == '/')
56                         path++;
57         strscpy(p, sizeof(p), path);
58         pos = strrchr(p, '/');
59         if (pos == p || pos == NULL)
60                 return 0;
61
62         for (;;) {
63                 *pos = '\0';
64                 pos = strrchr(p, '/');
65
66                 /* don't remove the last one */
67                 if ((pos == p) || (pos == NULL))
68                         break;
69
70                 err = rmdir(p);
71                 if (err < 0) {
72                         if (errno == ENOENT)
73                                 err = 0;
74                         break;
75                 }
76         }
77         return err;
78 }
79
80 uid_t util_lookup_user(struct udev *udev, const char *user)
81 {
82         char *endptr;
83         struct passwd pwbuf;
84         struct passwd *pw;
85         uid_t uid;
86         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
87         char *buf = alloca(buflen);
88
89         if (streq(user, "root"))
90                 return 0;
91         uid = strtoul(user, &endptr, 10);
92         if (endptr[0] == '\0')
93                 return uid;
94
95         errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
96         if (pw != NULL)
97                 return pw->pw_uid;
98         if (errno == 0 || errno == ENOENT || errno == ESRCH)
99                 udev_err(udev, "specified user '%s' unknown\n", user);
100         else
101                 udev_err(udev, "error resolving user '%s': %m\n", user);
102         return 0;
103 }
104
105 gid_t util_lookup_group(struct udev *udev, const char *group)
106 {
107         char *endptr;
108         struct group grbuf;
109         struct group *gr;
110         gid_t gid = 0;
111         size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
112         char *buf = NULL;
113
114         if (streq(group, "root"))
115                 return 0;
116         gid = strtoul(group, &endptr, 10);
117         if (endptr[0] == '\0')
118                 return gid;
119         gid = 0;
120         for (;;) {
121                 char *newbuf;
122
123                 newbuf = realloc(buf, buflen);
124                 if (!newbuf)
125                         break;
126                 buf = newbuf;
127                 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
128                 if (gr != NULL) {
129                         gid = gr->gr_gid;
130                 } else if (errno == ERANGE) {
131                         buflen *= 2;
132                         continue;
133                 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
134                         udev_err(udev, "specified group '%s' unknown\n", group);
135                 } else {
136                         udev_err(udev, "error resolving group '%s': %m\n", group);
137                 }
138                 break;
139         }
140         free(buf);
141         return gid;
142 }
143
144 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
145 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
146                                char *result, size_t maxsize, int read_value)
147 {
148         char temp[UTIL_PATH_SIZE];
149         char *subsys;
150         char *sysname;
151         struct udev_device *dev;
152         char *attr;
153
154         if (string[0] != '[')
155                 return -1;
156
157         strscpy(temp, sizeof(temp), string);
158
159         subsys = &temp[1];
160
161         sysname = strchr(subsys, '/');
162         if (sysname == NULL)
163                 return -1;
164         sysname[0] = '\0';
165         sysname = &sysname[1];
166
167         attr = strchr(sysname, ']');
168         if (attr == NULL)
169                 return -1;
170         attr[0] = '\0';
171         attr = &attr[1];
172         if (attr[0] == '/')
173                 attr = &attr[1];
174         if (attr[0] == '\0')
175                 attr = NULL;
176
177         if (read_value && attr == NULL)
178                 return -1;
179
180         dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
181         if (dev == NULL)
182                 return -1;
183
184         if (read_value) {
185                 const char *val;
186
187                 val = udev_device_get_sysattr_value(dev, attr);
188                 if (val != NULL)
189                         strscpy(result, maxsize, val);
190                 else
191                         result[0] = '\0';
192                 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
193         } else {
194                 size_t l;
195                 char *s;
196
197                 s = result;
198                 l = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
199                 if (attr != NULL)
200                         strpcpyl(&s, l, "/", attr, NULL);
201                 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
202         }
203         udev_device_unref(dev);
204         return 0;
205 }
206 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
207 {
208         char path[UTIL_PATH_SIZE];
209         char target[UTIL_PATH_SIZE];
210         ssize_t len;
211         const char *pos;
212
213         strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
214         len = readlink(path, target, sizeof(target));
215         if (len <= 0 || len == (ssize_t)sizeof(target))
216                 return -1;
217         target[len] = '\0';
218         pos = strrchr(target, '/');
219         if (pos == NULL)
220                 return -1;
221         pos = &pos[1];
222         return strscpy(value, size, pos);
223 }
224
225 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
226 {
227         char link_target[UTIL_PATH_SIZE];
228
229         ssize_t len;
230         int i;
231         int back;
232         char *base = NULL;
233
234         len = readlink(syspath, link_target, sizeof(link_target));
235         if (len <= 0 || len == (ssize_t)sizeof(link_target))
236                 return -1;
237         link_target[len] = '\0';
238
239         for (back = 0; startswith(&link_target[back * 3], "../"); back++)
240                 ;
241         for (i = 0; i <= back; i++) {
242                 base = strrchr(syspath, '/');
243                 if (base == NULL)
244                         return -EINVAL;
245                 base[0] = '\0';
246         }
247
248         strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
249         return 0;
250 }
251
252 int util_log_priority(const char *priority)
253 {
254         char *endptr;
255         int prio;
256
257         prio = strtol(priority, &endptr, 10);
258         if (endptr[0] == '\0' || isspace(endptr[0]))
259                 return prio;
260         if (startswith(priority, "err"))
261                 return LOG_ERR;
262         if (startswith(priority, "info"))
263                 return LOG_INFO;
264         if (startswith(priority, "debug"))
265                 return LOG_DEBUG;
266         return 0;
267 }
268
269 size_t util_path_encode(const char *src, char *dest, size_t size)
270 {
271         size_t i, j;
272
273         for (i = 0, j = 0; src[i] != '\0'; i++) {
274                 if (src[i] == '/') {
275                         if (j+4 >= size) {
276                                 j = 0;
277                                 break;
278                         }
279                         memcpy(&dest[j], "\\x2f", 4);
280                         j += 4;
281                 } else if (src[i] == '\\') {
282                         if (j+4 >= size) {
283                                 j = 0;
284                                 break;
285                         }
286                         memcpy(&dest[j], "\\x5c", 4);
287                         j += 4;
288                 } else {
289                         if (j+1 >= size) {
290                                 j = 0;
291                                 break;
292                         }
293                         dest[j] = src[i];
294                         j++;
295                 }
296         }
297         dest[j] = '\0';
298         return j;
299 }
300
301 void util_remove_trailing_chars(char *path, char c)
302 {
303         size_t len;
304
305         if (path == NULL)
306                 return;
307         len = strlen(path);
308         while (len > 0 && path[len-1] == c)
309                 path[--len] = '\0';
310 }
311
312 int util_replace_whitespace(const char *str, char *to, size_t len)
313 {
314         size_t i, j;
315
316         /* strip trailing whitespace */
317         len = strnlen(str, len);
318         while (len && isspace(str[len-1]))
319                 len--;
320
321         /* strip leading whitespace */
322         i = 0;
323         while (isspace(str[i]) && (i < len))
324                 i++;
325
326         j = 0;
327         while (i < len) {
328                 /* substitute multiple whitespace with a single '_' */
329                 if (isspace(str[i])) {
330                         while (isspace(str[i]))
331                                 i++;
332                         to[j++] = '_';
333                 }
334                 to[j++] = str[i++];
335         }
336         to[j] = '\0';
337         return 0;
338 }
339
340 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
341 int util_replace_chars(char *str, const char *white)
342 {
343         size_t i = 0;
344         int replaced = 0;
345
346         while (str[i] != '\0') {
347                 int len;
348
349                 if (whitelisted_char_for_devnode(str[i], white)) {
350                         i++;
351                         continue;
352                 }
353
354                 /* accept hex encoding */
355                 if (str[i] == '\\' && str[i+1] == 'x') {
356                         i += 2;
357                         continue;
358                 }
359
360                 /* accept valid utf8 */
361                 len = utf8_encoded_valid_unichar(&str[i]);
362                 if (len > 1) {
363                         i += len;
364                         continue;
365                 }
366
367                 /* if space is allowed, replace whitespace with ordinary space */
368                 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
369                         str[i] = ' ';
370                         i++;
371                         replaced++;
372                         continue;
373                 }
374
375                 /* everything else is replaced with '_' */
376                 str[i] = '_';
377                 i++;
378                 replaced++;
379         }
380         return replaced;
381 }
382
383 /**
384  * udev_util_encode_string:
385  * @str: input string to be encoded
386  * @str_enc: output string to store the encoded input string
387  * @len: maximum size of the output string, which may be
388  *       four times as long as the input string
389  *
390  * Encode all potentially unsafe characters of a string to the
391  * corresponding 2 char hex value prefixed by '\x'.
392  *
393  * Returns: 0 if the entire string was copied, non-zero otherwise.
394  **/
395 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
396 {
397         return encode_devnode_name(str, str_enc, len);
398 }
399
400 unsigned int util_string_hash32(const char *str)
401 {
402         return MurmurHash2(str, strlen(str), 0);
403 }
404
405 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
406 uint64_t util_string_bloom64(const char *str)
407 {
408         uint64_t bits = 0;
409         unsigned int hash = util_string_hash32(str);
410
411         bits |= 1LLU << (hash & 63);
412         bits |= 1LLU << ((hash >> 6) & 63);
413         bits |= 1LLU << ((hash >> 12) & 63);
414         bits |= 1LLU << ((hash >> 18) & 63);
415         return bits;
416 }
417
418 ssize_t print_kmsg(const char *fmt, ...)
419 {
420         int fd;
421         va_list ap;
422         char text[1024];
423         ssize_t len;
424         ssize_t ret;
425
426         fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
427         if (fd < 0)
428                 return -errno;
429
430         len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
431
432         va_start(ap, fmt);
433         len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
434         va_end(ap);
435
436         ret = write(fd, text, len);
437         if (ret < 0)
438                 ret = -errno;
439         close(fd);
440         return ret;
441 }