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