]>
Commit | Line | Data |
---|---|---|
e7145211 | 1 | /* SPDX-License-Identifier: GPL-2.0+ */ |
d6170d27 | 2 | |
13aca847 YW |
3 | #include <errno.h> |
4 | ||
b753e14a | 5 | #include "alloc-util.h" |
13aca847 | 6 | #include "device-private.h" |
27458ed6 | 7 | #include "path-util.h" |
d6170d27 | 8 | #include "udevadm-util.h" |
b6854081 | 9 | #include "unit-name.h" |
d6170d27 | 10 | |
13aca847 | 11 | int find_device(const char *id, const char *prefix, sd_device **ret) { |
b6854081 ZJS |
12 | _cleanup_free_ char *path = NULL; |
13 | int r; | |
b753e14a | 14 | |
d6170d27 | 15 | assert(id); |
13aca847 | 16 | assert(ret); |
d6170d27 | 17 | |
b6854081 ZJS |
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 | } | |
b753e14a | 34 | } |
d6170d27 | 35 | |
13aca847 YW |
36 | if (path_startswith(id, "/sys/")) |
37 | return sd_device_new_from_syspath(ret, id); | |
38 | ||
27458ed6 | 39 | if (path_startswith(id, "/dev/")) { |
13aca847 YW |
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; | |
d6170d27 | 49 | } |