summaryrefslogtreecommitdiffstats
path: root/device/hid/hid_connection_win.cc
blob: 2e5eab24dd63220ddee74081636e4d530bcb44f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/hid/hid_connection_win.h"

#include <cstring>

#include "base/bind.h"
#include "base/files/file.h"
#include "base/message_loop/message_loop.h"
#include "base/numerics/safe_conversions.h"
#include "base/win/object_watcher.h"
#include "components/device_event_log/device_event_log.h"

#define INITGUID

#include <windows.h>
#include <hidclass.h>

extern "C" {
#include <hidsdi.h>
}

#include <setupapi.h>
#include <winioctl.h>

namespace device {

struct PendingHidTransfer : public base::RefCounted<PendingHidTransfer>,
                            public base::win::ObjectWatcher::Delegate,
                            public base::MessageLoop::DestructionObserver {
  typedef base::Callback<void(PendingHidTransfer*, bool)> Callback;

  PendingHidTransfer(scoped_refptr<net::IOBuffer> buffer,
                     const Callback& callback);

  void TakeResultFromWindowsAPI(BOOL result);

  OVERLAPPED* GetOverlapped() { return &overlapped_; }

  // Implements base::win::ObjectWatcher::Delegate.
  void OnObjectSignaled(HANDLE object) override;

  // Implements base::MessageLoop::DestructionObserver
  void WillDestroyCurrentMessageLoop() override;

  // The buffer isn't used by this object but it's important that a reference
  // to it is held until the transfer completes.
  scoped_refptr<net::IOBuffer> buffer_;
  Callback callback_;
  OVERLAPPED overlapped_;
  base::win::ScopedHandle event_;
  base::win::ObjectWatcher watcher_;

 private:
  friend class base::RefCounted<PendingHidTransfer>;

  ~PendingHidTransfer() override;

  DISALLOW_COPY_AND_ASSIGN(PendingHidTransfer);
};

PendingHidTransfer::PendingHidTransfer(
    scoped_refptr<net::IOBuffer> buffer,
    const PendingHidTransfer::Callback& callback)
    : buffer_(buffer),
      callback_(callback),
      event_(CreateEvent(NULL, FALSE, FALSE, NULL)) {
  memset(&overlapped_, 0, sizeof(OVERLAPPED));
  overlapped_.hEvent = event_.Get();
}

PendingHidTransfer::~PendingHidTransfer() {
  base::MessageLoop::current()->RemoveDestructionObserver(this);
}

void PendingHidTransfer::TakeResultFromWindowsAPI(BOOL result) {
  if (result) {
    callback_.Run(this, true);
  } else if (GetLastError() == ERROR_IO_PENDING) {
    base::MessageLoop::current()->AddDestructionObserver(this);
    AddRef();
    watcher_.StartWatching(event_.Get(), this);
  } else {
    HID_PLOG(EVENT) << "HID transfer failed";
    callback_.Run(this, false);
  }
}

void PendingHidTransfer::OnObjectSignaled(HANDLE event_handle) {
  callback_.Run(this, true);
  Release();
}

void PendingHidTransfer::WillDestroyCurrentMessageLoop() {
  watcher_.StopWatching();
  callback_.Run(this, false);
}

HidConnectionWin::HidConnectionWin(scoped_refptr<HidDeviceInfo> device_info,
                                   base::win::ScopedHandle file)
    : HidConnection(device_info) {
  file_ = file.Pass();
}

HidConnectionWin::~HidConnectionWin() {
}

void HidConnectionWin::PlatformClose() {
  CancelIo(file_.Get());
}

void HidConnectionWin::PlatformRead(
    const HidConnection::ReadCallback& callback) {
  // Windows will always include the report ID (including zero if report IDs
  // are not in use) in the buffer.
  scoped_refptr<net::IOBufferWithSize> buffer = new net::IOBufferWithSize(
      base::checked_cast<int>(device_info()->max_input_report_size() + 1));
  scoped_refptr<PendingHidTransfer> transfer(new PendingHidTransfer(
      buffer,
      base::Bind(&HidConnectionWin::OnReadComplete, this, buffer, callback)));
  transfers_.insert(transfer);
  transfer->TakeResultFromWindowsAPI(
      ReadFile(file_.Get(),
               buffer->data(),
               static_cast<DWORD>(buffer->size()),
               NULL,
               transfer->GetOverlapped()));
}

void HidConnectionWin::PlatformWrite(scoped_refptr<net::IOBuffer> buffer,
                                     size_t size,
                                     const WriteCallback& callback) {
  size_t expected_size = device_info()->max_output_report_size() + 1;
  DCHECK(size <= expected_size);
  // The Windows API always wants either a report ID (if supported) or zero at
  // the front of every output report and requires that the buffer size be equal
  // to the maximum output report size supported by this collection.
  if (size < expected_size) {
    scoped_refptr<net::IOBuffer> tmp_buffer = new net::IOBuffer(
        base::checked_cast<int>(expected_size));
    memcpy(tmp_buffer->data(), buffer->data(), size);
    memset(tmp_buffer->data() + size, 0, expected_size - size);
    buffer = tmp_buffer;
    size = expected_size;
  }
  scoped_refptr<PendingHidTransfer> transfer(new PendingHidTransfer(
      buffer, base::Bind(&HidConnectionWin::OnWriteComplete, this, callback)));
  transfers_.insert(transfer);
  transfer->TakeResultFromWindowsAPI(WriteFile(file_.Get(),
                                               buffer->data(),
                                               static_cast<DWORD>(size),
                                               NULL,
                                               transfer->GetOverlapped()));
}

void HidConnectionWin::PlatformGetFeatureReport(uint8_t report_id,
                                                const ReadCallback& callback) {
  // The first byte of the destination buffer is the report ID being requested.
  scoped_refptr<net::IOBufferWithSize> buffer = new net::IOBufferWithSize(
      base::checked_cast<int>(device_info()->max_feature_report_size() + 1));
  buffer->data()[0] = report_id;

  scoped_refptr<PendingHidTransfer> transfer(new PendingHidTransfer(
      buffer,
      base::Bind(
          &HidConnectionWin::OnReadFeatureComplete, this, buffer, callback)));
  transfers_.insert(transfer);
  transfer->TakeResultFromWindowsAPI(
      DeviceIoControl(file_.Get(),
                      IOCTL_HID_GET_FEATURE,
                      NULL,
                      0,
                      buffer->data(),
                      static_cast<DWORD>(buffer->size()),
                      NULL,
                      transfer->GetOverlapped()));
}

void HidConnectionWin::PlatformSendFeatureReport(
    scoped_refptr<net::IOBuffer> buffer,
    size_t size,
    const WriteCallback& callback) {
  // The Windows API always wants either a report ID (if supported) or
  // zero at the front of every output report.
  scoped_refptr<PendingHidTransfer> transfer(new PendingHidTransfer(
      buffer, base::Bind(&HidConnectionWin::OnWriteComplete, this, callback)));
  transfer->TakeResultFromWindowsAPI(
      DeviceIoControl(file_.Get(),
                      IOCTL_HID_SET_FEATURE,
                      buffer->data(),
                      static_cast<DWORD>(size),
                      NULL,
                      0,
                      NULL,
                      transfer->GetOverlapped()));
}

void HidConnectionWin::OnReadComplete(scoped_refptr<net::IOBuffer> buffer,
                                      const ReadCallback& callback,
                                      PendingHidTransfer* transfer,
                                      bool signaled) {
  if (!signaled) {
    callback.Run(false, NULL, 0);
    return;
  }

  DWORD bytes_transferred;
  if (GetOverlappedResult(
          file_.Get(), transfer->GetOverlapped(), &bytes_transferred, FALSE)) {
    CompleteRead(buffer, bytes_transferred, callback);
  } else {
    HID_PLOG(EVENT) << "HID read failed";
    callback.Run(false, NULL, 0);
  }
}

void HidConnectionWin::OnReadFeatureComplete(
    scoped_refptr<net::IOBuffer> buffer,
    const ReadCallback& callback,
    PendingHidTransfer* transfer,
    bool signaled) {
  if (!signaled) {
    callback.Run(false, NULL, 0);
    return;
  }

  DWORD bytes_transferred;
  if (GetOverlappedResult(
          file_.Get(), transfer->GetOverlapped(), &bytes_transferred, FALSE)) {
    callback.Run(true, buffer, bytes_transferred);
  } else {
    HID_PLOG(EVENT) << "HID read failed";
    callback.Run(false, NULL, 0);
  }
}

void HidConnectionWin::OnWriteComplete(const WriteCallback& callback,
                                       PendingHidTransfer* transfer,
                                       bool signaled) {
  if (!signaled) {
    callback.Run(false);
    return;
  }

  DWORD bytes_transferred;
  if (GetOverlappedResult(
          file_.Get(), transfer->GetOverlapped(), &bytes_transferred, FALSE)) {
    callback.Run(true);
  } else {
    HID_PLOG(EVENT) << "HID write failed";
    callback.Run(false);
  }
}

}  // namespace device