lsusb.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. auto bus_id = proc_usb_device->filename().split('/').last();
  47. if (!proc_usb_device->open(Core::OpenMode::ReadOnly)) {
  48. warnln("Failed to open {}: {}", proc_usb_device->name(), proc_usb_device->error_string());
  49. continue;
  50. }
  51. auto contents = proc_usb_device->read_all();
  52. auto json = JsonValue::from_string(contents);
  53. VERIFY(json.has_value());
  54. json.value().as_array().for_each([bus_id, usb_db](auto& value) {
  55. auto& device_descriptor = value.as_object();
  56. auto vendor_id = device_descriptor.get("vendor_id").to_u32();
  57. auto product_id = device_descriptor.get("product_id").to_u32();
  58. StringView vendor_string = usb_db->get_vendor(vendor_id);
  59. StringView device_string = usb_db->get_device(vendor_id, product_id);
  60. if (device_string.is_empty())
  61. device_string = "Unknown Device";
  62. outln("Device {}: ID {:04x}:{:04x} {} {}", bus_id, vendor_id, product_id, vendor_string, device_string);
  63. });
  64. }
  65. return 0;
  66. }