aboutsummaryrefslogtreecommitdiffstats
path: root/src/usb/osmo_libusb.c
blob: 5b012b865e369b1d39b4629127a92cf9dfb89212 (plain)
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/* libosmocore integration with libusb-1.0
 *
 * (C) 2019-2019 by Harald Welte <laforge@gnumonks.org>
 * All Rights Reserved.
 *
 * SPDX-License-Identifier: GPL-2.0+
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <poll.h>

#include <osmocom/core/utils.h>
#include <osmocom/core/logging.h>
#include <osmocom/core/select.h>
#include <osmocom/core/talloc.h>

#include <libusb.h>

#include <osmocom/usb/libusb.h>

/***********************************************************************
 * logging integration
 ***********************************************************************/

#define DLUSB	DLINP

#ifdef LIBUSB_LOG_CB_CONTEXT /* introduced in 1.0.23 */
static const int usb2logl[] = {
	[LIBUSB_LOG_LEVEL_NONE] = LOGL_FATAL,
	[LIBUSB_LOG_LEVEL_ERROR] = LOGL_ERROR,
	[LIBUSB_LOG_LEVEL_WARNING] = LOGL_NOTICE,
	[LIBUSB_LOG_LEVEL_INFO] = LOGL_INFO,
	[LIBUSB_LOG_LEVEL_DEBUG] = LOGL_DEBUG,
};

/* called by libusb if it wants to log something */
static void libosmo_usb_log_cb(libusb_context *luctx, enum libusb_log_level level_usb, const char *str)
{
	int level = LOGL_NOTICE;

	if (level_usb < ARRAY_SIZE(usb2logl))
		level = usb2logl[level_usb];

	LOGP(DLUSB, level, "%s", str);
}
#endif /* LIBUSB_LOG_CB_CONTEXT */

/***********************************************************************
 * select loop integration
 ***********************************************************************/

static int osmo_usb_fd_cb(struct osmo_fd *ofd, unsigned int what)
{
	libusb_context *luctx = ofd->data;

	/* we assume that we're running Linux v2.6.27 with timerfd support here
	 * and hence don't have to perform manual timeout handling.  See
	 * "Notes on time-based events" at
	 * http://libusb.sourceforge.net/api-1.0/group__libusb__poll.html */
	struct timeval zero_tv = { 0, 0 };
	libusb_handle_events_timeout(luctx, &zero_tv);

	return 0;
}

/* called by libusb if it wants to add a file-descriptor */
static void osmo_usb_added_cb(int fd, short events, void *user_data)
{
	struct osmo_fd *ofd = talloc_zero(OTC_GLOBAL, struct osmo_fd);
	libusb_context *luctx = user_data;
	unsigned int when = 0;

	if (events & POLLIN)
		when |= OSMO_FD_READ;
	if (events & POLLOUT)
		when |= OSMO_FD_WRITE;

	osmo_fd_setup(ofd, fd, when, osmo_usb_fd_cb, luctx, 0);
	osmo_fd_register(ofd);
}

/* called by libusb if it wants to remove a file-descriptor */
static void osmo_usb_removed_cb(int fd, void *user_data)
{
	struct osmo_fd *ofd = osmo_fd_get_by_fd(fd);
	if (!fd)
		return;
	osmo_fd_unregister(ofd);
	talloc_free(ofd);
}

/***********************************************************************
 * utility functions
 ***********************************************************************/

/*! obtain the string representation of the USB device path of given device.
 *  \param[out] buf Output string buffer
 *  \param[in] bufsize Size of output string buffer in bytes
 *  \param[in] dev USB device whose bus path we want to obtain
 *  \returns pointer to 'buf' in case of success; NULL in case of error */
char *osmo_libusb_dev_get_path_buf(char *buf, size_t bufsize, libusb_device *dev)
{
#if (defined(LIBUSB_API_VERSION) && LIBUSB_API_VERSION >= 0x01000102) || \
    (defined(LIBUSBX_API_VERSION) && LIBUSBX_API_VERSION >= 0x01000102)
	struct osmo_strbuf sb = { .buf = buf, .len = bufsize };
	uint8_t path[8];
	int r,j;
	r = libusb_get_port_numbers(dev, path, sizeof(path));
	if (r > 0) {
		OSMO_STRBUF_PRINTF(sb, "%d-%d", libusb_get_bus_number(dev), path[0]);
		for (j = 1; j < r; j++){
			OSMO_STRBUF_PRINTF(sb, ".%d", path[j]);
		}
	}
	return buf;
#else
# warning "libusb too old - building without USB path support!"
	return NULL;
#endif
}

