blob: acddeb2c116a5116b75d757a91fe3501bbc9759b [file] [log] [blame]
Vincent Palatinc6c7e4e2017-06-15 15:45:05 +02001// Copyright 2017 The Chromium OS 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
5#ifndef U2FD_UHID_DEVICE_H_
6#define U2FD_UHID_DEVICE_H_
7
Qijiang Fan356bf272019-11-18 16:13:57 +09008#include <memory>
Vincent Palatinc6c7e4e2017-06-15 15:45:05 +02009#include <string>
10
Qijiang Fan356bf272019-11-18 16:13:57 +090011#include <base/files/file_descriptor_watcher_posix.h>
Vincent Palatinc6c7e4e2017-06-15 15:45:05 +020012#include <base/files/scoped_file.h>
13#include <base/macros.h>
14
15#include "u2fd/hid_interface.h"
16
17extern "C" {
18#include <linux/uhid.h>
19}
20
21namespace u2f {
22
23// Create a HID device using the /dev/uhid kernel interface.
24class UHidDevice : public HidInterface {
25 public:
26 UHidDevice(uint32_t vendor_id,
27 uint32_t product_id,
28 const std::string& name,
29 const std::string& phys);
Qijiang Fan6bc59e12020-11-11 02:51:06 +090030 UHidDevice(const UHidDevice&) = delete;
31 UHidDevice& operator=(const UHidDevice&) = delete;
32
Vincent Palatinc6c7e4e2017-06-15 15:45:05 +020033 ~UHidDevice() override;
34
35 // HidInterface implementation:
36 bool Init(uint32_t hid_version, const std::string& report_desc) override;
37 bool SendReport(const std::string& report) override;
38 void SetOutputReportHandler(
39 const HidInterface::OutputReportCallback& on_output_report) override;
40
41 private:
42 // Asks the kernel to create a new hid device node with interface |version|
43 // presenting the blob |report_desc| as report descriptor.
44 // Returns true on success.
45 bool CreateDev(uint32_t version, const std::string& report_desc);
46 // Asks the kernel to destroy the previously created hid device.
47 void DestroyDev();
48 // Sends to the kernel a new event |ev| on the hid device.
49 // Returns true on success.
50 bool WriteEvent(const struct uhid_event& ev);
51 // Callback used when the kernel sends us an event on the hid device.
52 void FdEvent();
53
54 base::ScopedFD fd_; // A file descriptor for /dev/uhid.
55 bool created_;
56 uint32_t vendor_id_;
57 uint32_t product_id_;
58 std::string name_;
59 std::string phys_;
60
61 HidInterface::OutputReportCallback on_output_report_;
62
Qijiang Fan356bf272019-11-18 16:13:57 +090063 std::unique_ptr<base::FileDescriptorWatcher::Controller> watcher_;
Vincent Palatinc6c7e4e2017-06-15 15:45:05 +020064};
65
66} // namespace u2f
67
68#endif // U2FD_UHID_DEVICE_H_