3 * Low-level USB interface glue towards libusb.
5 * Copyright (C) 2005-2007 Richard A. Low <richard@wentnet.com>
6 * Copyright (C) 2005-2012 Linus Walleij <triad@df.lth.se>
7 * Copyright (C) 2006-2007 Marcus Meissner
8 * Copyright (C) 2007 Ted Bullock
9 * Copyright (C) 2008 Chris Bagwell <chris@cnpbagwell.com>
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.
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.
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.
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.)
34 #include "libusb-glue.h"
35 #include "device-flags.h"
47 /* Aha, older libusb does not have USB_CLASS_PTP */
49 #define USB_CLASS_PTP 6
53 * Default USB timeout length. This can be overridden as needed
54 * but should start with a reasonable value so most common
55 * requests can be completed. The original value of 4000 was
56 * not long enough for large file transfer. Also, players can
57 * spend a bit of time collecting data. Higher values also
58 * make connecting/disconnecting more reliable.
60 #define USB_TIMEOUT_DEFAULT 20000
61 #define USB_TIMEOUT_LONG 60000
62 static inline int get_timeout(PTP_USB* ptp_usb)
64 if (FLAG_LONG_TIMEOUT(ptp_usb)) {
65 return USB_TIMEOUT_LONG;
67 return USB_TIMEOUT_DEFAULT;
70 /* USB control message data phase direction */
72 #define USB_DP_HTD (0x00 << 7) /* host to device */
75 #define USB_DP_DTH (0x01 << 7) /* device to host */
78 /* USB Feature selector HALT */
79 #ifndef USB_FEATURE_HALT
80 #define USB_FEATURE_HALT 0x00
83 /* Internal data types */
84 struct mtpdevice_list_struct {
85 struct usb_device *libusb_device;
88 uint32_t bus_location;
89 struct mtpdevice_list_struct *next;
91 typedef struct mtpdevice_list_struct mtpdevice_list_t;
93 static const LIBMTP_device_entry_t mtp_device_table[] = {
94 /* We include an .h file which is shared between us and libgphoto2 */
95 #include "music-players.h"
97 static const int mtp_device_table_size = sizeof(mtp_device_table) / sizeof(LIBMTP_device_entry_t);
100 static struct usb_bus* init_usb();
101 static void close_usb(PTP_USB* ptp_usb);
102 static int find_interface_and_endpoints(struct usb_device *dev,
109 int* outep_maxpacket,
111 static void clear_stall(PTP_USB* ptp_usb);
112 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, struct usb_device* dev);
113 static short ptp_write_func(unsigned long,PTPDataHandler*,void *data,unsigned long*);
114 static short ptp_read_func(unsigned long,PTPDataHandler*,void *data,unsigned long*,int);
115 static int usb_clear_stall_feature(PTP_USB* ptp_usb, int ep);
116 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status);
119 * Get a list of the supported USB devices.
121 * The developers depend on users of this library to constantly
122 * add in to the list of supported devices. What we need is the
123 * device name, USB Vendor ID (VID) and USB Product ID (PID).
124 * put this into a bug ticket at the project homepage, please.
125 * The VID/PID is used to let e.g. udev lift the device to
126 * console userspace access when it's plugged in.
128 * @param devices a pointer to a pointer that will hold a device
129 * list after the call to this function, if it was
131 * @param numdevs a pointer to an integer that will hold the number
132 * of devices in the device list if the call was successful.
133 * @return 0 if the list was successfull retrieved, any other
134 * value means failure.
136 int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const devices, int * const numdevs)
138 *devices = (LIBMTP_device_entry_t *) &mtp_device_table;
139 *numdevs = mtp_device_table_size;
144 static struct usb_bus* init_usb()
146 struct usb_bus* busses;
150 * Some additional libusb debugging please.
151 * We use the same level debug between MTP and USB.
153 if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0)
159 /* Workaround a libusb 0.1 bug : bus location is not initialised */
160 busses = usb_get_busses();
161 for (bus = busses; bus != NULL; bus = bus->next) {
163 bus->location = strtoul(bus->dirname, NULL, 10);
169 * Small recursive function to append a new usb_device to the linked list of
171 * @param devlist dynamic linked list of pointers to usb devices with MTP
172 * properties, to be extended with new device.
173 * @param newdevice the new device to add.
174 * @param bus_location bus for this device.
175 * @return an extended array or NULL on failure.
177 static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist,
178 struct usb_device *newdevice,
179 uint32_t bus_location)
181 mtpdevice_list_t *new_list_entry;
183 new_list_entry = (mtpdevice_list_t *) malloc(sizeof(mtpdevice_list_t));
184 if (new_list_entry == NULL) {
187 // Fill in USB device, if we *HAVE* to make a copy of the device do it here.
188 new_list_entry->libusb_device = newdevice;
189 new_list_entry->bus_location = bus_location;
190 new_list_entry->next = NULL;
192 if (devlist == NULL) {
193 return new_list_entry;
195 mtpdevice_list_t *tmp = devlist;
196 while (tmp->next != NULL) {
199 tmp->next = new_list_entry;
205 * Small recursive function to free dynamic memory allocated to the linked list
207 * @param devlist dynamic linked list of pointers to usb devices with MTP
211 static void free_mtpdevice_list(mtpdevice_list_t *devlist)
213 mtpdevice_list_t *tmplist = devlist;
217 while (tmplist != NULL) {
218 mtpdevice_list_t *tmp = tmplist;
219 tmplist = tmplist->next;
220 // Do not free() the fields (ptp_usb, params)! These are used elsewhere.
227 * This checks if a device has an MTP descriptor. The descriptor was
228 * elaborated about in gPhoto bug 1482084, and some official documentation
229 * with no strings attached was published by Microsoft at
230 * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC
232 * @param dev a device struct from libusb.
233 * @param dumpfile set to non-NULL to make the descriptors dump out
234 * to this file in human-readable hex so we can scruitinze them.
235 * @return 1 if the device is MTP compliant, 0 if not.
237 static int probe_device_descriptor(struct usb_device *dev, FILE *dumpfile)
239 usb_dev_handle *devh;
240 unsigned char buf[1024], cmd;
243 /* This is to indicate if we find some vendor interface */
244 int found_vendor_spec_interface = 0;
247 * Don't examine devices that are not likely to
248 * contain any MTP interface, update this the day
249 * you find some weird combination...
251 if (!(dev->descriptor.bDeviceClass == USB_CLASS_PER_INTERFACE ||
252 dev->descriptor.bDeviceClass == USB_CLASS_COMM ||
253 dev->descriptor.bDeviceClass == USB_CLASS_PTP ||
254 dev->descriptor.bDeviceClass == 0xEF || /* Intf. Association Desc.*/
255 dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC)) {
259 /* Attempt to open Device on this port */
260 devh = usb_open(dev);
262 /* Could not open this device */
267 * This sometimes crashes on the j for loop below
268 * I think it is because config is NULL yet
269 * dev->descriptor.bNumConfigurations > 0
270 * this check should stop this
274 * Loop over the device configurations and interfaces. Nokia MTP-capable
275 * handsets (possibly others) typically have the string "MTP" in their
276 * MTP interface descriptions, that's how they can be detected, before
277 * we try the more esoteric "OS descriptors" (below).
279 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
282 for (j = 0; j < dev->config[i].bNumInterfaces; j++) {
284 for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) {
285 /* Current interface descriptor */
286 struct usb_interface_descriptor *intf =
287 &dev->config[i].interface[j].altsetting[k];
290 * MTP interfaces have three endpoints, two bulk and one
291 * interrupt. Don't probe anything else.
293 if (intf->bNumEndpoints != 3)
297 * We only want to probe for the OS descriptor if the
298 * device is USB_CLASS_VENDOR_SPEC or one of the interfaces
299 * in it is, so flag if we find an interface like this.
301 if (intf->bInterfaceClass == USB_CLASS_VENDOR_SPEC) {
302 found_vendor_spec_interface = 1;
306 * Check for Still Image Capture class with PIMA 15740 protocol,
310 if (intf->bInterfaceClass == USB_CLASS_PTP
311 && intf->bInterfaceSubClass == 0x01
312 && intf->bInterfaceProtocol == 0x01) {
313 if (dumpfile != NULL) {
314 fprintf(dumpfile, " Found PTP device, check vendor "
317 // This is where we may insert code to open a PTP
318 // session and query the vendor extension ID to see
319 // if it is 0xffffffff, i.e. MTP according to the spec.
320 if (was_mtp_extension) {
328 * Next we search for the MTP substring in the interface name.
329 * For example : "RIM MS/MTP" should work.
332 ret = usb_get_string_simple(devh,
333 dev->config[i].interface[j].altsetting[k].iInterface,
338 if (strstr((char *) buf, "MTP") != NULL) {
339 if (dumpfile != NULL) {
340 fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k);
341 fprintf(dumpfile, " Interface description contains the string \"MTP\"\n");
342 fprintf(dumpfile, " Device recognized as MTP, no further probing.\n");
347 #ifdef LIBUSB_HAS_GET_DRIVER_NP
350 * Specifically avoid probing anything else than USB mass storage devices
351 * and non-associated drivers in Linux.
356 ret = usb_get_driver_np(devh,
357 dev->config[i].interface[j].altsetting[k].iInterface,
360 if (devname[0] != '\0' && strcmp(devname, "usb-storage")) {
361 LIBMTP_INFO("avoid probing device using kernel interface \"%s\"\n", devname);
370 if (dev->descriptor.bNumConfigurations)
371 LIBMTP_INFO("dev->config is NULL in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n");
375 * Only probe for OS descriptor if the device is vendor specific
376 * or one of the interfaces found is.
378 if (dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC ||
379 found_vendor_spec_interface) {
381 /* Read the special descriptor */
382 ret = usb_get_descriptor(devh, 0x03, 0xee, buf, sizeof(buf));
385 * If something failed we're probably stalled to we need
386 * to clear the stall off the endpoint and say this is not
390 /* EP0 is the default control endpoint */
391 usb_clear_halt(devh, 0);
396 // Dump it, if requested
397 if (dumpfile != NULL && ret > 0) {
398 fprintf(dumpfile, "Microsoft device descriptor 0xee:\n");
399 data_dump_ascii(dumpfile, buf, ret, 16);
402 /* Check if descriptor length is at least 10 bytes */
408 /* Check if this device has a Microsoft Descriptor */
409 if (!((buf[2] == 'M') && (buf[4] == 'S') &&
410 (buf[6] == 'F') && (buf[8] == 'T'))) {
415 /* Check if device responds to control message 1 or if there is an error */
417 ret = usb_control_msg (devh,
418 USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_TYPE_VENDOR,
424 USB_TIMEOUT_DEFAULT);
426 // Dump it, if requested
427 if (dumpfile != NULL && ret > 0) {
428 fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd);
429 data_dump_ascii(dumpfile, buf, ret, 16);
432 /* If this is true, the device either isn't MTP or there was an error */
434 /* TODO: If there was an error, flag it and let the user know somehow */
435 /* if(ret == -1) {} */
440 /* Check if device is MTP or if it is something like a USB Mass Storage
441 device with Janus DRM support */
442 if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
447 /* After this point we are probably dealing with an MTP device */
450 * Check if device responds to control message 2, which is
451 * the extended device parameters. Most devices will just
452 * respond with a copy of the same message as for the first
453 * message, some respond with zero-length (which is OK)
454 * and some with pure garbage. We're not parsing the result
455 * so this is not very important.
457 ret = usb_control_msg (devh,
458 USB_ENDPOINT_IN | USB_RECIP_DEVICE | USB_TYPE_VENDOR,
464 USB_TIMEOUT_DEFAULT);
466 // Dump it, if requested
467 if (dumpfile != NULL && ret > 0) {
468 fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd);
469 data_dump_ascii(dumpfile, buf, ret, 16);
472 /* If this is true, the device errored against control message 2 */
474 /* TODO: Implement callback function to let managing program know there
475 was a problem, along with description of the problem */
476 LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and "
477 "ProductID:%04x encountered an error responding to "
478 "control message 2.\n"
479 "Problems may arrise but continuing\n",
480 dev->descriptor.idVendor, dev->descriptor.idProduct);
481 } else if (dumpfile != NULL && ret == 0) {
482 fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n");
483 } else if (dumpfile != NULL) {
484 fprintf(dumpfile, "Device responds to control message 2 with some data.\n");
486 /* Close the USB device handle */
491 /* Close the USB device handle */
497 * This function scans through the connected usb devices on a machine and
498 * if they match known Vendor and Product identifiers appends them to the
499 * dynamic array mtp_device_list. Be sure to call
500 * <code>free_mtpdevice_list(mtp_device_list)</code> when you are done
501 * with it, assuming it is not NULL.
502 * @param mtp_device_list dynamic array of pointers to usb devices with MTP
503 * properties (if this list is not empty, new entries will be appended
505 * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list
506 * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no
507 * devices have been found.
509 static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list)
511 struct usb_bus *bus = init_usb();
512 for (; bus != NULL; bus = bus->next) {
513 struct usb_device *dev = bus->devices;
514 for (; dev != NULL; dev = dev->next) {
515 if (dev->descriptor.bDeviceClass != USB_CLASS_HUB) {
519 // First check if we know about the device already.
520 // Devices well known to us will not have their descriptors
521 // probed, it caused problems with some devices.
522 for(i = 0; i < mtp_device_table_size; i++) {
523 if(dev->descriptor.idVendor == mtp_device_table[i].vendor_id &&
524 dev->descriptor.idProduct == mtp_device_table[i].product_id) {
525 /* Append this usb device to the MTP device list */
526 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
533 // If we didn't know it, try probing the "OS Descriptor".
535 if (probe_device_descriptor(dev, NULL)) {
536 /* Append this usb device to the MTP USB Device List */
537 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
542 * By thomas_-_s: Also append devices that are no MTP but PTP devices
543 * if this is commented out.
547 // Check whether the device is no USB hub but a PTP.
548 if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == USB_CLASS_PTP && dev->descriptor.bDeviceClass != USB_CLASS_HUB ) {
549 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location);
558 /* If nothing was found we end up here. */
559 if(*mtp_device_list == NULL) {
560 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
562 return LIBMTP_ERROR_NONE;
566 * Checks if a specific device with a certain bus and device
567 * number has an MTP type device descriptor.
569 * @param busno the bus number of the device to check
570 * @param deviceno the device number of the device to check
571 * @return 1 if the device is MTP else 0
573 int LIBMTP_Check_Specific_Device(int busno, int devno)
575 struct usb_bus *bus = init_usb();
576 for (; bus != NULL; bus = bus->next) {
577 struct usb_device *dev = bus->devices;
578 if (bus->location != busno)
581 for (; dev != NULL; dev = dev->next) {
583 if (dev->devnum != devno)
586 if (probe_device_descriptor(dev, NULL))
594 * Detect the raw MTP device descriptors and return a list of
595 * of the devices found.
597 * @param devices a pointer to a variable that will hold
598 * the list of raw devices found. This may be NULL
599 * on return if the number of detected devices is zero.
600 * The user shall simply <code>free()</code> this
601 * variable when finished with the raw devices,
602 * in order to release memory.
603 * @param numdevs a pointer to an integer that will hold
604 * the number of devices in the list. This may
606 * @return 0 if successful, any other value means failure.
608 LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices,
611 mtpdevice_list_t *devlist = NULL;
612 mtpdevice_list_t *dev;
613 LIBMTP_error_number_t ret;
614 LIBMTP_raw_device_t *retdevs;
618 ret = get_mtp_usb_device_list(&devlist);
619 if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) {
623 } else if (ret != LIBMTP_ERROR_NONE) {
624 LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() "
625 "error code: %d on line %d\n", ret, __LINE__);
631 while (dev != NULL) {
638 return LIBMTP_ERROR_NONE;
640 // Conjure a device list
641 retdevs = (LIBMTP_raw_device_t *) malloc(sizeof(LIBMTP_raw_device_t) * devs);
642 if (retdevs == NULL) {
646 return LIBMTP_ERROR_MEMORY_ALLOCATION;
650 while (dev != NULL) {
651 int device_known = 0;
653 // Assign default device info
654 retdevs[i].device_entry.vendor = NULL;
655 retdevs[i].device_entry.vendor_id = dev->libusb_device->descriptor.idVendor;
656 retdevs[i].device_entry.product = NULL;
657 retdevs[i].device_entry.product_id = dev->libusb_device->descriptor.idProduct;
658 retdevs[i].device_entry.device_flags = 0x00000000U;
659 // See if we can locate some additional vendor info and device flags
660 for(j = 0; j < mtp_device_table_size; j++) {
661 if(dev->libusb_device->descriptor.idVendor == mtp_device_table[j].vendor_id &&
662 dev->libusb_device->descriptor.idProduct == mtp_device_table[j].product_id) {
664 retdevs[i].device_entry.vendor = mtp_device_table[j].vendor;
665 retdevs[i].device_entry.product = mtp_device_table[j].product;
666 retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags;
668 // This device is known to the developers
669 LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n",
671 dev->libusb_device->descriptor.idVendor,
672 dev->libusb_device->descriptor.idProduct,
673 mtp_device_table[j].vendor,
674 mtp_device_table[j].product);
679 // This device is unknown to the developers
680 LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is UNKNOWN.\n",
682 dev->libusb_device->descriptor.idVendor,
683 dev->libusb_device->descriptor.idProduct);
684 LIBMTP_ERROR("Please report this VID/PID and the device model to the "
685 "libmtp development team\n");
687 * Trying to get iManufacturer or iProduct from the device at this
688 * point would require opening a device handle, that we don't want
689 * to do right now. (Takes time for no good enough reason.)
692 // Save the location on the bus
693 retdevs[i].bus_location = dev->bus_location;
694 retdevs[i].devnum = dev->libusb_device->devnum;
700 free_mtpdevice_list(devlist);
701 return LIBMTP_ERROR_NONE;
705 * This routine just dumps out low-level
706 * USB information about the current device.
707 * @param ptp_usb the USB device to get information from.
709 void dump_usbinfo(PTP_USB *ptp_usb)
711 struct usb_device *dev;
713 #ifdef LIBUSB_HAS_GET_DRIVER_NP
718 res = usb_get_driver_np(ptp_usb->handle, (int) ptp_usb->interface, devname, sizeof(devname));
719 if (devname[0] != '\0') {
720 LIBMTP_INFO(" Using kernel interface \"%s\"\n", devname);
723 dev = usb_device(ptp_usb->handle);
724 LIBMTP_INFO(" bcdUSB: %d\n", dev->descriptor.bcdUSB);
725 LIBMTP_INFO(" bDeviceClass: %d\n", dev->descriptor.bDeviceClass);
726 LIBMTP_INFO(" bDeviceSubClass: %d\n", dev->descriptor.bDeviceSubClass);
727 LIBMTP_INFO(" bDeviceProtocol: %d\n", dev->descriptor.bDeviceProtocol);
728 LIBMTP_INFO(" idVendor: %04x\n", dev->descriptor.idVendor);
729 LIBMTP_INFO(" idProduct: %04x\n", dev->descriptor.idProduct);
730 LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
731 LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
732 LIBMTP_INFO(" Raw device info:\n");
733 LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location);
734 LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum);
735 LIBMTP_INFO(" Device entry info:\n");
736 LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
737 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
738 LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product);
739 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
740 LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
741 (void) probe_device_descriptor(dev, stdout);
745 * Retrieve the apropriate playlist extension for this
746 * device. Rather hacky at the moment. This is probably
747 * desired by the managing software, but when creating
748 * lists on the device itself you notice certain preferences.
749 * @param ptp_usb the USB device to get suggestion for.
750 * @return the suggested playlist extension.
752 const char *get_playlist_extension(PTP_USB *ptp_usb)
754 struct usb_device *dev;
755 static char creative_pl_extension[] = ".zpl";
756 static char default_pl_extension[] = ".pla";
758 dev = usb_device(ptp_usb->handle);
759 if (dev->descriptor.idVendor == 0x041e) {
760 return creative_pl_extension;
762 return default_pl_extension;
766 libusb_glue_debug (PTPParams *params, const char *format, ...)
770 va_start (args, format);
771 if (params->debug_func!=NULL)
772 params->debug_func (params->data, format, args);
775 vfprintf (stderr, format, args);
776 fprintf (stderr,"\n");
783 libusb_glue_error (PTPParams *params, const char *format, ...)
787 va_start (args, format);
788 if (params->error_func!=NULL)
789 params->error_func (params->data, format, args);
792 vfprintf (stderr, format, args);
793 fprintf (stderr,"\n");
801 * ptp_read_func() and ptp_write_func() are
802 * based on same functions usb.c in libgphoto2.
803 * Much reading packet logs and having fun with trials and errors
804 * reveals that WMP / Windows is probably using an algorithm like this
805 * for large transfers:
807 * 1. Send the command (0x0c bytes) if headers are split, else, send
808 * command plus sizeof(endpoint) - 0x0c bytes.
809 * 2. Send first packet, max size to be sizeof(endpoint) but only when using
810 * split headers. Else goto 3.
811 * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
812 * We call 0x10000 CONTEXT_BLOCK_SIZE.
813 * 4. Send remaining bytes MOD sizeof(endpoint)
814 * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
815 * then also send a zero-length package.
817 * Further there is some special quirks to handle zero reads from the
818 * device, since some devices can't do them at all due to shortcomings
819 * of the USB slave controller in the device.
821 #define CONTEXT_BLOCK_SIZE_1 0x3e00
822 #define CONTEXT_BLOCK_SIZE_2 0x200
823 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
827 unsigned long size, PTPDataHandler *handler,void *data,
828 unsigned long *readbytes,
831 PTP_USB *ptp_usb = (PTP_USB *)data;
832 unsigned long toread = 0;
834 unsigned long curread = 0;
835 unsigned long written;
836 unsigned char *bytes;
837 int expect_terminator_byte = 0;
838 unsigned long usb_inep_maxpacket_size;
839 unsigned long context_block_size_1;
840 unsigned long context_block_size_2;
841 uint16_t ptp_dev_vendor_id = ptp_usb->rawdevice.device_entry.vendor_id;
843 //"iRiver" device special handling
844 if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
845 usb_inep_maxpacket_size = ptp_usb->inep_maxpacket;
846 if (usb_inep_maxpacket_size == 0x400) {
847 context_block_size_1 = CONTEXT_BLOCK_SIZE_1 - 0x200;
848 context_block_size_2 = CONTEXT_BLOCK_SIZE_2 + 0x200;
851 context_block_size_1 = CONTEXT_BLOCK_SIZE_1;
852 context_block_size_2 = CONTEXT_BLOCK_SIZE_2;
856 // This is the largest block we'll need to read in.
857 bytes = malloc(CONTEXT_BLOCK_SIZE);
858 while (curread < size) {
860 LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
862 // check equal to condition here
863 if (size - curread < CONTEXT_BLOCK_SIZE)
865 // this is the last packet
866 toread = size - curread;
867 // this is equivalent to zero read for these devices
868 if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
870 expect_terminator_byte = 1;
873 else if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
874 //"iRiver" device special handling
876 // we are first packet, but not last packet
877 toread = context_block_size_1;
878 else if (toread == context_block_size_1)
879 toread = context_block_size_2;
880 else if (toread == context_block_size_2)
881 toread = context_block_size_1;
883 LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
884 (unsigned int) toread, (unsigned int) (size-curread));
887 toread = CONTEXT_BLOCK_SIZE;
889 LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
891 result = USB_BULK_READ(ptp_usb->handle,
897 LIBMTP_USB_DEBUG("Result of read: 0x%04x\n", result);
903 LIBMTP_USB_DEBUG("<==USB IN\n");
905 LIBMTP_USB_DEBUG("Zero Read\n");
907 LIBMTP_USB_DATA(bytes, result, 16);
909 // want to discard extra byte
910 if (expect_terminator_byte && result == toread)
912 LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
917 int putfunc_ret = handler->putfunc(NULL, handler->priv, result, bytes, &written);
918 if (putfunc_ret != PTP_RC_OK)
921 ptp_usb->current_transfer_complete += result;
924 // Increase counters, call callback
925 if (ptp_usb->callback_active) {
926 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
927 // send last update and disable callback.
928 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
929 ptp_usb->callback_active = 0;
931 if (ptp_usb->current_transfer_callback != NULL) {
933 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
934 ptp_usb->current_transfer_total,
935 ptp_usb->current_transfer_callback_data);
937 return PTP_ERROR_CANCEL;
942 if (result < toread) /* short reads are common */
945 if (readbytes) *readbytes = curread;
948 // there might be a zero packet waiting for us...
950 !FLAG_NO_ZERO_READS(ptp_usb) &&
951 curread % ptp_usb->outep_maxpacket == 0) {
955 LIBMTP_USB_DEBUG("<==USB IN\n");
956 LIBMTP_USB_DEBUG("Zero Read\n");
958 zeroresult = USB_BULK_READ(ptp_usb->handle,
964 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
973 PTPDataHandler *handler,
975 unsigned long *written
977 PTP_USB *ptp_usb = (PTP_USB *)data;
978 unsigned long towrite = 0;
980 unsigned long curwrite = 0;
981 unsigned char *bytes;
983 // This is the largest block we'll need to read in.
984 bytes = malloc(CONTEXT_BLOCK_SIZE);
988 while (curwrite < size) {
989 unsigned long usbwritten = 0;
990 towrite = size-curwrite;
991 if (towrite > CONTEXT_BLOCK_SIZE) {
992 towrite = CONTEXT_BLOCK_SIZE;
994 // This magic makes packets the same size that WMP send them.
995 if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
996 towrite -= towrite % ptp_usb->outep_maxpacket;
999 int getfunc_ret = handler->getfunc(NULL, handler->priv,towrite,bytes,&towrite);
1000 if (getfunc_ret != PTP_RC_OK)
1002 while (usbwritten < towrite) {
1003 result = USB_BULK_WRITE(ptp_usb->handle,
1005 ((char*) bytes+usbwritten),
1009 LIBMTP_USB_DEBUG("USB OUT==>\n");
1010 LIBMTP_USB_DATA(bytes+usbwritten, result, 16);
1013 return PTP_ERROR_IO;
1015 // check for result == 0 perhaps too.
1016 // Increase counters
1017 ptp_usb->current_transfer_complete += result;
1019 usbwritten += result;
1022 if (ptp_usb->callback_active) {
1023 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1024 // send last update and disable callback.
1025 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
1026 ptp_usb->callback_active = 0;
1028 if (ptp_usb->current_transfer_callback != NULL) {
1030 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1031 ptp_usb->current_transfer_total,
1032 ptp_usb->current_transfer_callback_data);
1034 return PTP_ERROR_CANCEL;
1038 if (result < towrite) /* short writes happen */
1043 *written = curwrite;
1046 // If this is the last transfer send a zero write if required
1047 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1048 if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1050 LIBMTP_USB_DEBUG("USB OUT==>\n");
1051 LIBMTP_USB_DEBUG("Zero Write\n");
1053 result=USB_BULK_WRITE(ptp_usb->handle,
1062 return PTP_ERROR_IO;
1066 /* memory data get/put handler */
1068 unsigned char *data;
1069 unsigned long size, curoff;
1070 } PTPMemHandlerPrivate;
1073 memory_getfunc(PTPParams* params, void* private,
1074 unsigned long wantlen, unsigned char *data,
1075 unsigned long *gotlen
1077 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1078 unsigned long tocopy = wantlen;
1080 if (priv->curoff + tocopy > priv->size)
1081 tocopy = priv->size - priv->curoff;
1082 memcpy (data, priv->data + priv->curoff, tocopy);
1083 priv->curoff += tocopy;
1089 memory_putfunc(PTPParams* params, void* private,
1090 unsigned long sendlen, unsigned char *data,
1091 unsigned long *putlen
1093 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1095 if (priv->curoff + sendlen > priv->size) {
1096 priv->data = realloc (priv->data, priv->curoff+sendlen);
1097 priv->size = priv->curoff + sendlen;
1099 memcpy (priv->data + priv->curoff, data, sendlen);
1100 priv->curoff += sendlen;
1105 /* init private struct for receiving data. */
1107 ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1108 PTPMemHandlerPrivate* priv;
1109 priv = malloc (sizeof(PTPMemHandlerPrivate));
1110 handler->priv = priv;
1111 handler->getfunc = memory_getfunc;
1112 handler->putfunc = memory_putfunc;
1119 /* init private struct and put data in for sending data.
1120 * data is still owned by caller.
1123 ptp_init_send_memory_handler(PTPDataHandler *handler,
1124 unsigned char *data, unsigned long len
1126 PTPMemHandlerPrivate* priv;
1127 priv = malloc (sizeof(PTPMemHandlerPrivate));
1129 return PTP_RC_GeneralError;
1130 handler->priv = priv;
1131 handler->getfunc = memory_getfunc;
1132 handler->putfunc = memory_putfunc;
1139 /* free private struct + data */
1141 ptp_exit_send_memory_handler (PTPDataHandler *handler) {
1142 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1143 /* data is owned by caller */
1148 /* hand over our internal data to caller */
1150 ptp_exit_recv_memory_handler (PTPDataHandler *handler,
1151 unsigned char **data, unsigned long *size
1153 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1160 /* send / receive functions */
1163 ptp_usb_sendreq (PTPParams* params, PTPContainer* req)
1166 PTPUSBBulkContainer usbreq;
1167 PTPDataHandler memhandler;
1168 unsigned long written = 0;
1169 unsigned long towrite;
1173 (void) ptp_render_opcode (params, req->Code, sizeof(txt), txt);
1174 LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1176 /* build appropriate USB container */
1177 usbreq.length=htod32(PTP_USB_BULK_REQ_LEN-
1178 (sizeof(uint32_t)*(5-req->Nparam)));
1179 usbreq.type=htod16(PTP_USB_CONTAINER_COMMAND);
1180 usbreq.code=htod16(req->Code);
1181 usbreq.trans_id=htod32(req->Transaction_ID);
1182 usbreq.payload.params.param1=htod32(req->Param1);
1183 usbreq.payload.params.param2=htod32(req->Param2);
1184 usbreq.payload.params.param3=htod32(req->Param3);
1185 usbreq.payload.params.param4=htod32(req->Param4);
1186 usbreq.payload.params.param5=htod32(req->Param5);
1187 /* send it to responder */
1188 towrite = PTP_USB_BULK_REQ_LEN-(sizeof(uint32_t)*(5-req->Nparam));
1189 ptp_init_send_memory_handler (&memhandler, (unsigned char*)&usbreq, towrite);
1196 ptp_exit_send_memory_handler (&memhandler);
1197 if (ret!=PTP_RC_OK && ret!=PTP_ERROR_CANCEL) {
1200 if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1201 libusb_glue_error (params,
1202 "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1203 req->Code, written, towrite
1211 ptp_usb_senddata (PTPParams* params, PTPContainer* ptp,
1212 uint64_t size, PTPDataHandler *handler
1216 unsigned long written;
1217 PTPUSBBulkContainer usbdata;
1218 uint64_t bytes_left_to_transfer;
1219 PTPDataHandler memhandler;
1222 LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1224 /* build appropriate USB container */
1225 usbdata.length = htod32(PTP_USB_BULK_HDR_LEN+size);
1226 usbdata.type = htod16(PTP_USB_CONTAINER_DATA);
1227 usbdata.code = htod16(ptp->Code);
1228 usbdata.trans_id= htod32(ptp->Transaction_ID);
1230 ((PTP_USB*)params->data)->current_transfer_complete = 0;
1231 ((PTP_USB*)params->data)->current_transfer_total = size+PTP_USB_BULK_HDR_LEN;
1233 if (params->split_header_data) {
1235 wlen = PTP_USB_BULK_HDR_LEN;
1237 unsigned long gotlen;
1238 /* For all camera devices. */
1239 datawlen = (size<PTP_USB_BULK_PAYLOAD_LEN_WRITE)?size:PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1240 wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1242 ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1243 if (ret != PTP_RC_OK)
1245 if (gotlen != datawlen)
1246 return PTP_RC_GeneralError;
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) {
1255 if (size <= datawlen) return ret;
1256 /* if everything OK send the rest */
1257 bytes_left_to_transfer = size-datawlen;
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)
1267 bytes_left_to_transfer -= written;
1269 if (ret!=PTP_RC_OK && ret!=PTP_ERROR_CANCEL)
1274 static uint16_t ptp_usb_getpacket(PTPParams *params,
1275 PTPUSBBulkContainer *packet, unsigned long *rlen)
1277 PTPDataHandler memhandler;
1279 unsigned char *x = NULL;
1280 unsigned long packet_size;
1281 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1283 packet_size = ptp_usb->inep_maxpacket;
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" */
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);
1300 memcpy (packet, x, *rlen);
1307 ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler)
1310 PTPUSBBulkContainer usbdata;
1311 unsigned long written;
1312 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1315 LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1317 memset(&usbdata,0,sizeof(usbdata));
1319 unsigned long len, rlen;
1321 ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1322 if (ret!=PTP_RC_OK) {
1326 if (dtoh16(usbdata.type)!=PTP_USB_CONTAINER_DATA) {
1327 ret = PTP_ERROR_DATA_EXPECTED;
1330 if (dtoh16(usbdata.code)!=ptp->Code) {
1331 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1332 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1333 "PTP header, code field insane, expect problems! (But continuing)");
1334 // Repair the header, so it won't wreak more havoc, don't just ignore it.
1335 // Typically these two fields will be broken.
1336 usbdata.code = htod16(ptp->Code);
1337 usbdata.trans_id = htod32(ptp->Transaction_ID);
1340 ret = dtoh16(usbdata.code);
1341 // This filters entirely insane garbage return codes, but still
1342 // makes it possible to return error codes in the code field when
1343 // getting data. It appears Windows ignores the contents of this
1345 if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1346 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1347 "PTP header, code field insane.");
1353 if (rlen == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) {
1354 /* Copy first part of data to 'data' */
1357 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1360 if (putfunc_ret != PTP_RC_OK)
1363 /* stuff data directly to passed data handler */
1365 unsigned long readdata;
1368 xret = ptp_read_func(
1375 if (xret != PTP_RC_OK)
1377 if (readdata < 0x20000000)
1382 if (rlen > dtoh32(usbdata.length)) {
1384 * Buffer the surplus response packet if it is >=
1385 * PTP_USB_BULK_HDR_LEN
1386 * (i.e. it is probably an entire package)
1387 * else discard it as erroneous surplus data.
1388 * This will even work if more than 2 packets appear
1389 * in the same transaction, they will just be handled
1392 * Marcus observed stray bytes on iRiver devices;
1393 * these are still discarded.
1395 unsigned int packlen = dtoh32(usbdata.length);
1396 unsigned int surplen = rlen - packlen;
1398 if (surplen >= PTP_USB_BULK_HDR_LEN) {
1399 params->response_packet = malloc(surplen);
1400 memcpy(params->response_packet,
1401 (uint8_t *) &usbdata + packlen, surplen);
1402 params->response_packet_size = surplen;
1403 /* Ignore reading one extra byte if device flags have been set */
1404 } else if(!FLAG_NO_ZERO_READS(ptp_usb) &&
1405 (rlen - dtoh32(usbdata.length) == 1)) {
1406 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: read %d bytes "
1407 "too much, expect problems!",
1408 rlen - dtoh32(usbdata.length));
1413 /* For most PTP devices rlen is 512 == sizeof(usbdata)
1414 * here. For MTP devices splitting header and data it might
1417 /* Evaluate full data length. */
1418 len=dtoh32(usbdata.length)-PTP_USB_BULK_HDR_LEN;
1420 /* autodetect split header/data MTP devices */
1421 if (dtoh32(usbdata.length) > 12 && (rlen==12))
1422 params->split_header_data = 1;
1424 /* Copy first part of data to 'data' */
1427 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1428 usbdata.payload.data,
1431 if (putfunc_ret != PTP_RC_OK)
1434 if (FLAG_NO_ZERO_READS(ptp_usb) &&
1435 len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ) {
1437 LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1439 // need to read in extra byte and discard it
1442 result = USB_BULK_READ(ptp_usb->handle,
1449 LIBMTP_INFO("Could not read in extra byte for PTP_USB_BULK_HS_MAX_PACKET_LEN_READ long file, return value 0x%04x\n", result);
1450 } else if (len+PTP_USB_BULK_HDR_LEN == PTP_USB_BULK_HS_MAX_PACKET_LEN_READ && params->split_header_data == 0) {
1455 LIBMTP_INFO("Reading in zero packet after header\n");
1457 zeroresult = USB_BULK_READ(ptp_usb->handle,
1463 if (zeroresult != 0)
1464 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1467 /* Is that all of data? */
1468 if (len+PTP_USB_BULK_HDR_LEN<=rlen) {
1472 ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1474 params->data, &rlen, 1);
1476 if (ret!=PTP_RC_OK) {
1484 ptp_usb_getresp (PTPParams* params, PTPContainer* resp)
1488 PTPUSBBulkContainer usbresp;
1489 PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1492 LIBMTP_USB_DEBUG("RESPONSE: ");
1494 memset(&usbresp,0,sizeof(usbresp));
1495 /* read response, it should never be longer than sizeof(usbresp) */
1496 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1498 // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1499 // sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1500 // after a NULL packet when it should send the response. This code ignores
1501 // such illegal packets.
1502 while (ret==PTP_RC_OK && rlen<PTP_USB_BULK_HDR_LEN && usbresp.length==0) {
1503 libusb_glue_debug (params, "ptp_usb_getresp: detected short response "
1504 "of %d bytes, expect problems! (re-reading "
1506 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1509 if (ret!=PTP_RC_OK) {
1512 if (dtoh16(usbresp.type)!=PTP_USB_CONTAINER_RESPONSE) {
1513 ret = PTP_ERROR_RESP_EXPECTED;
1515 if (dtoh16(usbresp.code)!=resp->Code) {
1516 ret = dtoh16(usbresp.code);
1519 LIBMTP_USB_DEBUG("%04x\n", ret);
1521 if (ret!=PTP_RC_OK) {
1522 /* libusb_glue_error (params,
1523 "PTP: request code 0x%04x getting resp error 0x%04x",
1527 /* build an appropriate PTPContainer */
1528 resp->Code=dtoh16(usbresp.code);
1529 resp->SessionID=params->session_id;
1530 resp->Transaction_ID=dtoh32(usbresp.trans_id);
1531 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1532 if (resp->Transaction_ID != params->transaction_id-1) {
1533 libusb_glue_debug (params, "ptp_usb_getresp: detected a broken "
1534 "PTP header, transaction ID insane, expect "
1535 "problems! (But continuing)");
1536 // Repair the header, so it won't wreak more havoc.
1537 resp->Transaction_ID = params->transaction_id-1;
1540 resp->Param1=dtoh32(usbresp.payload.params.param1);
1541 resp->Param2=dtoh32(usbresp.payload.params.param2);
1542 resp->Param3=dtoh32(usbresp.payload.params.param3);
1543 resp->Param4=dtoh32(usbresp.payload.params.param4);
1544 resp->Param5=dtoh32(usbresp.payload.params.param5);
1548 /* Event handling functions */
1550 /* PTP Events wait for or check mode */
1551 #define PTP_EVENT_CHECK 0x0000 /* waits for */
1552 #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */
1554 static inline uint16_t
1555 ptp_usb_event (PTPParams* params, PTPContainer* event, int wait)
1560 PTPUSBEventContainer usbevent;
1561 PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1563 memset(&usbevent,0,sizeof(usbevent));
1565 if ((params==NULL) || (event==NULL))
1566 return PTP_ERROR_BADPARAM;
1569 case PTP_EVENT_CHECK:
1570 result = USB_BULK_READ(ptp_usb->handle,
1576 result = USB_BULK_READ(ptp_usb->handle,
1581 if (result < 0) ret = PTP_ERROR_IO;
1583 case PTP_EVENT_CHECK_FAST:
1584 result = USB_BULK_READ(ptp_usb->handle,
1590 result = USB_BULK_READ(ptp_usb->handle,
1595 if (result < 0) ret = PTP_ERROR_IO;
1598 ret=PTP_ERROR_BADPARAM;
1601 if (ret!=PTP_RC_OK) {
1602 libusb_glue_error (params,
1603 "PTP: reading event an error 0x%04x occurred", ret);
1604 return PTP_ERROR_IO;
1608 libusb_glue_error (params,
1609 "PTP: reading event an short read of %ld bytes occurred", rlen);
1610 return PTP_ERROR_IO;
1612 /* if we read anything over interrupt endpoint it must be an event */
1613 /* build an appropriate PTPContainer */
1614 event->Code=dtoh16(usbevent.code);
1615 event->SessionID=params->session_id;
1616 event->Transaction_ID=dtoh32(usbevent.trans_id);
1617 event->Param1=dtoh32(usbevent.param1);
1618 event->Param2=dtoh32(usbevent.param2);
1619 event->Param3=dtoh32(usbevent.param3);
1624 ptp_usb_event_check (PTPParams* params, PTPContainer* event) {
1626 return ptp_usb_event (params, event, PTP_EVENT_CHECK_FAST);
1630 ptp_usb_event_wait (PTPParams* params, PTPContainer* event) {
1632 return ptp_usb_event (params, event, PTP_EVENT_CHECK);
1636 ptp_usb_control_cancel_request (PTPParams *params, uint32_t transactionid) {
1637 PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1639 unsigned char buffer[6];
1641 htod16a(&buffer[0],PTP_EC_CancelTransaction);
1642 htod32a(&buffer[2],transactionid);
1643 ret = usb_control_msg(ptp_usb->handle,
1644 USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1645 0x64, 0x0000, 0x0000,
1649 if (ret < sizeof(buffer))
1650 return PTP_ERROR_IO;
1654 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, struct usb_device* dev)
1656 usb_dev_handle *device_handle;
1660 params->sendreq_func=ptp_usb_sendreq;
1661 params->senddata_func=ptp_usb_senddata;
1662 params->getresp_func=ptp_usb_getresp;
1663 params->getdata_func=ptp_usb_getdata;
1664 params->cancelreq_func=ptp_usb_control_cancel_request;
1665 params->data=ptp_usb;
1666 params->transaction_id=0;
1668 * This is hardcoded here since we have no devices whatsoever that are BE.
1669 * Change this the day we run into our first BE device (if ever).
1671 params->byteorder = PTP_DL_LE;
1673 ptp_usb->timeout = get_timeout(ptp_usb);
1675 device_handle = usb_open(dev);
1676 if (!device_handle) {
1677 perror("usb_open()");
1680 ptp_usb->handle = device_handle;
1682 #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP
1684 * If this device is known to be wrongfully claimed by other kernel
1685 * drivers (such as mass storage), then try to unload it to make it
1686 * accessible from user space.
1688 if (FLAG_UNLOAD_DRIVER(ptp_usb)) {
1689 if (usb_get_driver_np(device_handle, (int) ptp_usb->interface,
1690 buf, sizeof(buf)) == 0) {
1691 if (usb_detach_kernel_driver_np(device_handle,
1692 (int) ptp_usb->interface)) {
1693 perror("usb_detach_kernel_driver_np()");
1701 * Check if the config is set to something else than what we want
1702 * to use. Only set the configuration if we absolutely have to.
1703 * Also do not bail out if we fail.
1705 if (dev->config->bConfigurationValue != ptp_usb->config) {
1706 if (usb_set_configuration(device_handle, dev->config->bConfigurationValue)) {
1707 perror("error in usb_set_configuration()- continuing anyway");
1712 * It seems like on kernel 2.6.31 if we already have it open on another
1713 * pthread in our app, we'll get an error if we try to claim it again,
1714 * but that error is harmless because our process already claimed the interface
1716 usbresult = usb_claim_interface(device_handle, (int) ptp_usb->interface);
1719 fprintf(stderr, "ignoring usb_claim_interface = %d", usbresult);
1722 * If the altsetting is set to something different than we want, switch
1725 * FIXME: this seems to cause trouble on the Mac:s so disable it. Retry
1726 * this on the Mac now that it only sets this when the altsetting differs.
1729 #if 0 /* Disable this always, no idea on how to handle it */
1730 if (dev->config->interface[].altsetting[] !=
1731 ptp_usb->altsetting) {
1732 fprintf(stderr, "desired altsetting different from current, trying to set altsetting\n");
1733 usbresult = usb_set_altinterface(device_handle, 0);
1735 fprintf(stderr, "ignoring error from usb_claim_interface = %d\n", usbresult);
1740 if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1743 // FIXME : Only for BlackBerry Storm
1744 // What does it mean? Maybe switch mode...
1745 // This first control message is absolutely necessary
1747 ret = usb_control_msg(device_handle,
1748 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN,
1749 0xaa, 0x00, 0x04, buf, 0x40, 1000);
1750 LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1751 LIBMTP_USB_DATA(buf, ret, 16);
1754 // This control message is unnecessary
1755 ret = usb_control_msg(device_handle,
1756 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN,
1757 0xa5, 0x00, 0x01, buf, 0x02, 1000);
1758 LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1759 LIBMTP_USB_DATA(buf, ret, 16);
1762 // This control message is unnecessary
1763 ret = usb_control_msg(device_handle,
1764 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN,
1765 0xa8, 0x00, 0x01, buf, 0x05, 1000);
1766 LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1767 LIBMTP_USB_DATA(buf, ret, 16);
1770 // This control message is unnecessary
1771 ret = usb_control_msg(device_handle,
1772 USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN,
1773 0xa8, 0x00, 0x01, buf, 0x11, 1000);
1774 LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1775 LIBMTP_USB_DATA(buf, ret, 16);
1782 static void clear_stall(PTP_USB* ptp_usb)
1787 /* check the inep status */
1789 ret = usb_get_endpoint_status(ptp_usb,ptp_usb->inep,&status);
1791 perror ("inep: usb_get_endpoint_status()");
1792 } else if (status) {
1793 LIBMTP_INFO("Clearing stall on IN endpoint\n");
1794 ret = usb_clear_stall_feature(ptp_usb,ptp_usb->inep);
1796 perror ("usb_clear_stall_feature()");
1800 /* check the outep status */
1802 ret = usb_get_endpoint_status(ptp_usb,ptp_usb->outep,&status);
1804 perror("outep: usb_get_endpoint_status()");
1805 } else if (status) {
1806 LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1807 ret = usb_clear_stall_feature(ptp_usb,ptp_usb->outep);
1809 perror("usb_clear_stall_feature()");
1813 /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1816 static void clear_halt(PTP_USB* ptp_usb)
1820 ret = usb_clear_halt(ptp_usb->handle,ptp_usb->inep);
1822 perror("usb_clear_halt() on IN endpoint");
1824 ret = usb_clear_halt(ptp_usb->handle,ptp_usb->outep);
1826 perror("usb_clear_halt() on OUT endpoint");
1828 ret = usb_clear_halt(ptp_usb->handle,ptp_usb->intep);
1830 perror("usb_clear_halt() on INTERRUPT endpoint");
1834 static void close_usb(PTP_USB* ptp_usb)
1836 if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1838 * Clear any stalled endpoints
1839 * On misbehaving devices designed for Windows/Mac, quote from:
1840 * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1841 * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1842 * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1843 * and presumes that the stall has cleared. Some devices actually choke
1844 * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1845 * STALL is persistant or not).
1847 clear_stall(ptp_usb);
1849 // causes troubles due to a kernel bug in 3.x kernels before/around 3.8
1850 // Clear halts on any endpoints
1851 clear_halt(ptp_usb);
1852 // Added to clear some stuff on the OUT endpoint
1853 // TODO: is this good on the Mac too?
1854 // HINT: some devices may need that you comment these two out too.
1856 usb_resetep(ptp_usb->handle, ptp_usb->outep);
1857 usb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1859 if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1861 * Some devices really love to get reset after being
1862 * disconnected. Again, since Windows never disconnects
1863 * a device closing behaviour is seldom or never exercised
1864 * on devices when engineered and often error prone.
1865 * Reset may help some.
1867 usb_reset(ptp_usb->handle);
1869 usb_close(ptp_usb->handle);
1875 static int find_interface_and_endpoints(struct usb_device *dev,
1878 uint8_t *altsetting,
1880 int* inep_maxpacket,
1882 int *outep_maxpacket,
1887 // Loop over the device configurations
1888 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1891 *conf = dev->config->bConfigurationValue;;
1893 // Loop over each configurations interfaces
1894 for (j = 0; j < dev->config[i].bNumInterfaces; j++) {
1898 int found_outep = 0;
1899 int found_intep = 0;
1900 struct usb_endpoint_descriptor *ep;
1902 // Inspect the altsettings of this interface
1903 for (k = 0; k < dev->config[i].interface[j].num_altsetting; k++) {
1905 // MTP devices shall have 3 endpoints, ignore those interfaces
1907 no_ep = dev->config[i].interface[j].altsetting[k].bNumEndpoints;
1911 *interface = dev->config[i].interface[j].altsetting[k].bInterfaceNumber;
1912 *altsetting = dev->config[i].interface[j].altsetting[k].bAlternateSetting;
1913 ep = dev->config[i].interface[j].altsetting[k].endpoint;
1915 // Loop over the three endpoints to locate two bulk and
1916 // one interrupt endpoint and FAIL if we cannot, and continue.
1917 for (l = 0; l < no_ep; l++) {
1918 if (ep[l].bmAttributes == USB_ENDPOINT_TYPE_BULK) {
1919 if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
1920 USB_ENDPOINT_DIR_MASK) {
1921 *inep = ep[l].bEndpointAddress;
1922 *inep_maxpacket = ep[l].wMaxPacketSize;
1925 if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == 0) {
1926 *outep = ep[l].bEndpointAddress;
1927 *outep_maxpacket = ep[l].wMaxPacketSize;
1930 } else if (ep[l].bmAttributes == USB_ENDPOINT_TYPE_INTERRUPT) {
1931 if ((ep[l].bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
1932 USB_ENDPOINT_DIR_MASK) {
1933 *intep = ep[l].bEndpointAddress;
1938 if (found_inep && found_outep && found_intep)
1939 // We assigned the endpoints so return here.
1941 // Else loop to next interface/config
1942 } /* Next altsetting */
1943 } /* Next interface */
1949 * This function assigns params and usbinfo given a raw device
1951 * @param device the device to be assigned.
1952 * @param usbinfo a pointer to the new usbinfo.
1953 * @return an error code.
1955 LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
1960 struct usb_device *libusb_device;
1962 struct usb_bus *bus;
1966 /* See if we can find this raw device again... */
1968 for (; bus != NULL; bus = bus->next) {
1969 if (bus->location == device->bus_location) {
1970 struct usb_device *dev = bus->devices;
1972 for (; dev != NULL; dev = dev->next) {
1973 if(dev->devnum == device->devnum &&
1974 dev->descriptor.idVendor == device->device_entry.vendor_id &&
1975 dev->descriptor.idProduct == device->device_entry.product_id ) {
1976 libusb_device = dev;
1985 /* Device has gone since detecting raw devices! */
1987 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
1990 /* Allocate structs */
1991 ptp_usb = (PTP_USB *) malloc(sizeof(PTP_USB));
1992 if (ptp_usb == NULL) {
1993 return LIBMTP_ERROR_MEMORY_ALLOCATION;
1995 /* Start with a blank slate (includes setting device_flags to 0) */
1996 memset(ptp_usb, 0, sizeof(PTP_USB));
1998 /* Copy the raw device */
1999 memcpy(&ptp_usb->rawdevice, device, sizeof(LIBMTP_raw_device_t));
2002 * Some devices must have their "OS Descriptor" massaged in order
2005 if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
2006 // Massage the device descriptor
2007 (void) probe_device_descriptor(libusb_device, NULL);
2010 /* Assign interface and endpoints to usbinfo... */
2011 err = find_interface_and_endpoints(libusb_device,
2013 &ptp_usb->interface,
2014 &ptp_usb->altsetting,
2016 &ptp_usb->inep_maxpacket,
2018 &ptp_usb->outep_maxpacket,
2022 LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
2023 return LIBMTP_ERROR_CONNECTING;
2026 /* Copy USB version number */
2027 ptp_usb->bcdusb = libusb_device->descriptor.bcdUSB;
2029 /* Attempt to initialize this device */
2030 if (init_ptp_usb(params, ptp_usb, libusb_device) < 0) {
2031 LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
2032 return LIBMTP_ERROR_CONNECTING;
2036 * This works in situations where previous bad applications
2037 * have not used LIBMTP_Release_Device on exit
2039 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2040 LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
2041 LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2042 usb_reset(ptp_usb->handle);
2045 if(init_ptp_usb(params, ptp_usb, libusb_device) <0) {
2046 LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2047 return LIBMTP_ERROR_CONNECTING;
2050 /* Device has been reset, try again */
2051 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2052 LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2053 return LIBMTP_ERROR_CONNECTING;
2057 /* Was the transaction id invalid? Try again */
2058 if (ret == PTP_RC_InvalidTransactionID) {
2059 LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2060 params->transaction_id += 10;
2061 ret = ptp_opensession(params, 1);
2064 if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2065 LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2066 "(Return code %d)\n Try to reset the device.\n",
2068 usb_release_interface(ptp_usb->handle,
2069 (int) ptp_usb->interface);
2070 return LIBMTP_ERROR_CONNECTING;
2073 /* OK configured properly */
2074 *usbinfo = (void *) ptp_usb;
2075 return LIBMTP_ERROR_NONE;
2079 void close_device (PTP_USB *ptp_usb, PTPParams *params)
2081 if (ptp_closesession(params)!=PTP_RC_OK)
2082 LIBMTP_ERROR("ERROR: Could not close session!\n");
2086 void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout)
2088 ptp_usb->timeout = timeout;
2091 void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout)
2093 *timeout = ptp_usb->timeout;
2096 int guess_usb_speed(PTP_USB *ptp_usb)
2098 int bytes_per_second;
2101 * We don't know the actual speeds so these are rough guesses
2102 * from the info you can find here:
2103 * http://en.wikipedia.org/wiki/USB#Transfer_rates
2104 * http://www.barefeats.com/usb2.html
2106 switch (ptp_usb->bcdusb & 0xFF00) {
2108 /* 1.x USB versions let's say 1MiB/s */
2109 bytes_per_second = 1*1024*1024;
2113 /* USB 2.0 nominal speed 18MiB/s */
2114 /* USB 3.0 won't be worse? */
2115 bytes_per_second = 18*1024*1024;
2118 /* Half-guess something? */
2119 bytes_per_second = 1*1024*1024;
2122 return bytes_per_second;
2125 static int usb_clear_stall_feature(PTP_USB* ptp_usb, int ep)
2127 return (usb_control_msg(ptp_usb->handle,
2129 USB_REQ_CLEAR_FEATURE,
2137 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status)
2139 return (usb_control_msg(ptp_usb->handle,
2140 USB_DP_DTH|USB_RECIP_ENDPOINT,