Line data Source code
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 0 : int find_device(const char *id, const char *prefix, sd_device **ret) { 12 0 : _cleanup_free_ char *path = NULL; 13 : int r; 14 : 15 0 : assert(id); 16 0 : assert(ret); 17 : 18 0 : if (prefix) { 19 0 : if (!path_startswith(id, prefix)) { 20 0 : id = path = path_join(prefix, id); 21 0 : if (!path) 22 0 : 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 0 : if (unit_name_is_valid(id, UNIT_NAME_PLAIN) && 28 0 : unit_name_to_type(id) == UNIT_DEVICE) { 29 0 : r = unit_name_to_path(id, &path); 30 0 : if (r < 0) 31 0 : return log_debug_errno(r, "Failed to convert \"%s\" to a device path: %m", id); 32 0 : id = path; 33 : } 34 : } 35 : 36 0 : if (path_startswith(id, "/sys/")) 37 0 : return sd_device_new_from_syspath(ret, id); 38 : 39 0 : if (path_startswith(id, "/dev/")) { 40 : struct stat st; 41 : 42 0 : if (stat(id, &st) < 0) 43 0 : return -errno; 44 : 45 0 : return device_new_from_stat_rdev(ret, &st); 46 : } 47 : 48 0 : return -EINVAL; 49 : }