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"
40 * SECTION:libudev-util
41 * @short_description: utils
43 * Utilities useful when dealing with devices and device node names.
46 int util_delete_path(struct udev *udev, const char *path)
48 char p[UTIL_PATH_SIZE];
55 strscpy(p, sizeof(p), path);
56 pos = strrchr(p, '/');
57 if (pos == p || pos == NULL)
62 pos = strrchr(p, '/');
64 /* don't remove the last one */
65 if ((pos == p) || (pos == NULL))
78 uid_t util_lookup_user(struct udev *udev, const char *user)
84 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
85 char *buf = alloca(buflen);
87 if (streq(user, "root"))
89 uid = strtoul(user, &endptr, 10);
90 if (endptr[0] == '\0')
93 errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
96 if (errno == 0 || errno == ENOENT || errno == ESRCH)
97 udev_err(udev, "specified user '%s' unknown\n", user);
99 udev_err(udev, "error resolving user '%s': %m\n", user);
103 gid_t util_lookup_group(struct udev *udev, const char *group)
109 size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
112 if (streq(group, "root"))
114 gid = strtoul(group, &endptr, 10);
115 if (endptr[0] == '\0')
121 newbuf = realloc(buf, buflen);
125 errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
128 } else if (errno == ERANGE) {
131 } else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
132 udev_err(udev, "specified group '%s' unknown\n", group);
134 udev_err(udev, "error resolving group '%s': %m\n", group);
142 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
143 int util_resolve_subsys_kernel(struct udev *udev, const char *string,
144 char *result, size_t maxsize, int read_value)
146 char temp[UTIL_PATH_SIZE];
149 struct udev_device *dev;
152 if (string[0] != '[')
155 strscpy(temp, sizeof(temp), string);
159 sysname = strchr(subsys, '/');
163 sysname = &sysname[1];
165 attr = strchr(sysname, ']');
175 if (read_value && attr == NULL)
178 dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
185 val = udev_device_get_sysattr_value(dev, attr);
187 strscpy(result, maxsize, val);
190 udev_dbg(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
196 l = strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
198 strpcpyl(&s, l, "/", attr, NULL);
199 udev_dbg(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
201 udev_device_unref(dev);
204 ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
206 char path[UTIL_PATH_SIZE];
207 char target[UTIL_PATH_SIZE];
211 strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
212 len = readlink(path, target, sizeof(target));
213 if (len <= 0 || len == (ssize_t)sizeof(target))
216 pos = strrchr(target, '/');
220 return strscpy(value, size, pos);
223 int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
225 char link_target[UTIL_PATH_SIZE];
232 len = readlink(syspath, link_target, sizeof(link_target));
233 if (len <= 0 || len == (ssize_t)sizeof(link_target))
235 link_target[len] = '\0';
237 for (back = 0; startswith(&link_target[back * 3], "../"); back++)
239 for (i = 0; i <= back; i++) {
240 base = strrchr(syspath, '/');
246 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)
310 int util_replace_whitespace(const char *str, char *to, size_t len)
314 /* strip trailing whitespace */
315 len = strnlen(str, len);
316 while (len && isspace(str[len-1]))
319 /* strip leading whitespace */
321 while (isspace(str[i]) && (i < len))
326 /* substitute multiple whitespace with a single '_' */
327 if (isspace(str[i])) {
328 while (isspace(str[i]))
338 /* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
339 int util_replace_chars(char *str, const char *white)
344 while (str[i] != '\0') {
347 if (is_utf8_encoding_whitelisted(str[i], white)) {
352 /* accept hex encoding */
353 if (str[i] == '\\' && str[i+1] == 'x') {
358 /* accept valid utf8 */
359 len = utf8_encoded_valid_unichar(&str[i]);
365 /* if space is allowed, replace whitespace with ordinary space */
366 if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
373 /* everything else is replaced with '_' */
382 * udev_util_encode_string:
383 * @str: input string to be encoded
384 * @str_enc: output string to store the encoded input string
385 * @len: maximum size of the output string, which may be
386 * four times as long as the input string
388 * Encode all potentially unsafe characters of a string to the
389 * corresponding 2 char hex value prefixed by '\x'.
391 * Returns: 0 if the entire string was copied, non-zero otherwise.
393 _public_ int udev_util_encode_string(const char *str, char *str_enc, size_t len)
395 return udev_encode_string(str, str_enc, len);
399 * http://sites.google.com/site/murmurhash/
401 * All code is released to the public domain. For business purposes,
402 * Murmurhash is under the MIT license.
405 static unsigned int murmur_hash2(const char *key, size_t len, unsigned int seed)
408 * 'm' and 'r' are mixing constants generated offline.
409 * They're not really 'magic', they just happen to work well.
411 const unsigned int m = 0x5bd1e995;
414 /* initialize the hash to a 'random' value */
415 unsigned int h = seed ^ len;
417 /* mix 4 bytes at a time into the hash */
418 const unsigned char * data = (const unsigned char *)key;
420 while(len >= sizeof(unsigned int)) {
423 memcpy(&k, data, sizeof(k));
434 /* handle the last few bytes of the input array */
445 /* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
453 unsigned int util_string_hash32(const char *str)
455 return murmur_hash2(str, strlen(str), 0);
458 /* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
459 uint64_t util_string_bloom64(const char *str)
462 unsigned int hash = util_string_hash32(str);
464 bits |= 1LLU << (hash & 63);
465 bits |= 1LLU << ((hash >> 6) & 63);
466 bits |= 1LLU << ((hash >> 12) & 63);
467 bits |= 1LLU << ((hash >> 18) & 63);
471 ssize_t print_kmsg(const char *fmt, ...)
479 fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
483 len = snprintf(text, sizeof(text), "<30>systemd-udevd[%u]: ", getpid());
486 len += vsnprintf(text + len, sizeof(text) - len, fmt, ap);
489 ret = write(fd, text, len);