1 // Copyright 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.
5 #include "device/hid/hid_service_linux.h"
11 #include "base/bind.h"
12 #include "base/files/file.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/location.h"
16 #include "base/scoped_observer.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_split.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "components/device_event_log/device_event_log.h"
22 #include "device/hid/device_monitor_linux.h"
23 #include "device/hid/hid_connection_linux.h"
24 #include "device/hid/hid_device_info_linux.h"
25 #include "device/udev_linux/scoped_udev.h"
26 #include "net/base/net_util.h"
28 #if defined(OS_CHROMEOS)
29 #include "base/sys_info.h"
30 #include "chromeos/dbus/dbus_thread_manager.h"
31 #include "chromeos/dbus/permission_broker_client.h"
32 #endif // defined(OS_CHROMEOS)
38 const char kHidrawSubsystem
[] = "hidraw";
39 const char kHIDID
[] = "HID_ID";
40 const char kHIDName
[] = "HID_NAME";
41 const char kHIDUnique
[] = "HID_UNIQ";
42 const char kSysfsReportDescriptorKey
[] = "report_descriptor";
46 struct HidServiceLinux::ConnectParams
{
47 ConnectParams(scoped_refptr
<HidDeviceInfoLinux
> device_info
,
48 const ConnectCallback
& callback
,
49 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
,
50 scoped_refptr
<base::SingleThreadTaskRunner
> file_task_runner
)
51 : device_info(device_info
),
53 task_runner(task_runner
),
54 file_task_runner(file_task_runner
) {}
57 scoped_refptr
<HidDeviceInfoLinux
> device_info
;
58 ConnectCallback callback
;
59 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
;
60 scoped_refptr
<base::SingleThreadTaskRunner
> file_task_runner
;
61 base::File device_file
;
64 class HidServiceLinux::FileThreadHelper
65 : public DeviceMonitorLinux::Observer
,
66 public base::MessageLoop::DestructionObserver
{
68 FileThreadHelper(base::WeakPtr
<HidServiceLinux
> service
,
69 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
70 : observer_(this), service_(service
), task_runner_(task_runner
) {
71 DeviceMonitorLinux
* monitor
= DeviceMonitorLinux::GetInstance();
72 observer_
.Add(monitor
);
74 base::Bind(&FileThreadHelper::OnDeviceAdded
, base::Unretained(this)));
75 task_runner
->PostTask(
77 base::Bind(&HidServiceLinux::FirstEnumerationComplete
, service_
));
80 ~FileThreadHelper() override
{
81 DCHECK(thread_checker_
.CalledOnValidThread());
85 // DeviceMonitorLinux::Observer:
86 void OnDeviceAdded(udev_device
* device
) override
{
87 DCHECK(thread_checker_
.CalledOnValidThread());
88 const char* device_path
= udev_device_get_syspath(device
);
92 HidDeviceId device_id
= device_path
;
94 const char* subsystem
= udev_device_get_subsystem(device
);
95 if (!subsystem
|| strcmp(subsystem
, kHidrawSubsystem
) != 0) {
99 const char* str_property
= udev_device_get_devnode(device
);
103 std::string device_node
= str_property
;
105 udev_device
* parent
= udev_device_get_parent(device
);
110 const char* hid_id
= udev_device_get_property_value(parent
, kHIDID
);
115 std::vector
<std::string
> parts
;
116 base::SplitString(hid_id
, ':', &parts
);
117 if (parts
.size() != 3) {
121 uint32_t int_property
= 0;
122 if (!HexStringToUInt(base::StringPiece(parts
[1]), &int_property
) ||
123 int_property
> std::numeric_limits
<uint16_t>::max()) {
126 uint16_t vendor_id
= int_property
;
128 if (!HexStringToUInt(base::StringPiece(parts
[2]), &int_property
) ||
129 int_property
> std::numeric_limits
<uint16_t>::max()) {
132 uint16_t product_id
= int_property
;
134 std::string serial_number
;
135 str_property
= udev_device_get_property_value(parent
, kHIDUnique
);
136 if (str_property
!= NULL
) {
137 serial_number
= str_property
;
140 std::string product_name
;
141 str_property
= udev_device_get_property_value(parent
, kHIDName
);
142 if (str_property
!= NULL
) {
143 product_name
= str_property
;
146 const char* parent_sysfs_path
= udev_device_get_syspath(parent
);
147 if (!parent_sysfs_path
) {
150 base::FilePath report_descriptor_path
=
151 base::FilePath(parent_sysfs_path
).Append(kSysfsReportDescriptorKey
);
152 std::string report_descriptor_str
;
153 if (!base::ReadFileToString(report_descriptor_path
,
154 &report_descriptor_str
)) {
158 scoped_refptr
<HidDeviceInfo
> device_info(new HidDeviceInfoLinux(
159 device_id
, device_node
, vendor_id
, product_id
, product_name
,
161 kHIDBusTypeUSB
, // TODO(reillyg): Detect Bluetooth. crbug.com/443335
162 std::vector
<uint8
>(report_descriptor_str
.begin(),
163 report_descriptor_str
.end())));
165 task_runner_
->PostTask(FROM_HERE
, base::Bind(&HidServiceLinux::AddDevice
,
166 service_
, device_info
));
169 void OnDeviceRemoved(udev_device
* device
) override
{
170 DCHECK(thread_checker_
.CalledOnValidThread());
171 const char* device_path
= udev_device_get_syspath(device
);
173 task_runner_
->PostTask(
174 FROM_HERE
, base::Bind(&HidServiceLinux::RemoveDevice
, service_
,
175 std::string(device_path
)));
179 // base::MessageLoop::DestructionObserver:
180 void WillDestroyCurrentMessageLoop() override
{
181 DCHECK(thread_checker_
.CalledOnValidThread());
182 base::MessageLoop::current()->RemoveDestructionObserver(this);
186 base::ThreadChecker thread_checker_
;
187 ScopedObserver
<DeviceMonitorLinux
, DeviceMonitorLinux::Observer
> observer_
;
189 // This weak pointer is only valid when checked on this task runner.
190 base::WeakPtr
<HidServiceLinux
> service_
;
191 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
194 HidServiceLinux::HidServiceLinux(
195 scoped_refptr
<base::SingleThreadTaskRunner
> file_task_runner
)
196 : file_task_runner_(file_task_runner
), weak_factory_(this) {
197 task_runner_
= base::ThreadTaskRunnerHandle::Get();
198 // The device watcher is passed a weak pointer back to this service so that it
199 // can be cleaned up after the service is destroyed however this weak pointer
200 // must be constructed on the this thread where it will be checked.
201 file_task_runner_
->PostTask(
202 FROM_HERE
, base::Bind(&HidServiceLinux::StartHelper
,
203 weak_factory_
.GetWeakPtr(), task_runner_
));
207 void HidServiceLinux::StartHelper(
208 base::WeakPtr
<HidServiceLinux
> weak_ptr
,
209 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
) {
210 // Helper is a message loop destruction observer and will delete itself when
211 // this thread's message loop is destroyed.
212 new FileThreadHelper(weak_ptr
, task_runner
);
215 void HidServiceLinux::Connect(const HidDeviceId
& device_id
,
216 const ConnectCallback
& callback
) {
217 DCHECK(thread_checker_
.CalledOnValidThread());
219 const auto& map_entry
= devices().find(device_id
);
220 if (map_entry
== devices().end()) {
221 task_runner_
->PostTask(FROM_HERE
, base::Bind(callback
, nullptr));
224 scoped_refptr
<HidDeviceInfoLinux
> device_info
=
225 static_cast<HidDeviceInfoLinux
*>(map_entry
->second
.get());
227 scoped_ptr
<ConnectParams
> params(new ConnectParams(
228 device_info
, callback
, task_runner_
, file_task_runner_
));
230 #if defined(OS_CHROMEOS)
231 chromeos::PermissionBrokerClient
* client
=
232 chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient();
233 DCHECK(client
) << "Could not get permission broker client.";
235 device_info
->device_node(),
236 base::Bind(&HidServiceLinux::OnPathOpened
, base::Passed(¶ms
)));
238 file_task_runner_
->PostTask(FROM_HERE
,
239 base::Bind(&HidServiceLinux::OpenOnBlockingThread
,
240 base::Passed(¶ms
)));
241 #endif // defined(OS_CHROMEOS)
244 HidServiceLinux::~HidServiceLinux() {
245 file_task_runner_
->DeleteSoon(FROM_HERE
, helper_
.release());
248 #if defined(OS_CHROMEOS)
251 void HidServiceLinux::OnPathOpened(scoped_ptr
<ConnectParams
> params
,
252 dbus::FileDescriptor fd
) {
253 scoped_refptr
<base::SingleThreadTaskRunner
> file_task_runner
=
254 params
->file_task_runner
;
255 file_task_runner
->PostTask(
256 FROM_HERE
, base::Bind(&HidServiceLinux::ValidateFdOnBlockingThread
,
257 base::Passed(¶ms
), base::Passed(&fd
)));
261 void HidServiceLinux::ValidateFdOnBlockingThread(
262 scoped_ptr
<ConnectParams
> params
,
263 dbus::FileDescriptor fd
) {
264 base::ThreadRestrictions::AssertIOAllowed();
268 params
->device_file
= base::File(fd
.TakeValue());
269 FinishOpen(params
.Pass());
271 HID_LOG(EVENT
) << "Permission broker denied access to '"
272 << params
->device_info
->device_node() << "'.";
273 params
->task_runner
->PostTask(FROM_HERE
,
274 base::Bind(params
->callback
, nullptr));
281 void HidServiceLinux::OpenOnBlockingThread(scoped_ptr
<ConnectParams
> params
) {
282 base::ThreadRestrictions::AssertIOAllowed();
283 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
= params
->task_runner
;
285 base::FilePath
device_path(params
->device_info
->device_node());
286 base::File
& device_file
= params
->device_file
;
288 base::File::FLAG_OPEN
| base::File::FLAG_READ
| base::File::FLAG_WRITE
;
289 device_file
.Initialize(device_path
, flags
);
290 if (!device_file
.IsValid()) {
291 base::File::Error file_error
= device_file
.error_details();
293 if (file_error
== base::File::FILE_ERROR_ACCESS_DENIED
) {
295 << "Access denied opening device read-write, trying read-only.";
296 flags
= base::File::FLAG_OPEN
| base::File::FLAG_READ
;
297 device_file
.Initialize(device_path
, flags
);
300 if (!device_file
.IsValid()) {
301 HID_LOG(EVENT
) << "Failed to open '" << params
->device_info
->device_node()
303 << base::File::ErrorToString(device_file
.error_details());
304 task_runner
->PostTask(FROM_HERE
, base::Bind(params
->callback
, nullptr));
308 FinishOpen(params
.Pass());
311 #endif // defined(OS_CHROMEOS)
314 void HidServiceLinux::FinishOpen(scoped_ptr
<ConnectParams
> params
) {
315 base::ThreadRestrictions::AssertIOAllowed();
316 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
= params
->task_runner
;
318 int result
= net::SetNonBlocking(params
->device_file
.GetPlatformFile());
320 HID_PLOG(ERROR
) << "Failed to set the non-blocking flag on the device fd";
321 task_runner
->PostTask(FROM_HERE
, base::Bind(params
->callback
, nullptr));
325 task_runner
->PostTask(
327 base::Bind(&HidServiceLinux::CreateConnection
, base::Passed(¶ms
)));
331 void HidServiceLinux::CreateConnection(scoped_ptr
<ConnectParams
> params
) {
332 DCHECK(params
->device_file
.IsValid());
333 params
->callback
.Run(make_scoped_refptr(
334 new HidConnectionLinux(params
->device_info
, params
->device_file
.Pass(),
335 params
->file_task_runner
)));
338 } // namespace device