xref: /aosp_15_r20/external/libusb/android/examples/unrooted_android.c (revision 86b64dcb59b3a0b37502ecd56e119234366a6f7e)
1 /*
2  *  libusb example program for reading out USB descriptors on unrooted Android
3  *  (based on testlibusb.c)
4  *
5  *  Copyright 2020-2021 Peter Stoiber
6  *
7  *  This library is free software; you can redistribute it and/or
8  *  modify it under the terms of the GNU Lesser General Public
9  *  License as published by the Free Software Foundation; either
10  *  version 2.1 of the License, or (at your option) any later version.
11  *
12  *  This library is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  Lesser General Public License for more details.
16  *
17  *  You should have received a copy of the GNU Lesser General Public
18  *  License along with this library; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20  *
21  *  Please contact the author if you need another license.
22  *  This Repository is provided "as is", without warranties of any kind.
23 */
24 
25 /*
26  * This example creates a shared object which can be accessed over JNA or JNI from Java or Kotlin in Android.
27  * Hint: If you are using Android Studio, set the "Debug type" to "Java Only" to receive debug messages.
28  */
29 
30 /*
31  * Usage:
32  * First, you have to connect your USB device from the Java side.
33  * Use the android.hardware.usb class to find the USB device, claim the interfaces, and open the usb_device_connection
34  * Obtain the native File Descriptor --> usb_device_connection.getFileDescriptor()
35  * Pass the received int value to the unrooted_usb_description method of this code (over JNA)
36  */
37 
38 /*
39  * libusb can only be included in Android projects using NDK for now. (CMake is not supported at the moment)
40  * Clone the libusb git repo into your Android project and include the Android.mk file in your build.gradle.
41  */
42 
43 /*
44  Example JNA Approach:
45     public interface unrooted_sample extends Library {
46         public static final unrooted_sample INSTANCE = Native.load("unrooted_android", unrooted_sample.class);
47         public int unrooted_usb_description (int fileDescriptor);
48     }
49     unrooted_sample.INSTANCE.unrooted_usb_description( usbDeviceConnection.getFileDescriptor());
50  */
51 
52 #include <jni.h>
53 #include <string.h>
54 #include "unrooted_android.h"
55 #include "libusb.h"
56 #include <android/log.h>
57 #define  LOG_TAG    "LibUsb"
58 #define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
59 
60 int verbose = 0;
61 
print_endpoint_comp(const struct libusb_ss_endpoint_companion_descriptor * ep_comp)62 static void print_endpoint_comp(const struct libusb_ss_endpoint_companion_descriptor *ep_comp)
63 {
64     LOGD("      USB 3.0 Endpoint Companion:\n");
65     LOGD("        bMaxBurst:           %u\n", ep_comp->bMaxBurst);
66     LOGD("        bmAttributes:        %02xh\n", ep_comp->bmAttributes);
67     LOGD("        wBytesPerInterval:   %u\n", ep_comp->wBytesPerInterval);
68 }
69 
print_endpoint(const struct libusb_endpoint_descriptor * endpoint)70 static void print_endpoint(const struct libusb_endpoint_descriptor *endpoint)
71 {
72     int i, ret;
73 
74     LOGD("      Endpoint:\n");
75     LOGD("        bEndpointAddress:    %02xh\n", endpoint->bEndpointAddress);
76     LOGD("        bmAttributes:        %02xh\n", endpoint->bmAttributes);
77     LOGD("        wMaxPacketSize:      %u\n", endpoint->wMaxPacketSize);
78     LOGD("        bInterval:           %u\n", endpoint->bInterval);
79     LOGD("        bRefresh:            %u\n", endpoint->bRefresh);
80     LOGD("        bSynchAddress:       %u\n", endpoint->bSynchAddress);
81 
82     for (i = 0; i < endpoint->extra_length;) {
83         if (LIBUSB_DT_SS_ENDPOINT_COMPANION == endpoint->extra[i + 1]) {
84             struct libusb_ss_endpoint_companion_descriptor *ep_comp;
85 
86             ret = libusb_get_ss_endpoint_companion_descriptor(NULL, endpoint, &ep_comp);
87             if (LIBUSB_SUCCESS != ret)
88                 continue;
89 
90             print_endpoint_comp(ep_comp);
91 
92             libusb_free_ss_endpoint_companion_descriptor(ep_comp);
93         }
94 
95         i += endpoint->extra[i];
96     }
97 }
98 
print_altsetting(const struct libusb_interface_descriptor * interface)99 static void print_altsetting(const struct libusb_interface_descriptor *interface)
100 {
101     uint8_t i;
102 
103     LOGD("    Interface:\n");
104     LOGD("      bInterfaceNumber:      %u\n", interface->bInterfaceNumber);
105     LOGD("      bAlternateSetting:     %u\n", interface->bAlternateSetting);
106     LOGD("      bNumEndpoints:         %u\n", interface->bNumEndpoints);
107     LOGD("      bInterfaceClass:       %u\n", interface->bInterfaceClass);
108     LOGD("      bInterfaceSubClass:    %u\n", interface->bInterfaceSubClass);
109     LOGD("      bInterfaceProtocol:    %u\n", interface->bInterfaceProtocol);
110     LOGD("      iInterface:            %u\n", interface->iInterface);
111 
112     for (i = 0; i < interface->bNumEndpoints; i++)
113         print_endpoint(&interface->endpoint[i]);
114 }
115 
print_2_0_ext_cap(struct libusb_usb_2_0_extension_descriptor * usb_2_0_ext_cap)116 static void print_2_0_ext_cap(struct libusb_usb_2_0_extension_descriptor *usb_2_0_ext_cap)
117 {
118     LOGD("    USB 2.0 Extension Capabilities:\n");
119     LOGD("      bDevCapabilityType:    %u\n", usb_2_0_ext_cap->bDevCapabilityType);
120     LOGD("      bmAttributes:          %08xh\n", usb_2_0_ext_cap->bmAttributes);
121 }
122 
print_ss_usb_cap(struct libusb_ss_usb_device_capability_descriptor * ss_usb_cap)123 static void print_ss_usb_cap(struct libusb_ss_usb_device_capability_descriptor *ss_usb_cap)
124 {
125     LOGD("    USB 3.0 Capabilities:\n");
126     LOGD("      bDevCapabilityType:    %u\n", ss_usb_cap->bDevCapabilityType);
127     LOGD("      bmAttributes:          %02xh\n", ss_usb_cap->bmAttributes);
128     LOGD("      wSpeedSupported:       %u\n", ss_usb_cap->wSpeedSupported);
129     LOGD("      bFunctionalitySupport: %u\n", ss_usb_cap->bFunctionalitySupport);
130     LOGD("      bU1devExitLat:         %u\n", ss_usb_cap->bU1DevExitLat);
131     LOGD("      bU2devExitLat:         %u\n", ss_usb_cap->bU2DevExitLat);
132 }
133 
print_bos(libusb_device_handle * handle)134 static void print_bos(libusb_device_handle *handle)
135 {
136     struct libusb_bos_descriptor *bos;
137     uint8_t i;
138     int ret;
139 
140     ret = libusb_get_bos_descriptor(handle, &bos);
141     if (ret < 0)
142         return;
143 
144     LOGD("  Binary Object Store (BOS):\n");
145     LOGD("    wTotalLength:            %u\n", bos->wTotalLength);
146     LOGD("    bNumDeviceCaps:          %u\n", bos->bNumDeviceCaps);
147 
148     for (i = 0; i < bos->bNumDeviceCaps; i++) {
149         struct libusb_bos_dev_capability_descriptor *dev_cap = bos->dev_capability[i];
150 
151         if (dev_cap->bDevCapabilityType == LIBUSB_BT_USB_2_0_EXTENSION) {
152             struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension;
153 
154             ret = libusb_get_usb_2_0_extension_descriptor(NULL, dev_cap, &usb_2_0_extension);
155             if (ret < 0)
156                 return;
157 
158             print_2_0_ext_cap(usb_2_0_extension);
159             libusb_free_usb_2_0_extension_descriptor(usb_2_0_extension);
160         } else if (dev_cap->bDevCapabilityType == LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) {
161             struct libusb_ss_usb_device_capability_descriptor *ss_dev_cap;
162 
163             ret = libusb_get_ss_usb_device_capability_descriptor(NULL, dev_cap, &ss_dev_cap);
164             if (ret < 0)
165                 return;
166 
167             print_ss_usb_cap(ss_dev_cap);
168             libusb_free_ss_usb_device_capability_descriptor(ss_dev_cap);
169         }
170     }
171 
172     libusb_free_bos_descriptor(bos);
173 }
174 
print_interface(const struct libusb_interface * interface)175 static void print_interface(const struct libusb_interface *interface)
176 {
177     int i;
178 
179     for (i = 0; i < interface->num_altsetting; i++)
180         print_altsetting(&interface->altsetting[i]);
181 }
182 
print_configuration(struct libusb_config_descriptor * config)183 static void print_configuration(struct libusb_config_descriptor *config)
184 {
185     uint8_t i;
186 
187     LOGD("  Configuration:\n");
188     LOGD("    wTotalLength:            %u\n", config->wTotalLength);
189     LOGD("    bNumInterfaces:          %u\n", config->bNumInterfaces);
190     LOGD("    bConfigurationValue:     %u\n", config->bConfigurationValue);
191     LOGD("    iConfiguration:          %u\n", config->iConfiguration);
192     LOGD("    bmAttributes:            %02xh\n", config->bmAttributes);
193     LOGD("    MaxPower:                %u\n", config->MaxPower);
194 
195     for (i = 0; i < config->bNumInterfaces; i++)
196         print_interface(&config->interface[i]);
197 }
198 
print_device(libusb_device * dev,libusb_device_handle * handle)199 static void print_device(libusb_device *dev, libusb_device_handle *handle)
200 {
201     struct libusb_device_descriptor desc;
202     unsigned char string[256];
203     const char *speed;
204     int ret;
205     uint8_t i;
206 
207     switch (libusb_get_device_speed(dev)) {
208         case LIBUSB_SPEED_LOW:		speed = "1.5M"; break;
209         case LIBUSB_SPEED_FULL:		speed = "12M"; break;
210         case LIBUSB_SPEED_HIGH:		speed = "480M"; break;
211         case LIBUSB_SPEED_SUPER:	speed = "5G"; break;
212         case LIBUSB_SPEED_SUPER_PLUS:	speed = "10G"; break;
213         case LIBUSB_SPEED_SUPER_PLUS_X2:	speed = "20G"; break;
214         default:			speed = "Unknown";
215     }
216 
217     ret = libusb_get_device_descriptor(dev, &desc);
218     if (ret < 0) {
219         LOGD("failed to get device descriptor");
220         return;
221     }
222 
223     LOGD("Dev (bus %u, device %u): %04X - %04X speed: %s\n",
224            libusb_get_bus_number(dev), libusb_get_device_address(dev),
225            desc.idVendor, desc.idProduct, speed);
226 
227     if (!handle)
228         libusb_open(dev, &handle);
229 
230     if (handle) {
231         if (desc.iManufacturer) {
232             ret = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, string, sizeof(string));
233             if (ret > 0)
234                 LOGD("  Manufacturer:              %s\n", (char *)string);
235         }
236 
237         if (desc.iProduct) {
238             ret = libusb_get_string_descriptor_ascii(handle, desc.iProduct, string, sizeof(string));
239             if (ret > 0)
240                 LOGD("  Product:                   %s\n", (char *)string);
241         }
242 
243         if (desc.iSerialNumber && verbose) {
244             ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, string, sizeof(string));
245             if (ret > 0)
246                 LOGD("  Serial Number:             %s\n", (char *)string);
247         }
248     }
249 
250     if (verbose) {
251         for (i = 0; i < desc.bNumConfigurations; i++) {
252             struct libusb_config_descriptor *config;
253 
254             ret = libusb_get_config_descriptor(dev, i, &config);
255             if (LIBUSB_SUCCESS != ret) {
256                 LOGD("  Couldn't retrieve descriptors\n");
257                 continue;
258             }
259 
260             print_configuration(config);
261 
262             libusb_free_config_descriptor(config);
263         }
264 
265         if (handle && desc.bcdUSB >= 0x0201)
266             print_bos(handle);
267     }
268 
269     if (handle)
270         libusb_close(handle);
271 }
272 
273 
274 /* fileDescriptor = the native file descriptor obtained in Java and transferred to native over JNA, for example */
unrooted_usb_description(int fileDescriptor)275 int unrooted_usb_description(int fileDescriptor)
276 {
277     libusb_context *ctx = NULL;
278     libusb_device_handle *devh = NULL;
279     int r = 0;
280     verbose = 1;
281     r = libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY, NULL);
282     if (r != LIBUSB_SUCCESS) {
283         LOGD("libusb_set_option failed: %d\n", r);
284         return -1;
285     }
286     r = libusb_init(&ctx);
287     if (r < 0) {
288         LOGD("libusb_init failed: %d\n", r);
289         return r;
290     }
291     r = libusb_wrap_sys_device(ctx, (intptr_t)fileDescriptor, &devh);
292     if (r < 0) {
293         LOGD("libusb_wrap_sys_device failed: %d\n", r);
294         return r;
295     } else if (devh == NULL) {
296         LOGD("libusb_wrap_sys_device returned invalid handle\n");
297         return r;
298     }
299     print_device(libusb_get_device(devh), devh);
300     return r;
301 }
302