Debian Codegraph @

monero/src/device/device_io_hid.cpp

raw symbols SCIP
1 // Copyright (c) 2017-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 #if defined(HAVE_HIDAPI)
30
31 #include <boost/scope_exit.hpp>
32 #include "log.hpp"
33 #include "device_io_hid.hpp"
34 #include "device_errors.hpp"
35
36 namespace hw {
37 namespace io {
38
39 #undef MONERO_DEFAULT_LOG_CATEGORY
40 #define MONERO_DEFAULT_LOG_CATEGORY "device.io"
41
42 #define ASSERT_X(exp,msg) CHECK_AND_ASSERT_THROW_MES(exp, msg);
43
44 #define ASSERT_AND_EXCEPT(cond, err_type, message) \
45 if (!(cond)) \
46 { \
47 this->disconnected = true; \
48 LOG_ERROR(#cond << ". THROW EXCEPTION: " << #err_type); \
49 hw::error::throw_exception<err_type>(message); \
50 }
51
52
53 #define MAX_BLOCK 64
54
55 static std::string safe_hid_error(hid_device *hwdev) {
56 if (hwdev) {
57 const wchar_t* error_wstr = hid_error(hwdev);
58 if (error_wstr == nullptr)
59 {
60 return "Unknown error";
61 }
62 std::mbstate_t state{};
63 const size_t len_symbols = std::wcsrtombs(nullptr, &error_wstr, 0, &state);
64 if (len_symbols == static_cast<std::size_t>(-1))
65 {
66 return "Failed to convert wide char error";
67 }
68 std::string error_str(len_symbols + 1, 0);
69 std::wcsrtombs(&error_str[0], &error_wstr, error_str.size(), &state);
70 return error_str;
71 }
72 return std::string("NULL device");
73 }
74
75 static std::string safe_hid_path(const hid_device_info *hwdev_info) {
76 if (hwdev_info && hwdev_info->path) {
77 return std::string(hwdev_info->path);
78 }
79 return std::string("NULL path");
80 }
81
82 device_io_hid::device_io_hid(unsigned short c, unsigned char t, unsigned int ps, unsigned int to) :
83 channel(c),
84 tag(t),
85 packet_size(ps),
86 timeout(to),
87 usb_vid(0),
88 usb_pid(0),
89 usb_device(NULL) {
90 }
91
92 device_io_hid::device_io_hid() : device_io_hid(DEFAULT_CHANNEL, DEFAULT_TAG, DEFAULT_PACKET_SIZE, DEFAULT_TIMEOUT) {
93 }
94
95 void device_io_hid::io_hid_log(int read, unsigned char* buffer, int block_len) {
96 if (hid_verbose) {
97 char strbuffer[1024];
98 hw::buffer_to_str(strbuffer, sizeof(strbuffer), (char*)buffer, block_len);
99 MDEBUG( "HID " << (read?"<":">") <<" : "<<strbuffer);
100 }
101 }
102
103 void device_io_hid::init() {
104 int r;
105 r = hid_init();
106 ASSERT_X(r>=0, "Unable to init hidapi library. Error "+std::to_string(r)+": "+safe_hid_error(this->usb_device));
107 }
108
109 void device_io_hid::connect(void *params) {
110 hid_conn_params *p = (struct hid_conn_params*)params;
111 if (!this->connect(p->vid, p->pid, p->interface_number, p->usage_page)) {
112 ASSERT_X(false, "No device found");
113 }
114 }
115
116 void device_io_hid::connect(const std::vector<hid_conn_params> &hcpV) {
117 for (auto p: hcpV) {
118 if (this->connect(p.vid, p.pid, p.interface_number, p.usage_page)) {
119 return;
120 }
121 }
122 ASSERT_X(false, "No device found");
123 }
124
125 hid_device_info *device_io_hid::find_device(hid_device_info *devices_list, boost::optional<int> interface_number, boost::optional<unsigned short> usage_page) {
126 bool select_any = !interface_number && !usage_page;
127
128 MDEBUG( "Looking for " <<
129 (select_any ? "any HID Device" : "HID Device with") <<
130 (interface_number ? (" interface_number " + std::to_string(interface_number.value())) : "") <<
131 ((interface_number && usage_page) ? " or" : "") <<
132 (usage_page ? (" usage_page " + std::to_string(usage_page.value())) : ""));
133
134 hid_device_info *result = nullptr;
135 for (; devices_list != nullptr; devices_list = devices_list->next) {
136 BOOST_SCOPE_EXIT(&devices_list, &result) {
137 MDEBUG( (result == devices_list ? "SELECTED" : "SKIPPED ") <<
138 " HID Device" <<
139 " path " << safe_hid_path(devices_list) <<
140 " interface_number " << devices_list->interface_number <<
141 " usage_page " << devices_list->usage_page);
142 }
143 BOOST_SCOPE_EXIT_END
144
145 if (result != nullptr) {
146 continue;
147 }
148
149 if (select_any) {
150 result = devices_list;
151 } else if (interface_number && devices_list->interface_number == interface_number.value()) {
152 result = devices_list;
153 } else if (usage_page && devices_list->usage_page == usage_page.value()) {
154 result = devices_list;
155 }
156 }
157
158 return result;
159 }
160
161 hid_device *device_io_hid::connect(unsigned int vid, unsigned int pid, boost::optional<int> interface_number, boost::optional<unsigned short> usage_page) {
162 hid_device_info *hwdev_info_list;
163 hid_device *hwdev;
164
165 this->disconnect();
166
167 hwdev_info_list = hid_enumerate(vid, pid);
168 if (!hwdev_info_list) {
169 MDEBUG("Unable to enumerate device "+std::to_string(vid)+":"+std::to_string(vid)+ ": "+ safe_hid_error(this->usb_device));
170 return NULL;
171 }
172 hwdev = NULL;
173 if (hid_device_info *device = find_device(hwdev_info_list, interface_number, usage_page)) {
174 hwdev = hid_open_path(device->path);
175 }
176 hid_free_enumeration(hwdev_info_list);
177 ASSERT_X(hwdev, "Unable to open device "+std::to_string(pid)+":"+std::to_string(vid));
178 this->usb_vid = vid;
179 this->usb_pid = pid;
180 this->usb_device = hwdev;
181 return hwdev;
182 }
183
184
185 bool device_io_hid::connected() const {
186 return this->usb_device != NULL;
187 }
188
189 int device_io_hid::exchange(unsigned char *command, unsigned int cmd_len, unsigned char *response, unsigned int max_resp_len, bool user_input) {
190 unsigned char buffer[400];
191 unsigned char padding_buffer[MAX_BLOCK+1];
192 unsigned int result;
193 int hid_ret;
194 unsigned int remaining;
195 unsigned int offset = 0;
196
197 ASSERT_X(this->usb_device,"No device opened");
198
199 //Split command in several HID packet
200 memset(buffer, 0, sizeof(buffer));
201 result = this->wrapCommand(command, cmd_len, buffer, sizeof(buffer));
202 remaining = result;
203
204 while (remaining > 0) {
205 int block_size = (remaining > MAX_BLOCK ? MAX_BLOCK : remaining);
206 memset(padding_buffer, 0, sizeof(padding_buffer));
207 memcpy(padding_buffer+1, buffer + offset, block_size);
208 io_hid_log(0, padding_buffer, block_size+1);
209 hid_ret = hid_write(this->usb_device, padding_buffer, block_size+1);
210
211 ASSERT_AND_EXCEPT(hid_ret>0, hw::error::device_disconnected, "Unable to send hidapi command. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device));
212 offset += block_size;
213 remaining -= block_size;
214 }
215
216 //get first response
217 memset(buffer, 0, sizeof(buffer));
218 if (!user_input) {
219 hid_ret = hid_read_timeout(this->usb_device, buffer, MAX_BLOCK, this->timeout);
220 } else {
221 hid_ret = hid_read(this->usb_device, buffer, MAX_BLOCK);
222 }
223
224 ASSERT_AND_EXCEPT(hid_ret>=0, hw::error::device_disconnected, "Unable to read hidapi response. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device));
225
226 result = (unsigned int)hid_ret;
227 io_hid_log(1, buffer, result);
228 offset = MAX_BLOCK;
229 //parse first response and get others if any
230 for (;;) {
231 result = this->unwrapReponse(buffer, offset, response, max_resp_len);
232 if (result != 0) {
233 break;
234 }
235 hid_ret = hid_read_timeout(this->usb_device, buffer + offset, MAX_BLOCK, this->timeout);
236 ASSERT_AND_EXCEPT(hid_ret>=0, hw::error::device_disconnected, "Unable to receive hidapi response. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device))
237 result = (unsigned int)hid_ret;
238 io_hid_log(1, buffer + offset, result);
239 offset += MAX_BLOCK;
240 }
241
242 this->disconnected = false;
243 return result;
244 }
245
246 void device_io_hid::disconnect(void) {
247 if (this->usb_device) {
248 hid_close(this->usb_device);
249 }
250 this->usb_vid = 0;
251 this->usb_pid = 0;
252 this->usb_device = NULL;
253 }
254
255 void device_io_hid::release() {
256 /* Do not exit, as the lib context is global*/
257 //hid_exit();
258 }
259
260 unsigned int device_io_hid::wrapCommand(const unsigned char *command, size_t command_len, unsigned char *out, size_t out_len) {
261 unsigned int sequence_idx = 0;
262 unsigned int offset = 0;
263 unsigned int offset_out = 0;
264 unsigned int block_size;
265
266 ASSERT_X(this->packet_size >= 3, "Invalid Packet size: "+std::to_string(this->packet_size)) ;
267 ASSERT_X(out_len >= 7, "out_len too short: "+std::to_string(out_len));
268
269 out_len -= 7;
270 out[offset_out++] = ((this->channel >> 8) & 0xff);
271 out[offset_out++] = (this->channel & 0xff);
272 out[offset_out++] = this->tag;
273 out[offset_out++] = ((sequence_idx >> 8) & 0xff);
274 out[offset_out++] = (sequence_idx & 0xff);
275 sequence_idx++;
276 out[offset_out++] = ((command_len >> 8) & 0xff);
277 out[offset_out++] = (command_len & 0xff);
278 block_size = (command_len > this->packet_size - 7 ? this->packet_size - 7 : command_len);
279 ASSERT_X(out_len >= block_size, "out_len too short: "+std::to_string(out_len));
280 out_len -= block_size;
281 memcpy(out + offset_out, command + offset, block_size);
282 offset_out += block_size;
283 offset += block_size;
284 while (offset != command_len) {
285 ASSERT_X(out_len >= 5, "out_len too short: "+std::to_string(out_len));
286 out_len -= 5;
287 out[offset_out++] = ((this->channel >> 8) & 0xff);
288 out[offset_out++] = (this->channel & 0xff);
289 out[offset_out++] = this->tag;
290 out[offset_out++] = ((sequence_idx >> 8) & 0xff);
291 out[offset_out++] = (sequence_idx & 0xff);
292 sequence_idx++;
293 block_size = ((command_len - offset) > this->packet_size - 5 ? this->packet_size - 5 : command_len - offset);
294 ASSERT_X(out_len >= block_size, "out_len too short: "+std::to_string(out_len));
295 out_len -= block_size;
296 memcpy(out + offset_out, command + offset, block_size);
297 offset_out += block_size;
298 offset += block_size;
299 }
300 while ((offset_out % this->packet_size) != 0) {
301 ASSERT_X(out_len >= 1, "out_len too short: "+std::to_string(out_len));
302 out_len--;
303 out[offset_out++] = 0;
304 }
305 return offset_out;
306 }
307
308 /*
309 * return 0 if more data are needed
310 * >0 if response is fully available
311 */
312 unsigned int device_io_hid::unwrapReponse(const unsigned char *data, size_t data_len, unsigned char *out, size_t out_len) {
313 unsigned int sequence_idx = 0;
314 unsigned int offset = 0;
315 unsigned int offset_out = 0;
316 unsigned int response_len;
317 unsigned int block_size;
318 unsigned int val;
319
320 //end?
321 if ((data == NULL) || (data_len < 7 + 5)) {
322 return 0;
323 }
324
325 //check hid header
326 val = (data[offset]<<8) + data[offset+1];
327 offset += 2;
328 ASSERT_X(val == this->channel, "Wrong Channel");
329 val = data[offset];
330 offset++;
331 ASSERT_X(val == this->tag, "Wrong TAG");
332 val = (data[offset]<<8) + data[offset+1];
333 offset += 2;
334 ASSERT_X(val == sequence_idx, "Wrong sequence_idx");
335
336 //fetch
337 response_len = (data[offset++] << 8);
338 response_len |= data[offset++];
339 ASSERT_X(out_len >= response_len, "Out Buffer too short");
340 if (data_len < (7 + response_len)) {
341 return 0;
342 }
343 block_size = (response_len > (this->packet_size - 7) ? this->packet_size - 7 : response_len);
344 memcpy(out + offset_out, data + offset, block_size);
345 offset += block_size;
346 offset_out += block_size;
347 while (offset_out != response_len) {
348 sequence_idx++;
349 if (offset == data_len) {
350 return 0;
351 }
352 val = (data[offset]<<8) + data[offset+1];
353 offset += 2;
354 ASSERT_X(val == this->channel, "Wrong Channel");
355 val = data[offset];
356 offset++;
357 ASSERT_X(val == this->tag, "Wrong TAG");
358 val = (data[offset]<<8) + data[offset+1];
359 offset += 2;
360 ASSERT_X(val == sequence_idx, "Wrong sequence_idx");
361
362 block_size = ((response_len - offset_out) > this->packet_size - 5 ? this->packet_size - 5 : response_len - offset_out);
363 if (block_size > (data_len - offset)) {
364 return 0;
365 }
366 memcpy(out + offset_out, data + offset, block_size);
367 offset += block_size;
368 offset_out += block_size;
369 }
370 return offset_out;
371 }
372
373
374 }
375 }
376
377 #endif //#if defined(HAVE_HIDAPI)