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