1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
12 #include "device-internal.h"
13 #include "device-private.h"
14 #include "device-util.h"
15 #include "devnum-util.h"
16 #include "dirent-util.h"
20 #include "format-util.h"
23 #include "id128-util.h"
25 #include "missing_magic.h"
26 #include "netlink-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
30 #include "socket-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
35 #include "user-util.h"
37 int device_new_aux(sd_device
**ret
) {
42 device
= new(sd_device
, 1);
46 *device
= (sd_device
) {
48 .devmode
= MODE_INVALID
,
49 .devuid
= UID_INVALID
,
50 .devgid
= GID_INVALID
,
51 .action
= _SD_DEVICE_ACTION_INVALID
,
58 static sd_device
*device_free(sd_device
*device
) {
61 sd_device_unref(device
->parent
);
62 free(device
->syspath
);
63 free(device
->sysname
);
64 free(device
->devtype
);
65 free(device
->devname
);
66 free(device
->subsystem
);
67 free(device
->driver_subsystem
);
69 free(device
->device_id
);
70 free(device
->properties_strv
);
71 free(device
->properties_nulstr
);
73 ordered_hashmap_free(device
->properties
);
74 ordered_hashmap_free(device
->properties_db
);
75 hashmap_free(device
->sysattr_values
);
76 set_free(device
->sysattrs
);
77 set_free(device
->all_tags
);
78 set_free(device
->current_tags
);
79 set_free(device
->devlinks
);
80 hashmap_free(device
->children
);
85 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_device
, sd_device
, device_free
);
87 int device_add_property_aux(sd_device
*device
, const char *key
, const char *value
, bool db
) {
88 OrderedHashmap
**properties
;
94 properties
= &device
->properties_db
;
96 properties
= &device
->properties
;
99 _unused_ _cleanup_free_
char *old_value
= NULL
;
100 _cleanup_free_
char *new_key
= NULL
, *new_value
= NULL
, *old_key
= NULL
;
103 r
= ordered_hashmap_ensure_allocated(properties
, &string_hash_ops_free_free
);
107 new_key
= strdup(key
);
111 new_value
= strdup(value
);
115 old_value
= ordered_hashmap_get2(*properties
, key
, (void**) &old_key
);
117 /* ordered_hashmap_replace() does not fail when the hashmap already has the entry. */
118 r
= ordered_hashmap_replace(*properties
, new_key
, new_value
);
125 _unused_ _cleanup_free_
char *old_value
= NULL
;
126 _cleanup_free_
char *old_key
= NULL
;
128 old_value
= ordered_hashmap_remove2(*properties
, key
, (void**) &old_key
);
132 device
->properties_generation
++;
133 device
->properties_buf_outdated
= true;
139 int device_set_syspath(sd_device
*device
, const char *_syspath
, bool verify
) {
140 _cleanup_free_
char *syspath
= NULL
;
148 _cleanup_close_
int fd
= -EBADF
;
150 /* The input path maybe a symlink located outside of /sys. Let's try to chase the symlink at first.
151 * The primary use case is that e.g. /proc/device-tree is a symlink to /sys/firmware/devicetree/base.
152 * By chasing symlinks in the path at first, we can call sd_device_new_from_path() with such path. */
153 r
= chase(_syspath
, NULL
, 0, &syspath
, &fd
);
155 /* the device does not exist (any more?) */
156 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
157 "sd-device: Failed to chase symlinks in \"%s\".", _syspath
);
159 return log_debug_errno(r
, "sd-device: Failed to get target of '%s': %m", _syspath
);
161 if (!path_startswith(syspath
, "/sys")) {
162 _cleanup_free_
char *real_sys
= NULL
, *new_syspath
= NULL
;
165 /* /sys is a symlink to somewhere sysfs is mounted on? In that case, we convert the path to real sysfs to "/sys". */
166 r
= chase("/sys", NULL
, 0, &real_sys
, NULL
);
168 return log_debug_errno(r
, "sd-device: Failed to chase symlink /sys: %m");
170 p
= path_startswith(syspath
, real_sys
);
172 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
173 "sd-device: Canonicalized path '%s' does not starts with sysfs mount point '%s'",
176 new_syspath
= path_join("/sys", p
);
178 return log_oom_debug();
180 free_and_replace(syspath
, new_syspath
);
181 path_simplify(syspath
);
184 if (path_startswith(syspath
, "/sys/devices/")) {
185 /* For proper devices, stricter rules apply: they must have a 'uevent' file,
186 * otherwise we won't allow them */
188 if (faccessat(fd
, "uevent", F_OK
, 0) < 0) {
190 /* This is not a valid device. Note, this condition is quite often
191 * satisfied when enumerating devices or finding a parent device.
192 * Hence, use log_trace_errno() here. */
193 return log_trace_errno(SYNTHETIC_ERRNO(ENODEV
),
194 "sd-device: the uevent file \"%s/uevent\" does not exist.", syspath
);
195 if (errno
== ENOTDIR
)
196 /* Not actually a directory. */
197 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
198 "sd-device: the syspath \"%s\" is not a directory.", syspath
);
200 return log_debug_errno(errno
, "sd-device: cannot find uevent file for %s: %m", syspath
);
205 /* For everything else lax rules apply: they just need to be a directory */
207 if (fstat(fd
, &st
) < 0)
208 return log_debug_errno(errno
, "sd-device: failed to check if syspath \"%s\" is a directory: %m", syspath
);
209 if (!S_ISDIR(st
.st_mode
))
210 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
211 "sd-device: the syspath \"%s\" is not a directory.", syspath
);
214 /* Only operate on sysfs, i.e. refuse going down into /sys/fs/cgroup/ or similar places where
215 * things are not arranged as kobjects in kernel, and hence don't necessarily have
216 * kobject/attribute structure. */
217 r
= getenv_bool_secure("SYSTEMD_DEVICE_VERIFY_SYSFS");
218 if (r
< 0 && r
!= -ENXIO
)
219 log_debug_errno(r
, "Failed to parse $SYSTEMD_DEVICE_VERIFY_SYSFS value: %m");
221 r
= fd_is_fs_type(fd
, SYSFS_MAGIC
);
223 return log_debug_errno(r
, "sd-device: failed to check if syspath \"%s\" is backed by sysfs.", syspath
);
225 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
226 "sd-device: the syspath \"%s\" is outside of sysfs, refusing.", syspath
);
229 /* must be a subdirectory of /sys */
230 if (!path_startswith(_syspath
, "/sys/"))
231 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
232 "sd-device: Syspath '%s' is not a subdirectory of /sys",
235 r
= path_simplify_alloc(_syspath
, &syspath
);
240 assert_se(devpath
= startswith(syspath
, "/sys"));
241 if (devpath
[0] != '/')
242 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
), "sd-device: \"/sys\" alone is not a valid device path.");
244 r
= device_add_property_internal(device
, "DEVPATH", devpath
);
246 return log_debug_errno(r
, "sd-device: Failed to add \"DEVPATH\" property for device \"%s\": %m", syspath
);
248 free_and_replace(device
->syspath
, syspath
);
249 device
->devpath
= devpath
;
251 /* Unset sysname and sysnum, they will be assigned when requested. */
252 device
->sysnum
= NULL
;
253 device
->sysname
= mfree(device
->sysname
);
257 static int device_new_from_syspath(sd_device
**ret
, const char *syspath
, bool strict
) {
258 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
261 assert_return(ret
, -EINVAL
);
262 assert_return(syspath
, -EINVAL
);
264 if (strict
&& !path_startswith(syspath
, "/sys/"))
267 r
= device_new_aux(&device
);
271 r
= device_set_syspath(device
, syspath
, /* verify= */ true);
275 *ret
= TAKE_PTR(device
);
279 _public_
int sd_device_new_from_syspath(sd_device
**ret
, const char *syspath
) {
280 return device_new_from_syspath(ret
, syspath
, /* strict = */ true);
283 int device_new_from_mode_and_devnum(sd_device
**ret
, mode_t mode
, dev_t devnum
) {
284 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
285 _cleanup_free_
char *syspath
= NULL
;
294 else if (S_ISBLK(mode
))
299 if (major(devnum
) == 0)
302 if (asprintf(&syspath
, "/sys/dev/%s/" DEVNUM_FORMAT_STR
, t
, DEVNUM_FORMAT_VAL(devnum
)) < 0)
305 r
= sd_device_new_from_syspath(&dev
, syspath
);
309 r
= sd_device_get_devnum(dev
, &n
);
317 if (device_in_subsystem(dev
, "block") != !!S_ISBLK(mode
))
320 *ret
= TAKE_PTR(dev
);
324 _public_
int sd_device_new_from_devnum(sd_device
**ret
, char type
, dev_t devnum
) {
325 assert_return(ret
, -EINVAL
);
326 assert_return(IN_SET(type
, 'b', 'c'), -EINVAL
);
328 return device_new_from_mode_and_devnum(ret
, type
== 'b' ? S_IFBLK
: S_IFCHR
, devnum
);
331 static int device_new_from_main_ifname(sd_device
**ret
, const char *ifname
) {
337 syspath
= strjoina("/sys/class/net/", ifname
);
338 return sd_device_new_from_syspath(ret
, syspath
);
341 _public_
int sd_device_new_from_ifname(sd_device
**ret
, const char *ifname
) {
342 _cleanup_free_
char *main_name
= NULL
;
345 assert_return(ret
, -EINVAL
);
346 assert_return(ifname
, -EINVAL
);
348 r
= device_new_from_main_ifname(ret
, ifname
);
352 r
= rtnl_resolve_ifname_full(NULL
, RESOLVE_IFNAME_ALTERNATIVE
| RESOLVE_IFNAME_NUMERIC
, ifname
, &main_name
, NULL
);
356 return device_new_from_main_ifname(ret
, main_name
);
359 _public_
int sd_device_new_from_ifindex(sd_device
**ret
, int ifindex
) {
360 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
361 _cleanup_free_
char *ifname
= NULL
;
364 assert_return(ret
, -EINVAL
);
365 assert_return(ifindex
> 0, -EINVAL
);
367 r
= rtnl_get_ifname_full(NULL
, ifindex
, &ifname
, NULL
);
371 r
= device_new_from_main_ifname(&dev
, ifname
);
375 r
= sd_device_get_ifindex(dev
, &i
);
383 *ret
= TAKE_PTR(dev
);
387 static int device_strjoin_new(
397 p
= strjoina(a
, b
, c
, d
);
398 if (access(p
, F_OK
) < 0)
399 return IN_SET(errno
, ENOENT
, ENAMETOOLONG
) ? 0 : -errno
; /* If this sysfs is too long then it doesn't exist either */
401 r
= sd_device_new_from_syspath(ret
, p
);
408 _public_
int sd_device_new_from_subsystem_sysname(
410 const char *subsystem
,
411 const char *sysname
) {
416 assert_return(ret
, -EINVAL
);
417 assert_return(subsystem
, -EINVAL
);
418 assert_return(sysname
, -EINVAL
);
420 if (!path_is_normalized(subsystem
))
422 if (!path_is_normalized(sysname
))
425 /* translate sysname back to sysfs filename */
426 name
= strdupa_safe(sysname
);
427 string_replace_char(name
, '/', '!');
429 if (streq(subsystem
, "subsystem")) {
430 FOREACH_STRING(s
, "/sys/bus/", "/sys/class/") {
431 r
= device_strjoin_new(s
, name
, NULL
, NULL
, ret
);
438 } else if (streq(subsystem
, "module")) {
439 r
= device_strjoin_new("/sys/module/", name
, NULL
, NULL
, ret
);
445 } else if (streq(subsystem
, "drivers")) {
448 sep
= strchr(name
, ':');
449 if (sep
&& sep
[1] != '\0') { /* Require ":" and something non-empty after that. */
451 const char *subsys
= memdupa_suffix0(name
, sep
- name
);
454 if (streq(sep
, "drivers")) /* If the sysname is "drivers", then it's the drivers directory itself that is meant. */
455 r
= device_strjoin_new("/sys/bus/", subsys
, "/drivers", NULL
, ret
);
457 r
= device_strjoin_new("/sys/bus/", subsys
, "/drivers/", sep
, ret
);
465 r
= device_strjoin_new("/sys/bus/", subsystem
, "/devices/", name
, ret
);
471 r
= device_strjoin_new("/sys/class/", subsystem
, "/", name
, ret
);
477 r
= device_strjoin_new("/sys/firmware/", subsystem
, "/", name
, ret
);
486 _public_
int sd_device_new_from_stat_rdev(sd_device
**ret
, const struct stat
*st
) {
487 assert_return(ret
, -EINVAL
);
488 assert_return(st
, -EINVAL
);
490 return device_new_from_mode_and_devnum(ret
, st
->st_mode
, st
->st_rdev
);
493 _public_
int sd_device_new_from_devname(sd_device
**ret
, const char *devname
) {
498 assert_return(ret
, -EINVAL
);
499 assert_return(devname
, -EINVAL
);
501 /* This function actually accepts both devlinks and devnames, i.e. both symlinks and device
502 * nodes below /dev/. */
504 /* Also ignore when the specified path is "/dev". */
505 if (isempty(path_startswith(devname
, "/dev")))
508 if (device_path_parse_major_minor(devname
, &mode
, &devnum
) >= 0)
509 /* Let's shortcut when "/dev/block/maj:min" or "/dev/char/maj:min" is specified.
510 * In that case, we can directly convert the path to syspath, hence it is not necessary
511 * that the specified path exists. So, this works fine without udevd being running. */
512 return device_new_from_mode_and_devnum(ret
, mode
, devnum
);
514 if (stat(devname
, &st
) < 0)
515 return ERRNO_IS_DEVICE_ABSENT(errno
) ? -ENODEV
: -errno
;
517 return sd_device_new_from_stat_rdev(ret
, &st
);
520 _public_
int sd_device_new_from_path(sd_device
**ret
, const char *path
) {
521 assert_return(ret
, -EINVAL
);
522 assert_return(path
, -EINVAL
);
524 if (path_startswith(path
, "/dev"))
525 return sd_device_new_from_devname(ret
, path
);
527 return device_new_from_syspath(ret
, path
, /* strict = */ false);
530 int device_set_devtype(sd_device
*device
, const char *devtype
) {
531 _cleanup_free_
char *t
= NULL
;
541 r
= device_add_property_internal(device
, "DEVTYPE", t
);
545 return free_and_replace(device
->devtype
, t
);
548 int device_set_ifindex(sd_device
*device
, const char *name
) {
554 ifindex
= parse_ifindex(name
);
558 r
= device_add_property_internal(device
, "IFINDEX", name
);
562 device
->ifindex
= ifindex
;
567 static int mangle_devname(const char *p
, char **ret
) {
573 if (!path_is_safe(p
))
576 /* When the path is absolute, it must start with "/dev/", but ignore "/dev/" itself. */
577 if (path_is_absolute(p
)) {
578 if (isempty(path_startswith(p
, "/dev/")))
583 q
= path_join("/dev/", p
);
593 int device_set_devname(sd_device
*device
, const char *devname
) {
594 _cleanup_free_
char *t
= NULL
;
600 r
= mangle_devname(devname
, &t
);
604 r
= device_add_property_internal(device
, "DEVNAME", t
);
608 return free_and_replace(device
->devname
, t
);
611 int device_set_devmode(sd_device
*device
, const char *_devmode
) {
618 r
= safe_atou(_devmode
, &devmode
);
625 r
= device_add_property_internal(device
, "DEVMODE", _devmode
);
629 device
->devmode
= devmode
;
634 int device_set_devnum(sd_device
*device
, const char *major
, const char *minor
) {
635 unsigned maj
, min
= 0;
641 r
= safe_atou(major
, &maj
);
646 if (!DEVICE_MAJOR_VALID(maj
))
650 r
= safe_atou(minor
, &min
);
653 if (!DEVICE_MINOR_VALID(min
))
657 r
= device_add_property_internal(device
, "MAJOR", major
);
662 r
= device_add_property_internal(device
, "MINOR", minor
);
667 device
->devnum
= makedev(maj
, min
);
672 int device_set_diskseq(sd_device
*device
, const char *str
) {
679 r
= safe_atou64(str
, &diskseq
);
685 r
= device_add_property_internal(device
, "DISKSEQ", str
);
689 device
->diskseq
= diskseq
;
694 static int handle_uevent_line(
699 const char **minor
) {
707 if (streq(key
, "DEVTYPE"))
708 return device_set_devtype(device
, value
);
709 if (streq(key
, "IFINDEX"))
710 return device_set_ifindex(device
, value
);
711 if (streq(key
, "DEVNAME"))
712 return device_set_devname(device
, value
);
713 if (streq(key
, "DEVMODE"))
714 return device_set_devmode(device
, value
);
715 if (streq(key
, "DISKSEQ"))
716 return device_set_diskseq(device
, value
);
717 if (streq(key
, "MAJOR"))
719 else if (streq(key
, "MINOR"))
722 return device_add_property_internal(device
, key
, value
);
727 int device_read_uevent_file(sd_device
*device
) {
728 _cleanup_free_
char *uevent
= NULL
;
729 const char *syspath
, *key
= NULL
, *value
= NULL
, *major
= NULL
, *minor
= NULL
;
744 if (device
->uevent_loaded
|| device
->sealed
)
747 r
= sd_device_get_syspath(device
, &syspath
);
751 device
->uevent_loaded
= true;
753 path
= strjoina(syspath
, "/uevent");
755 r
= read_full_virtual_file(path
, &uevent
, &uevent_len
);
756 if (r
== -EACCES
|| ERRNO_IS_NEG_DEVICE_ABSENT(r
))
757 /* The uevent files may be write-only, the device may be already removed, or the device
758 * may not have the uevent file. */
761 return log_device_debug_errno(device
, r
, "sd-device: Failed to read uevent file '%s': %m", path
);
763 for (size_t i
= 0; i
< uevent_len
; i
++)
766 if (!strchr(NEWLINE
, uevent
[i
])) {
774 if (uevent
[i
] == '=') {
778 } else if (strchr(NEWLINE
, uevent
[i
])) {
780 log_device_debug(device
, "sd-device: Invalid uevent line '%s', ignoring", key
);
790 _fallthrough_
; /* to handle empty property */
792 if (strchr(NEWLINE
, uevent
[i
])) {
795 r
= handle_uevent_line(device
, key
, value
, &major
, &minor
);
797 log_device_debug_errno(device
, r
, "sd-device: Failed to handle uevent entry '%s=%s', ignoring: %m", key
, value
);
804 assert_not_reached();
808 r
= device_set_devnum(device
, major
, minor
);
810 log_device_debug_errno(device
, r
, "sd-device: Failed to set 'MAJOR=%s' or 'MINOR=%s' from '%s', ignoring: %m", major
, strna(minor
), path
);
816 _public_
int sd_device_get_ifindex(sd_device
*device
, int *ifindex
) {
819 assert_return(device
, -EINVAL
);
821 r
= device_read_uevent_file(device
);
825 if (device
->ifindex
<= 0)
829 *ifindex
= device
->ifindex
;
834 _public_
int sd_device_new_from_device_id(sd_device
**ret
, const char *id
) {
837 assert_return(ret
, -EINVAL
);
838 assert_return(id
, -EINVAL
);
848 r
= parse_devnum(id
+ 1, &devt
);
852 return sd_device_new_from_devnum(ret
, id
[0], devt
);
858 ifindex
= parse_ifindex(id
+ 1);
862 return sd_device_new_from_ifindex(ret
, ifindex
);
866 const char *subsys
, *sep
;
868 sep
= strchr(id
+ 1, ':');
869 if (!sep
|| sep
- id
- 1 > NAME_MAX
)
872 subsys
= memdupa_suffix0(id
+ 1, sep
- id
- 1);
874 return sd_device_new_from_subsystem_sysname(ret
, subsys
, sep
+ 1);
882 _public_
int sd_device_get_syspath(sd_device
*device
, const char **ret
) {
883 assert_return(device
, -EINVAL
);
885 assert(path_startswith(device
->syspath
, "/sys/"));
888 *ret
= device
->syspath
;
893 DEFINE_PRIVATE_HASH_OPS_FULL(
894 device_by_path_hash_ops
,
895 char, path_hash_func
, path_compare
, free
,
896 sd_device
, sd_device_unref
);
898 static int device_enumerate_children_internal(sd_device
*device
, const char *subdir
, Set
**stack
, Hashmap
**children
) {
899 _cleanup_closedir_
DIR *dir
= NULL
;
906 r
= device_opendir(device
, subdir
, &dir
);
910 FOREACH_DIRENT_ALL(de
, dir
, return -errno
) {
911 _cleanup_(sd_device_unrefp
) sd_device
*child
= NULL
;
912 _cleanup_free_
char *p
= NULL
;
914 if (dot_or_dot_dot(de
->d_name
))
917 if (!IN_SET(de
->d_type
, DT_LNK
, DT_DIR
))
921 p
= path_join(subdir
, de
->d_name
);
923 p
= strdup(de
->d_name
);
927 /* Try to create child device. */
928 r
= sd_device_new_child(&child
, device
, p
);
930 /* OK, this is a child device, saving it. */
931 r
= hashmap_ensure_put(children
, &device_by_path_hash_ops
, p
, child
);
937 } else if (r
== -ENODEV
) {
938 /* This is not a child device. Push the sub-directory into stack, and read it later. */
940 if (de
->d_type
== DT_LNK
)
941 /* Do not follow symlinks, otherwise, we will enter an infinite loop, e.g.,
942 * /sys/class/block/nvme0n1/subsystem/nvme0n1/subsystem/nvme0n1/subsystem/… */
945 r
= set_ensure_consume(stack
, &path_hash_ops_free
, TAKE_PTR(p
));
955 static int device_enumerate_children(sd_device
*device
) {
956 _cleanup_hashmap_free_ Hashmap
*children
= NULL
;
957 _cleanup_set_free_ Set
*stack
= NULL
;
962 if (device
->children_enumerated
)
963 return 0; /* Already enumerated. */
965 r
= device_enumerate_children_internal(device
, NULL
, &stack
, &children
);
970 _cleanup_free_
char *subdir
= NULL
;
972 subdir
= set_steal_first(stack
);
976 r
= device_enumerate_children_internal(device
, subdir
, &stack
, &children
);
981 device
->children_enumerated
= true;
982 device
->children
= TAKE_PTR(children
);
983 return 1; /* Enumerated. */
986 _public_ sd_device
*sd_device_get_child_first(sd_device
*device
, const char **ret_suffix
) {
991 r
= device_enumerate_children(device
);
993 log_device_debug_errno(device
, r
, "sd-device: failed to enumerate child devices: %m");
999 device
->children_iterator
= ITERATOR_FIRST
;
1001 return sd_device_get_child_next(device
, ret_suffix
);
1004 _public_ sd_device
*sd_device_get_child_next(sd_device
*device
, const char **ret_suffix
) {
1009 (void) hashmap_iterate(device
->children
, &device
->children_iterator
, (void**) &child
, (const void**) ret_suffix
);
1013 _public_
int sd_device_new_child(sd_device
**ret
, sd_device
*device
, const char *suffix
) {
1014 _cleanup_free_
char *path
= NULL
;
1019 assert_return(ret
, -EINVAL
);
1020 assert_return(device
, -EINVAL
);
1021 assert_return(suffix
, -EINVAL
);
1023 if (!path_is_safe(suffix
))
1026 /* If we have already enumerated children, try to find the child from the cache. */
1027 child
= hashmap_get(device
->children
, suffix
);
1029 *ret
= sd_device_ref(child
);
1033 r
= sd_device_get_syspath(device
, &s
);
1037 path
= path_join(s
, suffix
);
1041 return sd_device_new_from_syspath(ret
, path
);
1044 static int device_new_from_child(sd_device
**ret
, sd_device
*child
) {
1045 _cleanup_free_
char *path
= NULL
;
1046 const char *syspath
;
1052 r
= sd_device_get_syspath(child
, &syspath
);
1057 _cleanup_free_
char *p
= NULL
;
1059 r
= path_extract_directory(path
?: syspath
, &p
);
1063 if (path_equal(p
, "/sys"))
1066 r
= sd_device_new_from_syspath(ret
, p
);
1070 free_and_replace(path
, p
);
1074 _public_
int sd_device_get_parent(sd_device
*child
, sd_device
**ret
) {
1077 assert_return(child
, -EINVAL
);
1079 if (!child
->parent_set
) {
1080 r
= device_new_from_child(&child
->parent
, child
);
1081 if (r
< 0 && r
!= -ENODEV
)
1084 child
->parent_set
= true;
1091 *ret
= child
->parent
;
1095 int device_set_subsystem(sd_device
*device
, const char *subsystem
) {
1096 _cleanup_free_
char *s
= NULL
;
1102 s
= strdup(subsystem
);
1107 r
= device_add_property_internal(device
, "SUBSYSTEM", s
);
1111 device
->subsystem_set
= true;
1112 return free_and_replace(device
->subsystem
, s
);
1115 int device_set_drivers_subsystem(sd_device
*device
) {
1116 _cleanup_free_
char *subsystem
= NULL
;
1117 const char *devpath
, *drivers
, *p
;
1122 r
= sd_device_get_devpath(device
, &devpath
);
1126 drivers
= strstr(devpath
, "/drivers/");
1128 drivers
= endswith(devpath
, "/drivers");
1132 /* Find the path component immediately before the "/drivers/" string */
1133 r
= path_find_last_component(devpath
, /* accept_dot_dot= */ false, &drivers
, &p
);
1139 subsystem
= strndup(p
, r
);
1143 r
= device_set_subsystem(device
, "drivers");
1147 return free_and_replace(device
->driver_subsystem
, subsystem
);
1150 _public_
int sd_device_get_subsystem(sd_device
*device
, const char **ret
) {
1153 assert_return(device
, -EINVAL
);
1155 if (!device
->subsystem_set
) {
1156 _cleanup_free_
char *subsystem
= NULL
;
1157 const char *syspath
;
1160 r
= sd_device_get_syspath(device
, &syspath
);
1164 /* read 'subsystem' link */
1165 path
= strjoina(syspath
, "/subsystem");
1166 r
= readlink_value(path
, &subsystem
);
1167 if (r
< 0 && r
!= -ENOENT
)
1168 return log_device_debug_errno(device
, r
,
1169 "sd-device: Failed to read subsystem for %s: %m",
1173 r
= device_set_subsystem(device
, subsystem
);
1174 /* use implicit names */
1175 else if (!isempty(path_startswith(device
->devpath
, "/module/")))
1176 r
= device_set_subsystem(device
, "module");
1177 else if (strstr(syspath
, "/drivers/") || endswith(syspath
, "/drivers"))
1178 r
= device_set_drivers_subsystem(device
);
1179 else if (!isempty(PATH_STARTSWITH_SET(device
->devpath
, "/class/", "/bus/")))
1180 r
= device_set_subsystem(device
, "subsystem");
1182 device
->subsystem_set
= true;
1186 return log_device_debug_errno(device
, r
,
1187 "sd-device: Failed to set subsystem for %s: %m",
1191 if (!device
->subsystem
)
1195 *ret
= device
->subsystem
;
1199 _public_
int sd_device_get_devtype(sd_device
*device
, const char **devtype
) {
1202 assert_return(device
, -EINVAL
);
1204 r
= device_read_uevent_file(device
);
1208 if (!device
->devtype
)
1212 *devtype
= device
->devtype
;
1214 return !!device
->devtype
;
1217 _public_
int sd_device_get_parent_with_subsystem_devtype(sd_device
*device
, const char *subsystem
, const char *devtype
, sd_device
**ret
) {
1220 assert_return(device
, -EINVAL
);
1221 assert_return(subsystem
, -EINVAL
);
1224 r
= sd_device_get_parent(device
, &device
);
1228 if (!device_in_subsystem(device
, subsystem
))
1231 if (devtype
&& !device_is_devtype(device
, devtype
))
1240 _public_
int sd_device_get_devnum(sd_device
*device
, dev_t
*devnum
) {
1243 assert_return(device
, -EINVAL
);
1245 r
= device_read_uevent_file(device
);
1249 if (major(device
->devnum
) <= 0)
1253 *devnum
= device
->devnum
;
1258 int device_set_driver(sd_device
*device
, const char *driver
) {
1259 _cleanup_free_
char *d
= NULL
;
1270 r
= device_add_property_internal(device
, "DRIVER", d
);
1274 device
->driver_set
= true;
1275 return free_and_replace(device
->driver
, d
);
1278 _public_
int sd_device_get_driver(sd_device
*device
, const char **ret
) {
1279 assert_return(device
, -EINVAL
);
1281 if (!device
->driver_set
) {
1282 _cleanup_free_
char *driver
= NULL
;
1283 const char *syspath
;
1287 r
= sd_device_get_syspath(device
, &syspath
);
1291 path
= strjoina(syspath
, "/driver");
1292 r
= readlink_value(path
, &driver
);
1293 if (r
< 0 && r
!= -ENOENT
)
1294 return log_device_debug_errno(device
, r
,
1295 "sd-device: readlink(\"%s\") failed: %m", path
);
1297 r
= device_set_driver(device
, driver
);
1299 return log_device_debug_errno(device
, r
,
1300 "sd-device: Failed to set driver \"%s\": %m", driver
);
1303 if (!device
->driver
)
1307 *ret
= device
->driver
;
1311 _public_
int sd_device_get_devpath(sd_device
*device
, const char **ret
) {
1312 assert_return(device
, -EINVAL
);
1314 assert(device
->devpath
);
1315 assert(device
->devpath
[0] == '/');
1318 *ret
= device
->devpath
;
1323 _public_
int sd_device_get_devname(sd_device
*device
, const char **devname
) {
1326 assert_return(device
, -EINVAL
);
1328 r
= device_read_uevent_file(device
);
1332 if (!device
->devname
)
1335 assert(!isempty(path_startswith(device
->devname
, "/dev/")));
1338 *devname
= device
->devname
;
1342 static int device_set_sysname_and_sysnum(sd_device
*device
) {
1343 _cleanup_free_
char *sysname
= NULL
;
1349 r
= path_extract_filename(device
->devpath
, &sysname
);
1352 if (r
== O_DIRECTORY
)
1355 /* some devices have '!' in their name, change that to '/' */
1356 string_replace_char(sysname
, '!', '/');
1358 n
= strspn_from_end(sysname
, DIGITS
);
1359 len
= strlen(sysname
);
1362 n
= 0; /* Do not set sysnum for number only sysname. */
1364 device
->sysnum
= n
> 0 ? sysname
+ len
- n
: NULL
;
1365 return free_and_replace(device
->sysname
, sysname
);
1368 _public_
int sd_device_get_sysname(sd_device
*device
, const char **ret
) {
1371 assert_return(device
, -EINVAL
);
1373 if (!device
->sysname
) {
1374 r
= device_set_sysname_and_sysnum(device
);
1380 *ret
= device
->sysname
;
1384 _public_
int sd_device_get_sysnum(sd_device
*device
, const char **ret
) {
1387 assert_return(device
, -EINVAL
);
1389 if (!device
->sysname
) {
1390 r
= device_set_sysname_and_sysnum(device
);
1395 if (!device
->sysnum
)
1399 *ret
= device
->sysnum
;
1403 _public_
int sd_device_get_action(sd_device
*device
, sd_device_action_t
*ret
) {
1404 assert_return(device
, -EINVAL
);
1406 if (device
->action
< 0)
1410 *ret
= device
->action
;
1415 _public_
int sd_device_get_seqnum(sd_device
*device
, uint64_t *ret
) {
1416 assert_return(device
, -EINVAL
);
1418 if (device
->seqnum
== 0)
1422 *ret
= device
->seqnum
;
1427 _public_
int sd_device_get_diskseq(sd_device
*device
, uint64_t *ret
) {
1430 assert_return(device
, -EINVAL
);
1432 r
= device_read_uevent_file(device
);
1436 if (device
->diskseq
== 0)
1440 *ret
= device
->diskseq
;
1445 static bool is_valid_tag(const char *tag
) {
1448 return in_charset(tag
, ALPHANUMERICAL
"-_") && filename_is_valid(tag
);
1451 int device_add_tag(sd_device
*device
, const char *tag
, bool both
) {
1457 if (!is_valid_tag(tag
))
1460 /* Definitely add to the "all" list of tags (i.e. the sticky list) */
1461 added
= set_put_strdup(&device
->all_tags
, tag
);
1465 /* And optionally, also add it to the current list of tags */
1467 r
= set_put_strdup(&device
->current_tags
, tag
);
1470 (void) set_remove(device
->all_tags
, tag
);
1476 device
->tags_generation
++;
1477 device
->property_tags_outdated
= true;
1482 int device_add_devlink(sd_device
*device
, const char *devlink
) {
1489 r
= mangle_devname(devlink
, &p
);
1493 r
= set_ensure_consume(&device
->devlinks
, &path_hash_ops_free
, p
);
1497 device
->devlinks_generation
++;
1498 device
->property_devlinks_outdated
= true;
1500 return r
; /* return 1 when newly added, 0 when already exists */
1503 int device_remove_devlink(sd_device
*device
, const char *devlink
) {
1504 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
1510 r
= mangle_devname(devlink
, &p
);
1514 s
= set_remove(device
->devlinks
, p
);
1516 return 0; /* does not exist */
1518 device
->devlinks_generation
++;
1519 device
->property_devlinks_outdated
= true;
1520 return 1; /* removed */
1523 bool device_has_devlink(sd_device
*device
, const char *devlink
) {
1527 return set_contains(device
->devlinks
, devlink
);
1530 static int device_add_property_internal_from_string(sd_device
*device
, const char *str
) {
1531 _cleanup_free_
char *key
= NULL
;
1542 value
= strchr(key
, '=');
1548 if (isempty(++value
))
1551 /* Add the property to both sd_device::properties and sd_device::properties_db,
1552 * as this is called by only handle_db_line(). */
1553 r
= device_add_property_aux(device
, key
, value
, false);
1557 return device_add_property_aux(device
, key
, value
, true);
1560 int device_set_usec_initialized(sd_device
*device
, usec_t when
) {
1561 char s
[DECIMAL_STR_MAX(usec_t
)];
1566 xsprintf(s
, USEC_FMT
, when
);
1568 r
= device_add_property_internal(device
, "USEC_INITIALIZED", s
);
1572 device
->usec_initialized
= when
;
1576 static int handle_db_line(sd_device
*device
, char key
, const char *value
) {
1583 case 'G': /* Any tag */
1584 case 'Q': /* Current tag */
1585 return device_add_tag(device
, value
, key
== 'Q');
1590 path
= strjoina("/dev/", value
);
1591 return device_add_devlink(device
, path
);
1594 return device_add_property_internal_from_string(device
, value
);
1599 r
= safe_atou64(value
, &t
);
1603 return device_set_usec_initialized(device
, t
);
1606 return safe_atoi(value
, &device
->devlink_priority
);
1609 /* Deprecated. Previously, watch handle is both saved in database and /run/udev/watch.
1610 * However, the handle saved in database may not be updated when the handle is updated
1611 * or removed. Moreover, it is not necessary to store the handle within the database,
1612 * as its value becomes meaningless when udevd is restarted. */
1616 return safe_atou(value
, &device
->database_version
);
1619 log_device_debug(device
, "sd-device: Unknown key '%c' in device db, ignoring", key
);
1624 int device_get_device_id(sd_device
*device
, const char **ret
) {
1628 if (!device
->device_id
) {
1629 _cleanup_free_
char *id
= NULL
;
1630 const char *subsystem
;
1634 r
= sd_device_get_subsystem(device
, &subsystem
);
1638 if (sd_device_get_devnum(device
, &devnum
) >= 0) {
1639 /* use dev_t — b259:131072, c254:0 */
1640 if (asprintf(&id
, "%c" DEVNUM_FORMAT_STR
,
1641 streq(subsystem
, "block") ? 'b' : 'c',
1642 DEVNUM_FORMAT_VAL(devnum
)) < 0)
1644 } else if (sd_device_get_ifindex(device
, &ifindex
) >= 0) {
1645 /* use netdev ifindex — n3 */
1646 if (asprintf(&id
, "n%u", (unsigned) ifindex
) < 0)
1649 _cleanup_free_
char *sysname
= NULL
;
1651 /* use $subsys:$sysname — pci:0000:00:1f.2
1652 * sd_device_get_sysname() has '!' translated, get it from devpath */
1653 r
= path_extract_filename(device
->devpath
, &sysname
);
1656 if (r
== O_DIRECTORY
)
1659 if (streq(subsystem
, "drivers")) {
1660 /* the 'drivers' pseudo-subsystem is special, and needs the real
1661 * subsystem encoded as well */
1662 assert(device
->driver_subsystem
);
1663 id
= strjoin("+drivers:", device
->driver_subsystem
, ":", sysname
);
1665 id
= strjoin("+", subsystem
, ":", sysname
);
1670 if (!filename_is_valid(id
))
1673 device
->device_id
= TAKE_PTR(id
);
1676 *ret
= device
->device_id
;
1680 int device_read_db_internal_filename(sd_device
*device
, const char *filename
) {
1681 _cleanup_free_
char *db
= NULL
;
1684 char key
= '\0'; /* Unnecessary initialization to appease gcc-12.0.0-0.4.fc36 */
1698 r
= read_full_file(filename
, &db
, &db_len
);
1703 return log_device_debug_errno(device
, r
, "sd-device: Failed to read db '%s': %m", filename
);
1706 /* devices with a database entry are initialized */
1707 device
->is_initialized
= true;
1709 device
->db_loaded
= true;
1711 for (size_t i
= 0; i
< db_len
; i
++)
1714 if (!strchr(NEWLINE
, db
[i
])) {
1723 log_device_debug(device
, "sd-device: Invalid db entry with key '%c', ignoring", key
);
1725 state
= INVALID_LINE
;
1740 if (strchr(NEWLINE
, db
[i
]))
1745 if (strchr(NEWLINE
, db
[i
])) {
1747 r
= handle_db_line(device
, key
, value
);
1749 log_device_debug_errno(device
, r
, "sd-device: Failed to handle db entry '%c:%s', ignoring: %m",
1757 return log_device_debug_errno(device
, SYNTHETIC_ERRNO(EINVAL
), "sd-device: invalid db syntax.");
1763 _public_
int sd_device_get_is_initialized(sd_device
*device
) {
1766 assert_return(device
, -EINVAL
);
1768 r
= device_read_db(device
);
1770 /* The device may be already removed or renamed. */
1775 return device
->is_initialized
;
1778 _public_
int sd_device_get_usec_initialized(sd_device
*device
, uint64_t *ret
) {
1781 assert_return(device
, -EINVAL
);
1783 r
= sd_device_get_is_initialized(device
);
1789 if (device
->usec_initialized
== 0)
1793 *ret
= device
->usec_initialized
;
1798 _public_
int sd_device_get_usec_since_initialized(sd_device
*device
, uint64_t *ret
) {
1802 assert_return(device
, -EINVAL
);
1804 r
= sd_device_get_usec_initialized(device
, &ts
);
1808 now_ts
= now(CLOCK_MONOTONIC
);
1814 *ret
= usec_sub_unsigned(now_ts
, ts
);
1819 _public_
const char *sd_device_get_tag_first(sd_device
*device
) {
1822 assert_return(device
, NULL
);
1824 (void) device_read_db(device
);
1826 device
->all_tags_iterator_generation
= device
->tags_generation
;
1827 device
->all_tags_iterator
= ITERATOR_FIRST
;
1829 (void) set_iterate(device
->all_tags
, &device
->all_tags_iterator
, &v
);
1833 _public_
const char *sd_device_get_tag_next(sd_device
*device
) {
1836 assert_return(device
, NULL
);
1838 (void) device_read_db(device
);
1840 if (device
->all_tags_iterator_generation
!= device
->tags_generation
)
1843 (void) set_iterate(device
->all_tags
, &device
->all_tags_iterator
, &v
);
1847 static bool device_database_supports_current_tags(sd_device
*device
) {
1850 (void) device_read_db(device
);
1852 /* The current tags (saved in Q field) feature is implemented in database version 1.
1853 * If the database version is 0, then the tags (NOT current tags, saved in G field) are not
1854 * sticky. Thus, we can safely bypass the operations for the current tags (Q) to tags (G). */
1856 return device
->database_version
>= 1;
1859 _public_
const char *sd_device_get_current_tag_first(sd_device
*device
) {
1862 assert_return(device
, NULL
);
1864 if (!device_database_supports_current_tags(device
))
1865 return sd_device_get_tag_first(device
);
1867 (void) device_read_db(device
);
1869 device
->current_tags_iterator_generation
= device
->tags_generation
;
1870 device
->current_tags_iterator
= ITERATOR_FIRST
;
1872 (void) set_iterate(device
->current_tags
, &device
->current_tags_iterator
, &v
);
1876 _public_
const char *sd_device_get_current_tag_next(sd_device
*device
) {
1879 assert_return(device
, NULL
);
1881 if (!device_database_supports_current_tags(device
))
1882 return sd_device_get_tag_next(device
);
1884 (void) device_read_db(device
);
1886 if (device
->current_tags_iterator_generation
!= device
->tags_generation
)
1889 (void) set_iterate(device
->current_tags
, &device
->current_tags_iterator
, &v
);
1893 _public_
const char *sd_device_get_devlink_first(sd_device
*device
) {
1896 assert_return(device
, NULL
);
1898 (void) device_read_db(device
);
1900 device
->devlinks_iterator_generation
= device
->devlinks_generation
;
1901 device
->devlinks_iterator
= ITERATOR_FIRST
;
1903 (void) set_iterate(device
->devlinks
, &device
->devlinks_iterator
, &v
);
1907 _public_
const char *sd_device_get_devlink_next(sd_device
*device
) {
1910 assert_return(device
, NULL
);
1912 (void) device_read_db(device
);
1914 if (device
->devlinks_iterator_generation
!= device
->devlinks_generation
)
1917 (void) set_iterate(device
->devlinks
, &device
->devlinks_iterator
, &v
);
1921 int device_properties_prepare(sd_device
*device
) {
1926 r
= device_read_uevent_file(device
);
1930 r
= device_read_db(device
);
1934 if (device
->property_devlinks_outdated
) {
1935 _cleanup_free_
char *devlinks
= NULL
;
1937 r
= set_strjoin(device
->devlinks
, " ", false, &devlinks
);
1941 if (!isempty(devlinks
)) {
1942 r
= device_add_property_internal(device
, "DEVLINKS", devlinks
);
1947 device
->property_devlinks_outdated
= false;
1950 if (device
->property_tags_outdated
) {
1951 _cleanup_free_
char *tags
= NULL
;
1953 r
= set_strjoin(device
->all_tags
, ":", true, &tags
);
1957 if (!isempty(tags
)) {
1958 r
= device_add_property_internal(device
, "TAGS", tags
);
1964 r
= set_strjoin(device
->current_tags
, ":", true, &tags
);
1968 if (!isempty(tags
)) {
1969 r
= device_add_property_internal(device
, "CURRENT_TAGS", tags
);
1974 device
->property_tags_outdated
= false;
1980 _public_
const char *sd_device_get_property_first(sd_device
*device
, const char **_value
) {
1984 assert_return(device
, NULL
);
1986 r
= device_properties_prepare(device
);
1990 device
->properties_iterator_generation
= device
->properties_generation
;
1991 device
->properties_iterator
= ITERATOR_FIRST
;
1993 (void) ordered_hashmap_iterate(device
->properties
, &device
->properties_iterator
, (void**)_value
, (const void**)&key
);
1997 _public_
const char *sd_device_get_property_next(sd_device
*device
, const char **_value
) {
2001 assert_return(device
, NULL
);
2003 r
= device_properties_prepare(device
);
2007 if (device
->properties_iterator_generation
!= device
->properties_generation
)
2010 (void) ordered_hashmap_iterate(device
->properties
, &device
->properties_iterator
, (void**)_value
, (const void**)&key
);
2014 static int device_sysattrs_read_all_internal(sd_device
*device
, const char *subdir
, Set
**stack
) {
2015 _cleanup_closedir_
DIR *dir
= NULL
;
2021 r
= device_opendir(device
, subdir
, &dir
);
2022 if (r
== -ENOENT
&& subdir
)
2023 return 0; /* Maybe, this is a child device, and is already removed. */
2028 if (faccessat(dirfd(dir
), "uevent", F_OK
, 0) >= 0)
2029 return 0; /* this is a child device, skipping */
2030 if (errno
!= ENOENT
) {
2031 log_device_debug_errno(device
, errno
,
2032 "sd-device: Failed to access %s/uevent, ignoring sub-directory %s: %m",
2038 FOREACH_DIRENT_ALL(de
, dir
, return -errno
) {
2039 _cleanup_free_
char *p
= NULL
;
2040 struct stat statbuf
;
2042 if (dot_or_dot_dot(de
->d_name
))
2045 /* only handle symlinks, regular files, and directories */
2046 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
, DT_DIR
))
2050 p
= path_join(subdir
, de
->d_name
);
2055 if (de
->d_type
== DT_DIR
) {
2056 /* push the sub-directory into the stack, and read it later. */
2058 r
= set_ensure_consume(stack
, &path_hash_ops_free
, TAKE_PTR(p
));
2060 r
= set_put_strdup_full(stack
, &path_hash_ops_free
, de
->d_name
);
2067 if (fstatat(dirfd(dir
), de
->d_name
, &statbuf
, AT_SYMLINK_NOFOLLOW
) < 0)
2070 if ((statbuf
.st_mode
& (S_IRUSR
| S_IWUSR
)) == 0)
2074 r
= set_ensure_consume(&device
->sysattrs
, &path_hash_ops_free
, TAKE_PTR(p
));
2076 r
= set_put_strdup_full(&device
->sysattrs
, &path_hash_ops_free
, de
->d_name
);
2084 static int device_sysattrs_read_all(sd_device
*device
) {
2085 _cleanup_set_free_ Set
*stack
= NULL
;
2090 if (device
->sysattrs_read
)
2093 r
= device_sysattrs_read_all_internal(device
, NULL
, &stack
);
2098 _cleanup_free_
char *subdir
= NULL
;
2100 subdir
= set_steal_first(stack
);
2104 r
= device_sysattrs_read_all_internal(device
, subdir
, &stack
);
2109 device
->sysattrs_read
= true;
2114 _public_
const char *sd_device_get_sysattr_first(sd_device
*device
) {
2118 assert_return(device
, NULL
);
2120 if (!device
->sysattrs_read
) {
2121 r
= device_sysattrs_read_all(device
);
2128 device
->sysattrs_iterator
= ITERATOR_FIRST
;
2130 (void) set_iterate(device
->sysattrs
, &device
->sysattrs_iterator
, &v
);
2134 _public_
const char *sd_device_get_sysattr_next(sd_device
*device
) {
2137 assert_return(device
, NULL
);
2139 if (!device
->sysattrs_read
)
2142 (void) set_iterate(device
->sysattrs
, &device
->sysattrs_iterator
, &v
);
2146 _public_
int sd_device_has_tag(sd_device
*device
, const char *tag
) {
2147 assert_return(device
, -EINVAL
);
2148 assert_return(tag
, -EINVAL
);
2150 (void) device_read_db(device
);
2152 return set_contains(device
->all_tags
, tag
);
2155 _public_
int sd_device_has_current_tag(sd_device
*device
, const char *tag
) {
2156 assert_return(device
, -EINVAL
);
2157 assert_return(tag
, -EINVAL
);
2159 if (!device_database_supports_current_tags(device
))
2160 return sd_device_has_tag(device
, tag
);
2162 (void) device_read_db(device
);
2164 return set_contains(device
->current_tags
, tag
);
2167 _public_
int sd_device_get_property_value(sd_device
*device
, const char *key
, const char **ret_value
) {
2171 assert_return(device
, -EINVAL
);
2172 assert_return(key
, -EINVAL
);
2174 r
= device_properties_prepare(device
);
2178 value
= ordered_hashmap_get(device
->properties
, key
);
2187 int device_get_property_bool(sd_device
*device
, const char *key
) {
2194 r
= sd_device_get_property_value(device
, key
, &value
);
2198 return parse_boolean(value
);
2201 int device_get_property_int(sd_device
*device
, const char *key
, int *ret
) {
2208 r
= sd_device_get_property_value(device
, key
, &value
);
2212 r
= safe_atoi(value
, &v
);
2221 _public_
int sd_device_get_trigger_uuid(sd_device
*device
, sd_id128_t
*ret
) {
2226 assert_return(device
, -EINVAL
);
2228 /* Retrieves the UUID attached to a uevent when triggering it from userspace via
2229 * sd_device_trigger_with_uuid() or an equivalent interface. Returns -ENOENT if the record is not
2230 * caused by a synthetic event and -ENODATA if it was but no UUID was specified */
2232 r
= sd_device_get_property_value(device
, "SYNTH_UUID", &s
);
2236 if (streq(s
, "0")) /* SYNTH_UUID=0 is set whenever a device is triggered by userspace without specifying a UUID */
2239 r
= sd_id128_from_string(s
, &id
);
2249 void device_clear_sysattr_cache(sd_device
*device
) {
2250 device
->sysattr_values
= hashmap_free(device
->sysattr_values
);
2253 int device_cache_sysattr_value(sd_device
*device
, const char *key
, char *value
) {
2254 _unused_ _cleanup_free_
char *old_value
= NULL
;
2255 _cleanup_free_
char *new_key
= NULL
;
2261 /* This takes the reference of the input value. The input value may be NULL.
2262 * This replaces the value if it already exists. */
2264 /* First, remove the old cache entry. So, we do not need to clear cache on error. */
2265 old_value
= hashmap_remove2(device
->sysattr_values
, key
, (void **) &new_key
);
2267 new_key
= strdup(key
);
2272 r
= hashmap_ensure_put(&device
->sysattr_values
, &path_hash_ops_free_free
, new_key
, value
);
2281 int device_get_cached_sysattr_value(sd_device
*device
, const char *key
, const char **ret_value
) {
2282 const char *k
= NULL
, *value
;
2287 value
= hashmap_get2(device
->sysattr_values
, key
, (void **) &k
);
2289 return -ESTALE
; /* We have not read the attribute. */
2291 return -ENOENT
; /* We have looked up the attribute before and it did not exist. */
2297 /* We cache all sysattr lookups. If an attribute does not exist, it is stored
2298 * with a NULL value in the cache, otherwise the returned string is stored */
2299 _public_
int sd_device_get_sysattr_value(sd_device
*device
, const char *sysattr
, const char **ret_value
) {
2300 _cleanup_free_
char *value
= NULL
, *path
= NULL
;
2301 const char *syspath
;
2302 struct stat statbuf
;
2305 assert_return(device
, -EINVAL
);
2306 assert_return(sysattr
, -EINVAL
);
2308 /* look for possibly already cached result */
2309 r
= device_get_cached_sysattr_value(device
, sysattr
, ret_value
);
2313 r
= sd_device_get_syspath(device
, &syspath
);
2317 path
= path_join(syspath
, sysattr
);
2321 if (lstat(path
, &statbuf
) < 0) {
2326 /* remember that we could not access the sysattr */
2327 k
= device_cache_sysattr_value(device
, sysattr
, NULL
);
2329 log_device_debug_errno(device
, k
,
2330 "sd-device: failed to cache attribute '%s' with NULL, ignoring: %m",
2334 } else if (S_ISLNK(statbuf
.st_mode
)) {
2335 /* Some core links return only the last element of the target path,
2336 * these are just values, the paths should not be exposed. */
2337 if (STR_IN_SET(sysattr
, "driver", "subsystem", "module")) {
2338 r
= readlink_value(path
, &value
);
2343 } else if (S_ISDIR(statbuf
.st_mode
))
2344 /* skip directories */
2346 else if (!(statbuf
.st_mode
& S_IRUSR
))
2347 /* skip non-readable files */
2352 /* Read attribute value, Some attributes contain embedded '\0'. So, it is necessary to
2353 * also get the size of the result. See issue #20025. */
2354 r
= read_full_virtual_file(path
, &value
, &size
);
2358 /* drop trailing newlines */
2359 while (size
> 0 && strchr(NEWLINE
, value
[--size
]))
2363 /* Unfortunately, we need to return 'const char*' instead of 'char*'. Hence, failure in caching
2364 * sysattr value is critical unlike the other places. */
2365 r
= device_cache_sysattr_value(device
, sysattr
, value
);
2367 log_device_debug_errno(device
, r
,
2368 "sd-device: failed to cache attribute '%s' with '%s'%s: %m",
2369 sysattr
, value
, ret_value
? "" : ", ignoring");
2383 int device_get_sysattr_int(sd_device
*device
, const char *sysattr
, int *ret_value
) {
2387 r
= sd_device_get_sysattr_value(device
, sysattr
, &value
);
2392 r
= safe_atoi(value
, &v
);
2394 return log_device_debug_errno(device
, r
, "Failed to parse '%s' attribute: %m", sysattr
);
2398 /* We return "true" if the value is positive. */
2402 int device_get_sysattr_unsigned(sd_device
*device
, const char *sysattr
, unsigned *ret_value
) {
2406 r
= sd_device_get_sysattr_value(device
, sysattr
, &value
);
2411 r
= safe_atou(value
, &v
);
2413 return log_device_debug_errno(device
, r
, "Failed to parse '%s' attribute: %m", sysattr
);
2417 /* We return "true" if the value is positive. */
2421 int device_get_sysattr_u32(sd_device
*device
, const char *sysattr
, uint32_t *ret_value
) {
2425 r
= sd_device_get_sysattr_value(device
, sysattr
, &value
);
2430 r
= safe_atou32(value
, &v
);
2432 return log_device_debug_errno(device
, r
, "Failed to parse '%s' attribute: %m", sysattr
);
2436 /* We return "true" if the value is positive. */
2440 int device_get_sysattr_bool(sd_device
*device
, const char *sysattr
) {
2447 r
= sd_device_get_sysattr_value(device
, sysattr
, &value
);
2451 return parse_boolean(value
);
2454 static void device_remove_cached_sysattr_value(sd_device
*device
, const char *_key
) {
2455 _cleanup_free_
char *key
= NULL
;
2460 free(hashmap_remove2(device
->sysattr_values
, _key
, (void **) &key
));
2463 _public_
int sd_device_set_sysattr_value(sd_device
*device
, const char *sysattr
, const char *_value
) {
2464 _cleanup_free_
char *value
= NULL
, *path
= NULL
;
2465 const char *syspath
;
2469 assert_return(device
, -EINVAL
);
2470 assert_return(sysattr
, -EINVAL
);
2472 /* Set the attribute and save it in the cache. */
2475 /* If input value is NULL, then clear cache and not write anything. */
2476 device_remove_cached_sysattr_value(device
, sysattr
);
2480 r
= sd_device_get_syspath(device
, &syspath
);
2484 path
= path_join(syspath
, sysattr
);
2488 len
= strlen(_value
);
2490 /* drop trailing newlines */
2491 while (len
> 0 && strchr(NEWLINE
, _value
[len
- 1]))
2494 /* value length is limited to 4k */
2498 value
= strndup(_value
, len
);
2502 r
= write_string_file(path
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
| WRITE_STRING_FILE_NOFOLLOW
);
2504 /* On failure, clear cache entry, as we do not know how it fails. */
2505 device_remove_cached_sysattr_value(device
, sysattr
);
2509 /* Do not cache action string written into uevent file. */
2510 if (streq(sysattr
, "uevent"))
2513 r
= device_cache_sysattr_value(device
, sysattr
, value
);
2515 log_device_debug_errno(device
, r
,
2516 "sd-device: failed to cache attribute '%s' with '%s', ignoring: %m",
2524 _public_
int sd_device_set_sysattr_valuef(sd_device
*device
, const char *sysattr
, const char *format
, ...) {
2525 _cleanup_free_
char *value
= NULL
;
2529 assert_return(device
, -EINVAL
);
2530 assert_return(sysattr
, -EINVAL
);
2533 device_remove_cached_sysattr_value(device
, sysattr
);
2537 va_start(ap
, format
);
2538 r
= vasprintf(&value
, format
, ap
);
2544 return sd_device_set_sysattr_value(device
, sysattr
, value
);
2547 _public_
int sd_device_trigger(sd_device
*device
, sd_device_action_t action
) {
2550 assert_return(device
, -EINVAL
);
2552 s
= device_action_to_string(action
);
2556 /* This uses the simple no-UUID interface of kernel < 4.13 */
2557 return sd_device_set_sysattr_value(device
, "uevent", s
);
2560 _public_
int sd_device_trigger_with_uuid(
2562 sd_device_action_t action
,
2563 sd_id128_t
*ret_uuid
) {
2569 assert_return(device
, -EINVAL
);
2571 /* If no one wants to know the UUID, use the simple interface from pre-4.13 times */
2573 return sd_device_trigger(device
, action
);
2575 s
= device_action_to_string(action
);
2579 r
= sd_id128_randomize(&u
);
2583 j
= strjoina(s
, " ", SD_ID128_TO_UUID_STRING(u
));
2585 r
= sd_device_set_sysattr_value(device
, "uevent", j
);
2593 _public_
int sd_device_open(sd_device
*device
, int flags
) {
2594 _cleanup_close_
int fd
= -EBADF
, fd2
= -EBADF
;
2595 const char *devname
;
2596 uint64_t q
, diskseq
= 0;
2601 assert_return(device
, -EINVAL
);
2602 assert_return(FLAGS_SET(flags
, O_PATH
) || !FLAGS_SET(flags
, O_NOFOLLOW
), -EINVAL
);
2604 r
= sd_device_get_devname(device
, &devname
);
2610 r
= sd_device_get_devnum(device
, &devnum
);
2616 fd
= open(devname
, FLAGS_SET(flags
, O_PATH
) ? flags
: O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
2620 if (fstat(fd
, &st
) < 0)
2623 if (st
.st_rdev
!= devnum
)
2626 if (device_in_subsystem(device
, "block") ? !S_ISBLK(st
.st_mode
) : !S_ISCHR(st
.st_mode
))
2629 /* If flags has O_PATH, then we cannot check diskseq. Let's return earlier. */
2630 if (FLAGS_SET(flags
, O_PATH
))
2633 /* If the device is not initialized, then we cannot determine if we should check diskseq through
2634 * ID_IGNORE_DISKSEQ property. Let's skip to check diskseq in that case. */
2635 r
= sd_device_get_is_initialized(device
);
2639 r
= device_get_property_bool(device
, "ID_IGNORE_DISKSEQ");
2640 if (r
< 0 && r
!= -ENOENT
)
2643 r
= sd_device_get_diskseq(device
, &diskseq
);
2644 if (r
< 0 && r
!= -ENOENT
)
2649 fd2
= fd_reopen(fd
, flags
);
2654 return TAKE_FD(fd2
);
2656 r
= fd_get_diskseq(fd2
, &q
);
2663 return TAKE_FD(fd2
);
2666 int device_opendir(sd_device
*device
, const char *subdir
, DIR **ret
) {
2667 _cleanup_closedir_
DIR *d
= NULL
;
2668 _cleanup_free_
char *path
= NULL
;
2669 const char *syspath
;
2675 r
= sd_device_get_syspath(device
, &syspath
);
2680 if (!path_is_safe(subdir
))
2683 path
= path_join(syspath
, subdir
);
2688 d
= opendir(path
?: syspath
);