2 * libudev - interface to udev device information
4 * Copyright (C) 2008-2011 Kay Sievers <kay.sievers@vrfy.org>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
25 #include <sys/param.h>
28 #include "libudev-private.h"
31 * SECTION:libudev-util
32 * @short_description: utils
34 * Utilities useful when dealing with devices and device node names.
37 int util_delete_path(struct udev *udev, const char *path)
39 char p[UTIL_PATH_SIZE];
46 util_strscpy(p, sizeof(p), path);
47 pos = strrchr(p, '/');
48 if (pos == p || pos == NULL)
53 pos = strrchr(p, '/');
55 /* don't remove the last one */
56 if ((pos == p) || (pos == NULL))
69 uid_t util_lookup_user(struct udev *udev, const char *user)
75 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
76 char *buf = alloca(buflen);
78 if (strcmp(user, "root") == 0)
80 uid = strtoul(user, &endptr, 10);
81 if (endptr[0] == '\0')
84 errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
87 if (errno == 0 || errno == ENOENT || errno == ESRCH)
88 udev_err(udev, "specified user '%s' unknown\n", user);
90 udev_err(udev, "error resolving user '%s': %m\n", user);
94 gid_t util_lookup_group(struct udev *udev, const char *group)
100 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
103 if (strcmp(group, "root") == 0)
105 gid = strtoul(group, &endptr, 10);
106 if (endptr[0] == '\0')
112 newbuf = realloc(buf, buflen);
116 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
119 } else if (errno == ERANGE) {
122 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
123 udev_err(udev, "specified group '%s' unknown\n", group);
125 udev_err(udev, "error resolving group '%s': %m\n", group);
133 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
134 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
135 char *result, size_t maxsize, int read_value)
137 char temp[UTIL_PATH_SIZE];
140 struct udev_device *dev;
143 if (string[0] != '[')
146 util_strscpy(temp, sizeof(temp), string);
150 sysname = strchr(subsys, '/');
154 sysname = &sysname[1];
156 attr = strchr(sysname, ']');
166 if (read_value && attr == NULL)
169 dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
176 val = udev_device_get_sysattr_value(dev, attr);
178 util_strscpy(result, maxsize, val);
181 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
187 l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
189 util_strpcpyl(&s, l, "/", attr, NULL);
190 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
192 udev_device_unref(dev);
195 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
197 char path[UTIL_PATH_SIZE];
198 char target[UTIL_PATH_SIZE];
202 util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
203 len = readlink(path, target, sizeof(target));
204 if (len <= 0 || len == (ssize_t)sizeof(target))
207 pos = strrchr(target, '/');
211 return util_strscpy(value, size, pos);
214 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
216 char link_target[UTIL_PATH_SIZE];
223 len = readlink(syspath, link_target, sizeof(link_target));
224 if (len <= 0 || len == (ssize_t)sizeof(link_target))
226 link_target[len] = '\0';
228 for (back = 0; startswith(&link_target[back * 3], "../"); back++)
230 for (i = 0; i <= back; i++) {
231 base = strrchr(syspath, '/');
238 util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
242 int util_log_priority(const char *priority)
247 prio = strtol(priority, &endptr, 10);
248 if (endptr[0] == '\0' || isspace(endptr[0]))
250 if (startswith(priority, "err"))
252 if (startswith(priority, "info"))
254 if (startswith(priority, "debug"))
259 size_t util_path_encode(const char *src, char *dest, size_t size)
263 for (i = 0, j = 0; src[i] != '\0'; i++) {
269 memcpy(&dest[j], "\\x2f", 4);
271 } else if (src[i] == '\\') {
276 memcpy(&dest[j], "\\x5c", 4);
291 void util_remove_trailing_chars(char *path, char c)
298 while (len > 0 && path[len-1] == c)
303 * Concatenates strings. In any case, terminates in _all_ cases with '\0'
304 * and moves the @dest pointer forward to the added '\0'. Returns the
305 * remaining size, and 0 if the string was truncated.
307 size_t util_strpcpy(char **dest, size_t size, const char *src)
314 *dest = mempcpy(*dest, src, size-1);
319 *dest = mempcpy(*dest, src, len);
327 /* concatenates list of strings, moves dest forward */
328 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
334 size = util_strpcpy(dest, size, src);
335 src = va_arg(va, char *);
336 } while (src != NULL);
343 size_t util_strscpy(char *dest, size_t size, const char *src)
348 return util_strpcpy(&s, size, src);
351 /* concatenates list of strings */
352 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
360 size = util_strpcpy(&s, size, src);
361 src = va_arg(va, char *);
362 } while (src != NULL);
368 /* count of characters used to encode one unicode char */
369 static int utf8_encoded_expected_len(const char *str)
371 unsigned char c = (unsigned char)str[0];
375 if ((c & 0xe0) == 0xc0)
377 if ((c & 0xf0) == 0xe0)
379 if ((c & 0xf8) == 0xf0)
381 if ((c & 0xfc) == 0xf8)
383 if ((c & 0xfe) == 0xfc)
388 /* decode one unicode char */
389 static int utf8_encoded_to_unichar(const char *str)
395 len = utf8_encoded_expected_len(str);
400 unichar = str[0] & 0x1f;
403 unichar = (int)str[0] & 0x0f;
406 unichar = (int)str[0] & 0x07;
409 unichar = (int)str[0] & 0x03;
412 unichar = (int)str[0] & 0x01;
418 for (i = 1; i < len; i++) {
419 if (((int)str[i] & 0xc0) != 0x80)
422 unichar |= (int)str[i] & 0x3f;
428 /* expected size used to encode one unicode char */
429 static int utf8_unichar_to_encoded_len(int unichar)
435 if (unichar < 0x10000)
437 if (unichar < 0x200000)
439 if (unichar < 0x4000000)
444 /* check if unicode char has a valid numeric range */
445 static int utf8_unichar_valid_range(int unichar)
447 if (unichar > 0x10ffff)
449 if ((unichar & 0xfffff800) == 0xd800)
451 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
453 if ((unichar & 0xffff) == 0xffff)
458 /* validate one encoded unicode char and return its length */
459 static int utf8_encoded_valid_unichar(const char *str)
465 len = utf8_encoded_expected_len(str);
473 /* check if expected encoded chars are available */
474 for (i = 0; i < len; i++)
475 if ((str[i] & 0x80) != 0x80)
478 unichar = utf8_encoded_to_unichar(str);
480 /* check if encoded length matches encoded value */
481 if (utf8_unichar_to_encoded_len(unichar) != len)
484 /* check if value has valid range */
485 if (!utf8_unichar_valid_range(unichar))
491 int util_replace_whitespace(const char *str, char *to, size_t len)
495 /* strip trailing whitespace */
496 len = strnlen(str, len);
497 while (len && isspace(str[len-1]))
500 /* strip leading whitespace */
502 while (isspace(str[i]) && (i < len))
507 /* substitute multiple whitespace with a single '_' */
508 if (isspace(str[i])) {
509 while (isspace(str[i]))
519 static int is_whitelisted(char c, const char *white)
521 if ((c >= '0' && c <= '9') ||
522 (c >= 'A' && c <= 'Z') ||
523 (c >= 'a' && c <= 'z') ||
524 strchr("#+-.:=@_", c) != NULL ||
525 (white != NULL && strchr(white, c) != NULL))
530 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
531 int util_replace_chars(char *str, const char *white)
536 while (str[i] != '\0') {
539 if (is_whitelisted(str[i], white)) {
544 /* accept hex encoding */
545 if (str[i] == '\\' && str[i+1] == 'x') {
550 /* accept valid utf8 */
551 len = utf8_encoded_valid_unichar(&str[i]);
557 /* if space is allowed, replace whitespace with ordinary space */
558 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
565 /* everything else is replaced with '_' */
574 * udev_util_encode_string:
575 * @str: input string to be encoded
576 * @str_enc: output string to store the encoded input string
577 * @len: maximum size of the output string, which may be
578 * four times as long as the input string
580 * Encode all potentially unsafe characters of a string to the
581 * corresponding 2 char hex value prefixed by '\x'.
583 * Returns: 0 if the entire string was copied, non-zero otherwise.
585 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
589 if (str == NULL || str_enc == NULL)
592 for (i = 0, j = 0; str[i] != '\0'; i++) {
595 seqlen = utf8_encoded_valid_unichar(&str[i]);
597 if (len-j < (size_t)seqlen)
599 memcpy(&str_enc[j], &str[i], seqlen);
602 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
605 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
623 * http://sites.google.com/site/murmurhash/
625 * All code is released to the public domain. For business purposes,
626 * Murmurhash is under the MIT license.
629 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
632 * 'm' and 'r' are mixing constants generated offline.
633 * They're not really 'magic', they just happen to work well.
635 const unsigned int m = 0x5bd1e995;
638 /* initialize the hash to a 'random' value */
639 unsigned int h = seed ^ len;
641 /* mix 4 bytes at a time into the hash */
642 const unsigned char * data = (const unsigned char *)key;
645 unsigned int k = *(unsigned int *)data;
657 /* handle the last few bytes of the input array */
668 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
676 unsigned int util_string_hash32(const char *str)
678 return murmur_hash2(str, strlen(str), 0);
681 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
682 uint64_t util_string_bloom64(const char *str)
685 unsigned int hash = util_string_hash32(str);
687 bits |= 1LLU << (hash & 63);
688 bits |= 1LLU << ((hash >> 6) & 63);
689 bits |= 1LLU << ((hash >> 12) & 63);
690 bits |= 1LLU << ((hash >> 18) & 63);
694 #define USEC_PER_SEC 1000000ULL
695 #define NSEC_PER_USEC 1000ULL
696 unsigned long long ts_usec(const struct timespec *ts)
698 return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
699 (unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
702 unsigned long long now_usec(void)
706 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
711 ssize_t print_kmsg(const char *fmt, ...)
719 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
723 len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
726 len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
729 ret = write(fd, text, len);