/*! obtain the string representation of the USB device path of given device.
 *  \param[in] talloc context from which to dynamically allocate output string buffer
 *  \param[in] dev USB device whose bus path we want to obtain
 *  \returns pointer to 'buf' in case of success; NULL in case of error */
char *osmo_libusb_dev_get_path_c(void *ctx, libusb_device *dev)
{
	char *buf = talloc_zero_size(ctx, USB_MAX_PATH_LEN);
	if (!buf)
		return NULL;
	return osmo_libusb_dev_get_path_buf(buf, USB_MAX_PATH_LEN, dev);
}

static int match_dev_id(const struct libusb_device_descriptor *desc, const struct dev_id *id)
{
	if ((desc->idVendor == id->vendor_id) && (desc->idProduct == id->product_id))
		return 1;
	return 0;
}

static int match_dev_ids(const struct libusb_device_descriptor *desc, const struct dev_id *ids)
{
	const struct dev_id *id;

	for (id = ids; id->vendor_id || id->product_id; id++) {
		if (match_dev_id(desc, id))
			return 1;
	}
	return 0;
}

/*! Find USB devices matching the specified list of USB VendorID/ProductIDs
 *  \param[in] ctx talloc context from which to allocate output data
 *  \param[in] luctx libusb context on which to operate
 *  \param[in] dev_ids zero-terminated array of VendorId/ProductId tuples
 *  \returns array of up to 256 libusb_device pointers; NULL in case of error */
libusb_device **osmo_libusb_find_matching_usb_devs(void *ctx, struct libusb_context *luctx,
						   const struct dev_id *dev_ids)
{
	libusb_device **list;
	libusb_device **out = talloc_zero_array(ctx, libusb_device *, 256);
	libusb_device **cur = out;
	unsigned int i;
	int rc;

	if (!out)
		return NULL;

	rc = libusb_get_device_list(luctx, &list);
	if (rc <= 0) {
		perror("No USB devices found");
		talloc_free(out);
		return NULL;
	}

	for (i = 0; list[i] != NULL; i++) {
		struct libusb_device_descriptor dev_desc;
		libusb_device *dev = list[i];

		rc = libusb_get_device_descriptor(dev, &dev_desc);
		if (rc < 0) {
			perror("Couldn't get device descriptor\n");
			libusb_unref_device(dev);
			continue;
		}

		if (match_dev_ids(&dev_desc, dev_ids)) {
			*cur = dev;
			cur++;
			/* overflow check */
			if (cur >= out + 256)
				break;
		} else
			libusb_unref_device(dev);
	}
	if (cur == out) {
		libusb_free_device_list(list, 1);
		talloc_free(out);
		return NULL;
	}

	libusb_free_device_list(list, 0);
	return out;
}

/*! find a matching interface among all interfaces of the given USB device.
 *  \param[in] dev USB device in which we shall search
 *  \param[in] class USB Interface Class to look for
 *  \param[in] sub_class USB Interface Subclass to look for
 *  \param[in] protocol USB Interface Protocol to look for
 *  \param[out] out User-allocated array for storing matches
 *  \param[in] out_len Length of out array
 *  \returns number of matching interfaces; negative in case of error */
