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