Add ICU message format support
[chromium-blink-merge.git] / device / hid / hid_service_linux.cc
blob713b4474c2a2efc13f3c8477b9b93f45a1060cce
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"
7 #include <fcntl.h>
8 #include <limits>
9 #include <string>
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)
34 namespace device {
36 namespace {
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";
44 } // namespace
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),
52 callback(callback),
53 task_runner(task_runner),
54 file_task_runner(file_task_runner) {}
55 ~ConnectParams() {}
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 {
67 public:
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);
73 monitor->Enumerate(
74 base::Bind(&FileThreadHelper::OnDeviceAdded, base::Unretained(this)));
75 task_runner->PostTask(
76 FROM_HERE,
77 base::Bind(&HidServiceLinux::FirstEnumerationComplete, service_));
80 ~FileThreadHelper() override {
81 DCHECK(thread_checker_.CalledOnValidThread());
84 private:
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);
89 if (!device_path) {
90 return;
92 HidDeviceId device_id = device_path;
94 const char* subsystem = udev_device_get_subsystem(device);
95 if (!subsystem || strcmp(subsystem, kHidrawSubsystem) != 0) {
96 return;
99 const char* str_property = udev_device_get_devnode(device);
100 if (!str_property) {
101 return;
103 std::string device_node = str_property;
105 udev_device* parent = udev_device_get_parent(device);
106 if (!parent) {
107 return;
110 const char* hid_id = udev_device_get_property_value(parent, kHIDID);
111 if (!hid_id) {
112 return;
115 std::vector<std::string> parts;
116 base::SplitString(hid_id, ':', &parts);
117 if (parts.size() != 3) {
118 return;
121 uint32_t int_property = 0;
122 if (!HexStringToUInt(base::StringPiece(parts[1]), &int_property) ||
123 int_property > std::numeric_limits<uint16_t>::max()) {
124 return;
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()) {
130 return;
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) {
148 return;
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)) {
155 return;
158 scoped_refptr<HidDeviceInfo> device_info(new HidDeviceInfoLinux(
159 device_id, device_node, vendor_id, product_id, product_name,
160 serial_number,
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);
172 if (device_path) {
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);
183 delete 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_));
206 // static
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));
222 return;
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.";
234 client->OpenPath(
235 device_info->device_node(),
236 base::Bind(&HidServiceLinux::OnPathOpened, base::Passed(&params)));
237 #else
238 file_task_runner_->PostTask(FROM_HERE,
239 base::Bind(&HidServiceLinux::OpenOnBlockingThread,
240 base::Passed(&params)));
241 #endif // defined(OS_CHROMEOS)
244 HidServiceLinux::~HidServiceLinux() {
245 file_task_runner_->DeleteSoon(FROM_HERE, helper_.release());
248 #if defined(OS_CHROMEOS)
250 // static
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(&params), base::Passed(&fd)));
260 // static
261 void HidServiceLinux::ValidateFdOnBlockingThread(
262 scoped_ptr<ConnectParams> params,
263 dbus::FileDescriptor fd) {
264 base::ThreadRestrictions::AssertIOAllowed();
266 fd.CheckValidity();
267 if (fd.is_valid()) {
268 params->device_file = base::File(fd.TakeValue());
269 FinishOpen(params.Pass());
270 } else {
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));
278 #else
280 // static
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;
287 int flags =
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) {
294 HID_LOG(EVENT)
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()
302 << "': "
303 << base::File::ErrorToString(device_file.error_details());
304 task_runner->PostTask(FROM_HERE, base::Bind(params->callback, nullptr));
305 return;
308 FinishOpen(params.Pass());
311 #endif // defined(OS_CHROMEOS)
313 // static
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());
319 if (result == -1) {
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));
322 return;
325 task_runner->PostTask(
326 FROM_HERE,
327 base::Bind(&HidServiceLinux::CreateConnection, base::Passed(&params)));
330 // static
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