2 This file is part of systemd.
4 Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
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.
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.
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/>.
33 #include <sys/param.h>
36 #include "libudev-private.h"
39 * SECTION:libudev-util
40 * @short_description: utils
42 * Utilities useful when dealing with devices and device node names.
45 int util_delete_path(struct udev *udev, const char *path)
47 char p[UTIL_PATH_SIZE];
54 util_strscpy(p, sizeof(p), path);
55 pos = strrchr(p, '/');
56 if (pos == p || pos == NULL)
61 pos = strrchr(p, '/');
63 /* don't remove the last one */
64 if ((pos == p) || (pos == NULL))
77 uid_t util_lookup_user(struct udev *udev, const char *user)
83 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
84 char *buf = alloca(buflen);
86 if (strcmp(user, "root") == 0)
88 uid = strtoul(user, &endptr, 10);
89 if (endptr[0] == '\0')
92 errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
95 if (errno == 0 || errno == ENOENT || errno == ESRCH)
96 udev_err(udev, "specified user '%s' unknown\n", user);
98 udev_err(udev, "error resolving user '%s': %m\n", user);
102 gid_t util_lookup_group(struct udev *udev, const char *group)
108 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
111 if (strcmp(group, "root") == 0)
113 gid = strtoul(group, &endptr, 10);
114 if (endptr[0] == '\0')
120 newbuf = realloc(buf, buflen);
124 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
127 } else if (errno == ERANGE) {
130 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
131 udev_err(udev, "specified group '%s' unknown\n", group);
133 udev_err(udev, "error resolving group '%s': %m\n", group);
141 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
142 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
143 char *result, size_t maxsize, int read_value)
145 char temp[UTIL_PATH_SIZE];
148 struct udev_device *dev;
151 if (string[0] != '[')
154 util_strscpy(temp, sizeof(temp), string);
158 sysname = strchr(subsys, '/');
162 sysname = &sysname[1];
164 attr = strchr(sysname, ']');
174 if (read_value && attr == NULL)
177 dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
184 val = udev_device_get_sysattr_value(dev, attr);
186 util_strscpy(result, maxsize, val);
189 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
195 l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
197 util_strpcpyl(&s, l, "/", attr, NULL);
198 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
200 udev_device_unref(dev);
203 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
205 char path[UTIL_PATH_SIZE];
206 char target[UTIL_PATH_SIZE];
210 util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
211 len = readlink(path, target, sizeof(target));
212 if (len <= 0 || len == (ssize_t)sizeof(target))
215 pos = strrchr(target, '/');
219 return util_strscpy(value, size, pos);
222 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
224 char link_target[UTIL_PATH_SIZE];
231 len = readlink(syspath, link_target, sizeof(link_target));
232 if (len <= 0 || len == (ssize_t)sizeof(link_target))
234 link_target[len] = '\0';
236 for (back = 0; startswith(&link_target[back * 3], "../"); back++)
238 for (i = 0; i <= back; i++) {
239 base = strrchr(syspath, '/');
246 util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
250 int util_log_priority(const char *priority)
255 prio = strtol(priority, &endptr, 10);
256 if (endptr[0] == '\0' || isspace(endptr[0]))
258 if (startswith(priority, "err"))
260 if (startswith(priority, "info"))
262 if (startswith(priority, "debug"))
267 size_t util_path_encode(const char *src, char *dest, size_t size)
271 for (i = 0, j = 0; src[i] != '\0'; i++) {
277 memcpy(&dest[j], "\\x2f", 4);
279 } else if (src[i] == '\\') {
284 memcpy(&dest[j], "\\x5c", 4);
299 void util_remove_trailing_chars(char *path, char c)
306 while (len > 0 && path[len-1] == c)
311 * Concatenates strings. In any case, terminates in _all_ cases with '\0'
312 * and moves the @dest pointer forward to the added '\0'. Returns the
313 * remaining size, and 0 if the string was truncated.
315 size_t util_strpcpy(char **dest, size_t size, const char *src)
322 *dest = mempcpy(*dest, src, size-1);
326 *dest = mempcpy(*dest, src, len);
334 size_t util_strpcpyf(char **dest, size_t size, const char *src, ...)
340 i = vsnprintf(*dest, size, src, va);
353 /* concatenates list of strings, moves dest forward */
354 size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
360 size = util_strpcpy(dest, size, src);
361 src = va_arg(va, char *);
362 } while (src != NULL);
368 size_t util_strscpy(char *dest, size_t size, const char *src)
373 return util_strpcpy(&s, size, src);
376 /* concatenates list of strings */
377 size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
385 size = util_strpcpy(&s, size, src);
386 src = va_arg(va, char *);
387 } while (src != NULL);
393 /* count of characters used to encode one unicode char */
394 static int utf8_encoded_expected_len(const char *str)
396 unsigned char c = (unsigned char)str[0];
400 if ((c & 0xe0) == 0xc0)
402 if ((c & 0xf0) == 0xe0)
404 if ((c & 0xf8) == 0xf0)
406 if ((c & 0xfc) == 0xf8)
408 if ((c & 0xfe) == 0xfc)
413 /* decode one unicode char */
414 static int utf8_encoded_to_unichar(const char *str)
420 len = utf8_encoded_expected_len(str);
425 unichar = str[0] & 0x1f;
428 unichar = (int)str[0] & 0x0f;
431 unichar = (int)str[0] & 0x07;
434 unichar = (int)str[0] & 0x03;
437 unichar = (int)str[0] & 0x01;
443 for (i = 1; i < len; i++) {
444 if (((int)str[i] & 0xc0) != 0x80)
447 unichar |= (int)str[i] & 0x3f;
453 /* expected size used to encode one unicode char */
454 static int utf8_unichar_to_encoded_len(int unichar)
460 if (unichar < 0x10000)
462 if (unichar < 0x200000)
464 if (unichar < 0x4000000)
469 /* check if unicode char has a valid numeric range */
470 static int utf8_unichar_valid_range(int unichar)
472 if (unichar > 0x10ffff)
474 if ((unichar & 0xfffff800) == 0xd800)
476 if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
478 if ((unichar & 0xffff) == 0xffff)
483 /* validate one encoded unicode char and return its length */
484 static int utf8_encoded_valid_unichar(const char *str)
490 len = utf8_encoded_expected_len(str);
498 /* check if expected encoded chars are available */
499 for (i = 0; i < len; i++)
500 if ((str[i] & 0x80) != 0x80)
503 unichar = utf8_encoded_to_unichar(str);
505 /* check if encoded length matches encoded value */
506 if (utf8_unichar_to_encoded_len(unichar) != len)
509 /* check if value has valid range */
510 if (!utf8_unichar_valid_range(unichar))
516 int util_replace_whitespace(const char *str, char *to, size_t len)
520 /* strip trailing whitespace */
521 len = strnlen(str, len);
522 while (len && isspace(str[len-1]))
525 /* strip leading whitespace */
527 while (isspace(str[i]) && (i < len))
532 /* substitute multiple whitespace with a single '_' */
533 if (isspace(str[i])) {
534 while (isspace(str[i]))
544 static int is_whitelisted(char c, const char *white)
546 if ((c >= '0' && c <= '9') ||
547 (c >= 'A' && c <= 'Z') ||
548 (c >= 'a' && c <= 'z') ||
549 strchr("#+-.:=@_", c) != NULL ||
550 (white != NULL && strchr(white, c) != NULL))
555 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
556 int util_replace_chars(char *str, const char *white)
561 while (str[i] != '\0') {
564 if (is_whitelisted(str[i], white)) {
569 /* accept hex encoding */
570 if (str[i] == '\\' && str[i+1] == 'x') {
575 /* accept valid utf8 */
576 len = utf8_encoded_valid_unichar(&str[i]);
582 /* if space is allowed, replace whitespace with ordinary space */
583 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
590 /* everything else is replaced with '_' */
599 * udev_util_encode_string:
600 * @str: input string to be encoded
601 * @str_enc: output string to store the encoded input string
602 * @len: maximum size of the output string, which may be
603 * four times as long as the input string
605 * Encode all potentially unsafe characters of a string to the
606 * corresponding 2 char hex value prefixed by '\x'.
608 * Returns: 0 if the entire string was copied, non-zero otherwise.
610 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
614 if (str == NULL || str_enc == NULL)
617 for (i = 0, j = 0; str[i] != '\0'; i++) {
620 seqlen = utf8_encoded_valid_unichar(&str[i]);
622 if (len-j < (size_t)seqlen)
624 memcpy(&str_enc[j], &str[i], seqlen);
627 } else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
630 sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
648 * http://sites.google.com/site/murmurhash/
650 * All code is released to the public domain. For business purposes,
651 * Murmurhash is under the MIT license.
654 static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
657 * 'm' and 'r' are mixing constants generated offline.
658 * They're not really 'magic', they just happen to work well.
660 const unsigned int m = 0x5bd1e995;
663 /* initialize the hash to a 'random' value */
664 unsigned int h = seed ^ len;
666 /* mix 4 bytes at a time into the hash */
667 const unsigned char * data = (const unsigned char *)key;
670 unsigned int k = *(unsigned int *)data;
682 /* handle the last few bytes of the input array */
693 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
701 unsigned int util_string_hash32(const char *str)
703 return murmur_hash2(str, strlen(str), 0);
706 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
707 uint64_t util_string_bloom64(const char *str)
710 unsigned int hash = util_string_hash32(str);
712 bits |= 1LLU << (hash & 63);
713 bits |= 1LLU << ((hash >> 6) & 63);
714 bits |= 1LLU << ((hash >> 12) & 63);
715 bits |= 1LLU << ((hash >> 18) & 63);
719 ssize_t print_kmsg(const char *fmt, ...)
727 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
731 len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
734 len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
737 ret = write(fd, text, len);