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-2012 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"
48 * Default USB timeout length. This can be overridden as needed
49 * but should start with a reasonable value so most common
50 * requests can be completed. The original value of 4000 was
51 * not long enough for large file transfer. Also, players can
52 * spend a bit of time collecting data. Higher values also
53 * make connecting/disconnecting more reliable.
55 #define USB_TIMEOUT_DEFAULT 20000
56 #define USB_TIMEOUT_LONG 60000
57 static inline int get_timeout(PTP_USB* ptp_usb)
59 if (FLAG_LONG_TIMEOUT(ptp_usb)) {
60 return USB_TIMEOUT_LONG;
62 return USB_TIMEOUT_DEFAULT;
65 /* USB Feature selector HALT */
66 #ifndef USB_FEATURE_HALT
67 #define USB_FEATURE_HALT 0x00
70 /* Internal data types */
71 struct mtpdevice_list_struct {
72 libusb_device *device;
75 uint32_t bus_location;
76 struct mtpdevice_list_struct *next;
78 typedef struct mtpdevice_list_struct mtpdevice_list_t;
80 static const LIBMTP_device_entry_t mtp_device_table[] = {
81 /* We include an .h file which is shared between us and libgphoto2 */
82 #include "music-players.h"
84 static const int mtp_device_table_size =
85 sizeof(mtp_device_table) / sizeof(LIBMTP_device_entry_t);
88 static LIBMTP_error_number_t init_usb();
89 static void close_usb(PTP_USB* ptp_usb);
90 static int find_interface_and_endpoints(libusb_device *dev,
99 static void clear_stall(PTP_USB* ptp_usb);
100 static int init_ptp_usb(PTPParams* params,
101 PTP_USB* ptp_usb, libusb_device* dev);
102 static short ptp_write_func(unsigned long,
103 PTPDataHandler*, void *data, unsigned long*);
104 static short ptp_read_func (unsigned long,
105 PTPDataHandler*, void *data, unsigned long*, int);
106 static int usb_get_endpoint_status(PTP_USB* ptp_usb,
107 int ep, uint16_t* status);
110 * Get a list of the supported USB devices.
112 * The developers depend on users of this library to constantly
113 * add in to the list of supported devices. What we need is the
114 * device name, USB Vendor ID (VID) and USB Product ID (PID).
115 * put this into a bug ticket at the project homepage, please.
116 * The VID/PID is used to let e.g. udev lift the device to
117 * console userspace access when it's plugged in.
119 * @param devices a pointer to a pointer that will hold a device
120 * list after the call to this function, if it was
122 * @param numdevs a pointer to an integer that will hold the number
123 * of devices in the device list if the call was successful.
124 * @return 0 if the list was successfull retrieved, any other
125 * value means failure.
127 int LIBMTP_Get_Supported_Devices_List(LIBMTP_device_entry_t ** const devices,
130 *devices = (LIBMTP_device_entry_t *) &mtp_device_table;
131 *numdevs = mtp_device_table_size;
136 static LIBMTP_error_number_t init_usb()
138 static int libusb1_initialized = 0;
141 * Some additional libusb debugging please.
142 * We use the same level debug between MTP and USB.
144 if (libusb1_initialized)
145 return LIBMTP_ERROR_NONE;
147 if (libusb_init(NULL) < 0) {
148 LIBMTP_ERROR("Libusb1 init failed\n");
149 return LIBMTP_ERROR_USB_LAYER;
152 libusb1_initialized = 1;
154 if ((LIBMTP_debug & LIBMTP_DEBUG_USB) != 0)
155 libusb_set_debug(NULL,9);
156 return LIBMTP_ERROR_NONE;
160 * Small recursive function to append a new usb_device to the linked
161 * list of USB MTP devices
162 * @param devlist dynamic linked list of pointers to usb devices with
163 * MTP properties, to be extended with new device.
164 * @param newdevice the new device to add.
165 * @param bus_location bus for this device.
166 * @return an extended array or NULL on failure.
168 static mtpdevice_list_t *append_to_mtpdevice_list(mtpdevice_list_t *devlist,
169 libusb_device *newdevice,
170 uint32_t bus_location)
172 mtpdevice_list_t *new_list_entry;
174 new_list_entry = (mtpdevice_list_t *) malloc(sizeof(mtpdevice_list_t));
175 if (new_list_entry == NULL) {
178 // Fill in USB device, if we *HAVE* to make a copy of the device do it here.
179 new_list_entry->device = newdevice;
180 new_list_entry->bus_location = bus_location;
181 new_list_entry->next = NULL;
183 if (devlist == NULL) {
184 return new_list_entry;
186 mtpdevice_list_t *tmp = devlist;
187 while (tmp->next != NULL) {
190 tmp->next = new_list_entry;
196 * Small recursive function to free dynamic memory allocated to the linked list
198 * @param devlist dynamic linked list of pointers to usb devices with MTP
202 static void free_mtpdevice_list(mtpdevice_list_t *devlist)
204 mtpdevice_list_t *tmplist = devlist;
208 while (tmplist != NULL) {
209 mtpdevice_list_t *tmp = tmplist;
210 tmplist = tmplist->next;
211 // Do not free() the fields (ptp_usb, params)! These are used elsewhere.
218 * This checks if a device has an MTP descriptor. The descriptor was
219 * elaborated about in gPhoto bug 1482084, and some official documentation
220 * with no strings attached was published by Microsoft at
221 * http://www.microsoft.com/whdc/system/bus/USB/USBFAQ_intermed.mspx#E3HAC
223 * @param dev a device struct from libusb.
224 * @param dumpfile set to non-NULL to make the descriptors dump out
225 * to this file in human-readable hex so we can scruitinze them.
226 * @return 1 if the device is MTP compliant, 0 if not.
228 static int probe_device_descriptor(libusb_device *dev, FILE *dumpfile)
230 libusb_device_handle *devh;
231 unsigned char buf[1024], cmd;
234 /* This is to indicate if we find some vendor interface */
235 int found_vendor_spec_interface = 0;
236 struct libusb_device_descriptor desc;
238 ret = libusb_get_device_descriptor (dev, &desc);
239 if (ret != LIBUSB_SUCCESS) return 0;
241 * Don't examine devices that are not likely to
242 * contain any MTP interface, update this the day
243 * you find some weird combination...
245 if (!(desc.bDeviceClass == LIBUSB_CLASS_PER_INTERFACE ||
246 desc.bDeviceClass == LIBUSB_CLASS_COMM ||
247 desc.bDeviceClass == LIBUSB_CLASS_PTP ||
248 desc.bDeviceClass == 0xEF || /* Intf. Association Desc.*/
249 desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC)) {
254 * Attempt to open Device on this port
256 * TODO: is there a way to check the number of endpoints etc WITHOUT
257 * opening the device? Some color calibration devices are REALLY
258 * sensitive to this, and I found a Canon custom scanner that doesn't
259 * like it at all either :-(
261 ret = libusb_open(dev, &devh);
262 if (ret != LIBUSB_SUCCESS) {
263 /* Could not open this device */
268 * Loop over the device configurations and interfaces. Nokia MTP-capable
269 * handsets (possibly others) typically have the string "MTP" in their
270 * MTP interface descriptions, that's how they can be detected, before
271 * we try the more esoteric "OS descriptors" (below).
273 for (i = 0; i < desc.bNumConfigurations; i++) {
275 struct libusb_config_descriptor *config;
277 ret = libusb_get_config_descriptor (dev, i, &config);
278 if (ret != LIBUSB_SUCCESS) {
279 LIBMTP_INFO("configdescriptor %d get failed with ret %d in probe_device_descriptor yet dev->descriptor.bNumConfigurations > 0\n", i, ret);
283 for (j = 0; j < config->bNumInterfaces; j++) {
285 for (k = 0; k < config->interface[j].num_altsetting; k++) {
286 /* Current interface descriptor */
287 const struct libusb_interface_descriptor *intf =
288 &config->interface[j].altsetting[k];
291 * MTP interfaces have three endpoints, two bulk and one
292 * interrupt. Don't probe anything else.
294 if (intf->bNumEndpoints != 3)
298 * We only want to probe for the OS descriptor if the
299 * device is LIBUSB_CLASS_VENDOR_SPEC or one of the interfaces
300 * in it is, so flag if we find an interface like this.
302 if (intf->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC) {
303 found_vendor_spec_interface = 1;
307 * TODO: Check for Still Image Capture class with PIMA 15740
308 * protocol, also known as PTP
311 if (intf->bInterfaceClass == LIBUSB_CLASS_PTP
312 && intf->bInterfaceSubClass == 0x01
313 && intf->bInterfaceProtocol == 0x01) {
314 if (dumpfile != NULL) {
315 fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k);
316 fprintf(dumpfile, " Found PTP device, check vendor "
320 * This is where we may insert code to open a PTP
321 * session and query the vendor extension ID to see
322 * if it is 0xffffffff, i.e. MTP according to the spec.
324 if (was_mtp_extension) {
332 * Next we search for the MTP substring in the interface name.
333 * For example : "RIM MS/MTP" should work.
336 ret = libusb_get_string_descriptor_ascii(devh,
337 config->interface[j].altsetting[k].iInterface,
342 if (strstr((char *) buf, "MTP") != NULL) {
343 if (dumpfile != NULL) {
344 fprintf(dumpfile, "Configuration %d, interface %d, altsetting %d:\n", i, j, k);
345 fprintf(dumpfile, " Interface description contains the string \"MTP\"\n");
346 fprintf(dumpfile, " Device recognized as MTP, no further probing.\n");
348 libusb_free_config_descriptor(config);
352 if (libusb_kernel_driver_active(devh, config->interface[j].altsetting[k].iInterface))
355 * Specifically avoid probing anything else than USB mass storage devices
356 * and non-associated drivers in Linux.
358 if (config->interface[j].altsetting[k].bInterfaceClass !=
359 LIBUSB_CLASS_MASS_STORAGE) {
360 LIBMTP_INFO("avoid probing device using attached kernel interface\n");
361 libusb_free_config_descriptor(config);
368 libusb_free_config_descriptor(config);
372 * Only probe for OS descriptor if the device is vendor specific
373 * or one of the interfaces found is.
375 if (desc.bDeviceClass == LIBUSB_CLASS_VENDOR_SPEC ||
376 found_vendor_spec_interface) {
378 /* Read the special descriptor */
379 ret = libusb_get_descriptor(devh, 0x03, 0xee, buf, sizeof(buf));
382 * If something failed we're probably stalled to we need
383 * to clear the stall off the endpoint and say this is not
387 /* EP0 is the default control endpoint */
388 libusb_clear_halt (devh, 0);
393 // Dump it, if requested
394 if (dumpfile != NULL && ret > 0) {
395 fprintf(dumpfile, "Microsoft device descriptor 0xee:\n");
396 data_dump_ascii(dumpfile, buf, ret, 16);
399 /* Check if descriptor length is at least 10 bytes */
405 /* Check if this device has a Microsoft Descriptor */
406 if (!((buf[2] == 'M') && (buf[4] == 'S') &&
407 (buf[6] == 'F') && (buf[8] == 'T'))) {
412 /* Check if device responds to control message 1 or if there is an error */
414 ret = libusb_control_transfer (devh,
415 LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
421 USB_TIMEOUT_DEFAULT);
423 // Dump it, if requested
424 if (dumpfile != NULL && ret > 0) {
425 fprintf(dumpfile, "Microsoft device response to control message 1, CMD 0x%02x:\n", cmd);
426 data_dump_ascii(dumpfile, buf, ret, 16);
429 /* If this is true, the device either isn't MTP or there was an error */
431 /* TODO: If there was an error, flag it and let the user know somehow */
432 /* if(ret == -1) {} */
437 /* Check if device is MTP or if it is something like a USB Mass Storage
438 device with Janus DRM support */
439 if ((buf[0x12] != 'M') || (buf[0x13] != 'T') || (buf[0x14] != 'P')) {
444 /* After this point we are probably dealing with an MTP device */
447 * Check if device responds to control message 2, which is
448 * the extended device parameters. Most devices will just
449 * respond with a copy of the same message as for the first
450 * message, some respond with zero-length (which is OK)
451 * and some with pure garbage. We're not parsing the result
452 * so this is not very important.
454 ret = libusb_control_transfer (devh,
455 LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR,
461 USB_TIMEOUT_DEFAULT);
463 // Dump it, if requested
464 if (dumpfile != NULL && ret > 0) {
465 fprintf(dumpfile, "Microsoft device response to control message 2, CMD 0x%02x:\n", cmd);
466 data_dump_ascii(dumpfile, buf, ret, 16);
469 /* If this is true, the device errored against control message 2 */
471 /* TODO: Implement callback function to let managing program know there
472 was a problem, along with description of the problem */
473 LIBMTP_ERROR("Potential MTP Device with VendorID:%04x and "
474 "ProductID:%04x encountered an error responding to "
475 "control message 2.\n"
476 "Problems may arrise but continuing\n",
477 desc.idVendor, desc.idProduct);
478 } else if (dumpfile != NULL && ret == 0) {
479 fprintf(dumpfile, "Zero-length response to control message 2 (OK)\n");
480 } else if (dumpfile != NULL) {
481 fprintf(dumpfile, "Device responds to control message 2 with some data.\n");
483 /* Close the USB device handle */
488 /* Close the USB device handle */
494 * This function scans through the connected usb devices on a machine and
495 * if they match known Vendor and Product identifiers appends them to the
496 * dynamic array mtp_device_list. Be sure to call
497 * <code>free_mtpdevice_list(mtp_device_list)</code> when you are done
498 * with it, assuming it is not NULL.
499 * @param mtp_device_list dynamic array of pointers to usb devices with MTP
500 * properties (if this list is not empty, new entries will be appended
502 * @return LIBMTP_ERROR_NONE implies that devices have been found, scan the list
503 * appropriately. LIBMTP_ERROR_NO_DEVICE_ATTACHED implies that no
504 * devices have been found.
506 static LIBMTP_error_number_t get_mtp_usb_device_list(mtpdevice_list_t ** mtp_device_list)
509 libusb_device **devs = NULL;
511 LIBMTP_error_number_t init_usb_ret;
513 init_usb_ret = init_usb();
514 if (init_usb_ret != LIBMTP_ERROR_NONE)
517 nrofdevs = libusb_get_device_list (NULL, &devs);
518 for (i = 0; i < nrofdevs ; i++) {
519 libusb_device *dev = devs[i];
520 struct libusb_device_descriptor desc;
522 ret = libusb_get_device_descriptor(dev, &desc);
523 if (ret != LIBUSB_SUCCESS) continue;
525 if (desc.bDeviceClass != LIBUSB_CLASS_HUB) {
529 // First check if we know about the device already.
530 // Devices well known to us will not have their descriptors
531 // probed, it caused problems with some devices.
532 for(i = 0; i < mtp_device_table_size; i++) {
533 if(desc.idVendor == mtp_device_table[i].vendor_id &&
534 desc.idProduct == mtp_device_table[i].product_id) {
535 /* Append this usb device to the MTP device list */
536 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
538 libusb_get_bus_number(dev));
543 // If we didn't know it, try probing the "OS Descriptor".
545 if (probe_device_descriptor(dev, NULL)) {
546 /* Append this usb device to the MTP USB Device List */
547 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list,
549 libusb_get_bus_number(dev));
552 * By thomas_-_s: Also append devices that are no MTP but PTP devices
553 * if this is commented out.
557 // Check whether the device is no USB hub but a PTP.
558 if ( dev->config != NULL &&dev->config->interface->altsetting->bInterfaceClass == LIBUSB_CLASS_PTP && dev->descriptor.bDeviceClass != LIBUSB_CLASS_HUB ) {
559 *mtp_device_list = append_to_mtpdevice_list(*mtp_device_list, dev, bus->location);
566 libusb_free_device_list (devs, 0);
568 /* If nothing was found we end up here. */
569 if(*mtp_device_list == NULL) {
570 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
572 return LIBMTP_ERROR_NONE;
576 * Checks if a specific device with a certain bus and device
577 * number has an MTP type device descriptor.
579 * @param busno the bus number of the device to check
580 * @param deviceno the device number of the device to check
581 * @return 1 if the device is MTP else 0
583 int LIBMTP_Check_Specific_Device(int busno, int devno)
586 libusb_device **devs = NULL;
588 LIBMTP_error_number_t init_usb_ret;
590 init_usb_ret = init_usb();
591 if (init_usb_ret != LIBMTP_ERROR_NONE)
594 nrofdevs = libusb_get_device_list (NULL, &devs);
595 for (i = 0; i < nrofdevs ; i++ ) {
597 if (libusb_get_bus_number(devs[i]) != busno)
599 if (libusb_get_device_address(devs[i]) != devno)
602 if (probe_device_descriptor(devs[i], NULL))
609 * Detect the raw MTP device descriptors and return a list of
610 * of the devices found.
612 * @param devices a pointer to a variable that will hold
613 * the list of raw devices found. This may be NULL
614 * on return if the number of detected devices is zero.
615 * The user shall simply <code>free()</code> this
616 * variable when finished with the raw devices,
617 * in order to release memory.
618 * @param numdevs a pointer to an integer that will hold
619 * the number of devices in the list. This may
621 * @return 0 if successful, any other value means failure.
623 LIBMTP_error_number_t LIBMTP_Detect_Raw_Devices(LIBMTP_raw_device_t ** devices,
626 mtpdevice_list_t *devlist = NULL;
627 mtpdevice_list_t *dev;
628 LIBMTP_error_number_t ret;
629 LIBMTP_raw_device_t *retdevs;
633 ret = get_mtp_usb_device_list(&devlist);
634 if (ret == LIBMTP_ERROR_NO_DEVICE_ATTACHED) {
638 } else if (ret != LIBMTP_ERROR_NONE) {
639 LIBMTP_ERROR("LIBMTP PANIC: get_mtp_usb_device_list() "
640 "error code: %d on line %d\n", ret, __LINE__);
646 while (dev != NULL) {
653 return LIBMTP_ERROR_NONE;
655 // Conjure a device list
656 retdevs = (LIBMTP_raw_device_t *) malloc(sizeof(LIBMTP_raw_device_t) * devs);
657 if (retdevs == NULL) {
661 return LIBMTP_ERROR_MEMORY_ALLOCATION;
665 while (dev != NULL) {
666 int device_known = 0;
667 struct libusb_device_descriptor desc;
669 libusb_get_device_descriptor (dev->device, &desc);
670 // Assign default device info
671 retdevs[i].device_entry.vendor = NULL;
672 retdevs[i].device_entry.vendor_id = desc.idVendor;
673 retdevs[i].device_entry.product = NULL;
674 retdevs[i].device_entry.product_id = desc.idProduct;
675 retdevs[i].device_entry.device_flags = 0x00000000U;
676 // See if we can locate some additional vendor info and device flags
677 for(j = 0; j < mtp_device_table_size; j++) {
678 if(desc.idVendor == mtp_device_table[j].vendor_id &&
679 desc.idProduct == mtp_device_table[j].product_id) {
681 retdevs[i].device_entry.vendor = mtp_device_table[j].vendor;
682 retdevs[i].device_entry.product = mtp_device_table[j].product;
683 retdevs[i].device_entry.device_flags = mtp_device_table[j].device_flags;
685 // This device is known to the developers
686 LIBMTP_ERROR("Device %d (VID=%04x and PID=%04x) is a %s %s.\n",
690 mtp_device_table[j].vendor,
691 mtp_device_table[j].product);
696 device_unknown(i, desc.idVendor, desc.idProduct);
698 // Save the location on the bus
699 retdevs[i].bus_location = libusb_get_bus_number (dev->device);
700 retdevs[i].devnum = libusb_get_device_address (dev->device);
706 free_mtpdevice_list(devlist);
707 return LIBMTP_ERROR_NONE;
711 * This routine just dumps out low-level
712 * USB information about the current device.
713 * @param ptp_usb the USB device to get information from.
715 void dump_usbinfo(PTP_USB *ptp_usb)
718 struct libusb_device_descriptor desc;
720 if (libusb_kernel_driver_active(ptp_usb->handle, ptp_usb->interface))
721 LIBMTP_INFO(" Interface has a kernel driver attached.\n");
723 dev = libusb_get_device (ptp_usb->handle);
724 libusb_get_device_descriptor (dev, &desc);
726 LIBMTP_INFO(" bcdUSB: %d\n", desc.bcdUSB);
727 LIBMTP_INFO(" bDeviceClass: %d\n", desc.bDeviceClass);
728 LIBMTP_INFO(" bDeviceSubClass: %d\n", desc.bDeviceSubClass);
729 LIBMTP_INFO(" bDeviceProtocol: %d\n", desc.bDeviceProtocol);
730 LIBMTP_INFO(" idVendor: %04x\n", desc.idVendor);
731 LIBMTP_INFO(" idProduct: %04x\n", desc.idProduct);
732 LIBMTP_INFO(" IN endpoint maxpacket: %d bytes\n", ptp_usb->inep_maxpacket);
733 LIBMTP_INFO(" OUT endpoint maxpacket: %d bytes\n", ptp_usb->outep_maxpacket);
734 LIBMTP_INFO(" Raw device info:\n");
735 LIBMTP_INFO(" Bus location: %d\n", ptp_usb->rawdevice.bus_location);
736 LIBMTP_INFO(" Device number: %d\n", ptp_usb->rawdevice.devnum);
737 LIBMTP_INFO(" Device entry info:\n");
738 LIBMTP_INFO(" Vendor: %s\n", ptp_usb->rawdevice.device_entry.vendor);
739 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.vendor_id);
740 LIBMTP_INFO(" Product: %s\n", ptp_usb->rawdevice.device_entry.product);
741 LIBMTP_INFO(" Vendor id: 0x%04x\n", ptp_usb->rawdevice.device_entry.product_id);
742 LIBMTP_INFO(" Device flags: 0x%08x\n", ptp_usb->rawdevice.device_entry.device_flags);
743 (void) probe_device_descriptor(dev, stdout);
747 * Retrieve the apropriate playlist extension for this
748 * device. Rather hacky at the moment. This is probably
749 * desired by the managing software, but when creating
750 * lists on the device itself you notice certain preferences.
751 * @param ptp_usb the USB device to get suggestion for.
752 * @return the suggested playlist extension.
754 const char *get_playlist_extension(PTP_USB *ptp_usb)
757 struct libusb_device_descriptor desc;
758 static char creative_pl_extension[] = ".zpl";
759 static char default_pl_extension[] = ".pla";
761 dev = libusb_get_device(ptp_usb->handle);
762 libusb_get_device_descriptor (dev, &desc);
763 if (desc.idVendor == 0x041e)
764 return creative_pl_extension;
765 return default_pl_extension;
769 libusb_glue_debug (PTPParams *params, const char *format, ...)
773 va_start (args, format);
774 if (params->debug_func!=NULL)
775 params->debug_func (params->data, format, args);
778 vfprintf (stderr, format, args);
779 fprintf (stderr,"\n");
786 libusb_glue_error (PTPParams *params, const char *format, ...)
790 va_start (args, format);
791 if (params->error_func!=NULL)
792 params->error_func (params->data, format, args);
795 vfprintf (stderr, format, args);
796 fprintf (stderr,"\n");
804 * ptp_read_func() and ptp_write_func() are
805 * based on same functions usb.c in libgphoto2.
806 * Much reading packet logs and having fun with trials and errors
807 * reveals that WMP / Windows is probably using an algorithm like this
808 * for large transfers:
810 * 1. Send the command (0x0c bytes) if headers are split, else, send
811 * command plus sizeof(endpoint) - 0x0c bytes.
812 * 2. Send first packet, max size to be sizeof(endpoint) but only when using
813 * split headers. Else goto 3.
814 * 3. REPEAT send 0x10000 byte chunks UNTIL remaining bytes < 0x10000
815 * We call 0x10000 CONTEXT_BLOCK_SIZE.
816 * 4. Send remaining bytes MOD sizeof(endpoint)
817 * 5. Send remaining bytes. If this happens to be exactly sizeof(endpoint)
818 * then also send a zero-length package.
820 * Further there is some special quirks to handle zero reads from the
821 * device, since some devices can't do them at all due to shortcomings
822 * of the USB slave controller in the device.
824 #define CONTEXT_BLOCK_SIZE_1 0x3e00
825 #define CONTEXT_BLOCK_SIZE_2 0x200
826 #define CONTEXT_BLOCK_SIZE CONTEXT_BLOCK_SIZE_1+CONTEXT_BLOCK_SIZE_2
829 unsigned long size, PTPDataHandler *handler,void *data,
830 unsigned long *readbytes,
833 PTP_USB *ptp_usb = (PTP_USB *)data;
834 unsigned long toread = 0;
837 unsigned long curread = 0;
838 unsigned long written;
839 unsigned char *bytes;
840 int expect_terminator_byte = 0;
841 unsigned long usb_inep_maxpacket_size;
842 unsigned long context_block_size_1;
843 unsigned long context_block_size_2;
844 uint16_t ptp_dev_vendor_id = ptp_usb->rawdevice.device_entry.vendor_id;
846 //"iRiver" device special handling
847 if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
848 usb_inep_maxpacket_size = ptp_usb->inep_maxpacket;
849 if (usb_inep_maxpacket_size == 0x400) {
850 context_block_size_1 = CONTEXT_BLOCK_SIZE_1 - 0x200;
851 context_block_size_2 = CONTEXT_BLOCK_SIZE_2 + 0x200;
854 context_block_size_1 = CONTEXT_BLOCK_SIZE_1;
855 context_block_size_2 = CONTEXT_BLOCK_SIZE_2;
858 // This is the largest block we'll need to read in.
859 bytes = malloc(CONTEXT_BLOCK_SIZE);
860 while (curread < size) {
862 LIBMTP_USB_DEBUG("Remaining size to read: 0x%04lx bytes\n", size - curread);
864 // check equal to condition here
865 if (size - curread < CONTEXT_BLOCK_SIZE)
867 // this is the last packet
868 toread = size - curread;
869 // this is equivalent to zero read for these devices
870 if (readzero && FLAG_NO_ZERO_READS(ptp_usb) && toread % 64 == 0) {
872 expect_terminator_byte = 1;
875 else if (ptp_dev_vendor_id == 0x4102 || ptp_dev_vendor_id == 0x1006) {
876 //"iRiver" device special handling
878 // we are first packet, but not last packet
879 toread = context_block_size_1;
880 else if (toread == context_block_size_1)
881 toread = context_block_size_2;
882 else if (toread == context_block_size_2)
883 toread = context_block_size_1;
885 LIBMTP_INFO("unexpected toread size 0x%04x, 0x%04x remaining bytes\n",
886 (unsigned int) toread, (unsigned int) (size-curread));
889 toread = CONTEXT_BLOCK_SIZE;
891 LIBMTP_USB_DEBUG("Reading in 0x%04lx bytes\n", toread);
893 ret = USB_BULK_READ(ptp_usb->handle,
900 LIBMTP_USB_DEBUG("Result of read: 0x%04x (%d bytes)\n", ret, xread);
902 if (ret != LIBUSB_SUCCESS)
905 LIBMTP_USB_DEBUG("<==USB IN\n");
907 LIBMTP_USB_DEBUG("Zero Read\n");
909 LIBMTP_USB_DATA(bytes, xread, 16);
911 // want to discard extra byte
912 if (expect_terminator_byte && xread == toread)
914 LIBMTP_USB_DEBUG("<==USB IN\nDiscarding extra byte\n");
919 int putfunc_ret = handler->putfunc(NULL, handler->priv, xread, bytes, &written);
920 if (putfunc_ret != PTP_RC_OK)
923 ptp_usb->current_transfer_complete += xread;
926 // Increase counters, call callback
927 if (ptp_usb->callback_active) {
928 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
929 // send last update and disable callback.
930 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
931 ptp_usb->callback_active = 0;
933 if (ptp_usb->current_transfer_callback != NULL) {
935 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
936 ptp_usb->current_transfer_total,
937 ptp_usb->current_transfer_callback_data);
939 return PTP_ERROR_CANCEL;
944 if (xread < toread) /* short reads are common */
947 if (readbytes) *readbytes = curread;
950 // there might be a zero packet waiting for us...
952 !FLAG_NO_ZERO_READS(ptp_usb) &&
953 curread % ptp_usb->outep_maxpacket == 0) {
955 int zeroresult = 0, xread;
957 LIBMTP_USB_DEBUG("<==USB IN\n");
958 LIBMTP_USB_DEBUG("Zero Read\n");
960 zeroresult = USB_BULK_READ(ptp_usb->handle,
966 if (zeroresult != LIBUSB_SUCCESS)
967 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
976 PTPDataHandler *handler,
978 unsigned long *written
980 PTP_USB *ptp_usb = (PTP_USB *)data;
981 unsigned long towrite = 0;
983 unsigned long curwrite = 0;
984 unsigned char *bytes;
986 // This is the largest block we'll need to read in.
987 bytes = malloc(CONTEXT_BLOCK_SIZE);
991 while (curwrite < size) {
992 unsigned long usbwritten = 0;
995 towrite = size-curwrite;
996 if (towrite > CONTEXT_BLOCK_SIZE) {
997 towrite = CONTEXT_BLOCK_SIZE;
999 // This magic makes packets the same size that WMP send them.
1000 if (towrite > ptp_usb->outep_maxpacket && towrite % ptp_usb->outep_maxpacket != 0) {
1001 towrite -= towrite % ptp_usb->outep_maxpacket;
1004 int getfunc_ret = handler->getfunc(NULL, handler->priv,towrite,bytes,&towrite);
1005 if (getfunc_ret != PTP_RC_OK) {
1009 while (usbwritten < towrite) {
1010 ret = USB_BULK_WRITE(ptp_usb->handle,
1017 LIBMTP_USB_DEBUG("USB OUT==>\n");
1019 if (ret != LIBUSB_SUCCESS) {
1021 return PTP_ERROR_IO;
1023 LIBMTP_USB_DATA(bytes+usbwritten, xwritten, 16);
1024 // check for result == 0 perhaps too.
1025 // Increase counters
1026 ptp_usb->current_transfer_complete += xwritten;
1027 curwrite += xwritten;
1028 usbwritten += xwritten;
1031 if (ptp_usb->callback_active) {
1032 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1033 // send last update and disable callback.
1034 ptp_usb->current_transfer_complete = ptp_usb->current_transfer_total;
1035 ptp_usb->callback_active = 0;
1037 if (ptp_usb->current_transfer_callback != NULL) {
1039 ret = ptp_usb->current_transfer_callback(ptp_usb->current_transfer_complete,
1040 ptp_usb->current_transfer_total,
1041 ptp_usb->current_transfer_callback_data);
1044 return PTP_ERROR_CANCEL;
1048 if (xwritten < towrite) /* short writes happen */
1053 *written = curwrite;
1056 // If this is the last transfer send a zero write if required
1057 if (ptp_usb->current_transfer_complete >= ptp_usb->current_transfer_total) {
1058 if ((towrite % ptp_usb->outep_maxpacket) == 0) {
1061 LIBMTP_USB_DEBUG("USB OUT==>\n");
1062 LIBMTP_USB_DEBUG("Zero Write\n");
1064 ret =USB_BULK_WRITE(ptp_usb->handle,
1066 (unsigned char *) "x",
1073 if (ret != LIBUSB_SUCCESS)
1074 return PTP_ERROR_IO;
1078 /* memory data get/put handler */
1080 unsigned char *data;
1081 unsigned long size, curoff;
1082 } PTPMemHandlerPrivate;
1085 memory_getfunc(PTPParams* params, void* private,
1086 unsigned long wantlen, unsigned char *data,
1087 unsigned long *gotlen
1089 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1090 unsigned long tocopy = wantlen;
1092 if (priv->curoff + tocopy > priv->size)
1093 tocopy = priv->size - priv->curoff;
1094 memcpy (data, priv->data + priv->curoff, tocopy);
1095 priv->curoff += tocopy;
1101 memory_putfunc(PTPParams* params, void* private,
1102 unsigned long sendlen, unsigned char *data,
1103 unsigned long *putlen
1105 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)private;
1107 if (priv->curoff + sendlen > priv->size) {
1108 priv->data = realloc (priv->data, priv->curoff+sendlen);
1109 priv->size = priv->curoff + sendlen;
1111 memcpy (priv->data + priv->curoff, data, sendlen);
1112 priv->curoff += sendlen;
1117 /* init private struct for receiving data. */
1119 ptp_init_recv_memory_handler(PTPDataHandler *handler) {
1120 PTPMemHandlerPrivate* priv;
1121 priv = malloc (sizeof(PTPMemHandlerPrivate));
1122 handler->priv = priv;
1123 handler->getfunc = memory_getfunc;
1124 handler->putfunc = memory_putfunc;
1131 /* init private struct and put data in for sending data.
1132 * data is still owned by caller.
1135 ptp_init_send_memory_handler(PTPDataHandler *handler,
1136 unsigned char *data, unsigned long len
1138 PTPMemHandlerPrivate* priv;
1139 priv = malloc (sizeof(PTPMemHandlerPrivate));
1141 return PTP_RC_GeneralError;
1142 handler->priv = priv;
1143 handler->getfunc = memory_getfunc;
1144 handler->putfunc = memory_putfunc;
1151 /* free private struct + data */
1153 ptp_exit_send_memory_handler (PTPDataHandler *handler) {
1154 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1155 /* data is owned by caller */
1160 /* hand over our internal data to caller */
1162 ptp_exit_recv_memory_handler (PTPDataHandler *handler,
1163 unsigned char **data, unsigned long *size
1165 PTPMemHandlerPrivate* priv = (PTPMemHandlerPrivate*)handler->priv;
1172 /* send / receive functions */
1175 ptp_usb_sendreq (PTPParams* params, PTPContainer* req)
1178 PTPUSBBulkContainer usbreq;
1179 PTPDataHandler memhandler;
1180 unsigned long written = 0;
1181 unsigned long towrite;
1185 (void) ptp_render_opcode (params, req->Code, sizeof(txt), txt);
1186 LIBMTP_USB_DEBUG("REQUEST: 0x%04x, %s\n", req->Code, txt);
1188 /* build appropriate USB container */
1189 usbreq.length=htod32(PTP_USB_BULK_REQ_LEN-
1190 (sizeof(uint32_t)*(5-req->Nparam)));
1191 usbreq.type=htod16(PTP_USB_CONTAINER_COMMAND);
1192 usbreq.code=htod16(req->Code);
1193 usbreq.trans_id=htod32(req->Transaction_ID);
1194 usbreq.payload.params.param1=htod32(req->Param1);
1195 usbreq.payload.params.param2=htod32(req->Param2);
1196 usbreq.payload.params.param3=htod32(req->Param3);
1197 usbreq.payload.params.param4=htod32(req->Param4);
1198 usbreq.payload.params.param5=htod32(req->Param5);
1199 /* send it to responder */
1200 towrite = PTP_USB_BULK_REQ_LEN-(sizeof(uint32_t)*(5-req->Nparam));
1201 ptp_init_send_memory_handler (&memhandler, (unsigned char*)&usbreq, towrite);
1208 ptp_exit_send_memory_handler (&memhandler);
1209 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL) {
1212 if (written != towrite && ret != PTP_ERROR_CANCEL && ret != PTP_ERROR_IO) {
1213 libusb_glue_error (params,
1214 "PTP: request code 0x%04x sending req wrote only %ld bytes instead of %d",
1215 req->Code, written, towrite
1223 ptp_usb_senddata (PTPParams* params, PTPContainer* ptp,
1224 uint64_t size, PTPDataHandler *handler
1228 unsigned long written;
1229 PTPUSBBulkContainer usbdata;
1230 uint64_t bytes_left_to_transfer;
1231 PTPDataHandler memhandler;
1234 LIBMTP_USB_DEBUG("SEND DATA PHASE\n");
1236 /* build appropriate USB container */
1237 usbdata.length = htod32(PTP_USB_BULK_HDR_LEN+size);
1238 usbdata.type = htod16(PTP_USB_CONTAINER_DATA);
1239 usbdata.code = htod16(ptp->Code);
1240 usbdata.trans_id= htod32(ptp->Transaction_ID);
1242 ((PTP_USB*)params->data)->current_transfer_complete = 0;
1243 ((PTP_USB*)params->data)->current_transfer_total = size+PTP_USB_BULK_HDR_LEN;
1245 if (params->split_header_data) {
1247 wlen = PTP_USB_BULK_HDR_LEN;
1249 unsigned long gotlen;
1250 /* For all camera devices. */
1251 datawlen = (size<PTP_USB_BULK_PAYLOAD_LEN_WRITE)?size:PTP_USB_BULK_PAYLOAD_LEN_WRITE;
1252 wlen = PTP_USB_BULK_HDR_LEN + datawlen;
1254 ret = handler->getfunc(params, handler->priv, datawlen, usbdata.payload.data, &gotlen);
1255 if (ret != PTP_RC_OK)
1257 if (gotlen != datawlen)
1258 return PTP_RC_GeneralError;
1260 ptp_init_send_memory_handler (&memhandler, (unsigned char *)&usbdata, wlen);
1261 /* send first part of data */
1262 ret = ptp_write_func(wlen, &memhandler, params->data, &written);
1263 ptp_exit_send_memory_handler (&memhandler);
1264 if (ret != PTP_RC_OK) {
1267 if (size <= datawlen) return ret;
1268 /* if everything OK send the rest */
1269 bytes_left_to_transfer = size-datawlen;
1271 while(bytes_left_to_transfer > 0) {
1272 ret = ptp_write_func (bytes_left_to_transfer, handler, params->data, &written);
1273 if (ret != PTP_RC_OK)
1279 bytes_left_to_transfer -= written;
1281 if (ret != PTP_RC_OK && ret != PTP_ERROR_CANCEL)
1286 static uint16_t ptp_usb_getpacket(PTPParams *params,
1287 PTPUSBBulkContainer *packet, unsigned long *rlen)
1289 PTPDataHandler memhandler;
1291 unsigned char *x = NULL;
1292 unsigned long packet_size;
1293 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1295 packet_size = ptp_usb->inep_maxpacket;
1297 /* read the header and potentially the first data */
1298 if (params->response_packet_size > 0) {
1299 /* If there is a buffered packet, just use it. */
1300 memcpy(packet, params->response_packet, params->response_packet_size);
1301 *rlen = params->response_packet_size;
1302 free(params->response_packet);
1303 params->response_packet = NULL;
1304 params->response_packet_size = 0;
1305 /* Here this signifies a "virtual read" */
1308 ptp_init_recv_memory_handler (&memhandler);
1309 ret = ptp_read_func(packet_size, &memhandler, params->data, rlen, 0);
1310 ptp_exit_recv_memory_handler (&memhandler, &x, rlen);
1312 memcpy (packet, x, *rlen);
1319 ptp_usb_getdata (PTPParams* params, PTPContainer* ptp, PTPDataHandler *handler)
1322 PTPUSBBulkContainer usbdata;
1323 unsigned long written;
1324 PTP_USB *ptp_usb = (PTP_USB *) params->data;
1327 LIBMTP_USB_DEBUG("GET DATA PHASE\n");
1329 memset(&usbdata,0,sizeof(usbdata));
1331 unsigned long len, rlen;
1333 ret = ptp_usb_getpacket(params, &usbdata, &rlen);
1334 if (ret != PTP_RC_OK) {
1338 if (dtoh16(usbdata.type)!=PTP_USB_CONTAINER_DATA) {
1339 ret = PTP_ERROR_DATA_EXPECTED;
1342 if (dtoh16(usbdata.code)!=ptp->Code) {
1343 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1344 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1345 "PTP header, code field insane, expect problems! (But continuing)");
1346 // Repair the header, so it won't wreak more havoc, don't just ignore it.
1347 // Typically these two fields will be broken.
1348 usbdata.code = htod16(ptp->Code);
1349 usbdata.trans_id = htod32(ptp->Transaction_ID);
1352 ret = dtoh16(usbdata.code);
1353 // This filters entirely insane garbage return codes, but still
1354 // makes it possible to return error codes in the code field when
1355 // getting data. It appears Windows ignores the contents of this
1357 if (ret < PTP_RC_Undefined || ret > PTP_RC_SpecificationOfDestinationUnsupported) {
1358 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: detected a broken "
1359 "PTP header, code field insane.");
1365 if (rlen == ptp_usb->inep_maxpacket) {
1366 /* Copy first part of data to 'data' */
1369 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN, usbdata.payload.data,
1372 if (putfunc_ret != PTP_RC_OK)
1375 /* stuff data directly to passed data handler */
1377 unsigned long readdata;
1380 xret = ptp_read_func(
1387 if (xret != PTP_RC_OK)
1389 if (readdata < 0x20000000)
1394 if (rlen > dtoh32(usbdata.length)) {
1396 * Buffer the surplus response packet if it is >=
1397 * PTP_USB_BULK_HDR_LEN
1398 * (i.e. it is probably an entire package)
1399 * else discard it as erroneous surplus data.
1400 * This will even work if more than 2 packets appear
1401 * in the same transaction, they will just be handled
1404 * Marcus observed stray bytes on iRiver devices;
1405 * these are still discarded.
1407 unsigned int packlen = dtoh32(usbdata.length);
1408 unsigned int surplen = rlen - packlen;
1410 if (surplen >= PTP_USB_BULK_HDR_LEN) {
1411 params->response_packet = malloc(surplen);
1412 memcpy(params->response_packet,
1413 (uint8_t *) &usbdata + packlen, surplen);
1414 params->response_packet_size = surplen;
1415 /* Ignore reading one extra byte if device flags have been set */
1416 } else if(!FLAG_NO_ZERO_READS(ptp_usb) &&
1417 (rlen - dtoh32(usbdata.length) == 1)) {
1418 libusb_glue_debug (params, "ptp2/ptp_usb_getdata: read %d bytes "
1419 "too much, expect problems!",
1420 rlen - dtoh32(usbdata.length));
1425 /* For most PTP devices rlen is 512 == sizeof(usbdata)
1426 * here. For MTP devices splitting header and data it might
1429 /* Evaluate full data length. */
1430 len=dtoh32(usbdata.length)-PTP_USB_BULK_HDR_LEN;
1432 /* autodetect split header/data MTP devices */
1433 if (dtoh32(usbdata.length) > 12 && (rlen==12))
1434 params->split_header_data = 1;
1436 /* Copy first part of data to 'data' */
1439 params, handler->priv, rlen - PTP_USB_BULK_HDR_LEN,
1440 usbdata.payload.data,
1443 if (putfunc_ret != PTP_RC_OK)
1446 if (FLAG_NO_ZERO_READS(ptp_usb) &&
1447 len+PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket) {
1449 LIBMTP_USB_DEBUG("Reading in extra terminating byte\n");
1451 // need to read in extra byte and discard it
1452 int result = 0, xread;
1453 unsigned char byte = 0;
1454 result = USB_BULK_READ(ptp_usb->handle,
1462 LIBMTP_INFO("Could not read in extra byte for %d byte long file, return value 0x%04x\n", ptp_usb->inep_maxpacket, result);
1463 } else if (len+PTP_USB_BULK_HDR_LEN == ptp_usb->inep_maxpacket && params->split_header_data == 0) {
1464 int zeroresult = 0, xread;
1465 unsigned char zerobyte = 0;
1467 LIBMTP_INFO("Reading in zero packet after header\n");
1469 zeroresult = USB_BULK_READ(ptp_usb->handle,
1476 if (zeroresult != 0)
1477 LIBMTP_INFO("LIBMTP panic: unable to read in zero packet, response 0x%04x", zeroresult);
1480 /* Is that all of data? */
1481 if (len+PTP_USB_BULK_HDR_LEN<=rlen) {
1485 ret = ptp_read_func(len - (rlen - PTP_USB_BULK_HDR_LEN),
1487 params->data, &rlen, 1);
1489 if (ret != PTP_RC_OK) {
1497 ptp_usb_getresp (PTPParams* params, PTPContainer* resp)
1501 PTPUSBBulkContainer usbresp;
1502 PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1505 LIBMTP_USB_DEBUG("RESPONSE: ");
1507 memset(&usbresp,0,sizeof(usbresp));
1508 /* read response, it should never be longer than sizeof(usbresp) */
1509 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1511 // Fix for bevahiour reported by Scott Snyder on Samsung YP-U3. The player
1512 // sends a packet containing just zeroes of length 2 (up to 4 has been seen too)
1513 // after a NULL packet when it should send the response. This code ignores
1514 // such illegal packets.
1515 while (ret==PTP_RC_OK && rlen<PTP_USB_BULK_HDR_LEN && usbresp.length==0) {
1516 libusb_glue_debug (params, "ptp_usb_getresp: detected short response "
1517 "of %d bytes, expect problems! (re-reading "
1519 ret = ptp_usb_getpacket(params, &usbresp, &rlen);
1522 if (ret != PTP_RC_OK) {
1525 if (dtoh16(usbresp.type)!=PTP_USB_CONTAINER_RESPONSE) {
1526 ret = PTP_ERROR_RESP_EXPECTED;
1528 if (dtoh16(usbresp.code)!=resp->Code) {
1529 ret = dtoh16(usbresp.code);
1532 LIBMTP_USB_DEBUG("%04x\n", ret);
1534 if (ret != PTP_RC_OK) {
1535 /* libusb_glue_error (params,
1536 "PTP: request code 0x%04x getting resp error 0x%04x",
1540 /* build an appropriate PTPContainer */
1541 resp->Code=dtoh16(usbresp.code);
1542 resp->SessionID=params->session_id;
1543 resp->Transaction_ID=dtoh32(usbresp.trans_id);
1544 if (FLAG_IGNORE_HEADER_ERRORS(ptp_usb)) {
1545 if (resp->Transaction_ID != params->transaction_id-1) {
1546 libusb_glue_debug (params, "ptp_usb_getresp: detected a broken "
1547 "PTP header, transaction ID insane, expect "
1548 "problems! (But continuing)");
1549 // Repair the header, so it won't wreak more havoc.
1550 resp->Transaction_ID = params->transaction_id-1;
1553 resp->Param1=dtoh32(usbresp.payload.params.param1);
1554 resp->Param2=dtoh32(usbresp.payload.params.param2);
1555 resp->Param3=dtoh32(usbresp.payload.params.param3);
1556 resp->Param4=dtoh32(usbresp.payload.params.param4);
1557 resp->Param5=dtoh32(usbresp.payload.params.param5);
1561 /* Event handling functions */
1563 /* PTP Events wait for or check mode */
1564 #define PTP_EVENT_CHECK 0x0000 /* waits for */
1565 #define PTP_EVENT_CHECK_FAST 0x0001 /* checks */
1567 static inline uint16_t
1568 ptp_usb_event (PTPParams* params, PTPContainer* event, int wait)
1573 PTPUSBEventContainer usbevent;
1576 memset(&usbevent,0,sizeof(usbevent));
1578 if ((params==NULL) || (event==NULL))
1579 return PTP_ERROR_BADPARAM;
1580 ptp_usb = (PTP_USB *)(params->data);
1584 case PTP_EVENT_CHECK:
1585 result = USB_BULK_READ(ptp_usb->handle,
1587 (unsigned char *) &usbevent,
1592 result = USB_BULK_READ(ptp_usb->handle,
1594 (unsigned char *) &usbevent,
1598 if (result < 0) ret = PTP_ERROR_IO;
1600 case PTP_EVENT_CHECK_FAST:
1601 result = USB_BULK_READ(ptp_usb->handle,
1603 (unsigned char *) &usbevent,
1608 result = USB_BULK_READ(ptp_usb->handle,
1610 (unsigned char *) &usbevent,
1614 if (result < 0) ret = PTP_ERROR_IO;
1617 ret = PTP_ERROR_BADPARAM;
1620 if (ret != PTP_RC_OK) {
1621 libusb_glue_error (params,
1622 "PTP: reading event an error 0x%04x occurred", ret);
1623 return PTP_ERROR_IO;
1627 libusb_glue_error (params,
1628 "PTP: reading event an short read of %ld bytes occurred", rlen);
1629 return PTP_ERROR_IO;
1631 /* if we read anything over interrupt endpoint it must be an event */
1632 /* build an appropriate PTPContainer */
1633 event->Code=dtoh16(usbevent.code);
1634 event->SessionID=params->session_id;
1635 event->Transaction_ID=dtoh32(usbevent.trans_id);
1636 event->Param1=dtoh32(usbevent.param1);
1637 event->Param2=dtoh32(usbevent.param2);
1638 event->Param3=dtoh32(usbevent.param3);
1643 ptp_usb_event_check (PTPParams* params, PTPContainer* event) {
1645 return ptp_usb_event (params, event, PTP_EVENT_CHECK_FAST);
1649 ptp_usb_event_wait (PTPParams* params, PTPContainer* event) {
1651 return ptp_usb_event (params, event, PTP_EVENT_CHECK);
1655 ptp_usb_control_cancel_request (PTPParams *params, uint32_t transactionid) {
1656 PTP_USB *ptp_usb = (PTP_USB *)(params->data);
1658 unsigned char buffer[6];
1660 htod16a(&buffer[0],PTP_EC_CancelTransaction);
1661 htod32a(&buffer[2],transactionid);
1662 ret = libusb_control_transfer(ptp_usb->handle,
1663 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
1664 0x64, 0x0000, 0x0000,
1668 if (ret < sizeof(buffer))
1669 return PTP_ERROR_IO;
1673 static int init_ptp_usb(PTPParams* params, PTP_USB* ptp_usb, libusb_device* dev)
1675 libusb_device_handle *device_handle;
1676 unsigned char buf[255];
1678 struct libusb_config_descriptor *config;
1680 params->sendreq_func=ptp_usb_sendreq;
1681 params->senddata_func=ptp_usb_senddata;
1682 params->getresp_func=ptp_usb_getresp;
1683 params->getdata_func=ptp_usb_getdata;
1684 params->cancelreq_func=ptp_usb_control_cancel_request;
1685 params->data=ptp_usb;
1686 params->transaction_id=0;
1688 * This is hardcoded here since we have no devices whatsoever that are BE.
1689 * Change this the day we run into our first BE device (if ever).
1691 params->byteorder = PTP_DL_LE;
1693 ptp_usb->timeout = get_timeout(ptp_usb);
1695 ret = libusb_open(dev, &device_handle);
1696 if (ret != LIBUSB_SUCCESS) {
1697 perror("libusb_open() failed!");
1700 ptp_usb->handle = device_handle;
1703 * If this device is known to be wrongfully claimed by other kernel
1704 * drivers (such as mass storage), then try to unload it to make it
1705 * accessible from user space.
1707 if (FLAG_UNLOAD_DRIVER(ptp_usb) &&
1708 libusb_kernel_driver_active(device_handle, ptp_usb->interface)
1710 if (LIBUSB_SUCCESS != libusb_detach_kernel_driver(device_handle, ptp_usb->interface)) {
1711 perror("libusb_detach_kernel_driver() failed, continuing anyway...");
1716 * Check if the config is set to something else than what we want
1717 * to use. Only set the configuration if we absolutely have to.
1718 * Also do not bail out if we fail.
1720 * Note that Darwin will not set the configuration for vendor-specific
1721 * devices so we need to go in and set it.
1723 ret = libusb_get_active_config_descriptor(dev, &config);
1724 if (ret != LIBUSB_SUCCESS) {
1725 perror("libusb_get_active_config_descriptor(1) failed");
1726 fprintf(stderr, "no active configuration, trying to set configuration\n");
1727 if (libusb_set_configuration(device_handle, ptp_usb->config) != LIBUSB_SUCCESS) {
1728 perror("libusb_set_configuration() failed, continuing anyway...");
1730 ret = libusb_get_active_config_descriptor(dev, &config);
1731 if (ret != LIBUSB_SUCCESS) {
1732 perror("libusb_get_active_config_descriptor(2) failed");
1736 if (config->bConfigurationValue != ptp_usb->config) {
1737 fprintf(stderr, "desired configuration different from current, trying to set configuration\n");
1738 if (libusb_set_configuration(device_handle, ptp_usb->config)) {
1739 perror("libusb_set_configuration() failed, continuing anyway...");
1741 /* Re-fetch the config descriptor if we changed */
1742 libusb_free_config_descriptor(config);
1743 ret = libusb_get_active_config_descriptor(dev, &config);
1744 if (ret != LIBUSB_SUCCESS) {
1745 perror("libusb_get_active_config_descriptor(2) failed");
1751 * It seems like on kernel 2.6.31 if we already have it open on another
1752 * pthread in our app, we'll get an error if we try to claim it again,
1753 * but that error is harmless because our process already claimed the interface
1755 usbresult = libusb_claim_interface(device_handle, ptp_usb->interface);
1758 fprintf(stderr, "ignoring libusb_claim_interface() = %d", usbresult);
1761 * If the altsetting is set to something different than we want, switch
1764 * FIXME: this seems to cause trouble on the Mac:s so disable it. Retry
1765 * this on the Mac now that it only sets this when the altsetting differs.
1768 #if 0 /* Disable this always, no idea on how to handle it */
1769 if (config->interface[].altsetting[].bAlternateSetting !=
1770 ptp_usb->altsetting) {
1771 fprintf(stderr, "desired altsetting different from current, trying to set altsetting\n");
1772 usbresult = libusb_set_interface_alt_setting(device_handle,
1774 ptp_usb->altsetting);
1776 fprintf(stderr, "ignoring libusb_set_interface_alt_setting() = %d\n", usbresult);
1781 libusb_free_config_descriptor(config);
1783 if (FLAG_SWITCH_MODE_BLACKBERRY(ptp_usb)) {
1786 // FIXME : Only for BlackBerry Storm
1787 // What does it mean? Maybe switch mode...
1788 // This first control message is absolutely necessary
1790 ret = libusb_control_transfer(device_handle,
1791 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1792 0xaa, 0x00, 0x04, buf, 0x40, 1000);
1793 LIBMTP_USB_DEBUG("BlackBerry magic part 1:\n");
1794 LIBMTP_USB_DATA(buf, ret, 16);
1797 // This control message is unnecessary
1798 ret = libusb_control_transfer(device_handle,
1799 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1800 0xa5, 0x00, 0x01, buf, 0x02, 1000);
1801 LIBMTP_USB_DEBUG("BlackBerry magic part 2:\n");
1802 LIBMTP_USB_DATA(buf, ret, 16);
1805 // This control message is unnecessary
1806 ret = libusb_control_transfer(device_handle,
1807 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1808 0xa8, 0x00, 0x01, buf, 0x05, 1000);
1809 LIBMTP_USB_DEBUG("BlackBerry magic part 3:\n");
1810 LIBMTP_USB_DATA(buf, ret, 16);
1813 // This control message is unnecessary
1814 ret = libusb_control_transfer(device_handle,
1815 LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN,
1816 0xa8, 0x00, 0x01, buf, 0x11, 1000);
1817 LIBMTP_USB_DEBUG("BlackBerry magic part 4:\n");
1818 LIBMTP_USB_DATA(buf, ret, 16);
1825 static void clear_stall(PTP_USB* ptp_usb)
1830 /* check the inep status */
1832 ret = usb_get_endpoint_status(ptp_usb,ptp_usb->inep,&status);
1834 perror ("inep: usb_get_endpoint_status()");
1835 } else if (status) {
1836 LIBMTP_INFO("Clearing stall on IN endpoint\n");
1837 ret = libusb_clear_halt (ptp_usb->handle, ptp_usb->inep);
1838 if (ret != LIBUSB_SUCCESS) {
1839 perror ("usb_clear_stall_feature()");
1843 /* check the outep status */
1845 ret = usb_get_endpoint_status(ptp_usb,ptp_usb->outep,&status);
1847 perror("outep: usb_get_endpoint_status()");
1848 } else if (status) {
1849 LIBMTP_INFO("Clearing stall on OUT endpoint\n");
1850 ret = libusb_clear_halt(ptp_usb->handle, ptp_usb->outep);
1851 if (ret != LIBUSB_SUCCESS) {
1852 perror("usb_clear_stall_feature()");
1856 /* TODO: do we need this for INTERRUPT (ptp_usb->intep) too? */
1859 static void close_usb(PTP_USB* ptp_usb)
1861 if (!FLAG_NO_RELEASE_INTERFACE(ptp_usb)) {
1863 * Clear any stalled endpoints
1864 * On misbehaving devices designed for Windows/Mac, quote from:
1865 * http://www2.one-eyed-alien.net/~mdharm/linux-usb/target_offenses.txt
1866 * Device does Bad Things(tm) when it gets a GET_STATUS after CLEAR_HALT
1867 * (...) Windows, when clearing a stall, only sends the CLEAR_HALT command,
1868 * and presumes that the stall has cleared. Some devices actually choke
1869 * if the CLEAR_HALT is followed by a GET_STATUS (used to determine if the
1870 * STALL is persistant or not).
1872 clear_stall(ptp_usb);
1873 libusb_release_interface(ptp_usb->handle, (int) ptp_usb->interface);
1875 if (FLAG_FORCE_RESET_ON_CLOSE(ptp_usb)) {
1877 * Some devices really love to get reset after being
1878 * disconnected. Again, since Windows never disconnects
1879 * a device closing behaviour is seldom or never exercised
1880 * on devices when engineered and often error prone.
1881 * Reset may help some.
1883 libusb_reset_device (ptp_usb->handle);
1885 libusb_close(ptp_usb->handle);
1891 static int find_interface_and_endpoints(libusb_device *dev,
1894 uint8_t *altsetting,
1896 int* inep_maxpacket,
1898 int *outep_maxpacket,
1902 struct libusb_device_descriptor desc;
1904 ret = libusb_get_device_descriptor(dev, &desc);
1905 if (ret != LIBUSB_SUCCESS)
1908 // Loop over the device configurations
1909 for (i = 0; i < desc.bNumConfigurations; i++) {
1911 struct libusb_config_descriptor *config;
1913 ret = libusb_get_config_descriptor(dev, i, &config);
1914 if (ret != LIBUSB_SUCCESS)
1917 *conf = config->bConfigurationValue;
1919 // Loop over each configurations interfaces
1920 for (j = 0; j < config->bNumInterfaces; j++) {
1924 int found_outep = 0;
1925 int found_intep = 0;
1926 const struct libusb_endpoint_descriptor *ep;
1928 // Inspect the altsettings of this interface...
1929 for (k = 0; k < config->interface[j].num_altsetting; k++) {
1931 // MTP devices shall have 3 endpoints, ignore those interfaces
1933 no_ep = config->interface[j].altsetting[k].bNumEndpoints;
1937 *interface = config->interface[j].altsetting[k].bInterfaceNumber;
1938 *altsetting = config->interface[j].altsetting[k].bAlternateSetting;
1939 ep = config->interface[j].altsetting[k].endpoint;
1941 // Loop over the three endpoints to locate two bulk and
1942 // one interrupt endpoint and FAIL if we cannot, and continue.
1943 for (l = 0; l < no_ep; l++) {
1944 if (ep[l].bmAttributes == LIBUSB_TRANSFER_TYPE_BULK) {
1945 if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
1946 LIBUSB_ENDPOINT_DIR_MASK) {
1947 *inep = ep[l].bEndpointAddress;
1948 *inep_maxpacket = ep[l].wMaxPacketSize;
1951 if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == 0) {
1952 *outep = ep[l].bEndpointAddress;
1953 *outep_maxpacket = ep[l].wMaxPacketSize;
1956 } else if (ep[l].bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT) {
1957 if ((ep[l].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ==
1958 LIBUSB_ENDPOINT_DIR_MASK) {
1959 *intep = ep[l].bEndpointAddress;
1964 if (found_inep && found_outep && found_intep) {
1965 libusb_free_config_descriptor(config);
1966 // We assigned the endpoints so return here.
1969 } // Next altsetting
1971 libusb_free_config_descriptor(config);
1977 * This function assigns params and usbinfo given a raw device
1979 * @param device the device to be assigned.
1980 * @param usbinfo a pointer to the new usbinfo.
1981 * @return an error code.
1983 LIBMTP_error_number_t configure_usb_device(LIBMTP_raw_device_t *device,
1988 libusb_device *ldevice;
1990 int err, found = 0, i;
1992 libusb_device **devs = NULL;
1993 struct libusb_device_descriptor desc;
1994 LIBMTP_error_number_t init_usb_ret;
1996 /* See if we can find this raw device again... */
1997 init_usb_ret = init_usb();
1998 if (init_usb_ret != LIBMTP_ERROR_NONE)
1999 return init_usb_ret;
2001 nrofdevs = libusb_get_device_list(NULL, &devs);
2002 for (i = 0; i < nrofdevs ; i++) {
2003 if (libusb_get_bus_number(devs[i]) != device->bus_location)
2005 if (libusb_get_device_address(devs[i]) != device->devnum)
2008 ret = libusb_get_device_descriptor(devs[i], &desc);
2009 if (ret != LIBUSB_SUCCESS) continue;
2011 if(desc.idVendor == device->device_entry.vendor_id &&
2012 desc.idProduct == device->device_entry.product_id ) {
2018 /* Device has gone since detecting raw devices! */
2020 libusb_free_device_list (devs, 0);
2021 return LIBMTP_ERROR_NO_DEVICE_ATTACHED;
2024 /* Allocate structs */
2025 ptp_usb = (PTP_USB *) malloc(sizeof(PTP_USB));
2026 if (ptp_usb == NULL) {
2027 libusb_free_device_list (devs, 0);
2028 return LIBMTP_ERROR_MEMORY_ALLOCATION;
2030 /* Start with a blank slate (includes setting device_flags to 0) */
2031 memset(ptp_usb, 0, sizeof(PTP_USB));
2033 /* Copy the raw device */
2034 memcpy(&ptp_usb->rawdevice, device, sizeof(LIBMTP_raw_device_t));
2037 * Some devices must have their "OS Descriptor" massaged in order
2040 if (FLAG_ALWAYS_PROBE_DESCRIPTOR(ptp_usb)) {
2041 // Massage the device descriptor
2042 (void) probe_device_descriptor(ldevice, NULL);
2045 /* Assign interface and endpoints to usbinfo... */
2046 err = find_interface_and_endpoints(ldevice,
2048 &ptp_usb->interface,
2049 &ptp_usb->altsetting,
2051 &ptp_usb->inep_maxpacket,
2053 &ptp_usb->outep_maxpacket,
2057 libusb_free_device_list (devs, 0);
2059 LIBMTP_ERROR("LIBMTP PANIC: Unable to find interface & endpoints of device\n");
2060 return LIBMTP_ERROR_CONNECTING;
2063 /* Copy USB version number */
2064 ptp_usb->bcdusb = desc.bcdUSB;
2066 /* Attempt to initialize this device */
2067 if (init_ptp_usb(params, ptp_usb, ldevice) < 0) {
2069 LIBMTP_ERROR("LIBMTP PANIC: Unable to initialize device\n");
2070 libusb_free_device_list (devs, 0);
2071 return LIBMTP_ERROR_CONNECTING;
2075 * This works in situations where previous bad applications
2076 * have not used LIBMTP_Release_Device on exit
2078 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2079 LIBMTP_ERROR("PTP_ERROR_IO: failed to open session, trying again after resetting USB interface\n");
2080 LIBMTP_ERROR("LIBMTP libusb: Attempt to reset device\n");
2081 libusb_reset_device (ptp_usb->handle);
2084 if(init_ptp_usb(params, ptp_usb, ldevice) <0) {
2085 LIBMTP_ERROR("LIBMTP PANIC: Could not init USB on second attempt\n");
2086 libusb_free_device_list (devs, 0);
2088 return LIBMTP_ERROR_CONNECTING;
2091 /* Device has been reset, try again */
2092 if ((ret = ptp_opensession(params, 1)) == PTP_ERROR_IO) {
2093 LIBMTP_ERROR("LIBMTP PANIC: failed to open session on second attempt\n");
2094 libusb_free_device_list (devs, 0);
2096 return LIBMTP_ERROR_CONNECTING;
2100 /* Was the transaction id invalid? Try again */
2101 if (ret == PTP_RC_InvalidTransactionID) {
2102 LIBMTP_ERROR("LIBMTP WARNING: Transaction ID was invalid, increment and try again\n");
2103 params->transaction_id += 10;
2104 ret = ptp_opensession(params, 1);
2107 if (ret != PTP_RC_SessionAlreadyOpened && ret != PTP_RC_OK) {
2108 LIBMTP_ERROR("LIBMTP PANIC: Could not open session! "
2109 "(Return code %d)\n Try to reset the device.\n",
2111 libusb_release_interface(ptp_usb->handle, ptp_usb->interface);
2112 libusb_free_device_list (devs, 0);
2114 return LIBMTP_ERROR_CONNECTING;
2117 /* OK configured properly */
2118 *usbinfo = (void *) ptp_usb;
2119 libusb_free_device_list (devs, 0);
2120 return LIBMTP_ERROR_NONE;
2124 void close_device (PTP_USB *ptp_usb, PTPParams *params)
2126 if (ptp_closesession(params)!=PTP_RC_OK)
2127 LIBMTP_ERROR("ERROR: Could not close session!\n");
2131 void set_usb_device_timeout(PTP_USB *ptp_usb, int timeout)
2133 ptp_usb->timeout = timeout;
2136 void get_usb_device_timeout(PTP_USB *ptp_usb, int *timeout)
2138 *timeout = ptp_usb->timeout;
2141 int guess_usb_speed(PTP_USB *ptp_usb)
2143 int bytes_per_second;
2146 * We don't know the actual speeds so these are rough guesses
2147 * from the info you can find here:
2148 * http://en.wikipedia.org/wiki/USB#Transfer_rates
2149 * http://www.barefeats.com/usb2.html
2151 switch (ptp_usb->bcdusb & 0xFF00) {
2153 /* 1.x USB versions let's say 1MiB/s */
2154 bytes_per_second = 1*1024*1024;
2158 /* USB 2.0 nominal speed 18MiB/s */
2159 /* USB 3.0 won't be worse? */
2160 bytes_per_second = 18*1024*1024;
2163 /* Half-guess something? */
2164 bytes_per_second = 1*1024*1024;
2167 return bytes_per_second;
2170 static int usb_get_endpoint_status(PTP_USB* ptp_usb, int ep, uint16_t* status)
2172 return libusb_control_transfer(ptp_usb->handle,
2173 LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_ENDPOINT,
2174 LIBUSB_REQUEST_GET_STATUS,
2177 (unsigned char *) status,