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