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