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