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