1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
2 /* gphoto2-port-usb.c
3  *
4  * Copyright 2001 Lutz Mueller <lutz@users.sf.net>
5  * Copyright 1999-2000 Johannes Erdfelt <johannes@erdfelt.com>
6  * Copyright 2011,2015 Marcus Meissner <marcus@jet.franken.de>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library 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 GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA  02110-1301  USA
22  */
23 #include "config.h"
24 #include <gphoto2/gphoto2-port-library.h>
25 
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <string.h>
31 
32 #include <libusb.h>
33 
34 #include <gphoto2/gphoto2-port.h>
35 #include <gphoto2/gphoto2-port-result.h>
36 #include <gphoto2/gphoto2-port-log.h>
37 
38 #ifdef ENABLE_NLS
39 #  include <libintl.h>
40 #  undef _
41 #  define _(String) dgettext (GETTEXT_PACKAGE, String)
42 #  ifdef gettext_noop
43 #    define N_(String) gettext_noop (String)
44 #  else
45 #    define N_(String) (String)
46 #  endif
47 #else
48 #  define textdomain(String) (String)
49 #  define gettext(String) (String)
50 #  define dgettext(Domain,Message) (Message)
51 #  define dcgettext(Domain,Message,Type) (Message)
52 #  define bindtextdomain(Domain,Directory) (Domain)
53 #  define _(String) (String)
54 #  define N_(String) (String)
55 #endif
56 
57 #define C_GP(RESULT) do {\
58 	int _r=(RESULT);\
59 	if (_r<GP_OK) {\
60 		GP_LOG_E ("'%s' failed: %s (%d)", #RESULT, gp_port_result_as_string(_r), _r);\
61 		return _r;\
62 	}\
63 } while(0)
64 
my_libusb_strerror(int r)65 static const char *my_libusb_strerror(int r)
66 {
67 	switch (r) {
68 	case LIBUSB_SUCCESS:			return "Success";
69 	case LIBUSB_ERROR_IO:			return "Input/Output error";
70 	case LIBUSB_ERROR_INVALID_PARAM:	return "Invalid parameter";
71 	case LIBUSB_ERROR_ACCESS:		return "Access denied (insufficient permissions)";
72 	case LIBUSB_ERROR_NO_DEVICE:		return "No such device (it may have been disconnected)";
73 	case LIBUSB_ERROR_NOT_FOUND:		return "Entity not found";
74 	case LIBUSB_ERROR_BUSY:			return "Resource busy";
75 	case LIBUSB_ERROR_TIMEOUT:		return "Operation timed out";
76 	case LIBUSB_ERROR_OVERFLOW:		return "Overflow";
77 	case LIBUSB_ERROR_PIPE:			return "Pipe error";
78 	case LIBUSB_ERROR_INTERRUPTED:		return "System call interrupted (perhaps due to signal)";
79 	case LIBUSB_ERROR_NO_MEM:		return "Insufficient memory";
80 	case LIBUSB_ERROR_NOT_SUPPORTED:	return "Operation not supported or unimplemented on this platform";
81 	case LIBUSB_ERROR_OTHER:		return "Other error";
82 	default:				return "Unknown error";
83 	}
84 }
85 
log_on_libusb_error_helper(int _r,const char * _func,const char * file,int line,const char * func)86 static int log_on_libusb_error_helper( int _r, const char* _func, const char* file, int line, const char* func ) {
87 	if (_r < LIBUSB_SUCCESS)
88 		gp_log_with_source_location(GP_LOG_ERROR, file, line, func,
89 					    "'%s' failed: %s (%d)", _func, my_libusb_strerror(_r), _r);
90 	return _r;
91 }
92 #define LOG_ON_LIBUSB_E( RESULT ) log_on_libusb_error_helper( (RESULT), #RESULT, __FILE__, __LINE__, __func__ )
93 
94 #define C_LIBUSB(RESULT, DEFAULT_ERROR) do {\
95 	int _r = LOG_ON_LIBUSB_E( RESULT );\
96 	if (_r < LIBUSB_SUCCESS)\
97 		return translate_libusb_error(_r, DEFAULT_ERROR);\
98 } while (0)
99 
100 
translate_libusb_error(int error,int default_return)101 static int translate_libusb_error( int error, int default_return )
102 {
103 	switch (error) {
104 	case LIBUSB_SUCCESS:			return GP_OK;
105 	case LIBUSB_ERROR_INVALID_PARAM:	return GP_ERROR_BAD_PARAMETERS;
106 	case LIBUSB_ERROR_NO_DEVICE:		return GP_ERROR_IO_USB_FIND;
107 	case LIBUSB_ERROR_TIMEOUT:		return GP_ERROR_TIMEOUT;
108 	case LIBUSB_ERROR_NO_MEM:		return GP_ERROR_NO_MEMORY;
109 	case LIBUSB_ERROR_NOT_SUPPORTED:	return GP_ERROR_NOT_SUPPORTED;
110 
111 	case LIBUSB_ERROR_IO:
112 	case LIBUSB_ERROR_BUSY:
113 	case LIBUSB_ERROR_NOT_FOUND:
114 	case LIBUSB_ERROR_ACCESS:
115 	case LIBUSB_ERROR_OVERFLOW:
116 	case LIBUSB_ERROR_PIPE:
117 	case LIBUSB_ERROR_INTERRUPTED:
118 	default:
119 		return default_return; /* usually GP_ERROR_IO, but might be GP_ERROR_IO_READ/WRITE */
120 	}
121 }
122 
123 struct _PrivateIrqCompleted {
124 	struct _PrivateIrqCompleted	*next;
125 	enum libusb_transfer_status	status;
126 	int							data_len;
127 	unsigned char				*data;
128 };
129 
130 #define NB_INTERRUPT_TRANSFERS 10
131 /* FIXME: safe size? */
132 #define INTERRUPT_BUFFER_SIZE 256
133 
134 struct _GPPortPrivateLibrary {
135 	libusb_context *ctx;
136 	libusb_device *d;
137 	libusb_device_handle *dh;
138 
139 	int config;
140 	int interface;
141 	int altsetting;
142 
143 	int detached;
144 
145 	time_t				devslastchecked;
146 	int				nrofdevs;
147 	struct libusb_device_descriptor	*descs;
148 	libusb_device			**devs;
149 
150 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
151 	/* for dumping the read usb content */
152 	int				logfd;
153 #endif
154 
155 	struct libusb_transfer		*transfers[NB_INTERRUPT_TRANSFERS];
156 	int				nrofactiveinttransfers;
157 	struct _PrivateIrqCompleted	*irqs_head;
158 	struct _PrivateIrqCompleted	*irqs_tail;
159 };
160 
161 GPPortType
gp_port_library_type(void)162 gp_port_library_type (void)
163 {
164 	return (GP_PORT_USB);
165 }
166 
167 
168 static ssize_t
load_devicelist(GPPortPrivateLibrary * pl)169 load_devicelist (GPPortPrivateLibrary *pl) {
170 	time_t	xtime;
171 
172 	time(&xtime);
173 	if (xtime != pl->devslastchecked) {
174 		if (pl->nrofdevs)
175 			libusb_free_device_list (pl->devs, 1);
176 		free (pl->descs);
177 		pl->nrofdevs = 0;
178 		pl->devs = NULL;
179 		pl->descs = NULL;
180 	}
181 	if (!pl->nrofdevs) {
182 		int 	i;
183 
184 		pl->nrofdevs = libusb_get_device_list (pl->ctx, &pl->devs);
185 		C_MEM (pl->descs = calloc (pl->nrofdevs, sizeof(pl->descs[0])));
186 		for (i=0;i<pl->nrofdevs;i++)
187 			LOG_ON_LIBUSB_E (libusb_get_device_descriptor(pl->devs[i], &pl->descs[i]));
188 	}
189 	time (&pl->devslastchecked);
190 	return pl->nrofdevs;
191 }
192 
193 int
gp_port_library_list(GPPortInfoList * list)194 gp_port_library_list (GPPortInfoList *list)
195 {
196 	GPPortInfo	info;
197 	int		nrofdevices = 0;
198 	int		d, i, i1, i2, unknownint;
199 	libusb_context	*ctx;
200 	libusb_device	**devs = NULL;
201 	int		nrofdevs = 0;
202 	struct libusb_device_descriptor	*descs;
203 
204 	C_LIBUSB (libusb_init (&ctx), GP_ERROR_IO);
205 
206 	/* TODO: make sure libusb_exit gets called in all error paths inside this function */
207 
208 	/* generic matcher. This will catch passed XXX,YYY entries for instance. */
209 	C_GP (gp_port_info_new (&info));
210 	gp_port_info_set_type (info, GP_PORT_USB);
211 	gp_port_info_set_name (info, "");
212 	gp_port_info_set_path (info, "^usb:");
213 	gp_port_info_list_append (list, info); /* do not check return value, it might be -1 */
214 
215 	nrofdevs = libusb_get_device_list (ctx, &devs);
216 	if (!nrofdevs) {
217 		libusb_exit (ctx); /* should free all stuff above */
218 		goto nodevices;
219 	}
220 
221 	C_MEM (descs = calloc (nrofdevs, sizeof(descs[0])));
222 	for (i=0;i<nrofdevs;i++)
223 		LOG_ON_LIBUSB_E (libusb_get_device_descriptor(devs[i], &descs[i]));
224 
225 	for (d = 0; d < nrofdevs; d++) {
226 		/* Devices which are definitely not cameras. */
227 		if (	(descs[d].bDeviceClass == LIBUSB_CLASS_HUB)		||
228 			(descs[d].bDeviceClass == LIBUSB_CLASS_HID)		||
229 			(descs[d].bDeviceClass == LIBUSB_CLASS_PRINTER)	||
230 			(descs[d].bDeviceClass == LIBUSB_CLASS_COMM)	||
231 			(descs[d].bDeviceClass == 0xe0)	/* wireless / bluetooth */
232 		)
233 			continue;
234 		/* excepts HUBs, usually the interfaces have the classes, not
235 		 * the device */
236 		unknownint = 0;
237 		for (i = 0; i < descs[d].bNumConfigurations; i++) {
238 			struct libusb_config_descriptor *config;
239 
240 			if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (devs[d], i, &config))) {
241 				unknownint++;
242 				continue;
243 			}
244 			for (i1 = 0; i1 < config->bNumInterfaces; i1++)
245 				for (i2 = 0; i2 < config->interface[i1].num_altsetting; i2++) {
246 					const struct libusb_interface_descriptor *intf = &config->interface[i1].altsetting[i2];
247 					if (	(intf->bInterfaceClass == LIBUSB_CLASS_HID)	||
248 						(intf->bInterfaceClass == LIBUSB_CLASS_PRINTER)	||
249 						(intf->bInterfaceClass == LIBUSB_CLASS_COMM)	||
250 						(intf->bInterfaceClass == 0xe0)	/* wireless/bluetooth*/
251 					)
252 						continue;
253 					unknownint++;
254 				}
255 			libusb_free_config_descriptor (config);
256 		}
257 		/* when we find only hids, printer or comm ifaces  ... skip this */
258 		if (!unknownint)
259 			continue;
260 		/* Note: We do not skip USB storage. Some devices can support both,
261 		 * and the Ricoh erronously reports it.
262 		 */
263 		nrofdevices++;
264 	}
265 
266 #if 0
267 	/* If we already added usb:, and have 0 or 1 devices we have nothing to do.
268 	 * This should be the standard use case.
269 	 */
270 	/* We never want to return just "usb:" ... also return "usb:XXX,YYY", and
271 	 * let upper layers filter out the usb: */
272 	if (nrofdevices <= 1)
273 		return (GP_OK);
274 #endif
275 
276 	/* Redo the same bus/device walk, but now add the ports with usb:x,y notation,
277 	 * so we can address all USB devices.
278 	 */
279 	for (d = 0; d < nrofdevs; d++) {
280 		char path[200];
281 
282 		/* Devices which are definitely not cameras. */
283 		if (	(descs[d].bDeviceClass == LIBUSB_CLASS_HUB)		||
284 			(descs[d].bDeviceClass == LIBUSB_CLASS_HID)		||
285 			(descs[d].bDeviceClass == LIBUSB_CLASS_PRINTER)	||
286 			(descs[d].bDeviceClass == LIBUSB_CLASS_COMM)
287 		)
288 			continue;
289 		/* excepts HUBs, usually the interfaces have the classes, not
290 		 * the device */
291 		unknownint = 0;
292 		for (i = 0; i < descs[d].bNumConfigurations; i++) {
293 			struct libusb_config_descriptor *config;
294 
295 			if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (devs[d], i, &config))) {
296 				unknownint++;
297 				continue;
298 			}
299 			for (i1 = 0; i1 < config->bNumInterfaces; i1++)
300 				for (i2 = 0; i2 < config->interface[i1].num_altsetting; i2++) {
301 					const struct libusb_interface_descriptor *intf = &config->interface[i1].altsetting[i2];
302 					if (	(intf->bInterfaceClass == LIBUSB_CLASS_HID)	||
303 						(intf->bInterfaceClass == LIBUSB_CLASS_PRINTER)	||
304 						(intf->bInterfaceClass == LIBUSB_CLASS_COMM))
305 						continue;
306 					unknownint++;
307 				}
308 			libusb_free_config_descriptor (config);
309 		}
310 		/* when we find only hids, printer or comm ifaces  ... skip this */
311 		if (!unknownint)
312 			continue;
313 		/* Note: We do not skip USB storage. Some devices can support both,
314 		 * and the Ricoh erronously reports it.
315 		 */
316 		C_GP (gp_port_info_new (&info));
317 		gp_port_info_set_type (info, GP_PORT_USB);
318 		gp_port_info_set_name (info, "Universal Serial Bus");
319 		snprintf (path,sizeof(path), "usb:%03d,%03d",
320 			libusb_get_bus_number (devs[d]),
321 			libusb_get_device_address (devs[d])
322 		);
323 		gp_port_info_set_path (info, path);
324 		C_GP (gp_port_info_list_append (list, info));
325 	}
326 
327 	libusb_free_device_list (devs, 1);
328 	libusb_exit (ctx); /* should free all stuff above */
329 	free (descs);
330 
331 nodevices:
332 	/* This will only be added if no other device was ever added.
333 	 * Users doing "usb:" usage will enter the regular expression matcher case. */
334 	if (nrofdevices == 0) {
335 		C_GP (gp_port_info_new (&info));
336 		gp_port_info_set_type (info, GP_PORT_USB);
337 		gp_port_info_set_name (info, "Universal Serial Bus");
338 		gp_port_info_set_path (info, "usb:");
339 		C_GP (gp_port_info_list_append (list, info));
340 	}
341 	return (GP_OK);
342 }
343 
gp_libusb1_init(GPPort * port)344 static int gp_libusb1_init (GPPort *port)
345 {
346 	C_MEM (port->pl = malloc (sizeof (GPPortPrivateLibrary)));
347 	memset (port->pl, 0, sizeof (GPPortPrivateLibrary));
348 
349 	port->pl->config = port->pl->interface = port->pl->altsetting = -1;
350 
351 	if (LOG_ON_LIBUSB_E (libusb_init (&port->pl->ctx))) {
352 		free (port->pl);
353 		port->pl = NULL;
354 		return GP_ERROR_IO;
355 	}
356 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
357 	unlink("usblog.raw");
358 	port->pl->logfd = open("usblog.raw",O_CREAT|O_WRONLY,0644);
359 #endif
360 #if 0
361 	libusb_set_debug (port->pl->ctx, 255);
362 #endif
363 	return GP_OK;
364 }
365 
366 static int
gp_libusb1_exit(GPPort * port)367 gp_libusb1_exit (GPPort *port)
368 {
369 	if (port->pl) {
370 		free (port->pl->descs);
371 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
372 		if (port->pl->logfd >=0 ) close (port->pl->logfd);
373 #endif
374 		if (port->pl->nrofdevs)
375 			libusb_free_device_list (port->pl->devs, 1);
376 		libusb_exit (port->pl->ctx);
377 		free (port->pl);
378 		port->pl = NULL;
379 	}
380 	return GP_OK;
381 }
382 
383 static int gp_libusb1_find_path_lib(GPPort *port);
384 static int gp_libusb1_queue_interrupt_urbs (GPPort *port);
385 static int
gp_libusb1_open(GPPort * port)386 gp_libusb1_open (GPPort *port)
387 {
388 	int ret;
389 
390 	GP_LOG_D ("()");
391 	C_PARAMS (port);
392 
393 	if (!port->pl->d) {
394 		gp_libusb1_find_path_lib(port);
395 		C_PARAMS (port->pl->d);
396 	}
397 
398 	C_LIBUSB (libusb_open (port->pl->d, &port->pl->dh), GP_ERROR_IO);
399 	if (!port->pl->dh) {
400 		int saved_errno = errno;
401 		gp_port_set_error (port, _("Could not open USB device (%s)."),
402 				   strerror(saved_errno));
403 		return GP_ERROR_IO;
404 	}
405 	ret = libusb_kernel_driver_active (port->pl->dh, port->settings.usb.interface);
406 
407 #if 0
408 	if (strstr(name,"usbfs") || strstr(name,"storage")) {
409 		/* other gphoto instance most likely */
410 		gp_port_set_error (port, _("Camera is already in use."));
411 		return GP_ERROR_IO_LOCK;
412 	}
413 #endif
414 
415 	switch (ret) {
416 	case 1: GP_LOG_D ("Device has a kernel driver attached (%d), detaching it now.", ret);
417 		ret = libusb_detach_kernel_driver (port->pl->dh, port->settings.usb.interface);
418 		if (ret < 0)
419 			gp_port_set_error (port, _("Could not detach kernel driver of camera device."));
420 		else
421 			port->pl->detached = 1;
422 	case 0:	/* not detached */
423 		break;
424 	default:
425 		gp_port_set_error (port, _("Could not query kernel driver of device."));
426 		break;
427 	}
428 
429 	GP_LOG_D ("claiming interface %d", port->settings.usb.interface);
430 	if (LOG_ON_LIBUSB_E (libusb_claim_interface (port->pl->dh, port->settings.usb.interface))) {
431 		int saved_errno = errno;
432 		gp_port_set_error (port, _("Could not claim interface %d (%s). "
433 					   "Make sure no other program (%s) "
434 					   "or kernel module (such as %s) "
435 					   "is using the device and you have "
436 					   "read/write access to the device."),
437 				   port->settings.usb.interface,
438 				   strerror(saved_errno),
439 #ifdef __linux__
440 				   "gvfs-gphoto2-volume-monitor",
441 #else
442 #if defined(__APPLE__)
443 				   _("MacOS PTPCamera service"),
444 #else
445 				   _("unknown libgphoto2 using program"),
446 #endif
447 #endif
448 				   "sdc2xx, stv680, spca50x");
449 		return GP_ERROR_IO_USB_CLAIM;
450 	}
451 
452 	ret = gp_libusb1_queue_interrupt_urbs (port);
453 	if (ret)
454 		return ret;
455 
456 	return GP_OK;
457 }
458 
459 static int
_close_async_interrupts(GPPort * port)460 _close_async_interrupts(GPPort *port)
461 {
462 	unsigned int i, haveone;
463 	struct timeval tv;
464 
465 	C_PARAMS (port);
466 
467 	if (port->pl->dh == NULL)
468 		return GP_OK;
469 
470 	/* Catch up on pending ones */
471 	tv.tv_sec = 0;
472 	tv.tv_usec = 1000;
473 	LOG_ON_LIBUSB_E (libusb_handle_events_timeout(port->pl->ctx, &tv));
474 	/* Now cancel and free the async transfers */
475 	for (i = 0; i < sizeof(port->pl->transfers)/sizeof(port->pl->transfers[0]); i++) {
476 		if (port->pl->transfers[i]) {
477 			GP_LOG_D("canceling transfer %d:%p (status %d)",i, port->pl->transfers[i], port->pl->transfers[i]->status);
478 			/* this happens if the transfer is completed for instance, but not reaped. we cannot cancel it. */
479 			if (LOG_ON_LIBUSB_E(libusb_cancel_transfer(port->pl->transfers[i])) < 0) {
480 				/* do not libusb_free_transfer (port->pl->transfers[i]); causes crashes */
481 				port->pl->transfers[i] = NULL;
482 			}
483 		}
484 	}
485 	tv.tv_sec = 0;
486 	tv.tv_usec = 0;
487 	LOG_ON_LIBUSB_E (libusb_handle_events_timeout(port->pl->ctx, &tv));
488 	/* Do just one round ... this should be sufficient and avoids endless loops. */
489 	haveone = 0;
490 	for (i = 0; i < sizeof(port->pl->transfers)/sizeof(port->pl->transfers[0]); i++) {
491 		if (port->pl->transfers[i]) {
492 			GP_LOG_D("checking: transfer %d:%p status %d",i, port->pl->transfers[i], port->pl->transfers[i]->status);
493 			haveone = 1;
494 		}
495 	}
496 	if (haveone)
497 		LOG_ON_LIBUSB_E (libusb_handle_events(port->pl->ctx));
498 	return GP_OK;
499 }
500 
501 static int
gp_libusb1_close(GPPort * port)502 gp_libusb1_close (GPPort *port)
503 {
504 	C_PARAMS (port);
505 
506 	if (port->pl->dh == NULL)
507 		return GP_OK;
508 
509 	_close_async_interrupts(port);
510 
511 	if (libusb_release_interface (port->pl->dh,
512 				   port->settings.usb.interface) < 0) {
513 		int saved_errno = errno;
514 		gp_port_set_error (port, _("Could not release interface %d (%s)."),
515 				   port->settings.usb.interface,
516 				   strerror(saved_errno));
517 		return GP_ERROR_IO;
518 	}
519 
520 #if 0
521 	/* This confuses the EOS 5d camera and possible other EOSs. *sigh* */
522 	/* This is only for our very special Canon cameras which need a good
523 	 * whack after close, otherwise they get timeouts on reconnect.
524 	 */
525 	if (port->pl->d->descriptor.idVendor == 0x04a9) {
526 		if (usb_reset (port->pl->dh) < 0) {
527 			int saved_errno = errno;
528 			gp_port_set_error (port, _("Could not reset "
529 						   "USB port (%s)."),
530 					   strerror(saved_errno));
531 			return (GP_ERROR_IO);
532 		}
533 	}
534 #endif
535 	if (port->pl->detached) {
536 		if (LOG_ON_LIBUSB_E (libusb_attach_kernel_driver (port->pl->dh, port->settings.usb.interface)))
537 			gp_port_set_error (port, _("Could not reattach kernel driver of camera device."));
538 	}
539 
540 	libusb_close (port->pl->dh);
541 
542 	struct _PrivateIrqCompleted *irq_iter;
543 	struct _PrivateIrqCompleted *irq_next;
544 
545 	irq_iter=port->pl->irqs_head;
546 	while (irq_iter != NULL) {
547 		if (irq_iter->data)
548 			free(irq_iter->data);
549 		irq_next = irq_iter->next;
550 		free(irq_iter);
551 		irq_iter = irq_next;
552 	}
553 	port->pl->irqs_head = NULL;
554 	port->pl->irqs_tail = NULL;
555 	port->pl->dh = NULL;
556 	return GP_OK;
557 }
558 
559 static int
gp_libusb1_clear_halt_lib(GPPort * port,int ep)560 gp_libusb1_clear_halt_lib(GPPort *port, int ep)
561 {
562 	unsigned char internal_ep;
563 
564 	C_PARAMS (port && port->pl->dh);
565 
566 	switch (ep) {
567 	case GP_PORT_USB_ENDPOINT_IN :
568 		internal_ep = port->settings.usb.inep;
569 		break;
570 	case GP_PORT_USB_ENDPOINT_OUT :
571 		internal_ep = port->settings.usb.outep;
572 		break;
573 	case GP_PORT_USB_ENDPOINT_INT :
574 		internal_ep = port->settings.usb.intep;
575 		break;
576 	default:
577 		gp_port_set_error (port, "bad EndPoint argument 0x%x", ep);
578 		return GP_ERROR_BAD_PARAMETERS;
579 	}
580 
581 	C_LIBUSB (libusb_clear_halt(port->pl->dh, internal_ep), GP_ERROR_IO_USB_CLEAR_HALT);
582 
583 	return GP_OK;
584 }
585 
586 static int
gp_libusb1_write(GPPort * port,const char * bytes,int size)587 gp_libusb1_write (GPPort *port, const char *bytes, int size)
588 {
589         int curwritten;
590 
591 	C_PARAMS (port && port->pl->dh);
592 
593 	C_LIBUSB (libusb_bulk_transfer (port->pl->dh, port->settings.usb.outep,
594                            (unsigned char*)bytes, size, &curwritten, port->timeout),
595                   GP_ERROR_IO_WRITE);
596 
597         return curwritten;
598 }
599 
600 static int
gp_libusb1_read(GPPort * port,char * bytes,int size)601 gp_libusb1_read(GPPort *port, char *bytes, int size)
602 {
603 	int curread;
604 
605 	C_PARAMS (port && port->pl->dh);
606 
607 	C_LIBUSB (libusb_bulk_transfer (port->pl->dh, port->settings.usb.inep,
608 			(unsigned char*)bytes, size, &curread, port->timeout),
609 		  GP_ERROR_IO_READ );
610 
611 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
612 	write(port->pl->logfd, bytes, curread);
613 #endif
614         return curread;
615 }
616 
617 static int
gp_libusb1_reset(GPPort * port)618 gp_libusb1_reset(GPPort *port)
619 {
620 	C_PARAMS (port && port->pl->dh);
621 
622 	/* earlier libusb 1 versions get crashes otherwise */
623 	_close_async_interrupts(port);
624 
625 	C_LIBUSB (libusb_reset_device (port->pl->dh), GP_ERROR_IO);
626 
627 	return GP_OK;
628 }
629 
630 static void LIBUSB_CALL
_cb_irq(struct libusb_transfer * transfer)631 _cb_irq(struct libusb_transfer *transfer)
632 {
633 	struct _PrivateIrqCompleted *irq_new = NULL;
634 	struct _GPPortPrivateLibrary *pl = transfer->user_data;
635 	unsigned int i;
636 	int ret;
637 
638 	GP_LOG_D("%p with status %d", transfer, transfer->status);
639 
640 	if ((transfer->status != LIBUSB_TRANSFER_CANCELLED) &&
641 		(transfer->status != LIBUSB_TRANSFER_TIMED_OUT)
642 	) {
643 		irq_new = (struct _PrivateIrqCompleted *) calloc(1, sizeof (struct _PrivateIrqCompleted));
644 		irq_new->status = transfer->status;
645 
646 		/* Add the irq to the list */
647 		if (pl->irqs_tail)
648 			pl->irqs_tail->next = irq_new;
649 		pl->irqs_tail = irq_new;
650 		if (!pl->irqs_head)
651 			pl->irqs_head = irq_new;
652 	}
653 
654 	if (	(transfer->status == LIBUSB_TRANSFER_CANCELLED) ||
655 		(transfer->status == LIBUSB_TRANSFER_TIMED_OUT) || /* on close */
656 		(transfer->status == LIBUSB_TRANSFER_NO_DEVICE) || /* on removing camera */
657 		(transfer->status != LIBUSB_TRANSFER_COMPLETED) /* any error */
658 	) {
659 		if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
660 			/* So far we don't requeue for any error, previous behavior, maybe we should?
661 			 * Note: some times in case of device removed, libusb encounter an
662 			 * errno == -71, that results in a LIBUSB_TRANSFER_ERROR (1)
663 			 */
664 			GP_LOG_D("Transfer %p should be in LIBUSB_TRANSFER_COMPLETED, but is %d!", transfer, transfer->status);
665 		}
666 		/* Only requeue the global transfers, not temporary ones */
667 		for (i = 0; i < sizeof(pl->transfers)/sizeof(pl->transfers[0]); i++) {
668 			if (pl->transfers[i] == transfer) {
669 				libusb_free_transfer (transfer);
670 				pl->transfers[i] = NULL;
671 				pl->nrofactiveinttransfers--;
672 				return;
673 			}
674 		}
675 		return;
676 	}
677 
678 	if (transfer->actual_length) {
679 		GP_LOG_DATA ((char*)transfer->buffer, transfer->actual_length, "interrupt");
680 
681 		irq_new->data_len = transfer->actual_length;
682 		// Steal the transfer buffer and replace it with a new one for reusing the transfer
683 		irq_new->data = transfer->buffer;
684 		transfer->buffer = malloc(INTERRUPT_BUFFER_SIZE);
685 		transfer->length = INTERRUPT_BUFFER_SIZE;
686 	}
687 
688 	GP_LOG_D("Requeuing completed transfer %p", transfer);
689 	ret = LOG_ON_LIBUSB_E(libusb_submit_transfer (transfer));
690 	if (ret < LIBUSB_SUCCESS) {
691 		pl->nrofactiveinttransfers--;
692 	}
693 	return;
694 }
695 
696 static int
gp_libusb1_queue_interrupt_urbs(GPPort * port)697 gp_libusb1_queue_interrupt_urbs (GPPort *port)
698 {
699 	unsigned int i;
700 	int ret = 0;
701 
702 	/* no interrupt endpoint */
703 	if (port->settings.usb.intep == -1)
704 		return GP_OK;
705 
706 
707 	for (i = 0; i < sizeof(port->pl->transfers)/sizeof(port->pl->transfers[0]); i++) {
708 		unsigned char *buf;
709 		if (port->pl->transfers[i] != NULL)
710 			continue;
711 		port->pl->transfers[i] = libusb_alloc_transfer(0);
712 		buf = malloc(INTERRUPT_BUFFER_SIZE);
713 		libusb_fill_interrupt_transfer(port->pl->transfers[i], port->pl->dh, port->settings.usb.intep,
714 			buf, INTERRUPT_BUFFER_SIZE, _cb_irq, port->pl, 0
715 		);
716 		port->pl->transfers[i]->flags |= LIBUSB_TRANSFER_FREE_BUFFER;
717 		ret = LOG_ON_LIBUSB_E(libusb_submit_transfer (port->pl->transfers[i]));
718 		if (ret < LIBUSB_SUCCESS) {
719 			libusb_free_transfer (port->pl->transfers[i]);
720 			port->pl->transfers[i] = NULL;
721 			return translate_libusb_error(ret, GP_ERROR_IO);
722 		}
723 		port->pl->nrofactiveinttransfers++;
724 	}
725 	return GP_OK;
726 }
727 
728 static int
gp_libusb1_check_int(GPPort * port,char * bytes,int size,int timeout)729 gp_libusb1_check_int (GPPort *port, char *bytes, int size, int timeout)
730 {
731 	int 		ret;
732 	struct timeval	tv;
733 	struct _PrivateIrqCompleted *irq_cur = NULL;
734 
735 	C_PARAMS (port && port->pl->dh && timeout >= 0);
736 
737 	if (port->pl->irqs_head != NULL)
738 		goto handleirq;
739 
740 	if (!timeout)
741 		return GP_ERROR_TIMEOUT;
742 
743 	/* If we have lost all the queued transfers, we should probably restart them
744 	 * if there are long running error, like "no more device". That would be
745 	 * reported upstream, so upstream can take care of that.
746 	 */
747 	if (port->pl->nrofactiveinttransfers < NB_INTERRUPT_TRANSFERS) {
748 		ret = gp_libusb1_queue_interrupt_urbs(port);
749 		if (ret != GP_OK)
750 			return ret;
751 	}
752 
753 	tv.tv_sec = timeout/1000;
754 	tv.tv_usec = (timeout%1000)*1000;
755 
756 	ret = LOG_ON_LIBUSB_E (libusb_handle_events_timeout(port->pl->ctx, &tv));
757 
758 	if (port->pl->irqs_head != NULL)
759 		goto handleirq;
760 
761 	if (ret < LIBUSB_SUCCESS)
762 		return translate_libusb_error(ret, GP_ERROR_IO_READ);
763 
764 	return GP_ERROR_TIMEOUT;
765 
766 handleirq:
767 	irq_cur = port->pl->irqs_head;
768 
769 	switch (irq_cur->status) {
770 	case LIBUSB_TRANSFER_COMPLETED:
771 		ret = GP_OK;
772 		break;
773 	case LIBUSB_TRANSFER_NO_DEVICE:
774 		ret = GP_ERROR_IO_USB_FIND;
775 		/* Agglomerate similar errors to only report once. */
776 		while ((irq_cur->next) &&
777 			   (irq_cur->next->status == LIBUSB_TRANSFER_NO_DEVICE)
778 		) {
779 			port->pl->irqs_head = irq_cur->next;
780 			if (irq_cur->data)
781 				free(irq_cur->data);
782 			free(irq_cur);
783 			irq_cur = port->pl->irqs_head;
784 		}
785 		break;
786 	default:
787 		ret = GP_ERROR_IO;
788 		/* Agglomerate similar errors to only report once. */
789 		while ((irq_cur->next) &&
790 			   (irq_cur->next->status != LIBUSB_TRANSFER_COMPLETED) &&
791 			   (irq_cur->next->status != LIBUSB_TRANSFER_NO_DEVICE)
792         ) {
793 			port->pl->irqs_head = irq_cur->next;
794 			if (irq_cur->data)
795 				free(irq_cur->data);
796 			free(irq_cur);
797 			irq_cur = port->pl->irqs_head;
798 		}
799 		break;
800 	}
801 
802 	if (size > irq_cur->data_len)
803 		size = irq_cur->data_len;
804 	if (irq_cur->data) {
805 		if (size > 0)
806 			memcpy(bytes, irq_cur->data, size);
807 		free(irq_cur->data);
808 	}
809 	port->pl->irqs_head = irq_cur->next;
810 	if (port->pl->irqs_head == NULL)
811 		port->pl->irqs_tail = NULL;
812 	free(irq_cur);
813 
814 	if (ret != GP_OK)
815 		return ret;
816 
817 	return size;
818 }
819 
820 static int
gp_libusb1_msg(GPPort * port,int request,int value,int index,char * bytes,int size,int flags,int default_error)821 gp_libusb1_msg(GPPort *port, int request, int value, int index, char *bytes, int size, int flags, int default_error)
822 {
823 	int handled = 0;
824 	C_PARAMS (port && port->pl->dh);
825 
826 	C_LIBUSB (handled = libusb_control_transfer (port->pl->dh, flags, request, value, index,
827 			(unsigned char*)bytes, size, port->timeout),
828 		  default_error);
829 
830 	return handled;
831 }
832 
833 static int
gp_libusb1_msg_write_lib(GPPort * port,int request,int value,int index,char * bytes,int size)834 gp_libusb1_msg_write_lib(GPPort *port, int request, int value, int index,
835 	char *bytes, int size)
836 {
837 	return gp_libusb1_msg (port, request, value, index, bytes, size,
838 					LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
839 					GP_ERROR_IO_WRITE);
840 }
841 
842 static int
gp_libusb1_msg_read_lib(GPPort * port,int request,int value,int index,char * bytes,int size)843 gp_libusb1_msg_read_lib(GPPort *port, int request, int value, int index,
844 	char *bytes, int size)
845 {
846 	return gp_libusb1_msg (port, request, value, index, bytes, size,
847 					LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
848 					GP_ERROR_IO_READ);
849 }
850 
851 /* The next two functions support the nonstandard request types 0x41 (write)
852  * and 0xc1 (read), which are occasionally needed.
853  */
854 
855 static int
gp_libusb1_msg_interface_write_lib(GPPort * port,int request,int value,int index,char * bytes,int size)856 gp_libusb1_msg_interface_write_lib(GPPort *port, int request,
857 	int value, int index, char *bytes, int size)
858 {
859 	return gp_libusb1_msg (port, request, value, index, bytes, size,
860 					LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_INTERFACE,
861 					GP_ERROR_IO_WRITE);
862 }
863 
864 
865 static int
gp_libusb1_msg_interface_read_lib(GPPort * port,int request,int value,int index,char * bytes,int size)866 gp_libusb1_msg_interface_read_lib(GPPort *port, int request,
867 	int value, int index, char *bytes, int size)
868 {
869 	return gp_libusb1_msg (port, request, value, index, bytes, size,
870 					LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_INTERFACE | LIBUSB_ENDPOINT_IN,
871 					GP_ERROR_IO_READ);
872 }
873 
874 
875 /* The next two functions support the nonstandard request types 0x21 (write)
876  * and 0xa1 (read), which are occasionally needed.
877  */
878 
879 static int
gp_libusb1_msg_class_write_lib(GPPort * port,int request,int value,int index,char * bytes,int size)880 gp_libusb1_msg_class_write_lib(GPPort *port, int request,
881 	int value, int index, char *bytes, int size)
882 {
883 	return gp_libusb1_msg (port, request, value, index, bytes, size,
884 					LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
885 					GP_ERROR_IO_WRITE);
886 }
887 
888 
889 static int
gp_libusb1_msg_class_read_lib(GPPort * port,int request,int value,int index,char * bytes,int size)890 gp_libusb1_msg_class_read_lib(GPPort *port, int request,
891 	int value, int index, char *bytes, int size)
892 {
893 	return gp_libusb1_msg (port, request, value, index, bytes, size,
894 					LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE | LIBUSB_ENDPOINT_IN,
895 					GP_ERROR_IO_READ);
896 }
897 
898 /*
899  * This function applys changes to the device.
900  *
901  * New settings are in port->settings_pending and the old ones
902  * are in port->settings. Compare them first and only call
903  * usb_set_configuration() and usb_set_altinterface() if needed
904  * since some USB devices does not like it if this is done
905  * more than necessary (Canon Digital IXUS 300 for one).
906  *
907  */
908 static int
gp_libusb1_update(GPPort * port)909 gp_libusb1_update (GPPort *port)
910 {
911 	int ifacereleased = FALSE, changedone = FALSE;
912 
913 	C_PARAMS (port && port->pl && port->pl->ctx);
914 
915 	GP_LOG_D ("(old int=%d, conf=%d, alt=%d) port %s, (new int=%d, conf=%d, alt=%d) port %s",
916 		port->settings.usb.interface,
917 		port->settings.usb.config,
918 		port->settings.usb.altsetting,
919 		port->settings.usb.port,
920 		port->settings_pending.usb.interface,
921 		port->settings_pending.usb.config,
922 		port->settings_pending.usb.altsetting,
923 		port->settings_pending.usb.port
924 	);
925 
926 /* do not overwrite it ... we need to set it.
927 	if (port->pl->interface == -1) port->pl->interface = port->settings.usb.interface;
928 	if (port->pl->config == -1) port->pl->config = port->settings.usb.config;
929 	if (port->pl->altsetting == -1) port->pl->altsetting = port->settings.usb.altsetting;
930 */
931 
932 	/* The portname can also be changed with the device still fully closed. */
933 	memcpy(&port->settings.usb.port, &port->settings_pending.usb.port,
934 		sizeof(port->settings.usb.port));
935 
936 	if (!port->pl->dh) {
937 		GP_LOG_D("lowlevel libusb1 port not yet opened, no need for libusb changes");
938 		return GP_OK; /* the port might not be opened, yet. that is ok */
939 	}
940 
941 	memcpy(&port->settings.usb, &port->settings_pending.usb,
942 		sizeof(port->settings.usb));
943 
944 	/* The interface changed. release the old, claim the new ... */
945 	if (port->settings.usb.interface != port->pl->interface) {
946 		GP_LOG_D ("changing interface %d -> %d", port->pl->interface, port->settings.usb.interface);
947 		if ((port->pl->interface != -1) && (LOG_ON_LIBUSB_E (libusb_release_interface (port->pl->dh, port->pl->interface)))) {
948 			/* Not a hard error for now. -Marcus */
949 		} else {
950 			GP_LOG_D ("claiming interface %d", port->settings.usb.interface);
951 			C_LIBUSB (libusb_claim_interface (port->pl->dh, port->settings.usb.interface),
952 				  GP_ERROR_IO_USB_CLAIM);
953 			port->pl->interface = port->settings.usb.interface;
954 		}
955 		changedone = TRUE;
956 	}
957 	if (port->settings.usb.config != port->pl->config) {
958 		GP_LOG_D ("changing config %d -> %d", port->pl->config, port->settings.usb.config);
959 		/* This can only be changed with the interface released.
960 		 * This is a hard requirement since 2.6.12.
961 		 */
962 		if ((port->pl->config != -1) && (LOG_ON_LIBUSB_E (libusb_release_interface (port->pl->dh, port->settings.usb.interface)))) {
963 			ifacereleased = FALSE;
964 		} else {
965 			ifacereleased = TRUE;
966 		}
967 		if (LOG_ON_LIBUSB_E (libusb_set_configuration(port->pl->dh, port->settings.usb.config))) {
968 #if 0 /* setting the configuration failure is not fatal */
969 			int saved_errno = errno;
970 			gp_port_set_error (port,
971 					   _("Could not set config %d/%d (%s)"),
972 					   port->settings.usb.interface,
973 					   port->settings.usb.config,
974 					   strerror(saved_errno));
975 			return GP_ERROR_IO_UPDATE;
976 #endif
977 			GP_LOG_E ("setting configuration from %d to %d failed, but continuing...", port->pl->config, port->settings.usb.config);
978 		}
979 
980 		GP_LOG_D ("Changed usb.config from %d to %d", port->pl->config, port->settings.usb.config);
981 
982 		if (ifacereleased) {
983 			GP_LOG_D ("claiming interface %d", port->settings.usb.interface);
984 			LOG_ON_LIBUSB_E (libusb_claim_interface (port->pl->dh, port->settings.usb.interface));
985 		}
986 		/*
987 		 * Copy at once if something else fails so that this
988 		 * does not get re-applied
989 		 */
990 		port->pl->config = port->settings.usb.config;
991 		changedone = TRUE;
992 	}
993 
994 	/* This can be changed with interface claimed. (And I think it must be claimed.) */
995 	if (port->settings.usb.altsetting != port->pl->altsetting) {
996 		if (LOG_ON_LIBUSB_E (libusb_set_interface_alt_setting (port->pl->dh,
997 					port->settings.usb.interface, port->settings.usb.altsetting))) {
998 			int saved_errno = errno;
999 			gp_port_set_error (port,
1000 					   _("Could not set altsetting from %d "
1001 					     "to %d (%s)"),
1002 					   port->pl->altsetting,
1003 					   port->settings.usb.altsetting,
1004 					   strerror(saved_errno));
1005 			return GP_ERROR_IO_UPDATE;
1006 		}
1007 
1008 		GP_LOG_D ("Changed usb.altsetting from %d to %d", port->pl->altsetting, port->settings.usb.altsetting);
1009 		port->pl->altsetting = port->settings.usb.altsetting;
1010 		changedone = TRUE;
1011 	}
1012 
1013 	/* requeue the interrupts */
1014 	if (changedone)
1015 		gp_libusb1_queue_interrupt_urbs (port);
1016 	return GP_OK;
1017 }
1018 
1019 static int
gp_libusb1_find_ep(libusb_device * dev,int config,int interface,int altsetting,int direction,int type)1020 gp_libusb1_find_ep(libusb_device *dev, int config, int interface, int altsetting, int direction, int type)
1021 {
1022 	const struct libusb_interface_descriptor *intf;
1023 	struct libusb_config_descriptor *confdesc;
1024 	int i;
1025 
1026 	if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (dev, config, &confdesc)))
1027 		return -1;
1028 
1029 	intf = &confdesc->interface[interface].altsetting[altsetting];
1030 	for (i = 0; i < intf->bNumEndpoints; i++) {
1031 		if (((intf->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == direction) &&
1032 		    ((intf->endpoint[i].bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == type)) {
1033 			unsigned char ret;
1034 			ret = intf->endpoint[i].bEndpointAddress; /* intf is cleared after next line, copy epaddr! */
1035 			libusb_free_config_descriptor (confdesc);
1036 			return ret;
1037 		}
1038 	}
1039 	libusb_free_config_descriptor (confdesc);
1040 	return -1;
1041 }
1042 
1043 static int
gp_libusb1_find_first_altsetting(struct libusb_device * dev,int * config,int * interface,int * altsetting)1044 gp_libusb1_find_first_altsetting(struct libusb_device *dev, int *config, int *interface, int *altsetting)
1045 {
1046 	int i, i1, i2;
1047 	struct libusb_device_descriptor desc;
1048 
1049 	if (LOG_ON_LIBUSB_E (libusb_get_device_descriptor (dev, &desc)))
1050 		return -1;
1051 
1052 	for (i = 0; i < desc.bNumConfigurations; i++) {
1053 		struct libusb_config_descriptor *confdesc;
1054 
1055 		if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (dev, i, &confdesc)))
1056 			return -1;
1057 
1058 		for (i1 = 0; i1 < confdesc->bNumInterfaces; i1++)
1059 			for (i2 = 0; i2 < confdesc->interface[i1].num_altsetting; i2++)
1060 				if (confdesc->interface[i1].altsetting[i2].bNumEndpoints) {
1061 					*config = i;
1062 					*interface = i1;
1063 					*altsetting = i2;
1064 					libusb_free_config_descriptor (confdesc);
1065 
1066 					return 0;
1067 				}
1068 		libusb_free_config_descriptor (confdesc);
1069 	}
1070 	return -1;
1071 }
1072 
1073 static int
gp_libusb1_find_path_lib(GPPort * port)1074 gp_libusb1_find_path_lib(GPPort *port)
1075 {
1076 	char *s;
1077 	int d, busnr = 0, devnr = 0;
1078 	GPPortPrivateLibrary *pl;
1079 
1080 	C_PARAMS (port);
1081 
1082 	pl = port->pl;
1083 
1084 	s = strchr (port->settings.usb.port,':');
1085 	C_PARAMS (s && (s[1] != '\0'));
1086 	C_PARAMS (sscanf (s+1, "%d,%d", &busnr, &devnr) == 2); /* usb:%d,%d */
1087 
1088 	pl->nrofdevs = load_devicelist (port->pl);
1089 
1090 	for (d = 0; d < pl->nrofdevs; d++) {
1091 		struct libusb_config_descriptor *confdesc;
1092 		int config = -1, interface = -1, altsetting = -1;
1093 
1094 		if (busnr != libusb_get_bus_number (pl->devs[d]))
1095 			continue;
1096 		if (devnr != libusb_get_device_address (pl->devs[d]))
1097 			continue;
1098 
1099 		port->pl->d = pl->devs[d];
1100 
1101 		GP_LOG_D ("Found path %s", port->settings.usb.port);
1102 
1103 		/* Use the first config, interface and altsetting we find */
1104 		gp_libusb1_find_first_altsetting(pl->devs[d], &config, &interface, &altsetting);
1105 
1106 		if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (pl->devs[d], config, &confdesc)))
1107 			continue;
1108 
1109 		/* Set the defaults */
1110 		port->settings.usb.config = confdesc->bConfigurationValue;
1111 		port->settings.usb.interface = confdesc->interface[interface].altsetting[altsetting].bInterfaceNumber;
1112 		port->settings.usb.altsetting = confdesc->interface[interface].altsetting[altsetting].bAlternateSetting;
1113 
1114 		port->settings.usb.inep  = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_BULK);
1115 		port->settings.usb.outep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_OUT, LIBUSB_TRANSFER_TYPE_BULK);
1116 		port->settings.usb.intep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_INTERRUPT);
1117 
1118 		port->settings.usb.maxpacketsize = libusb_get_max_packet_size (pl->devs[d], port->settings.usb.inep);
1119 		GP_LOG_D ("Detected defaults: config %d, interface %d, altsetting %d, "
1120 			"inep %02x, outep %02x, intep %02x, class %02x, subclass %02x",
1121 			port->settings.usb.config,
1122 			port->settings.usb.interface,
1123 			port->settings.usb.altsetting,
1124 			port->settings.usb.inep,
1125 			port->settings.usb.outep,
1126 			port->settings.usb.intep,
1127 			confdesc->interface[interface].altsetting[altsetting].bInterfaceClass,
1128 			confdesc->interface[interface].altsetting[altsetting].bInterfaceSubClass
1129 			);
1130 		libusb_free_config_descriptor (confdesc);
1131 		return GP_OK;
1132 	}
1133 #if 0
1134 	gp_port_set_error (port, _("Could not find USB device "
1135 		"(vendor 0x%x, product 0x%x). Make sure this device "
1136 		"is connected to the computer."), idvendor, idproduct);
1137 #endif
1138 	return GP_ERROR_IO_USB_FIND;
1139 }
1140 static int
gp_libusb1_find_device_lib(GPPort * port,int idvendor,int idproduct)1141 gp_libusb1_find_device_lib(GPPort *port, int idvendor, int idproduct)
1142 {
1143 	char *s;
1144 	int d, busnr = 0, devnr = 0;
1145 	GPPortPrivateLibrary *pl;
1146 
1147 	C_PARAMS (port);
1148 
1149 	pl = port->pl;
1150 
1151 	s = strchr (port->settings.usb.port,':');
1152 	if (s && (s[1] != '\0')) { /* usb:%d,%d */
1153 		if (sscanf (s+1, "%d,%d", &busnr, &devnr) != 2) {
1154 			devnr = 0;
1155 			sscanf (s+1, "%d", &busnr);
1156 		}
1157 	}
1158 	/*
1159 	 * 0x0000 idvendor is not valid.
1160 	 * 0x0000 idproduct is ok.
1161 	 * Should the USB layer report that ? I don't know.
1162 	 * Better to check here.
1163 	 */
1164 	if (!idvendor) {
1165 		gp_port_set_error (port, _("The supplied vendor or product "
1166 			"id (0x%x,0x%x) is not valid."), idvendor, idproduct);
1167 		return GP_ERROR_BAD_PARAMETERS;
1168 	}
1169 
1170 	pl->nrofdevs = load_devicelist (port->pl);
1171 
1172 	for (d = 0; d < pl->nrofdevs; d++) {
1173 		struct libusb_config_descriptor *confdesc;
1174 		int config = -1, interface = -1, altsetting = -1;
1175 
1176 		if ((pl->descs[d].idVendor != idvendor) ||
1177 		    (pl->descs[d].idProduct != idproduct))
1178 			continue;
1179 
1180 		if (busnr && (busnr != libusb_get_bus_number (pl->devs[d])))
1181 			continue;
1182 		if (devnr && (devnr != libusb_get_device_address (pl->devs[d])))
1183 			continue;
1184 
1185 		port->pl->d = pl->devs[d];
1186 
1187 		GP_LOG_D ("Looking for USB device (vendor 0x%x, product 0x%x)... found.", idvendor, idproduct);
1188 
1189 		/* Use the first config, interface and altsetting we find */
1190 		gp_libusb1_find_first_altsetting(pl->devs[d], &config, &interface, &altsetting);
1191 
1192 		if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (pl->devs[d], config, &confdesc)))
1193 			continue;
1194 
1195 		/* Set the defaults */
1196 		if (confdesc->interface[interface].altsetting[altsetting].bInterfaceClass
1197 		    == LIBUSB_CLASS_MASS_STORAGE) {
1198 			GP_LOG_D ("USB device (vendor 0x%x, product 0x%x) is a mass"
1199 				  " storage device, and might not function with gphoto2."
1200 				  " Reference: %s", idvendor, idproduct, URL_USB_MASSSTORAGE);
1201 		}
1202 		port->settings.usb.config = confdesc->bConfigurationValue;
1203 		port->settings.usb.interface = confdesc->interface[interface].altsetting[altsetting].bInterfaceNumber;
1204 		port->settings.usb.altsetting = confdesc->interface[interface].altsetting[altsetting].bAlternateSetting;
1205 
1206 		port->settings.usb.inep  = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_BULK);
1207 		port->settings.usb.outep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_OUT, LIBUSB_TRANSFER_TYPE_BULK);
1208 		port->settings.usb.intep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_INTERRUPT);
1209 
1210 		port->settings.usb.maxpacketsize = libusb_get_max_packet_size (pl->devs[d], port->settings.usb.inep);
1211 		GP_LOG_D ("Detected defaults: config %d, interface %d, altsetting %d, "
1212 			  "inep %02x, outep %02x, intep %02x, class %02x, subclass %02x",
1213 			port->settings.usb.config,
1214 			port->settings.usb.interface,
1215 			port->settings.usb.altsetting,
1216 			port->settings.usb.inep,
1217 			port->settings.usb.outep,
1218 			port->settings.usb.intep,
1219 			confdesc->interface[interface].altsetting[altsetting].bInterfaceClass,
1220 			confdesc->interface[interface].altsetting[altsetting].bInterfaceSubClass
1221 			);
1222 		libusb_free_config_descriptor (confdesc);
1223 		return GP_OK;
1224 	}
1225 #if 0
1226 	gp_port_set_error (port, _("Could not find USB device "
1227 		"(vendor 0x%x, product 0x%x). Make sure this device "
1228 		"is connected to the computer."), idvendor, idproduct);
1229 #endif
1230 	return GP_ERROR_IO_USB_FIND;
1231 }
1232 
1233 /* This function reads the Microsoft OS Descriptor and looks inside to
1234  * find if it is a MTP device. This is the similar to the way that
1235  * Windows Media Player 10 uses.
1236  * It is documented to some degree on various internet pages.
1237  */
1238 static int
gp_libusb1_match_mtp_device(struct libusb_device * dev,int * configno,int * interfaceno,int * altsettingno)1239 gp_libusb1_match_mtp_device(struct libusb_device *dev,int *configno, int *interfaceno, int *altsettingno)
1240 {
1241 	/* Marcus: Avoid this probing altogether, its too unstable on some devices */
1242 	return 0;
1243 
1244 #if 0
1245 	char buf[1000], cmd;
1246 	int ret,i,i1,i2, xifaces,xnocamifaces;
1247 	usb_dev_handle *devh;
1248 
1249 	/* All of them are "vendor specific" device class */
1250 #if 0
1251 	if ((desc.bDeviceClass!=0xff) && (desc.bDeviceClass!=0))
1252 		return 0;
1253 #endif
1254 	if (dev->config) {
1255 		xifaces = xnocamifaces = 0;
1256 		for (i = 0; i < desc.bNumConfigurations; i++) {
1257 			unsigned int j;
1258 
1259 			for (j = 0; j < dev->config[i].bNumInterfaces; j++) {
1260 				int k;
1261 				xifaces++;
1262 
1263 				for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) {
1264 					struct usb_interface_descriptor *intf = &dev->config[i].interface[j].altsetting[k];
1265 					if (	(intf->bInterfaceClass == LIBUSB_CLASS_HID)	||
1266 						(intf->bInterfaceClass == LIBUSB_CLASS_PRINTER)	||
1267 						(intf->bInterfaceClass == LIBUSB_CLASS_AUDIO)	||
1268 						(intf->bInterfaceClass == LIBUSB_CLASS_HUB)	||
1269 						(intf->bInterfaceClass == LIBUSB_CLASS_COMM)	||
1270 						(intf->bInterfaceClass == 0xe0)	/* wireless/bluetooth*/
1271 					)
1272 						xnocamifaces++;
1273 				}
1274 			}
1275 		}
1276 	}
1277 	if (xifaces == xnocamifaces) /* only non-camera ifaces */
1278 		return 0;
1279 
1280 	devh = usb_open (dev);
1281 	if (!devh)
1282 		return 0;
1283 
1284 	/*
1285 	 * Loop over the device configurations and interfaces. Nokia MTP-capable
1286 	 * handsets (possibly others) typically have the string "MTP" in their
1287 	 * MTP interface descriptions, that's how they can be detected, before
1288 	 * we try the more esoteric "OS descriptors" (below).
1289 	 */
1290 	if (dev->config) {
1291 		for (i = 0; i < desc.bNumConfigurations; i++) {
1292 			unsigned int j;
1293 
1294 			for (j = 0; j < dev->config[i].bNumInterfaces; j++) {
1295 				int k;
1296 				for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) {
1297 					buf[0] = '\0';
1298 					ret = usb_get_string_simple(devh,
1299 						dev->config[i].interface[j].altsetting[k].iInterface,
1300 						(char *) buf,
1301 						1024);
1302 					if (ret < 3)
1303 						continue;
1304 					if (strcmp((char *) buf, "MTP") == 0) {
1305 						GP_LOG_D ("Configuration %d, interface %d, altsetting %d:\n", i, j, k);
1306 						GP_LOG_D ("   Interface description contains the string \"MTP\"\n");
1307 						GP_LOG_D ("   Device recognized as MTP, no further probing.\n");
1308 						goto found;
1309 					}
1310 				}
1311 			}
1312 		}
1313 	}
1314 	/* get string descriptor at 0xEE */
1315 	ret = usb_get_descriptor (devh, 0x03, 0xee, buf, sizeof(buf));
1316 	if (ret > 0) GP_LOG_DATA (buf, ret, "get_MS_OSD");
1317 	if (ret < 10) goto errout;
1318 	if (!((buf[2] == 'M') && (buf[4]=='S') && (buf[6]=='F') && (buf[8]=='T')))
1319 		goto errout;
1320 	cmd = buf[16];
1321 	ret = usb_control_msg (devh, USB_ENDPOINT_IN|USB_RECIP_DEVICE|LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 4, buf, sizeof(buf), 1000);
1322 	if (ret == -1) {
1323 		GP_LOG_E ("control message says %d\n", ret);
1324 		goto errout;
1325 	}
1326 	if (buf[0] != 0x28) {
1327 		GP_LOG_E ("ret is %d, buf[0] is %x\n", ret, buf[0]);
1328 		goto errout;
1329 	}
1330 	if (ret > 0) GP_LOG_DATA (buf, ret, "get_MS_ExtDesc");
1331 	if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
1332 		GP_LOG_E ("buf at 0x12 is %02x%02x%02x\n", buf[0x12], buf[0x13], buf[0x14]);
1333 		goto errout;
1334 	}
1335 	ret = usb_control_msg (devh, USB_ENDPOINT_IN|USB_RECIP_DEVICE|LIBUSB_REQUEST_TYPE_VENDOR, cmd, 0, 5, buf, sizeof(buf), 1000);
1336 	if (ret == -1) goto errout;
1337 	if (buf[0] != 0x28) {
1338 		GP_LOG_E ("ret is %d, buf[0] is %x\n", ret, buf[0]);
1339 		goto errout;
1340 	}
1341 	if (ret > 0) GP_LOG_DATA (buf, ret, "get_MS_ExtProp");
1342 	if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
1343 		GP_LOG_E ("buf at 0x12 is %02x%02x%02x\n", buf[0x12], buf[0x13], buf[0x14]);
1344 		goto errout;
1345 	}
1346 
1347 found:
1348 	usb_close (devh);
1349 
1350 	/* Now chose a nice interface for us to use ... Just take the first. */
1351 
1352 	if (desc.bNumConfigurations > 1)
1353 		GP_LOG_E ("The device has %d configurations!\n", desc.bNumConfigurations);
1354 	for (i = 0; i < desc.bNumConfigurations; i++) {
1355 		struct usb_config_descriptor *config =
1356 			&dev->config[i];
1357 
1358 		if (config->bNumInterfaces > 1)
1359 			GP_LOG_E ("The configuration has %d interfaces!\n", config->bNumInterfaces);
1360 		for (i1 = 0; i1 < config->bNumInterfaces; i1++) {
1361 			struct usb_interface *interface =
1362 				&config->interface[i1];
1363 
1364 			if (interface->num_altsetting > 1)
1365 				GP_LOG_E ("The interface has %d altsettings!\n", interface->num_altsetting);
1366 			for (i2 = 0; i2 < interface->num_altsetting; i2++) {
1367 				*configno = i;
1368 				*interfaceno = i1;
1369 				*altsettingno = i2;
1370 				return 1;
1371 			}
1372 		}
1373 	}
1374 	return 1;
1375 errout:
1376 	usb_close (devh);
1377 	return 0;
1378 #endif
1379 }
1380 
1381 static int
gp_libusb1_match_device_by_class(struct libusb_device * dev,int class,int subclass,int protocol,int * configno,int * interfaceno,int * altsettingno)1382 gp_libusb1_match_device_by_class(struct libusb_device *dev, int class, int subclass, int protocol, int *configno, int *interfaceno, int *altsettingno)
1383 {
1384 	int i, i1, i2;
1385 	struct libusb_device_descriptor desc;
1386 
1387 	if (class == 666) /* Special hack for MTP devices with MS OS descriptors. */
1388 		return gp_libusb1_match_mtp_device (dev, configno, interfaceno, altsettingno);
1389 
1390 	if (LOG_ON_LIBUSB_E (libusb_get_device_descriptor(dev, &desc)))
1391 		return 0;
1392 
1393 	if (desc.bDeviceClass == class &&
1394 	    (subclass == -1 ||
1395 	     desc.bDeviceSubClass == subclass) &&
1396 	    (protocol == -1 ||
1397 	     desc.bDeviceProtocol == protocol))
1398 		return 1;
1399 
1400 
1401 	for (i = 0; i < desc.bNumConfigurations; i++) {
1402 		struct libusb_config_descriptor *config;
1403 
1404 		if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (dev, i, &config)))
1405 			continue;
1406 
1407 		for (i1 = 0; i1 < config->bNumInterfaces; i1++) {
1408 			const struct libusb_interface *interface =
1409 				&config->interface[i1];
1410 
1411 			for (i2 = 0; i2 < interface->num_altsetting; i2++) {
1412 				const struct libusb_interface_descriptor *altsetting =
1413 					&interface->altsetting[i2];
1414 
1415 				if (altsetting->bInterfaceClass == class &&
1416 				    (subclass == -1 ||
1417 				     altsetting->bInterfaceSubClass == subclass) &&
1418 				    (protocol == -1 ||
1419 				     altsetting->bInterfaceProtocol == protocol)) {
1420 					*configno = i;
1421 					*interfaceno = i1;
1422 					*altsettingno = i2;
1423 
1424 					libusb_free_config_descriptor (config);
1425 					return 2;
1426 				}
1427 			}
1428 		}
1429 		libusb_free_config_descriptor (config);
1430 	}
1431 	return 0;
1432 }
1433 
1434 static int
gp_libusb1_find_device_by_class_lib(GPPort * port,int class,int subclass,int protocol)1435 gp_libusb1_find_device_by_class_lib(GPPort *port, int class, int subclass, int protocol)
1436 {
1437 	char *s;
1438 	int d, busnr = 0, devnr = 0;
1439 	GPPortPrivateLibrary *pl;
1440 
1441 	C_PARAMS (port);
1442 
1443 	pl = port->pl;
1444 
1445 	s = strchr (port->settings.usb.port,':');
1446 	if (s && (s[1] != '\0')) { /* usb:%d,%d */
1447 		if (sscanf (s+1, "%d,%d", &busnr, &devnr) != 2) {
1448 			devnr = 0;
1449 			sscanf (s+1, "%d", &busnr);
1450 		}
1451 	}
1452 	/*
1453 	 * 0x00 class is not valid.
1454 	 * 0x00 subclass and protocol is ok.
1455 	 * Should the USB layer report that ? I don't know.
1456 	 * Better to check here.
1457 	 */
1458 	C_PARAMS (class);
1459 
1460 	pl->nrofdevs = load_devicelist (port->pl);
1461 	for (d = 0; d < pl->nrofdevs; d++) {
1462 		struct libusb_config_descriptor *confdesc;
1463 		int i, ret, config = -1, interface = -1, altsetting = -1;
1464 
1465 		if (busnr && (busnr != libusb_get_bus_number (pl->devs[d])))
1466 			continue;
1467 		if (devnr && (devnr != libusb_get_device_address (pl->devs[d])))
1468 			continue;
1469 
1470 		GP_LOG_D ("Looking for USB device (class 0x%x, subclass, 0x%x, protocol 0x%x)...",
1471 			  class, subclass, protocol);
1472 
1473 		ret = gp_libusb1_match_device_by_class(pl->devs[d], class, subclass, protocol, &config, &interface, &altsetting);
1474 		if (!ret)
1475 			continue;
1476 
1477 		port->pl->d = pl->devs[d];
1478 		GP_LOG_D ("Found USB class device (class 0x%x, subclass, 0x%x, protocol 0x%x)",
1479 			  class, subclass, protocol);
1480 
1481 		if (LOG_ON_LIBUSB_E (libusb_get_config_descriptor (pl->devs[d], config, &confdesc)))
1482 			continue;
1483 
1484 		/* Set the defaults */
1485 		port->settings.usb.config = confdesc->bConfigurationValue;
1486 		port->settings.usb.interface = confdesc->interface[interface].altsetting[altsetting].bInterfaceNumber;
1487 		port->settings.usb.altsetting = confdesc->interface[interface].altsetting[altsetting].bAlternateSetting;
1488 
1489 		port->settings.usb.inep  = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_BULK);
1490 		port->settings.usb.outep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_OUT, LIBUSB_TRANSFER_TYPE_BULK);
1491 		port->settings.usb.intep = gp_libusb1_find_ep(pl->devs[d], config, interface, altsetting, LIBUSB_ENDPOINT_IN, LIBUSB_TRANSFER_TYPE_INTERRUPT);
1492 		port->settings.usb.maxpacketsize = 0;
1493 		GP_LOG_D ("inep to look for is %02x", port->settings.usb.inep);
1494 		for (i=0;i<confdesc->interface[interface].altsetting[altsetting].bNumEndpoints;i++) {
1495 			if (port->settings.usb.inep == confdesc->interface[interface].altsetting[altsetting].endpoint[i].bEndpointAddress) {
1496 				port->settings.usb.maxpacketsize = confdesc->interface[interface].altsetting[altsetting].endpoint[i].wMaxPacketSize;
1497 				break;
1498 			}
1499 		}
1500 		GP_LOG_D ("Detected defaults: config %d, interface %d, altsetting %d, "
1501 			  "idVendor ID %04x, idProduct %04x, inep %02x, outep %02x, intep %02x",
1502 			port->settings.usb.config,
1503 			port->settings.usb.interface,
1504 			port->settings.usb.altsetting,
1505 			pl->descs[d].idVendor,
1506 			pl->descs[d].idProduct,
1507 			port->settings.usb.inep,
1508 			port->settings.usb.outep,
1509 			port->settings.usb.intep
1510 		);
1511 		libusb_free_config_descriptor (confdesc);
1512 		return GP_OK;
1513 	}
1514 #if 0
1515 	gp_port_set_error (port, _("Could not find USB device "
1516 		"(class 0x%x, subclass 0x%x, protocol 0x%x). Make sure this device "
1517 		"is connected to the computer."), class, subclass, protocol);
1518 #endif
1519 	return GP_ERROR_IO_USB_FIND;
1520 }
1521 
1522 GPPortOperations *
gp_port_library_operations(void)1523 gp_port_library_operations (void)
1524 {
1525 	GPPortOperations *ops;
1526 
1527 	ops = calloc (1, sizeof (GPPortOperations));
1528 	if (!ops)
1529 		return (NULL);
1530 
1531 	ops->init   = gp_libusb1_init;
1532 	ops->exit   = gp_libusb1_exit;
1533 	ops->open   = gp_libusb1_open;
1534 	ops->close  = gp_libusb1_close;
1535 	ops->read   = gp_libusb1_read;
1536 	ops->reset  = gp_libusb1_reset;
1537 	ops->write  = gp_libusb1_write;
1538 	ops->check_int = gp_libusb1_check_int;
1539 	ops->update = gp_libusb1_update;
1540 	ops->clear_halt = gp_libusb1_clear_halt_lib;
1541 	ops->msg_write  = gp_libusb1_msg_write_lib;
1542 	ops->msg_read   = gp_libusb1_msg_read_lib;
1543 	ops->msg_interface_write  = gp_libusb1_msg_interface_write_lib;
1544 	ops->msg_interface_read   = gp_libusb1_msg_interface_read_lib;
1545 	ops->msg_class_write  = gp_libusb1_msg_class_write_lib;
1546 	ops->msg_class_read   = gp_libusb1_msg_class_read_lib;
1547 	ops->find_device = gp_libusb1_find_device_lib;
1548 	ops->find_device_by_class = gp_libusb1_find_device_by_class_lib;
1549 
1550 	return (ops);
1551 }
1552