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