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