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