lsusb.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/String.h>
  11. #include <LibCore/ArgsParser.h>
  12. #include <LibCore/DirIterator.h>
  13. #include <LibCore/File.h>
  14. #include <LibUSBDB/Database.h>
  15. #include <stdio.h>
  16. #include <unistd.h>
  17. int main(int argc, char** argv)
  18. {
  19. if (pledge("stdio rpath", nullptr) < 0) {
  20. perror("pledge");
  21. return 1;
  22. }
  23. if (unveil("/sys/bus/usb", "r") < 0) {
  24. perror("unveil");
  25. return 1;
  26. }
  27. if (unveil("/res/usb.ids", "r") < 0) {
  28. perror("unveil");
  29. return 1;
  30. }
  31. if (unveil(nullptr, nullptr) < 0) {
  32. perror("unveil");
  33. return 1;
  34. }
  35. Core::ArgsParser args;
  36. args.set_general_help("List USB devices.");
  37. args.parse(argc, argv);
  38. Core::DirIterator usb_devices("/sys/bus/usb", Core::DirIterator::SkipDots);
  39. RefPtr<USBDB::Database> usb_db = USBDB::Database::open();
  40. if (!usb_db) {
  41. warnln("Failed to open usb.ids");
  42. }
  43. while (usb_devices.has_next()) {
  44. auto full_path = LexicalPath(usb_devices.next_full_path());
  45. auto proc_usb_device = Core::File::construct(full_path.string());
  46. if (!proc_usb_device->open(Core::OpenMode::ReadOnly)) {
  47. warnln("Failed to open {}: {}", proc_usb_device->name(), proc_usb_device->error_string());
  48. continue;
  49. }
  50. auto contents = proc_usb_device->read_all();
  51. auto json = JsonValue::from_string(contents).release_value_but_fixme_should_propagate_errors();
  52. json.as_array().for_each([usb_db](auto& value) {
  53. auto& device_descriptor = value.as_object();
  54. auto device_address = device_descriptor.get("device_address").to_u32();
  55. auto vendor_id = device_descriptor.get("vendor_id").to_u32();
  56. auto product_id = device_descriptor.get("product_id").to_u32();
  57. StringView vendor_string = usb_db->get_vendor(vendor_id);
  58. StringView device_string = usb_db->get_device(vendor_id, product_id);
  59. if (device_string.is_empty())
  60. device_string = "Unknown Device";
  61. outln("Device {}: ID {:04x}:{:04x} {} {}", device_address, vendor_id, product_id, vendor_string, device_string);
  62. });
  63. }
  64. return 0;
  65. }