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>
35 #include "device-nodes.h"
37 #include "libudev-private.h"
41 * SECTION:libudev-util
42 * @short_description: utils
44 * Utilities useful when dealing with devices and device node names.
47 int util_delete_path(struct udev *udev, const char *path)
49 char p[UTIL_PATH_SIZE];
56 strscpy(p, sizeof(p), path);
57 pos = strrchr(p, '/');
58 if (pos == p || pos == NULL)
63 pos = strrchr(p, '/');
65 /* don't remove the last one */
66 if ((pos == p) || (pos == NULL))
79 uid_t util_lookup_user(struct udev *udev, const char *user)
85 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
86 char *buf = alloca(buflen);
88 if (streq(user, "root"))
90 uid = strtoul(user, &endptr, 10);
91 if (endptr[0] == '\0')
94 errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
97 if (errno == 0 || errno == ENOENT || errno == ESRCH)
98 udev_err(udev, "specified user '%s' unknown\n", user);
100 udev_err(udev, "error resolving user '%s': %m\n", user);
104 gid_t util_lookup_group(struct udev *udev, const char *group)
110 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
113 if (streq(group, "root"))
115 gid = strtoul(group, &endptr, 10);
116 if (endptr[0] == '\0')
122 newbuf = realloc(buf, buflen);
126 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
129 } else if (errno == ERANGE) {
132 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
133 udev_err(udev, "specified group '%s' unknown\n", group);
135 udev_err(udev, "error resolving group '%s': %m\n", group);
143 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
144 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
145 char *result, size_t maxsize, int read_value)
147 char temp[UTIL_PATH_SIZE];
150 struct udev_device *dev;
153 if (string[0] != '[')
156 strscpy(temp, sizeof(temp), string);
160 sysname = strchr(subsys, '/');
164 sysname = &sysname[1];
166 attr = strchr(sysname, ']');
176 if (read_value && attr == NULL)
179 dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
186 val = udev_device_get_sysattr_value(dev, attr);
188 strscpy(result, maxsize, val);
191 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
197 l = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
199 strpcpyl(&s, l, "/", attr, NULL);
200 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
202 udev_device_unref(dev);
205 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
207 char path[UTIL_PATH_SIZE];
208 char target[UTIL_PATH_SIZE];
212 strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
213 len = readlink(path, target, sizeof(target));
214 if (len <= 0 || len == (ssize_t)sizeof(target))
217 pos = strrchr(target, '/');
221 return strscpy(value, size, pos);
224 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
226 char link_target[UTIL_PATH_SIZE];
233 len = readlink(syspath, link_target, sizeof(link_target));
234 if (len <= 0 || len == (ssize_t)sizeof(link_target))
236 link_target[len] = '\0';
238 for (back = 0; startswith(&link_target[back * 3], "../"); back++)
240 for (i = 0; i <= back; i++) {
241 base = strrchr(syspath, '/');
247 strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
251 int util_log_priority(const char *priority)
256 prio = strtol(priority, &endptr, 10);
257 if (endptr[0] == '\0' || isspace(endptr[0]))
259 if (startswith(priority, "err"))
261 if (startswith(priority, "info"))
263 if (startswith(priority, "debug"))
268 size_t util_path_encode(const char *src, char *dest, size_t size)
272 for (i = 0, j = 0; src[i] != '\0'; i++) {
278 memcpy(&dest[j], "\\x2f", 4);
280 } else if (src[i] == '\\') {
285 memcpy(&dest[j], "\\x5c", 4);
300 void util_remove_trailing_chars(char *path, char c)
307 while (len > 0 && path[len-1] == c)
311 int util_replace_whitespace(const char *str, char *to, size_t len)
315 /* strip trailing whitespace */
316 len = strnlen(str, len);
317 while (len && isspace(str[len-1]))
320 /* strip leading whitespace */
322 while (isspace(str[i]) && (i < len))
327 /* substitute multiple whitespace with a single '_' */
328 if (isspace(str[i])) {
329 while (isspace(str[i]))
339 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
340 int util_replace_chars(char *str, const char *white)
345 while (str[i] != '\0') {
348 if (whitelisted_char_for_devnode(str[i], white)) {
353 /* accept hex encoding */
354 if (str[i] == '\\' && str[i+1] == 'x') {
359 /* accept valid utf8 */
360 len = utf8_encoded_valid_unichar(&str[i]);
366 /* if space is allowed, replace whitespace with ordinary space */
367 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
374 /* everything else is replaced with '_' */
383 * udev_util_encode_string:
384 * @str: input string to be encoded
385 * @str_enc: output string to store the encoded input string
386 * @len: maximum size of the output string, which may be
387 * four times as long as the input string
389 * Encode all potentially unsafe characters of a string to the
390 * corresponding 2 char hex value prefixed by '\x'.
392 * Returns: 0 if the entire string was copied, non-zero otherwise.
394 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
396 return encode_devnode_name(str, str_enc, len);
400 * http://sites.google.com/site/murmurhash/
402 * All code is released to the public domain. For business purposes,
403 * Murmurhash is under the MIT license.
406 static unsigned int murmur_hash2(const char *key, size_t len, unsigned int seed)
409 * 'm' and 'r' are mixing constants generated offline.
410 * They're not really 'magic', they just happen to work well.
412 const unsigned int m = 0x5bd1e995;
415 /* initialize the hash to a 'random' value */
416 unsigned int h = seed ^ len;
418 /* mix 4 bytes at a time into the hash */
419 const unsigned char * data = (const unsigned char *)key;
421 while(len >= sizeof(unsigned int)) {
424 memcpy(&k, data, sizeof(k));
435 /* handle the last few bytes of the input array */
446 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
454 unsigned int util_string_hash32(const char *str)
456 return murmur_hash2(str, strlen(str), 0);
459 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
460 uint64_t util_string_bloom64(const char *str)
463 unsigned int hash = util_string_hash32(str);
465 bits |= 1LLU << (hash & 63);
466 bits |= 1LLU << ((hash >> 6) & 63);
467 bits |= 1LLU << ((hash >> 12) & 63);
468 bits |= 1LLU << ((hash >> 18) & 63);
472 ssize_t print_kmsg(const char *fmt, ...)
480 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
484 len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
487 len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
490 ret = write(fd, text, len);