hid_connection_linux.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Copyright (c) 2014 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/hid/hid_connection_linux.h"
  5. #include <errno.h>
  6. #include <linux/hidraw.h>
  7. #include <sys/ioctl.h>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include "base/bind.h"
  12. #include "base/files/file_descriptor_watcher_posix.h"
  13. #include "base/memory/ref_counted_memory.h"
  14. #include "base/posix/eintr_wrapper.h"
  15. #include "base/threading/scoped_blocking_call.h"
  16. #include "base/threading/sequenced_task_runner_handle.h"
  17. #include "components/device_event_log/device_event_log.h"
  18. #include "services/device/hid/hid_service.h"
  19. // These are already defined in newer versions of linux/hidraw.h.
  20. #ifndef HIDIOCSFEATURE
  21. #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x06, len)
  22. #endif
  23. #ifndef HIDIOCGFEATURE
  24. #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x07, len)
  25. #endif
  26. namespace device {
  27. class HidConnectionLinux::BlockingTaskRunnerHelper {
  28. public:
  29. BlockingTaskRunnerHelper(base::ScopedFD fd,
  30. scoped_refptr<HidDeviceInfo> device_info,
  31. base::WeakPtr<HidConnectionLinux> connection)
  32. : fd_(std::move(fd)),
  33. connection_(connection),
  34. origin_task_runner_(base::SequencedTaskRunnerHandle::Get()) {
  35. DETACH_FROM_SEQUENCE(sequence_checker_);
  36. // Report buffers must always have room for the report ID.
  37. report_buffer_size_ = device_info->max_input_report_size() + 1;
  38. has_report_id_ = device_info->has_report_id();
  39. }
  40. BlockingTaskRunnerHelper(const BlockingTaskRunnerHelper&) = delete;
  41. BlockingTaskRunnerHelper& operator=(const BlockingTaskRunnerHelper&) = delete;
  42. ~BlockingTaskRunnerHelper() {
  43. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  44. }
  45. // Starts the FileDescriptorWatcher that reads input events from the device.
  46. // Must be called on a thread that has a base::MessageLoopForIO.
  47. void Start() {
  48. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  49. file_watcher_ = base::FileDescriptorWatcher::WatchReadable(
  50. fd_.get(), base::BindRepeating(
  51. &BlockingTaskRunnerHelper::OnFileCanReadWithoutBlocking,
  52. base::Unretained(this)));
  53. }
  54. void Write(scoped_refptr<base::RefCountedBytes> buffer,
  55. WriteCallback callback) {
  56. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  57. base::ScopedBlockingCall scoped_blocking_call(
  58. FROM_HERE, base::BlockingType::MAY_BLOCK);
  59. ssize_t result =
  60. HANDLE_EINTR(write(fd_.get(), buffer->front(), buffer->size()));
  61. if (result < 0) {
  62. HID_PLOG(EVENT) << "Write failed";
  63. origin_task_runner_->PostTask(FROM_HERE,
  64. base::BindOnce(std::move(callback), false));
  65. } else {
  66. if (static_cast<size_t>(result) != buffer->size()) {
  67. HID_LOG(EVENT) << "Incomplete HID write: " << result
  68. << " != " << buffer->size();
  69. }
  70. origin_task_runner_->PostTask(FROM_HERE,
  71. base::BindOnce(std::move(callback), true));
  72. }
  73. }
  74. void GetFeatureReport(uint8_t report_id,
  75. scoped_refptr<base::RefCountedBytes> buffer,
  76. ReadCallback callback) {
  77. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  78. base::ScopedBlockingCall scoped_blocking_call(
  79. FROM_HERE, base::BlockingType::MAY_BLOCK);
  80. int result = HANDLE_EINTR(
  81. ioctl(fd_.get(), HIDIOCGFEATURE(buffer->size()), buffer->front()));
  82. if (result < 0) {
  83. HID_PLOG(EVENT) << "Failed to get feature report";
  84. origin_task_runner_->PostTask(
  85. FROM_HERE, base::BindOnce(std::move(callback), false, nullptr, 0));
  86. } else if (result == 0) {
  87. HID_LOG(EVENT) << "Get feature result too short.";
  88. origin_task_runner_->PostTask(
  89. FROM_HERE, base::BindOnce(std::move(callback), false, nullptr, 0));
  90. } else if (report_id == 0) {
  91. // Linux adds a 0 to the beginning of the data received from the device.
  92. auto copied_buffer =
  93. base::MakeRefCounted<base::RefCountedBytes>(result - 1);
  94. memcpy(copied_buffer->front(), buffer->front() + 1, result - 1);
  95. origin_task_runner_->PostTask(
  96. FROM_HERE,
  97. base::BindOnce(std::move(callback), true, copied_buffer, result - 1));
  98. } else {
  99. origin_task_runner_->PostTask(
  100. FROM_HERE, base::BindOnce(std::move(callback), true, buffer, result));
  101. }
  102. }
  103. void SendFeatureReport(scoped_refptr<base::RefCountedBytes> buffer,
  104. WriteCallback callback) {
  105. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  106. base::ScopedBlockingCall scoped_blocking_call(
  107. FROM_HERE, base::BlockingType::MAY_BLOCK);
  108. int result = HANDLE_EINTR(
  109. ioctl(fd_.get(), HIDIOCSFEATURE(buffer->size()), buffer->front()));
  110. if (result < 0) {
  111. HID_PLOG(EVENT) << "Failed to send feature report";
  112. origin_task_runner_->PostTask(FROM_HERE,
  113. base::BindOnce(std::move(callback), false));
  114. } else {
  115. origin_task_runner_->PostTask(FROM_HERE,
  116. base::BindOnce(std::move(callback), true));
  117. }
  118. }
  119. private:
  120. void OnFileCanReadWithoutBlocking() {
  121. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  122. auto buffer =
  123. base::MakeRefCounted<base::RefCountedBytes>(report_buffer_size_);
  124. uint8_t* data = buffer->front();
  125. size_t length = report_buffer_size_;
  126. if (!has_report_id_) {
  127. // Linux will not prefix the buffer with a report ID if report IDs are not
  128. // used by the device. Prefix the buffer with 0.
  129. *data++ = 0;
  130. length--;
  131. }
  132. ssize_t bytes_read = HANDLE_EINTR(read(fd_.get(), data, length));
  133. if (bytes_read < 0) {
  134. if (errno != EAGAIN) {
  135. HID_PLOG(EVENT) << "Read failed";
  136. // This assumes that the error is unrecoverable and disables reading
  137. // from the device until it has been re-opened.
  138. // TODO(reillyg): Investigate starting and stopping the file descriptor
  139. // watcher in response to pending read requests so that per-request
  140. // errors can be returned to the client.
  141. file_watcher_.reset();
  142. }
  143. return;
  144. }
  145. if (!has_report_id_) {
  146. // Behave as if the byte prefixed above as the the report ID was read.
  147. bytes_read++;
  148. }
  149. origin_task_runner_->PostTask(
  150. FROM_HERE, base::BindOnce(&HidConnectionLinux::ProcessInputReport,
  151. connection_, buffer, bytes_read));
  152. }
  153. SEQUENCE_CHECKER(sequence_checker_);
  154. base::ScopedFD fd_;
  155. size_t report_buffer_size_;
  156. bool has_report_id_;
  157. base::WeakPtr<HidConnectionLinux> connection_;
  158. const scoped_refptr<base::SequencedTaskRunner> origin_task_runner_;
  159. std::unique_ptr<base::FileDescriptorWatcher::Controller> file_watcher_;
  160. };
  161. HidConnectionLinux::HidConnectionLinux(
  162. scoped_refptr<HidDeviceInfo> device_info,
  163. base::ScopedFD fd,
  164. scoped_refptr<base::SequencedTaskRunner> blocking_task_runner,
  165. bool allow_protected_reports,
  166. bool allow_fido_reports)
  167. : HidConnection(device_info, allow_protected_reports, allow_fido_reports),
  168. helper_(nullptr, base::OnTaskRunnerDeleter(blocking_task_runner)),
  169. blocking_task_runner_(std::move(blocking_task_runner)) {
  170. helper_.reset(new BlockingTaskRunnerHelper(std::move(fd), device_info,
  171. weak_factory_.GetWeakPtr()));
  172. blocking_task_runner_->PostTask(
  173. FROM_HERE, base::BindOnce(&BlockingTaskRunnerHelper::Start,
  174. base::Unretained(helper_.get())));
  175. }
  176. HidConnectionLinux::~HidConnectionLinux() {}
  177. void HidConnectionLinux::PlatformClose() {
  178. // By closing the device on the blocking task runner 1) the requirement that
  179. // base::ScopedFD is destroyed on a thread where I/O is allowed is satisfied
  180. // and 2) any tasks posted to this task runner that refer to this file will
  181. // complete before it is closed.
  182. helper_.reset();
  183. }
  184. void HidConnectionLinux::PlatformWrite(
  185. scoped_refptr<base::RefCountedBytes> buffer,
  186. WriteCallback callback) {
  187. // Linux expects the first byte of the buffer to always be a report ID so the
  188. // buffer can be used directly.
  189. blocking_task_runner_->PostTask(
  190. FROM_HERE, base::BindOnce(&BlockingTaskRunnerHelper::Write,
  191. base::Unretained(helper_.get()), buffer,
  192. std::move(callback)));
  193. }
  194. void HidConnectionLinux::PlatformGetFeatureReport(uint8_t report_id,
  195. ReadCallback callback) {
  196. // The first byte of the destination buffer is the report ID being requested
  197. // and is overwritten by the feature report.
  198. DCHECK_GT(device_info()->max_feature_report_size(), 0u);
  199. auto buffer = base::MakeRefCounted<base::RefCountedBytes>(
  200. device_info()->max_feature_report_size() + 1);
  201. buffer->data()[0] = report_id;
  202. blocking_task_runner_->PostTask(
  203. FROM_HERE, base::BindOnce(&BlockingTaskRunnerHelper::GetFeatureReport,
  204. base::Unretained(helper_.get()), report_id,
  205. buffer, std::move(callback)));
  206. }
  207. void HidConnectionLinux::PlatformSendFeatureReport(
  208. scoped_refptr<base::RefCountedBytes> buffer,
  209. WriteCallback callback) {
  210. // Linux expects the first byte of the buffer to always be a report ID so the
  211. // buffer can be used directly.
  212. blocking_task_runner_->PostTask(
  213. FROM_HERE, base::BindOnce(&BlockingTaskRunnerHelper::SendFeatureReport,
  214. base::Unretained(helper_.get()), buffer,
  215. std::move(callback)));
  216. }
  217. } // namespace device