]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udevadm-util.c
Merge pull request #16504 from poettering/read-file-ipc
[thirdparty/systemd.git] / src / udev / udevadm-util.c
1 /* SPDX-License-Identifier: GPL-2.0+ */
2
3 #include <errno.h>
4
5 #include "alloc-util.h"
6 #include "device-private.h"
7 #include "path-util.h"
8 #include "udevadm-util.h"
9 #include "unit-name.h"
10
11 int find_device(const char *id, const char *prefix, sd_device **ret) {
12 _cleanup_free_ char *path = NULL;
13 int r;
14
15 assert(id);
16 assert(ret);
17
18 if (prefix) {
19 if (!path_startswith(id, prefix)) {
20 id = path = path_join(prefix, id);
21 if (!path)
22 return -ENOMEM;
23 }
24 } else {
25 /* In cases where the argument is generic (no prefix specified),
26 * check if the argument looks like a device unit name. */
27 if (unit_name_is_valid(id, UNIT_NAME_PLAIN) &&
28 unit_name_to_type(id) == UNIT_DEVICE) {
29 r = unit_name_to_path(id, &path);
30 if (r < 0)
31 return log_debug_errno(r, "Failed to convert \"%s\" to a device path: %m", id);
32 id = path;
33 }
34 }
35
36 if (path_startswith(id, "/sys/"))
37 return sd_device_new_from_syspath(ret, id);
38
39 if (path_startswith(id, "/dev/")) {
40 struct stat st;
41
42 if (stat(id, &st) < 0)
43 return -errno;
44
45 return device_new_from_stat_rdev(ret, &st);
46 }
47
48 return -EINVAL;
49 }