blob: d8f15cd6c58c652125f7fa94a8c61c55e77c0400 [file] [log] [blame]
Mike Lockwood30ff2c72010-05-09 16:23:47 -04001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Philip P. Moltmann36952852016-10-17 16:57:43 -070017#ifndef _GNU_SOURCE
18#define _GNU_SOURCE
19#endif
20
Elliott Hughesb8895392022-01-19 10:26:45 -080021#include <usbhost/usbhost.h>
Mike Lockwoode15af092010-06-10 10:20:49 -040022
Elliott Hughesb8895392022-01-19 10:26:45 -080023#include "usbhost_private.h"
Mike Lockwoode15af092010-06-10 10:20:49 -040024
Mike Lockwood30ff2c72010-05-09 16:23:47 -040025#include <stdio.h>
26#include <stdlib.h>
27#include <unistd.h>
28#include <string.h>
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020029#include <stddef.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040030
31#include <sys/ioctl.h>
32#include <sys/types.h>
33#include <sys/time.h>
34#include <sys/inotify.h>
35#include <dirent.h>
36#include <fcntl.h>
37#include <errno.h>
38#include <ctype.h>
Philip P. Moltmann36952852016-10-17 16:57:43 -070039#include <poll.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040040
41#include <linux/usbdevice_fs.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040042
Elliott Hughesb8895392022-01-19 10:26:45 -080043// #define DEBUG 1
44#if defined(DEBUG)
45#if defined(__BIONIC__)
46#define D ALOGD
47#else
48#define D printf
49#endif
50#else
51#define D(...)
52#endif
Mike Lockwood30ff2c72010-05-09 16:23:47 -040053
Benoit Gobyf4de0782012-08-01 18:54:02 -070054#define DEV_DIR "/dev"
Ziv Hendela306ced2013-08-07 19:29:17 +030055#define DEV_BUS_DIR DEV_DIR "/bus"
56#define USB_FS_DIR DEV_BUS_DIR "/usb"
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020057#define USB_FS_ID_SCANNER USB_FS_DIR "/%d/%d"
58#define USB_FS_ID_FORMAT USB_FS_DIR "/%03d/%03d"
Mike Lockwood30ff2c72010-05-09 16:23:47 -040059
Mike Lockwood0dd1aab2015-06-18 13:38:31 -070060// Some devices fail to send string descriptors if we attempt reading > 255 bytes
61#define MAX_STRING_DESCRIPTOR_LENGTH 255
62
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020063#define MAX_USBFS_WD_COUNT 10
64
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040065struct usb_host_context {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020066 int fd;
67 usb_device_added_cb cb_added;
68 usb_device_removed_cb cb_removed;
69 void *data;
70 int wds[MAX_USBFS_WD_COUNT];
71 int wdd;
Ziv Hendela306ced2013-08-07 19:29:17 +030072 int wddbus;
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040073};
74
Mike Lockwood30ff2c72010-05-09 16:23:47 -040075struct usb_device {
76 char dev_name[64];
Paul McLeanbaea1bd2017-11-06 10:22:51 -070077 unsigned char desc[MAX_DESCRIPTORS_LENGTH];
Mike Lockwood30ff2c72010-05-09 16:23:47 -040078 int desc_length;
79 int fd;
80 int writeable;
81};
82
Mike Lockwood30ff2c72010-05-09 16:23:47 -040083static inline int badname(const char *name)
84{
85 while(*name) {
86 if(!isdigit(*name++)) return 1;
87 }
88 return 0;
89}
90
Benoit Goby6cc883c2012-07-31 19:22:06 -070091static int find_existing_devices_bus(char *busname,
92 usb_device_added_cb added_cb,
93 void *client_data)
94{
95 char devname[32];
96 DIR *devdir;
97 struct dirent *de;
98 int done = 0;
99
100 devdir = opendir(busname);
101 if(devdir == 0) return 0;
102
103 while ((de = readdir(devdir)) && !done) {
104 if(badname(de->d_name)) continue;
105
106 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
107 done = added_cb(devname, client_data);
108 } // end of devdir while
109 closedir(devdir);
110
111 return done;
112}
113
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400114/* returns true if one of the callbacks indicates we are done */
115static int find_existing_devices(usb_device_added_cb added_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400116 void *client_data)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400117{
Benoit Goby6cc883c2012-07-31 19:22:06 -0700118 char busname[32];
119 DIR *busdir;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400120 struct dirent *de;
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400121 int done = 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400122
123 busdir = opendir(USB_FS_DIR);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700124 if(busdir == 0) return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400125
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400126 while ((de = readdir(busdir)) != 0 && !done) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400127 if(badname(de->d_name)) continue;
128
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200129 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
Benoit Goby6cc883c2012-07-31 19:22:06 -0700130 done = find_existing_devices_bus(busname, added_cb,
131 client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200132 } //end of busdir while
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400133 closedir(busdir);
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400134
135 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400136}
137
Benoit Gobyf4de0782012-08-01 18:54:02 -0700138static void watch_existing_subdirs(struct usb_host_context *context,
139 int *wds, int wd_count)
140{
141 char path[100];
142 int i, ret;
143
144 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
145 if (wds[0] < 0)
146 return;
147
148 /* watch existing subdirectories of USB_FS_DIR */
149 for (i = 1; i < wd_count; i++) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200150 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700151 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
152 if (ret >= 0)
153 wds[i] = ret;
154 }
155}
156
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400157struct usb_host_context *usb_host_init()
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400158{
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400159 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
160 if (!context) {
161 fprintf(stderr, "out of memory in usb_host_context\n");
162 return NULL;
163 }
164 context->fd = inotify_init();
165 if (context->fd < 0) {
166 fprintf(stderr, "inotify_init failed\n");
167 free(context);
168 return NULL;
169 }
170 return context;
171}
172
173void usb_host_cleanup(struct usb_host_context *context)
174{
175 close(context->fd);
176 free(context);
177}
178
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200179int usb_host_get_fd(struct usb_host_context *context)
180{
181 return context->fd;
182} /* usb_host_get_fd() */
183
184int usb_host_load(struct usb_host_context *context,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400185 usb_device_added_cb added_cb,
186 usb_device_removed_cb removed_cb,
Mike Lockwooda8055192010-07-19 20:15:15 -0400187 usb_discovery_done_cb discovery_done_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400188 void *client_data)
189{
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200190 int done = 0;
191 int i;
192
193 context->cb_added = added_cb;
194 context->cb_removed = removed_cb;
195 context->data = client_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400196
197 D("Created device discovery thread\n");
198
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400199 /* watch for files added and deleted within USB_FS_DIR */
Ziv Hendela306ced2013-08-07 19:29:17 +0300200 context->wddbus = -1;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200201 for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
202 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700203
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400204 /* watch the root for new subdirectories */
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200205 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
206 if (context->wdd < 0) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400207 fprintf(stderr, "inotify_add_watch failed\n");
Mike Lockwoode8849d12010-07-20 16:31:42 -0400208 if (discovery_done_cb)
209 discovery_done_cb(client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200210 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400211 }
212
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200213 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400214
215 /* check for existing devices first, after we have inotify set up */
Benoit Goby6cc883c2012-07-31 19:22:06 -0700216 done = find_existing_devices(added_cb, client_data);
Mike Lockwooda8055192010-07-19 20:15:15 -0400217 if (discovery_done_cb)
218 done |= discovery_done_cb(client_data);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400219
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200220 return done;
221} /* usb_host_load() */
222
223int usb_host_read_event(struct usb_host_context *context)
224{
225 struct inotify_event* event;
226 char event_buf[512];
227 char path[100];
228 int i, ret, done = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200229 int offset = 0;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200230 int wd;
231
232 ret = read(context->fd, event_buf, sizeof(event_buf));
233 if (ret >= (int)sizeof(struct inotify_event)) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300234 while (offset < ret && !done) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200235 event = (struct inotify_event*)&event_buf[offset];
236 done = 0;
237 wd = event->wd;
238 if (wd == context->wdd) {
239 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300240 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
241 if (context->wddbus < 0) {
242 done = 1;
243 } else {
244 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
245 done = find_existing_devices(context->cb_added, context->data);
246 }
247 }
248 } else if (wd == context->wddbus) {
249 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200250 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
251 done = find_existing_devices(context->cb_added, context->data);
Ziv Hendela306ced2013-08-07 19:29:17 +0300252 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200253 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
254 if (context->wds[i] >= 0) {
255 inotify_rm_watch(context->fd, context->wds[i]);
256 context->wds[i] = -1;
257 }
258 }
259 }
260 } else if (wd == context->wds[0]) {
261 i = atoi(event->name);
262 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
263 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
264 "new" : "gone", path, i);
265 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800266 int local_ret = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200267 if (event->mask & IN_CREATE) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800268 local_ret = inotify_add_watch(context->fd, path,
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200269 IN_CREATE | IN_DELETE);
Bo Huang3c1d7b32014-01-21 14:25:22 +0800270 if (local_ret >= 0)
271 context->wds[i] = local_ret;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200272 done = find_existing_devices_bus(path, context->cb_added,
273 context->data);
274 } else if (event->mask & IN_DELETE) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200275 inotify_rm_watch(context->fd, context->wds[i]);
276 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700277 }
278 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200279 } else {
280 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
281 if (wd == context->wds[i]) {
282 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
283 if (event->mask == IN_CREATE) {
284 D("new device %s\n", path);
285 done = context->cb_added(path, context->data);
286 } else if (event->mask == IN_DELETE) {
287 D("gone device %s\n", path);
288 done = context->cb_removed(path, context->data);
289 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400290 }
291 }
292 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200293
294 offset += sizeof(struct inotify_event) + event->len;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400295 }
296 }
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200297
298 return done;
299} /* usb_host_read_event() */
300
301void usb_host_run(struct usb_host_context *context,
302 usb_device_added_cb added_cb,
303 usb_device_removed_cb removed_cb,
304 usb_discovery_done_cb discovery_done_cb,
305 void *client_data)
306{
307 int done;
308
309 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
310
311 while (!done) {
312
313 done = usb_host_read_event(context);
314 }
315} /* usb_host_run() */
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400316
317struct usb_device *usb_device_open(const char *dev_name)
318{
Andrew Chant3af9e402017-11-01 17:32:35 -0700319 int fd, attempts, writeable = 1;
320 const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
321 const int64_t MAX_ATTEMPTS = 10; /* 1s */
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800322 D("usb_device_open %s\n", dev_name);
323
Andrew Chant3af9e402017-11-01 17:32:35 -0700324 /* Hack around waiting for permissions to be set on the USB device node.
325 * Should really be a timeout instead of attempt count, and should REALLY
326 * be triggered by the perm change via inotify rather than polling.
327 */
328 for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
329 if (access(dev_name, R_OK | W_OK) == 0) {
330 writeable = 1;
331 break;
332 } else {
333 if (access(dev_name, R_OK) == 0) {
334 /* double check that write permission didn't just come along too! */
335 writeable = (access(dev_name, R_OK | W_OK) == 0);
336 break;
337 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400338 }
Andrew Chant3af9e402017-11-01 17:32:35 -0700339 /* not writeable or readable - sleep and try again. */
340 D("usb_device_open no access sleeping\n");
341 usleep(SLEEP_BETWEEN_ATTEMPTS_US);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400342 }
343
Andrew Chant3af9e402017-11-01 17:32:35 -0700344 if (writeable) {
345 fd = open(dev_name, O_RDWR);
346 } else {
347 fd = open(dev_name, O_RDONLY);
348 }
349 D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
350 if (fd < 0) return NULL;
351
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800352 struct usb_device* result = usb_device_new(dev_name, fd);
353 if (result)
354 result->writeable = writeable;
355 return result;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400356}
357
358void usb_device_close(struct usb_device *device)
359{
360 close(device->fd);
361 free(device);
362}
363
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800364struct usb_device *usb_device_new(const char *dev_name, int fd)
365{
366 struct usb_device *device = calloc(1, sizeof(struct usb_device));
367 int length;
368
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800369 D("usb_device_new %s fd: %d\n", dev_name, fd);
370
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800371 if (lseek(fd, 0, SEEK_SET) != 0)
372 goto failed;
373 length = read(fd, device->desc, sizeof(device->desc));
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800374 D("usb_device_new read returned %d errno %d\n", length, errno);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800375 if (length < 0)
376 goto failed;
377
Mike Lockwood93aff722010-12-15 12:58:04 -0800378 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800379 device->fd = fd;
380 device->desc_length = length;
381 // assume we are writeable, since usb_device_get_fd will only return writeable fds
382 device->writeable = 1;
383 return device;
384
385failed:
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700386 // TODO It would be more appropriate to have callers do this
387 // since this function doesn't "own" this file descriptor.
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800388 close(fd);
389 free(device);
390 return NULL;
391}
392
393static int usb_device_reopen_writeable(struct usb_device *device)
394{
395 if (device->writeable)
396 return 1;
397
398 int fd = open(device->dev_name, O_RDWR);
399 if (fd >= 0) {
400 close(device->fd);
401 device->fd = fd;
402 device->writeable = 1;
403 return 1;
404 }
405 D("usb_device_reopen_writeable failed errno %d\n", errno);
406 return 0;
407}
408
409int usb_device_get_fd(struct usb_device *device)
410{
411 if (!usb_device_reopen_writeable(device))
412 return -1;
413 return device->fd;
414}
415
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400416const char* usb_device_get_name(struct usb_device *device)
417{
418 return device->dev_name;
419}
420
Mike Lockwood203f1022010-05-27 10:12:03 -0400421int usb_device_get_unique_id(struct usb_device *device)
422{
423 int bus = 0, dev = 0;
424 sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
425 return bus * 1000 + dev;
426}
427
Mike Lockwood07eb4af2010-07-27 19:05:33 -0400428int usb_device_get_unique_id_from_name(const char* name)
429{
430 int bus = 0, dev = 0;
431 sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
432 return bus * 1000 + dev;
433}
434
Mike Lockwood7d700f82010-12-29 08:47:29 -0500435char* usb_device_get_name_from_unique_id(int id)
436{
437 int bus = id / 1000;
438 int dev = id % 1000;
439 char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
440 snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
441 return result;
442}
443
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400444uint16_t usb_device_get_vendor_id(struct usb_device *device)
445{
446 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
447 return __le16_to_cpu(desc->idVendor);
448}
449
450uint16_t usb_device_get_product_id(struct usb_device *device)
451{
452 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
453 return __le16_to_cpu(desc->idProduct);
454}
455
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700456const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device* device) {
Mike Lockwood50372072010-12-13 10:15:25 -0800457 return (struct usb_device_descriptor*)device->desc;
458}
459
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700460size_t usb_device_get_descriptors_length(const struct usb_device* device) {
461 return device->desc_length;
462}
463
464const unsigned char* usb_device_get_raw_descriptors(const struct usb_device* device) {
465 return device->desc;
466}
467
Andrew Chant169742e2017-12-07 16:51:49 -0800468/* Returns a USB descriptor string for the given string ID.
469 * Return value: < 0 on error. 0 on success.
470 * The string is returned in ucs2_out in USB-native UCS-2 encoding.
471 *
472 * parameters:
473 * id - the string descriptor index.
474 * timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
475 * ucs2_out - Must point to null on call.
476 * Will be filled in with a buffer on success.
477 * If this is non-null on return, it must be free()d.
478 * response_size - size, in bytes, of ucs-2 string in ucs2_out.
479 * The size isn't guaranteed to include null termination.
480 * Call free() to free the result when you are done with it.
481 */
482int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
483 size_t* response_size) {
Mike Lockwood0dd1aab2015-06-18 13:38:31 -0700484 __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
Andrew Chant169742e2017-12-07 16:51:49 -0800485 char response[MAX_STRING_DESCRIPTOR_LENGTH];
486 int result;
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400487 int languageCount = 0;
488
Andrew Chant169742e2017-12-07 16:51:49 -0800489 if (id == 0) return -1;
490 if (*ucs2_out != NULL) return -1;
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800491
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400492 memset(languages, 0, sizeof(languages));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400493
494 // read list of supported languages
Mike Lockwood120b57a2011-01-27 10:46:19 -0800495 result = usb_device_control_transfer(device,
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400496 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700497 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
498 timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400499 if (result > 0)
500 languageCount = (result - 2) / 2;
501
Andrew Chant169742e2017-12-07 16:51:49 -0800502 for (int i = 1; i <= languageCount; i++) {
503 memset(response, 0, sizeof(response));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400504
Andrew Chant169742e2017-12-07 16:51:49 -0800505 result = usb_device_control_transfer(
506 device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
507 (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
508 if (result >= 2) { // string contents begin at offset 2.
509 int descriptor_len = result - 2;
510 char* out = malloc(descriptor_len + 3);
511 if (out == NULL) {
512 return -1;
513 }
514 memcpy(out, response + 2, descriptor_len);
515 // trail with three additional NULLs, so that there's guaranteed
516 // to be a UCS-2 NULL character beyond whatever USB returned.
517 // The returned string length is still just what USB returned.
518 memset(out + descriptor_len, '\0', 3);
519 *ucs2_out = (void*)out;
520 *response_size = descriptor_len;
521 return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400522 }
523 }
Andrew Chant169742e2017-12-07 16:51:49 -0800524 return -1;
525}
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400526
Andrew Chant169742e2017-12-07 16:51:49 -0800527/* Warning: previously this blindly returned the lower 8 bits of
528 * every UCS-2 character in a USB descriptor. Now it will replace
529 * values > 127 with ascii '?'.
530 */
531char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
532 char* ascii_string = NULL;
533 size_t raw_string_len = 0;
534 size_t i;
535 if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
536 return NULL;
537 if (ascii_string == NULL) return NULL;
538 for (i = 0; i < raw_string_len / 2; ++i) {
539 // wire format for USB is always little-endian.
540 char lower = ascii_string[2 * i];
541 char upper = ascii_string[2 * i + 1];
542 if (upper || (lower & 0x80)) {
543 ascii_string[i] = '?';
544 } else {
545 ascii_string[i] = lower;
546 }
547 }
548 ascii_string[i] = '\0';
549 return ascii_string;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400550}
551
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700552char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400553{
554 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700555 return usb_device_get_string(device, desc->iManufacturer, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400556}
557
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700558char* usb_device_get_product_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400559{
560 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700561 return usb_device_get_string(device, desc->iProduct, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400562}
563
Mike Lockwoodf68600a2015-04-29 13:04:10 -0700564int usb_device_get_version(struct usb_device *device)
565{
566 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
567 return desc->bcdUSB;
568}
569
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700570char* usb_device_get_serial(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400571{
572 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700573 return usb_device_get_string(device, desc->iSerialNumber, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400574}
575
576int usb_device_is_writeable(struct usb_device *device)
577{
578 return device->writeable;
579}
580
581void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
582{
583 iter->config = device->desc;
584 iter->config_end = device->desc + device->desc_length;
585 iter->curr_desc = device->desc;
586}
587
588struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
589{
590 struct usb_descriptor_header* next;
591 if (iter->curr_desc >= iter->config_end)
592 return NULL;
593 next = (struct usb_descriptor_header*)iter->curr_desc;
Jacob Abrams43d246c2020-02-21 10:16:16 -0800594 // Corrupt descriptor with zero length, cannot continue iterating
595 if (next->bLength == 0) {
596 D("usb_descriptor_iter_next got zero length USB descriptor, ending iteration\n");
597 return NULL;
598 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400599 iter->curr_desc += next->bLength;
600 return next;
601}
602
603int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
604{
605 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
606}
607
608int usb_device_release_interface(struct usb_device *device, unsigned int interface)
609{
610 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
611}
612
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800613int usb_device_connect_kernel_driver(struct usb_device *device,
614 unsigned int interface, int connect)
615{
616 struct usbdevfs_ioctl ctl;
617
618 ctl.ifno = interface;
619 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
620 ctl.data = NULL;
621 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
622}
623
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800624int usb_device_set_configuration(struct usb_device *device, int configuration)
625{
626 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
627}
628
629int usb_device_set_interface(struct usb_device *device, unsigned int interface,
630 unsigned int alt_setting)
631{
632 struct usbdevfs_setinterface ctl;
633
634 ctl.interface = interface;
635 ctl.altsetting = alt_setting;
636 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
637}
638
Mike Lockwood120b57a2011-01-27 10:46:19 -0800639int usb_device_control_transfer(struct usb_device *device,
640 int requestType,
641 int request,
642 int value,
643 int index,
644 void* buffer,
645 int length,
646 unsigned int timeout)
647{
648 struct usbdevfs_ctrltransfer ctrl;
649
650 // this usually requires read/write permission
651 if (!usb_device_reopen_writeable(device))
652 return -1;
653
654 memset(&ctrl, 0, sizeof(ctrl));
655 ctrl.bRequestType = requestType;
656 ctrl.bRequest = request;
657 ctrl.wValue = value;
658 ctrl.wIndex = index;
659 ctrl.wLength = length;
660 ctrl.data = buffer;
661 ctrl.timeout = timeout;
662 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
663}
664
665int usb_device_bulk_transfer(struct usb_device *device,
666 int endpoint,
667 void* buffer,
Philip P. Moltmann9879bb22016-09-20 14:11:26 -0700668 unsigned int length,
Mike Lockwood120b57a2011-01-27 10:46:19 -0800669 unsigned int timeout)
670{
671 struct usbdevfs_bulktransfer ctrl;
672
673 memset(&ctrl, 0, sizeof(ctrl));
674 ctrl.ep = endpoint;
675 ctrl.len = length;
676 ctrl.data = buffer;
677 ctrl.timeout = timeout;
678 return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
679}
680
Keun-young Parkf6411fa2016-01-12 18:22:36 -0800681int usb_device_reset(struct usb_device *device)
682{
683 return ioctl(device->fd, USBDEVFS_RESET);
684}
685
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500686struct usb_request *usb_request_new(struct usb_device *dev,
687 const struct usb_endpoint_descriptor *ep_desc)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400688{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500689 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
690 if (!urb)
691 return NULL;
692
693 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
694 urb->type = USBDEVFS_URB_TYPE_BULK;
695 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
696 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
697 else {
698 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
699 free(urb);
700 return NULL;
701 }
702 urb->endpoint = ep_desc->bEndpointAddress;
703
704 struct usb_request *req = calloc(1, sizeof(struct usb_request));
705 if (!req) {
706 free(urb);
707 return NULL;
708 }
709
710 req->dev = dev;
711 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
712 req->private_data = urb;
Mike Lockwoodb5d68a32011-02-14 08:05:40 -0500713 req->endpoint = urb->endpoint;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500714 urb->usercontext = req;
715
716 return req;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400717}
718
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500719void usb_request_free(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400720{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500721 free(req->private_data);
722 free(req);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400723}
724
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500725int usb_request_queue(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400726{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500727 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400728 int res;
729
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400730 urb->status = -1;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500731 urb->buffer = req->buffer;
Jerry Zhang3be61d32018-02-06 18:25:44 -0800732 urb->buffer_length = req->buffer_length;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400733
734 do {
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500735 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400736 } while((res < 0) && (errno == EINTR));
737
738 return res;
739}
740
Philip P. Moltmann36952852016-10-17 16:57:43 -0700741struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400742{
Philip P. Moltmann36952852016-10-17 16:57:43 -0700743 // Poll until a request becomes available if there is a timeout
744 if (timeoutMillis > 0) {
745 struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400746
Philip P. Moltmann36952852016-10-17 16:57:43 -0700747 int res = poll(&p, 1, timeoutMillis);
748
749 if (res != 1 || p.revents != POLLOUT) {
750 D("[ poll - event %d, error %d]\n", p.revents, errno);
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500751 return NULL;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400752 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400753 }
Philip P. Moltmann36952852016-10-17 16:57:43 -0700754
755 // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
756 // two threads are reading usb requests at the same time and only a single request is available.
757 struct usbdevfs_urb *urb = NULL;
758 int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
759 USBDEVFS_REAPURBNDELAY, &urb));
760 D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
761
762 if (res < 0) {
763 D("[ reap urb - error %d]\n", errno);
764 return NULL;
765 } else {
766 D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
767
768 struct usb_request *req = (struct usb_request*)urb->usercontext;
769 req->actual_length = urb->actual_length;
770
771 return req;
772 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400773}
774
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500775int usb_request_cancel(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400776{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500777 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
Badhri Jagan Sridharanef4087b2014-08-06 12:34:30 -0700778 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400779}