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
35 int util_delete_path(struct udev *udev, const char *path)
37 char p[UTIL_PATH_SIZE];
44 util_strscpy(p, sizeof(p), path);
45 pos = strrchr(p, '/');
46 if (pos == p || pos == NULL)
51 pos = strrchr(p, '/');
53 /* don't remove the last one */
54 if ((pos == p) || (pos == NULL))
67 uid_t util_lookup_user(struct udev *udev, const char *user)
73 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
74 char *buf = alloca(buflen);
76 if (strcmp(user, "root") == 0)
78 uid = strtoul(user, &endptr, 10);
79 if (endptr[0] == '\0')
82 errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
85 if (errno == 0 || errno == ENOENT || errno == ESRCH)
86 err(udev, "specified user '%s' unknown\n", user);
88 err(udev, "error resolving user '%s': %m\n", user);
92 gid_t util_lookup_group(struct udev *udev, const char *group)
98 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
101 if (strcmp(group, "root") == 0)
103 gid = strtoul(group, &endptr, 10);
104 if (endptr[0] == '\0')
110 newbuf = realloc(buf, buflen);
114 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
117 } else if (errno == ERANGE) {
120 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
121 err(udev, "specified group '%s' unknown\n", group);
123 err(udev, "error resolving group '%s': %m\n", group);
131 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
132 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
133 char *result, size_t maxsize, int read_value)
135 char temp[UTIL_PATH_SIZE];
138 struct udev_device *dev;
141 if (string[0] != '[')
144 util_strscpy(temp, sizeof(temp), string);
148 sysname = strchr(subsys, '/');
152 sysname = &sysname[1];
154 attr = strchr(sysname, ']');
164 if (read_value && attr == NULL)
167 dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
174 val = udev_device_get_sysattr_value(dev, attr);
176 util_strscpy(result, maxsize, val);
179 dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
185 l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
187 util_strpcpyl(&s, l, "/", attr, NULL);
188 dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
190 udev_device_unref(dev);
193 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
195 char path[UTIL_PATH_SIZE];
196 char target[UTIL_PATH_SIZE];
200 util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
201 len = readlink(path, target, sizeof(target));
202 if (len <= 0 || len == (ssize_t)sizeof(target))
205 pos = strrchr(target, '/');
209 return util_strscpy(value, size, pos);
212 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
214 char link_target[UTIL_PATH_SIZE];
221 len = readlink(syspath, link_target, sizeof(link_target));
222 if (len <= 0 || len == (ssize_t)sizeof(link_target))
224 link_target[len] = '\0';
226 for (back = 0; startswith(&link_target[back * 3], "../"); back++)
228 for (i = 0; i <= back; i++) {
229 base = strrchr(syspath, '/');
236 util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
240 int util_log_priority(const char *priority)
245 prio = strtol(priority, &endptr, 10);
246 if (endptr[0] == '\0' || isspace(endptr[0]))
248 if (startswith(priority, "err"))
250 if (startswith(priority, "info"))
252 if (startswith(priority, "debug"))
257 size_t util_path_encode(const char *src, char *dest, size_t size)
261 for (i = 0, j = 0; src[i] != '\0'; i++) {
267 memcpy(&dest[j], "\\x2f", 4);
269 } else if (src[i] == '\\') {
274 memcpy(&dest[j], "\\x5c", 4);
289 size_t util_path_decode(char *s)
293 for (i = 0, j = 0; s[i] != '\0'; j++) {
294 if (memcmp(&s[i], "\\x2f", 4) == 0) {
297 } else if (memcmp(&s[i], "\\x5c", 4) == 0) {
309 void util_remove_trailing_chars(char *path, char c)
316 while (len > 0 && path[len-1] == c)
321 * Concatenates strings. In any case, terminates in _all_ cases with '\0'
322 * and moves the @dest pointer forward to the added '\0'. Returns the
323 * remaining size, and 0 if the string was truncated.
325 size_t util_strpcpy(char **dest, size_t size, const char *src)
332 *dest = mempcpy(*dest, src, size-1);
337 *dest = mempcpy(*dest, src, len);
345 /* concatenates list of strings, moves dest forward */
346 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
352 size = util_strpcpy(dest, size, src);
353 src = va_arg(va, char *);
354 } while (src != NULL);
361 size_t util_strscpy(char *dest, size_t size, const char *src)
366 return util_strpcpy(&s, size, src);
369 /* concatenates list of strings */
370 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
378 size = util_strpcpy(&s, size, src);
379 src = va_arg(va, char *);
380 } while (src != NULL);
386 /* count of characters used to encode one unicode char */
387 static int utf8_encoded_expected_len(const char *str)
389 unsigned char c = (unsigned char)str[0];
393 if ((c & 0xe0) == 0xc0)
395 if ((c & 0xf0) == 0xe0)
397 if ((c & 0xf8) == 0xf0)
399 if ((c & 0xfc) == 0xf8)
401 if ((c & 0xfe) == 0xfc)
406 /* decode one unicode char */
407 static int utf8_encoded_to_unichar(const char *str)
413 len = utf8_encoded_expected_len(str);
418 unichar = str[0] & 0x1f;
421 unichar = (int)str[0] & 0x0f;
424 unichar = (int)str[0] & 0x07;
427 unichar = (int)str[0] & 0x03;
430 unichar = (int)str[0] & 0x01;
436 for (i = 1; i < len; i++) {
437 if (((int)str[i] & 0xc0) != 0x80)
440 unichar |= (int)str[i] & 0x3f;
446 /* expected size used to encode one unicode char */
447 static int utf8_unichar_to_encoded_len(int unichar)
453 if (unichar < 0x10000)
455 if (unichar < 0x200000)
457 if (unichar < 0x4000000)
462 /* check if unicode char has a valid numeric range */
463 static int utf8_unichar_valid_range(int unichar)
465 if (unichar > 0x10ffff)
467 if ((unichar & 0xfffff800) == 0xd800)
469 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
471 if ((unichar & 0xffff) == 0xffff)
476 /* validate one encoded unicode char and return its length */
477 static int utf8_encoded_valid_unichar(const char *str)
483 len = utf8_encoded_expected_len(str);
491 /* check if expected encoded chars are available */
492 for (i = 0; i < len; i++)
493 if ((str[i] & 0x80) != 0x80)
496 unichar = utf8_encoded_to_unichar(str);
498 /* check if encoded length matches encoded value */
499 if (utf8_unichar_to_encoded_len(unichar) != len)
502 /* check if value has valid range */
503 if (!utf8_unichar_valid_range(unichar))
509 int util_replace_whitespace(const char *str, char *to, size_t len)
513 /* strip trailing whitespace */
514 len = strnlen(str, len);
515 while (len && isspace(str[len-1]))
518 /* strip leading whitespace */
520 while (isspace(str[i]) && (i < len))
525 /* substitute multiple whitespace with a single '_' */
526 if (isspace(str[i])) {
527 while (isspace(str[i]))
537 static int is_whitelisted(char c, const char *white)
539 if ((c >= '0' && c <= '9') ||
540 (c >= 'A' && c <= 'Z') ||
541 (c >= 'a' && c <= 'z') ||
542 strchr("#+-.:=@_", c) != NULL ||
543 (white != NULL && strchr(white, c) != NULL))
548 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
549 int util_replace_chars(char *str, const char *white)
554 while (str[i] != '\0') {
557 if (is_whitelisted(str[i], white)) {
562 /* accept hex encoding */
563 if (str[i] == '\\' && str[i+1] == 'x') {
568 /* accept valid utf8 */
569 len = utf8_encoded_valid_unichar(&str[i]);
575 /* if space is allowed, replace whitespace with ordinary space */
576 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
583 /* everything else is replaced with '_' */
592 * udev_util_encode_string:
593 * @str: input string to be encoded
594 * @str_enc: output string to store the encoded input string
595 * @len: maximum size of the output string, which may be
596 * four times as long as the input string
598 * Encode all potentially unsafe characters of a string to the
599 * corresponding 2 char hex value prefixed by '\x'.
601 * Returns: 0 if the entire string was copied, non-zero otherwise.
603 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
607 if (str == NULL || str_enc == NULL)
610 for (i = 0, j = 0; str[i] != '\0'; i++) {
613 seqlen = utf8_encoded_valid_unichar(&str[i]);
615 if (len-j < (size_t)seqlen)
617 memcpy(&str_enc[j], &str[i], seqlen);
620 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
623 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
641 * http://sites.google.com/site/murmurhash/
643 * All code is released to the public domain. For business purposes,
644 * Murmurhash is under the MIT license.
647 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
650 * 'm' and 'r' are mixing constants generated offline.
651 * They're not really 'magic', they just happen to work well.
653 const unsigned int m = 0x5bd1e995;
656 /* initialize the hash to a 'random' value */
657 unsigned int h = seed ^ len;
659 /* mix 4 bytes at a time into the hash */
660 const unsigned char * data = (const unsigned char *)key;
663 unsigned int k = *(unsigned int *)data;
675 /* handle the last few bytes of the input array */
686 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
694 unsigned int util_string_hash32(const char *str)
696 return murmur_hash2(str, strlen(str), 0);
699 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
700 uint64_t util_string_bloom64(const char *str)
703 unsigned int hash = util_string_hash32(str);
705 bits |= 1LLU << (hash & 63);
706 bits |= 1LLU << ((hash >> 6) & 63);
707 bits |= 1LLU << ((hash >> 12) & 63);
708 bits |= 1LLU << ((hash >> 18) & 63);
712 #define USEC_PER_SEC 1000000ULL
713 #define NSEC_PER_USEC 1000ULL
714 unsigned long long ts_usec(const struct timespec *ts)
716 return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
717 (unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
720 unsigned long long now_usec(void)
724 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)