Debian Codegraph @

src/dfu_util.c

raw
1 /*
2 * Functions for detecting DFU USB entities
3 *
4 * Written by Harald Welte <[email protected]>
5 * Copyright 2007-2008 by OpenMoko, Inc.
6 * Copyright 2013 Hans Petter Selasky <[email protected]>
7 * Copyright 2016-2019 Tormod Volden <[email protected]>
8 *
9 * Based on existing code of dfu-programmer-0.4
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 */
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <string.h>
34 #include <libusb.h>
35
36 #include "portable.h"
37 #include "dfu.h"
38 #include "usb_dfu.h"
39 #include "dfu_file.h"
40 #include "dfu_util.h"
41 #include "quirks.h"
42
43 /*
44 * Look for a descriptor in a concatenated descriptor list. Will
45 * return upon the first match of the given descriptor type. Returns length of
46 * found descriptor, limited to res_size
47 */
48 static int find_descriptor(const uint8_t *desc_list, int list_len,
49 uint8_t desc_type, void *res_buf, int res_size)
50 {
51 int p = 0;
52
53 if (list_len < 2)
54 return (-1);
55
56 while (p + 1 < list_len) {
57 int desclen;
58
59 desclen = (int) desc_list[p];
60 if (desclen == 0) {
61 warnx("Invalid descriptor list");
62 return -1;
63 }
64 if (desc_list[p + 1] == desc_type) {
65 if (desclen > res_size)
66 desclen = res_size;
67 if (p + desclen > list_len)
68 desclen = list_len - p;
69 memcpy(res_buf, &desc_list[p], desclen);
70 return desclen;
71 }
72 p += (int) desc_list[p];
73 }
74 return -1;
75 }
76
77 /*
78 * Get a string descriptor that's UTF-8 (or ASCII) encoded instead
79 * of UTF-16 encoded like the USB specification mandates. Some
80 * devices, like the GD32VF103, both violate the spec in this way
81 * and store important information in the serial number field. This
82 * function does NOT append a NUL terminator to its buffer, so you
83 * must use the returned length to ensure you stay within bounds.
84 */
85 static int get_utf8_string_descriptor(libusb_device_handle *devh,
86 uint8_t desc_index, unsigned char *data, int length)
87 {
88 unsigned char tbuf[255];
89 uint16_t langid;
90 int r, outlen;
91
92 /* get the language IDs and pick the first one */
93 r = libusb_get_string_descriptor(devh, 0, 0, tbuf, sizeof(tbuf));
94 if (r < 0) {
95 warnx("Failed to retrieve language identifiers");
96 return r;
97 }
98 if (r < 4 || tbuf[0] < 4 || tbuf[1] != LIBUSB_DT_STRING) { /* must have at least one ID */
99 warnx("Broken LANGID string descriptor");
100 return -1;
101 }
102 langid = tbuf[2] | (tbuf[3] << 8);
103
104 r = libusb_get_string_descriptor(devh, desc_index, langid, tbuf,
105 sizeof(tbuf));
106 if (r < 0) {
107 warnx("Failed to retrieve string descriptor %d", desc_index);
108 return r;
109 }
110 if (r < 2 || tbuf[0] < 2) {
111 warnx("String descriptor %d too short", desc_index);
112 return -1;
113 }
114 if (tbuf[1] != LIBUSB_DT_STRING) { /* sanity check */
115 warnx("Malformed string descriptor %d, type = 0x%02x", desc_index, tbuf[1]);
116 return -1;
117 }
118 if (tbuf[0] > r) { /* if short read, */
119 warnx("Patching string descriptor %d length (was %d, received %d)", desc_index, tbuf[0], r);
120 tbuf[0] = r; /* fix up descriptor length */
121 }
122
123 outlen = tbuf[0] - 2;
124 if (length < outlen)
125 outlen = length;
126
127 memcpy(data, tbuf + 2, outlen);
128
129 return outlen;
130 }
131
132 /*
133 * Similar to libusb_get_string_descriptor_ascii but will allow
134 * truncated descriptors (descriptor length mismatch) seen on
135 * e.g. the STM32F427 ROM bootloader.
136 */
137 static int get_string_descriptor_ascii(libusb_device_handle *devh,
138 uint8_t desc_index, unsigned char *data, int length)
139 {
140 unsigned char buf[255];
141 int r, di, si;
142
143 r = get_utf8_string_descriptor(devh, desc_index, buf, sizeof(buf));
144 if (r < 0)
145 return r;
146
147 /* convert from 16-bit unicode to ascii string */
148 for (di = 0, si = 0; si + 1 < r && di < length; si += 2) {
149 if (buf[si + 1]) /* high byte of unicode char */
150 data[di++] = '?';
151 else
152 data[di++] = buf[si];
153 }
154 data[di] = '\0';
155 return di;
156 }
157
158 static void probe_configuration(libusb_device *dev, struct libusb_device_descriptor *desc)
159 {
160 struct usb_dfu_func_descriptor func_dfu;
161 libusb_device_handle *devh;
162 struct dfu_if *pdfu;
163 struct libusb_config_descriptor *cfg;
164 const struct libusb_interface_descriptor *intf;
165 const struct libusb_interface *uif;
166 char alt_name[MAX_DESC_STR_LEN + 1];
167 char serial_name[MAX_DESC_STR_LEN + 1];
168 int cfg_idx;
169 int intf_idx;
170 int alt_idx;
171 int ret;
172 int has_dfu;
173
174 for (cfg_idx = 0; cfg_idx != desc->bNumConfigurations; cfg_idx++) {
175 memset(&func_dfu, 0, sizeof(func_dfu));
176 has_dfu = 0;
177
178 ret = libusb_get_config_descriptor(dev, cfg_idx, &cfg);
179 if (ret != 0)
180 return;
181 if (match_config_index > -1 && match_config_index != cfg->bConfigurationValue) {
182 libusb_free_config_descriptor(cfg);
183 continue;
184 }
185
186 /*
187 * In some cases, noticably FreeBSD if uid != 0,
188 * the configuration descriptors are empty
189 */
190 if (!cfg)
191 return;
192
193 ret = find_descriptor(cfg->extra, cfg->extra_length,
194 USB_DT_DFU, &func_dfu, sizeof(func_dfu));
195 if (ret > -1)
196 goto found_dfu;
197
198 for (intf_idx = 0; intf_idx < cfg->bNumInterfaces;
199 intf_idx++) {
200 uif = &cfg->interface[intf_idx];
201 if (!uif)
202 break;
203
204 for (alt_idx = 0; alt_idx < cfg->interface[intf_idx].num_altsetting;
205 alt_idx++) {
206 intf = &uif->altsetting[alt_idx];
207
208 if (intf->bInterfaceClass != 0xfe ||
209 intf->bInterfaceSubClass != 1)
210 continue;
211
212 ret = find_descriptor(intf->extra, intf->extra_length, USB_DT_DFU,
213 &func_dfu, sizeof(func_dfu));
214 if (ret > -1)
215 goto found_dfu;
216
217 has_dfu = 1;
218 }
219 }
220 if (has_dfu) {
221 /*
222 * Finally try to retrieve it requesting the
223 * device directly This is not supported on
224 * all devices for non-standard types
225 */
226 if (libusb_open(dev, &devh) == 0) {
227 ret = libusb_get_descriptor(devh, USB_DT_DFU, 0,
228 (void *)&func_dfu, sizeof(func_dfu));
229 libusb_close(devh);
230 if (ret > -1)
231 goto found_dfu;
232 }
233 warnx("Device has DFU interface, "
234 "but has no DFU functional descriptor");
235
236 /* fake version 1.0 */
237 func_dfu.bLength = 7;
238 func_dfu.bcdDFUVersion = libusb_cpu_to_le16(0x0100);
239 goto found_dfu;
240 }
241 libusb_free_config_descriptor(cfg);
242 continue;
243
244 found_dfu:
245 if (func_dfu.bLength == 7) {
246 printf("Deducing device DFU version from functional descriptor "
247 "length\n");
248 func_dfu.bcdDFUVersion = libusb_cpu_to_le16(0x0100);
249 } else if (func_dfu.bLength < 9) {
250 printf("Error obtaining DFU functional descriptor\n");
251 printf("Please report this as a bug!\n");
252 printf("Warning: Assuming DFU version 1.0\n");
253 func_dfu.bcdDFUVersion = libusb_cpu_to_le16(0x0100);
254 printf("Warning: Transfer size can not be detected\n");
255 func_dfu.wTransferSize = 0;
256 }
257
258 for (intf_idx = 0; intf_idx < cfg->bNumInterfaces;
259 intf_idx++) {
260 int multiple_alt;
261
262 if (match_iface_index > -1 && match_iface_index != intf_idx)
263 continue;
264
265 uif = &cfg->interface[intf_idx];
266 if (!uif)
267 break;
268
269 multiple_alt = uif->num_altsetting > 0;
270
271 for (alt_idx = 0;
272 alt_idx < uif->num_altsetting; alt_idx++) {
273 int dfu_mode;
274 uint16_t quirks;
275
276 quirks = get_quirks(desc->idVendor,
277 desc->idProduct, desc->bcdDevice);
278
279 intf = &uif->altsetting[alt_idx];
280
281 if (intf->bInterfaceClass != 0xfe ||
282 intf->bInterfaceSubClass != 1)
283 continue;
284
285 dfu_mode = (intf->bInterfaceProtocol == 2);
286 /* e.g. DSO Nano has bInterfaceProtocol 0 instead of 2 */
287 if (func_dfu.bcdDFUVersion == 0x011a && intf->bInterfaceProtocol == 0)
288 dfu_mode = 1;
289
290 /* LPC DFU bootloader has bInterfaceProtocol 1 (Runtime) instead of 2 */
291 if (desc->idVendor == 0x1fc9 && desc->idProduct == 0x000c && intf->bInterfaceProtocol == 1)
292 dfu_mode = 1;
293
294 /*
295 * Old Jabra devices may have bInterfaceProtocol 0 instead of 2.
296 * Also runtime PID and DFU pid are the same.
297 * In DFU mode, the configuration descriptor has only 1 interface.
298 */
299 if (desc->idVendor == 0x0b0e && intf->bInterfaceProtocol == 0 && cfg->bNumInterfaces == 1)
300 dfu_mode = 1;
301
302 if (dfu_mode &&
303 match_iface_alt_index > -1 && match_iface_alt_index != intf->bAlternateSetting)
304 continue;
305
306 if (dfu_mode) {
307 if ((match_vendor_dfu >= 0 && match_vendor_dfu != desc->idVendor) ||
308 (match_product_dfu >= 0 && match_product_dfu != desc->idProduct)) {
309 continue;
310 }
311 } else {
312 if ((match_vendor >= 0 && match_vendor != desc->idVendor) ||
313 (match_product >= 0 && match_product != desc->idProduct)) {
314 continue;
315 }
316 }
317
318 if (match_devnum >= 0 && match_devnum != libusb_get_device_address(dev))
319 continue;
320
321 ret = libusb_open(dev, &devh);
322 if (ret) {
323 warnx("Cannot open DFU device %04x:%04x found on devnum %i (%s)",
324 desc->idVendor, desc->idProduct, libusb_get_device_address(dev),
325 libusb_error_name(ret));
326 break;
327 }
328 if (intf->iInterface != 0)
329 ret = get_string_descriptor_ascii(devh,
330 intf->iInterface, (void *)alt_name, MAX_DESC_STR_LEN);
331 else
332 ret = -1;
333 if (ret < 1)
334 strcpy(alt_name, "UNKNOWN");
335 if (desc->iSerialNumber != 0) {
336 if (quirks & QUIRK_UTF8_SERIAL) {
337 ret = get_utf8_string_descriptor(devh, desc->iSerialNumber,
338 (void *)serial_name, MAX_DESC_STR_LEN - 1);
339 if (ret >= 0)
340 serial_name[ret] = '\0';
341 } else {
342 ret = get_string_descriptor_ascii(devh, desc->iSerialNumber,
343 (void *)serial_name, MAX_DESC_STR_LEN);
344 }
345 } else {
346 ret = -1;
347 }
348 if (ret < 1)
349 strcpy(serial_name, "UNKNOWN");
350 libusb_close(devh);
351
352 if (dfu_mode &&
353 match_iface_alt_name != NULL && strcmp(alt_name, match_iface_alt_name))
354 continue;
355
356 if (dfu_mode) {
357 if (match_serial_dfu != NULL && strcmp(match_serial_dfu, serial_name))
358 continue;
359 } else {
360 if (match_serial != NULL && strcmp(match_serial, serial_name))
361 continue;
362 }
363
364 pdfu = dfu_malloc(sizeof(*pdfu));
365
366 memset(pdfu, 0, sizeof(*pdfu));
367
368 pdfu->func_dfu = func_dfu;
369 pdfu->dev = libusb_ref_device(dev);
370 pdfu->quirks = quirks;
371 pdfu->vendor = desc->idVendor;
372 pdfu->product = desc->idProduct;
373 pdfu->bcdDevice = desc->bcdDevice;
374 pdfu->configuration = cfg->bConfigurationValue;
375 pdfu->interface = intf->bInterfaceNumber;
376 pdfu->altsetting = intf->bAlternateSetting;
377 pdfu->devnum = libusb_get_device_address(dev);
378 pdfu->busnum = libusb_get_bus_number(dev);
379 pdfu->alt_name = strdup(alt_name);
380 if (pdfu->alt_name == NULL)
381 errx(EX_SOFTWARE, "Out of memory");
382 pdfu->serial_name = strdup(serial_name);
383 if (pdfu->serial_name == NULL)
384 errx(EX_SOFTWARE, "Out of memory");
385 if (dfu_mode)
386 pdfu->flags |= DFU_IFF_DFU;
387 if (multiple_alt)
388 pdfu->flags |= DFU_IFF_ALT;
389 if (pdfu->quirks & QUIRK_FORCE_DFU11) {
390 pdfu->func_dfu.bcdDFUVersion =
391 libusb_cpu_to_le16(0x0110);
392 }
393 pdfu->bMaxPacketSize0 = desc->bMaxPacketSize0;
394
395 /* queue into list */
396 pdfu->next = dfu_root;
397 dfu_root = pdfu;
398 }
399 }
400 libusb_free_config_descriptor(cfg);
401 }
402 }
403
404 #define MAX_PATH_LEN 20
405 char path_buf[MAX_PATH_LEN];
406
407 char *get_path(libusb_device *dev)
408 {
409 #if (defined(LIBUSB_API_VERSION) && LIBUSB_API_VERSION >= 0x01000102) || (defined(LIBUSBX_API_VERSION) && LIBUSBX_API_VERSION >= 0x01000102)
410 uint8_t path[8];
411 int r,j;
412 r = libusb_get_port_numbers(dev, path, sizeof(path));
413 if (r > 0) {
414 sprintf(path_buf,"%d-%d",libusb_get_bus_number(dev),path[0]);
415 for (j = 1; j < r; j++){
416 sprintf(path_buf+strlen(path_buf),".%d",path[j]);
417 };
418 }
419 return path_buf;
420 #else
421 # warning "libusb too old - building without USB path support!"
422 (void)dev;
423 return NULL;
424 #endif
425 }
426
427 void probe_devices(libusb_context *ctx)
428 {
429 libusb_device **list;
430 ssize_t num_devs;
431 ssize_t i;
432
433 num_devs = libusb_get_device_list(ctx, &list);
434 for (i = 0; i < num_devs; ++i) {
435 struct libusb_device_descriptor desc;
436 struct libusb_device *dev = list[i];
437
438 if (match_path != NULL && strcmp(get_path(dev),match_path) != 0)
439 continue;
440 if (libusb_get_device_descriptor(dev, &desc))
441 continue;
442 probe_configuration(dev, &desc);
443 }
444 libusb_free_device_list(list, 1);
445 }
446
447 void disconnect_devices(void)
448 {
449 struct dfu_if *pdfu;
450 struct dfu_if *prev = NULL;
451
452 for (pdfu = dfu_root; pdfu != NULL; pdfu = pdfu->next) {
453 free(prev);
454 libusb_unref_device(pdfu->dev);
455 free(pdfu->alt_name);
456 free(pdfu->serial_name);
457 prev = pdfu;
458 }
459 free(prev);
460 dfu_root = NULL;
461 }
462
463 void print_dfu_if(struct dfu_if *dfu_if)
464 {
465 printf("Found %s: [%04x:%04x] ver=%04x, devnum=%u, cfg=%u, intf=%u, "
466 "path=\"%s\", alt=%u, name=\"%s\", serial=\"%s\"\n",
467 dfu_if->flags & DFU_IFF_DFU ? "DFU" : "Runtime",
468 dfu_if->vendor, dfu_if->product,
469 dfu_if->bcdDevice, dfu_if->devnum,
470 dfu_if->configuration, dfu_if->interface,
471 get_path(dfu_if->dev),
472 dfu_if->altsetting, dfu_if->alt_name,
473 dfu_if->serial_name);
474 }
475
476 /* Walk the device tree and print out DFU devices */
477 void list_dfu_interfaces(void)
478 {
479 struct dfu_if *pdfu;
480
481 for (pdfu = dfu_root; pdfu != NULL; pdfu = pdfu->next)
482 print_dfu_if(pdfu);
483 }