Imported Upstream version 1.1.11
[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             device_unknown(i, desc.idVendor, desc.idProduct);
665         }
666         // Save the location on the bus
667         retdevs[i].bus_location = 0;
668         retdevs[i].devnum = openusb_get_devid(libmtp_openusb_handle, &dev->device);
669         i++;
670         dev = dev->next;
671     }
672     *devices = retdevs;
673     *numdevs = i;
674     free_mtpdevice_list(devlist);
675     return LIBMTP_ERROR_NONE;
676 }
677
678 /**
679  * This routine just dumps out low-level
680  * USB information about the current device.
681  * @param ptp_usb the USB device to get information from.
682  */
683 void dump_usbinfo(PTP_USB *ptp_usb) {
684     struct usb_device_desc desc;
685
686     openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
687
688     LIBMTP_INFO("   bcdUSB: %d\n", desc.bcdUSB);
689     LIBMTP_INFO("   bDeviceClass: %d\n", desc.bDeviceClass);
690     LIBMTP_INFO("   bDeviceSubClass: %d\n", desc.bDeviceSubClass);
691     LIBMTP_INFO("   bDeviceProtocol: %d\n", desc.bDeviceProtocol);
692     LIBMTP_INFO("   idVendor: %04x\n", desc.idVendor);
693     LIBMTP_INFO("   idProduct: %04x\n", desc.idProduct);
694     LIBMTP_INFO("   IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
695     LIBMTP_INFO("   OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
696     LIBMTP_INFO("   Raw device info:\n");
697     LIBMTP_INFO("      Bus location: %d\n", ptp_usb->rawdevice.bus_location);
698     LIBMTP_INFO("      Device number: %d\n", ptp_usb->rawdevice.devnum);
699     LIBMTP_INFO("      Device entry info:\n");
700     LIBMTP_INFO("         Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
701     LIBMTP_INFO("         Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
702     LIBMTP_INFO("         Product: %s\n", ptp_usb->rawdevice.device_entry.product);
703     LIBMTP_INFO("         Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
704     LIBMTP_INFO("         Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
705     // TODO: (void) probe_device_descriptor(dev, stdout);
706 }
707
708 /**
709  * Retrieve the apropriate playlist extension for this
710  * device. Rather hacky at the moment. This is probably
711  * desired by the managing software, but when creating
712  * lists on the device itself you notice certain preferences.
713  * @param ptp_usb the USB device to get suggestion for.
714  * @return the suggested playlist extension.
715  */
716 const char *get_playlist_extension(PTP_USB *ptp_usb) {
717     static char creative_pl_extension[] = ".zpl";
718     static char default_pl_extension[] = ".pla";
719     struct usb_device_desc desc;
720     openusb_parse_device_desc(libmtp_openusb_handle, *ptp_usb->handle, NULL, 0, &desc);
721     if (desc.idVendor == 0x041e)
722         return creative_pl_extension;
723     return default_pl_extension;
724 }
725
726 static void
727 libusb_glue_debug(PTPParams *params, const char *format, ...) {
728     va_list args;
729
730     va_start(args, format);
731     if (params->debug_func != NULL)
732         params->debug_func(params->data, format, args);
733     else {
734         vfprintf(stderr, format, args);
735         fprintf(stderr, "\n");
736         fflush(stderr);
737     }
738     va_end(args);
739 }
740
741 static void
742 libusb_glue_error(PTPParams *params, const char *format, ...) {
743     va_list args;
744
745     va_start(args, format);
746     if (params->error_func != NULL)
747         params->error_func(params->data, format, args);
748     else {
749         vfprintf(stderr, format, args);
750         fprintf(stderr, "\n");
751         fflush(stderr);
752     }
753     va_end(args);
754 }
755
756
757 /*
758  * ptp_read_func() and ptp_write_func() are
759  * based on same functions usb.c in libgphoto2.
760  * Much reading packet logs and having fun with trials and errors
761  * reveals that WMP / Windows is probably using an algorithm like this
762  * for large transfers:
763  *
764  * 1. Send the command (0x0c bytes) if headers are split, else, send
765  *    command plus sizeof(endpoint) - 0x0c bytes.
766  * 2. Send first packet, max size to be sizeof(endpoint) but only when using
767  *    split headers. Else goto 3.
768  * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
769  *    We call 0x10000 CONTEXT_BLOCK_SIZE.
770  * 4. Send remaining bytes MOD sizeof(endpoint)
771  * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
772  *    then also send a zero-length package.
773  *
774  * Further there is some special quirks to handle zero reads from the
775  * device, since some devices can't do them at all due to shortcomings
776  * of the USB slave controller in the device.
777  */
778 #define CONTEXT_BLOCK_SIZE_1    0x3e00
779 #define CONTEXT_BLOCK_SIZE_2  0x200
780 #define CONTEXT_BLOCK_SIZE    CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
781
782 static short
783 ptp_read_func(
784         unsigned long size, PTPDataHandler *handler, void *data,
785         unsigned long *readbytes,
786         int readzero
787         ) {
788     PTP_USB *ptp_usb = (PTP_USB *) data;
789     unsigned long toread = 0;
790     int ret = 0;
791     int xread;
792     unsigned long curread = 0;
793     unsigned long written;
794     unsigned char *bytes;
795     int expect_terminator_byte = 0;
796     unsigned long usb_inep_maxpacket_size;
797     unsigned long context_block_size_1;
798     unsigned long context_block_size_2;
799     uint16_t ptp_dev_vendor_id = ptp_usb->rawdevice.device_entry.vendor_id;
800
801     //"iRiver" device special handling
802     if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
803             usb_inep_maxpacket_size = ptp_usb->inep_maxpacket;
804             if (usb_inep_maxpacket_size == 0x400) {
805                     context_block_size_1 = CONTEXT_BLOCK_SIZE_1 - 0x200;
806                     context_block_size_2 = CONTEXT_BLOCK_SIZE_2 + 0x200;
807             }
808             else {
809                     context_block_size_1 = CONTEXT_BLOCK_SIZE_1;
810                     context_block_size_2 = CONTEXT_BLOCK_SIZE_2;
811             }
812     }
813     struct openusb_bulk_request bulk;
814     // This is the largest block we'll need to read in.
815     bytes = malloc(CONTEXT_BLOCK_SIZE);
816     while (curread < size) {
817
818         LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
819
820         // check equal to condition here
821         if (size - curread < CONTEXT_BLOCK_SIZE) {
822             // this is the last packet
823             toread = size - curread;
824             // this is equivalent to zero read for these devices
825             if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
826                 toread += 1;
827                 expect_terminator_byte = 1;
828             }
829         } else if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
830                 //"iRiver" device special handling
831                 if (curread == 0)
832                         // we are first packet, but not last packet
833                         toread = context_block_size_1;
834                 else if (toread == context_block_size_1)
835                         toread = context_block_size_2;
836                 else if (toread == context_block_size_2)
837                         toread = context_block_size_1;
838                 else
839                         LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
840                                     (unsigned int) toread, (unsigned int) (size - curread));
841         }
842         else
843                 toread = CONTEXT_BLOCK_SIZE;
844
845         LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
846
847         /*
848                 ret = USB_BULK_READ(ptp_usb->handle,
849                         ptp_usb->inep,
850                         bytes,
851                         toread,
852                         &xread,
853                         ptp_usb->timeout);
854          */
855         bulk.payload = bytes;
856         bulk.length = toread;
857         bulk.timeout = ptp_usb->timeout;
858         bulk.flags = 0;
859         bulk.next = NULL;
860         ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
861         xread = bulk.result.transferred_bytes;
862         LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread);
863
864         if (ret != OPENUSB_SUCCESS)
865             return PTP_ERROR_IO;
866
867         LIBMTP_USB_DEBUG("<==USB IN\n");
868         if (xread == 0)
869             LIBMTP_USB_DEBUG("Zero Read\n");
870         else
871             LIBMTP_USB_DATA(bytes, xread, 16);
872
873         // want to discard extra byte
874         if (expect_terminator_byte && xread == toread) {
875             LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
876
877             xread--;
878         }
879
880         int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written);
881         LIBMTP_USB_DEBUG("handler->putfunc ret = 0x%x\n", putfunc_ret);
882         if (putfunc_ret != PTP_RC_OK)
883             return putfunc_ret;
884
885         ptp_usb->current_transfer_complete += xread;
886         curread += xread;
887
888         // Increase counters, call callback
889         if (ptp_usb->callback_active) {
890             if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
891                 // send last update and disable callback.
892                 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
893                 ptp_usb->callback_active = 0;
894             }
895             if (ptp_usb->current_transfer_callback != NULL) {
896                 int ret;
897                 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
898                         ptp_usb->current_transfer_total,
899                         ptp_usb->current_transfer_callback_data);
900                 if (ret != 0) {
901                     return PTP_ERROR_CANCEL;
902                 }
903             }
904         }
905
906         if (xread < toread) /* short reads are common */
907             break;
908     }
909     if (readbytes) *readbytes = curread;
910     free(bytes);
911     LIBMTP_USB_DEBUG("Pointer Updated\n");
912     // there might be a zero packet waiting for us...
913     if (readzero &&
914             !FLAG_NO_ZERO_READS(ptp_usb) &&
915             curread % ptp_usb->outep_maxpacket == 0) {
916         unsigned char temp;
917         int zeroresult = 0, xread;
918
919         LIBMTP_USB_DEBUG("<==USB IN\n");
920         LIBMTP_USB_DEBUG("Zero Read\n");
921
922         /*
923                 zeroresult = USB_BULK_READ(ptp_usb->handle,
924                         ptp_usb->inep,
925                         &temp,
926                         0,
927                         &xread,
928                         ptp_usb->timeout);
929          */
930         bulk.payload = &temp;
931         bulk.length = 0;
932         bulk.timeout = ptp_usb->timeout;
933         bulk.flags = 0;
934         bulk.next = NULL;
935         ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
936         xread = bulk.result.transferred_bytes;
937         if (zeroresult != OPENUSB_SUCCESS)
938             LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
939     }
940     return PTP_RC_OK;
941 }
942
943 static short
944 ptp_write_func(
945         unsigned long size,
946         PTPDataHandler *handler,
947         void *data,
948         unsigned long *written
949         ) {
950     PTP_USB *ptp_usb = (PTP_USB *) data;
951     unsigned long towrite = 0;
952     int ret = 0;
953     unsigned long curwrite = 0;
954     unsigned char *bytes;
955
956     struct openusb_bulk_request bulk;
957
958     // This is the largest block we'll need to read in.
959     bytes = malloc(CONTEXT_BLOCK_SIZE);
960     if (!bytes) {
961         return PTP_ERROR_IO;
962     }
963     while (curwrite < size) {
964         unsigned long usbwritten = 0;
965         int xwritten;
966
967         towrite = size - curwrite;
968         if (towrite > CONTEXT_BLOCK_SIZE) {
969             towrite = CONTEXT_BLOCK_SIZE;
970         } else {
971             // This magic makes packets the same size that WMP send them.
972             if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
973                 towrite -= towrite % ptp_usb->outep_maxpacket;
974             }
975         }
976         int getfunc_ret = handler->getfunc(NULL, handler->priv, towrite, bytes, &towrite);
977         if (getfunc_ret != PTP_RC_OK)
978             return getfunc_ret;
979         while (usbwritten < towrite) {
980             /*
981                         ret = USB_BULK_WRITE(ptp_usb->handle,
982                                 ptp_usb->outep,
983                                 bytes + usbwritten,
984                                 towrite - usbwritten,
985                                 &xwritten,
986                                 ptp_usb->timeout);
987              */
988             bulk.payload = bytes + usbwritten;
989             bulk.length = towrite - usbwritten;
990             bulk.timeout = ptp_usb->timeout;
991             bulk.flags = 0;
992             bulk.next = NULL;
993             ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
994             xwritten = bulk.result.transferred_bytes;
995
996             LIBMTP_USB_DEBUG("USB OUT==>\n");
997
998             if (ret != OPENUSB_SUCCESS) {
999                 return PTP_ERROR_IO;
1000             }
1001             LIBMTP_USB_DATA(bytes + usbwritten, xwritten, 16);
1002             // check for result == 0 perhaps too.
1003             // Increase counters
1004             ptp_usb->current_transfer_complete += xwritten;
1005             curwrite += xwritten;
1006             usbwritten += xwritten;
1007         }
1008         // call callback
1009         if (ptp_usb->callback_active) {
1010             if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1011                 // send last update and disable callback.
1012                 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
1013                 ptp_usb->callback_active = 0;
1014             }
1015             if (ptp_usb->current_transfer_callback != NULL) {
1016                 int ret;
1017                 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1018                         ptp_usb->current_transfer_total,
1019                         ptp_usb->current_transfer_callback_data);
1020                 if (ret != 0) {
1021                     return PTP_ERROR_CANCEL;
1022                 }
1023             }
1024         }
1025         if (xwritten < towrite) /* short writes happen */
1026             break;
1027     }
1028     free(bytes);
1029     if (written) {
1030         *written = curwrite;
1031     }
1032
1033     // If this is the last transfer send a zero write if required
1034     if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1035         if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1036             int xwritten;
1037
1038             LIBMTP_USB_DEBUG("USB OUT==>\n");
1039             LIBMTP_USB_DEBUG("Zero Write\n");
1040
1041             /*
1042                         ret = USB_BULK_WRITE(ptp_usb->handle,
1043                                 ptp_usb->outep,
1044                                 (unsigned char *) "x",
1045                                 0,
1046                                 &xwritten,
1047                                 ptp_usb->timeout);
1048              */
1049             bulk.payload = (unsigned char *) "x";
1050             bulk.length = 0;
1051             bulk.timeout = ptp_usb->timeout;
1052             bulk.flags = 0;
1053             bulk.next = NULL;
1054             ret = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &bulk);
1055             xwritten = bulk.result.transferred_bytes;
1056         }
1057     }
1058
1059     if (ret != OPENUSB_SUCCESS)
1060         return PTP_ERROR_IO;
1061     return PTP_RC_OK;
1062 }
1063
1064 /* memory data get/put handler */
1065 typedef struct {
1066     unsigned char *data;
1067     unsigned long size, curoff;
1068 } PTPMemHandlerPrivate;
1069
1070 static uint16_t
1071 memory_getfunc(PTPParams* params, void* private,
1072         unsigned long wantlen, unsigned char *data,
1073         unsigned long *gotlen
1074         ) {
1075     PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1076     unsigned long tocopy = wantlen;
1077
1078     if (priv->curoff + tocopy > priv->size)
1079         tocopy = priv->size - priv->curoff;
1080     memcpy(data, priv->data + priv->curoff, tocopy);
1081     priv->curoff += tocopy;
1082     *gotlen = tocopy;
1083     return PTP_RC_OK;
1084 }
1085
1086 static uint16_t
1087 memory_putfunc(PTPParams* params, void* private,
1088         unsigned long sendlen, unsigned char *data,
1089         unsigned long *putlen
1090         ) {
1091     PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) private;
1092
1093     if (priv->curoff + sendlen > priv->size) {
1094         priv->data = realloc(priv->data, priv->curoff + sendlen);
1095         priv->size = priv->curoff + sendlen;
1096     }
1097     memcpy(priv->data + priv->curoff, data, sendlen);
1098     priv->curoff += sendlen;
1099     *putlen = sendlen;
1100     return PTP_RC_OK;
1101 }
1102
1103 /* init private struct for receiving data. */
1104 static uint16_t
1105 ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1106     PTPMemHandlerPrivate* priv;
1107     priv = malloc(sizeof (PTPMemHandlerPrivate));
1108     handler->priv = priv;
1109     handler->getfunc = memory_getfunc;
1110     handler->putfunc = memory_putfunc;
1111     priv->data = NULL;
1112     priv->size = 0;
1113     priv->curoff = 0;
1114     return PTP_RC_OK;
1115 }
1116
1117 /* init private struct and put data in for sending data.
1118  * data is still owned by caller.
1119  */
1120 static uint16_t
1121 ptp_init_send_memory_handler(PTPDataHandler *handler,
1122         unsigned char *data, unsigned long len
1123         ) {
1124     PTPMemHandlerPrivate* priv;
1125     priv = malloc(sizeof (PTPMemHandlerPrivate));
1126     if (!priv){
1127         return PTP_RC_GeneralError;
1128     }
1129     handler->priv = priv;
1130     handler->getfunc = memory_getfunc;
1131     handler->putfunc = memory_putfunc;
1132     priv->data = data;
1133     priv->size = len;
1134     priv->curoff = 0;
1135     return PTP_RC_OK;
1136 }
1137
1138 /* free private struct + data */
1139 static uint16_t
1140 ptp_exit_send_memory_handler(PTPDataHandler *handler) {
1141     PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1142     /* data is owned by caller */
1143     free(priv);
1144     return PTP_RC_OK;
1145 }
1146
1147 /* hand over our internal data to caller */
1148 static uint16_t
1149 ptp_exit_recv_memory_handler(PTPDataHandler *handler,
1150         unsigned char **data, unsigned long *size
1151         ) {
1152     PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*) handler->priv;
1153     *data = priv->data;
1154     *size = priv->size;
1155     free(priv);
1156     return PTP_RC_OK;
1157 }
1158
1159 /* send / receive functions */
1160
1161 uint16_t
1162 ptp_usb_sendreq(PTPParams* params, PTPContainer* req) {
1163     uint16_t ret;
1164     PTPUSBBulkContainer usbreq;
1165     PTPDataHandler memhandler;
1166     unsigned long written = 0;
1167     unsigned long towrite;
1168
1169     char txt[256];
1170
1171     (void) ptp_render_opcode(params, req->Code, sizeof (txt), txt);
1172     LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1173
1174     /* build appropriate USB container */
1175     usbreq.length = htod32(PTP_USB_BULK_REQ_LEN -
1176             (sizeof (uint32_t)*(5 - req->Nparam)));
1177     usbreq.type = htod16(PTP_USB_CONTAINER_COMMAND);
1178     usbreq.code = htod16(req->Code);
1179     usbreq.trans_id = htod32(req->Transaction_ID);
1180     usbreq.payload.params.param1 = htod32(req->Param1);
1181     usbreq.payload.params.param2 = htod32(req->Param2);
1182     usbreq.payload.params.param3 = htod32(req->Param3);
1183     usbreq.payload.params.param4 = htod32(req->Param4);
1184     usbreq.payload.params.param5 = htod32(req->Param5);
1185     /* send it to responder */
1186     towrite = PTP_USB_BULK_REQ_LEN - (sizeof (uint32_t)*(5 - req->Nparam));
1187     ptp_init_send_memory_handler(&memhandler, (unsigned char*) &usbreq, towrite);
1188     ret = ptp_write_func(
1189             towrite,
1190             &memhandler,
1191             params->data,
1192             &written
1193             );
1194     ptp_exit_send_memory_handler(&memhandler);
1195     if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) {
1196         ret = PTP_ERROR_IO;
1197     }
1198     if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1199         libusb_glue_error(params,
1200                 "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1201                 req->Code, written, towrite
1202                 );
1203         ret = PTP_ERROR_IO;
1204     }
1205     return ret;
1206 }
1207
1208 uint16_t
1209 ptp_usb_senddata(PTPParams* params, PTPContainer* ptp,
1210         uint64_t size, PTPDataHandler *handler
1211         ) {
1212     uint16_t ret;
1213     int wlen, datawlen;
1214     unsigned long written;
1215     PTPUSBBulkContainer usbdata;
1216     uint64_t bytes_left_to_transfer;
1217     PTPDataHandler memhandler;
1218
1219     LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1220
1221     /* build appropriate USB container */
1222     usbdata.length = htod32(PTP_USB_BULK_HDR_LEN + size);
1223     usbdata.type = htod16(PTP_USB_CONTAINER_DATA);
1224     usbdata.code = htod16(ptp->Code);
1225     usbdata.trans_id = htod32(ptp->Transaction_ID);
1226
1227     ((PTP_USB*) params->data)->current_transfer_complete = 0;
1228     ((PTP_USB*) params->data)->current_transfer_total = size + PTP_USB_BULK_HDR_LEN;
1229
1230     if (params->split_header_data) {
1231         datawlen = 0;
1232         wlen = PTP_USB_BULK_HDR_LEN;
1233     } else {
1234         unsigned long gotlen;
1235         /* For all camera devices. */
1236         datawlen = (size < PTP_USB_BULK_PAYLOAD_LEN_WRITE) ? size : PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1237         wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1238
1239         ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1240         if (ret != PTP_RC_OK){
1241             return ret;
1242         }
1243             
1244         if (gotlen != datawlen){
1245             return PTP_RC_GeneralError;
1246         }
1247     }
1248     ptp_init_send_memory_handler(&memhandler, (unsigned char *) &usbdata, wlen);
1249     /* send first part of data */
1250     ret = ptp_write_func(wlen, &memhandler, params->data, &written);
1251     ptp_exit_send_memory_handler(&memhandler);
1252     if (ret != PTP_RC_OK) {
1253         return ret;
1254     }
1255     if (size <= datawlen) return ret;
1256     /* if everything OK send the rest */
1257     bytes_left_to_transfer = size - datawlen;
1258     ret = PTP_RC_OK;
1259     while (bytes_left_to_transfer > 0) {
1260         ret = ptp_write_func(bytes_left_to_transfer, handler, params->data, &written);
1261         if (ret != PTP_RC_OK){
1262             break;
1263         }
1264         if (written == 0) {
1265             ret = PTP_ERROR_IO;
1266             break;
1267         }
1268         bytes_left_to_transfer -= written;
1269     }
1270     if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL)
1271         ret = PTP_ERROR_IO;
1272     return ret;
1273 }
1274
1275 static uint16_t ptp_usb_getpacket(PTPParams *params,
1276         PTPUSBBulkContainer *packet, unsigned long *rlen) {
1277     PTPDataHandler memhandler;
1278     uint16_t ret;
1279     unsigned char *x = NULL;
1280     unsigned long packet_size;
1281     PTP_USB *ptp_usb = (PTP_USB *) params->data;
1282
1283     packet_size = ptp_usb->inep_maxpacket;
1284
1285     /* read the header and potentially the first data */
1286     if (params->response_packet_size > 0) {
1287         /* If there is a buffered packet, just use it. */
1288         memcpy(packet, params->response_packet, params->response_packet_size);
1289         *rlen = params->response_packet_size;
1290         free(params->response_packet);
1291         params->response_packet = NULL;
1292         params->response_packet_size = 0;
1293         /* Here this signifies a "virtual read" */
1294         return PTP_RC_OK;
1295     }
1296     ptp_init_recv_memory_handler(&memhandler);
1297     ret = ptp_read_func(packet_size, &memhandler, params->data, rlen, 0);
1298     ptp_exit_recv_memory_handler(&memhandler, &x, rlen);
1299     if (x) {
1300         memcpy(packet, x, *rlen);
1301         free(x);
1302     }
1303     return ret;
1304 }
1305
1306 uint16_t
1307 ptp_usb_getdata(PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler) {
1308     uint16_t ret;
1309     PTPUSBBulkContainer usbdata;
1310     unsigned long written;
1311     PTP_USB *ptp_usb = (PTP_USB *) params->data;
1312     int putfunc_ret;
1313
1314     LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1315
1316     struct openusb_bulk_request bulk;
1317
1318     memset(&usbdata, 0, sizeof (usbdata));
1319     do {
1320         unsigned long len, rlen;
1321
1322         ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1323         if (ret != PTP_RC_OK) {
1324             ret = PTP_ERROR_IO;
1325             break;
1326         }
1327         if (dtoh16(usbdata.type) != PTP_USB_CONTAINER_DATA) {
1328             ret = PTP_ERROR_DATA_EXPECTED;
1329             break;
1330         }
1331         if (dtoh16(usbdata.code) != ptp->Code) {
1332             if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1333                 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1334                         "PTP header, code field insane, expect problems! (But continuing)");
1335                 // Repair the header, so it won't wreak more havoc, don't just ignore it.
1336                 // Typically these two fields will be broken.
1337                 usbdata.code = htod16(ptp->Code);
1338                 usbdata.trans_id = htod32(ptp->Transaction_ID);
1339                 ret = PTP_RC_OK;
1340             } else {
1341                 ret = dtoh16(usbdata.code);
1342                 // This filters entirely insane garbage return codes, but still
1343                 // makes it possible to return error codes in the code field when
1344                 // getting data. It appears Windows ignores the contents of this
1345                 // field entirely.
1346                 if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1347                     libusb_glue_debug(params, "ptp2/ptp_usb_getdata: detected a broken "
1348                             "PTP header, code field insane.");
1349                     ret = PTP_ERROR_IO;
1350                 }
1351                 break;
1352             }
1353         }
1354         if (rlen == ptp_usb->inep_maxpacket) {
1355             /* Copy first part of data to 'data' */
1356             putfunc_ret =
1357                     handler->putfunc(
1358                     params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1359                     &written
1360                     );
1361             if (putfunc_ret != PTP_RC_OK)
1362                 return putfunc_ret;
1363
1364             /* stuff data directly to passed data handler */
1365             while (1) {
1366                 unsigned long readdata;
1367                 uint16_t xret;
1368
1369                 xret = ptp_read_func(
1370                         0x20000000,
1371                         handler,
1372                         params->data,
1373                         &readdata,
1374                         0
1375                         );
1376                 if (xret != PTP_RC_OK)
1377                     return xret;
1378                 if (readdata < 0x20000000)
1379                     break;
1380             }
1381             return PTP_RC_OK;
1382         }
1383         if (rlen > dtoh32(usbdata.length)) {
1384             /*
1385              * Buffer the surplus response packet if it is >=
1386              * PTP_USB_BULK_HDR_LEN
1387              * (i.e. it is probably an entire package)
1388              * else discard it as erroneous surplus data.
1389              * This will even work if more than 2 packets appear
1390              * in the same transaction, they will just be handled
1391              * iteratively.
1392              *
1393              * Marcus observed stray bytes on iRiver devices;
1394              * these are still discarded.
1395              */
1396             unsigned int packlen = dtoh32(usbdata.length);
1397             unsigned int surplen = rlen - packlen;
1398
1399             if (surplen >= PTP_USB_BULK_HDR_LEN) {
1400                 params->response_packet = malloc(surplen);
1401                 memcpy(params->response_packet,
1402                         (uint8_t *) & usbdata + packlen, surplen);
1403                 params->response_packet_size = surplen;
1404                 /* Ignore reading one extra byte if device flags have been set */
1405             } else if (!FLAG_NO_ZERO_READS(ptp_usb) &&
1406                     (rlen - dtoh32(usbdata.length) == 1)) {
1407                 libusb_glue_debug(params, "ptp2/ptp_usb_getdata: read %d bytes "
1408                         "too much, expect problems!",
1409                         rlen - dtoh32(usbdata.length));
1410             }
1411             rlen = packlen;
1412         }
1413
1414         /* For most PTP devices rlen is 512 == sizeof(usbdata)
1415          * here. For MTP devices splitting header and data it might
1416          * be 12.
1417          */
1418         /* Evaluate full data length. */
1419         len = dtoh32(usbdata.length) - PTP_USB_BULK_HDR_LEN;
1420
1421         /* autodetect split header/data MTP devices */
1422         if (dtoh32(usbdata.length) > 12 && (rlen == 12))
1423             params->split_header_data = 1;
1424
1425         /* Copy first part of data to 'data' */
1426         putfunc_ret =
1427                 handler->putfunc(
1428                 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1429                 usbdata.payload.data,
1430                 &written
1431                 );
1432         if (putfunc_ret != PTP_RC_OK)
1433             return putfunc_ret;
1434
1435         if (FLAG_NO_ZERO_READS(ptp_usb) &&
1436                 len + PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket) {
1437
1438             LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1439
1440             // need to read in extra byte and discard it
1441             int result = 0, xread;
1442             unsigned char byte = 0;
1443
1444             /*
1445                         result = USB_BULK_READ(ptp_usb->handle,
1446                                 ptp_usb->inep,
1447                                 &byte,
1448                                 1,
1449                                 &xread,
1450                                 ptp_usb->timeout);
1451              */
1452
1453             bulk.payload = &byte;
1454             bulk.length = 1;
1455             bulk.timeout = ptp_usb->timeout;
1456             bulk.flags = 0;
1457             bulk.next = NULL;
1458             result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1459             xread = bulk.result.transferred_bytes;
1460
1461             if (result != 1)
1462                 LIBMTP_INFO("Could not read in extra byte for %d bytes long file, return value 0x%04x\n", ptp_usb->inep_maxpacket, result);
1463         } else if (len + PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket && params->split_header_data == 0) {
1464             int zeroresult = 0, xread;
1465             unsigned char zerobyte = 0;
1466
1467             LIBMTP_INFO("Reading in zero packet after header\n");
1468             /*
1469                         zeroresult = USB_BULK_READ(ptp_usb->handle,
1470                                 ptp_usb->inep,
1471                                 &zerobyte,
1472                                 0,
1473                                 &xread,
1474                                 ptp_usb->timeout);
1475              */
1476
1477             bulk.payload = &zerobyte;
1478             bulk.length = 0;
1479             bulk.timeout = ptp_usb->timeout;
1480             bulk.flags = 0;
1481             bulk.next = NULL;
1482             zeroresult = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->inep, &bulk);
1483             xread = bulk.result.transferred_bytes;
1484
1485             if (zeroresult != 0)
1486                 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1487         }
1488
1489         /* Is that all of data? */
1490         if (len + PTP_USB_BULK_HDR_LEN <= rlen) {
1491             break;
1492         }
1493
1494         ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1495                 handler,
1496                 params->data, &rlen, 1);
1497
1498         if (ret != PTP_RC_OK) {
1499             break;
1500         }
1501     } while (0);
1502     return ret;
1503 }
1504
1505 uint16_t
1506 ptp_usb_getresp(PTPParams* params, PTPContainer* resp) {
1507     uint16_t ret;
1508     unsigned long rlen;
1509     PTPUSBBulkContainer usbresp;
1510     PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1511
1512
1513     LIBMTP_USB_DEBUG("RESPONSE: ");
1514     memset(&usbresp, 0, sizeof (usbresp));
1515     /* read response, it should never be longer than sizeof(usbresp) */
1516     ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1517     // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1518     // sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1519     // after a NULL packet when it should send the response. This code ignores
1520     // such illegal packets.
1521     while (ret == PTP_RC_OK && rlen < PTP_USB_BULK_HDR_LEN && usbresp.length == 0) {
1522         libusb_glue_debug(params, "ptp_usb_getresp: detected short response "
1523                 "of %d bytes, expect problems! (re-reading "
1524                 "response), rlen");
1525         ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1526     }
1527     if (ret != PTP_RC_OK) {
1528         ret = PTP_ERROR_IO;
1529     } else
1530         if (dtoh16(usbresp.type) != PTP_USB_CONTAINER_RESPONSE) {
1531         ret = PTP_ERROR_RESP_EXPECTED;
1532     } else
1533         if (dtoh16(usbresp.code) != resp->Code) {
1534         ret = dtoh16(usbresp.code);
1535     }
1536
1537     LIBMTP_USB_DEBUG("%04x\n", ret);
1538     if (ret != PTP_RC_OK) {
1539         /*              libusb_glue_error (params,
1540                         "PTP: request code 0x%04x getting resp error 0x%04x",
1541                                 resp->Code, ret);*/
1542         return ret;
1543     }
1544     /* build an appropriate PTPContainer */
1545     resp->Code = dtoh16(usbresp.code);
1546     resp->SessionID = params->session_id;
1547     resp->Transaction_ID = dtoh32(usbresp.trans_id);
1548     if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1549         if (resp->Transaction_ID != params->transaction_id - 1) {
1550             libusb_glue_debug(params, "ptp_usb_getresp: detected a broken "
1551                     "PTP header, transaction ID insane, expect "
1552                     "problems! (But continuing)");
1553             // Repair the header, so it won't wreak more havoc.
1554             resp->Transaction_ID = params->transaction_id - 1;
1555         }
1556     }
1557     resp->Param1 = dtoh32(usbresp.payload.params.param1);
1558     resp->Param2 = dtoh32(usbresp.payload.params.param2);
1559     resp->Param3 = dtoh32(usbresp.payload.params.param3);
1560     resp->Param4 = dtoh32(usbresp.payload.params.param4);
1561     resp->Param5 = dtoh32(usbresp.payload.params.param5);
1562     return ret;
1563 }
1564
1565 /* Event handling functions */
1566
1567 /* PTP Events wait for or check mode */
1568 #define PTP_EVENT_CHECK                 0x0000  /* waits for */
1569 #define PTP_EVENT_CHECK_FAST            0x0001  /* checks */
1570
1571 static inline uint16_t
1572 ptp_usb_event(PTPParams* params, PTPContainer* event, int wait) {
1573     uint16_t ret;
1574     int result, xread;
1575     unsigned long rlen;
1576     PTPUSBEventContainer usbevent;
1577     PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1578
1579     struct openusb_bulk_request bulk;
1580
1581     memset(&usbevent, 0, sizeof (usbevent));
1582
1583     if ((params == NULL) || (event == NULL))
1584         return PTP_ERROR_BADPARAM;
1585     ret = PTP_RC_OK;
1586     switch (wait) {
1587         case PTP_EVENT_CHECK:
1588
1589             /*
1590                         result = USB_BULK_READ(ptp_usb->handle,
1591                                 ptp_usb->intep,
1592                                 (unsigned char *) &usbevent,
1593                                 sizeof (usbevent),
1594                                 &xread,
1595                                 0);
1596              */
1597             bulk.payload = (unsigned char *) &usbevent;
1598             bulk.length = sizeof (usbevent);
1599             bulk.timeout = ptp_usb->timeout;
1600             bulk.flags = 0;
1601             bulk.next = NULL;
1602             result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1603             xread = bulk.result.transferred_bytes;
1604
1605             if (result == 0) {
1606                 /*
1607                                 result = USB_BULK_READ(ptp_usb->handle,
1608                                     ptp_usb->intep,
1609                                     (unsigned char *) &usbevent,
1610                                     sizeof (usbevent),
1611                                     &xread,
1612                                     0);
1613                  */
1614                 bulk.payload = (unsigned char *) &usbevent;
1615                 bulk.length = sizeof (usbevent);
1616                 bulk.timeout = ptp_usb->timeout;
1617                 bulk.flags = 0;
1618                 bulk.next = NULL;
1619                 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1620                 xread = bulk.result.transferred_bytes;
1621             }
1622             if (result < 0) ret = PTP_ERROR_IO;
1623             break;
1624         case PTP_EVENT_CHECK_FAST:
1625             /*
1626                         result = USB_BULK_READ(ptp_usb->handle,
1627                                 ptp_usb->intep,
1628                                 (unsigned char *) &usbevent,
1629                                 sizeof (usbevent),
1630                                 &xread,
1631                                 ptp_usb->timeout);
1632              */
1633             bulk.payload = (unsigned char *) &usbevent;
1634             bulk.length = sizeof (usbevent);
1635             bulk.timeout = ptp_usb->timeout;
1636             bulk.flags = 0;
1637             bulk.next = NULL;
1638             result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1639             xread = bulk.result.transferred_bytes;
1640
1641             if (result == 0) {
1642                 /*
1643                                 result = USB_BULK_READ(ptp_usb->handle,
1644                                         ptp_usb->intep,
1645                                         (unsigned char *) &usbevent,
1646                                         sizeof (usbevent),
1647                                         &xread,
1648                                         ptp_usb->timeout);
1649                  */
1650                 bulk.payload = (unsigned char *) &usbevent;
1651                 bulk.length = sizeof (usbevent);
1652                 bulk.timeout = ptp_usb->timeout;
1653                 bulk.flags = 0;
1654                 bulk.next = NULL;
1655                 result = openusb_bulk_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->intep, &bulk);
1656                 xread = bulk.result.transferred_bytes;
1657             }
1658             if (result < 0) ret = PTP_ERROR_IO;
1659             break;
1660         default:
1661             ret = PTP_ERROR_BADPARAM;
1662             break;
1663     }
1664     if (ret != PTP_RC_OK) {
1665         libusb_glue_error(params,
1666                 "PTP: reading event an error 0x%04x occurred", ret);
1667         return PTP_ERROR_IO;
1668     }
1669     rlen = result;
1670     if (rlen < 8) {
1671         libusb_glue_error(params,
1672                 "PTP: reading event an short read of %ld bytes occurred", rlen);
1673         return PTP_ERROR_IO;
1674     }
1675     /* if we read anything over interrupt endpoint it must be an event */
1676     /* build an appropriate PTPContainer */
1677     event->Code = dtoh16(usbevent.code);
1678     event->SessionID = params->session_id;
1679     event->Transaction_ID = dtoh32(usbevent.trans_id);
1680     event->Param1 = dtoh32(usbevent.param1);
1681     event->Param2 = dtoh32(usbevent.param2);
1682     event->Param3 = dtoh32(usbevent.param3);
1683     return ret;
1684 }
1685
1686 uint16_t
1687 ptp_usb_event_check(PTPParams* params, PTPContainer* event) {
1688
1689     return ptp_usb_event(params, event, PTP_EVENT_CHECK_FAST);
1690 }
1691
1692 uint16_t
1693 ptp_usb_event_wait(PTPParams* params, PTPContainer* event) {
1694
1695     return ptp_usb_event(params, event, PTP_EVENT_CHECK);
1696 }
1697
1698 uint16_t
1699 ptp_usb_control_cancel_request(PTPParams *params, uint32_t transactionid) {
1700     PTP_USB *ptp_usb = (PTP_USB *) (params->data);
1701     int ret;
1702     unsigned char buffer[6];
1703
1704     htod16a(&buffer[0], PTP_EC_CancelTransaction);
1705     htod32a(&buffer[2], transactionid);
1706     /*
1707             ret = libusb_control_transfer(ptp_usb->handle,
1708                                   LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
1709                                   0x64, 0x0000, 0x0000,
1710                                   buffer,
1711                                   sizeof(buffer),
1712                                   ptp_usb->timeout);
1713      */
1714     struct openusb_ctrl_request ctrl;
1715     ctrl.setup.bmRequestType = USB_REQ_TYPE_CLASS | USB_RECIP_INTERFACE;
1716     ctrl.setup.bRequest = 0x64;
1717     ctrl.setup.wValue = 0;
1718     ctrl.setup.wIndex = 0;
1719     ctrl.payload = (unsigned char *)&buffer; // Out
1720     ctrl.length = sizeof (buffer);
1721     ctrl.timeout = ptp_usb->timeout;
1722     ctrl.next = NULL;
1723     ctrl.flags = 0;
1724
1725     ret = openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1726     if (ctrl.result.transferred_bytes < sizeof (buffer))
1727         return PTP_ERROR_IO;
1728     return PTP_RC_OK;
1729 }
1730
1731 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, openusb_dev_handle_t* dev) {
1732     openusb_dev_handle_t device_handle;
1733     unsigned char buf[255];
1734     int ret, usbresult;
1735
1736     params->sendreq_func = ptp_usb_sendreq;
1737     params->senddata_func = ptp_usb_senddata;
1738     params->getresp_func = ptp_usb_getresp;
1739     params->getdata_func = ptp_usb_getdata;
1740     params->cancelreq_func = ptp_usb_control_cancel_request;
1741     params->data = ptp_usb;
1742     params->transaction_id = 0;
1743     /*
1744      * This is hardcoded here since we have no devices whatsoever that are BE.
1745      * Change this the day we run into our first BE device (if ever).
1746      */
1747     params->byteorder = PTP_DL_LE;
1748
1749     ptp_usb->timeout = get_timeout(ptp_usb);
1750
1751     ret = openusb_open_device(libmtp_openusb_handle, *dev, USB_INIT_DEFAULT, &device_handle);
1752     if (ret != OPENUSB_SUCCESS) {
1753         perror("usb_open()");
1754         return -1;
1755     }
1756     ptp_usb->handle = malloc(sizeof(openusb_dev_handle_t));
1757     *ptp_usb->handle = device_handle;
1758     /*
1759      * If this device is known to be wrongfully claimed by other kernel
1760      * drivers (such as mass storage), then try to unload it to make it
1761      * accessible from user space.
1762      * Note: OpenUSB doesn't support this type of operation?
1763      */
1764     /*
1765       if (FLAG_UNLOAD_DRIVER(ptp_usb) &&
1766           libusb_kernel_driver_active (device_handle, ptp_usb->interface)
1767       ) {
1768           if (OPENUSB_SUCCESS != libusb_detach_kernel_driver (device_handle, ptp_usb->interface)) {
1769             return -1;
1770           }
1771       }
1772      */
1773     // It seems like on kernel 2.6.31 if we already have it open on another
1774     // pthread in our app, we'll get an error if we try to claim it again,
1775     // but that error is harmless because our process already claimed the interface
1776     usbresult = openusb_claim_interface(device_handle, ptp_usb->interface, USB_INIT_DEFAULT);
1777
1778     if (usbresult != 0)
1779         fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1780
1781     if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1782         int ret;
1783
1784         // FIXME : Only for BlackBerry Storm
1785         // What does it mean? Maybe switch mode...
1786         // This first control message is absolutely necessary
1787         usleep(1000);
1788         /*
1789                 ret = libusb_control_transfer(device_handle,
1790                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1791                         0xaa, 0x00, 0x04, buf, 0x40, 1000);
1792          */
1793         struct openusb_ctrl_request ctrl;
1794         ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1795         ctrl.setup.bRequest = 0xaa;
1796         ctrl.setup.wValue = 0;
1797         ctrl.setup.wIndex = 4;
1798         ctrl.payload = (unsigned char *)&buf; // Out
1799         ctrl.length = 0x40;
1800         ctrl.timeout = 1000;
1801         ctrl.next = NULL;
1802         ctrl.flags = 0;
1803
1804         ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1805         LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1806         LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1807
1808         usleep(1000);
1809         // This control message is unnecessary
1810         /*
1811                 ret = libusb_control_transfer(device_handle,
1812                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1813                         0xa5, 0x00, 0x01, buf, 0x02, 1000);
1814          */
1815         ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1816         ctrl.setup.bRequest = 0xa5;
1817         ctrl.setup.wValue = 0;
1818         ctrl.setup.wIndex = 1;
1819         ctrl.payload = (unsigned char *)&buf; // Out
1820         ctrl.length = 0x02;
1821         ctrl.timeout = 1000;
1822         ctrl.next = NULL;
1823         ctrl.flags = 0;
1824
1825         ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1826         LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1827         LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1828
1829         usleep(1000);
1830         // This control message is unnecessary
1831         /*
1832                 ret = libusb_control_transfer(device_handle,
1833                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1834                         0xa8, 0x00, 0x01, buf, 0x05, 1000);
1835          */
1836         ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1837         ctrl.setup.bRequest = 0xa8;
1838         ctrl.setup.wValue = 0;
1839         ctrl.setup.wIndex = 1;
1840         ctrl.payload = (unsigned char *)&buf; // Out
1841         ctrl.length = 0x05;
1842         ctrl.timeout = 1000;
1843         ctrl.next = NULL;
1844         ctrl.flags = 0;
1845
1846         ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1847         LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1848         LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1849
1850         usleep(1000);
1851         // This control message is unnecessary
1852         /*
1853                 ret = libusb_control_transfer(device_handle,
1854                         LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1855                         0xa8, 0x00, 0x01, buf, 0x11, 1000);
1856          */
1857         ctrl.setup.bmRequestType = USB_REQ_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN;
1858         ctrl.setup.bRequest = 0xa8;
1859         ctrl.setup.wValue = 0;
1860         ctrl.setup.wIndex = 1;
1861         ctrl.payload = (unsigned char *)&buf; // Out
1862         ctrl.length = 0x11;
1863         ctrl.timeout = 1000;
1864         ctrl.next = NULL;
1865         ctrl.flags = 0;
1866
1867         ret = openusb_ctrl_xfer(device_handle, ptp_usb->interface, ptp_usb->outep, &ctrl);
1868         LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1869         LIBMTP_USB_DATA(buf, ctrl.result.transferred_bytes, 16);
1870
1871         usleep(1000);
1872     }
1873     return 0;
1874 }
1875
1876 static void clear_stall(PTP_USB* ptp_usb) {
1877     uint16_t status;
1878     int ret;
1879
1880     /* check the inep status */
1881     /*
1882         status = 0;
1883         ret = usb_get_endpoint_status(ptp_usb, ptp_usb->inep, &status);
1884         if (ret < 0) {
1885             perror("inep: usb_get_endpoint_status()");
1886         } else if (status) {
1887             LIBMTP_INFO("Clearing stall on IN endpoint\n");
1888             ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1889             if (ret != OPENUSB_SUCCESS) {
1890                 perror("usb_clear_stall_feature()");
1891             }
1892         }
1893
1894         /* check the outep status */
1895     /*status = 0;
1896     ret = usb_get_endpoint_status(ptp_usb, ptp_usb->outep, &status);
1897     if (ret < 0) {
1898         perror("outep: usb_get_endpoint_status()");
1899     } else if (status) {
1900         LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1901         ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1902         if (ret != OPENUSB_SUCCESS) {
1903             perror("usb_clear_stall_feature()");
1904         }
1905     }
1906      */
1907
1908     /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1909 }
1910
1911 static void clear_halt(PTP_USB* ptp_usb) {
1912     int ret;
1913
1914     /*
1915         ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->inep);
1916         if (ret < 0) {
1917             perror("usb_clear_halt() on IN endpoint");
1918         }
1919         ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1920         if (ret < 0) {
1921             perror("usb_clear_halt() on OUT endpoint");
1922         }
1923         ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->intep);
1924         if (ret < 0) {
1925             perror("usb_clear_halt() on INTERRUPT endpoint");
1926         }
1927      */
1928 }
1929
1930 static void close_usb(PTP_USB* ptp_usb) {
1931     if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1932         /*
1933          * Clear any stalled endpoints
1934          * On misbehaving devices designed for Windows/Mac, quote from:
1935          * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1936          * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1937          * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1938          * and presumes that the stall has cleared.  Some devices actually choke
1939          * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1940          * STALL is persistant or not).
1941          */
1942         clear_stall(ptp_usb);
1943         // Clear halts on any endpoints
1944         clear_halt(ptp_usb);
1945         // Added to clear some stuff on the OUT endpoint
1946         // TODO: is this good on the Mac too?
1947         // HINT: some devices may need that you comment these two out too.
1948         //libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1949         //libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1950     }
1951     if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1952         /*
1953          * Some devices really love to get reset after being
1954          * disconnected. Again, since Windows never disconnects
1955          * a device closing behaviour is seldom or never exercised
1956          * on devices when engineered and often error prone.
1957          * Reset may help some.
1958          */
1959         openusb_reset(*ptp_usb->handle);
1960     }
1961     openusb_close_device(*ptp_usb->handle);
1962 }
1963
1964 /**
1965  * Self-explanatory?
1966  */
1967 static int find_interface_and_endpoints(openusb_dev_handle_t *dev,
1968         uint8_t *conf,
1969         uint8_t *interface,
1970         uint8_t *altsetting,
1971         int* inep,
1972         int* inep_maxpacket,
1973         int* outep,
1974         int *outep_maxpacket,
1975         int* intep) {
1976     uint8_t i;
1977     int ret;
1978     struct usb_device_desc desc;
1979
1980     ret = openusb_parse_device_desc(libmtp_openusb_handle, *dev, NULL, 0, &desc);
1981     if (ret != OPENUSB_SUCCESS) return -1;
1982
1983     // Loop over the device configurations
1984     for (i = 0; i < desc.bNumConfigurations; i++) {
1985         uint8_t j;
1986         struct usb_config_desc config;
1987
1988         ret = openusb_parse_config_desc(libmtp_openusb_handle, *dev, NULL, 0, i, &config);
1989         if (ret != OPENUSB_SUCCESS) continue;
1990         *conf = desc.bConfigurationValue;
1991         // Loop over each configurations interfaces
1992         for (j = 0; j < config.bNumInterfaces; j++) {
1993             uint8_t k;
1994             uint8_t no_ep;
1995             int found_inep = 0;
1996             int found_outep = 0;
1997             int found_intep = 0;
1998             struct usb_endpoint_desc ep;
1999             struct usb_interface_desc ifcdesc;
2000             openusb_parse_interface_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, &ifcdesc);
2001             // MTP devices shall have 3 endpoints, ignore those interfaces
2002             // that haven't.
2003             no_ep = ifcdesc.bNumEndpoints;
2004             if (no_ep != 3)
2005                 continue;
2006             *interface = ifcdesc.bInterfaceNumber;
2007             *altsetting = ifcdesc.bAlternateSetting;
2008             // Loop over the three endpoints to locate two bulk and
2009             // one interrupt endpoint and FAIL if we cannot, and continue.
2010             for (k = 0; k < no_ep; k++) {
2011                 openusb_parse_endpoint_desc(libmtp_openusb_handle, *dev, NULL, 0, i, j, 0, k, &ep);
2012                 if (ep.bmAttributes == USB_ENDPOINT_TYPE_BULK) {
2013                     if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2014                             USB_ENDPOINT_DIR_MASK) {
2015                         *inep = ep.bEndpointAddress;
2016                         *inep_maxpacket = ep.wMaxPacketSize;
2017                         found_inep = 1;
2018                     }
2019                     if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) {
2020                         *outep = ep.bEndpointAddress;
2021                         *outep_maxpacket = ep.wMaxPacketSize;
2022                         found_outep = 1;
2023                     }
2024                 } else if (ep.bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) {
2025                     if ((ep.bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
2026                             USB_ENDPOINT_DIR_MASK) {
2027                         *intep = ep.bEndpointAddress;
2028                         found_intep = 1;
2029                     }
2030                 }
2031             }
2032             if (found_inep && found_outep && found_intep) {
2033                 // We assigned the endpoints so return here.
2034                 return 0;
2035             }
2036             // Else loop to next interface/config
2037         }
2038     }
2039     return -1;
2040 }
2041
2042 /**
2043  * This function assigns params and usbinfo given a raw device
2044  * as input.
2045  * @param device the device to be assigned.
2046  * @param usbinfo a pointer to the new usbinfo.
2047  * @return an error code.
2048  */
2049 LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
2050         PTPParams *params,
2051         void **usbinfo) {
2052     PTP_USB *ptp_usb;
2053     openusb_devid_t *ldevice;
2054     uint16_t ret = 0;
2055     int err, found = 0, i;
2056     unsigned int nrofdevs;
2057     openusb_devid_t *devs = NULL;
2058     struct usb_device_desc desc;
2059
2060     /* See if we can find this raw device again... */
2061     init_usb();
2062
2063     openusb_get_devids_by_bus(libmtp_openusb_handle, 0, &devs, &nrofdevs);
2064     for (i = 0; i < nrofdevs; i++) {
2065         /*
2066                 if (libusb_get_bus_number(devs[i]) != device->bus_location)
2067                     continue;
2068                 if (libusb_get_device_address(devs[i]) != device->devnum)
2069                     continue;
2070          */
2071
2072         ret = openusb_parse_device_desc(libmtp_openusb_handle, devs[i], NULL, 0, &desc);
2073         if (ret != OPENUSB_SUCCESS) continue;
2074
2075         if (desc.idVendor == device->device_entry.vendor_id &&
2076                 desc.idProduct == device->device_entry.product_id) {
2077             ldevice = &devs[i];
2078             found = 1;
2079             break;
2080         }
2081     }
2082     /* Device has gone since detecting raw devices! */
2083     if (!found) {
2084         openusb_free_devid_list(devs);
2085         return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
2086     }
2087
2088     /* Allocate structs */
2089     ptp_usb = (PTP_USB *) malloc(sizeof (PTP_USB));
2090     if (ptp_usb == NULL) {
2091         openusb_free_devid_list(devs);
2092         return LIBMTP_ERROR_MEMORY_ALLOCATION;
2093     }
2094     /* Start with a blank slate (includes setting device_flags to 0) */
2095     memset(ptp_usb, 0, sizeof (PTP_USB));
2096
2097     /* Copy the raw device */
2098     memcpy(&ptp_usb->rawdevice, device, sizeof (LIBMTP_raw_device_t));
2099
2100     /*
2101      * Some devices must have their "OS Descriptor" massaged in order
2102      * to work.
2103      */
2104     if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
2105         // Massage the device descriptor
2106         (void) probe_device_descriptor(ldevice, NULL);
2107     }
2108
2109
2110     /* Assign interface and endpoints to usbinfo... */
2111     err = find_interface_and_endpoints(ldevice,
2112             &ptp_usb->conf,
2113             &ptp_usb->interface,
2114             &ptp_usb->altsetting,
2115             &ptp_usb->inep,
2116             &ptp_usb->inep_maxpacket,
2117             &ptp_usb->outep,
2118             &ptp_usb->outep_maxpacket,
2119             &ptp_usb->intep);
2120
2121     if (err) {
2122         openusb_free_devid_list(devs);
2123         LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
2124         return LIBMTP_ERROR_CONNECTING;
2125     }
2126
2127     /* Copy USB version number */
2128     ptp_usb->bcdusb = desc.bcdUSB;
2129
2130     /* Attempt to initialize this device */
2131     if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2132         LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
2133         return LIBMTP_ERROR_CONNECTING;
2134     }
2135
2136     /*
2137      * This works in situations where previous bad applications
2138      * have not used LIBMTP_Release_Device on exit
2139      */
2140     if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2141         LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
2142         LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2143         openusb_reset(*ptp_usb->handle);
2144         close_usb(ptp_usb);
2145
2146         if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2147             LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2148             return LIBMTP_ERROR_CONNECTING;
2149         }
2150
2151         /* Device has been reset, try again */
2152         if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2153             LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2154             return LIBMTP_ERROR_CONNECTING;
2155         }
2156     }
2157
2158     /* Was the transaction id invalid? Try again */
2159     if (ret == PTP_RC_InvalidTransactionID) {
2160         LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2161         params->transaction_id += 10;
2162         ret = ptp_opensession(params, 1);
2163     }
2164
2165     if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2166         LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2167                 "(Return code %d)\n  Try to reset the device.\n",
2168                 ret);
2169         openusb_release_interface(*ptp_usb->handle, ptp_usb->interface);
2170         return LIBMTP_ERROR_CONNECTING;
2171     }
2172
2173     /* OK configured properly */
2174     *usbinfo = (void *) ptp_usb;
2175     return LIBMTP_ERROR_NONE;
2176 }
2177
2178 void close_device(PTP_USB *ptp_usb, PTPParams *params) {
2179     if (ptp_closesession(params) != PTP_RC_OK)
2180         LIBMTP_ERROR("ERROR: Could not close session!\n");
2181     close_usb(ptp_usb);
2182 }
2183
2184 void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout) {
2185     ptp_usb->timeout = timeout;
2186 }
2187
2188 void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout) {
2189     *timeout = ptp_usb->timeout;
2190 }
2191
2192 int guess_usb_speed(PTP_USB *ptp_usb) {
2193     int bytes_per_second;
2194
2195     /*
2196      * We don't know the actual speeds so these are rough guesses
2197      * from the info you can find here:
2198      * http://en.wikipedia.org/wiki/USB#Transfer_rates
2199      * http://www.barefeats.com/usb2.html
2200      */
2201     switch (ptp_usb->bcdusb & 0xFF00) {
2202         case 0x0100:
2203             /* 1.x USB versions let's say 1MiB/s */
2204             bytes_per_second = 1 * 1024 * 1024;
2205             break;
2206         case 0x0200:
2207         case 0x0300:
2208             /* USB 2.0 nominal speed 18MiB/s */
2209             /* USB 3.0 won't be worse? */
2210             bytes_per_second = 18 * 1024 * 1024;
2211             break;
2212         default:
2213             /* Half-guess something? */
2214             bytes_per_second = 1 * 1024 * 1024;
2215             break;
2216     }
2217     return bytes_per_second;
2218 }
2219
2220 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status) {
2221     /*
2222       return libusb_control_transfer(ptp_usb->handle,
2223                               LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT,
2224                               LIBUSB_REQUEST_GET_STATUS,
2225                               USB_FEATURE_HALT,
2226                               ep,
2227                               (unsigned char *) status,
2228                               2,
2229                               ptp_usb->timeout);
2230      */
2231     struct openusb_ctrl_request ctrl;
2232     ctrl.flags = 0;
2233     ctrl.length = 2;
2234     ctrl.payload = (unsigned char *)status;
2235     ctrl.timeout = ptp_usb->timeout;
2236     ctrl.next = NULL;
2237     ctrl.setup.bRequest = USB_REQ_GET_STATUS;
2238     ctrl.setup.bmRequestType = USB_ENDPOINT_IN | USB_RECIP_ENDPOINT;
2239     ctrl.setup.wIndex = ep;
2240     ctrl.setup.wValue = USB_FEATURE_HALT;
2241     openusb_ctrl_xfer(*ptp_usb->handle, ptp_usb->interface, ep, &ctrl);
2242     return ctrl.result.status;
2243
2244 }