usb_service_linux.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "services/device/usb/usb_service_linux.h"
  5. #include <stdint.h>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/bind.h"
  9. #include "base/containers/contains.h"
  10. #include "base/files/file.h"
  11. #include "base/files/file_path.h"
  12. #include "base/files/file_util.h"
  13. #include "base/location.h"
  14. #include "base/logging.h"
  15. #include "base/memory/ptr_util.h"
  16. #include "base/memory/weak_ptr.h"
  17. #include "base/strings/string_number_conversions.h"
  18. #include "base/strings/utf_string_conversions.h"
  19. #include "base/threading/scoped_blocking_call.h"
  20. #include "base/threading/sequenced_task_runner_handle.h"
  21. #include "build/build_config.h"
  22. #include "build/chromeos_buildflags.h"
  23. #include "components/device_event_log/device_event_log.h"
  24. #include "device/udev_linux/udev_watcher.h"
  25. #include "services/device/usb/usb_device_handle.h"
  26. #include "services/device/usb/usb_device_linux.h"
  27. #include "services/device/usb/webusb_descriptors.h"
  28. namespace device {
  29. namespace {
  30. // Standard USB requests and descriptor types:
  31. const uint16_t kUsbVersion2_1 = 0x0210;
  32. const uint8_t kDeviceClassHub = 0x09;
  33. constexpr int kUsbClassMassStorage = 0x08;
  34. bool ShouldReadDescriptors(const UsbDeviceLinux& device) {
  35. if (device.usb_version() < kUsbVersion2_1)
  36. return false;
  37. // Avoid detaching the usb-storage driver.
  38. // TODO(crbug.com/1176107): We should read descriptors for composite mass
  39. // storage devices.
  40. auto* configuration = device.GetActiveConfiguration();
  41. if (configuration) {
  42. for (const auto& interface : configuration->interfaces) {
  43. for (const auto& alternate : interface->alternates) {
  44. if (alternate->class_code == kUsbClassMassStorage)
  45. return false;
  46. }
  47. }
  48. }
  49. return true;
  50. }
  51. void OnReadDescriptors(base::OnceCallback<void(bool)> callback,
  52. scoped_refptr<UsbDeviceHandle> device_handle,
  53. const GURL& landing_page) {
  54. UsbDeviceLinux* device =
  55. static_cast<UsbDeviceLinux*>(device_handle->GetDevice().get());
  56. if (landing_page.is_valid())
  57. device->set_webusb_landing_page(landing_page);
  58. device_handle->Close();
  59. std::move(callback).Run(true /* success */);
  60. }
  61. void OnDeviceOpenedToReadDescriptors(
  62. base::OnceCallback<void(bool)> callback,
  63. scoped_refptr<UsbDeviceHandle> device_handle) {
  64. if (device_handle) {
  65. ReadWebUsbDescriptors(
  66. device_handle,
  67. base::BindOnce(&OnReadDescriptors, std::move(callback), device_handle));
  68. } else {
  69. std::move(callback).Run(false /* failure */);
  70. }
  71. }
  72. } // namespace
  73. class UsbServiceLinux::BlockingTaskRunnerHelper : public UdevWatcher::Observer {
  74. public:
  75. explicit BlockingTaskRunnerHelper(
  76. base::WeakPtr<UsbServiceLinux> service,
  77. scoped_refptr<base::SequencedTaskRunner> task_runner);
  78. BlockingTaskRunnerHelper(const BlockingTaskRunnerHelper&) = delete;
  79. BlockingTaskRunnerHelper& operator=(const BlockingTaskRunnerHelper&) = delete;
  80. ~BlockingTaskRunnerHelper() override;
  81. private:
  82. // UdevWatcher::Observer
  83. void OnDeviceAdded(ScopedUdevDevicePtr device) override;
  84. void OnDeviceRemoved(ScopedUdevDevicePtr device) override;
  85. void OnDeviceChanged(ScopedUdevDevicePtr device) override;
  86. std::unique_ptr<UdevWatcher> watcher_;
  87. // |service_| can only be checked for validity on |task_runner_|'s sequence.
  88. base::WeakPtr<UsbServiceLinux> service_;
  89. scoped_refptr<base::SequencedTaskRunner> task_runner_;
  90. SEQUENCE_CHECKER(sequence_checker_);
  91. };
  92. UsbServiceLinux::BlockingTaskRunnerHelper::BlockingTaskRunnerHelper(
  93. base::WeakPtr<UsbServiceLinux> service,
  94. scoped_refptr<base::SequencedTaskRunner> task_runner)
  95. : service_(std::move(service)), task_runner_(std::move(task_runner)) {
  96. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  97. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  98. base::BlockingType::MAY_BLOCK);
  99. // Initializing udev for device enumeration and monitoring may fail. In that
  100. // case this service will continue to exist but no devices will be found.
  101. watcher_ = UdevWatcher::StartWatching(this);
  102. if (watcher_)
  103. watcher_->EnumerateExistingDevices();
  104. task_runner_->PostTask(
  105. FROM_HERE, base::BindOnce(&UsbServiceLinux::HelperStarted, service_));
  106. }
  107. UsbServiceLinux::BlockingTaskRunnerHelper::~BlockingTaskRunnerHelper() {
  108. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  109. }
  110. void UsbServiceLinux::BlockingTaskRunnerHelper::OnDeviceAdded(
  111. ScopedUdevDevicePtr device) {
  112. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  113. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  114. base::BlockingType::MAY_BLOCK);
  115. const char* subsystem = udev_device_get_subsystem(device.get());
  116. if (!subsystem || strcmp(subsystem, "usb") != 0)
  117. return;
  118. const char* value = udev_device_get_devnode(device.get());
  119. if (!value)
  120. return;
  121. std::string device_path = value;
  122. const char* sysfs_path = udev_device_get_syspath(device.get());
  123. if (!sysfs_path)
  124. return;
  125. base::FilePath descriptors_path =
  126. base::FilePath(sysfs_path).Append("descriptors");
  127. std::string descriptors_str;
  128. if (!base::ReadFileToString(descriptors_path, &descriptors_str))
  129. return;
  130. std::unique_ptr<UsbDeviceDescriptor> descriptor(new UsbDeviceDescriptor());
  131. if (!descriptor->Parse(base::make_span(
  132. reinterpret_cast<const uint8_t*>(descriptors_str.data()),
  133. descriptors_str.size()))) {
  134. return;
  135. }
  136. if (descriptor->device_info->class_code == kDeviceClassHub) {
  137. // Don't try to enumerate hubs. We never want to connect to a hub.
  138. return;
  139. }
  140. value = udev_device_get_sysattr_value(device.get(), "manufacturer");
  141. if (value)
  142. descriptor->device_info->manufacturer_name = base::UTF8ToUTF16(value);
  143. value = udev_device_get_sysattr_value(device.get(), "product");
  144. if (value)
  145. descriptor->device_info->product_name = base::UTF8ToUTF16(value);
  146. value = udev_device_get_sysattr_value(device.get(), "serial");
  147. if (value)
  148. descriptor->device_info->serial_number = base::UTF8ToUTF16(value);
  149. unsigned active_configuration = 0;
  150. value = udev_device_get_sysattr_value(device.get(), "bConfigurationValue");
  151. if (value)
  152. base::StringToUint(value, &active_configuration);
  153. descriptor->device_info->active_configuration = active_configuration;
  154. unsigned bus_number = 0;
  155. value = udev_device_get_sysattr_value(device.get(), "busnum");
  156. if (value)
  157. base::StringToUint(value, &bus_number);
  158. descriptor->device_info->bus_number = bus_number;
  159. unsigned port_number = 0;
  160. value = udev_device_get_sysattr_value(device.get(), "devnum");
  161. if (value)
  162. base::StringToUint(value, &port_number);
  163. descriptor->device_info->port_number = port_number;
  164. task_runner_->PostTask(
  165. FROM_HERE, base::BindOnce(&UsbServiceLinux::OnDeviceAdded, service_,
  166. device_path, std::move(descriptor)));
  167. }
  168. void UsbServiceLinux::BlockingTaskRunnerHelper::OnDeviceRemoved(
  169. ScopedUdevDevicePtr device) {
  170. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  171. base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
  172. base::BlockingType::MAY_BLOCK);
  173. const char* device_path = udev_device_get_devnode(device.get());
  174. if (device_path) {
  175. task_runner_->PostTask(
  176. FROM_HERE, base::BindOnce(&UsbServiceLinux::OnDeviceRemoved, service_,
  177. std::string(device_path)));
  178. }
  179. }
  180. void UsbServiceLinux::BlockingTaskRunnerHelper::OnDeviceChanged(
  181. ScopedUdevDevicePtr) {}
  182. UsbServiceLinux::UsbServiceLinux() {
  183. helper_ = base::SequenceBound<BlockingTaskRunnerHelper>(
  184. CreateBlockingTaskRunner(), weak_factory_.GetWeakPtr(),
  185. base::SequencedTaskRunnerHandle::Get());
  186. }
  187. UsbServiceLinux::~UsbServiceLinux() {
  188. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  189. NotifyWillDestroyUsbService();
  190. }
  191. void UsbServiceLinux::GetDevices(GetDevicesCallback callback) {
  192. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  193. if (enumeration_ready())
  194. UsbService::GetDevices(std::move(callback));
  195. else
  196. enumeration_callbacks_.push_back(std::move(callback));
  197. }
  198. void UsbServiceLinux::OnDeviceAdded(
  199. const std::string& device_path,
  200. std::unique_ptr<UsbDeviceDescriptor> descriptor) {
  201. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  202. if (base::Contains(devices_by_path_, device_path)) {
  203. USB_LOG(ERROR) << "Got duplicate add event for path: " << device_path;
  204. return;
  205. }
  206. // Devices that appear during initial enumeration are gathered into the first
  207. // result returned by GetDevices() and prevent device add/remove notifications
  208. // from being sent.
  209. if (!enumeration_ready())
  210. ++first_enumeration_countdown_;
  211. scoped_refptr<UsbDeviceLinux> device(
  212. new UsbDeviceLinux(device_path, std::move(descriptor)));
  213. devices_by_path_[device->device_path()] = device;
  214. if (ShouldReadDescriptors(*device)) {
  215. device->Open(
  216. base::BindOnce(&OnDeviceOpenedToReadDescriptors,
  217. base::BindOnce(&UsbServiceLinux::DeviceReady,
  218. weak_factory_.GetWeakPtr(), device)));
  219. } else {
  220. DeviceReady(device, /*success=*/true);
  221. }
  222. }
  223. void UsbServiceLinux::DeviceReady(scoped_refptr<UsbDeviceLinux> device,
  224. bool success) {
  225. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  226. bool enumeration_became_ready = false;
  227. if (!enumeration_ready()) {
  228. DCHECK_GT(first_enumeration_countdown_, 0u);
  229. first_enumeration_countdown_--;
  230. if (enumeration_ready())
  231. enumeration_became_ready = true;
  232. }
  233. // If |device| was disconnected while descriptors were being read then it
  234. // will have been removed from |devices_by_path_|.
  235. auto it = devices_by_path_.find(device->device_path());
  236. if (it == devices_by_path_.end()) {
  237. success = false;
  238. } else if (success) {
  239. DCHECK(!base::Contains(devices(), device->guid()));
  240. devices()[device->guid()] = device;
  241. USB_LOG(USER) << "USB device added: path=" << device->device_path()
  242. << " vendor=" << device->vendor_id() << " \""
  243. << device->manufacturer_string()
  244. << "\", product=" << device->product_id() << " \""
  245. << device->product_string() << "\", serial=\""
  246. << device->serial_number() << "\", guid=" << device->guid();
  247. } else {
  248. devices_by_path_.erase(it);
  249. }
  250. if (enumeration_became_ready) {
  251. std::vector<scoped_refptr<UsbDevice>> result;
  252. result.reserve(devices().size());
  253. for (const auto& map_entry : devices())
  254. result.push_back(map_entry.second);
  255. for (auto& callback : enumeration_callbacks_)
  256. std::move(callback).Run(result);
  257. enumeration_callbacks_.clear();
  258. } else if (success && enumeration_ready()) {
  259. NotifyDeviceAdded(device);
  260. }
  261. }
  262. void UsbServiceLinux::OnDeviceRemoved(const std::string& path) {
  263. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  264. auto by_path_it = devices_by_path_.find(path);
  265. if (by_path_it == devices_by_path_.end())
  266. return;
  267. scoped_refptr<UsbDeviceLinux> device = by_path_it->second;
  268. devices_by_path_.erase(by_path_it);
  269. device->OnDisconnect();
  270. auto by_guid_it = devices().find(device->guid());
  271. if (by_guid_it != devices().end() && enumeration_ready()) {
  272. USB_LOG(USER) << "USB device removed: path=" << device->device_path()
  273. << " guid=" << device->guid();
  274. devices().erase(by_guid_it);
  275. NotifyDeviceRemoved(device);
  276. }
  277. }
  278. void UsbServiceLinux::HelperStarted() {
  279. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  280. helper_started_ = true;
  281. if (enumeration_ready()) {
  282. std::vector<scoped_refptr<UsbDevice>> result;
  283. result.reserve(devices().size());
  284. for (const auto& map_entry : devices())
  285. result.push_back(map_entry.second);
  286. for (auto& callback : enumeration_callbacks_)
  287. std::move(callback).Run(result);
  288. enumeration_callbacks_.clear();
  289. }
  290. }
  291. } // namespace device