Debian Codegraph @

src/udev/udevadm-info.c

raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 #include <ctype.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <sys/stat.h>
7 #include <sys/sysmacros.h>
8 #include <unistd.h>
9
10 #include "sd-device.h"
11 #include "sd-json.h"
12
13 #include "alloc-util.h"
14 #include "ansi-color.h"
15 #include "device-enumerator-private.h"
16 #include "device-private.h"
17 #include "device-util.h"
18 #include "dirent-util.h"
19 #include "errno-util.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "format-table.h"
23 #include "glyph-util.h"
24 #include "help-util.h"
25 #include "options.h"
26 #include "pager.h"
27 #include "parse-argument.h"
28 #include "sort-util.h"
29 #include "static-destruct.h"
30 #include "string-table.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "time-util.h"
34 #include "udev-util.h"
35 #include "udevadm.h"
36 #include "udevadm-util.h"
37
38 typedef enum ActionType {
39 ACTION_QUERY,
40 ACTION_ATTRIBUTE_WALK,
41 ACTION_DEVICE_ID_FILE,
42 ACTION_TREE,
43 ACTION_EXPORT,
44 ACTION_CLEANUP_DB,
45 } ActionType;
46
47 typedef enum QueryType {
48 QUERY_NAME,
49 QUERY_PATH,
50 QUERY_SYMLINK,
51 QUERY_PROPERTY,
52 QUERY_ALL,
53 _QUERY_TYPE_MAX,
54 _QUERY_TYPE_INVALID = -EINVAL,
55 } QueryType;
56
57 static char **arg_properties = NULL;
58 static bool arg_root = false;
59 static bool arg_export = false;
60 static bool arg_value = false;
61 static const char *arg_export_prefix = NULL;
62 static usec_t arg_wait_for_initialization_timeout = 0;
63 static PagerFlags arg_pager_flags = 0;
64 static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
65 static ActionType arg_action_type = ACTION_QUERY;
66 static QueryType arg_query = QUERY_ALL;
67 static char **arg_devices = NULL;
68 static char *arg_name = NULL;
69 static char **arg_attr_match = NULL;
70 static char **arg_attr_nomatch = NULL;
71 static char **arg_name_match = NULL;
72 static char **arg_parent_match = NULL;
73 static char **arg_property_match = NULL;
74 static char **arg_subsystem_match = NULL;
75 static char **arg_subsystem_nomatch = NULL;
76 static char **arg_sysname_match = NULL;
77 static char **arg_tag_match = NULL;
78 static int arg_initialized_match = -1;
79
80 STATIC_DESTRUCTOR_REGISTER(arg_properties, strv_freep);
81 STATIC_DESTRUCTOR_REGISTER(arg_devices, strv_freep);
82 STATIC_DESTRUCTOR_REGISTER(arg_name, freep);
83 STATIC_DESTRUCTOR_REGISTER(arg_attr_match, strv_freep);
84 STATIC_DESTRUCTOR_REGISTER(arg_attr_nomatch, strv_freep);
85 STATIC_DESTRUCTOR_REGISTER(arg_name_match, strv_freep);
86 STATIC_DESTRUCTOR_REGISTER(arg_parent_match, strv_freep);
87 STATIC_DESTRUCTOR_REGISTER(arg_property_match, strv_freep);
88 STATIC_DESTRUCTOR_REGISTER(arg_subsystem_match, strv_freep);
89 STATIC_DESTRUCTOR_REGISTER(arg_subsystem_nomatch, strv_freep);
90 STATIC_DESTRUCTOR_REGISTER(arg_sysname_match, strv_freep);
91 STATIC_DESTRUCTOR_REGISTER(arg_tag_match, strv_freep);
92
93 /* Put a limit on --tree descent level to not exhaust our stack */
94 #define TREE_DEPTH_MAX 64
95
96 static const char *query_type_table[_QUERY_TYPE_MAX] = {
97 [QUERY_NAME] = "name",
98 [QUERY_PATH] = "path",
99 [QUERY_SYMLINK] = "symlink",
100 [QUERY_PROPERTY] = "property",
101 [QUERY_ALL] = "all",
102 };
103
104 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(query_type, QueryType);
105
106 static bool skip_attribute(const char *name) {
107 assert(name);
108
109 /* Those are either displayed separately or should not be shown at all. */
110 return STR_IN_SET(name,
111 "uevent",
112 "dev",
113 "modalias",
114 "resource",
115 "driver",
116 "subsystem",
117 "module");
118 }
119
120 typedef struct SysAttr {
121 const char *name;
122 const char *value;
123 } SysAttr;
124
125 static int sysattr_compare(const SysAttr *a, const SysAttr *b) {
126 assert(a);
127 assert(b);
128
129 return strcmp(a->name, b->name);
130 }
131
132 static int print_all_attributes(sd_device *device, bool is_parent) {
133 _cleanup_free_ SysAttr *sysattrs = NULL;
134 const char *value;
135 size_t n_items = 0;
136 int r;
137
138 assert(device);
139
140 if (is_parent)
141 puts("");
142
143 value = NULL;
144 (void) sd_device_get_devpath(device, &value);
145 printf(" looking at %sdevice '%s':\n", is_parent ? "parent " : "", strempty(value));
146
147 value = NULL;
148 (void) sd_device_get_sysname(device, &value);
149 printf(" %s==\"%s\"\n", is_parent ? "KERNELS" : "KERNEL", strempty(value));
150
151 value = NULL;
152 (void) sd_device_get_subsystem(device, &value);
153 printf(" %s==\"%s\"\n", is_parent ? "SUBSYSTEMS" : "SUBSYSTEM", strempty(value));
154
155 value = NULL;
156 (void) sd_device_get_driver(device, &value);
157 printf(" %s==\"%s\"\n", is_parent ? "DRIVERS" : "DRIVER", strempty(value));
158
159 FOREACH_DEVICE_SYSATTR(device, name) {
160 size_t len;
161
162 if (skip_attribute(name))
163 continue;
164
165 r = device_get_sysattr_safe_string(device, name, &value);
166 if (r >= 0) {
167 /* skip any values that look like a path */
168 if (value[0] == '/')
169 continue;
170
171 /* skip nonprintable attributes */
172 len = strlen(value);
173 while (len > 0 && isprint((unsigned char) value[len-1]))
174 len--;
175 if (len > 0)
176 continue;
177
178 } else if (ERRNO_IS_PRIVILEGE(r))
179 value = "(not readable)";
180 else
181 continue;
182
183 if (!GREEDY_REALLOC(sysattrs, n_items + 1))
184 return log_oom();
185
186 sysattrs[n_items] = (SysAttr) {
187 .name = name,
188 .value = value,
189 };
190 n_items++;
191 }
192
193 typesafe_qsort(sysattrs, n_items, sysattr_compare);
194
195 FOREACH_ARRAY(i, sysattrs, n_items)
196 printf(" %s{%s}==\"%s\"\n", is_parent ? "ATTRS" : "ATTR", i->name, i->value);
197
198 return 0;
199 }
200
201 static int print_device_chain(sd_device *device) {
202 sd_device *child, *parent;
203 int r;
204
205 assert(device);
206
207 printf("\n"
208 "Udevadm info starts with the device specified by the devpath and then\n"
209 "walks up the chain of parent devices. It prints for every device\n"
210 "found, all possible attributes in the udev rules key format.\n"
211 "A rule to match, can be composed by the attributes of the device\n"
212 "and the attributes from one single parent device.\n"
213 "\n");
214
215 r = print_all_attributes(device, /* is_parent= */ false);
216 if (r < 0)
217 return r;
218
219 for (child = device; sd_device_get_parent(child, &parent) >= 0; child = parent) {
220 r = print_all_attributes(parent, /* is_parent= */ true);
221 if (r < 0)
222 return r;
223 }
224
225 return 0;
226 }
227
228 static int print_all_attributes_in_json(sd_device *device, bool is_parent) {
229 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *w = NULL;
230 _cleanup_free_ SysAttr *sysattrs = NULL;
231 const char *value;
232 size_t n_items = 0;
233 int r;
234
235 assert(device);
236
237 value = NULL;
238 (void) sd_device_get_devpath(device, &value);
239 r = sd_json_variant_set_field_string(&v, "DEVPATH", value);
240 if (r < 0)
241 return r;
242
243 value = NULL;
244 (void) sd_device_get_sysname(device, &value);
245 r = sd_json_variant_set_field_string(&v, is_parent ? "KERNELS" : "KERNEL", value);
246 if (r < 0)
247 return r;
248
249 value = NULL;
250 (void) sd_device_get_subsystem(device, &value);
251 r = sd_json_variant_set_field_string(&v, is_parent ? "SUBSYSTEMS" : "SUBSYSTEM", value);
252 if (r < 0)
253 return r;
254
255 value = NULL;
256 (void) sd_device_get_driver(device, &value);
257 r = sd_json_variant_set_field_string(&v, is_parent ? "DRIVERS" : "DRIVER", value);
258 if (r < 0)
259 return r;
260
261 FOREACH_DEVICE_SYSATTR(device, name) {
262 size_t len;
263
264 if (skip_attribute(name))
265 continue;
266
267 r = device_get_sysattr_safe_string(device, name, &value);
268 if (r >= 0) {
269 /* skip any values that look like a path */
270 if (value[0] == '/')
271 continue;
272
273 /* skip nonprintable attributes */
274 len = strlen(value);
275 while (len > 0 && isprint((unsigned char) value[len-1]))
276 len--;
277 if (len > 0)
278 continue;
279
280 } else if (ERRNO_IS_PRIVILEGE(r))
281 value = "(not readable)";
282 else
283 continue;
284
285 if (!GREEDY_REALLOC(sysattrs, n_items + 1))
286 return log_oom();
287
288 sysattrs[n_items] = (SysAttr) {
289 .name = name,
290 .value = value,
291 };
292 n_items++;
293 }
294
295 typesafe_qsort(sysattrs, n_items, sysattr_compare);
296
297 FOREACH_ARRAY(i, sysattrs, n_items) {
298 r = sd_json_variant_set_field_string(&w, i->name, i->value);
299 if (r < 0)
300 return r;
301 }
302
303 r = sd_json_variant_set_field(&v, is_parent ? "ATTRS" : "ATTR", w);
304 if (r < 0)
305 return r;
306
307 return sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
308 }
309
310 static int print_device_chain_in_json(sd_device *device) {
311 sd_device *child, *parent;
312 int r;
313
314 assert(device);
315
316 arg_json_format_flags |=SD_JSON_FORMAT_SEQ;
317
318 r = print_all_attributes_in_json(device, /* is_parent= */ false);
319 if (r < 0)
320 return r;
321
322 for (child = device; sd_device_get_parent(child, &parent) >= 0; child = parent) {
323 r = print_all_attributes_in_json(parent, /* is_parent= */ true);
324 if (r < 0)
325 return r;
326 }
327
328 return 0;
329 }
330
331 static int print_record(sd_device *device, const char *prefix) {
332 const char *str, *subsys;
333 dev_t devnum;
334 uint64_t q;
335 int i, ifi;
336
337 assert(device);
338
339 prefix = strempty(prefix);
340
341 /* We don't show syspath here, because it's identical to devpath (modulo the "/sys" prefix).
342 *
343 * We don't show action/seqnum here because that only makes sense for records synthesized from
344 * uevents, not for those synthesized from database entries.
345 *
346 * We don't show sysattrs here, because they can be expensive and potentially issue expensive driver
347 * IO.
348 *
349 * Coloring: let's be conservative with coloring. Let's use it to group related fields. Right now:
350 *
351 * • highlight fields that give the device a name
352 * • green for fields that categorize the device into subsystem/devtype and similar
353 * • cyan for fields about associated device nodes/symlinks/network interfaces and such
354 * • magenta for block device diskseq
355 * • yellow for driver info
356 * • no color for regular properties */
357
358 assert_se(sd_device_get_devpath(device, &str) >= 0);
359 printf("%sP: %s%s%s\n", prefix, ansi_highlight(), str, ansi_normal());
360
361 if (sd_device_get_sysname(device, &str) >= 0)
362 printf("%sM: %s%s%s\n", prefix, ansi_highlight(), str, ansi_normal());
363
364 if (sd_device_get_sysnum(device, &str) >= 0)
365 printf("%sR: %s%s%s\n", prefix, ansi_highlight(), str, ansi_normal());
366
367 if (sd_device_get_device_id(device, &str) >= 0)
368 printf("%sJ: %s%s%s\n", prefix, ansi_highlight(), str, ansi_normal());
369
370 if (sd_device_get_subsystem(device, &subsys) >= 0)
371 printf("%sU: %s%s%s\n", prefix, ansi_highlight_green(), subsys, ansi_normal());
372
373 if (sd_device_get_driver_subsystem(device, &str) >= 0)
374 printf("%sB: %s%s%s\n", prefix, ansi_highlight_green(), str, ansi_normal());
375
376 if (sd_device_get_devtype(device, &str) >= 0)
377 printf("%sT: %s%s%s\n", prefix, ansi_highlight_green(), str, ansi_normal());
378
379 if (sd_device_get_devnum(device, &devnum) >= 0)
380 printf("%sD: %s%c %u:%u%s\n",
381 prefix,
382 ansi_highlight_cyan(),
383 streq_ptr(subsys, "block") ? 'b' : 'c', major(devnum), minor(devnum),
384 ansi_normal());
385
386 if (sd_device_get_ifindex(device, &ifi) >= 0)
387 printf("%sI: %s%i%s\n", prefix, ansi_highlight_cyan(), ifi, ansi_normal());
388
389 if (sd_device_get_devname(device, &str) >= 0) {
390 const char *val;
391
392 assert_se(val = path_startswith(str, "/dev/"));
393 printf("%sN: %s%s%s\n", prefix, ansi_highlight_cyan(), val, ansi_normal());
394
395 if (device_get_devlink_priority(device, &i) >= 0)
396 printf("%sL: %s%i%s\n", prefix, ansi_highlight_cyan(), i, ansi_normal());
397
398 FOREACH_DEVICE_DEVLINK(device, link) {
399 assert_se(val = path_startswith(link, "/dev/"));
400 printf("%sS: %s%s%s\n", prefix, ansi_highlight_cyan(), val, ansi_normal());
401 }
402 }
403
404 if (sd_device_get_diskseq(device, &q) >= 0)
405 printf("%sQ: %s%" PRIu64 "%s\n", prefix, ansi_highlight_magenta(), q, ansi_normal());
406
407 if (sd_device_get_driver(device, &str) >= 0)
408 printf("%sV: %s%s%s\n", prefix, ansi_highlight_yellow4(), str, ansi_normal());
409
410 FOREACH_DEVICE_PROPERTY(device, key, val)
411 printf("%sE: %s=%s\n", prefix, key, val);
412
413 if (isempty(prefix))
414 puts("");
415 return 0;
416 }
417
418 static int record_to_json(sd_device *device, sd_json_variant **ret) {
419 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
420 const char *str;
421 int r;
422
423 assert(device);
424 assert(ret);
425
426 /* We don't show any shorthand fields here as done in print_record() except for SYSNAME, SYSNUM,
427 * DRIVER_SUBSYSTEM, and DEVICE_ID, as all the other ones have a matching property which will already
428 * be included. */
429
430 if (sd_device_get_sysname(device, &str) >= 0) {
431 r = sd_json_variant_set_field_string(&v, "SYSNAME", str);
432 if (r < 0)
433 return r;
434 }
435
436 if (sd_device_get_sysnum(device, &str) >= 0) {
437 r = sd_json_variant_set_field_string(&v, "SYSNUM", str);
438 if (r < 0)
439 return r;
440 }
441
442 if (sd_device_get_driver_subsystem(device, &str) >= 0) {
443 r = sd_json_variant_set_field_string(&v, "DRIVER_SUBSYSTEM", str);
444 if (r < 0)
445 return r;
446 }
447
448 if (sd_device_get_device_id(device, &str) >= 0) {
449 r = sd_json_variant_set_field_string(&v, "DEVICE_ID", str);
450 if (r < 0)
451 return r;
452 }
453
454 FOREACH_DEVICE_PROPERTY(device, key, val) {
455 r = sd_json_variant_set_field_string(&v, key, val);
456 if (r < 0)
457 return r;
458 }
459
460 *ret = TAKE_PTR(v);
461 return 0;
462 }
463
464 static int stat_device(void) {
465 struct stat statbuf;
466
467 assert(arg_name);
468
469 if (stat(arg_name, &statbuf) != 0)
470 return -errno;
471
472 if (arg_export) {
473 const char *prefix = arg_export_prefix ?: "INFO_";
474 printf("%sMAJOR=%u\n"
475 "%sMINOR=%u\n",
476 prefix, major(statbuf.st_dev),
477 prefix, minor(statbuf.st_dev));
478 } else
479 printf("%u:%u\n", major(statbuf.st_dev), minor(statbuf.st_dev));
480 return 0;
481 }
482
483 static int add_match_parent(sd_device_enumerator *e, const char *s, const char *prefix) {
484 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
485 int r;
486
487 assert(e);
488 assert(s);
489
490 r = find_device(s, prefix, &dev);
491 if (r < 0)
492 return log_error_errno(r, "Failed to open the device '%s': %m", s);
493
494 r = device_enumerator_add_match_parent_incremental(e, dev);
495 if (r < 0)
496 return log_error_errno(r, "Failed to add parent match '%s': %m", s);
497
498 return 0;
499 }
500
501 static int setup_matches(sd_device_enumerator *e) {
502 int r;
503
504 assert(e);
505
506 STRV_FOREACH(n, arg_name_match) {
507 r = add_match_parent(e, *n, "/dev");
508 if (r < 0)
509 return r;
510 }
511
512 STRV_FOREACH(p, arg_parent_match) {
513 r = add_match_parent(e, *p, "/sys");
514 if (r < 0)
515 return r;
516 }
517
518 STRV_FOREACH(s, arg_subsystem_match) {
519 r = sd_device_enumerator_add_match_subsystem(e, *s, /* match= */ true);
520 if (r < 0)
521 return log_error_errno(r, "Failed to add subsystem match '%s': %m", *s);
522 }
523
524 STRV_FOREACH(s, arg_subsystem_nomatch) {
525 r = sd_device_enumerator_add_match_subsystem(e, *s, /* match= */ false);
526 if (r < 0)
527 return log_error_errno(r, "Failed to add negative subsystem match '%s': %m", *s);
528 }
529
530 STRV_FOREACH(a, arg_attr_match) {
531 _cleanup_free_ char *k = NULL, *v = NULL;
532
533 r = parse_key_value_argument(*a, /* require_value= */ true, &k, &v);
534 if (r < 0)
535 return r;
536
537 r = sd_device_enumerator_add_match_sysattr(e, k, v, /* match= */ true);
538 if (r < 0)
539 return log_error_errno(r, "Failed to add sysattr match '%s=%s': %m", k, v);
540 }
541
542 STRV_FOREACH(a, arg_attr_nomatch) {
543 _cleanup_free_ char *k = NULL, *v = NULL;
544
545 r = parse_key_value_argument(*a, /* require_value= */ true, &k, &v);
546 if (r < 0)
547 return r;
548
549 r = sd_device_enumerator_add_match_sysattr(e, k, v, /* match= */ false);
550 if (r < 0)
551 return log_error_errno(r, "Failed to add negative sysattr match '%s=%s': %m", k, v);
552 }
553
554 STRV_FOREACH(p, arg_property_match) {
555 _cleanup_free_ char *k = NULL, *v = NULL;
556
557 r = parse_key_value_argument(*p, /* require_value= */ true, &k, &v);
558 if (r < 0)
559 return r;
560
561 r = sd_device_enumerator_add_match_property_required(e, k, v);
562 if (r < 0)
563 return log_error_errno(r, "Failed to add property match '%s=%s': %m", k, v);
564 }
565
566 STRV_FOREACH(t, arg_tag_match) {
567 r = sd_device_enumerator_add_match_tag(e, *t);
568 if (r < 0)
569 return log_error_errno(r, "Failed to add tag match '%s': %m", *t);
570 }
571
572 STRV_FOREACH(s, arg_sysname_match) {
573 r = sd_device_enumerator_add_match_sysname(e, *s);
574 if (r < 0)
575 return log_error_errno(r, "Failed to add sysname match '%s': %m", *s);
576 }
577
578 if (arg_initialized_match != -1) {
579 r = device_enumerator_add_match_is_initialized(e, arg_initialized_match);
580 if (r < 0)
581 return log_error_errno(r, "Failed to set initialized filter: %m");
582 }
583
584 return 0;
585 }
586
587 static int export_devices(void) {
588 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
589 sd_device *d;
590 int r;
591
592 r = sd_device_enumerator_new(&e);
593 if (r < 0)
594 return log_error_errno(r, "Failed to create device enumerator: %m");
595
596 r = sd_device_enumerator_allow_uninitialized(e);
597 if (r < 0)
598 return log_error_errno(r, "Failed to allow uninitialized devices: %m");
599
600 r = setup_matches(e);
601 if (r < 0)
602 return r;
603
604 r = device_enumerator_scan_devices(e);
605 if (r < 0)
606 return log_error_errno(r, "Failed to scan devices: %m");
607
608 FOREACH_DEVICE_AND_SUBSYSTEM(e, d)
609 if (sd_json_format_enabled(arg_json_format_flags)) {
610 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
611
612 r = record_to_json(d, &v);
613 if (r < 0)
614 return r;
615
616 (void) sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
617 } else
618 (void) print_record(d, NULL);
619
620 return 0;
621 }
622
623 static void cleanup_dir(DIR *dir, mode_t mask, int depth) {
624 assert(dir);
625
626 if (depth <= 0)
627 return;
628
629 FOREACH_DIRENT_ALL(dent, dir, break) {
630 struct stat stats;
631
632 if (dot_or_dot_dot(dent->d_name))
633 continue;
634 if (fstatat(dirfd(dir), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) < 0)
635 continue;
636 if ((stats.st_mode & mask) != 0)
637 continue;
638 if (S_ISDIR(stats.st_mode)) {
639 _cleanup_closedir_ DIR *subdir = NULL;
640
641 subdir = xopendirat(dirfd(dir), dent->d_name, O_NOFOLLOW);
642 if (!subdir)
643 log_debug_errno(errno, "Failed to open subdirectory '%s', ignoring: %m", dent->d_name);
644 else
645 cleanup_dir(subdir, mask, depth-1);
646
647 (void) unlinkat(dirfd(dir), dent->d_name, AT_REMOVEDIR);
648 } else
649 (void) unlinkat(dirfd(dir), dent->d_name, 0);
650 }
651 }
652
653 /*
654 * Assume that dir is a directory with file names matching udev data base
655 * entries for devices in /run/udev/data (such as "b8:16"), and removes
656 * all files except those that haven't been deleted in /run/udev/data
657 * (i.e. they were skipped during db cleanup because of the db_persist flag).
658 */
659 static void cleanup_dir_after_db_cleanup(DIR *dir, DIR *datadir) {
660 assert(dir);
661 assert(datadir);
662
663 FOREACH_DIRENT_ALL(dent, dir, break) {
664 if (dot_or_dot_dot(dent->d_name))
665 continue;
666
667 if (faccessat(dirfd(datadir), dent->d_name, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
668 /* The corresponding udev database file still exists.
669 * Assuming the persistent flag is set for the database. */
670 continue;
671
672 (void) unlinkat(dirfd(dir), dent->d_name, 0);
673 }
674 }
675
676 static void cleanup_dirs_after_db_cleanup(DIR *dir, DIR *datadir) {
677 assert(dir);
678 assert(datadir);
679
680 FOREACH_DIRENT_ALL(dent, dir, break) {
681 struct stat stats;
682
683 if (dot_or_dot_dot(dent->d_name))
684 continue;
685 if (fstatat(dirfd(dir), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) < 0)
686 continue;
687 if (S_ISDIR(stats.st_mode)) {
688 _cleanup_closedir_ DIR *subdir = NULL;
689
690 subdir = xopendirat(dirfd(dir), dent->d_name, O_NOFOLLOW);
691 if (!subdir)
692 log_debug_errno(errno, "Failed to open subdirectory '%s', ignoring: %m", dent->d_name);
693 else
694 cleanup_dir_after_db_cleanup(subdir, datadir);
695
696 (void) unlinkat(dirfd(dir), dent->d_name, AT_REMOVEDIR);
697 } else
698 (void) unlinkat(dirfd(dir), dent->d_name, 0);
699 }
700 }
701
702 static int cleanup_db(void) {
703 _cleanup_closedir_ DIR *dir1 = NULL, *dir2 = NULL, *dir3 = NULL, *dir4 = NULL;
704
705 dir1 = opendir("/run/udev/data");
706 if (dir1)
707 cleanup_dir(dir1, S_ISVTX, 1);
708
709 dir2 = opendir("/run/udev/links");
710 if (dir2)
711 cleanup_dirs_after_db_cleanup(dir2, dir1);
712
713 dir3 = opendir("/run/udev/tags");
714 if (dir3)
715 cleanup_dirs_after_db_cleanup(dir3, dir1);
716
717 dir4 = opendir("/run/udev/static_node-tags");
718 if (dir4)
719 cleanup_dir(dir4, 0, 2);
720
721 /* Do not remove /run/udev/watch. It will be handled by udevd well on restart.
722 * And should not be removed by external program when udevd is running. */
723
724 return 0;
725 }
726
727 static int query_device(QueryType query, sd_device* device) {
728 int r;
729
730 assert(device);
731
732 switch (query) {
733 case QUERY_NAME: {
734 const char *node;
735
736 r = sd_device_get_devname(device, &node);
737 if (r < 0)
738 return log_error_errno(r, "No device node found: %m");
739
740 if (!arg_root)
741 assert_se(node = path_startswith(node, "/dev/"));
742 printf("%s\n", node);
743 return 0;
744 }
745
746 case QUERY_SYMLINK: {
747 const char *prefix = "";
748
749 FOREACH_DEVICE_DEVLINK(device, devlink) {
750 if (!arg_root)
751 assert_se(devlink = path_startswith(devlink, "/dev/"));
752 printf("%s%s", prefix, devlink);
753 prefix = " ";
754 }
755 puts("");
756 return 0;
757 }
758
759 case QUERY_PATH: {
760 const char *devpath;
761
762 r = sd_device_get_devpath(device, &devpath);
763 if (r < 0)
764 return log_error_errno(r, "Failed to get device path: %m");
765
766 printf("%s\n", devpath);
767 return 0;
768 }
769
770 case QUERY_PROPERTY:
771 FOREACH_DEVICE_PROPERTY(device, key, value) {
772 if (arg_properties && !strv_contains(arg_properties, key))
773 continue;
774
775 if (arg_export)
776 printf("%s%s='%s'\n", strempty(arg_export_prefix), key, value);
777 else if (arg_value)
778 printf("%s\n", value);
779 else
780 printf("%s=%s\n", key, value);
781 }
782
783 return 0;
784
785 case QUERY_ALL:
786 if (sd_json_format_enabled(arg_json_format_flags)) {
787 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
788
789 r = record_to_json(device, &v);
790 if (r < 0)
791 return r;
792
793 (void) sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
794 } else
795 return print_record(device, NULL);
796
797 return 0;
798
799 default:
800 assert_not_reached();
801 }
802 }
803
804 static int help(void) {
805 _cleanup_(table_unrefp) Table *options = NULL;
806 int r;
807
808 r = option_parser_get_help_table_ns("udevadm-info", &options);
809 if (r < 0)
810 return r;
811
812 help_cmdline("info [OPTIONS] [DEVPATH|FILE]");
813 help_abstract("Query sysfs or the udev database.");
814 help_section("Options");
815 r = table_print_or_warn(options);
816 if (r < 0)
817 return r;
818
819 help_man_page_reference("udevadm", "8");
820 return 0;
821 }
822
823 static int draw_tree(
824 sd_device *parent,
825 sd_device *const array[], size_t n,
826 const char *prefix,
827 unsigned level);
828
829 static int output_tree_device(
830 sd_device *device,
831 const char *str,
832 const char *prefix,
833 bool more,
834 sd_device *const array[], size_t n,
835 unsigned level) {
836
837 _cleanup_free_ char *subprefix = NULL, *subsubprefix = NULL;
838
839 assert(device);
840 assert(str);
841
842 prefix = strempty(prefix);
843
844 printf("%s%s%s\n", prefix, glyph(more ? GLYPH_TREE_BRANCH : GLYPH_TREE_RIGHT), str);
845
846 subprefix = strjoin(prefix, glyph(more ? GLYPH_TREE_VERTICAL : GLYPH_TREE_SPACE));
847 if (!subprefix)
848 return log_oom();
849
850 subsubprefix = strjoin(subprefix, glyph(GLYPH_VERTICAL_DOTTED), " ");
851 if (!subsubprefix)
852 return log_oom();
853
854 (void) print_record(device, subsubprefix);
855
856 return draw_tree(device, array, n, subprefix, level + 1);
857 }
858
859 static int draw_tree(
860 sd_device *parent,
861 sd_device *const array[], size_t n,
862 const char *prefix,
863 unsigned level) {
864
865 const char *parent_path;
866 size_t i = 0;
867 int r;
868
869 if (n == 0)
870 return 0;
871
872 assert(array);
873
874 if (parent) {
875 r = sd_device_get_devpath(parent, &parent_path);
876 if (r < 0)
877 return log_error_errno(r, "Failed to get sysfs path of parent device: %m");
878 } else
879 parent_path = NULL;
880
881 if (level > TREE_DEPTH_MAX) {
882 log_warning("Eliding tree below '%s', too deep.", strna(parent_path));
883 return 0;
884 }
885
886 while (i < n) {
887 sd_device *device = array[i];
888 const char *device_path, *str;
889 bool more = false;
890 size_t j;
891
892 r = sd_device_get_devpath(device, &device_path);
893 if (r < 0)
894 return log_error_errno(r, "Failed to get sysfs path of enumerated device: %m");
895
896 /* Scan through the subsequent devices looking children of the device we are looking at. */
897 for (j = i + 1; j < n; j++) {
898 sd_device *next = array[j];
899 const char *next_path;
900
901 r = sd_device_get_devpath(next, &next_path);
902 if (r < 0)
903 return log_error_errno(r, "Failed to get sysfs of child device: %m");
904
905 if (!path_startswith(next_path, device_path)) {
906 more = !parent_path || path_startswith(next_path, parent_path);
907 break;
908 }
909 }
910
911 /* Determine the string to display for this node. If we are at the top of the tree, the full
912 * device path so far, otherwise just the part suffixing the parent's device path. */
913 str = parent ? ASSERT_PTR(path_startswith(device_path, parent_path)) : device_path;
914
915 r = output_tree_device(device, str, prefix, more, array + i + 1, j - i - 1, level);
916 if (r < 0)
917 return r;
918
919 i = j;
920 }
921
922 return 0;
923 }
924
925 static int print_tree(sd_device* below) {
926 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
927 const char *below_path;
928 sd_device **array;
929 size_t n = 0;
930 int r;
931
932 if (below) {
933 r = sd_device_get_devpath(below, &below_path);
934 if (r < 0)
935 return log_error_errno(r, "Failed to get sysfs path of device: %m");
936
937 } else
938 below_path = NULL;
939
940 r = sd_device_enumerator_new(&e);
941 if (r < 0)
942 return log_error_errno(r, "Failed to allocate device enumerator: %m");
943
944 if (below) {
945 r = sd_device_enumerator_add_match_parent(e, below);
946 if (r < 0)
947 return log_error_errno(r, "Failed to install parent enumerator match: %m");
948 }
949
950 r = sd_device_enumerator_allow_uninitialized(e);
951 if (r < 0)
952 return log_error_errno(r, "Failed to enable enumeration of uninitialized devices: %m");
953
954 r = device_enumerator_scan_devices_and_subsystems(e);
955 if (r < 0)
956 return log_error_errno(r, "Failed to scan for devices and subsystems: %m");
957
958 if (below) {
959 /* This must be called after device_enumerator_scan_devices_and_subsystems(). */
960 r = device_enumerator_add_parent_devices(e, below);
961 if (r < 0)
962 return log_error_errno(r, "Failed to add parent devices: %m");
963 }
964
965 assert_se(array = device_enumerator_get_devices(e, &n));
966
967 if (n == 0) {
968 log_info("No items.");
969 return 0;
970 }
971
972 r = draw_tree(NULL, array, n, NULL, 0);
973 if (r < 0)
974 return r;
975
976 printf("\n%zu items shown.\n", n);
977 return 0;
978 }
979
980 static int parse_argv(int argc, char *argv[]) {
981 int r;
982
983 assert(argc >= 0);
984 assert(argv);
985
986 OptionParser opts = { argc, argv, .namespace = "udevadm-info" };
987
988 FOREACH_OPTION_OR_RETURN(c, &opts)
989 switch (c) {
990
991 OPTION_NAMESPACE("udevadm-info"): {}
992
993 OPTION_COMMON_HELP:
994 return help();
995
996 OPTION('V', "version", NULL, "Show package version"):
997 return print_version();
998
999 OPTION('q', "query", "TYPE", "Query device information:"): {}
1000 OPTION_HELP_VERBATIM(" name", "- name of device node"): {}
1001 OPTION_HELP_VERBATIM(" symlink", "- pointing to node"): {}
1002 OPTION_HELP_VERBATIM(" path", "- sysfs device path"): {}
1003 OPTION_HELP_VERBATIM(" property", "- the device properties"): {}
1004 OPTION_HELP_VERBATIM(" all", "- all values"):
1005 arg_query = query_type_from_string(opts.arg);
1006 if (arg_query < 0) {
1007 if (streq(opts.arg, "env")) /* deprecated */
1008 arg_query = QUERY_PROPERTY;
1009 else
1010 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown query type '%s'", opts.arg);
1011 }
1012 break;
1013
1014 OPTION_LONG("property", "NAME", "Show only properties by this name"):
1015 /* Make sure that if the empty property list was specified, we won't show any
1016 properties. */
1017 if (isempty(opts.arg) && !arg_properties) {
1018 arg_properties = new0(char*, 1);
1019 if (!arg_properties)
1020 return log_oom();
1021 } else {
1022 r = strv_split_and_extend(&arg_properties, opts.arg, ",", true);
1023 if (r < 0)
1024 return log_oom();
1025 }
1026 break;
1027
1028 OPTION_LONG("value", NULL,
1029 "When showing properties, print only their values"):
1030 arg_value = true;
1031 break;
1032
1033 OPTION('p', "path", "SYSPATH", "sysfs device path used for query or attribute walk"): {} /* fall through */
1034 OPTION('n', "name", "NAME", "Node or symlink name used for query or attribute walk"): {
1035 const char *prefix = opts.opt->short_code == 'n' ? "/dev/" : "/sys/";
1036 char *path;
1037
1038 path = path_join(path_startswith(opts.arg, prefix) ? NULL : prefix, opts.arg);
1039 if (!path)
1040 return log_oom();
1041
1042 r = strv_consume(&arg_devices, path);
1043 if (r < 0)
1044 return log_oom();
1045 break;
1046 }
1047
1048 OPTION('r', "root", NULL, "Prepend dev directory to path names"):
1049 arg_root = true;
1050 break;
1051
1052 OPTION('a', "attribute-walk", NULL,
1053 "Print all key matches walking along the chain of parent devices"):
1054 arg_action_type = ACTION_ATTRIBUTE_WALK;
1055 break;
1056
1057 OPTION('t', "tree", NULL, "Show tree of devices"):
1058 arg_action_type = ACTION_TREE;
1059 break;
1060
1061 OPTION('d', "device-id-of-file", "FILE",
1062 "Print major:minor of device containing this file"):
1063 arg_action_type = ACTION_DEVICE_ID_FILE;
1064 r = free_and_strdup(&arg_name, opts.arg);
1065 if (r < 0)
1066 return log_oom();
1067 break;
1068
1069 OPTION('x', "export", NULL, "Export key/value pairs"):
1070 arg_export = true;
1071 break;
1072
1073 OPTION('P', "export-prefix", "NAME", "Export the key name with a prefix"):
1074 arg_export = true;
1075 arg_export_prefix = opts.arg;
1076 break;
1077
1078 OPTION('e', "export-db", NULL, "Export the content of the udev database"):
1079 arg_action_type = ACTION_EXPORT;
1080 break;
1081
1082 OPTION('c', "cleanup-db", NULL, "Clean up the udev database"):
1083 arg_action_type = ACTION_CLEANUP_DB;
1084 break;
1085
1086 OPTION_FULL(OPTION_OPTIONAL_ARG, 'w', "wait-for-initialization", "SECS",
1087 "Wait for device to be initialized"):
1088 if (opts.arg) {
1089 r = parse_sec(opts.arg, &arg_wait_for_initialization_timeout);
1090 if (r < 0)
1091 return log_error_errno(r, "Failed to parse timeout value: %m");
1092 } else
1093 arg_wait_for_initialization_timeout = USEC_INFINITY;
1094 break;
1095
1096 OPTION_COMMON_NO_PAGER:
1097 arg_pager_flags |= PAGER_DISABLE;
1098 break;
1099
1100 OPTION_COMMON_JSON:
1101 r = parse_json_argument(opts.arg, &arg_json_format_flags);
1102 if (r <= 0)
1103 return r;
1104 break;
1105
1106 OPTION_LONG("subsystem-match", "SUBSYSTEM",
1107 "Query devices matching a subsystem"):
1108 r = strv_extend(&arg_subsystem_match, opts.arg);
1109 if (r < 0)
1110 return log_oom();
1111 break;
1112
1113 OPTION_LONG("subsystem-nomatch", "SUBSYSTEM",
1114 "Query devices not matching a subsystem"):
1115 r = strv_extend(&arg_subsystem_nomatch, opts.arg);
1116 if (r < 0)
1117 return log_oom();
1118 break;
1119
1120 OPTION_LONG("attr-match", "FILE[=VALUE]",
1121 "Query devices that match an attribute"):
1122 if (!strchr(opts.arg, '='))
1123 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1124 "Expected <ATTR>=<value> instead of '%s'", opts.arg);
1125
1126 r = strv_extend(&arg_attr_match, opts.arg);
1127 if (r < 0)
1128 return log_oom();
1129 break;
1130
1131 OPTION_LONG("attr-nomatch", "FILE[=VALUE]",
1132 "Query devices that do not match an attribute"):
1133 if (!strchr(opts.arg, '='))
1134 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1135 "Expected <ATTR>=<value> instead of '%s'", opts.arg);
1136
1137 r = strv_extend(&arg_attr_nomatch, opts.arg);
1138 if (r < 0)
1139 return log_oom();
1140 break;
1141
1142 OPTION_LONG("property-match", "KEY=VALUE",
1143 "Query devices with matching properties"):
1144 if (!strchr(opts.arg, '='))
1145 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1146 "Expected <PROPERTY>=<value> instead of '%s'", opts.arg);
1147
1148 r = strv_extend(&arg_property_match, opts.arg);
1149 if (r < 0)
1150 return log_oom();
1151 break;
1152
1153 OPTION_LONG("tag-match", "TAG", "Query devices with a matching tag"):
1154 r = strv_extend(&arg_tag_match, opts.arg);
1155 if (r < 0)
1156 return log_oom();
1157 break;
1158
1159 OPTION_LONG("sysname-match", "NAME", "Query devices with this /sys path"):
1160 r = strv_extend(&arg_sysname_match, opts.arg);
1161 if (r < 0)
1162 return log_oom();
1163 break;
1164
1165 OPTION_LONG("name-match", "NAME", "Query devices with this /dev name"):
1166 r = strv_extend(&arg_name_match, opts.arg);
1167 if (r < 0)
1168 return log_oom();
1169 break;
1170
1171 OPTION_LONG("parent-match", "NAME", "Query devices with this parent device"):
1172 r = strv_extend(&arg_parent_match, opts.arg);
1173 if (r < 0)
1174 return log_oom();
1175 break;
1176
1177 OPTION_LONG("initialized-match", NULL,
1178 "Query devices that are already initialized"):
1179 arg_initialized_match = MATCH_INITIALIZED_YES;
1180 break;
1181
1182 OPTION_LONG("initialized-nomatch", NULL,
1183 "Query devices that are not initialized yet"):
1184 arg_initialized_match = MATCH_INITIALIZED_NO;
1185 break;
1186 }
1187
1188 r = strv_extend_strv(&arg_devices, option_parser_get_args(&opts), /* filter_duplicates= */ false);
1189 if (r < 0)
1190 return log_error_errno(r, "Failed to build argument list: %m");
1191
1192 if (IN_SET(arg_action_type, ACTION_DEVICE_ID_FILE, ACTION_CLEANUP_DB) && !strv_isempty(arg_devices))
1193 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1194 "Devices are not allowed with -d/--device-id-of-file and -c/--cleanup-db.");
1195
1196 if (!IN_SET(arg_action_type, ACTION_DEVICE_ID_FILE, ACTION_CLEANUP_DB, ACTION_EXPORT, ACTION_TREE) &&
1197 strv_isempty(arg_devices))
1198 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1199 "A device name or path is required");
1200
1201 if (IN_SET(arg_action_type, ACTION_ATTRIBUTE_WALK, ACTION_TREE) && strv_length(arg_devices) > 1)
1202 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1203 "Only one device may be specified with -a/--attribute-walk and -t/--tree");
1204
1205 if (arg_export && arg_value)
1206 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1207 "-x/--export or -P/--export-prefix cannot be used with --value");
1208
1209 return 1;
1210 }
1211
1212 int verb_info_main(int argc, char *argv[], uintptr_t _data, void *userdata) {
1213 int r;
1214
1215 r = parse_argv(argc, argv);
1216 if (r <= 0)
1217 return r;
1218
1219 if (arg_action_type == ACTION_CLEANUP_DB)
1220 return cleanup_db();
1221
1222 if (arg_action_type == ACTION_DEVICE_ID_FILE)
1223 return stat_device();
1224
1225 pager_open(arg_pager_flags);
1226
1227 if (arg_action_type == ACTION_EXPORT)
1228 return export_devices();
1229
1230 if (strv_isempty(arg_devices)) {
1231 assert(arg_action_type == ACTION_TREE);
1232 return print_tree(NULL);
1233 }
1234
1235 int ret = 0;
1236 STRV_FOREACH(p, arg_devices) {
1237 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
1238
1239 r = find_device(*p, /* prefix= */ NULL, &device);
1240 if (r < 0) {
1241 if (r == -EINVAL)
1242 log_error_errno(r, "Bad argument \"%s\", expected an absolute path in /dev/ or /sys/, device ID, or a unit name: %m", *p);
1243 else
1244 log_error_errno(r, "Unknown device \"%s\": %m", *p);
1245
1246 RET_GATHER(ret, r);
1247 continue;
1248 }
1249
1250 if (arg_wait_for_initialization_timeout > 0) {
1251 sd_device *d;
1252
1253 r = device_wait_for_initialization(
1254 device,
1255 NULL,
1256 arg_wait_for_initialization_timeout,
1257 &d);
1258 if (r < 0)
1259 return r;
1260
1261 sd_device_unref(device);
1262 device = d;
1263 }
1264
1265 if (arg_action_type == ACTION_QUERY)
1266 r = query_device(arg_query, device);
1267 else if (arg_action_type == ACTION_ATTRIBUTE_WALK) {
1268 if (sd_json_format_enabled(arg_json_format_flags))
1269 r = print_device_chain_in_json(device);
1270 else
1271 r = print_device_chain(device);
1272 } else if (arg_action_type == ACTION_TREE)
1273 r = print_tree(device);
1274 else
1275 assert_not_reached();
1276 if (r < 0)
1277 return r;
1278 }
1279
1280 return ret;
1281 }