Debian Codegraph @

src/libsystemd/sd-device/sd-device.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/magic.h>
4 #include <unistd.h>
5
6 #include "sd-device.h"
7 #include "sd-id128.h"
8
9 #include "alloc-util.h"
10 #include "chase.h"
11 #include "device-internal.h"
12 #include "device-private.h"
13 #include "device-util.h"
14 #include "devnum-util.h"
15 #include "dirent-util.h"
16 #include "env-util.h"
17 #include "errno-util.h"
18 #include "escape.h"
19 #include "extract-word.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "fs-util.h"
23 #include "hashmap.h"
24 #include "netlink-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "set.h"
28 #include "socket-util.h"
29 #include "stat-util.h"
30 #include "stdio-util.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "time-util.h"
34
35 int device_new_aux(sd_device **ret) {
36 sd_device *device;
37
38 assert(ret);
39
40 device = new(sd_device, 1);
41 if (!device)
42 return -ENOMEM;
43
44 *device = (sd_device) {
45 .n_ref = 1,
46 .devmode = MODE_INVALID,
47 .devuid = UID_INVALID,
48 .devgid = GID_INVALID,
49 .action = _SD_DEVICE_ACTION_INVALID,
50 .database_version = OLDEST_UDEV_DATABASE_VERSION,
51 };
52
53 *ret = device;
54 return 0;
55 }
56
57 static sd_device* device_free(sd_device *device) {
58 assert(device);
59
60 sd_device_unref(device->parent);
61 free(device->syspath);
62 free(device->sysname);
63 free(device->devtype);
64 free(device->devname);
65 free(device->subsystem);
66 free(device->driver_subsystem);
67 free(device->driver);
68 free(device->device_id);
69 free(device->properties_strv);
70 free(device->properties_nulstr);
71
72 ordered_hashmap_free(device->properties);
73 ordered_hashmap_free(device->properties_db);
74 hashmap_free(device->sysattr_values);
75 set_free(device->sysattrs);
76 set_free(device->all_tags);
77 set_free(device->current_tags);
78 set_free(device->devlinks);
79 hashmap_free(device->children);
80
81 return mfree(device);
82 }
83
84 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_device, sd_device, device_free);
85
86 static bool property_is_valid(const char *key, const char *value) {
87 /* Device properties may be saved to database file, then may be parsed from the file. When if a
88 * property contains spurious characters, then the parser may be confused. Let's refuse spurious
89 * properties, even if it is internal, which will not be saved to database file, for consistency. */
90
91 if (isempty(key) || !in_charset(key, ALPHANUMERICAL "_."))
92 return false;
93
94 /* an empty value means unset the property, hence that's fine. */
95 if (isempty(value))
96 return true;
97
98 /* refuse invalid UTF8 and control characters */
99 return string_is_safe(value,
100 STRING_ALLOW_BACKSLASHES |
101 STRING_ALLOW_QUOTES |
102 STRING_ALLOW_GLOBS);
103 }
104
105 int device_add_property_aux(sd_device *device, const char *key, const char *value, bool db) {
106 OrderedHashmap **properties;
107
108 assert(device);
109 assert(key);
110
111 if (!property_is_valid(key, value)) {
112 if (DEBUG_LOGGING) {
113 _cleanup_free_ char *escaped_key = cescape(key),
114 *escaped_value = cescape(strempty(value));
115 log_device_debug(device, "sd-device: Refusing invalid property: %s=%s",
116 strnull(escaped_key), strnull(escaped_value));
117 }
118 return -EINVAL;
119 }
120
121 if (db)
122 properties = &device->properties_db;
123 else
124 properties = &device->properties;
125
126 if (!isempty(value)) {
127 _unused_ _cleanup_free_ char *old_value = NULL;
128 _cleanup_free_ char *new_key = NULL, *new_value = NULL, *old_key = NULL;
129 int r;
130
131 r = ordered_hashmap_ensure_allocated(properties, &string_hash_ops_free_free);
132 if (r < 0)
133 return r;
134
135 new_key = strdup(key);
136 if (!new_key)
137 return -ENOMEM;
138
139 new_value = strdup(value);
140 if (!new_value)
141 return -ENOMEM;
142
143 old_value = ordered_hashmap_get2(*properties, key, (void**) &old_key);
144
145 /* ordered_hashmap_replace() does not fail when the hashmap already has the entry. */
146 r = ordered_hashmap_replace(*properties, new_key, new_value);
147 if (r < 0)
148 return r;
149
150 TAKE_PTR(new_key);
151 TAKE_PTR(new_value);
152 } else {
153 _unused_ _cleanup_free_ char *old_value = NULL;
154 _cleanup_free_ char *old_key = NULL;
155
156 old_value = ordered_hashmap_remove2(*properties, key, (void**) &old_key);
157 }
158
159 if (!db) {
160 device->properties_generation++;
161 device->properties_buf_outdated = true;
162 }
163
164 return 0;
165 }
166
167 int device_set_syspath(sd_device *device, const char *_syspath, bool verify) {
168 _cleanup_free_ char *syspath = NULL;
169 const char *devpath;
170 int r;
171
172 assert(device);
173 assert(_syspath);
174
175 if (verify) {
176 _cleanup_close_ int fd = -EBADF;
177
178 /* The input path maybe a symlink located outside of /sys. Let's try to chase the symlink at first.
179 * The primary use case is that e.g. /proc/device-tree is a symlink to /sys/firmware/devicetree/base.
180 * By chasing symlinks in the path at first, we can call sd_device_new_from_path() with such path. */
181 r = chase(_syspath, NULL, 0, &syspath, &fd);
182 if (r == -ENOENT)
183 /* the device does not exist (any more?) */
184 return log_trace_errno(SYNTHETIC_ERRNO(ENODEV),
185 "sd-device: Device \"%s\" not found.", _syspath);
186 if (r < 0)
187 return log_debug_errno(r, "sd-device: Failed to get target of '%s': %m", _syspath);
188
189 if (!path_startswith(syspath, "/sys")) {
190 _cleanup_free_ char *real_sys = NULL, *new_syspath = NULL;
191 char *p;
192
193 /* /sys is a symlink to somewhere sysfs is mounted on? In that case, we convert the path to real sysfs to "/sys". */
194 r = chase("/sys", NULL, 0, &real_sys, NULL);
195 if (r < 0)
196 return log_debug_errno(r, "sd-device: Failed to chase symlink /sys: %m");
197
198 p = path_startswith(syspath, real_sys);
199 if (!p)
200 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV),
201 "sd-device: Canonicalized path '%s' does not starts with sysfs mount point '%s'",
202 syspath, real_sys);
203
204 new_syspath = path_join("/sys", p);
205 if (!new_syspath)
206 return log_oom_debug();
207
208 free_and_replace(syspath, new_syspath);
209 path_simplify(syspath);
210 }
211
212 if (path_startswith(syspath, "/sys/devices/")) {
213 /* For proper devices, stricter rules apply: they must have a 'uevent' file,
214 * otherwise we won't allow them */
215
216 if (faccessat(fd, "uevent", F_OK, 0) < 0) {
217 if (errno == ENOENT)
218 /* This is not a valid device. Note, this condition is quite often
219 * satisfied when enumerating devices or finding a parent device.
220 * Hence, use log_trace_errno() here. */
221 return log_trace_errno(SYNTHETIC_ERRNO(ENODEV),
222 "sd-device: the uevent file \"%s/uevent\" does not exist.", syspath);
223 if (errno == ENOTDIR)
224 /* Not actually a directory. */
225 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV),
226 "sd-device: the syspath \"%s\" is not a directory.", syspath);
227
228 return log_debug_errno(errno, "sd-device: cannot find uevent file for %s: %m", syspath);
229 }
230 } else {
231 struct stat st;
232
233 /* For everything else lax rules apply: they just need to be a directory */
234
235 if (fstat(fd, &st) < 0)
236 return log_debug_errno(errno, "sd-device: failed to check if syspath \"%s\" is a directory: %m", syspath);
237 if (!S_ISDIR(st.st_mode))
238 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV),
239 "sd-device: the syspath \"%s\" is not a directory.", syspath);
240 }
241
242 /* Only operate on sysfs, i.e. refuse going down into /sys/fs/cgroup/ or similar places where
243 * things are not arranged as kobjects in kernel, and hence don't necessarily have
244 * kobject/attribute structure. */
245 r = secure_getenv_bool("SYSTEMD_DEVICE_VERIFY_SYSFS");
246 if (r < 0 && r != -ENXIO)
247 log_debug_errno(r, "Failed to parse $SYSTEMD_DEVICE_VERIFY_SYSFS value: %m");
248 if (r != 0) {
249 r = fd_is_fs_type(fd, SYSFS_MAGIC);
250 if (r < 0)
251 return log_debug_errno(r, "sd-device: failed to check if syspath \"%s\" is backed by sysfs.", syspath);
252 if (r == 0)
253 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV),
254 "sd-device: the syspath \"%s\" is outside of sysfs, refusing.", syspath);
255 }
256 } else {
257 /* must be a subdirectory of /sys */
258 if (!path_startswith(_syspath, "/sys/"))
259 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
260 "sd-device: Syspath '%s' is not a subdirectory of /sys",
261 _syspath);
262
263 r = path_simplify_alloc(_syspath, &syspath);
264 if (r < 0)
265 return log_oom_debug();
266 }
267
268 assert_se(devpath = startswith(syspath, "/sys"));
269 if (devpath[0] != '/')
270 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV), "sd-device: \"/sys\" alone is not a valid device path.");
271
272 r = device_add_property_internal(device, "DEVPATH", devpath);
273 if (r < 0)
274 return log_debug_errno(r, "sd-device: Failed to add \"DEVPATH\" property for device \"%s\": %m", syspath);
275
276 free_and_replace(device->syspath, syspath);
277 device->devpath = devpath;
278
279 /* Unset sysname and sysnum, they will be assigned when requested. */
280 device->sysnum = NULL;
281 device->sysname = mfree(device->sysname);
282 return 0;
283 }
284
285 static int device_new_from_syspath(sd_device **ret, const char *syspath, bool strict) {
286 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
287 int r;
288
289 assert_return(ret, -EINVAL);
290 assert_return(syspath, -EINVAL);
291
292 if (strict && !path_startswith(syspath, "/sys/"))
293 return -EINVAL;
294
295 r = device_new_aux(&device);
296 if (r < 0)
297 return r;
298
299 r = device_set_syspath(device, syspath, /* verify= */ true);
300 if (r < 0)
301 return r;
302
303 *ret = TAKE_PTR(device);
304 return 0;
305 }
306
307 _public_ int sd_device_new_from_syspath(sd_device **ret, const char *syspath) {
308 return device_new_from_syspath(ret, syspath, /* strict= */ true);
309 }
310
311 int device_new_from_mode_and_devnum(sd_device **ret, mode_t mode, dev_t devnum) {
312 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
313 _cleanup_free_ char *syspath = NULL;
314 const char *t;
315 dev_t n;
316 int r;
317
318 assert(ret);
319
320 if (S_ISCHR(mode))
321 t = "char";
322 else if (S_ISBLK(mode))
323 t = "block";
324 else
325 return -ENOTTY;
326
327 if (major(devnum) == 0)
328 return -ENODEV;
329
330 if (asprintf(&syspath, "/sys/dev/%s/" DEVNUM_FORMAT_STR, t, DEVNUM_FORMAT_VAL(devnum)) < 0)
331 return -ENOMEM;
332
333 r = sd_device_new_from_syspath(&dev, syspath);
334 if (r < 0)
335 return r;
336
337 r = sd_device_get_devnum(dev, &n);
338 if (r == -ENOENT)
339 return -ENXIO;
340 if (r < 0)
341 return r;
342 if (n != devnum)
343 return -ENXIO;
344
345 r = device_in_subsystem(dev, "block");
346 if (r < 0)
347 return r;
348 if (r > 0 ? !S_ISBLK(mode) : !S_ISCHR(mode))
349 return -ENXIO;
350
351 *ret = TAKE_PTR(dev);
352 return 0;
353 }
354
355 _public_ int sd_device_new_from_devnum(sd_device **ret, char type, dev_t devnum) {
356 assert_return(ret, -EINVAL);
357 assert_return(IN_SET(type, 'b', 'c'), -EINVAL);
358
359 return device_new_from_mode_and_devnum(ret, type == 'b' ? S_IFBLK : S_IFCHR, devnum);
360 }
361
362 static int device_new_from_main_ifname(sd_device **ret, const char *ifname) {
363 const char *syspath;
364
365 assert(ret);
366 assert(ifname);
367
368 syspath = strjoina("/sys/class/net/", ifname);
369 return sd_device_new_from_syspath(ret, syspath);
370 }
371
372 _public_ int sd_device_new_from_ifname(sd_device **ret, const char *ifname) {
373 _cleanup_free_ char *main_name = NULL;
374 int r;
375
376 assert_return(ret, -EINVAL);
377 assert_return(ifname, -EINVAL);
378
379 if (ifname_valid(ifname)) {
380 r = device_new_from_main_ifname(ret, ifname);
381 if (r >= 0)
382 return r;
383 }
384
385 r = rtnl_resolve_ifname_full(NULL, RESOLVE_IFNAME_ALTERNATIVE | RESOLVE_IFNAME_NUMERIC, ifname, &main_name, NULL);
386 if (r < 0)
387 return r;
388
389 return device_new_from_main_ifname(ret, main_name);
390 }
391
392 _public_ int sd_device_new_from_ifindex(sd_device **ret, int ifindex) {
393 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
394 _cleanup_free_ char *ifname = NULL;
395 int r, i;
396
397 assert_return(ret, -EINVAL);
398 assert_return(ifindex > 0, -EINVAL);
399
400 r = rtnl_get_ifname(NULL, ifindex, &ifname);
401 if (r < 0)
402 return r;
403
404 r = device_new_from_main_ifname(&dev, ifname);
405 if (r < 0)
406 return r;
407
408 r = sd_device_get_ifindex(dev, &i);
409 if (r == -ENOENT)
410 return -ENXIO;
411 if (r < 0)
412 return r;
413 if (i != ifindex)
414 return -ENXIO;
415
416 *ret = TAKE_PTR(dev);
417 return 0;
418 }
419
420 static int device_new_from_path_join(
421 sd_device **device,
422 const char *subsystem,
423 const char *driver_subsystem,
424 const char *sysname,
425 const char *a,
426 const char *b,
427 const char *c,
428 const char *d) {
429
430 _cleanup_(sd_device_unrefp) sd_device *new_device = NULL;
431 _cleanup_free_ char *p = NULL;
432 int r;
433
434 assert(device);
435 assert(sysname);
436
437 p = path_join(a, b, c, d);
438 if (!p)
439 return -ENOMEM;
440
441 r = sd_device_new_from_syspath(&new_device, p);
442 if (r == -ENODEV)
443 return 0;
444 if (r < 0)
445 return r;
446
447 /* Check if the found device really has the expected subsystem and sysname, for safety. */
448 r = device_in_subsystem(new_device, subsystem);
449 if (r <= 0)
450 return r;
451
452 const char *new_driver_subsystem = NULL;
453 (void) sd_device_get_driver_subsystem(new_device, &new_driver_subsystem);
454
455 if (!streq_ptr(driver_subsystem, new_driver_subsystem))
456 return 0;
457
458 const char *new_sysname;
459 r = sd_device_get_sysname(new_device, &new_sysname);
460 if (r < 0)
461 return r;
462
463 if (!streq(sysname, new_sysname))
464 return 0;
465
466 /* If this is the first device we found, then take it. */
467 if (!*device) {
468 *device = TAKE_PTR(new_device);
469 return 1;
470 }
471
472 /* Unfortunately, (subsystem, sysname) pair is not unique. For examples,
473 * - /sys/bus/gpio and /sys/class/gpio, both have gpiochip%N. However, these point to different devpaths.
474 * - /sys/bus/mdio_bus and /sys/class/mdio_bus,
475 * - /sys/bus/mei and /sys/class/mei,
476 * - /sys/bus/typec and /sys/class/typec, and so on.
477 * Hence, if we already know a device, then we need to check if it is equivalent to the newly found one. */
478
479 const char *devpath, *new_devpath;
480 r = sd_device_get_devpath(*device, &devpath);
481 if (r < 0)
482 return r;
483
484 r = sd_device_get_devpath(new_device, &new_devpath);
485 if (r < 0)
486 return r;
487
488 if (!streq(devpath, new_devpath))
489 return log_debug_errno(SYNTHETIC_ERRNO(ETOOMANYREFS),
490 "sd-device: found multiple devices for subsystem=%s and sysname=%s, refusing: %s, %s",
491 subsystem, sysname, devpath, new_devpath);
492
493 return 1; /* Fortunately, they are consistent. */
494 }
495
496 _public_ int sd_device_new_from_subsystem_sysname(
497 sd_device **ret,
498 const char *subsystem,
499 const char *sysname) {
500
501 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
502 char *name;
503 int r;
504
505 assert_return(ret, -EINVAL);
506 assert_return(subsystem, -EINVAL);
507 assert_return(sysname, -EINVAL);
508
509 if (!path_is_normalized(subsystem))
510 return -EINVAL;
511 if (!path_is_normalized(sysname))
512 return -EINVAL;
513
514 /* translate sysname back to sysfs filename */
515 name = strdupa_safe(sysname);
516 string_replace_char(name, '/', '!');
517
518 if (streq(subsystem, "subsystem")) {
519 FOREACH_STRING(s, "/sys/bus/", "/sys/class/") {
520 r = device_new_from_path_join(&device, subsystem, /* driver_subsystem= */ NULL, sysname, s, name, NULL, NULL);
521 if (r < 0)
522 return r;
523 }
524
525 } else if (streq(subsystem, "module")) {
526 r = device_new_from_path_join(&device, subsystem, /* driver_subsystem= */ NULL, sysname, "/sys/module/", name, NULL, NULL);
527 if (r < 0)
528 return r;
529
530 } else if (streq(subsystem, "drivers")) {
531 const char *sep;
532
533 sep = strchr(name, ':');
534 if (sep && sep[1] != '\0') { /* Require ":" and something non-empty after that. */
535
536 const char *subsys = memdupa_suffix0(name, sep - name);
537 sep++;
538
539 if (streq(sep, "drivers")) /* If the sysname is "drivers", then it's the drivers directory itself that is meant. */
540 r = device_new_from_path_join(&device, subsystem, subsys, "drivers", "/sys/bus/", subsys, "/drivers", NULL);
541 else
542 r = device_new_from_path_join(&device, subsystem, subsys, sysname + (sep - name), "/sys/bus/", subsys, "/drivers/", sep);
543 if (r < 0)
544 return r;
545 }
546 }
547
548 r = device_new_from_path_join(&device, subsystem, /* driver_subsystem= */ NULL, sysname, "/sys/bus/", subsystem, "/devices/", name);
549 if (r < 0)
550 return r;
551
552 r = device_new_from_path_join(&device, subsystem, /* driver_subsystem= */ NULL, sysname, "/sys/class/", subsystem, name, NULL);
553 if (r < 0)
554 return r;
555
556 /* Note that devices under /sys/firmware/ (e.g. /sys/firmware/devicetree/base/) do not have
557 * subsystem. Hence, pass NULL for subsystem. See issue #35861. */
558 r = device_new_from_path_join(&device, /* subsystem= */ NULL, /* driver_subsystem= */ NULL, sysname, "/sys/firmware/", subsystem, name, NULL);
559 if (r < 0)
560 return r;
561
562 if (!device)
563 return -ENODEV;
564
565 *ret = TAKE_PTR(device);
566 return 0;
567 }
568
569 _public_ int sd_device_new_from_stat_rdev(sd_device **ret, const struct stat *st) {
570 assert_return(ret, -EINVAL);
571 assert_return(st, -EINVAL);
572
573 return device_new_from_mode_and_devnum(ret, st->st_mode, st->st_rdev);
574 }
575
576 static int device_new_from_devname(sd_device **ret, const char *devname, bool strict) {
577 int r;
578
579 assert_return(ret, -EINVAL);
580 assert_return(devname, -EINVAL);
581
582 /* This function actually accepts both devlinks and devnames, i.e. both symlinks and device
583 * nodes below /dev/. */
584
585 if (strict && isempty(path_startswith(devname, "/dev/")))
586 return -EINVAL;
587
588 dev_t devnum;
589 mode_t mode;
590 if (device_path_parse_major_minor(devname, &mode, &devnum) >= 0)
591 /* Let's shortcut when "/dev/block/maj:min" or "/dev/char/maj:min" is specified.
592 * In that case, we can directly convert the path to syspath, hence it is not necessary
593 * that the specified path exists. So, this works fine without udevd being running. */
594 return device_new_from_mode_and_devnum(ret, mode, devnum);
595
596 _cleanup_free_ char *resolved = NULL;
597 struct stat st;
598 r = chase_and_stat(devname, /* root= */ NULL, /* chase_flags= */ 0, &resolved, &st);
599 if (ERRNO_IS_NEG_DEVICE_ABSENT(r))
600 return -ENODEV;
601 if (r < 0)
602 return r;
603
604 if (isempty(path_startswith(resolved, "/dev/")))
605 return -EINVAL;
606
607 return sd_device_new_from_stat_rdev(ret, &st);
608 }
609
610 _public_ int sd_device_new_from_devname(sd_device **ret, const char *devname) {
611 return device_new_from_devname(ret, devname, /* strict= */ true);
612 }
613
614 _public_ int sd_device_new_from_path(sd_device **ret, const char *path) {
615 assert_return(ret, -EINVAL);
616 assert_return(path, -EINVAL);
617
618 if (device_new_from_devname(ret, path, /* strict= */ false) >= 0)
619 return 0;
620
621 return device_new_from_syspath(ret, path, /* strict= */ false);
622 }
623
624 int device_set_devtype(sd_device *device, const char *devtype) {
625 _cleanup_free_ char *t = NULL;
626 int r;
627
628 assert(device);
629 assert(devtype);
630
631 t = strdup(devtype);
632 if (!t)
633 return -ENOMEM;
634
635 r = device_add_property_internal(device, "DEVTYPE", t);
636 if (r < 0)
637 return r;
638
639 return free_and_replace(device->devtype, t);
640 }
641
642 int device_set_ifindex(sd_device *device, const char *name) {
643 int r, ifindex;
644
645 assert(device);
646 assert(name);
647
648 ifindex = parse_ifindex(name);
649 if (ifindex < 0)
650 return ifindex;
651
652 r = device_add_property_internal(device, "IFINDEX", name);
653 if (r < 0)
654 return r;
655
656 device->ifindex = ifindex;
657
658 return 0;
659 }
660
661 static int mangle_devname(const char *p, char **ret) {
662 char *q;
663
664 assert(p);
665 assert(ret);
666
667 if (!path_is_safe(p))
668 return -EINVAL;
669
670 /* When the path is absolute, it must start with "/dev/", but ignore "/dev/" itself. */
671 if (path_is_absolute(p)) {
672 if (isempty(path_startswith(p, "/dev/")))
673 return -EINVAL;
674
675 q = strdup(p);
676 } else
677 q = path_join("/dev/", p);
678 if (!q)
679 return -ENOMEM;
680
681 path_simplify(q);
682
683 *ret = q;
684 return 0;
685 }
686
687 int device_set_devname(sd_device *device, const char *devname) {
688 _cleanup_free_ char *t = NULL;
689 int r;
690
691 assert(device);
692 assert(devname);
693
694 r = mangle_devname(devname, &t);
695 if (r < 0)
696 return r;
697
698 r = device_add_property_internal(device, "DEVNAME", t);
699 if (r < 0)
700 return r;
701
702 return free_and_replace(device->devname, t);
703 }
704
705 int device_set_devmode(sd_device *device, const char *_devmode) {
706 unsigned devmode;
707 int r;
708
709 assert(device);
710 assert(_devmode);
711
712 r = safe_atou(_devmode, &devmode);
713 if (r < 0)
714 return r;
715
716 if (devmode > 07777)
717 return -EINVAL;
718
719 r = device_add_property_internal(device, "DEVMODE", _devmode);
720 if (r < 0)
721 return r;
722
723 device->devmode = devmode;
724
725 return 0;
726 }
727
728 int device_set_devnum(sd_device *device, const char *major, const char *minor) {
729 unsigned maj, min = 0;
730 int r;
731
732 assert(device);
733 assert(major);
734
735 r = safe_atou(major, &maj);
736 if (r < 0)
737 return r;
738 if (maj == 0)
739 return 0;
740 if (!DEVICE_MAJOR_VALID(maj))
741 return -EINVAL;
742
743 if (minor) {
744 r = safe_atou(minor, &min);
745 if (r < 0)
746 return r;
747 if (!DEVICE_MINOR_VALID(min))
748 return -EINVAL;
749 }
750
751 r = device_add_property_internal(device, "MAJOR", major);
752 if (r < 0)
753 return r;
754
755 if (minor) {
756 r = device_add_property_internal(device, "MINOR", minor);
757 if (r < 0)
758 return r;
759 }
760
761 device->devnum = makedev(maj, min);
762
763 return 0;
764 }
765
766 int device_set_diskseq(sd_device *device, const char *str) {
767 uint64_t diskseq;
768 int r;
769
770 assert(device);
771 assert(str);
772
773 r = safe_atou64(str, &diskseq);
774 if (r < 0)
775 return r;
776 if (diskseq == 0)
777 return -EINVAL;
778
779 r = device_add_property_internal(device, "DISKSEQ", str);
780 if (r < 0)
781 return r;
782
783 device->diskseq = diskseq;
784
785 return 0;
786 }
787
788 static int handle_uevent_line(
789 sd_device *device,
790 const char *key,
791 const char *value,
792 const char **major,
793 const char **minor) {
794
795 assert(device);
796 assert(key);
797 assert(value);
798 assert(major);
799 assert(minor);
800
801 if (streq(key, "SUBSYSTEM"))
802 return device_set_subsystem(device, value);
803 if (streq(key, "DEVTYPE"))
804 return device_set_devtype(device, value);
805 if (streq(key, "IFINDEX"))
806 return device_set_ifindex(device, value);
807 if (streq(key, "DEVNAME"))
808 return device_set_devname(device, value);
809 if (streq(key, "DEVUID"))
810 return device_set_devuid(device, value);
811 if (streq(key, "DEVGID"))
812 return device_set_devgid(device, value);
813 if (streq(key, "DEVMODE"))
814 return device_set_devmode(device, value);
815 if (streq(key, "DISKSEQ"))
816 return device_set_diskseq(device, value);
817 if (streq(key, "DRIVER"))
818 return device_set_driver(device, value);
819 if (streq(key, "MAJOR"))
820 *major = value;
821 else if (streq(key, "MINOR"))
822 *minor = value;
823 else
824 return device_add_property_internal(device, key, value);
825
826 return 0;
827 }
828
829 int device_read_uevent_file(sd_device *device) {
830 int r;
831
832 assert(device);
833
834 if (device->uevent_loaded || device->sealed)
835 return 0;
836
837 device->uevent_loaded = true;
838
839 const char *uevent;
840 r = device_get_sysattr_safe_string(device, "uevent", &uevent);
841 if (ERRNO_IS_NEG_PRIVILEGE(r) || ERRNO_IS_NEG_DEVICE_ABSENT(r))
842 /* The uevent files may be write-only, the device may be already removed, or the device
843 * may not have the uevent file. */
844 return 0;
845 if (r < 0)
846 return log_device_debug_errno(device, r, "sd-device: Failed to read uevent file: %m");
847
848 _cleanup_strv_free_ char **v = NULL;
849 r = strv_split_newlines_full(&v, uevent, EXTRACT_RETAIN_ESCAPE);
850 if (r < 0)
851 return log_device_debug_errno(device, r, "sd-device: Failed to parse uevent file: %m");
852
853 const char *major = NULL, *minor = NULL;
854 STRV_FOREACH(s, v) {
855 char *eq = strchr(*s, '=');
856 if (!eq) {
857 log_device_debug(device, "sd-device: Invalid uevent line, ignoring: %s", *s);
858 continue;
859 }
860
861 *eq = '\0';
862
863 r = handle_uevent_line(device, *s, eq + 1, &major, &minor);
864 if (r < 0)
865 log_device_debug_errno(device, r,
866 "sd-device: Failed to handle uevent entry '%s=%s', ignoring: %m",
867 *s, eq + 1);
868 }
869
870 if (major) {
871 r = device_set_devnum(device, major, minor);
872 if (r < 0)
873 log_device_debug_errno(device, r,
874 "sd-device: Failed to set 'MAJOR=%s' and/or 'MINOR=%s' from uevent, ignoring: %m",
875 major, strna(minor));
876 }
877
878 r = device_in_subsystem(device, "drivers");
879 if (r < 0)
880 log_device_debug_errno(device, r, "Failed to check if the device is a driver, ignoring: %m");
881 if (r > 0) {
882 r = device_set_drivers_subsystem(device);
883 if (r < 0)
884 log_device_debug_errno(device, r,
885 "sd-device: Failed to set driver subsystem, ignoring: %m");
886 }
887
888 return 0;
889 }
890
891 _public_ int sd_device_get_ifindex(sd_device *device, int *ret) {
892 int r;
893
894 assert_return(device, -EINVAL);
895
896 r = device_read_uevent_file(device);
897 if (r < 0)
898 return r;
899
900 if (device->ifindex <= 0)
901 return -ENOENT;
902
903 if (ret)
904 *ret = device->ifindex;
905
906 return 0;
907 }
908
909 int device_get_ifname(sd_device *device, const char **ret) {
910 int r;
911
912 assert_return(device, -EINVAL);
913
914 /* First, check if the device is a network interface. */
915 r = sd_device_get_ifindex(device, NULL);
916 if (r < 0)
917 return r;
918
919 /* The sysname and ifname may be different, as '!' in sysname are replaced with '/'.
920 * For network interfaces, we can use INTERFACE property. */
921 return sd_device_get_property_value(device, "INTERFACE", ret);
922 }
923
924 _public_ int sd_device_new_from_device_id(sd_device **ret, const char *id) {
925 int r;
926
927 assert_return(ret, -EINVAL);
928 assert_return(id, -EINVAL);
929
930 switch (id[0]) {
931 case 'b':
932 case 'c': {
933 dev_t devt;
934
935 if (isempty(id))
936 return -EINVAL;
937
938 r = parse_devnum(id + 1, &devt);
939 if (r < 0)
940 return r;
941
942 return sd_device_new_from_devnum(ret, id[0], devt);
943 }
944
945 case 'n': {
946 int ifindex;
947
948 ifindex = parse_ifindex(id + 1);
949 if (ifindex < 0)
950 return ifindex;
951
952 return sd_device_new_from_ifindex(ret, ifindex);
953 }
954
955 case '+': {
956 const char *sep = strchr(id + 1, ':');
957 if (!sep || sep[1] == '\0')
958 return -EINVAL;
959
960 _cleanup_free_ char *subsystem = strndup(id + 1, sep - id - 1);
961 if (!subsystem)
962 return -ENOMEM;
963
964 _cleanup_free_ char *sysname = strdup(sep + 1);
965 if (!sysname)
966 return -ENOMEM;
967
968 /* Device ID uses device directory name as is, hence may contain '!', but
969 * sd_device_new_from_subsystem_sysname() expects that the input is sysname,
970 * that is, '!' must be replaced with '/'. */
971 string_replace_char(sysname, '!', '/');
972
973 return sd_device_new_from_subsystem_sysname(ret, subsystem, sysname);
974 }
975
976 default:
977 return -EINVAL;
978 }
979 }
980
981 _public_ int sd_device_get_syspath(sd_device *device, const char **ret) {
982 assert_return(device, -EINVAL);
983
984 assert(path_startswith(device->syspath, "/sys/"));
985
986 if (ret)
987 *ret = device->syspath;
988
989 return 0;
990 }
991
992 DEFINE_PRIVATE_HASH_OPS_FULL(
993 device_by_path_hash_ops,
994 char, path_hash_func, path_compare, free,
995 sd_device, sd_device_unref);
996
997 static int device_enumerate_children_internal(sd_device *device, const char *subdir, Set **stack, Hashmap **children) {
998 _cleanup_closedir_ DIR *dir = NULL;
999 int r;
1000
1001 assert(device);
1002 assert(stack);
1003 assert(children);
1004
1005 r = device_opendir(device, subdir, &dir);
1006 if (r < 0)
1007 return r;
1008
1009 FOREACH_DIRENT_ALL(de, dir, return -errno) {
1010 _cleanup_(sd_device_unrefp) sd_device *child = NULL;
1011 _cleanup_free_ char *p = NULL;
1012
1013 if (dot_or_dot_dot(de->d_name))
1014 continue;
1015
1016 if (!IN_SET(de->d_type, DT_LNK, DT_DIR))
1017 continue;
1018
1019 if (subdir)
1020 p = path_join(subdir, de->d_name);
1021 else
1022 p = strdup(de->d_name);
1023 if (!p)
1024 return -ENOMEM;
1025
1026 /* Try to create child device. */
1027 r = sd_device_new_child(&child, device, p);
1028 if (r >= 0) {
1029 /* OK, this is a child device, saving it. */
1030 r = hashmap_ensure_put(children, &device_by_path_hash_ops, p, child);
1031 if (r < 0)
1032 return r;
1033
1034 TAKE_PTR(p);
1035 TAKE_PTR(child);
1036 } else if (r == -ENODEV) {
1037 /* This is not a child device. Push the sub-directory into stack, and read it later. */
1038
1039 if (de->d_type == DT_LNK)
1040 /* Do not follow symlinks, otherwise, we will enter an infinite loop, e.g.,
1041 * /sys/class/block/nvme0n1/subsystem/nvme0n1/subsystem/nvme0n1/subsystem/… */
1042 continue;
1043
1044 r = set_ensure_consume(stack, &path_hash_ops_free, TAKE_PTR(p));
1045 if (r < 0)
1046 return r;
1047 } else
1048 return r;
1049 }
1050
1051 return 0;
1052 }
1053
1054 static int device_enumerate_children(sd_device *device) {
1055 _cleanup_hashmap_free_ Hashmap *children = NULL;
1056 _cleanup_set_free_ Set *stack = NULL;
1057 int r;
1058
1059 assert(device);
1060
1061 if (device->children_enumerated)
1062 return 0; /* Already enumerated. */
1063
1064 r = device_enumerate_children_internal(device, NULL, &stack, &children);
1065 if (r < 0)
1066 return r;
1067
1068 for (;;) {
1069 _cleanup_free_ char *subdir = NULL;
1070
1071 subdir = set_steal_first(stack);
1072 if (!subdir)
1073 break;
1074
1075 r = device_enumerate_children_internal(device, subdir, &stack, &children);
1076 if (r < 0)
1077 return r;
1078 }
1079
1080 device->children_enumerated = true;
1081 device->children = TAKE_PTR(children);
1082 return 1; /* Enumerated. */
1083 }
1084
1085 _public_ sd_device* sd_device_get_child_first(sd_device *device, const char **ret_suffix) {
1086 int r;
1087
1088 assert(device);
1089
1090 r = device_enumerate_children(device);
1091 if (r < 0) {
1092 log_device_debug_errno(device, r, "sd-device: failed to enumerate child devices: %m");
1093 if (ret_suffix)
1094 *ret_suffix = NULL;
1095 return NULL;
1096 }
1097
1098 device->children_iterator = ITERATOR_FIRST;
1099
1100 return sd_device_get_child_next(device, ret_suffix);
1101 }
1102
1103 _public_ sd_device* sd_device_get_child_next(sd_device *device, const char **ret_suffix) {
1104 sd_device *child;
1105
1106 assert(device);
1107
1108 (void) hashmap_iterate(device->children, &device->children_iterator, (void**) &child, (const void**) ret_suffix);
1109 return child;
1110 }
1111
1112 _public_ int sd_device_new_child(sd_device **ret, sd_device *device, const char *suffix) {
1113 _cleanup_free_ char *path = NULL;
1114 sd_device *child;
1115 const char *s;
1116 int r;
1117
1118 assert_return(ret, -EINVAL);
1119 assert_return(device, -EINVAL);
1120 assert_return(suffix, -EINVAL);
1121
1122 if (!path_is_safe(suffix))
1123 return -EINVAL;
1124
1125 /* If we have already enumerated children, try to find the child from the cache. */
1126 child = hashmap_get(device->children, suffix);
1127 if (child) {
1128 *ret = sd_device_ref(child);
1129 return 0;
1130 }
1131
1132 r = sd_device_get_syspath(device, &s);
1133 if (r < 0)
1134 return r;
1135
1136 path = path_join(s, suffix);
1137 if (!path)
1138 return -ENOMEM;
1139
1140 return sd_device_new_from_syspath(ret, path);
1141 }
1142
1143 static int device_new_from_child(sd_device **ret, sd_device *child) {
1144 _cleanup_free_ char *path = NULL;
1145 const char *syspath;
1146 int r;
1147
1148 assert(ret);
1149 assert(child);
1150
1151 r = sd_device_get_syspath(child, &syspath);
1152 if (r < 0)
1153 return r;
1154
1155 for (;;) {
1156 _cleanup_free_ char *p = NULL;
1157
1158 r = path_extract_directory(path ?: syspath, &p);
1159 if (r < 0)
1160 return r;
1161
1162 if (path_equal(p, "/sys"))
1163 return -ENODEV;
1164
1165 r = sd_device_new_from_syspath(ret, p);
1166 if (r != -ENODEV)
1167 return r;
1168
1169 free_and_replace(path, p);
1170 }
1171 }
1172
1173 _public_ int sd_device_get_parent(sd_device *device, sd_device **ret) {
1174 int r;
1175
1176 assert_return(device, -EINVAL);
1177
1178 if (!device->parent_set) {
1179 r = device_new_from_child(&device->parent, device);
1180 if (r < 0 && r != -ENODEV)
1181 return r;
1182
1183 device->parent_set = true;
1184 }
1185
1186 if (!device->parent)
1187 return -ENOENT;
1188
1189 if (ret)
1190 *ret = device->parent;
1191 return 0;
1192 }
1193
1194 int device_set_subsystem(sd_device *device, const char *subsystem) {
1195 _cleanup_free_ char *s = NULL;
1196 int r;
1197
1198 assert(device);
1199
1200 if (subsystem) {
1201 s = strdup(subsystem);
1202 if (!s)
1203 return -ENOMEM;
1204 }
1205
1206 r = device_add_property_internal(device, "SUBSYSTEM", s);
1207 if (r < 0)
1208 return r;
1209
1210 device->subsystem_set = true;
1211 return free_and_replace(device->subsystem, s);
1212 }
1213
1214 int device_set_drivers_subsystem(sd_device *device) {
1215 _cleanup_free_ char *subsystem = NULL;
1216 const char *devpath, *drivers, *p;
1217 int r;
1218
1219 assert(device);
1220
1221 r = sd_device_get_devpath(device, &devpath);
1222 if (r < 0)
1223 return r;
1224
1225 drivers = strstr(devpath, "/drivers/");
1226 if (!drivers)
1227 drivers = endswith(devpath, "/drivers");
1228 if (!drivers)
1229 return -EINVAL;
1230
1231 /* Find the path component immediately before the "/drivers/" string */
1232 r = path_find_last_component(devpath, /* accept_dot_dot= */ false, &drivers, &p);
1233 if (r < 0)
1234 return r;
1235 if (r == 0)
1236 return -EINVAL;
1237
1238 subsystem = strndup(p, r);
1239 if (!subsystem)
1240 return -ENOMEM;
1241
1242 r = device_set_subsystem(device, "drivers");
1243 if (r < 0)
1244 return r;
1245
1246 return free_and_replace(device->driver_subsystem, subsystem);
1247 }
1248
1249 _public_ int sd_device_get_subsystem(sd_device *device, const char **ret) {
1250 int r;
1251
1252 assert_return(device, -EINVAL);
1253
1254 r = device_read_uevent_file(device);
1255 if (r < 0)
1256 return r;
1257
1258 if (!device->subsystem_set) {
1259 const char *subsystem;
1260
1261 r = device_get_sysattr_safe_string(device, "subsystem", &subsystem);
1262 if (r < 0 && r != -ENOENT)
1263 return log_device_debug_errno(device, r,
1264 "sd-device: Failed to read subsystem for %s: %m",
1265 device->devpath);
1266 if (r >= 0)
1267 r = device_set_subsystem(device, subsystem);
1268 /* use implicit names */
1269 else if (!isempty(path_startswith(device->devpath, "/module/")))
1270 r = device_set_subsystem(device, "module");
1271 else if (strstr(device->devpath, "/drivers/") || endswith(device->devpath, "/drivers"))
1272 r = device_set_drivers_subsystem(device);
1273 else if (!isempty(PATH_STARTSWITH_SET(device->devpath, "/class/", "/bus/")))
1274 r = device_set_subsystem(device, "subsystem");
1275 else
1276 r = device_set_subsystem(device, NULL);
1277 if (r < 0)
1278 return log_device_debug_errno(device, r,
1279 "sd-device: Failed to set subsystem for %s: %m",
1280 device->devpath);
1281 }
1282
1283 if (!device->subsystem)
1284 return -ENOENT;
1285
1286 if (ret)
1287 *ret = device->subsystem;
1288 return 0;
1289 }
1290
1291 _public_ int sd_device_get_driver_subsystem(sd_device *device, const char **ret) {
1292 int r;
1293
1294 assert_return(device, -EINVAL);
1295
1296 r = device_in_subsystem(device, "drivers");
1297 if (r < 0)
1298 return r;
1299 if (r == 0)
1300 return -ENOENT;
1301
1302 assert(device->driver_subsystem);
1303
1304 if (ret)
1305 *ret = device->driver_subsystem;
1306
1307 return 0;
1308 }
1309
1310 _public_ int sd_device_get_devtype(sd_device *device, const char **ret) {
1311 int r;
1312
1313 assert_return(device, -EINVAL);
1314
1315 r = device_read_uevent_file(device);
1316 if (r < 0)
1317 return r;
1318
1319 if (!device->devtype)
1320 return -ENOENT;
1321
1322 if (ret)
1323 *ret = device->devtype;
1324
1325 return 0;
1326 }
1327
1328 _public_ int sd_device_get_parent_with_subsystem_devtype(sd_device *device, const char *subsystem, const char *devtype, sd_device **ret) {
1329 int r;
1330
1331 assert_return(device, -EINVAL);
1332 assert_return(subsystem, -EINVAL);
1333
1334 for (;;) {
1335 r = sd_device_get_parent(device, &device);
1336 if (r < 0)
1337 return r;
1338
1339 r = device_is_subsystem_devtype(device, subsystem, devtype);
1340 if (r < 0)
1341 return r;
1342 if (r == 0)
1343 continue;
1344
1345 if (ret)
1346 *ret = device;
1347 return 0;
1348 }
1349 }
1350
1351 _public_ int sd_device_get_devnum(sd_device *device, dev_t *ret) {
1352 int r;
1353
1354 assert_return(device, -EINVAL);
1355
1356 r = device_read_uevent_file(device);
1357 if (r < 0)
1358 return r;
1359
1360 if (major(device->devnum) <= 0)
1361 return -ENOENT;
1362
1363 if (ret)
1364 *ret = device->devnum;
1365
1366 return 0;
1367 }
1368
1369 int device_set_driver(sd_device *device, const char *driver) {
1370 _cleanup_free_ char *d = NULL;
1371 int r;
1372
1373 assert(device);
1374
1375 if (driver) {
1376 d = strdup(driver);
1377 if (!d)
1378 return -ENOMEM;
1379 }
1380
1381 r = device_add_property_internal(device, "DRIVER", d);
1382 if (r < 0)
1383 return r;
1384
1385 device->driver_set = true;
1386 return free_and_replace(device->driver, d);
1387 }
1388
1389 _public_ int sd_device_get_driver(sd_device *device, const char **ret) {
1390 int r;
1391
1392 assert_return(device, -EINVAL);
1393
1394 r = device_read_uevent_file(device);
1395 if (r < 0)
1396 return r;
1397
1398 if (!device->driver_set) {
1399 const char *driver = NULL;
1400
1401 r = device_get_sysattr_safe_string(device, "driver", &driver);
1402 if (r < 0 && r != -ENOENT)
1403 return log_device_debug_errno(device, r,
1404 "sd-device: Failed to read driver: %m");
1405
1406 r = device_set_driver(device, driver);
1407 if (r < 0)
1408 return log_device_debug_errno(device, r,
1409 "sd-device: Failed to set driver \"%s\": %m", driver);
1410 }
1411
1412 if (!device->driver)
1413 return -ENOENT;
1414
1415 if (ret)
1416 *ret = device->driver;
1417 return 0;
1418 }
1419
1420 _public_ int sd_device_get_devpath(sd_device *device, const char **ret) {
1421 assert_return(device, -EINVAL);
1422
1423 assert(device->devpath);
1424 assert(device->devpath[0] == '/');
1425
1426 if (ret)
1427 *ret = device->devpath;
1428
1429 return 0;
1430 }
1431
1432 _public_ int sd_device_get_devname(sd_device *device, const char **ret) {
1433 int r;
1434
1435 assert_return(device, -EINVAL);
1436
1437 r = device_read_uevent_file(device);
1438 if (r < 0)
1439 return r;
1440
1441 if (!device->devname)
1442 return -ENOENT;
1443
1444 assert(!isempty(path_startswith(device->devname, "/dev/")));
1445
1446 if (ret)
1447 *ret = device->devname;
1448 return 0;
1449 }
1450
1451 static int device_set_sysname_and_sysnum(sd_device *device) {
1452 _cleanup_free_ char *sysname = NULL;
1453 size_t len, n;
1454 int r;
1455
1456 assert(device);
1457
1458 r = path_extract_filename(device->devpath, &sysname);
1459 if (r < 0)
1460 return r;
1461 if (r == O_DIRECTORY)
1462 return -EINVAL;
1463
1464 /* some devices have '!' in their name, change that to '/' */
1465 string_replace_char(sysname, '!', '/');
1466
1467 n = strspn_from_end(sysname, DIGITS);
1468 len = strlen(sysname);
1469 assert(n <= len);
1470 if (n == len)
1471 n = 0; /* Do not set sysnum for number only sysname. */
1472
1473 device->sysnum = n > 0 ? sysname + len - n : NULL;
1474 return free_and_replace(device->sysname, sysname);
1475 }
1476
1477 _public_ int sd_device_get_sysname(sd_device *device, const char **ret) {
1478 int r;
1479
1480 assert_return(device, -EINVAL);
1481
1482 if (!device->sysname) {
1483 r = device_set_sysname_and_sysnum(device);
1484 if (r < 0)
1485 return r;
1486 }
1487
1488 if (ret)
1489 *ret = device->sysname;
1490 return 0;
1491 }
1492
1493 _public_ int sd_device_get_sysnum(sd_device *device, const char **ret) {
1494 int r;
1495
1496 assert_return(device, -EINVAL);
1497
1498 if (!device->sysname) {
1499 r = device_set_sysname_and_sysnum(device);
1500 if (r < 0)
1501 return r;
1502 }
1503
1504 if (!device->sysnum)
1505 return -ENOENT;
1506
1507 if (ret)
1508 *ret = device->sysnum;
1509 return 0;
1510 }
1511
1512 int device_get_sysnum_unsigned(sd_device *device, unsigned *ret) {
1513 int r;
1514
1515 assert(device);
1516
1517 const char *s;
1518 r = sd_device_get_sysnum(device, &s);
1519 if (r < 0)
1520 return r;
1521
1522 unsigned n;
1523 r = safe_atou_full(s, SAFE_ATO_REFUSE_PLUS_MINUS | SAFE_ATO_REFUSE_LEADING_WHITESPACE | 10, &n);
1524 if (r < 0)
1525 return r;
1526
1527 if (ret)
1528 *ret = n;
1529 return 0;
1530 }
1531
1532 _public_ int sd_device_get_action(sd_device *device, sd_device_action_t *ret) {
1533 assert_return(device, -EINVAL);
1534
1535 if (device->action < 0)
1536 return -ENOENT;
1537
1538 if (ret)
1539 *ret = device->action;
1540
1541 return 0;
1542 }
1543
1544 _public_ int sd_device_get_seqnum(sd_device *device, uint64_t *ret) {
1545 assert_return(device, -EINVAL);
1546
1547 if (device->seqnum == 0)
1548 return -ENOENT;
1549
1550 if (ret)
1551 *ret = device->seqnum;
1552
1553 return 0;
1554 }
1555
1556 _public_ int sd_device_get_diskseq(sd_device *device, uint64_t *ret) {
1557 int r;
1558
1559 assert_return(device, -EINVAL);
1560
1561 r = device_read_uevent_file(device);
1562 if (r < 0)
1563 return r;
1564
1565 if (device->diskseq == 0)
1566 return -ENOENT;
1567
1568 if (ret)
1569 *ret = device->diskseq;
1570
1571 return 0;
1572 }
1573
1574 static bool is_valid_tag(const char *tag) {
1575 assert(tag);
1576
1577 return in_charset(tag, ALPHANUMERICAL "-_") && filename_is_valid(tag);
1578 }
1579
1580 int device_add_tag(sd_device *device, const char *tag, bool both) {
1581 int r, added;
1582
1583 assert(device);
1584 assert(tag);
1585
1586 if (!is_valid_tag(tag))
1587 return -EINVAL;
1588
1589 /* Definitely add to the "all" list of tags (i.e. the sticky list) */
1590 added = set_put_strdup(&device->all_tags, tag);
1591 if (added < 0)
1592 return added;
1593
1594 /* And optionally, also add it to the current list of tags */
1595 if (both) {
1596 r = set_put_strdup(&device->current_tags, tag);
1597 if (r < 0) {
1598 if (added > 0)
1599 (void) set_remove(device->all_tags, tag);
1600
1601 return r;
1602 }
1603 }
1604
1605 device->tags_generation++;
1606 device->property_tags_outdated = true;
1607
1608 return 0;
1609 }
1610
1611 int device_add_devlink(sd_device *device, const char *devlink) {
1612 char *p;
1613 int r;
1614
1615 assert(device);
1616 assert(devlink);
1617
1618 r = mangle_devname(devlink, &p);
1619 if (r < 0)
1620 return r;
1621
1622 r = set_ensure_consume(&device->devlinks, &path_hash_ops_free, p);
1623 if (r < 0)
1624 return r;
1625
1626 device->devlinks_generation++;
1627 device->property_devlinks_outdated = true;
1628
1629 return r; /* return 1 when newly added, 0 when already exists */
1630 }
1631
1632 int device_remove_devlink(sd_device *device, const char *devlink) {
1633 _cleanup_free_ char *p = NULL, *s = NULL;
1634 int r;
1635
1636 assert(device);
1637 assert(devlink);
1638
1639 r = mangle_devname(devlink, &p);
1640 if (r < 0)
1641 return r;
1642
1643 s = set_remove(device->devlinks, p);
1644 if (!s)
1645 return 0; /* does not exist */
1646
1647 device->devlinks_generation++;
1648 device->property_devlinks_outdated = true;
1649 return 1; /* removed */
1650 }
1651
1652 bool device_has_devlink(sd_device *device, const char *devlink) {
1653 assert(device);
1654 assert(devlink);
1655
1656 return set_contains(device->devlinks, devlink);
1657 }
1658
1659 static int device_add_property_internal_from_string(sd_device *device, const char *str) {
1660 _cleanup_free_ char *key = NULL;
1661 char *value;
1662
1663 assert(device);
1664 assert(str);
1665
1666 key = strdup(str);
1667 if (!key)
1668 return -ENOMEM;
1669
1670 value = strchr(key, '=');
1671 if (!value)
1672 return -EINVAL;
1673
1674 *value = '\0';
1675
1676 if (isempty(++value))
1677 value = NULL;
1678
1679 /* Add the property to both sd_device::properties and sd_device::properties_db,
1680 * as this is called by only handle_db_line(). */
1681 return device_add_property(device, key, value);
1682 }
1683
1684 int device_set_usec_initialized(sd_device *device, usec_t when) {
1685 char s[DECIMAL_STR_MAX(usec_t)];
1686 int r;
1687
1688 assert(device);
1689
1690 xsprintf(s, USEC_FMT, when);
1691
1692 r = device_add_property_internal(device, "USEC_INITIALIZED", s);
1693 if (r < 0)
1694 return r;
1695
1696 device->usec_initialized = when;
1697 return 0;
1698 }
1699
1700 static int handle_db_line(sd_device *device, char key, const char *value) {
1701 int r;
1702
1703 assert(device);
1704 assert(value);
1705
1706 switch (key) {
1707 case 'G': /* Any tag */
1708 case 'Q': /* Current tag */
1709 return device_add_tag(device, value, key == 'Q');
1710
1711 case 'S': {
1712 const char *path;
1713
1714 path = strjoina("/dev/", value);
1715 return device_add_devlink(device, path);
1716 }
1717 case 'E':
1718 return device_add_property_internal_from_string(device, value);
1719
1720 case 'I': {
1721 usec_t t;
1722
1723 r = safe_atou64(value, &t);
1724 if (r < 0)
1725 return r;
1726
1727 return device_set_usec_initialized(device, t);
1728 }
1729 case 'L':
1730 return safe_atoi(value, &device->devlink_priority);
1731
1732 case 'W':
1733 /* Deprecated. Previously, watch handle is both saved in database and /run/udev/watch.
1734 * However, the handle saved in database may not be updated when the handle is updated
1735 * or removed. Moreover, it is not necessary to store the handle within the database,
1736 * as its value becomes meaningless when udevd is restarted. */
1737 return 0;
1738
1739 case 'V':
1740 return safe_atou(value, &device->database_version);
1741
1742 default:
1743 log_device_debug(device, "sd-device: Unknown key '%c' in device db, ignoring", key);
1744 return 0;
1745 }
1746 }
1747
1748 _public_ int sd_device_get_device_id(sd_device *device, const char **ret) {
1749 assert_return(device, -EINVAL);
1750
1751 if (!device->device_id) {
1752 _cleanup_free_ char *id = NULL;
1753 dev_t devnum;
1754 int ifindex, r;
1755
1756 if (sd_device_get_devnum(device, &devnum) >= 0) {
1757 r = device_in_subsystem(device, "block");
1758 if (r < 0)
1759 return r;
1760 char t = r > 0 ? 'b' : 'c';
1761
1762 /* use dev_t — b259:131072, c254:0 */
1763 if (asprintf(&id, "%c" DEVNUM_FORMAT_STR, t, DEVNUM_FORMAT_VAL(devnum)) < 0)
1764 return -ENOMEM;
1765
1766 } else if (sd_device_get_ifindex(device, &ifindex) >= 0) {
1767 /* use netdev ifindex — n3 */
1768 if (asprintf(&id, "n%u", (unsigned) ifindex) < 0)
1769 return -ENOMEM;
1770
1771 } else {
1772 _cleanup_free_ char *sysname = NULL;
1773
1774 /* use $subsys:$sysname — pci:0000:00:1f.2
1775 * sd_device_get_sysname() has '!' translated, get it from devpath */
1776 r = path_extract_filename(device->devpath, &sysname);
1777 if (r < 0)
1778 return r;
1779 if (r == O_DIRECTORY)
1780 return -EINVAL;
1781
1782 r = device_in_subsystem(device, "drivers");
1783 if (r < 0)
1784 return r;
1785 if (r > 0)
1786 /* the 'drivers' pseudo-subsystem is special, and needs the real
1787 * subsystem encoded as well */
1788 id = strjoin("+drivers:", ASSERT_PTR(device->driver_subsystem), ":", sysname);
1789 else {
1790 const char *subsystem;
1791 r = sd_device_get_subsystem(device, &subsystem);
1792 if (r < 0)
1793 return r;
1794
1795 id = strjoin("+", subsystem, ":", sysname);
1796 }
1797 if (!id)
1798 return -ENOMEM;
1799 }
1800
1801 if (!filename_is_valid(id))
1802 return -EINVAL;
1803
1804 device->device_id = TAKE_PTR(id);
1805 }
1806
1807 if (ret)
1808 *ret = device->device_id;
1809 return 0;
1810 }
1811
1812 int device_read_db_internal_filename(sd_device *device, const char *filename) {
1813 _cleanup_free_ char *db = NULL;
1814 const char *value;
1815 size_t db_len;
1816 char key = '\0'; /* Unnecessary initialization to appease gcc-12.0.0-0.4.fc36 */
1817 int r;
1818
1819 enum {
1820 PRE_KEY,
1821 KEY,
1822 PRE_VALUE,
1823 VALUE,
1824 INVALID_LINE,
1825 } state = PRE_KEY;
1826
1827 assert(device);
1828 assert(filename);
1829
1830 r = read_full_file(filename, &db, &db_len);
1831 if (r == -ENOENT)
1832 return 0;
1833 if (r < 0)
1834 return log_device_debug_errno(device, r, "sd-device: Failed to read db '%s': %m", filename);
1835
1836 /* devices with a database entry are initialized */
1837 device->is_initialized = true;
1838
1839 device->db_loaded = true;
1840
1841 for (size_t i = 0; i < db_len; i++)
1842 switch (state) {
1843 case PRE_KEY:
1844 if (!strchr(NEWLINE, db[i])) {
1845 key = db[i];
1846
1847 state = KEY;
1848 }
1849
1850 break;
1851 case KEY:
1852 if (db[i] != ':') {
1853 log_device_debug(device, "sd-device: Invalid db entry with key '%c', ignoring", key);
1854
1855 state = INVALID_LINE;
1856 } else {
1857 db[i] = '\0';
1858
1859 state = PRE_VALUE;
1860 }
1861
1862 break;
1863 case PRE_VALUE:
1864 value = &db[i];
1865
1866 state = VALUE;
1867
1868 break;
1869 case INVALID_LINE:
1870 if (strchr(NEWLINE, db[i]))
1871 state = PRE_KEY;
1872
1873 break;
1874 case VALUE:
1875 if (strchr(NEWLINE, db[i])) {
1876 db[i] = '\0';
1877 r = handle_db_line(device, key, value);
1878 if (r < 0)
1879 log_device_debug_errno(device, r, "sd-device: Failed to handle db entry '%c:%s', ignoring: %m",
1880 key, value);
1881
1882 state = PRE_KEY;
1883 }
1884
1885 break;
1886 default:
1887 return log_device_debug_errno(device, SYNTHETIC_ERRNO(EINVAL), "sd-device: invalid db syntax.");
1888 }
1889
1890 return 0;
1891 }
1892
1893 _public_ int sd_device_get_is_initialized(sd_device *device) {
1894 int r;
1895
1896 assert_return(device, -EINVAL);
1897
1898 r = device_read_db(device);
1899 if (r == -ENOENT)
1900 /* The device may be already removed or renamed. */
1901 return false;
1902 if (r < 0)
1903 return r;
1904
1905 return device->is_initialized;
1906 }
1907
1908 _public_ int sd_device_get_usec_initialized(sd_device *device, uint64_t *ret) {
1909 int r;
1910
1911 assert_return(device, -EINVAL);
1912
1913 r = sd_device_get_is_initialized(device);
1914 if (r < 0)
1915 return r;
1916 if (r == 0)
1917 return -EBUSY;
1918
1919 if (device->usec_initialized == 0)
1920 return -ENODATA;
1921
1922 if (ret)
1923 *ret = device->usec_initialized;
1924
1925 return 0;
1926 }
1927
1928 _public_ int sd_device_get_usec_since_initialized(sd_device *device, uint64_t *ret) {
1929 usec_t now_ts, ts;
1930 int r;
1931
1932 assert_return(device, -EINVAL);
1933
1934 r = sd_device_get_usec_initialized(device, &ts);
1935 if (r < 0)
1936 return r;
1937
1938 now_ts = now(CLOCK_MONOTONIC);
1939
1940 if (now_ts < ts)
1941 return -EIO;
1942
1943 if (ret)
1944 *ret = usec_sub_unsigned(now_ts, ts);
1945
1946 return 0;
1947 }
1948
1949 _public_ const char* sd_device_get_tag_first(sd_device *device) {
1950 void *v;
1951
1952 assert_return(device, NULL);
1953
1954 (void) device_read_db(device);
1955
1956 device->all_tags_iterator_generation = device->tags_generation;
1957 device->all_tags_iterator = ITERATOR_FIRST;
1958
1959 (void) set_iterate(device->all_tags, &device->all_tags_iterator, &v);
1960 return v;
1961 }
1962
1963 _public_ const char* sd_device_get_tag_next(sd_device *device) {
1964 void *v;
1965
1966 assert_return(device, NULL);
1967
1968 (void) device_read_db(device);
1969
1970 if (device->all_tags_iterator_generation != device->tags_generation)
1971 return NULL;
1972
1973 (void) set_iterate(device->all_tags, &device->all_tags_iterator, &v);
1974 return v;
1975 }
1976
1977 _public_ const char* sd_device_get_current_tag_first(sd_device *device) {
1978 void *v;
1979
1980 assert_return(device, NULL);
1981
1982 (void) device_read_db(device);
1983
1984 device->current_tags_iterator_generation = device->tags_generation;
1985 device->current_tags_iterator = ITERATOR_FIRST;
1986
1987 (void) set_iterate(device->current_tags, &device->current_tags_iterator, &v);
1988 return v;
1989 }
1990
1991 _public_ const char* sd_device_get_current_tag_next(sd_device *device) {
1992 void *v;
1993
1994 assert_return(device, NULL);
1995
1996 (void) device_read_db(device);
1997
1998 if (device->current_tags_iterator_generation != device->tags_generation)
1999 return NULL;
2000
2001 (void) set_iterate(device->current_tags, &device->current_tags_iterator, &v);
2002 return v;
2003 }
2004
2005 _public_ const char* sd_device_get_devlink_first(sd_device *device) {
2006 void *v;
2007
2008 assert_return(device, NULL);
2009
2010 (void) device_read_db(device);
2011
2012 device->devlinks_iterator_generation = device->devlinks_generation;
2013 device->devlinks_iterator = ITERATOR_FIRST;
2014
2015 (void) set_iterate(device->devlinks, &device->devlinks_iterator, &v);
2016 return v;
2017 }
2018
2019 _public_ const char* sd_device_get_devlink_next(sd_device *device) {
2020 void *v;
2021
2022 assert_return(device, NULL);
2023
2024 (void) device_read_db(device);
2025
2026 if (device->devlinks_iterator_generation != device->devlinks_generation)
2027 return NULL;
2028
2029 (void) set_iterate(device->devlinks, &device->devlinks_iterator, &v);
2030 return v;
2031 }
2032
2033 int device_properties_prepare(sd_device *device) {
2034 int r;
2035
2036 assert(device);
2037
2038 r = device_read_uevent_file(device);
2039 if (r < 0)
2040 return r;
2041
2042 r = device_read_db(device);
2043 if (r < 0)
2044 return r;
2045
2046 if (device->property_devlinks_outdated) {
2047 _cleanup_free_ char *devlinks = NULL;
2048
2049 r = set_strjoin(device->devlinks, " ", false, &devlinks);
2050 if (r < 0)
2051 return r;
2052
2053 if (!isempty(devlinks)) {
2054 r = device_add_property_internal(device, "DEVLINKS", devlinks);
2055 if (r < 0)
2056 return r;
2057 }
2058
2059 device->property_devlinks_outdated = false;
2060 }
2061
2062 if (device->property_tags_outdated) {
2063 _cleanup_free_ char *tags = NULL;
2064
2065 r = set_strjoin(device->all_tags, ":", true, &tags);
2066 if (r < 0)
2067 return r;
2068
2069 if (!isempty(tags)) {
2070 r = device_add_property_internal(device, "TAGS", tags);
2071 if (r < 0)
2072 return r;
2073 }
2074
2075 tags = mfree(tags);
2076 r = set_strjoin(device->current_tags, ":", true, &tags);
2077 if (r < 0)
2078 return r;
2079
2080 if (!isempty(tags)) {
2081 r = device_add_property_internal(device, "CURRENT_TAGS", tags);
2082 if (r < 0)
2083 return r;
2084 }
2085
2086 device->property_tags_outdated = false;
2087 }
2088
2089 return 0;
2090 }
2091
2092 _public_ const char* sd_device_get_property_first(sd_device *device, const char **_value) {
2093 const char *key;
2094 int r;
2095
2096 assert_return(device, NULL);
2097
2098 r = device_properties_prepare(device);
2099 if (r < 0)
2100 return NULL;
2101
2102 device->properties_iterator_generation = device->properties_generation;
2103 device->properties_iterator = ITERATOR_FIRST;
2104
2105 (void) ordered_hashmap_iterate(device->properties, &device->properties_iterator, (void**)_value, (const void**)&key);
2106 return key;
2107 }
2108
2109 _public_ const char* sd_device_get_property_next(sd_device *device, const char **_value) {
2110 const char *key;
2111 int r;
2112
2113 assert_return(device, NULL);
2114
2115 r = device_properties_prepare(device);
2116 if (r < 0)
2117 return NULL;
2118
2119 if (device->properties_iterator_generation != device->properties_generation)
2120 return NULL;
2121
2122 (void) ordered_hashmap_iterate(device->properties, &device->properties_iterator, (void**)_value, (const void**)&key);
2123 return key;
2124 }
2125
2126 static int device_sysattrs_read_all_internal(sd_device *device, const char *subdir, Set **stack) {
2127 _cleanup_closedir_ DIR *dir = NULL;
2128 int r;
2129
2130 assert(device);
2131 assert(stack);
2132
2133 r = device_opendir(device, subdir, &dir);
2134 if (r == -ENOENT && subdir)
2135 return 0; /* Maybe, this is a child device, and is already removed. */
2136 if (r < 0)
2137 return r;
2138
2139 if (subdir) {
2140 if (faccessat(dirfd(dir), "uevent", F_OK, 0) >= 0)
2141 return 0; /* this is a child device, skipping */
2142 if (errno != ENOENT) {
2143 log_device_debug_errno(device, errno,
2144 "sd-device: Failed to access %s/uevent, ignoring sub-directory %s: %m",
2145 subdir, subdir);
2146 return 0;
2147 }
2148 }
2149
2150 FOREACH_DIRENT_ALL(de, dir, return -errno) {
2151 _cleanup_free_ char *p = NULL;
2152 struct stat statbuf;
2153
2154 if (dot_or_dot_dot(de->d_name))
2155 continue;
2156
2157 /* only handle symlinks, regular files, and directories */
2158 if (!IN_SET(de->d_type, DT_LNK, DT_REG, DT_DIR))
2159 continue;
2160
2161 if (subdir) {
2162 p = path_join(subdir, de->d_name);
2163 if (!p)
2164 return -ENOMEM;
2165 }
2166
2167 if (de->d_type == DT_DIR) {
2168 /* push the sub-directory into the stack, and read it later. */
2169 if (p)
2170 r = set_ensure_consume(stack, &path_hash_ops_free, TAKE_PTR(p));
2171 else
2172 r = set_put_strdup_full(stack, &path_hash_ops_free, de->d_name);
2173 if (r < 0)
2174 return r;
2175
2176 continue;
2177 }
2178
2179 if (fstatat(dirfd(dir), de->d_name, &statbuf, AT_SYMLINK_NOFOLLOW) < 0)
2180 continue;
2181
2182 if ((statbuf.st_mode & (S_IRUSR | S_IWUSR)) == 0)
2183 continue;
2184
2185 if (p)
2186 r = set_ensure_consume(&device->sysattrs, &path_hash_ops_free, TAKE_PTR(p));
2187 else
2188 r = set_put_strdup_full(&device->sysattrs, &path_hash_ops_free, de->d_name);
2189 if (r < 0)
2190 return r;
2191 }
2192
2193 return 0;
2194 }
2195
2196 static int device_sysattrs_read_all(sd_device *device) {
2197 _cleanup_set_free_ Set *stack = NULL;
2198 int r;
2199
2200 assert(device);
2201
2202 if (device->sysattrs_read)
2203 return 0;
2204
2205 r = device_sysattrs_read_all_internal(device, NULL, &stack);
2206 if (r < 0)
2207 return r;
2208
2209 for (;;) {
2210 _cleanup_free_ char *subdir = NULL;
2211
2212 subdir = set_steal_first(stack);
2213 if (!subdir)
2214 break;
2215
2216 r = device_sysattrs_read_all_internal(device, subdir, &stack);
2217 if (r < 0)
2218 return r;
2219 }
2220
2221 device->sysattrs_read = true;
2222
2223 return 0;
2224 }
2225
2226 _public_ const char* sd_device_get_sysattr_first(sd_device *device) {
2227 void *v;
2228
2229 assert_return(device, NULL);
2230
2231 if (!device->sysattrs_read &&
2232 device_sysattrs_read_all(device) < 0)
2233 return NULL;
2234
2235 device->sysattrs_iterator = ITERATOR_FIRST;
2236
2237 (void) set_iterate(device->sysattrs, &device->sysattrs_iterator, &v);
2238 return v;
2239 }
2240
2241 _public_ const char* sd_device_get_sysattr_next(sd_device *device) {
2242 void *v;
2243
2244 assert_return(device, NULL);
2245
2246 if (!device->sysattrs_read)
2247 return NULL;
2248
2249 (void) set_iterate(device->sysattrs, &device->sysattrs_iterator, &v);
2250 return v;
2251 }
2252
2253 _public_ int sd_device_has_tag(sd_device *device, const char *tag) {
2254 assert_return(device, -EINVAL);
2255 assert_return(tag, -EINVAL);
2256
2257 (void) device_read_db(device);
2258
2259 return set_contains(device->all_tags, tag);
2260 }
2261
2262 _public_ int sd_device_has_current_tag(sd_device *device, const char *tag) {
2263 assert_return(device, -EINVAL);
2264 assert_return(tag, -EINVAL);
2265
2266 (void) device_read_db(device);
2267
2268 return set_contains(device->current_tags, tag);
2269 }
2270
2271 _public_ int sd_device_get_property_value(sd_device *device, const char *key, const char **ret) {
2272 const char *value;
2273 int r;
2274
2275 assert_return(device, -EINVAL);
2276 assert_return(key, -EINVAL);
2277
2278 r = device_properties_prepare(device);
2279 if (r < 0)
2280 return r;
2281
2282 value = ordered_hashmap_get(device->properties, key);
2283 if (!value)
2284 return -ENOENT;
2285
2286 if (ret)
2287 *ret = value;
2288 return 0;
2289 }
2290
2291 int device_get_property_bool(sd_device *device, const char *key) {
2292 const char *value;
2293 int r;
2294
2295 assert(device);
2296 assert(key);
2297
2298 r = sd_device_get_property_value(device, key, &value);
2299 if (r < 0)
2300 return r;
2301
2302 return parse_boolean(value);
2303 }
2304
2305 int device_get_property_int(sd_device *device, const char *key, int *ret) {
2306 const char *value;
2307 int r, v;
2308
2309 assert(device);
2310 assert(key);
2311
2312 r = sd_device_get_property_value(device, key, &value);
2313 if (r < 0)
2314 return r;
2315
2316 r = safe_atoi(value, &v);
2317 if (r < 0)
2318 return r;
2319
2320 if (ret)
2321 *ret = v;
2322 return 0;
2323 }
2324
2325 int device_get_property_uint(sd_device *device, const char *key, unsigned *ret) {
2326 const char *value;
2327 int r;
2328
2329 assert(device);
2330 assert(key);
2331
2332 r = sd_device_get_property_value(device, key, &value);
2333 if (r < 0)
2334 return r;
2335
2336 unsigned v;
2337 r = safe_atou(value, &v);
2338 if (r < 0)
2339 return r;
2340
2341 if (ret)
2342 *ret = v;
2343 return 0;
2344 }
2345
2346 _public_ int sd_device_get_trigger_uuid(sd_device *device, sd_id128_t *ret) {
2347 const char *s;
2348 sd_id128_t id;
2349 int r;
2350
2351 assert_return(device, -EINVAL);
2352
2353 /* Retrieves the UUID attached to a uevent when triggering it from userspace via
2354 * sd_device_trigger_with_uuid() or an equivalent interface. Returns -ENOENT if the record is not
2355 * caused by a synthetic event and -ENODATA if it was but no UUID was specified */
2356
2357 r = sd_device_get_property_value(device, "SYNTH_UUID", &s);
2358 if (r < 0)
2359 return r;
2360
2361 if (streq(s, "0")) /* SYNTH_UUID=0 is set whenever a device is triggered by userspace without specifying a UUID */
2362 return -ENODATA;
2363
2364 r = sd_id128_from_string(s, &id);
2365 if (r < 0)
2366 return r;
2367
2368 if (ret)
2369 *ret = id;
2370
2371 return 0;
2372 }
2373
2374 void device_clear_sysattr_cache(sd_device *device) {
2375 device->sysattr_values = hashmap_free(device->sysattr_values);
2376 }
2377
2378 typedef struct SysAttrCacheEntry {
2379 char *key;
2380 char *value;
2381 char *value_stripped;
2382 size_t size;
2383 int error;
2384 } SysAttrCacheEntry;
2385
2386 static SysAttrCacheEntry* sysattr_cache_entry_free(SysAttrCacheEntry *p) {
2387 if (!p)
2388 return NULL;
2389
2390 free(p->key);
2391 free(p->value);
2392 free(p->value_stripped);
2393 return mfree(p);
2394 }
2395
2396 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
2397 sysattr_cache_hash_ops,
2398 char, path_hash_func, path_compare,
2399 SysAttrCacheEntry, sysattr_cache_entry_free);
2400
2401 static int device_cache_sysattr_value_full(sd_device *device, char *key, char *value, size_t size, int error, bool ignore_uevent) {
2402 int r;
2403
2404 assert(device);
2405 assert(key);
2406 assert(value || error > 0);
2407
2408 /* This takes the reference of the input arguments when cached, hence the caller must not free them
2409 * when a positive return value is returned. The input value may be NULL. This replaces an already
2410 * existing entry. */
2411
2412 if (ignore_uevent && streq(last_path_component(key), "uevent"))
2413 return 0; /* not cached */
2414
2415 /* Remove the old cache entry. So, we do not need to clear cache on error. */
2416 sysattr_cache_entry_free(hashmap_remove(device->sysattr_values, key));
2417
2418 /* We use ENOANO as a recognizable error code when we have not read the attribute. */
2419 if (error == ENOANO)
2420 error = ESTALE;
2421
2422 _cleanup_free_ SysAttrCacheEntry *entry = new(SysAttrCacheEntry, 1);
2423 if (!entry)
2424 return -ENOMEM;
2425
2426 _cleanup_free_ char *value_stripped = NULL;
2427
2428 if (value) {
2429 value_stripped = memdup_suffix0(value, size);
2430 if (!value_stripped)
2431 return -ENOMEM;
2432 delete_trailing_chars(value_stripped, NEWLINE);
2433 }
2434
2435 *entry = (SysAttrCacheEntry) {
2436 .key = key,
2437 .value = value,
2438 .value_stripped = value_stripped,
2439 .size = size,
2440 .error = error,
2441 };
2442
2443 r = hashmap_ensure_put(&device->sysattr_values, &sysattr_cache_hash_ops, entry->key, entry);
2444 if (r < 0)
2445 return r;
2446
2447 TAKE_PTR(entry);
2448 TAKE_PTR(value_stripped);
2449 return 1; /* cached */
2450 }
2451
2452 int device_cache_sysattr_value(sd_device *device, char *key, char *value, int error) {
2453 return device_cache_sysattr_value_full(device, key, value, strlen(value), error, /* ignore_uevent= */ true);
2454 }
2455
2456 static int device_get_cached_sysattr_value(sd_device *device, const char *key, const char **ret_value, size_t *ret_size) {
2457 SysAttrCacheEntry *entry;
2458
2459 assert(device);
2460 assert(key);
2461
2462 entry = hashmap_get(device->sysattr_values, key);
2463 if (!entry)
2464 return -ENOANO; /* We have not read the attribute. */
2465 if (!entry->value) {
2466 /* We have looked up the attribute before and failed. Return the cached error code. */
2467 assert(entry->error > 0);
2468 return -entry->error;
2469 }
2470 if (ret_value)
2471 *ret_value = ret_size ? entry->value : entry->value_stripped;
2472 if (ret_size)
2473 *ret_size = entry->size;
2474 return 0;
2475 }
2476
2477 int device_chase(sd_device *device, const char *path, ChaseFlags flags, char **ret_resolved, int *ret_fd) {
2478 int r;
2479
2480 assert(device);
2481 assert(path);
2482
2483 const char *syspath;
2484 r = sd_device_get_syspath(device, &syspath);
2485 if (r < 0)
2486 return r;
2487
2488 /* Here, CHASE_PREFIX_ROOT is borrowed. If the flag is set or the specified path is relative, then
2489 * the path will be prefixed with the syspath. Note, we do not pass CHASE_PREFIX_ROOT flag with
2490 * syspath as root to chase(), but we manually concatenate the specified path with syspath before
2491 * calling chase(). Otherwise, we cannot set/get attributes of parent or sibling devices. */
2492 _cleanup_free_ char *prefixed = NULL;
2493 if (FLAGS_SET(flags, CHASE_PREFIX_ROOT) || !path_is_absolute(path)) {
2494 prefixed = path_join(syspath, path);
2495 if (!prefixed)
2496 return -ENOMEM;
2497 path = prefixed;
2498 flags &= ~CHASE_PREFIX_ROOT;
2499 }
2500
2501 _cleanup_free_ char *resolved = NULL;
2502 _cleanup_close_ int fd = -EBADF;
2503 r = chase(path, /* root= */ NULL, CHASE_NO_AUTOFS | flags, &resolved, ret_fd ? &fd : NULL);
2504 if (r < 0)
2505 return r;
2506
2507 /* Refuse to reading/writing files outside of sysfs. */
2508 if (!path_startswith(resolved, "/sys/"))
2509 return -EINVAL;
2510
2511 if (ret_resolved) {
2512 /* Always return relative path. */
2513 r = path_make_relative(syspath, resolved, ret_resolved);
2514 if (r < 0)
2515 return r;
2516 }
2517
2518 if (ret_fd)
2519 *ret_fd = TAKE_FD(fd);
2520
2521 return 0;
2522 }
2523
2524 _public_ int sd_device_get_sysattr_value_with_size(sd_device *device, const char *sysattr, const char **ret_value, size_t *ret_size) {
2525 _cleanup_free_ char *resolved = NULL, *value = NULL;
2526 _cleanup_close_ int fd = -EBADF;
2527 size_t size = 0;
2528 int r;
2529
2530 assert_return(device, -EINVAL);
2531 assert_return(sysattr, -EINVAL);
2532
2533 /* Look for possibly already cached result. */
2534 r = device_get_cached_sysattr_value(device, sysattr, ret_value, ret_size);
2535 if (r != -ENOANO)
2536 return r;
2537
2538 /* Special cases: read the symlink and return the last component of the value. Some core links return
2539 * only the last element of the target path, these are just values, the paths should not be exposed. */
2540 if (STR_IN_SET(sysattr, "driver", "subsystem", "module")) {
2541 _cleanup_free_ char *prefixed = NULL;
2542 const char *syspath;
2543
2544 r = sd_device_get_syspath(device, &syspath);
2545 if (r < 0)
2546 return r;
2547
2548 prefixed = path_join(syspath, sysattr);
2549 if (!prefixed)
2550 return -ENOMEM;
2551
2552 r = readlink_value(prefixed, &value);
2553 if (r >= 0)
2554 size = strlen(value);
2555
2556 if (r != -EINVAL) /* -EINVAL means the path is not a symlink. */
2557 goto cache_result;
2558 }
2559
2560 r = device_chase(device, sysattr, CHASE_PREFIX_ROOT, &resolved, &fd);
2561 if (r < 0)
2562 goto cache_result;
2563
2564 /* Look for cached result again with the resolved path. */
2565 r = device_get_cached_sysattr_value(device, resolved, ret_value, ret_size);
2566 if (r != -ENOANO)
2567 return r;
2568
2569 /* Read attribute value, Some attributes contain embedded '\0'. So, it is necessary to also get the
2570 * size of the result. See issue #20025. */
2571 r = read_virtual_file_fd(fd, SIZE_MAX, &value, &size);
2572 if (r < 0)
2573 goto cache_result;
2574
2575 r = 0;
2576
2577 cache_result:
2578 if (r == -ENOMEM)
2579 return r; /* Do not cache -ENOMEM, as the failure may be transient. */
2580
2581 if (!resolved) {
2582 /* If we have not or could not chase the path, assume 'sysattr' is normalized. */
2583 resolved = strdup(sysattr);
2584 if (!resolved)
2585 return RET_GATHER(r, -ENOMEM);
2586 }
2587
2588 int k = device_cache_sysattr_value_full(device, resolved, value, size, -r, /* ignore_uevent= */ false);
2589 if (k < 0) {
2590 if (r < 0)
2591 log_device_debug_errno(device, k,
2592 "sd-device: failed to cache error code (%i) in reading attribute '%s', ignoring: %m",
2593 -r, resolved);
2594 else {
2595 /* Unfortunately, we need to return 'const char*' instead of 'char*'. Hence, failure in caching
2596 * sysattr value is critical unlike the other places. */
2597 log_device_debug_errno(device, k,
2598 "sd-device: failed to cache attribute '%s' with '%s'%s: %m",
2599 resolved, value, ret_value ? "" : ", ignoring");
2600 if (ret_value)
2601 return k;
2602 }
2603
2604 return r;
2605 }
2606 assert(k > 0);
2607
2608 /* device_cache_sysattr_value_full() takes 'resolved' and 'value' on success. */
2609 sysattr = TAKE_PTR(resolved);
2610 TAKE_PTR(value);
2611
2612 if (r < 0)
2613 return r;
2614
2615 return device_get_cached_sysattr_value(device, sysattr, ret_value, ret_size);
2616 }
2617
2618 _public_ int sd_device_get_sysattr_value(sd_device *device, const char *sysattr, const char **ret) {
2619 return sd_device_get_sysattr_value_with_size(device, sysattr, ret, NULL);
2620 }
2621
2622 int device_get_sysattr_streq(sd_device *device, const char *sysattr, const char *expected) {
2623 const char *value;
2624 int r;
2625
2626 assert(expected);
2627
2628 r = sd_device_get_sysattr_value(device, sysattr, &value);
2629 if (r < 0)
2630 return r;
2631
2632 return streq(value, expected);
2633 }
2634
2635 int device_get_sysattr_safe_string(sd_device *device, const char *sysattr, const char **ret) {
2636 const char *value;
2637 int r;
2638
2639 r = sd_device_get_sysattr_value(device, sysattr, &value);
2640 if (r < 0)
2641 return r;
2642
2643 if (!string_is_safe(value,
2644 STRING_ALLOW_EMPTY |
2645 STRING_ALLOW_NEWLINES |
2646 STRING_ALLOW_BACKSLASHES |
2647 STRING_ALLOW_QUOTES |
2648 STRING_ALLOW_GLOBS)) {
2649 if (DEBUG_LOGGING) {
2650 _cleanup_free_ char *escaped = cescape(value);
2651 log_device_debug(device, "sd-device: '%s' sysattr contains invalid characters, refusing: %s",
2652 sysattr, strnull(escaped));
2653 }
2654 return -ENXIO;
2655 }
2656
2657 if (ret)
2658 *ret = value;
2659
2660 return 0;
2661 }
2662
2663 #define DEFINE_DEVICE_GET_SYSATTR_PARSE(name, type, parser) \
2664 int device_get_sysattr_##name(sd_device *device, const char *sysattr, type *ret) { \
2665 const char *value; \
2666 int r; \
2667 \
2668 r = sd_device_get_sysattr_value(device, sysattr, &value); \
2669 if (r < 0) \
2670 return r; \
2671 \
2672 type v; \
2673 r = parser(value, &v); \
2674 if (r < 0) \
2675 return log_device_debug_errno(device, r, "Failed to parse '%s' attribute: %m", sysattr); \
2676 \
2677 if (ret) \
2678 *ret = v; \
2679 /* We return "true" if the value is positive. */ \
2680 return v > 0; \
2681 }
2682
2683 #define DEFINE_DEVICE_GET_SYSATTR_PARSE_BASE(name, type, parser) \
2684 int device_get_sysattr_##name##_full(sd_device *device, const char *sysattr, unsigned base, type *ret) { \
2685 const char *value; \
2686 int r; \
2687 \
2688 r = sd_device_get_sysattr_value(device, sysattr, &value); \
2689 if (r < 0) \
2690 return r; \
2691 \
2692 type v; \
2693 r = parser(value, base, &v); \
2694 if (r < 0) \
2695 return log_device_debug_errno(device, r, "Failed to parse '%s' attribute: %m", sysattr); \
2696 \
2697 if (ret) \
2698 *ret = v; \
2699 /* We return "true" if the value is positive. */ \
2700 return v > 0; \
2701 }
2702
2703 DEFINE_DEVICE_GET_SYSATTR_PARSE(int, int, safe_atoi);
2704 DEFINE_DEVICE_GET_SYSATTR_PARSE_BASE(unsigned, unsigned, safe_atou_full);
2705 DEFINE_DEVICE_GET_SYSATTR_PARSE_BASE(u8, uint8_t, safe_atou8_full);
2706 DEFINE_DEVICE_GET_SYSATTR_PARSE_BASE(u16, uint16_t, safe_atou16_full);
2707 DEFINE_DEVICE_GET_SYSATTR_PARSE_BASE(u32, uint32_t, safe_atou32_full);
2708 DEFINE_DEVICE_GET_SYSATTR_PARSE(u64, uint64_t, safe_atou64);
2709
2710 int device_get_sysattr_bool(sd_device *device, const char *sysattr) {
2711 const char *value;
2712 int r;
2713
2714 assert(device);
2715 assert(sysattr);
2716
2717 r = sd_device_get_sysattr_value(device, sysattr, &value);
2718 if (r < 0)
2719 return r;
2720
2721 return parse_boolean(value);
2722 }
2723
2724 static int device_remove_cached_sysattr_value(sd_device *device, const char *sysattr) {
2725 int r;
2726
2727 assert(device);
2728 assert(sysattr);
2729
2730 _cleanup_free_ char *resolved = NULL;
2731 r = device_chase(device, sysattr, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &resolved, /* ret_fd= */ NULL);
2732 if (r < 0)
2733 return r;
2734
2735 sysattr_cache_entry_free(hashmap_remove(device->sysattr_values, resolved));
2736 return 0;
2737 }
2738
2739 _public_ int sd_device_set_sysattr_value(sd_device *device, const char *sysattr, const char *value) {
2740 int r;
2741
2742 assert_return(device, -EINVAL);
2743 assert_return(sysattr, -EINVAL);
2744
2745 /* Set the attribute and save it in the cache. */
2746
2747 if (!value)
2748 /* If input value is NULL, then clear cache and not write anything. */
2749 return device_remove_cached_sysattr_value(device, sysattr);
2750
2751 _cleanup_free_ char *resolved = NULL;
2752 _cleanup_close_ int fd = -EBADF;
2753 r = device_chase(device, sysattr, CHASE_PREFIX_ROOT, &resolved, &fd);
2754 if (r < 0) {
2755 /* On failure, clear cache entry, hopefully, 'sysattr' is normalized. */
2756 sysattr_cache_entry_free(hashmap_remove(device->sysattr_values, sysattr));
2757 return r;
2758 }
2759
2760 /* value length is limited to 4k */
2761 _cleanup_free_ char *copied = strndup(value, 4096);
2762 if (!copied)
2763 return -ENOMEM;
2764
2765 /* drop trailing newlines */
2766 delete_trailing_chars(copied, NEWLINE);
2767
2768 r = write_string_file_fd(fd, copied, WRITE_STRING_FILE_DISABLE_BUFFER | WRITE_STRING_FILE_AVOID_NEWLINE);
2769 if (r < 0) {
2770 /* On failure, clear cache entry, as we do not know how it fails. */
2771 sysattr_cache_entry_free(hashmap_remove(device->sysattr_values, resolved));
2772 return r;
2773 }
2774
2775 r = device_cache_sysattr_value(device, resolved, copied, 0);
2776 if (r < 0)
2777 log_device_debug_errno(device, r,
2778 "sd-device: failed to cache written attribute '%s' with '%s', ignoring: %m",
2779 resolved, copied);
2780 else if (r > 0) {
2781 TAKE_PTR(resolved);
2782 TAKE_PTR(copied);
2783 }
2784
2785 return 0;
2786 }
2787
2788 _public_ int sd_device_set_sysattr_valuef(sd_device *device, const char *sysattr, const char *format, ...) {
2789 _cleanup_free_ char *value = NULL;
2790 va_list ap;
2791 int r;
2792
2793 assert_return(device, -EINVAL);
2794 assert_return(sysattr, -EINVAL);
2795
2796 if (!format)
2797 return device_remove_cached_sysattr_value(device, sysattr);
2798
2799 va_start(ap, format);
2800 r = vasprintf(&value, format, ap);
2801 va_end(ap);
2802
2803 if (r < 0)
2804 return -ENOMEM;
2805
2806 return sd_device_set_sysattr_value(device, sysattr, value);
2807 }
2808
2809 _public_ int sd_device_trigger(sd_device *device, sd_device_action_t action) {
2810 return sd_device_trigger_with_uuid(device, action, NULL);
2811 }
2812
2813 _public_ int sd_device_trigger_with_uuid(
2814 sd_device *device,
2815 sd_device_action_t action,
2816 sd_id128_t *ret_uuid) {
2817
2818 const char *s, *j;
2819 sd_id128_t u;
2820 int r;
2821
2822 assert_return(device, -EINVAL);
2823
2824 s = device_action_to_string(action);
2825 if (!s)
2826 return -EINVAL;
2827
2828 r = sd_id128_randomize(&u);
2829 if (r < 0)
2830 return r;
2831
2832 j = strjoina(s, " ", SD_ID128_TO_UUID_STRING(u));
2833
2834 r = sd_device_set_sysattr_value(device, "uevent", j);
2835 if (r < 0)
2836 return r;
2837
2838 if (ret_uuid)
2839 *ret_uuid = u;
2840 return 0;
2841 }
2842
2843 _public_ int sd_device_open(sd_device *device, int flags) {
2844 _cleanup_close_ int fd = -EBADF, fd2 = -EBADF;
2845 const char *devname;
2846 uint64_t q, diskseq = 0;
2847 struct stat st;
2848 dev_t devnum;
2849 int r;
2850
2851 assert_return(device, -EINVAL);
2852 assert_return(FLAGS_SET(flags, O_PATH) || !FLAGS_SET(flags, O_NOFOLLOW), -EINVAL);
2853
2854 r = sd_device_get_devname(device, &devname);
2855 if (r == -ENOENT)
2856 return -ENOEXEC;
2857 if (r < 0)
2858 return r;
2859
2860 r = sd_device_get_devnum(device, &devnum);
2861 if (r == -ENOENT)
2862 return -ENOEXEC;
2863 if (r < 0)
2864 return r;
2865
2866 fd = open(devname, FLAGS_SET(flags, O_PATH) ? flags : O_CLOEXEC|O_NOFOLLOW|O_PATH);
2867 if (fd < 0)
2868 return -errno;
2869
2870 if (fstat(fd, &st) < 0)
2871 return -errno;
2872
2873 if (st.st_rdev != devnum)
2874 return -ENXIO;
2875
2876 r = device_in_subsystem(device, "block");
2877 if (r < 0)
2878 return r;
2879 if (r > 0 ? !S_ISBLK(st.st_mode) : !S_ISCHR(st.st_mode))
2880 return -ENXIO;
2881
2882 /* If flags has O_PATH, then we cannot check diskseq. Let's return earlier. */
2883 if (FLAGS_SET(flags, O_PATH))
2884 return TAKE_FD(fd);
2885
2886 /* If the device is not initialized, then we cannot determine if we should check diskseq through
2887 * ID_IGNORE_DISKSEQ property. Let's skip to check diskseq in that case. */
2888 r = sd_device_get_is_initialized(device);
2889 if (r < 0)
2890 return r;
2891 if (r > 0) {
2892 r = device_get_property_bool(device, "ID_IGNORE_DISKSEQ");
2893 if (r < 0 && r != -ENOENT)
2894 return r;
2895 if (r <= 0) {
2896 r = sd_device_get_diskseq(device, &diskseq);
2897 if (r < 0 && r != -ENOENT)
2898 return r;
2899 }
2900 }
2901
2902 fd2 = fd_reopen(fd, flags);
2903 if (fd2 < 0)
2904 return fd2;
2905
2906 if (diskseq == 0)
2907 return TAKE_FD(fd2);
2908
2909 r = fd_get_diskseq(fd2, &q);
2910 if (r < 0)
2911 return r;
2912
2913 if (q != diskseq)
2914 return -ENXIO;
2915
2916 return TAKE_FD(fd2);
2917 }
2918
2919 int device_opendir(sd_device *device, const char *subdir, DIR **ret) {
2920 _cleanup_closedir_ DIR *d = NULL;
2921 _cleanup_free_ char *path = NULL;
2922 const char *syspath;
2923 int r;
2924
2925 assert(device);
2926 assert(ret);
2927
2928 r = sd_device_get_syspath(device, &syspath);
2929 if (r < 0)
2930 return r;
2931
2932 if (subdir) {
2933 if (!path_is_safe(subdir))
2934 return -EINVAL;
2935
2936 path = path_join(syspath, subdir);
2937 if (!path)
2938 return -ENOMEM;
2939 }
2940
2941 d = opendir(path ?: syspath);
2942 if (!d)
2943 return -errno;
2944
2945 *ret = TAKE_PTR(d);
2946 return 0;
2947 }