-
Notifications
You must be signed in to change notification settings - Fork 21
/
usb_context.c
138 lines (113 loc) · 2.34 KB
/
usb_context.c
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
#include "updater.h"
int open_usb(int vid, int pid, int indf)
{
int rc;
rc = libusb_init(&ctx);
if(rc < 0)
return rc;
devintf = indf;
printf(">>> Trying to open VID:%04x PID:%04x...\n", vid&0xffff, pid&0xffff);
devh = libusb_open_device_with_vid_pid(ctx, vid, pid);
if(devh == NULL) {
printf(">>> Device not found\n");
return -1;
}
rc = libusb_kernel_driver_active(devh, indf);
if (rc > 0) {
printf(">>> Kernel Driver Active\n");
rc = libusb_detach_kernel_driver(devh, indf);
if (rc < 0) {
printf(">>> libusb_detach_kernel_driver: %d\n", rc);
goto finish;
}
}
rc = libusb_claim_interface(devh, indf);
if(rc < 0) {
printf(">>> libusb_claim_interface: %d\n", rc);
goto finish;
}
finish:
if (rc < 0) {
close_usb();
}
return rc;
}
void close_usb()
{
if (devh) {
printf(">>> release interface\r\n");
libusb_release_interface(devh, devintf);
libusb_close(devh);
libusb_exit(ctx);
devh = NULL;
}
}
int open_user_mode()
{
int rc = open_usb(0x258a, 0x001e, 1);
if (rc < 0) {
rc = open_usb(0x258a, 0x001f, 1);
}
if (rc < 0) {
rc = open_usb(0x258a, 0x000d, 1);
}
return rc;
}
int open_touchpad_mode()
{
int rc = open_usb(0x258a, 0x001f, 1);
if (rc < 0) {
rc = open_usb(0x258a, 0x000d, 1);
}
return rc;
}
int open_boot_mode()
{
return open_usb(0x0603, 0x1020, 0);
}
int switch_to_boot_mode()
{
int rc, try;
printf("[*] Opening in user mode...\n");
for (try = 0; try < 3; try++) {
rc = open_user_mode();
if (rc >= 0) {
break;
}
usleep(500*1000);
}
if (try == 3) {
printf(">>> Failed to open in user mode\n");
goto finish;
}
printf("[*] Sending command to switch to boot mode...\n");
unsigned char dataOut[6] = {
0x5, 0x75
};
rc = libusb_control_transfer(devh, 0x21, 0x09, 0x0305, 1,
dataOut, sizeof(dataOut), 1000);
if (rc < 0) {
printf("failed to send switch command\n");
goto finish;
}
printf("[*] Command send\n");
finish:
close_usb();
return rc;
}
int reset_device()
{
int rc;
unsigned char data[6] = {
0x05, 0x55, 0x55, 0x55, 0x55, 0x55
};
rc = libusb_control_transfer(devh, 0x21, 0x09, 0x0305, 0, data, sizeof(data), 100);
if (rc < 0) {
return rc;
}
rc = libusb_reset_device(devh);
if (rc < 0) {
return rc;
}
return 0;
}