1/*
2 *
3 *  BlueZ - Bluetooth protocol stack for Linux
4 *
5 *  Copyright (C) 2003-2009  Marcel Holtmann <marcel@holtmann.org>
6 *
7 *
8 *  This program is free software; you can redistribute it and/or modify
9 *  it under the terms of the GNU General Public License as published by
10 *  the Free Software Foundation; either version 2 of the License, or
11 *  (at your option) any later version.
12 *
13 *  This program is distributed in the hope that it will be useful,
14 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *  GNU General Public License for more details.
17 *
18 *  You should have received a copy of the GNU General Public License
19 *  along with this program; if not, write to the Free Software
20 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21 *
22 */
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <stdio.h>
29#include <errno.h>
30#include <ctype.h>
31#include <fcntl.h>
32#include <unistd.h>
33#include <stdint.h>
34#include <stdlib.h>
35#include <getopt.h>
36#include <string.h>
37#include <libgen.h>
38#include <endian.h>
39#include <byteswap.h>
40#include <sys/types.h>
41#include <sys/stat.h>
42
43#include <usb.h>
44
45#include "dfu.h"
46
47#if __BYTE_ORDER == __LITTLE_ENDIAN
48#define cpu_to_le16(d)  (d)
49#define cpu_to_le32(d)  (d)
50#define le16_to_cpu(d)  (d)
51#define le32_to_cpu(d)  (d)
52#elif __BYTE_ORDER == __BIG_ENDIAN
53#define cpu_to_le16(d)  bswap_16(d)
54#define cpu_to_le32(d)  bswap_32(d)
55#define le16_to_cpu(d)  bswap_16(d)
56#define le32_to_cpu(d)  bswap_32(d)
57#else
58#error "Unknown byte order"
59#endif
60
61#ifdef NEED_USB_GET_BUSSES
62static inline struct usb_bus *usb_get_busses(void)
63{
64	return usb_busses;
65}
66#endif
67
68#ifndef USB_CLASS_WIRELESS
69#define USB_CLASS_WIRELESS	0xe0
70#endif
71
72#ifndef USB_CLASS_APPLICATION
73#define USB_CLASS_APPLICATION	0xfe
74#endif
75
76static int get_interface_number(struct usb_device *dev)
77{
78	int c, i, a;
79
80	for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
81		struct usb_config_descriptor *config = &dev->config[c];
82
83		for (i = 0; i < config->bNumInterfaces; i++) {
84			struct usb_interface *interface = &config->interface[i];
85
86			for (a = 0; a < interface->num_altsetting; a++) {
87				struct usb_interface_descriptor *desc = &interface->altsetting[a];
88
89				if (desc->bInterfaceClass != USB_CLASS_APPLICATION)
90					continue;
91				if (desc->bInterfaceSubClass != 0x01)
92					continue;
93				if (desc->bInterfaceProtocol != 0x00)
94					continue;
95
96				return desc->bInterfaceNumber;
97			}
98		}
99	}
100
101	return -1;
102}
103
104static void print_device(struct usb_device *dev)
105{
106	printf("Bus %s Device %s: ID %04x:%04x Interface %d%s\n",
107		dev->bus->dirname, dev->filename,
108		dev->descriptor.idVendor, dev->descriptor.idProduct,
109		get_interface_number(dev),
110		dev->descriptor.bDeviceClass == USB_CLASS_APPLICATION ? " (DFU mode)" : "");
111}
112
113static struct usb_dev_handle *open_device(char *device, struct dfu_suffix *suffix)
114{
115	struct usb_bus *bus;
116	struct usb_device *dev, *dfu_dev[10];
117	struct usb_dev_handle *udev;
118	struct dfu_status status;
119	char str[8];
120	int i, intf, sel = 0, num = 0, try = 5, bus_id = -1, dev_id = -1;
121
122	printf("Scanning USB busses ... ");
123	fflush(stdout);
124
125	usb_find_busses();
126	usb_find_devices();
127
128	for (bus = usb_get_busses(); bus; bus = bus->next) {
129		if (bus_id > 0) {
130			snprintf(str, sizeof(str) - 1, "%03i", bus_id);
131			if (strcmp(str, bus->dirname))
132				continue;
133		}
134
135		for (dev = bus->devices; dev; dev = dev->next) {
136			if (bus_id > 0 && dev_id > 0) {
137				snprintf(str, sizeof(str) - 1, "%03i", dev_id);
138				if (strcmp(str, dev->filename))
139					continue;
140			}
141
142			if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
143				continue;
144
145			if (num > 9 || get_interface_number(dev) < 0)
146				continue;
147
148			dfu_dev[num++] = dev;
149		}
150	}
151
152	if (num < 1) {
153		printf("\rCan't find any DFU devices\n");
154		return NULL;
155	}
156
157	printf("\rAvailable devices with DFU support:\n\n");
158	for (i = 0; i < num; i++) {
159		printf("\t%2d) ", i + 1);
160		print_device(dfu_dev[i]);
161	}
162	printf("\n");
163
164	do {
165		printf("\rSelect device (abort with 0): ");
166		fflush(stdout);
167		memset(str, 0, sizeof(str));
168		if (!fgets(str, sizeof(str) - 1, stdin))
169			continue;
170		sel = atoi(str);
171	} while (!isdigit(str[0]) || sel < 0 || sel > num );
172
173	if (sel < 1)
174		return NULL;
175
176	sel--;
177	intf = get_interface_number(dfu_dev[sel]);
178	printf("\n");
179
180	udev = usb_open(dfu_dev[sel]);
181	if (!udev) {
182		printf("Can't open device: %s (%d)\n", strerror(errno), errno);
183		return NULL;
184	}
185
186	if (usb_claim_interface(udev, intf) < 0) {
187		printf("Can't claim interface: %s (%d)\n", strerror(errno), errno);
188		usb_close(udev);
189		return NULL;
190	}
191
192	if (dfu_get_status(udev, intf, &status) < 0) {
193		printf("Can't get status: %s (%d)\n", strerror(errno), errno);
194		goto error;
195	}
196
197	if (status.bState == DFU_STATE_ERROR) {
198		if (dfu_clear_status(udev, intf) < 0) {
199			printf("Can't clear status: %s (%d)\n", strerror(errno), errno);
200			goto error;
201		}
202		if (dfu_abort(udev, intf) < 0) {
203			printf("Can't abort previous action: %s (%d)\n", strerror(errno), errno);
204			goto error;
205		}
206		if (dfu_get_status(udev, intf, &status) < 0) {
207			printf("Can't get status: %s (%d)\n", strerror(errno), errno);
208			goto error;
209		}
210	}
211
212	if (status.bState == DFU_STATE_DFU_IDLE) {
213		if (suffix) {
214			suffix->idVendor  = cpu_to_le16(0x0000);
215			suffix->idProduct = cpu_to_le16(0x0000);
216			suffix->bcdDevice = cpu_to_le16(0x0000);
217		}
218		return udev;
219	}
220
221	if (status.bState != DFU_STATE_APP_IDLE) {
222		printf("Device is not idle, can't detach it (state %d)\n", status.bState);
223		goto error;
224	}
225
226	printf("Switching device into DFU mode ... ");
227	fflush(stdout);
228
229	if (suffix) {
230		suffix->idVendor  = cpu_to_le16(dfu_dev[sel]->descriptor.idVendor);
231		suffix->idProduct = cpu_to_le16(dfu_dev[sel]->descriptor.idProduct);
232		suffix->bcdDevice = cpu_to_le16(dfu_dev[sel]->descriptor.bcdDevice);
233	}
234
235	if (dfu_detach(udev, intf) < 0) {
236		printf("\rCan't detach device: %s (%d)\n", strerror(errno), errno);
237		goto error;
238	}
239
240	if (dfu_get_status(udev, intf, &status) < 0) {
241		printf("\rCan't get status: %s (%d)\n", strerror(errno), errno);
242		goto error;
243	}
244
245	if (status.bState != DFU_STATE_APP_DETACH) {
246		printf("\rDevice is not in detach mode, try again\n");
247		goto error;
248	}
249
250	usb_release_interface(udev, intf);
251	usb_reset(udev);
252	usb_close(udev);
253
254	bus = dfu_dev[sel]->bus;
255	num = 0;
256
257	while (num != 1 && try-- > 0) {
258		sleep(1);
259		usb_find_devices();
260
261		for (dev = bus->devices; dev; dev = dev->next) {
262			if (dev->descriptor.bDeviceClass != USB_CLASS_APPLICATION)
263				continue;
264
265			if (suffix && dev->descriptor.idVendor != le16_to_cpu(suffix->idVendor))
266				continue;
267
268			if (num > 9 || get_interface_number(dev) != 0)
269				continue;
270
271			dfu_dev[num++] = dev;
272		}
273	}
274
275	if (num != 1) {
276		printf("\rCan't identify device with DFU mode\n");
277		goto error;
278	}
279
280	printf("\r");
281
282	intf = 0;
283
284	udev = usb_open(dfu_dev[0]);
285	if (!udev) {
286		printf("Can't open device: %s (%d)\n", strerror(errno), errno);
287		return NULL;
288	}
289
290	if (usb_claim_interface(udev, intf) < 0) {
291		printf("Can't claim interface: %s (%d)\n", strerror(errno), errno);
292		usb_close(udev);
293		return NULL;
294	}
295
296	if (dfu_get_status(udev, intf, &status) < 0) {
297		printf("Can't get status: %s (%d)\n", strerror(errno), errno);
298		goto error;
299	}
300
301	if (status.bState != DFU_STATE_DFU_IDLE) {
302		printf("Device is not in DFU mode, can't use it\n");
303		goto error;
304	}
305
306	return udev;
307
308error:
309	usb_release_interface(udev, intf);
310	usb_close(udev);
311	return NULL;
312}
313
314static void usage(void);
315
316static void cmd_verify(char *device, int argc, char **argv)
317{
318	struct stat st;
319	struct dfu_suffix *suffix;
320	uint32_t crc;
321	uint16_t bcd;
322	char str[16];
323	unsigned char *buf;
324	size_t size;
325	char *filename;
326	unsigned int i, len;
327	int fd;
328
329	if (argc < 2) {
330		usage();
331		exit(1);
332	}
333
334	filename = argv[1];
335
336	if (stat(filename, &st) < 0) {
337		perror("Can't access firmware");
338		exit(1);
339	}
340
341	size = st.st_size;
342
343	if (!(buf = malloc(size))) {
344		perror("Unable to allocate file buffer");
345		exit(1);
346	}
347
348	if ((fd = open(filename, O_RDONLY)) < 0) {
349		perror("Can't open firmware");
350		free(buf);
351		exit(1);
352	}
353
354	if (read(fd, buf, size) < (ssize_t) size) {
355		perror("Can't load firmware");
356		free(buf);
357		close(fd);
358		exit(1);
359	}
360
361	printf("Filename\t%s\n", basename(filename));
362	printf("Filesize\t%zd\n", size);
363
364	crc = crc32_init();
365	for (i = 0; i < size - 4; i++)
366		crc = crc32_byte(crc, buf[i]);
367	printf("Checksum\t%08x\n", crc);
368
369	printf("\n");
370	len = buf[size - 5];
371	printf("DFU suffix\t");
372	for (i = 0; i < len; i++) {
373		printf("%02x ", buf[size - len + i]);
374	}
375	printf("\n\n");
376
377	suffix = (struct dfu_suffix *) (buf + size - DFU_SUFFIX_SIZE);
378
379	printf("idVendor\t%04x\n", le16_to_cpu(suffix->idVendor));
380	printf("idProduct\t%04x\n", le16_to_cpu(suffix->idProduct));
381	printf("bcdDevice\t%x\n", le16_to_cpu(suffix->bcdDevice));
382
383	printf("\n");
384
385	bcd = le16_to_cpu(suffix->bcdDFU);
386
387	printf("bcdDFU\t\t%x.%x\n", bcd >> 8, bcd & 0xff);
388	printf("ucDfuSignature\t%c%c%c\n", suffix->ucDfuSignature[2],
389		suffix->ucDfuSignature[1], suffix->ucDfuSignature[0]);
390	printf("bLength\t\t%d\n", suffix->bLength);
391	printf("dwCRC\t\t%08x\n", le32_to_cpu(suffix->dwCRC));
392	printf("\n");
393
394	memset(str, 0, sizeof(str));
395	memcpy(str, buf, 8);
396
397	if (!strcmp(str, "CSR-dfu1") || !strcmp(str, "CSR-dfu2")) {
398		crc = crc32_init();
399		for (i = 0; i < size - DFU_SUFFIX_SIZE; i++)
400			crc = crc32_byte(crc, buf[i]);
401
402		printf("Firmware type\t%s\n", str);
403		printf("Firmware check\t%s checksum\n", crc == 0 ? "valid" : "corrupt");
404		printf("\n");
405	}
406
407	free(buf);
408
409	close(fd);
410}
411
412static void cmd_modify(char *device, int argc, char **argv)
413{
414}
415
416static void cmd_upgrade(char *device, int argc, char **argv)
417{
418	struct usb_dev_handle *udev;
419	struct dfu_status status;
420	struct dfu_suffix suffix;
421	struct stat st;
422	char *buf;
423	size_t filesize;
424	unsigned long count, timeout = 0;
425	char *filename;
426	uint32_t crc, dwCRC;
427	unsigned int i;
428	int fd, block, len, size, sent = 0, try = 10;
429
430	if (argc < 2) {
431		usage();
432		exit(1);
433	}
434
435	filename = argv[1];
436
437	if (stat(filename, &st) < 0) {
438		perror("Can't access firmware");
439		exit(1);
440	}
441
442	filesize = st.st_size;
443
444	if (!(buf = malloc(filesize))) {
445		perror("Unable to allocate file buffer");
446		exit(1);
447	}
448
449	if ((fd = open(filename, O_RDONLY)) < 0) {
450		perror("Can't open firmware");
451		free(buf);
452		exit(1);
453	}
454
455	if (read(fd, buf, filesize) < (ssize_t) filesize) {
456		perror("Can't load firmware");
457		free(buf);
458		close(fd);
459		exit(1);
460	}
461
462	memcpy(&suffix, buf + filesize - DFU_SUFFIX_SIZE, sizeof(suffix));
463	dwCRC = le32_to_cpu(suffix.dwCRC);
464
465	printf("Filename\t%s\n", basename(filename));
466	printf("Filesize\t%zd\n", filesize);
467
468	crc = crc32_init();
469	for (i = 0; i < filesize - 4; i++)
470		crc = crc32_byte(crc, buf[i]);
471
472	printf("Checksum\t%08x (%s)\n", crc,
473			crc == dwCRC ? "valid" : "corrupt");
474
475	if (crc != dwCRC) {
476		free(buf);
477		close(fd);
478		exit(1);
479	}
480
481	printf("\n");
482
483	udev = open_device(device, &suffix);
484	if (!udev)
485		exit(1);
486
487	printf("\r" "          " "          " "          " "          " "          ");
488	printf("\rFirmware download ... ");
489	fflush(stdout);
490
491	count = filesize - DFU_SUFFIX_SIZE;
492	block = 0;
493
494	while (count) {
495		size = (count > 1023) ? 1023 : count;
496
497		if (dfu_get_status(udev, 0, &status) < 0) {
498			if (try-- > 0) {
499				sleep(1);
500				continue;
501			}
502			printf("\rCan't get status: %s (%d)\n", strerror(errno), errno);
503			goto done;
504		}
505
506		if (status.bStatus != DFU_OK) {
507			if (try-- > 0) {
508				dfu_clear_status(udev, 0);
509				sleep(1);
510				continue;
511			}
512			printf("\rFirmware download ... aborting (status %d state %d)\n",
513						status.bStatus, status.bState);
514			goto done;
515		}
516
517		if (status.bState != DFU_STATE_DFU_IDLE &&
518				status.bState != DFU_STATE_DFU_DNLOAD_IDLE) {
519			sleep(1);
520			continue;
521		}
522
523		timeout = (status.bwPollTimeout[2] << 16) |
524				(status.bwPollTimeout[1] << 8) |
525					status.bwPollTimeout[0];
526
527		usleep(timeout * 1000);
528
529		len = dfu_download(udev, 0, block, buf + sent, size);
530		if (len < 0) {
531			if (try-- > 0) {
532				sleep(1);
533				continue;
534			}
535			printf("\rCan't upload next block: %s (%d)\n", strerror(errno), errno);
536			goto done;
537		}
538
539		printf("\rFirmware download ... %d bytes ", block * 1023 + len);
540		fflush(stdout);
541
542		sent  += len;
543		count -= len;
544		block++;
545	}
546
547	printf("\r" "          " "          " "          " "          " "          ");
548	printf("\rFinishing firmware download ... ");
549	fflush(stdout);
550
551	sleep(1);
552
553	if (dfu_get_status(udev, 0, &status) < 0) {
554		printf("\rCan't get status: %s (%d)\n", strerror(errno), errno);
555		goto done;
556	}
557
558	timeout = (status.bwPollTimeout[2] << 16) |
559			(status.bwPollTimeout[1] << 8) |
560				status.bwPollTimeout[0];
561
562	usleep(timeout * 1000);
563
564	if (count == 0) {
565		len = dfu_download(udev, 0, block, NULL, 0);
566		if (len < 0) {
567			printf("\rCan't send final block: %s (%d)\n", strerror(errno), errno);
568			goto done;
569		}
570	}
571
572	printf("\r" "          " "          " "          " "          " "          ");
573	printf("\rWaiting for device ... ");
574	fflush(stdout);
575
576	sleep(10);
577
578	printf("\n");
579
580done:
581	free(buf);
582	close(fd);
583
584	usb_release_interface(udev, 0);
585	usb_reset(udev);
586	usb_close(udev);
587}
588
589static void cmd_archive(char *device, int argc, char **argv)
590{
591	struct usb_dev_handle *udev;
592	struct dfu_status status;
593	struct dfu_suffix suffix;
594	char buf[2048];
595	unsigned long timeout = 0;
596	char *filename;
597	uint32_t crc;
598	int fd, i, n, len, try = 8;
599
600	if (argc < 2) {
601		usage();
602		exit(1);
603	}
604
605	filename = argv[1];
606
607	udev = open_device(device, &suffix);
608	if (!udev)
609		exit(1);
610
611	fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
612	if (fd < 0) {
613		printf("Can't open firmware file: %s (%d)\n", strerror(errno), errno);
614		goto done;
615	}
616
617	printf("\r" "          " "          " "          " "          " "          ");
618	printf("\rFirmware upload ... ");
619	fflush(stdout);
620
621	crc = crc32_init();
622	n = 0;
623	while (1) {
624		if (dfu_get_status(udev, 0, &status) < 0) {
625			if (try-- > 0) {
626				sleep(1);
627				continue;
628			}
629			printf("\rCan't get status: %s (%d)\n", strerror(errno), errno);
630			goto done;
631		}
632
633		if (status.bStatus != DFU_OK) {
634			if (try-- > 0) {
635				dfu_clear_status(udev, 0);
636				sleep(1);
637				continue;
638			}
639			printf("\rFirmware upload ... aborting (status %d state %d)\n",
640						status.bStatus, status.bState);
641			goto done;
642		}
643
644		if (status.bState != DFU_STATE_DFU_IDLE &&
645				status.bState != DFU_STATE_UPLOAD_IDLE) {
646			sleep(1);
647			continue;
648		}
649
650		timeout = (status.bwPollTimeout[2] << 16) |
651				(status.bwPollTimeout[1] << 8) |
652					status.bwPollTimeout[0];
653
654		usleep(timeout * 1000);
655
656		len = dfu_upload(udev, 0, n, buf, 1023);
657		if (len < 0) {
658			if (try-- > 0) {
659				sleep(1);
660				continue;
661			}
662			printf("\rCan't upload next block: %s (%d)\n", strerror(errno), errno);
663			goto done;
664		}
665
666		printf("\rFirmware upload ... %d bytes ", n * 1023 + len);
667		fflush(stdout);
668
669		for (i = 0; i < len; i++)
670			crc = crc32_byte(crc, buf[i]);
671
672		if (len > 0) {
673			if (write(fd, buf, len) < 0) {
674				printf("\rCan't write next block: %s (%d)\n", strerror(errno), errno);
675				goto done;
676			}
677		}
678
679		n++;
680		if (len != 1023)
681			break;
682	}
683	printf("\n");
684
685	suffix.bcdDFU = cpu_to_le16(0x0100);
686	suffix.ucDfuSignature[0] = 'U';
687	suffix.ucDfuSignature[1] = 'F';
688	suffix.ucDfuSignature[2] = 'D';
689	suffix.bLength = DFU_SUFFIX_SIZE;
690
691	memcpy(buf, &suffix, DFU_SUFFIX_SIZE);
692	for (i = 0; i < DFU_SUFFIX_SIZE - 4; i++)
693		crc = crc32_byte(crc, buf[i]);
694
695	suffix.dwCRC = cpu_to_le32(crc);
696
697	if (write(fd, &suffix, DFU_SUFFIX_SIZE) < 0)
698		printf("Can't write suffix block: %s (%d)\n", strerror(errno), errno);
699
700done:
701	close(fd);
702
703	usb_release_interface(udev, 0);
704	usb_reset(udev);
705	usb_close(udev);
706}
707
708struct {
709	char *cmd;
710	char *alt;
711	void (*func)(char *device, int argc, char **argv);
712	char *opt;
713	char *doc;
714} command[] = {
715	{ "verify",  "check",    cmd_verify,  "<dfu-file>", "Check firmware file"         },
716	{ "modify",  "change",   cmd_modify,  "<dfu-file>", "Change firmware attributes"  },
717	{ "upgrade", "download", cmd_upgrade, "<dfu-file>", "Download a new firmware"     },
718	{ "archive", "upload",   cmd_archive, "<dfu-file>", "Upload the current firmware" },
719	{ NULL, NULL, NULL, 0, 0 }
720};
721
722static void usage(void)
723{
724	int i;
725
726	printf("dfutool - Device Firmware Upgrade utility ver %s\n\n", VERSION);
727
728	printf("Usage:\n"
729		"\tdfutool [options] <command>\n"
730		"\n");
731
732	printf("Options:\n"
733		"\t-d, --device <device>   USB device\n"
734		"\t-h, --help              Display help\n"
735		"\n");
736
737	printf("Commands:\n");
738	for (i = 0; command[i].cmd; i++)
739		printf("\t%-8s %-10s\t%s\n", command[i].cmd,
740		command[i].opt ? command[i].opt : " ",
741		command[i].doc);
742	printf("\n");
743}
744
745static struct option main_options[] = {
746	{ "help",	0, 0, 'h' },
747	{ "device",	1, 0, 'd' },
748	{ 0, 0, 0, 0 }
749};
750
751int main(int argc, char *argv[])
752{
753	char *device = NULL;
754	int i, opt;
755
756	while ((opt = getopt_long(argc, argv, "+d:h", main_options, NULL)) != -1) {
757		switch(opt) {
758		case 'd':
759			device = strdup(optarg);
760			break;
761
762		case 'h':
763			usage();
764			exit(0);
765
766		default:
767			exit(0);
768		}
769	}
770
771	argc -= optind;
772	argv += optind;
773	optind = 0;
774
775	if (argc < 1) {
776		usage();
777		exit(1);
778	}
779
780	usb_init();
781
782	for (i = 0; command[i].cmd; i++) {
783		if (strcmp(command[i].cmd, argv[0]) && strcmp(command[i].alt, argv[0]))
784			continue;
785		command[i].func(device, argc, argv);
786		exit(0);
787	}
788
789	usage();
790	exit(1);
791}
792