Debian Codegraph @

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
35 namespace hw {
36 namespace io {
37
38 #undef MONERO_DEFAULT_LOG_CATEGORY
39 #define MONERO_DEFAULT_LOG_CATEGORY "device.io"
40
41 #define ASSERT_X(exp,msg) CHECK_AND_ASSERT_THROW_MES(exp, msg);
42
43 #define MAX_BLOCK 64
44
45 static std::string safe_hid_error(hid_device *hwdev) {
46 if (hwdev) {
47 const wchar_t* error_wstr = hid_error(hwdev);
48 if (error_wstr == nullptr)
49 {
50 return "Unknown error";
51 }
52 std::mbstate_t state{};
53 const size_t len_symbols = std::wcsrtombs(nullptr, &error_wstr, 0, &state);
54 if (len_symbols == static_cast<std::size_t>(-1))
55 {
56 return "Failed to convert wide char error";
57 }
58 std::string error_str(len_symbols + 1, 0);
59 std::wcsrtombs(&error_str[0], &error_wstr, error_str.size(), &state);
60 return error_str;
61 }
62 return std::string("NULL device");
63 }
64
65 static std::string safe_hid_path(const hid_device_info *hwdev_info) {
66 if (hwdev_info && hwdev_info->path) {
67 return std::string(hwdev_info->path);
68 }
69 return std::string("NULL path");
70 }
71
72 device_io_hid::device_io_hid(unsigned short c, unsigned char t, unsigned int ps, unsigned int to) :
73 channel(c),
74 tag(t),
75 packet_size(ps),
76 timeout(to),
77 usb_vid(0),
78 usb_pid(0),
79 usb_device(NULL) {
80 }
81
82 device_io_hid::device_io_hid() : device_io_hid(DEFAULT_CHANNEL, DEFAULT_TAG, DEFAULT_PACKET_SIZE, DEFAULT_TIMEOUT) {
83 }
84
85 void device_io_hid::io_hid_log(int read, unsigned char* buffer, int block_len) {
86 if (hid_verbose) {
87 char strbuffer[1024];
88 hw::buffer_to_str(strbuffer, sizeof(strbuffer), (char*)buffer, block_len);
89 MDEBUG( "HID " << (read?"<":">") <<" : "<<strbuffer);
90 }
91 }
92
93 void device_io_hid::init() {
94 int r;
95 r = hid_init();
96 ASSERT_X(r>=0, "Unable to init hidapi library. Error "+std::to_string(r)+": "+safe_hid_error(this->usb_device));
97 }
98
99 void device_io_hid::connect(void *params) {
100 hid_conn_params *p = (struct hid_conn_params*)params;
101 if (!this->connect(p->vid, p->pid, p->interface_number, p->usage_page)) {
102 ASSERT_X(false, "No device found");
103 }
104 }
105
106 void device_io_hid::connect(const std::vector<hid_conn_params> &hcpV) {
107 for (auto p: hcpV) {
108 if (this->connect(p.vid, p.pid, p.interface_number, p.usage_page)) {
109 return;
110 }
111 }
112 ASSERT_X(false, "No device found");
113 }
114
115 hid_device_info *device_io_hid::find_device(hid_device_info *devices_list, boost::optional<int> interface_number, boost::optional<unsigned short> usage_page) {
116 bool select_any = !interface_number && !usage_page;
117
118 MDEBUG( "Looking for " <<
119 (select_any ? "any HID Device" : "HID Device with") <<
120 (interface_number ? (" interface_number " + std::to_string(interface_number.value())) : "") <<
121 ((interface_number && usage_page) ? " or" : "") <<
122 (usage_page ? (" usage_page " + std::to_string(usage_page.value())) : ""));
123
124 hid_device_info *result = nullptr;
125 for (; devices_list != nullptr; devices_list = devices_list->next) {
126 BOOST_SCOPE_EXIT(&devices_list, &result) {
127 MDEBUG( (result == devices_list ? "SELECTED" : "SKIPPED ") <<
128 " HID Device" <<
129 " path " << safe_hid_path(devices_list) <<
130 " interface_number " << devices_list->interface_number <<
131 " usage_page " << devices_list->usage_page);
132 }
133 BOOST_SCOPE_EXIT_END
134
135 if (result != nullptr) {
136 continue;
137 }
138
139 if (select_any) {
140 result = devices_list;
141 } else if (interface_number && devices_list->interface_number == interface_number.value()) {
142 result = devices_list;
143 } else if (usage_page && devices_list->usage_page == usage_page.value()) {
144 result = devices_list;
145 }
146 }
147
148 return result;
149 }
150
151 hid_device *device_io_hid::connect(unsigned int vid, unsigned int pid, boost::optional<int> interface_number, boost::optional<unsigned short> usage_page) {
152 hid_device_info *hwdev_info_list;
153 hid_device *hwdev;
154
155 this->disconnect();
156
157 hwdev_info_list = hid_enumerate(vid, pid);
158 if (!hwdev_info_list) {
159 MDEBUG("Unable to enumerate device "+std::to_string(vid)+":"+std::to_string(vid)+ ": "+ safe_hid_error(this->usb_device));
160 return NULL;
161 }
162 hwdev = NULL;
163 if (hid_device_info *device = find_device(hwdev_info_list, interface_number, usage_page)) {
164 hwdev = hid_open_path(device->path);
165 }
166 hid_free_enumeration(hwdev_info_list);
167 ASSERT_X(hwdev, "Unable to open device "+std::to_string(pid)+":"+std::to_string(vid));
168 this->usb_vid = vid;
169 this->usb_pid = pid;
170 this->usb_device = hwdev;
171 return hwdev;
172 }
173
174
175 bool device_io_hid::connected() const {
176 return this->usb_device != NULL;
177 }
178
179 int device_io_hid::exchange(unsigned char *command, unsigned int cmd_len, unsigned char *response, unsigned int max_resp_len, bool user_input) {
180 unsigned char buffer[400];
181 unsigned char padding_buffer[MAX_BLOCK+1];
182 unsigned int result;
183 int hid_ret;
184 unsigned int remaining;
185 unsigned int offset = 0;
186
187 ASSERT_X(this->usb_device,"No device opened");
188
189 //Split command in several HID packet
190 memset(buffer, 0, sizeof(buffer));
191 result = this->wrapCommand(command, cmd_len, buffer, sizeof(buffer));
192 remaining = result;
193
194 while (remaining > 0) {
195 int block_size = (remaining > MAX_BLOCK ? MAX_BLOCK : remaining);
196 memset(padding_buffer, 0, sizeof(padding_buffer));
197 memcpy(padding_buffer+1, buffer + offset, block_size);
198 io_hid_log(0, padding_buffer, block_size+1);
199 hid_ret = hid_write(this->usb_device, padding_buffer, block_size+1);
200 ASSERT_X(hid_ret>=0, "Unable to send hidapi command. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device));
201 offset += block_size;
202 remaining -= block_size;
203 }
204
205 //get first response
206 memset(buffer, 0, sizeof(buffer));
207 if (!user_input) {
208 hid_ret = hid_read_timeout(this->usb_device, buffer, MAX_BLOCK, this->timeout);
209 } else {
210 hid_ret = hid_read(this->usb_device, buffer, MAX_BLOCK);
211 }
212 ASSERT_X(hid_ret>=0, "Unable to read hidapi response. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device));
213 result = (unsigned int)hid_ret;
214 io_hid_log(1, buffer, result);
215 offset = MAX_BLOCK;
216 //parse first response and get others if any
217 for (;;) {
218 result = this->unwrapReponse(buffer, offset, response, max_resp_len);
219 if (result != 0) {
220 break;
221 }
222 hid_ret = hid_read_timeout(this->usb_device, buffer + offset, MAX_BLOCK, this->timeout);
223 ASSERT_X(hid_ret>=0, "Unable to receive hidapi response. Error "+std::to_string(result)+": "+ safe_hid_error(this->usb_device));
224 result = (unsigned int)hid_ret;
225 io_hid_log(1, buffer + offset, result);
226 offset += MAX_BLOCK;
227 }
228 return result;
229 }
230
231 void device_io_hid::disconnect(void) {
232 if (this->usb_device) {
233 hid_close(this->usb_device);
234 }
235 this->usb_vid = 0;
236 this->usb_pid = 0;
237 this->usb_device = NULL;
238 }
239
240 void device_io_hid::release() {
241 /* Do not exit, as the lib context is global*/
242 //hid_exit();
243 }
244
245 unsigned int device_io_hid::wrapCommand(const unsigned char *command, size_t command_len, unsigned char *out, size_t out_len) {
246 unsigned int sequence_idx = 0;
247 unsigned int offset = 0;
248 unsigned int offset_out = 0;
249 unsigned int block_size;
250
251 ASSERT_X(this->packet_size >= 3, "Invalid Packet size: "+std::to_string(this->packet_size)) ;
252 ASSERT_X(out_len >= 7, "out_len too short: "+std::to_string(out_len));
253
254 out_len -= 7;
255 out[offset_out++] = ((this->channel >> 8) & 0xff);
256 out[offset_out++] = (this->channel & 0xff);
257 out[offset_out++] = this->tag;
258 out[offset_out++] = ((sequence_idx >> 8) & 0xff);
259 out[offset_out++] = (sequence_idx & 0xff);
260 sequence_idx++;
261 out[offset_out++] = ((command_len >> 8) & 0xff);
262 out[offset_out++] = (command_len & 0xff);
263 block_size = (command_len > this->packet_size - 7 ? this->packet_size - 7 : command_len);
264 ASSERT_X(out_len >= block_size, "out_len too short: "+std::to_string(out_len));
265 out_len -= block_size;
266 memcpy(out + offset_out, command + offset, block_size);
267 offset_out += block_size;
268 offset += block_size;
269 while (offset != command_len) {
270 ASSERT_X(out_len >= 5, "out_len too short: "+std::to_string(out_len));
271 out_len -= 5;
272 out[offset_out++] = ((this->channel >> 8) & 0xff);
273 out[offset_out++] = (this->channel & 0xff);
274 out[offset_out++] = this->tag;
275 out[offset_out++] = ((sequence_idx >> 8) & 0xff);
276 out[offset_out++] = (sequence_idx & 0xff);
277 sequence_idx++;
278 block_size = ((command_len - offset) > this->packet_size - 5 ? this->packet_size - 5 : command_len - offset);
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 }
285 while ((offset_out % this->packet_size) != 0) {
286 ASSERT_X(out_len >= 1, "out_len too short: "+std::to_string(out_len));
287 out_len--;
288 out[offset_out++] = 0;
289 }
290 return offset_out;
291 }
292
293 /*
294 * return 0 if more data are needed
295 * >0 if response is fully available
296 */
297 unsigned int device_io_hid::unwrapReponse(const unsigned char *data, size_t data_len, unsigned char *out, size_t out_len) {
298 unsigned int sequence_idx = 0;
299 unsigned int offset = 0;
300 unsigned int offset_out = 0;
301 unsigned int response_len;
302 unsigned int block_size;
303 unsigned int val;
304
305 //end?
306 if ((data == NULL) || (data_len < 7 + 5)) {
307 return 0;
308 }
309
310 //check hid header
311 val = (data[offset]<<8) + data[offset+1];
312 offset += 2;
313 ASSERT_X(val == this->channel, "Wrong Channel");
314 val = data[offset];
315 offset++;
316 ASSERT_X(val == this->tag, "Wrong TAG");
317 val = (data[offset]<<8) + data[offset+1];
318 offset += 2;
319 ASSERT_X(val == sequence_idx, "Wrong sequence_idx");
320
321 //fetch
322 response_len = (data[offset++] << 8);
323 response_len |= data[offset++];
324 ASSERT_X(out_len >= response_len, "Out Buffer too short");
325 if (data_len < (7 + response_len)) {
326 return 0;
327 }
328 block_size = (response_len > (this->packet_size - 7) ? this->packet_size - 7 : response_len);
329 memcpy(out + offset_out, data + offset, block_size);
330 offset += block_size;
331 offset_out += block_size;
332 while (offset_out != response_len) {
333 sequence_idx++;
334 if (offset == data_len) {
335 return 0;
336 }
337 val = (data[offset]<<8) + data[offset+1];
338 offset += 2;
339 ASSERT_X(val == this->channel, "Wrong Channel");
340 val = data[offset];
341 offset++;
342 ASSERT_X(val == this->tag, "Wrong TAG");
343 val = (data[offset]<<8) + data[offset+1];
344 offset += 2;
345 ASSERT_X(val == sequence_idx, "Wrong sequence_idx");
346
347 block_size = ((response_len - offset_out) > this->packet_size - 5 ? this->packet_size - 5 : response_len - offset_out);
348 if (block_size > (data_len - offset)) {
349 return 0;
350 }
351 memcpy(out + offset_out, data + offset, block_size);
352 offset += block_size;
353 offset_out += block_size;
354 }
355 return offset_out;
356 }
357
358
359 }
360 }
361
362 #endif //#if defined(HAVE_HIDAPI)