int osmo_libusb_dev_find_matching_interfaces(libusb_device *dev, int class, int sub_class,
					     int protocol, struct usb_interface_match *out,
					     unsigned int out_len)
{
	struct libusb_device_descriptor dev_desc;
	int rc, i, out_idx = 0;
	uint8_t addr;
	char pathbuf[USB_MAX_PATH_LEN];
	char *path;

	rc = libusb_get_device_descriptor(dev, &dev_desc);
	if (rc < 0) {
		perror("Couldn't get device descriptor\n");
		return -EIO;
	}

	addr = libusb_get_device_address(dev);
	path = osmo_libusb_dev_get_path_buf(pathbuf, sizeof(pathbuf), dev);

	/* iterate over all configurations */
	for (i = 0; i < dev_desc.bNumConfigurations; i++) {
		struct libusb_config_descriptor *conf_desc;
		int j;

		rc = libusb_get_config_descriptor(dev, i, &conf_desc);
		if (rc < 0) {
			fprintf(stderr, "Couldn't get config descriptor %u\n", i);
			continue;
		}
		/* iterate over all interfaces */
		for (j = 0; j < conf_desc->bNumInterfaces; j++) {
			const struct libusb_interface *intf = &conf_desc->interface[j];
			int k;
			/* iterate over all alternate settings */
			for (k = 0; k < intf->num_altsetting; k++) {
				const struct libusb_interface_descriptor *if_desc;
				if_desc = &intf->altsetting[k];
				if (class >= 0 && if_desc->bInterfaceClass != class)
					continue;
				if (sub_class >= 0 && if_desc->bInterfaceSubClass != sub_class)
					continue;
				if (protocol >= 0 && if_desc->bInterfaceProtocol != protocol)
					continue;
				/* MATCH! */
				out[out_idx].usb_dev = dev;
				out[out_idx].vendor = dev_desc.idVendor;
				out[out_idx].product = dev_desc.idProduct;
				out[out_idx].addr = addr;
				strncpy(out[out_idx].path, path, sizeof(out[out_idx].path)-1);
				out[out_idx].path[sizeof(out[out_idx].path)-1] = '\0';
				out[out_idx].configuration = conf_desc->bConfigurationValue;
				out[out_idx].interface = if_desc->bInterfaceNumber;
				out[out_idx].altsetting = if_desc->bAlternateSetting;
				out[out_idx].class = if_desc->bInterfaceClass;
				out[out_idx].sub_class = if_desc->bInterfaceSubClass;
				out[out_idx].protocol = if_desc->bInterfaceProtocol;
				out[out_idx].string_idx = if_desc->iInterface;
				out_idx++;
				if (out_idx >= out_len)
					return out_idx;
			}
		}
	}
	return out_idx;
}

/*! find matching interfaces among a list devices of specified VendorId/ProductID tuples.
 *  \param[in] luctx libusb context on which to operate
 *  \param[in] dev_ids zero-terminated array of VendorId/ProductId tuples
 *  \param[in] class USB Interface Class to look for
 *  \param[in] sub_class USB Interface Subclass to look for
 *  \param[in] protocol USB Interface Protocol to look for
 *  \param[out] out User-allocated array for storing matches
 *  \param[in] out_len Length of out array
 *  \returns number of matching interfaces; negative in case of error */
int osmo_libusb_find_matching_interfaces(libusb_context *luctx, const struct dev_id *dev_ids,
					 int class, int sub_class, int protocol,
					 struct usb_interface_match *out, unsigned int out_len)
{
	struct usb_interface_match *out_cur = out;
	unsigned int out_len_remain = out_len;
	libusb_device **list;
	libusb_device **dev;

	list = osmo_libusb_find_matching_usb_devs(NULL, luctx, dev_ids);
	if (!list)
		return 0;

	for (dev = list; *dev; dev++) {
		int rc;

#if 0
		struct libusb_device_descriptor dev_desc;
		uint8_t ports[8];
		uint8_t addr;
		rc = libusb_get_device_descriptor(*dev, &dev_desc);
		if (rc < 0) {
			perror("Cannot get device descriptor");
			continue;
		}

		addr = libusb_get_device_address(*dev);

		rc = libusb_get_port_numbers(*dev, ports, sizeof(ports));
		if (rc < 0) {
			perror("Cannot get device path");
			continue;
		}

		printf("Found USB Device %04x:%04x at address %d\n",
			dev_desc.idVendor, dev_desc.idProduct, addr);
#endif

		rc = osmo_libusb_dev_find_matching_interfaces(*dev, class, sub_class,
							      protocol, out_cur, out_len_remain);
		if (rc < 0)
			continue;
		out_cur += rc;
		out_len_remain -= rc;

	}

	/* unref / free list */
	for (dev = list; *dev; dev++)
		libusb_unref_device(*dev);
	talloc_free(list);

	return out_len - out_len_remain;
}

/*! open matching USB device and claim interface
 *  \param[in] ctx talloc context to use for related allocations
 *  \param[in] luctx libusb context on which to operate
 *  \param[in] ifm interface match describing interface to claim
 *  \returns libusb device chandle on success; NULL on error */
