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 size_t util_path_decode(char *s)
295 for (i = 0, j = 0; s[i] != '\0'; j++) {
296 if (memcmp(&s[i], "\\x2f", 4) == 0) {
299 } else if (memcmp(&s[i], "\\x5c", 4) == 0) {
311 void util_remove_trailing_chars(char *path, char c)
318 while (len > 0 && path[len-1] == c)
323 * Concatenates strings. In any case, terminates in _all_ cases with '\0'
324 * and moves the @dest pointer forward to the added '\0'. Returns the
325 * remaining size, and 0 if the string was truncated.
327 size_t util_strpcpy(char **dest, size_t size, const char *src)
334 *dest = mempcpy(*dest, src, size-1);
339 *dest = mempcpy(*dest, src, len);
347 /* concatenates list of strings, moves dest forward */
348 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
354 size = util_strpcpy(dest, size, src);
355 src = va_arg(va, char *);
356 } while (src != NULL);
363 size_t util_strscpy(char *dest, size_t size, const char *src)
368 return util_strpcpy(&s, size, src);
371 /* concatenates list of strings */
372 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
380 size = util_strpcpy(&s, size, src);
381 src = va_arg(va, char *);
382 } while (src != NULL);
388 /* count of characters used to encode one unicode char */
389 static int utf8_encoded_expected_len(const char *str)
391 unsigned char c = (unsigned char)str[0];
395 if ((c & 0xe0) == 0xc0)
397 if ((c & 0xf0) == 0xe0)
399 if ((c & 0xf8) == 0xf0)
401 if ((c & 0xfc) == 0xf8)
403 if ((c & 0xfe) == 0xfc)
408 /* decode one unicode char */
409 static int utf8_encoded_to_unichar(const char *str)
415 len = utf8_encoded_expected_len(str);
420 unichar = str[0] & 0x1f;
423 unichar = (int)str[0] & 0x0f;
426 unichar = (int)str[0] & 0x07;
429 unichar = (int)str[0] & 0x03;
432 unichar = (int)str[0] & 0x01;
438 for (i = 1; i < len; i++) {
439 if (((int)str[i] & 0xc0) != 0x80)
442 unichar |= (int)str[i] & 0x3f;
448 /* expected size used to encode one unicode char */
449 static int utf8_unichar_to_encoded_len(int unichar)
455 if (unichar < 0x10000)
457 if (unichar < 0x200000)
459 if (unichar < 0x4000000)
464 /* check if unicode char has a valid numeric range */
465 static int utf8_unichar_valid_range(int unichar)
467 if (unichar > 0x10ffff)
469 if ((unichar & 0xfffff800) == 0xd800)
471 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
473 if ((unichar & 0xffff) == 0xffff)
478 /* validate one encoded unicode char and return its length */
479 static int utf8_encoded_valid_unichar(const char *str)
485 len = utf8_encoded_expected_len(str);
493 /* check if expected encoded chars are available */
494 for (i = 0; i < len; i++)
495 if ((str[i] & 0x80) != 0x80)
498 unichar = utf8_encoded_to_unichar(str);
500 /* check if encoded length matches encoded value */
501 if (utf8_unichar_to_encoded_len(unichar) != len)
504 /* check if value has valid range */
505 if (!utf8_unichar_valid_range(unichar))
511 int util_replace_whitespace(const char *str, char *to, size_t len)
515 /* strip trailing whitespace */
516 len = strnlen(str, len);
517 while (len && isspace(str[len-1]))
520 /* strip leading whitespace */
522 while (isspace(str[i]) && (i < len))
527 /* substitute multiple whitespace with a single '_' */
528 if (isspace(str[i])) {
529 while (isspace(str[i]))
539 static int is_whitelisted(char c, const char *white)
541 if ((c >= '0' && c <= '9') ||
542 (c >= 'A' && c <= 'Z') ||
543 (c >= 'a' && c <= 'z') ||
544 strchr("#+-.:=@_", c) != NULL ||
545 (white != NULL && strchr(white, c) != NULL))
550 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
551 int util_replace_chars(char *str, const char *white)
556 while (str[i] != '\0') {
559 if (is_whitelisted(str[i], white)) {
564 /* accept hex encoding */
565 if (str[i] == '\\' && str[i+1] == 'x') {
570 /* accept valid utf8 */
571 len = utf8_encoded_valid_unichar(&str[i]);
577 /* if space is allowed, replace whitespace with ordinary space */
578 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
585 /* everything else is replaced with '_' */
594 * udev_util_encode_string:
595 * @str: input string to be encoded
596 * @str_enc: output string to store the encoded input string
597 * @len: maximum size of the output string, which may be
598 * four times as long as the input string
600 * Encode all potentially unsafe characters of a string to the
601 * corresponding 2 char hex value prefixed by '\x'.
603 * Returns: 0 if the entire string was copied, non-zero otherwise.
605 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
609 if (str == NULL || str_enc == NULL)
612 for (i = 0, j = 0; str[i] != '\0'; i++) {
615 seqlen = utf8_encoded_valid_unichar(&str[i]);
617 if (len-j < (size_t)seqlen)
619 memcpy(&str_enc[j], &str[i], seqlen);
622 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
625 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
643 * http://sites.google.com/site/murmurhash/
645 * All code is released to the public domain. For business purposes,
646 * Murmurhash is under the MIT license.
649 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
652 * 'm' and 'r' are mixing constants generated offline.
653 * They're not really 'magic', they just happen to work well.
655 const unsigned int m = 0x5bd1e995;
658 /* initialize the hash to a 'random' value */
659 unsigned int h = seed ^ len;
661 /* mix 4 bytes at a time into the hash */
662 const unsigned char * data = (const unsigned char *)key;
665 unsigned int k = *(unsigned int *)data;
677 /* handle the last few bytes of the input array */
688 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
696 unsigned int util_string_hash32(const char *str)
698 return murmur_hash2(str, strlen(str), 0);
701 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
702 uint64_t util_string_bloom64(const char *str)
705 unsigned int hash = util_string_hash32(str);
707 bits |= 1LLU << (hash & 63);
708 bits |= 1LLU << ((hash >> 6) & 63);
709 bits |= 1LLU << ((hash >> 12) & 63);
710 bits |= 1LLU << ((hash >> 18) & 63);
714 #define USEC_PER_SEC 1000000ULL
715 #define NSEC_PER_USEC 1000ULL
716 unsigned long long ts_usec(const struct timespec *ts)
718 return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
719 (unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
722 unsigned long long now_usec(void)
726 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
731 ssize_t print_kmsg(const char *fmt, ...)
739 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
743 len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
746 len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
749 ret = write(fd, text, len);