libusb1-glue.c revision bda39ab9dec06c34236d1d7b01492fe13ca3d595
1/*
2 * \file libusb1-glue.c
3 * Low-level USB interface glue towards libusb.
4 *
5 * Copyright (C) 2005-2007 Richard A. Low <richard@wentnet.com>
6 * Copyright (C) 2005-2012 Linus Walleij <triad@df.lth.se>
7 * Copyright (C) 2006-2012 Marcus Meissner
8 * Copyright (C) 2007 Ted Bullock
9 * Copyright (C) 2008 Chris Bagwell <chris@cnpbagwell.com>
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 * Lesser General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the
23 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 * Boston, MA 02111-1307, USA.
25 *
26 * Created by Richard Low on 24/12/2005. (as mtp-utils.c)
27 * Modified by Linus Walleij 2006-03-06
28 *  (Notice that Anglo-Saxons use little-endian dates and Swedes
29 *   use big-endian dates.)
30 *
31 */
32#include "config.h"
33#include "libmtp.h"
34#include "libusb-glue.h"
35#include "device-flags.h"
36#include "util.h"
37#include "ptp.h"
38
39#include <errno.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <unistd.h>
44
45#include "ptp-pack.c"
46
47/* Aha, older libusb does not have USB_CLASS_PTP */
48#ifndef USB_CLASS_PTP
49#define USB_CLASS_PTP 6
50#endif
51
52/*
53 * Default USB timeout length.  This can be overridden as needed
54 * but should start with a reasonable value so most common
55 * requests can be completed.  The original value of 4000 was
56 * not long enough for large file transfer.  Also, players can
57 * spend a bit of time collecting data.  Higher values also
58 * make connecting/disconnecting more reliable.
59 */
60#define USB_TIMEOUT_DEFAULT     20000
61#define USB_TIMEOUT_LONG        60000
62static inline int get_timeout(PTP_USB* ptp_usb)
63{
64  if (FLAG_LONG_TIMEOUT(ptp_usb)) {
65    return USB_TIMEOUT_LONG;
66  }
67  return USB_TIMEOUT_DEFAULT;
68}
69
70/* USB Feature selector HALT */
71#ifndef USB_FEATURE_HALT
72#define USB_FEATURE_HALT	0x00
73#endif
74
75/* Internal data types */
76struct mtpdevice_list_struct {
77  libusb_device *device;
78  PTPParams *params;
79  PTP_USB *ptp_usb;
80  uint32_t bus_location;
81  struct mtpdevice_list_struct *next;
82};
83typedef struct mtpdevice_list_struct mtpdevice_list_t;
84
85static const LIBMTP_device_entry_t mtp_device_table[] = {
86/* We include an .h file which is shared between us and libgphoto2 */
87#include "music-players.h"
88};
89static const int mtp_device_table_size = sizeof(mtp_device_table) / sizeof(LIBMTP_device_entry_t);
90
91// Local functions
92static void init_usb();
93static void close_usb(PTP_USB* ptp_usb);
94static int find_interface_and_endpoints(libusb_device *dev,
95					uint8_t *interface,
96					int* inep,
97					int* inep_maxpacket,
98					int* outep,
99					int* outep_maxpacket,
100					int* intep);
101static void clear_stall(PTP_USB* ptp_usb);
102static int init_ptp_usb (PTPParams* params, PTP_USB* ptp_usb, libusb_device* dev);
103static short ptp_write_func (unsigned long,PTPDataHandler*,void *data,unsigned long*);
104static short ptp_read_func (unsigned long,PTPDataHandler*,void *data,unsigned long*,int);
105static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status);
106
107/**
108 * Get a list of the supported USB devices.
109 *
110 * The developers depend on users of this library to constantly
111 * add in to the list of supported devices. What we need is the
112 * device name, USB Vendor ID (VID) and USB Product ID (PID).
113 * put this into a bug ticket at the project homepage, please.
114 * The VID/PID is used to let e.g. udev lift the device to
115 * console userspace access when it's plugged in.
116 *
117 * @param devices a pointer to a pointer that will hold a device
118 *        list after the call to this function, if it was
119 *        successful.
120 * @param numdevs a pointer to an integer that will hold the number
121 *        of devices in the device list if the call was successful.
122 * @return 0 if the list was successfull retrieved, any other
123 *        value means failure.
124 */
125int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const devices, int * const numdevs)
126{
127  *devices = (LIBMTP_device_entry_t *) &mtp_device_table;
128  *numdevs = mtp_device_table_size;
129  return 0;
130}
131
132
133static void init_usb()
134{
135  /*
136   * Some additional libusb debugging please.
137   * We use the same level debug between MTP and USB.
138   */
139  libusb_init(NULL);
140
141  if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0)
142    libusb_set_debug(NULL,9);
143}
144
145/**
146 * Small recursive function to append a new usb_device to the linked list of
147 * USB MTP devices
148 * @param devlist dynamic linked list of pointers to usb devices with MTP
149 *        properties, to be extended with new device.
150 * @param newdevice the new device to add.
151 * @param bus_location bus for this device.
152 * @return an extended array or NULL on failure.
153 */
154static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist,
155						  libusb_device *newdevice,
156
157						  uint32_t bus_location)
158{
159  mtpdevice_list_t *new_list_entry;
160
161  new_list_entry = (mtpdevice_list_t *) malloc(sizeof(mtpdevice_list_t));
162  if (new_list_entry == NULL) {
163    return NULL;
164  }
165  // Fill in USB device, if we *HAVE* to make a copy of the device do it here.
166  new_list_entry->device = newdevice;
167  new_list_entry->bus_location = bus_location;
168  new_list_entry->next = NULL;
169
170  if (devlist == NULL) {
171    return new_list_entry;
172  } else {
173    mtpdevice_list_t *tmp = devlist;
174    while (tmp->next != NULL) {
175      tmp = tmp->next;
176    }
177    tmp->next = new_list_entry;
178  }
179  return devlist;
180}
181
182/**
183 * Small recursive function to free dynamic memory allocated to the linked list
184 * of USB MTP devices
185 * @param devlist dynamic linked list of pointers to usb devices with MTP
186 * properties.
187 * @return nothing
188 */
189static void free_mtpdevice_list(mtpdevice_list_t *devlist)
190{
191  mtpdevice_list_t *tmplist = devlist;
192
193  if (devlist == NULL)
194    return;
195  while (tmplist != NULL) {
196    mtpdevice_list_t *tmp = tmplist;
197    tmplist = tmplist->next;
198    // Do not free() the fields (ptp_usb, params)! These are used elsewhere.
199    free(tmp);
200  }
201  return;
202}
203
204/**
205 * This checks if a device has an MTP descriptor. The descriptor was
206 * elaborated about in gPhoto bug 1482084, and some official documentation
207 * with no strings attached was published by Microsoft at
208 * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC
209 *
210 * @param dev a device struct from libusb.
211 * @param dumpfile set to non-NULL to make the descriptors dump out
212 *        to this file in human-readable hex so we can scruitinze them.
213 * @return 1 if the device is MTP compliant, 0 if not.
214 */
215static int probe_device_descriptor(libusb_device *dev, FILE *dumpfile)
216{
217  libusb_device_handle *devh;
218  unsigned char buf[1024], cmd;
219  int i;
220  int ret;
221  /* This is to indicate if we find some vendor interface */
222  int found_vendor_spec_interface = 0;
223  struct libusb_device_descriptor desc;
224
225  ret = libusb_get_device_descriptor (dev, &desc);
226  if (ret != LIBUSB_SUCCESS) return 0;
227  /*
228   * Don't examine devices that are not likely to
229   * contain any MTP interface, update this the day
230   * you find some weird combination...
231   */
232  if (!(desc.bDeviceClass == LIBUSB_CLASS_PER_INTERFACE ||
233	desc.bDeviceClass == LIBUSB_CLASS_COMM ||
234	desc.bDeviceClass == LIBUSB_CLASS_PTP ||
235	desc.bDeviceClass == 0xEF ||	/* Intf. Association Desc.*/
236	desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC)) {
237    return 0;
238  }
239
240  /*
241   * Attempt to open Device on this port
242   *
243   * TODO: is there a way to check the number of endpoints etc WITHOUT
244   * opening the device? Some color calibration devices are REALLY
245   * sensitive to this, and I found a Canon custom scanner that doesn't
246   * like it at all either :-(
247   */
248  ret = libusb_open(dev, &devh);
249  if (ret != LIBUSB_SUCCESS) {
250    /* Could not open this device */
251    return 0;
252  }
253
254  /*
255   * Loop over the device configurations and interfaces. Nokia MTP-capable
256   * handsets (possibly others) typically have the string "MTP" in their
257   * MTP interface descriptions, that's how they can be detected, before
258   * we try the more esoteric "OS descriptors" (below).
259   */
260  for (i = 0; i < desc.bNumConfigurations; i++) {
261     uint8_t j;
262     struct libusb_config_descriptor *config;
263
264     ret = libusb_get_config_descriptor (dev, i, &config);
265     if (ret != LIBUSB_SUCCESS) {
266       LIBMTP_INFO("configdescriptor %d get failed with ret %d in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n", i, ret);
267       continue;
268     }
269
270     for (j = 0; j < config->bNumInterfaces; j++) {
271        int k;
272        for (k = 0; k < config->interface[j].num_altsetting; k++) {
273	  /* Current interface descriptor */
274	  const struct libusb_interface_descriptor *intf =
275	    &config->interface[j].altsetting[k];
276
277	  /*
278	   * MTP interfaces have three endpoints, two bulk and one
279	   * interrupt. Don't probe anything else.
280	   */
281	  if (intf->bNumEndpoints != 3)
282	    continue;
283
284	  /*
285	   * We only want to probe for the OS descriptor if the
286	   * device is LIBUSB_CLASS_VENDOR_SPEC or one of the interfaces
287	   * in it is, so flag if we find an interface like this.
288	   */
289	  if (intf->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC) {
290	    found_vendor_spec_interface = 1;
291	  }
292
293	  /*
294	   * Check for Still Image Capture class with PIMA 15740 protocol,
295	   * also known as PTP
296	   */
297#if 0
298	  if (intf->bInterfaceClass == LIBUSB_CLASS_PTP
299	      && intf->bInterfaceSubClass == 0x01
300	      && intf->bInterfaceProtocol == 0x01) {
301	    if (dumpfile != NULL) {
302	      fprintf(dumpfile, "   Found PTP device, check vendor "
303		      "extension...\n");
304	    }
305	    /*
306	     * This is where we may insert code to open a PTP
307	     * session and query the vendor extension ID to see
308	     * if it is 0xffffffff, i.e. MTP according to the spec.
309	     */
310	    if (was_mtp_extension) {
311	      libusb_close(devh);
312	      return 1;
313	    }
314	  }
315#endif
316
317	  /*
318	   * Next we search for the MTP substring in the interface name.
319	   * For example : "RIM MS/MTP" should work.
320	   */
321          buf[0] = '\0';
322          ret = libusb_get_string_descriptor_ascii(devh,
323				      config->interface[j].altsetting[k].iInterface,
324				      buf,
325				      1024);
326	  if (ret < 3)
327	    continue;
328          if (strstr((char *) buf, "MTP") != NULL) {
329	    if (dumpfile != NULL) {
330              fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k);
331	      fprintf(dumpfile, "   Interface description contains the string \"MTP\"\n");
332	      fprintf(dumpfile, "   Device recognized as MTP, no further probing.\n");
333	    }
334            libusb_free_config_descriptor (config);
335            libusb_close(devh);
336            return 1;
337          }
338          if (libusb_kernel_driver_active(devh, config->interface[j].altsetting[k].iInterface))
339	  {
340	    /*
341	     * Specifically avoid probing anything else than USB mass storage devices
342	     * and non-associated drivers in Linux.
343	     */
344	    if (config->interface[j].altsetting[k].bInterfaceClass !=
345		LIBUSB_CLASS_MASS_STORAGE) {
346	      LIBMTP_INFO("avoid probing device using attached kernel interface\n");
347              libusb_free_config_descriptor (config);
348	      return 0;
349	    }
350	  }
351        }
352      }
353    }
354
355  /*
356   * Only probe for OS descriptor if the device is vendor specific
357   * or one of the interfaces found is.
358   */
359  if (desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC ||
360      found_vendor_spec_interface) {
361
362    /* Read the special descriptor */
363    ret = libusb_get_descriptor(devh, 0x03, 0xee, buf, sizeof(buf));
364
365    /*
366     * If something failed we're probably stalled to we need
367     * to clear the stall off the endpoint and say this is not
368     * MTP.
369     */
370    if (ret < 0) {
371      /* EP0 is the default control endpoint */
372      libusb_clear_halt (devh, 0);
373      libusb_close(devh);
374      return 0;
375    }
376
377    // Dump it, if requested
378    if (dumpfile != NULL && ret > 0) {
379      fprintf(dumpfile, "Microsoft device descriptor 0xee:\n");
380      data_dump_ascii(dumpfile, buf, ret, 16);
381    }
382
383    /* Check if descriptor length is at least 10 bytes */
384    if (ret < 10) {
385      libusb_close(devh);
386      return 0;
387    }
388
389    /* Check if this device has a Microsoft Descriptor */
390    if (!((buf[2] == 'M') && (buf[4] == 'S') &&
391	  (buf[6] == 'F') && (buf[8] == 'T'))) {
392      libusb_close(devh);
393      return 0;
394    }
395
396    /* Check if device responds to control message 1 or if there is an error */
397    cmd = buf[16];
398    ret = libusb_control_transfer (devh,
399			   LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
400			   cmd,
401			   0,
402			   4,
403			   buf,
404			   sizeof(buf),
405			   USB_TIMEOUT_DEFAULT);
406
407    // Dump it, if requested
408    if (dumpfile != NULL && ret > 0) {
409      fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd);
410      data_dump_ascii(dumpfile, buf, ret, 16);
411    }
412
413    /* If this is true, the device either isn't MTP or there was an error */
414    if (ret <= 0x15) {
415      /* TODO: If there was an error, flag it and let the user know somehow */
416      /* if(ret == -1) {} */
417      libusb_close(devh);
418      return 0;
419    }
420
421    /* Check if device is MTP or if it is something like a USB Mass Storage
422       device with Janus DRM support */
423    if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
424      libusb_close(devh);
425      return 0;
426    }
427
428    /* After this point we are probably dealing with an MTP device */
429
430    /*
431     * Check if device responds to control message 2, which is
432     * the extended device parameters. Most devices will just
433     * respond with a copy of the same message as for the first
434     * message, some respond with zero-length (which is OK)
435     * and some with pure garbage. We're not parsing the result
436     * so this is not very important.
437     */
438    ret = libusb_control_transfer (devh,
439			   LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
440			   cmd,
441			   0,
442			   5,
443			   buf,
444			   sizeof(buf),
445			   USB_TIMEOUT_DEFAULT);
446
447    // Dump it, if requested
448    if (dumpfile != NULL && ret > 0) {
449      fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd);
450      data_dump_ascii(dumpfile, buf, ret, 16);
451    }
452
453    /* If this is true, the device errored against control message 2 */
454    if (ret == -1) {
455      /* TODO: Implement callback function to let managing program know there
456	 was a problem, along with description of the problem */
457      LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and "
458		   "ProductID:%04x encountered an error responding to "
459		   "control message 2.\n"
460		   "Problems may arrise but continuing\n",
461		   desc.idVendor, desc.idProduct);
462    } else if (dumpfile != NULL && ret == 0) {
463      fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n");
464    } else if (dumpfile != NULL) {
465      fprintf(dumpfile, "Device responds to control message 2 with some data.\n");
466    }
467    /* Close the USB device handle */
468    libusb_close(devh);
469    return 1;
470  }
471
472  /* Close the USB device handle */
473  libusb_close(devh);
474  return 0;
475}
476
477/**
478 * This function scans through the connected usb devices on a machine and
479 * if they match known Vendor and Product identifiers appends them to the
480 * dynamic array mtp_device_list. Be sure to call
481 * <code>free_mtpdevice_list(mtp_device_list)</code> when you are done
482 * with it, assuming it is not NULL.
483 * @param mtp_device_list dynamic array of pointers to usb devices with MTP
484 *        properties (if this list is not empty, new entries will be appended
485 *        to the list).
486 * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list
487 *        appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no
488 *        devices have been found.
489 */
490static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list)
491{
492  ssize_t nrofdevs;
493  libusb_device **devs = NULL;
494  int ret, i;
495
496  init_usb();
497
498  nrofdevs = libusb_get_device_list (NULL, &devs);
499  for (i = 0; i < nrofdevs ; i++) {
500      libusb_device *dev = devs[i];
501      struct libusb_device_descriptor desc;
502
503      ret = libusb_get_device_descriptor(dev, &desc);
504      if (ret != LIBUSB_SUCCESS) continue;
505
506      if (desc.bDeviceClass != LIBUSB_CLASS_HUB) {
507	int i;
508        int found = 0;
509
510	// First check if we know about the device already.
511	// Devices well known to us will not have their descriptors
512	// probed, it caused problems with some devices.
513        for(i = 0; i < mtp_device_table_size; i++) {
514          if(desc.idVendor == mtp_device_table[i].vendor_id &&
515            desc.idProduct == mtp_device_table[i].product_id) {
516            /* Append this usb device to the MTP device list */
517            *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
518							dev,
519							libusb_get_bus_number(dev));
520            found = 1;
521            break;
522          }
523        }
524	// If we didn't know it, try probing the "OS Descriptor".
525        if (!found) {
526          if (probe_device_descriptor(dev, NULL)) {
527            /* Append this usb device to the MTP USB Device List */
528            *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
529							dev,
530							libusb_get_bus_number(dev));
531          }
532          /*
533	   * By thomas_-_s: Also append devices that are no MTP but PTP devices
534	   * if this is commented out.
535	   */
536	  /*
537	  else {
538	    // Check whether the device is no USB hub but a PTP.
539	    if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == LIBUSB_CLASS_PTP && dev->descriptor.bDeviceClass != LIBUSB_CLASS_HUB ) {
540	      *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location);
541	    }
542          }
543	  */
544        }
545      }
546    }
547
548  /* If nothing was found we end up here. */
549  if(*mtp_device_list == NULL) {
550    return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
551  }
552  return LIBMTP_ERROR_NONE;
553}
554
555/**
556 * Checks if a specific device with a certain bus and device
557 * number has an MTP type device descriptor.
558 *
559 * @param busno the bus number of the device to check
560 * @param deviceno the device number of the device to check
561 * @return 1 if the device is MTP else 0
562 */
563int LIBMTP_Check_Specific_Device(int busno, int devno)
564{
565  ssize_t nrofdevs;
566  libusb_device **devs = NULL;
567  int i;
568
569  init_usb();
570
571  nrofdevs = libusb_get_device_list (NULL, &devs);
572  for (i = 0; i < nrofdevs ; i++ ) {
573
574    if (libusb_get_bus_number(devs[i]) != busno)
575      continue;
576    if (libusb_get_device_address(devs[i]) != devno)
577      continue;
578
579      if (probe_device_descriptor(devs[i], NULL))
580	return 1;
581  }
582  return 0;
583}
584
585/**
586 * Detect the raw MTP device descriptors and return a list of
587 * of the devices found.
588 *
589 * @param devices a pointer to a variable that will hold
590 *        the list of raw devices found. This may be NULL
591 *        on return if the number of detected devices is zero.
592 *        The user shall simply <code>free()</code> this
593 *        variable when finished with the raw devices,
594 *        in order to release memory.
595 * @param numdevs a pointer to an integer that will hold
596 *        the number of devices in the list. This may
597 *        be 0.
598 * @return 0 if successful, any other value means failure.
599 */
600LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices,
601			      int * numdevs)
602{
603  mtpdevice_list_t *devlist = NULL;
604  mtpdevice_list_t *dev;
605  LIBMTP_error_number_t ret;
606  LIBMTP_raw_device_t *retdevs;
607  int devs = 0;
608  int i, j;
609
610  ret = get_mtp_usb_device_list(&devlist);
611  if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) {
612    *devices = NULL;
613    *numdevs = 0;
614    return ret;
615  } else if (ret != LIBMTP_ERROR_NONE) {
616    LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() "
617	    "error code: %d on line %d\n", ret, __LINE__);
618    return ret;
619  }
620
621  // Get list size
622  dev = devlist;
623  while (dev != NULL) {
624    devs++;
625    dev = dev->next;
626  }
627  if (devs == 0) {
628    *devices = NULL;
629    *numdevs = 0;
630    return LIBMTP_ERROR_NONE;
631  }
632  // Conjure a device list
633  retdevs = (LIBMTP_raw_device_t *) malloc(sizeof(LIBMTP_raw_device_t) * devs);
634  if (retdevs == NULL) {
635    // Out of memory
636    *devices = NULL;
637    *numdevs = 0;
638    return LIBMTP_ERROR_MEMORY_ALLOCATION;
639  }
640  dev = devlist;
641  i = 0;
642  while (dev != NULL) {
643    int device_known = 0;
644    struct libusb_device_descriptor desc;
645
646    libusb_get_device_descriptor (dev->device, &desc);
647    // Assign default device info
648    retdevs[i].device_entry.vendor = NULL;
649    retdevs[i].device_entry.vendor_id = desc.idVendor;
650    retdevs[i].device_entry.product = NULL;
651    retdevs[i].device_entry.product_id = desc.idProduct;
652    retdevs[i].device_entry.device_flags = 0x00000000U;
653    // See if we can locate some additional vendor info and device flags
654    for(j = 0; j < mtp_device_table_size; j++) {
655      if(desc.idVendor == mtp_device_table[j].vendor_id &&
656	 desc.idProduct == mtp_device_table[j].product_id) {
657	device_known = 1;
658	retdevs[i].device_entry.vendor = mtp_device_table[j].vendor;
659	retdevs[i].device_entry.product = mtp_device_table[j].product;
660	retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags;
661
662	// This device is known to the developers
663	LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n",
664		i,
665		desc.idVendor,
666		desc.idProduct,
667		mtp_device_table[j].vendor,
668		mtp_device_table[j].product);
669	break;
670      }
671    }
672    if (!device_known) {
673      // This device is unknown to the developers
674      LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n",
675	      i,
676	      desc.idVendor,
677	      desc.idProduct);
678      LIBMTP_ERROR("Please report this VID/PID and the device model to the "
679	      "libmtp development team\n");
680      /*
681       * Trying to get iManufacturer or iProduct from the device at this
682       * point would require opening a device handle, that we don't want
683       * to do right now. (Takes time for no good enough reason.)
684       */
685    }
686    // Save the location on the bus
687    retdevs[i].bus_location = libusb_get_bus_number (dev->device);
688    retdevs[i].devnum = libusb_get_device_address (dev->device);
689    i++;
690    dev = dev->next;
691  }
692  *devices = retdevs;
693  *numdevs = i;
694  free_mtpdevice_list(devlist);
695  return LIBMTP_ERROR_NONE;
696}
697
698/**
699 * This routine just dumps out low-level
700 * USB information about the current device.
701 * @param ptp_usb the USB device to get information from.
702 */
703void dump_usbinfo(PTP_USB *ptp_usb)
704{
705  libusb_device *dev;
706  struct libusb_device_descriptor desc;
707
708  if (libusb_kernel_driver_active(ptp_usb->handle, ptp_usb->interface))
709    LIBMTP_INFO("   Interface has a kernel driver attached.\n");
710
711  dev = libusb_get_device (ptp_usb->handle);
712  libusb_get_device_descriptor (dev, &desc);
713
714  LIBMTP_INFO("   bcdUSB: %d\n", desc.bcdUSB);
715  LIBMTP_INFO("   bDeviceClass: %d\n", desc.bDeviceClass);
716  LIBMTP_INFO("   bDeviceSubClass: %d\n", desc.bDeviceSubClass);
717  LIBMTP_INFO("   bDeviceProtocol: %d\n", desc.bDeviceProtocol);
718  LIBMTP_INFO("   idVendor: %04x\n", desc.idVendor);
719  LIBMTP_INFO("   idProduct: %04x\n", desc.idProduct);
720  LIBMTP_INFO("   IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
721  LIBMTP_INFO("   OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
722  LIBMTP_INFO("   Raw device info:\n");
723  LIBMTP_INFO("      Bus location: %d\n", ptp_usb->rawdevice.bus_location);
724  LIBMTP_INFO("      Device number: %d\n", ptp_usb->rawdevice.devnum);
725  LIBMTP_INFO("      Device entry info:\n");
726  LIBMTP_INFO("         Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
727  LIBMTP_INFO("         Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
728  LIBMTP_INFO("         Product: %s\n", ptp_usb->rawdevice.device_entry.product);
729  LIBMTP_INFO("         Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
730  LIBMTP_INFO("         Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
731  (void) probe_device_descriptor(dev, stdout);
732}
733
734/**
735 * Retrieve the apropriate playlist extension for this
736 * device. Rather hacky at the moment. This is probably
737 * desired by the managing software, but when creating
738 * lists on the device itself you notice certain preferences.
739 * @param ptp_usb the USB device to get suggestion for.
740 * @return the suggested playlist extension.
741 */
742const char *get_playlist_extension(PTP_USB *ptp_usb)
743{
744  libusb_device *dev;
745  struct libusb_device_descriptor desc;
746  static char creative_pl_extension[] = ".zpl";
747  static char default_pl_extension[] = ".pla";
748
749  dev = libusb_get_device(ptp_usb->handle);
750  libusb_get_device_descriptor (dev, &desc);
751  if (desc.idVendor == 0x041e)
752    return creative_pl_extension;
753  return default_pl_extension;
754}
755
756static void
757libusb_glue_debug (PTPParams *params, const char *format, ...)
758{
759        va_list args;
760
761        va_start (args, format);
762        if (params->debug_func!=NULL)
763                params->debug_func (params->data, format, args);
764        else
765	{
766                vfprintf (stderr, format, args);
767		fprintf (stderr,"\n");
768		fflush (stderr);
769	}
770        va_end (args);
771}
772
773static void
774libusb_glue_error (PTPParams *params, const char *format, ...)
775{
776        va_list args;
777
778        va_start (args, format);
779        if (params->error_func!=NULL)
780                params->error_func (params->data, format, args);
781        else
782	{
783                vfprintf (stderr, format, args);
784		fprintf (stderr,"\n");
785		fflush (stderr);
786	}
787        va_end (args);
788}
789
790
791/*
792 * ptp_read_func() and ptp_write_func() are
793 * based on same functions usb.c in libgphoto2.
794 * Much reading packet logs and having fun with trials and errors
795 * reveals that WMP / Windows is probably using an algorithm like this
796 * for large transfers:
797 *
798 * 1. Send the command (0x0c bytes) if headers are split, else, send
799 *    command plus sizeof(endpoint) - 0x0c bytes.
800 * 2. Send first packet, max size to be sizeof(endpoint) but only when using
801 *    split headers. Else goto 3.
802 * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
803 *    We call 0x10000 CONTEXT_BLOCK_SIZE.
804 * 4. Send remaining bytes MOD sizeof(endpoint)
805 * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
806 *    then also send a zero-length package.
807 *
808 * Further there is some special quirks to handle zero reads from the
809 * device, since some devices can't do them at all due to shortcomings
810 * of the USB slave controller in the device.
811 */
812#define CONTEXT_BLOCK_SIZE_1	0x3e00
813#define CONTEXT_BLOCK_SIZE_2  0x200
814#define CONTEXT_BLOCK_SIZE    CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
815static short
816ptp_read_func (
817	unsigned long size, PTPDataHandler *handler,void *data,
818	unsigned long *readbytes,
819	int readzero
820) {
821  PTP_USB *ptp_usb = (PTP_USB *)data;
822  unsigned long toread = 0;
823  int ret = 0;
824  int xread;
825  unsigned long curread = 0;
826  unsigned long written;
827  unsigned char *bytes;
828  int expect_terminator_byte = 0;
829
830  // This is the largest block we'll need to read in.
831  bytes = malloc(CONTEXT_BLOCK_SIZE);
832  while (curread < size) {
833
834    LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
835
836    // check equal to condition here
837    if (size - curread < CONTEXT_BLOCK_SIZE)
838    {
839      // this is the last packet
840      toread = size - curread;
841      // this is equivalent to zero read for these devices
842      if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
843        toread += 1;
844        expect_terminator_byte = 1;
845      }
846    }
847    else if (curread == 0)
848      // we are first packet, but not last packet
849      toread = CONTEXT_BLOCK_SIZE_1;
850    else if (toread == CONTEXT_BLOCK_SIZE_1)
851      toread = CONTEXT_BLOCK_SIZE_2;
852    else if (toread == CONTEXT_BLOCK_SIZE_2)
853      toread = CONTEXT_BLOCK_SIZE_1;
854    else
855      LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
856	     (unsigned int) toread, (unsigned int) (size-curread));
857
858    LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
859
860    ret = USB_BULK_READ(ptp_usb->handle,
861			   ptp_usb->inep,
862			   bytes,
863			   toread,
864                           &xread,
865			   ptp_usb->timeout);
866
867    LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread);
868
869    if (ret != LIBUSB_SUCCESS)
870      return PTP_ERROR_IO;
871
872    LIBMTP_USB_DEBUG("<==USB IN\n");
873    if (xread == 0)
874      LIBMTP_USB_DEBUG("Zero Read\n");
875    else
876      LIBMTP_USB_DATA(bytes, xread, 16);
877
878    // want to discard extra byte
879    if (expect_terminator_byte && xread == toread)
880    {
881      LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
882
883      xread--;
884    }
885
886    int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written);
887    if (putfunc_ret != PTP_RC_OK)
888      return putfunc_ret;
889
890    ptp_usb->current_transfer_complete += xread;
891    curread += xread;
892
893    // Increase counters, call callback
894    if (ptp_usb->callback_active) {
895      if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
896	// send last update and disable callback.
897	ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
898	ptp_usb->callback_active = 0;
899      }
900      if (ptp_usb->current_transfer_callback != NULL) {
901	int ret;
902	ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
903						 ptp_usb->current_transfer_total,
904						 ptp_usb->current_transfer_callback_data);
905	if (ret != 0) {
906	  return PTP_ERROR_CANCEL;
907	}
908      }
909    }
910
911    if (xread < toread) /* short reads are common */
912      break;
913  }
914  if (readbytes) *readbytes = curread;
915  free (bytes);
916
917  // there might be a zero packet waiting for us...
918  if (readzero &&
919      !FLAG_NO_ZERO_READS(ptp_usb) &&
920      curread % ptp_usb->outep_maxpacket == 0) {
921    unsigned char temp;
922    int zeroresult = 0, xread;
923
924    LIBMTP_USB_DEBUG("<==USB IN\n");
925    LIBMTP_USB_DEBUG("Zero Read\n");
926
927    zeroresult = USB_BULK_READ(ptp_usb->handle,
928			       ptp_usb->inep,
929			       &temp,
930			       0,
931                               &xread,
932			       ptp_usb->timeout);
933    if (zeroresult != LIBUSB_SUCCESS)
934      LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
935  }
936
937  return PTP_RC_OK;
938}
939
940static short
941ptp_write_func (
942        unsigned long   size,
943        PTPDataHandler  *handler,
944        void            *data,
945        unsigned long   *written
946) {
947  PTP_USB *ptp_usb = (PTP_USB *)data;
948  unsigned long towrite = 0;
949  int ret = 0;
950  unsigned long curwrite = 0;
951  unsigned char *bytes;
952
953  // This is the largest block we'll need to read in.
954  bytes = malloc(CONTEXT_BLOCK_SIZE);
955  if (!bytes) {
956    return PTP_ERROR_IO;
957  }
958  while (curwrite < size) {
959    unsigned long usbwritten = 0;
960    int xwritten;
961
962    towrite = size-curwrite;
963    if (towrite > CONTEXT_BLOCK_SIZE) {
964      towrite = CONTEXT_BLOCK_SIZE;
965    } else {
966      // This magic makes packets the same size that WMP send them.
967      if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
968        towrite -= towrite % ptp_usb->outep_maxpacket;
969      }
970    }
971    int getfunc_ret = handler->getfunc(NULL, handler->priv,towrite,bytes,&towrite);
972    if (getfunc_ret != PTP_RC_OK)
973      return getfunc_ret;
974    while (usbwritten < towrite) {
975	    ret = USB_BULK_WRITE(ptp_usb->handle,
976				    ptp_usb->outep,
977				    bytes+usbwritten,
978				    towrite-usbwritten,
979                                    &xwritten,
980				    ptp_usb->timeout);
981
982	    LIBMTP_USB_DEBUG("USB OUT==>\n");
983
984	    if (ret != LIBUSB_SUCCESS) {
985	      return PTP_ERROR_IO;
986	    }
987	    LIBMTP_USB_DATA(bytes+usbwritten, xwritten, 16);
988	    // check for result == 0 perhaps too.
989	    // Increase counters
990	    ptp_usb->current_transfer_complete += xwritten;
991	    curwrite += xwritten;
992	    usbwritten += xwritten;
993    }
994    // call callback
995    if (ptp_usb->callback_active) {
996      if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
997	// send last update and disable callback.
998	ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
999	ptp_usb->callback_active = 0;
1000      }
1001      if (ptp_usb->current_transfer_callback != NULL) {
1002	int ret;
1003	ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1004						 ptp_usb->current_transfer_total,
1005						 ptp_usb->current_transfer_callback_data);
1006	if (ret != 0) {
1007	  return PTP_ERROR_CANCEL;
1008	}
1009      }
1010    }
1011    if (xwritten < towrite) /* short writes happen */
1012      break;
1013  }
1014  free (bytes);
1015  if (written) {
1016    *written = curwrite;
1017  }
1018
1019  // If this is the last transfer send a zero write if required
1020  if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1021    if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1022      int xwritten;
1023
1024      LIBMTP_USB_DEBUG("USB OUT==>\n");
1025      LIBMTP_USB_DEBUG("Zero Write\n");
1026
1027      ret =USB_BULK_WRITE(ptp_usb->handle,
1028			    ptp_usb->outep,
1029			    (unsigned char *) "x",
1030			    0,
1031                            &xwritten,
1032			    ptp_usb->timeout);
1033    }
1034  }
1035
1036  if (ret != LIBUSB_SUCCESS)
1037    return PTP_ERROR_IO;
1038  return PTP_RC_OK;
1039}
1040
1041/* memory data get/put handler */
1042typedef struct {
1043	unsigned char	*data;
1044	unsigned long	size, curoff;
1045} PTPMemHandlerPrivate;
1046
1047static uint16_t
1048memory_getfunc(PTPParams* params, void* private,
1049	       unsigned long wantlen, unsigned char *data,
1050	       unsigned long *gotlen
1051) {
1052	PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1053	unsigned long tocopy = wantlen;
1054
1055	if (priv->curoff + tocopy > priv->size)
1056		tocopy = priv->size - priv->curoff;
1057	memcpy (data, priv->data + priv->curoff, tocopy);
1058	priv->curoff += tocopy;
1059	*gotlen = tocopy;
1060	return PTP_RC_OK;
1061}
1062
1063static uint16_t
1064memory_putfunc(PTPParams* params, void* private,
1065	       unsigned long sendlen, unsigned char *data,
1066	       unsigned long *putlen
1067) {
1068	PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1069
1070	if (priv->curoff + sendlen > priv->size) {
1071		priv->data = realloc (priv->data, priv->curoff+sendlen);
1072		priv->size = priv->curoff + sendlen;
1073	}
1074	memcpy (priv->data + priv->curoff, data, sendlen);
1075	priv->curoff += sendlen;
1076	*putlen = sendlen;
1077	return PTP_RC_OK;
1078}
1079
1080/* init private struct for receiving data. */
1081static uint16_t
1082ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1083	PTPMemHandlerPrivate* priv;
1084	priv = malloc (sizeof(PTPMemHandlerPrivate));
1085	handler->priv = priv;
1086	handler->getfunc = memory_getfunc;
1087	handler->putfunc = memory_putfunc;
1088	priv->data = NULL;
1089	priv->size = 0;
1090	priv->curoff = 0;
1091	return PTP_RC_OK;
1092}
1093
1094/* init private struct and put data in for sending data.
1095 * data is still owned by caller.
1096 */
1097static uint16_t
1098ptp_init_send_memory_handler(PTPDataHandler *handler,
1099	unsigned char *data, unsigned long len
1100) {
1101	PTPMemHandlerPrivate* priv;
1102	priv = malloc (sizeof(PTPMemHandlerPrivate));
1103	if (!priv)
1104		return PTP_RC_GeneralError;
1105	handler->priv = priv;
1106	handler->getfunc = memory_getfunc;
1107	handler->putfunc = memory_putfunc;
1108	priv->data = data;
1109	priv->size = len;
1110	priv->curoff = 0;
1111	return PTP_RC_OK;
1112}
1113
1114/* free private struct + data */
1115static uint16_t
1116ptp_exit_send_memory_handler (PTPDataHandler *handler) {
1117	PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1118	/* data is owned by caller */
1119	free (priv);
1120	return PTP_RC_OK;
1121}
1122
1123/* hand over our internal data to caller */
1124static uint16_t
1125ptp_exit_recv_memory_handler (PTPDataHandler *handler,
1126	unsigned char **data, unsigned long *size
1127) {
1128	PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1129	*data = priv->data;
1130	*size = priv->size;
1131	free (priv);
1132	return PTP_RC_OK;
1133}
1134
1135/* send / receive functions */
1136
1137uint16_t
1138ptp_usb_sendreq (PTPParams* params, PTPContainer* req)
1139{
1140	uint16_t ret;
1141	PTPUSBBulkContainer usbreq;
1142	PTPDataHandler	memhandler;
1143	unsigned long written = 0;
1144	unsigned long towrite;
1145
1146	char txt[256];
1147
1148	(void) ptp_render_opcode (params, req->Code, sizeof(txt), txt);
1149	LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1150
1151	/* build appropriate USB container */
1152	usbreq.length=htod32(PTP_USB_BULK_REQ_LEN-
1153		(sizeof(uint32_t)*(5-req->Nparam)));
1154	usbreq.type=htod16(PTP_USB_CONTAINER_COMMAND);
1155	usbreq.code=htod16(req->Code);
1156	usbreq.trans_id=htod32(req->Transaction_ID);
1157	usbreq.payload.params.param1=htod32(req->Param1);
1158	usbreq.payload.params.param2=htod32(req->Param2);
1159	usbreq.payload.params.param3=htod32(req->Param3);
1160	usbreq.payload.params.param4=htod32(req->Param4);
1161	usbreq.payload.params.param5=htod32(req->Param5);
1162	/* send it to responder */
1163	towrite = PTP_USB_BULK_REQ_LEN-(sizeof(uint32_t)*(5-req->Nparam));
1164	ptp_init_send_memory_handler (&memhandler, (unsigned char*)&usbreq, towrite);
1165	ret=ptp_write_func(
1166		towrite,
1167		&memhandler,
1168		params->data,
1169		&written
1170	);
1171	ptp_exit_send_memory_handler (&memhandler);
1172	if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) {
1173		ret = PTP_ERROR_IO;
1174	}
1175	if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1176		libusb_glue_error (params,
1177			"PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1178			req->Code, written, towrite
1179		);
1180		ret = PTP_ERROR_IO;
1181	}
1182	return ret;
1183}
1184
1185uint16_t
1186ptp_usb_senddata (PTPParams* params, PTPContainer* ptp,
1187		  unsigned long size, PTPDataHandler *handler
1188) {
1189	uint16_t ret;
1190	int wlen, datawlen;
1191	unsigned long written;
1192	PTPUSBBulkContainer usbdata;
1193	uint32_t bytes_left_to_transfer;
1194	PTPDataHandler memhandler;
1195
1196
1197	LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1198
1199	/* build appropriate USB container */
1200	usbdata.length	= htod32(PTP_USB_BULK_HDR_LEN+size);
1201	usbdata.type	= htod16(PTP_USB_CONTAINER_DATA);
1202	usbdata.code	= htod16(ptp->Code);
1203	usbdata.trans_id= htod32(ptp->Transaction_ID);
1204
1205	((PTP_USB*)params->data)->current_transfer_complete = 0;
1206	((PTP_USB*)params->data)->current_transfer_total = size+PTP_USB_BULK_HDR_LEN;
1207
1208	if (params->split_header_data) {
1209		datawlen = 0;
1210		wlen = PTP_USB_BULK_HDR_LEN;
1211	} else {
1212		unsigned long gotlen;
1213		/* For all camera devices. */
1214		datawlen = (size<PTP_USB_BULK_PAYLOAD_LEN_WRITE)?size:PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1215		wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1216
1217		ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1218		if (ret != PTP_RC_OK)
1219			return ret;
1220		if (gotlen != datawlen)
1221			return PTP_RC_GeneralError;
1222	}
1223	ptp_init_send_memory_handler (&memhandler, (unsigned char *)&usbdata, wlen);
1224	/* send first part of data */
1225	ret = ptp_write_func(wlen, &memhandler, params->data, &written);
1226	ptp_exit_send_memory_handler (&memhandler);
1227	if (ret != PTP_RC_OK) {
1228		return ret;
1229	}
1230	if (size <= datawlen) return ret;
1231	/* if everything OK send the rest */
1232	bytes_left_to_transfer = size-datawlen;
1233	ret = PTP_RC_OK;
1234	while(bytes_left_to_transfer > 0) {
1235		ret = ptp_write_func (bytes_left_to_transfer, handler, params->data, &written);
1236		if (ret != PTP_RC_OK)
1237			break;
1238		if (written == 0) {
1239			ret = PTP_ERROR_IO;
1240			break;
1241		}
1242		bytes_left_to_transfer -= written;
1243	}
1244	if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL)
1245		ret = PTP_ERROR_IO;
1246	return ret;
1247}
1248
1249static uint16_t ptp_usb_getpacket(PTPParams *params,
1250		PTPUSBBulkContainer *packet, unsigned long *rlen)
1251{
1252	PTPDataHandler	memhandler;
1253	uint16_t	ret;
1254	unsigned char	*x = NULL;
1255
1256	/* read the header and potentially the first data */
1257	if (params->response_packet_size > 0) {
1258		/* If there is a buffered packet, just use it. */
1259		memcpy(packet, params->response_packet, params->response_packet_size);
1260		*rlen = params->response_packet_size;
1261		free(params->response_packet);
1262		params->response_packet = NULL;
1263		params->response_packet_size = 0;
1264		/* Here this signifies a "virtual read" */
1265		return PTP_RC_OK;
1266	}
1267	ptp_init_recv_memory_handler (&memhandler);
1268	ret = ptp_read_func(PTP_USB_BULK_HS_MAX_PACKET_LEN_READ, &memhandler, params->data, rlen, 0);
1269	ptp_exit_recv_memory_handler (&memhandler, &x, rlen);
1270	if (x) {
1271		memcpy (packet, x, *rlen);
1272		free (x);
1273	}
1274	return ret;
1275}
1276
1277uint16_t
1278ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler)
1279{
1280	uint16_t ret;
1281	PTPUSBBulkContainer usbdata;
1282	unsigned long	written;
1283	PTP_USB *ptp_usb = (PTP_USB *) params->data;
1284	int putfunc_ret;
1285
1286	LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1287
1288	memset(&usbdata,0,sizeof(usbdata));
1289	do {
1290		unsigned long len, rlen;
1291
1292		ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1293		if (ret != PTP_RC_OK) {
1294			ret = PTP_ERROR_IO;
1295			break;
1296		}
1297		if (dtoh16(usbdata.type)!=PTP_USB_CONTAINER_DATA) {
1298			ret = PTP_ERROR_DATA_EXPECTED;
1299			break;
1300		}
1301		if (dtoh16(usbdata.code)!=ptp->Code) {
1302			if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1303				libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1304					   "PTP header, code field insane, expect problems! (But continuing)");
1305				// Repair the header, so it won't wreak more havoc, don't just ignore it.
1306				// Typically these two fields will be broken.
1307				usbdata.code	 = htod16(ptp->Code);
1308				usbdata.trans_id = htod32(ptp->Transaction_ID);
1309				ret = PTP_RC_OK;
1310			} else {
1311				ret = dtoh16(usbdata.code);
1312				// This filters entirely insane garbage return codes, but still
1313				// makes it possible to return error codes in the code field when
1314				// getting data. It appears Windows ignores the contents of this
1315				// field entirely.
1316				if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1317					libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1318						   "PTP header, code field insane.");
1319					ret = PTP_ERROR_IO;
1320				}
1321				break;
1322			}
1323		}
1324		if (usbdata.length == 0xffffffffU) {
1325		  /* Copy first part of data to 'data' */
1326		  putfunc_ret =
1327		    handler->putfunc(
1328				     params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1329				     &written
1330				     );
1331		  if (putfunc_ret != PTP_RC_OK)
1332		    return putfunc_ret;
1333
1334		  /* stuff data directly to passed data handler */
1335		  while (1) {
1336		    unsigned long readdata;
1337		    uint16_t xret;
1338
1339		    xret = ptp_read_func(
1340					 PTP_USB_BULK_HS_MAX_PACKET_LEN_READ,
1341					 handler,
1342					 params->data,
1343					 &readdata,
1344					 0
1345					 );
1346		    if (xret != PTP_RC_OK)
1347		      return xret;
1348		    if (readdata < PTP_USB_BULK_HS_MAX_PACKET_LEN_READ)
1349		      break;
1350		  }
1351		  return PTP_RC_OK;
1352		}
1353		if (rlen > dtoh32(usbdata.length)) {
1354			/*
1355			 * Buffer the surplus response packet if it is >=
1356			 * PTP_USB_BULK_HDR_LEN
1357			 * (i.e. it is probably an entire package)
1358			 * else discard it as erroneous surplus data.
1359			 * This will even work if more than 2 packets appear
1360			 * in the same transaction, they will just be handled
1361			 * iteratively.
1362			 *
1363			 * Marcus observed stray bytes on iRiver devices;
1364			 * these are still discarded.
1365			 */
1366			unsigned int packlen = dtoh32(usbdata.length);
1367			unsigned int surplen = rlen - packlen;
1368
1369			if (surplen >= PTP_USB_BULK_HDR_LEN) {
1370				params->response_packet = malloc(surplen);
1371				memcpy(params->response_packet,
1372				       (uint8_t *) &usbdata + packlen, surplen);
1373				params->response_packet_size = surplen;
1374			/* Ignore reading one extra byte if device flags have been set */
1375			} else if(!FLAG_NO_ZERO_READS(ptp_usb) &&
1376				  (rlen - dtoh32(usbdata.length) == 1)) {
1377			  libusb_glue_debug (params, "ptp2/ptp_usb_getdata: read %d bytes "
1378				     "too much, expect problems!",
1379				     rlen - dtoh32(usbdata.length));
1380			}
1381			rlen = packlen;
1382		}
1383
1384		/* For most PTP devices rlen is 512 == sizeof(usbdata)
1385		 * here. For MTP devices splitting header and data it might
1386		 * be 12.
1387		 */
1388		/* Evaluate full data length. */
1389		len=dtoh32(usbdata.length)-PTP_USB_BULK_HDR_LEN;
1390
1391		/* autodetect split header/data MTP devices */
1392		if (dtoh32(usbdata.length) > 12 && (rlen==12))
1393			params->split_header_data = 1;
1394
1395		/* Copy first part of data to 'data' */
1396		putfunc_ret =
1397		  handler->putfunc(
1398				   params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1399				   usbdata.payload.data,
1400				   &written
1401				   );
1402		if (putfunc_ret != PTP_RC_OK)
1403		  return putfunc_ret;
1404
1405		if (FLAG_NO_ZERO_READS(ptp_usb) &&
1406		    len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) {
1407
1408		  LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1409
1410		  // need to read in extra byte and discard it
1411		  int result = 0, xread;
1412		  unsigned char byte = 0;
1413                  result = USB_BULK_READ(ptp_usb->handle,
1414					 ptp_usb->inep,
1415					 &byte,
1416					 1,
1417                                         &xread,
1418					 ptp_usb->timeout);
1419
1420		  if (result != 1)
1421		    LIBMTP_INFO("Could not read in extra byte for PTP_USB_BULK_HS_MAX_PACKET_LEN_READ long file, return value 0x%04x\n", result);
1422		} else if (len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) {
1423		  int zeroresult = 0, xread;
1424		  unsigned char zerobyte = 0;
1425
1426		  LIBMTP_INFO("Reading in zero packet after header\n");
1427
1428		  zeroresult = USB_BULK_READ(ptp_usb->handle,
1429					     ptp_usb->inep,
1430					     &zerobyte,
1431					     0,
1432					     &xread,
1433					     ptp_usb->timeout);
1434
1435		  if (zeroresult != 0)
1436		    LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1437		}
1438
1439		/* Is that all of data? */
1440		if (len+PTP_USB_BULK_HDR_LEN<=rlen) {
1441		  break;
1442		}
1443
1444		ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1445				    handler,
1446				    params->data, &rlen, 1);
1447
1448		if (ret != PTP_RC_OK) {
1449		  break;
1450		}
1451	} while (0);
1452	return ret;
1453}
1454
1455uint16_t
1456ptp_usb_getresp (PTPParams* params, PTPContainer* resp)
1457{
1458	uint16_t ret;
1459	unsigned long rlen;
1460	PTPUSBBulkContainer usbresp;
1461	PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1462
1463
1464	LIBMTP_USB_DEBUG("RESPONSE: ");
1465
1466	memset(&usbresp,0,sizeof(usbresp));
1467	/* read response, it should never be longer than sizeof(usbresp) */
1468	ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1469
1470	// Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1471	// sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1472	// after a NULL packet when it should send the response. This code ignores
1473	// such illegal packets.
1474	while (ret==PTP_RC_OK && rlen<PTP_USB_BULK_HDR_LEN && usbresp.length==0) {
1475	  libusb_glue_debug (params, "ptp_usb_getresp: detected short response "
1476		     "of %d bytes, expect problems! (re-reading "
1477		     "response), rlen");
1478	  ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1479	}
1480
1481	if (ret != PTP_RC_OK) {
1482		ret = PTP_ERROR_IO;
1483	} else
1484	if (dtoh16(usbresp.type)!=PTP_USB_CONTAINER_RESPONSE) {
1485		ret = PTP_ERROR_RESP_EXPECTED;
1486	} else
1487	if (dtoh16(usbresp.code)!=resp->Code) {
1488		ret = dtoh16(usbresp.code);
1489	}
1490
1491	LIBMTP_USB_DEBUG("%04x\n", ret);
1492
1493	if (ret != PTP_RC_OK) {
1494/*		libusb_glue_error (params,
1495		"PTP: request code 0x%04x getting resp error 0x%04x",
1496			resp->Code, ret);*/
1497		return ret;
1498	}
1499	/* build an appropriate PTPContainer */
1500	resp->Code=dtoh16(usbresp.code);
1501	resp->SessionID=params->session_id;
1502	resp->Transaction_ID=dtoh32(usbresp.trans_id);
1503	if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1504		if (resp->Transaction_ID != params->transaction_id-1) {
1505			libusb_glue_debug (params, "ptp_usb_getresp: detected a broken "
1506				   "PTP header, transaction ID insane, expect "
1507				   "problems! (But continuing)");
1508			// Repair the header, so it won't wreak more havoc.
1509			resp->Transaction_ID = params->transaction_id-1;
1510		}
1511	}
1512	resp->Param1=dtoh32(usbresp.payload.params.param1);
1513	resp->Param2=dtoh32(usbresp.payload.params.param2);
1514	resp->Param3=dtoh32(usbresp.payload.params.param3);
1515	resp->Param4=dtoh32(usbresp.payload.params.param4);
1516	resp->Param5=dtoh32(usbresp.payload.params.param5);
1517	return ret;
1518}
1519
1520/* Event handling functions */
1521
1522/* PTP Events wait for or check mode */
1523#define PTP_EVENT_CHECK			0x0000	/* waits for */
1524#define PTP_EVENT_CHECK_FAST		0x0001	/* checks */
1525
1526static inline uint16_t
1527ptp_usb_event (PTPParams* params, PTPContainer* event, int wait)
1528{
1529	uint16_t ret;
1530	int result, xread;
1531	unsigned long rlen;
1532	PTPUSBEventContainer usbevent;
1533	PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1534
1535	memset(&usbevent,0,sizeof(usbevent));
1536
1537	if ((params==NULL) || (event==NULL))
1538		return PTP_ERROR_BADPARAM;
1539	ret = PTP_RC_OK;
1540	switch(wait) {
1541	case PTP_EVENT_CHECK:
1542                result = USB_BULK_READ(ptp_usb->handle,
1543				     ptp_usb->intep,
1544				     (unsigned char *) &usbevent,
1545				     sizeof(usbevent),
1546				     &xread,
1547				     0);
1548		if (xread == 0)
1549		  result = USB_BULK_READ(ptp_usb->handle,
1550					 ptp_usb->intep,
1551					 (unsigned char *) &usbevent,
1552					 sizeof(usbevent),
1553				         &xread,
1554					 0);
1555		if (result < 0) ret = PTP_ERROR_IO;
1556		break;
1557	case PTP_EVENT_CHECK_FAST:
1558                result = USB_BULK_READ(ptp_usb->handle,
1559				     ptp_usb->intep,
1560				     (unsigned char *) &usbevent,
1561				     sizeof(usbevent),
1562				     &xread,
1563				     ptp_usb->timeout);
1564		if (xread == 0)
1565		  result = USB_BULK_READ(ptp_usb->handle,
1566					 ptp_usb->intep,
1567					 (unsigned char *) &usbevent,
1568					 sizeof(usbevent),
1569				         &xread,
1570					 ptp_usb->timeout);
1571		if (result < 0) ret = PTP_ERROR_IO;
1572		break;
1573	default:
1574		ret = PTP_ERROR_BADPARAM;
1575		break;
1576	}
1577	if (ret != PTP_RC_OK) {
1578		libusb_glue_error (params,
1579			"PTP: reading event an error 0x%04x occurred", ret);
1580		return PTP_ERROR_IO;
1581	}
1582	rlen = xread;
1583	if (rlen < 8) {
1584		libusb_glue_error (params,
1585			"PTP: reading event an short read of %ld bytes occurred", rlen);
1586		return PTP_ERROR_IO;
1587	}
1588	/* if we read anything over interrupt endpoint it must be an event */
1589	/* build an appropriate PTPContainer */
1590	event->Code=dtoh16(usbevent.code);
1591	event->SessionID=params->session_id;
1592	event->Transaction_ID=dtoh32(usbevent.trans_id);
1593	event->Param1=dtoh32(usbevent.param1);
1594	event->Param2=dtoh32(usbevent.param2);
1595	event->Param3=dtoh32(usbevent.param3);
1596	return ret;
1597}
1598
1599uint16_t
1600ptp_usb_event_check (PTPParams* params, PTPContainer* event) {
1601
1602	return ptp_usb_event (params, event, PTP_EVENT_CHECK_FAST);
1603}
1604
1605uint16_t
1606ptp_usb_event_wait (PTPParams* params, PTPContainer* event) {
1607
1608	return ptp_usb_event (params, event, PTP_EVENT_CHECK);
1609}
1610
1611uint16_t
1612ptp_usb_control_cancel_request (PTPParams *params, uint32_t transactionid) {
1613	PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1614	int ret;
1615	unsigned char buffer[6];
1616
1617	htod16a(&buffer[0],PTP_EC_CancelTransaction);
1618	htod32a(&buffer[2],transactionid);
1619	ret = libusb_control_transfer(ptp_usb->handle,
1620			      LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
1621                              0x64, 0x0000, 0x0000,
1622			      buffer,
1623			      sizeof(buffer),
1624			      ptp_usb->timeout);
1625	if (ret < sizeof(buffer))
1626		return PTP_ERROR_IO;
1627	return PTP_RC_OK;
1628}
1629
1630static int init_ptp_usb (PTPParams* params, PTP_USB* ptp_usb, libusb_device* dev)
1631{
1632  libusb_device_handle *device_handle;
1633  unsigned char buf[255];
1634  int ret, usbresult;
1635
1636  params->sendreq_func=ptp_usb_sendreq;
1637  params->senddata_func=ptp_usb_senddata;
1638  params->getresp_func=ptp_usb_getresp;
1639  params->getdata_func=ptp_usb_getdata;
1640  params->cancelreq_func=ptp_usb_control_cancel_request;
1641  params->data=ptp_usb;
1642  params->transaction_id=0;
1643  /*
1644   * This is hardcoded here since we have no devices whatsoever that are BE.
1645   * Change this the day we run into our first BE device (if ever).
1646   */
1647  params->byteorder = PTP_DL_LE;
1648
1649  ptp_usb->timeout = get_timeout(ptp_usb);
1650
1651  ret = libusb_open(dev, &device_handle);
1652  if (ret != LIBUSB_SUCCESS) {
1653    perror("usb_open()");
1654    return -1;
1655  }
1656  ptp_usb->handle = device_handle;
1657  /*
1658   * If this device is known to be wrongfully claimed by other kernel
1659   * drivers (such as mass storage), then try to unload it to make it
1660   * accessible from user space.
1661   */
1662  if (FLAG_UNLOAD_DRIVER(ptp_usb) &&
1663      libusb_kernel_driver_active (device_handle, ptp_usb->interface)
1664  ) {
1665      if (LIBUSB_SUCCESS != libusb_detach_kernel_driver (device_handle, ptp_usb->interface)) {
1666        return -1;
1667      }
1668  }
1669#ifdef __WIN32__
1670  // Only needed on Windows, and cause problems on other platforms.
1671  if (libusb_set_configuration(device_handle, dev->config->bConfigurationValue)) {
1672    perror("usb_set_configuration()");
1673    return -1;
1674  }
1675#endif
1676  // It seems like on kernel 2.6.31 if we already have it open on another
1677  // pthread in our app, we'll get an error if we try to claim it again,
1678  // but that error is harmless because our process already claimed the interface
1679  usbresult = libusb_claim_interface(device_handle, ptp_usb->interface);
1680
1681  if (usbresult != 0)
1682    fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1683
1684  // FIXME : Discovered in the Barry project
1685  // kernels >= 2.6.28 don't set the interface the same way as
1686  // previous versions did, and the Blackberry gets confused
1687  // if it isn't explicitly set
1688  // See above, same issue with pthreads means that if this fails it is not
1689  // fatal
1690  // However, this causes problems on Macs so disable here
1691#ifndef __APPLE__
1692  usbresult = libusb_set_interface_alt_setting(device_handle, ptp_usb->interface, 0);
1693  if (usbresult)
1694    fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1695#endif
1696
1697  if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1698    int ret;
1699
1700    // FIXME : Only for BlackBerry Storm
1701    // What does it mean? Maybe switch mode...
1702    // This first control message is absolutely necessary
1703    usleep(1000);
1704    ret = libusb_control_transfer(device_handle,
1705                          LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1706                          0xaa, 0x00, 0x04, buf, 0x40, 1000);
1707    LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1708    LIBMTP_USB_DATA(buf, ret, 16);
1709
1710    usleep(1000);
1711    // This control message is unnecessary
1712    ret = libusb_control_transfer(device_handle,
1713                          LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1714                          0xa5, 0x00, 0x01, buf, 0x02, 1000);
1715    LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1716    LIBMTP_USB_DATA(buf, ret, 16);
1717
1718    usleep(1000);
1719    // This control message is unnecessary
1720    ret = libusb_control_transfer(device_handle,
1721                          LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1722                          0xa8, 0x00, 0x01, buf, 0x05, 1000);
1723    LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1724    LIBMTP_USB_DATA(buf, ret, 16);
1725
1726    usleep(1000);
1727    // This control message is unnecessary
1728    ret = libusb_control_transfer(device_handle,
1729                          LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1730                          0xa8, 0x00, 0x01, buf, 0x11, 1000);
1731    LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1732    LIBMTP_USB_DATA(buf, ret, 16);
1733
1734    usleep(1000);
1735  }
1736  return 0;
1737}
1738
1739static void clear_stall(PTP_USB* ptp_usb)
1740{
1741  uint16_t status;
1742  int ret;
1743
1744  /* check the inep status */
1745  status = 0;
1746  ret = usb_get_endpoint_status(ptp_usb,ptp_usb->inep,&status);
1747  if (ret<0) {
1748    perror ("inep: usb_get_endpoint_status()");
1749  } else if (status) {
1750    LIBMTP_INFO("Clearing stall on IN endpoint\n");
1751    ret = libusb_clear_halt (ptp_usb->handle, ptp_usb->inep);
1752    if (ret != LIBUSB_SUCCESS) {
1753      perror ("usb_clear_stall_feature()");
1754    }
1755  }
1756
1757  /* check the outep status */
1758  status=0;
1759  ret = usb_get_endpoint_status(ptp_usb,ptp_usb->outep,&status);
1760  if (ret<0) {
1761    perror("outep: usb_get_endpoint_status()");
1762  } else if (status) {
1763    LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1764    ret = libusb_clear_halt (ptp_usb->handle, ptp_usb->outep);
1765    if (ret != LIBUSB_SUCCESS) {
1766      perror("usb_clear_stall_feature()");
1767    }
1768  }
1769
1770  /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1771}
1772
1773static void clear_halt(PTP_USB* ptp_usb)
1774{
1775  int ret;
1776
1777  ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->inep);
1778  if (ret<0) {
1779    perror("usb_clear_halt() on IN endpoint");
1780  }
1781  ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->outep);
1782  if (ret<0) {
1783    perror("usb_clear_halt() on OUT endpoint");
1784  }
1785  ret = libusb_clear_halt(ptp_usb->handle,ptp_usb->intep);
1786  if (ret<0) {
1787    perror("usb_clear_halt() on INTERRUPT endpoint");
1788  }
1789}
1790
1791static void close_usb(PTP_USB* ptp_usb)
1792{
1793  if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1794    /*
1795     * Clear any stalled endpoints
1796     * On misbehaving devices designed for Windows/Mac, quote from:
1797     * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1798     * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1799     * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1800     * and presumes that the stall has cleared.  Some devices actually choke
1801     * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1802     * STALL is persistant or not).
1803     */
1804    clear_stall(ptp_usb);
1805    // Clear halts on any endpoints
1806    clear_halt(ptp_usb);
1807    // Added to clear some stuff on the OUT endpoint
1808    // TODO: is this good on the Mac too?
1809    // HINT: some devices may need that you comment these two out too.
1810    libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1811    libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1812  }
1813  if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1814    /*
1815     * Some devices really love to get reset after being
1816     * disconnected. Again, since Windows never disconnects
1817     * a device closing behaviour is seldom or never exercised
1818     * on devices when engineered and often error prone.
1819     * Reset may help some.
1820     */
1821    libusb_reset_device (ptp_usb->handle);
1822  }
1823  libusb_close(ptp_usb->handle);
1824}
1825
1826/**
1827 * Self-explanatory?
1828 */
1829static int find_interface_and_endpoints(libusb_device *dev,
1830					uint8_t *interface,
1831					int* inep,
1832					int* inep_maxpacket,
1833					int* outep,
1834					int *outep_maxpacket,
1835					int* intep)
1836{
1837  int i, ret;
1838  struct libusb_device_descriptor desc;
1839
1840  ret = libusb_get_device_descriptor (dev, &desc);
1841  if (ret != LIBUSB_SUCCESS) return -1;
1842
1843  // Loop over the device configurations
1844  for (i = 0; i < desc.bNumConfigurations; i++) {
1845    uint8_t j;
1846    struct libusb_config_descriptor *config;
1847
1848    ret = libusb_get_config_descriptor (dev, i, &config);
1849    if (ret != LIBUSB_SUCCESS) continue;
1850    // Loop over each configurations interfaces
1851    for (j = 0; j < config->bNumInterfaces; j++) {
1852      uint8_t k;
1853      uint8_t no_ep;
1854      int found_inep = 0;
1855      int found_outep = 0;
1856      int found_intep = 0;
1857      const struct libusb_endpoint_descriptor *ep;
1858
1859      // MTP devices shall have 3 endpoints, ignore those interfaces
1860      // that haven't.
1861      no_ep = config->interface[j].altsetting->bNumEndpoints;
1862      if (no_ep != 3)
1863	continue;
1864
1865      *interface = config->interface[j].altsetting->bInterfaceNumber;
1866      ep = config->interface[j].altsetting->endpoint;
1867
1868      // Loop over the three endpoints to locate two bulk and
1869      // one interrupt endpoint and FAIL if we cannot, and continue.
1870      for (k = 0; k < no_ep; k++) {
1871	if (ep[k].bmAttributes == LIBUSB_TRANSFER_TYPE_BULK) {
1872	  if ((ep[k].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
1873	      LIBUSB_ENDPOINT_DIR_MASK) {
1874	    *inep = ep[k].bEndpointAddress;
1875	    *inep_maxpacket = ep[k].wMaxPacketSize;
1876	    found_inep = 1;
1877	  }
1878	  if ((ep[k].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == 0) {
1879	    *outep = ep[k].bEndpointAddress;
1880	    *outep_maxpacket = ep[k].wMaxPacketSize;
1881	    found_outep = 1;
1882	  }
1883	} else if (ep[k].bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT) {
1884	  if ((ep[k].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
1885	      LIBUSB_ENDPOINT_DIR_MASK) {
1886	    *intep = ep[k].bEndpointAddress;
1887	    found_intep = 1;
1888	  }
1889	}
1890      }
1891      if (found_inep && found_outep && found_intep) {
1892        libusb_free_config_descriptor (config);
1893	// We assigned the endpoints so return here.
1894	return 0;
1895      }
1896      // Else loop to next interface/config
1897    }
1898    libusb_free_config_descriptor (config);
1899  }
1900  return -1;
1901}
1902
1903/**
1904 * This function assigns params and usbinfo given a raw device
1905 * as input.
1906 * @param device the device to be assigned.
1907 * @param usbinfo a pointer to the new usbinfo.
1908 * @return an error code.
1909 */
1910LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
1911					   PTPParams *params,
1912					   void **usbinfo)
1913{
1914  PTP_USB *ptp_usb;
1915  libusb_device *ldevice;
1916  uint16_t ret = 0;
1917  int err, found = 0, i;
1918  ssize_t nrofdevs;
1919  libusb_device **devs = NULL;
1920  struct libusb_device_descriptor desc;
1921
1922  /* See if we can find this raw device again... */
1923  init_usb();
1924
1925  nrofdevs = libusb_get_device_list (NULL, &devs);
1926  for (i = 0; i < nrofdevs ; i++) {
1927    if (libusb_get_bus_number (devs[i]) != device->bus_location)
1928      continue;
1929    if (libusb_get_device_address (devs[i]) != device->devnum)
1930      continue;
1931
1932    ret = libusb_get_device_descriptor (devs[i], &desc);
1933    if (ret != LIBUSB_SUCCESS) continue;
1934
1935    if(desc.idVendor  == device->device_entry.vendor_id &&
1936       desc.idProduct == device->device_entry.product_id ) {
1937	  ldevice = devs[i];
1938	  found = 1;
1939	  break;
1940    }
1941  }
1942  /* Device has gone since detecting raw devices! */
1943  if (!found) {
1944    libusb_free_device_list (devs, 0);
1945    return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
1946  }
1947
1948  /* Allocate structs */
1949  ptp_usb = (PTP_USB *) malloc(sizeof(PTP_USB));
1950  if (ptp_usb == NULL) {
1951    libusb_free_device_list (devs, 0);
1952    return LIBMTP_ERROR_MEMORY_ALLOCATION;
1953  }
1954  /* Start with a blank slate (includes setting device_flags to 0) */
1955  memset(ptp_usb, 0, sizeof(PTP_USB));
1956
1957  /* Copy the raw device */
1958  memcpy(&ptp_usb->rawdevice, device, sizeof(LIBMTP_raw_device_t));
1959
1960  /*
1961   * Some devices must have their "OS Descriptor" massaged in order
1962   * to work.
1963   */
1964  if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
1965    // Massage the device descriptor
1966    (void) probe_device_descriptor(ldevice, NULL);
1967  }
1968
1969  /* Assign interface and endpoints to usbinfo... */
1970  err = find_interface_and_endpoints(ldevice,
1971				     &ptp_usb->interface,
1972				     &ptp_usb->inep,
1973				     &ptp_usb->inep_maxpacket,
1974				     &ptp_usb->outep,
1975				     &ptp_usb->outep_maxpacket,
1976				     &ptp_usb->intep);
1977
1978  if (err) {
1979    libusb_free_device_list (devs, 0);
1980    LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
1981    return LIBMTP_ERROR_CONNECTING;
1982  }
1983
1984  /* Copy USB version number */
1985  ptp_usb->bcdusb = desc.bcdUSB;
1986
1987  /* Attempt to initialize this device */
1988  if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
1989    LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
1990    return LIBMTP_ERROR_CONNECTING;
1991  }
1992
1993  /*
1994   * This works in situations where previous bad applications
1995   * have not used LIBMTP_Release_Device on exit
1996   */
1997  if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
1998    LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
1999    LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2000    libusb_reset_device (ptp_usb->handle);
2001    close_usb(ptp_usb);
2002
2003    if(init_ptp_usb(params, ptp_usb, ldevice) <0) {
2004      LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2005      return LIBMTP_ERROR_CONNECTING;
2006    }
2007
2008    /* Device has been reset, try again */
2009    if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2010      LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2011      return LIBMTP_ERROR_CONNECTING;
2012    }
2013  }
2014
2015  /* Was the transaction id invalid? Try again */
2016  if (ret == PTP_RC_InvalidTransactionID) {
2017    LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2018    params->transaction_id += 10;
2019    ret = ptp_opensession(params, 1);
2020  }
2021
2022  if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2023    LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2024	    "(Return code %d)\n  Try to reset the device.\n",
2025	    ret);
2026    libusb_release_interface(ptp_usb->handle, ptp_usb->interface);
2027    return LIBMTP_ERROR_CONNECTING;
2028  }
2029
2030  /* OK configured properly */
2031  *usbinfo = (void *) ptp_usb;
2032  return LIBMTP_ERROR_NONE;
2033}
2034
2035
2036void close_device (PTP_USB *ptp_usb, PTPParams *params)
2037{
2038  if (ptp_closesession(params)!=PTP_RC_OK)
2039    LIBMTP_ERROR("ERROR: Could not close session!\n");
2040  close_usb(ptp_usb);
2041}
2042
2043void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout)
2044{
2045  ptp_usb->timeout = timeout;
2046}
2047
2048void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout)
2049{
2050  *timeout = ptp_usb->timeout;
2051}
2052
2053int guess_usb_speed(PTP_USB *ptp_usb)
2054{
2055  int bytes_per_second;
2056
2057  /*
2058   * We don't know the actual speeds so these are rough guesses
2059   * from the info you can find here:
2060   * http://en.wikipedia.org/wiki/USB#Transfer_rates
2061   * http://www.barefeats.com/usb2.html
2062   */
2063  switch (ptp_usb->bcdusb & 0xFF00) {
2064  case 0x0100:
2065    /* 1.x USB versions let's say 1MiB/s */
2066    bytes_per_second = 1*1024*1024;
2067    break;
2068  case 0x0200:
2069  case 0x0300:
2070    /* USB 2.0 nominal speed 18MiB/s */
2071    /* USB 3.0 won't be worse? */
2072    bytes_per_second = 18*1024*1024;
2073    break;
2074  default:
2075    /* Half-guess something? */
2076    bytes_per_second = 1*1024*1024;
2077    break;
2078  }
2079  return bytes_per_second;
2080}
2081
2082static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status)
2083{
2084  return libusb_control_transfer(ptp_usb->handle,
2085			  LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT,
2086			  LIBUSB_REQUEST_GET_STATUS,
2087                          USB_FEATURE_HALT,
2088			  ep,
2089			  (unsigned char *) status,
2090			  2,
2091			  ptp_usb->timeout);
2092}
2093