libusb_device_handle *osmo_libusb_open_claim_interface(void *ctx, libusb_context *luctx,
							const struct usb_interface_match *ifm)
{
	int rc, config;
	struct dev_id dev_ids[] = { { ifm->vendor, ifm->product }, { 0, 0 } };
	libusb_device **list;
	libusb_device **dev;
	libusb_device_handle *usb_devh = NULL;

	list = osmo_libusb_find_matching_usb_devs(ctx, luctx, dev_ids);
	if (!list) {
		perror("No USB device with matching VID/PID");
		return NULL;
	}

	for (dev = list; *dev; dev++) {
		int addr;
		char pathbuf[USB_MAX_PATH_LEN];
		char *path;

		addr = libusb_get_device_address(*dev);
		path = osmo_libusb_dev_get_path_buf(pathbuf, sizeof(pathbuf), *dev);
		if ((ifm->addr && addr == ifm->addr) ||
		    (strlen(ifm->path) && !strcmp(path, ifm->path))) {
			rc = libusb_open(*dev, &usb_devh);
			if (rc < 0) {
				fprintf(stderr, "Cannot open device: %s\n", libusb_error_name(rc));
				usb_devh = NULL;
				break;
			}
			rc = libusb_get_configuration(usb_devh, &config);
			if (rc < 0) {
				fprintf(stderr, "Cannot get current configuration: %s\n", libusb_error_name(rc));
				libusb_close(usb_devh);
				usb_devh = NULL;
				break;
			}
			if (config != ifm->configuration) {
				rc = libusb_set_configuration(usb_devh, ifm->configuration);
				if (rc < 0) {
					fprintf(stderr, "Cannot set configuration: %s\n", libusb_error_name(rc));
					libusb_close(usb_devh);
					usb_devh = NULL;
					break;
				}
			}
			rc = libusb_claim_interface(usb_devh, ifm->interface);
			if (rc < 0) {
				fprintf(stderr, "Cannot claim interface: %s\n", libusb_error_name(rc));
				libusb_close(usb_devh);
				usb_devh = NULL;
				break;
			}
			rc = libusb_set_interface_alt_setting(usb_devh, ifm->interface, ifm->altsetting);
			if (rc < 0) {
				fprintf(stderr, "Cannot set interface altsetting: %s\n", libusb_error_name(rc));
				libusb_release_interface(usb_devh, ifm->interface);
				libusb_close(usb_devh);
				usb_devh = NULL;
				break;
			}
		}
	}

	/* unref / free list */
	for (dev = list; *dev; dev++)
		libusb_unref_device(*dev);
	talloc_free(list);

	return usb_devh;
}

/*! obtain the endpoint addresses for a given USB interface.
 *  \param[in] devh USB device handle on which to operate
 *  \param[in] if_num USB Interface number on which to operate
 *  \param[out] out user-provided storage for OUT endpoint number
 *  \param[out] in user-provided storage for IN endpoint number
 *  \param[out] irq user-provided storage for IRQ endpoint number
 *  \returns 0 in case of success; negative in case of error */
int osmo_libusb_get_ep_addrs(libusb_device_handle *devh, unsigned int if_num,
			     uint8_t *out, uint8_t *in, uint8_t *irq)
{
	libusb_device *dev = libusb_get_device(devh);
	struct libusb_config_descriptor *cdesc;
	const struct libusb_interface_descriptor *idesc;
	const struct libusb_interface *iface;
	int rc, l;

	rc = libusb_get_active_config_descriptor(dev, &cdesc);
	if (rc < 0)
		return rc;

	iface = &cdesc->interface[if_num];
	/* FIXME: we assume there's no altsetting */
	idesc = &iface->altsetting[0];

	for (l = 0; l < idesc->bNumEndpoints; l++) {
		const struct libusb_endpoint_descriptor *edesc = &idesc->endpoint[l];
		switch (edesc->bmAttributes & 3) {
		case LIBUSB_TRANSFER_TYPE_BULK:
			if (edesc->bEndpointAddress & 0x80) {
				if (in)
					*in = edesc->bEndpointAddress;
			} else {
				if (out)
					*out = edesc->bEndpointAddress;
			}
			break;
		case LIBUSB_TRANSFER_TYPE_INTERRUPT:
			if (irq)
				*irq = edesc->bEndpointAddress;
			break;
		default:
			break;
		}
	}
	return 0;
}
/***********************************************************************
 * initialization
 ***********************************************************************/

int osmo_libusb_init(libusb_context **pluctx)
{
	libusb_context *luctx = NULL;
	int rc;

	rc = libusb_init(pluctx);
	if (rc != 0)
		return rc;

	if (pluctx)
		luctx = *pluctx;

#ifdef LIBUSB_LOG_CB_CONTEXT /* introduced in 1.0.23 */
	libusb_set_log_cb(luctx, &libosmo_usb_log_cb, LIBUSB_LOG_CB_CONTEXT);
#endif

	libusb_set_pollfd_notifiers(luctx, osmo_usb_added_cb, osmo_usb_removed_cb, luctx);

	return 0;
}

void osmo_libusb_exit(libusb_context *luctx)
{
	/* we just assume libusb is cleaning up all the osmo_Fd's we've allocated */
	libusb_exit(luctx);
}