blob: 8a50ef19088aa589b42e24800e32e9ad7cbb55d1 [file] [log] [blame]
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "MtpDevice"
18
19#include "MtpDebug.h"
20#include "MtpDevice.h"
21#include "MtpDeviceInfo.h"
22#include "MtpEventPacket.h"
23#include "MtpObjectInfo.h"
24#include "MtpProperty.h"
25#include "MtpStorageInfo.h"
26#include "MtpStringBuffer.h"
27#include "MtpUtils.h"
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <sys/types.h>
32#include <sys/ioctl.h>
33#include <sys/stat.h>
34#include <fcntl.h>
35#include <errno.h>
36#include <endian.h>
37
38#include <usbhost/usbhost.h>
39
40namespace {
41
42static constexpr int USB_CONTROL_TRANSFER_TIMEOUT_MS = 200;
43
44} // namespace
45
46#if 0
47static bool isMtpDevice(uint16_t vendor, uint16_t product) {
48 // Sandisk Sansa Fuze
49 if (vendor == 0x0781 && product == 0x74c2)
50 return true;
51 // Samsung YP-Z5
52 if (vendor == 0x04e8 && product == 0x503c)
53 return true;
54 return false;
55}
56#endif
57
58namespace {
59
60bool writeToFd(void* data, uint32_t /* unused_offset */, uint32_t length, void* clientData) {
61 const int fd = *static_cast<int*>(clientData);
62 const ssize_t result = write(fd, data, length);
63 if (result < 0) {
64 return false;
65 }
66 return static_cast<uint32_t>(result) == length;
67}
68
69} // namespace
70
71MtpDevice* MtpDevice::open(const char* deviceName, int fd) {
72 struct usb_device *device = usb_device_new(deviceName, fd);
73 if (!device) {
74 MTPE("usb_device_new failed for %s", deviceName);
75 return NULL;
76 }
77
78 struct usb_descriptor_header* desc;
79 struct usb_descriptor_iter iter;
80
81 usb_descriptor_iter_init(device, &iter);
82
83 while ((desc = usb_descriptor_iter_next(&iter)) != NULL) {
84 if (desc->bDescriptorType == USB_DT_INTERFACE) {
85 struct usb_interface_descriptor *interface = (struct usb_interface_descriptor *)desc;
86
87 if (interface->bInterfaceClass == USB_CLASS_STILL_IMAGE &&
88 interface->bInterfaceSubClass == 1 && // Still Image Capture
89 interface->bInterfaceProtocol == 1) // Picture Transfer Protocol (PIMA 15470)
90 {
91 char* manufacturerName = usb_device_get_manufacturer_name(device,
92 USB_CONTROL_TRANSFER_TIMEOUT_MS);
93 char* productName = usb_device_get_product_name(device,
94 USB_CONTROL_TRANSFER_TIMEOUT_MS);
95 MTPD("Found camera: \"%s\" \"%s\"\n", manufacturerName, productName);
96 free(manufacturerName);
97 free(productName);
98 } else if (interface->bInterfaceClass == 0xFF &&
99 interface->bInterfaceSubClass == 0xFF &&
100 interface->bInterfaceProtocol == 0) {
101 char* interfaceName = usb_device_get_string(device, interface->iInterface,
102 USB_CONTROL_TRANSFER_TIMEOUT_MS);
103 if (!interfaceName) {
104 continue;
105 } else if (strcmp(interfaceName, "MTP")) {
106 free(interfaceName);
107 continue;
108 }
109 free(interfaceName);
110
111 // Looks like an android style MTP device
112 char* manufacturerName = usb_device_get_manufacturer_name(device,
113 USB_CONTROL_TRANSFER_TIMEOUT_MS);
114 char* productName = usb_device_get_product_name(device,
115 USB_CONTROL_TRANSFER_TIMEOUT_MS);
116 MTPD("Found MTP device: \"%s\" \"%s\"\n", manufacturerName, productName);
117 free(manufacturerName);
118 free(productName);
119 }
120#if 0
121 else {
122 // look for special cased devices based on vendor/product ID
123 // we are doing this mainly for testing purposes
124 uint16_t vendor = usb_device_get_vendor_id(device);
125 uint16_t product = usb_device_get_product_id(device);
126 if (!isMtpDevice(vendor, product)) {
127 // not an MTP or PTP device
128 continue;
129 }
130 // request MTP OS string and descriptor
131 // some music players need to see this before entering MTP mode.
132 char buffer[256];
133 memset(buffer, 0, sizeof(buffer));
134 int ret = usb_device_control_transfer(device,
135 USB_DIR_IN|USB_RECIP_DEVICE|USB_TYPE_STANDARD,
136 USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) | 0xEE,
137 0, buffer, sizeof(buffer), 0);
138 printf("usb_device_control_transfer returned %d errno: %d\n", ret, errno);
139 if (ret > 0) {
140 printf("got MTP string %s\n", buffer);
141 ret = usb_device_control_transfer(device,
142 USB_DIR_IN|USB_RECIP_DEVICE|USB_TYPE_VENDOR, 1,
143 0, 4, buffer, sizeof(buffer), 0);
144 printf("OS descriptor got %d\n", ret);
145 } else {
146 printf("no MTP string\n");
147 }
148 }
149#else
150 else {
151 continue;
152 }
153#endif
154 // if we got here, then we have a likely MTP or PTP device
155
156 // interface should be followed by three endpoints
157 struct usb_endpoint_descriptor *ep;
158 struct usb_endpoint_descriptor *ep_in_desc = NULL;
159 struct usb_endpoint_descriptor *ep_out_desc = NULL;
160 struct usb_endpoint_descriptor *ep_intr_desc = NULL;
161 //USB3 add USB_DT_SS_ENDPOINT_COMP as companion descriptor;
162 struct usb_ss_ep_comp_descriptor *ep_ss_ep_comp_desc = NULL;
163 for (int i = 0; i < 3; i++) {
164 ep = (struct usb_endpoint_descriptor *)usb_descriptor_iter_next(&iter);
165 if (ep && ep->bDescriptorType == USB_DT_SS_ENDPOINT_COMP) {
166 MTPD("Descriptor type is USB_DT_SS_ENDPOINT_COMP for USB3 \n");
167 ep_ss_ep_comp_desc = (usb_ss_ep_comp_descriptor*)ep;
168 ep = (struct usb_endpoint_descriptor *)usb_descriptor_iter_next(&iter);
169 }
170
171 if (!ep || ep->bDescriptorType != USB_DT_ENDPOINT) {
172 MTPE("endpoints not found\n");
173 usb_device_close(device);
174 return NULL;
175 }
176
177 if (ep->bmAttributes == USB_ENDPOINT_XFER_BULK) {
178 if (ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
179 ep_in_desc = ep;
180 else
181 ep_out_desc = ep;
182 } else if (ep->bmAttributes == USB_ENDPOINT_XFER_INT &&
183 ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
184 ep_intr_desc = ep;
185 }
186 }
187 if (!ep_in_desc || !ep_out_desc || !ep_intr_desc) {
188 MTPE("endpoints not found\n");
189 usb_device_close(device);
190 return NULL;
191 }
192
193 int ret = usb_device_claim_interface(device, interface->bInterfaceNumber);
194 if (ret && errno == EBUSY) {
195 // disconnect kernel driver and try again
196 usb_device_connect_kernel_driver(device, interface->bInterfaceNumber, false);
197 ret = usb_device_claim_interface(device, interface->bInterfaceNumber);
198 }
199 if (ret) {
200 MTPE("usb_device_claim_interface failed errno: %d\n", errno);
201 usb_device_close(device);
202 return NULL;
203 }
204
205 MtpDevice* mtpDevice = new MtpDevice(device, interface->bInterfaceNumber,
206 ep_in_desc, ep_out_desc, ep_intr_desc);
207 mtpDevice->initialize();
208 return mtpDevice;
209 }
210 }
211
212 usb_device_close(device);
213 MTPE("device not found");
214 return NULL;
215}
216
217MtpDevice::MtpDevice(struct usb_device* device, int interface,
218 const struct usb_endpoint_descriptor *ep_in,
219 const struct usb_endpoint_descriptor *ep_out,
220 const struct usb_endpoint_descriptor *ep_intr)
221 : mDevice(device),
222 mInterface(interface),
223 mRequestIn1(NULL),
224 mRequestIn2(NULL),
225 mRequestOut(NULL),
226 mRequestIntr(NULL),
227 mDeviceInfo(NULL),
228 mSessionID(0),
229 mTransactionID(0),
230 mReceivedResponse(false),
231 mProcessingEvent(false),
232 mCurrentEventHandle(0),
233 mLastSendObjectInfoTransactionID(0),
234 mLastSendObjectInfoObjectHandle(0),
235 mPacketDivisionMode(FIRST_PACKET_HAS_PAYLOAD)
236{
237 mRequestIn1 = usb_request_new(device, ep_in);
238 mRequestIn2 = usb_request_new(device, ep_in);
239 mRequestOut = usb_request_new(device, ep_out);
240 mRequestIntr = usb_request_new(device, ep_intr);
241}
242
243MtpDevice::~MtpDevice() {
244 close();
245 for (size_t i = 0; i < mDeviceProperties.size(); i++)
246 delete mDeviceProperties[i];
247 usb_request_free(mRequestIn1);
248 usb_request_free(mRequestIn2);
249 usb_request_free(mRequestOut);
250 usb_request_free(mRequestIntr);
251}
252
253void MtpDevice::initialize() {
254 openSession();
255 mDeviceInfo = getDeviceInfo();
256 if (mDeviceInfo) {
257 if (mDeviceInfo->mDeviceProperties) {
258 int count = mDeviceInfo->mDeviceProperties->size();
259 for (int i = 0; i < count; i++) {
260 MtpDeviceProperty propCode = (*mDeviceInfo->mDeviceProperties)[i];
261 MtpProperty* property = getDevicePropDesc(propCode);
262 if (property)
263 mDeviceProperties.push_back(property);
264 }
265 }
266 }
267}
268
269void MtpDevice::close() {
270 if (mDevice) {
271 usb_device_release_interface(mDevice, mInterface);
272 usb_device_close(mDevice);
273 mDevice = NULL;
274 }
275}
276
277void MtpDevice::print() {
278 if (!mDeviceInfo)
279 return;
280
281 mDeviceInfo->print();
282
283 if (mDeviceInfo->mDeviceProperties) {
284 MTPD("***** DEVICE PROPERTIES *****\n");
285 int count = mDeviceInfo->mDeviceProperties->size();
286 for (int i = 0; i < count; i++) {
287 MtpDeviceProperty propCode = (*mDeviceInfo->mDeviceProperties)[i];
288 MtpProperty* property = getDevicePropDesc(propCode);
289 if (property) {
290 property->print();
291 delete property;
292 }
293 }
294 }
295
296 if (mDeviceInfo->mPlaybackFormats) {
297 MTPD("***** OBJECT PROPERTIES *****\n");
298 int count = mDeviceInfo->mPlaybackFormats->size();
299 for (int i = 0; i < count; i++) {
300 MtpObjectFormat format = (*mDeviceInfo->mPlaybackFormats)[i];
301 MTPD("*** FORMAT: %s\n", MtpDebug::getFormatCodeName(format));
302 MtpObjectPropertyList* props = getObjectPropsSupported(format);
303 if (props) {
304 for (size_t j = 0; j < props->size(); j++) {
305 MtpObjectProperty prop = (*props)[j];
306 MtpProperty* property = getObjectPropDesc(prop, format);
307 if (property) {
308 property->print();
309 delete property;
310 } else {
311 MTPE("could not fetch property: %s",
312 MtpDebug::getObjectPropCodeName(prop));
313 }
314 }
315 }
316 }
317 }
318}
319
320const char* MtpDevice::getDeviceName() {
321 if (mDevice)
322 return usb_device_get_name(mDevice);
323 else
324 return "???";
325}
326
327bool MtpDevice::openSession() {
328 std::lock_guard<std::mutex> lg(mMutex);
329
330 mSessionID = 0;
331 mTransactionID = 0;
332 MtpSessionID newSession = 1;
333 mRequest.reset();
334 mRequest.setParameter(1, newSession);
335 if (!sendRequest(MTP_OPERATION_OPEN_SESSION))
336 return false;
337 MtpResponseCode ret = readResponse();
338 if (ret == MTP_RESPONSE_SESSION_ALREADY_OPEN)
339 newSession = mResponse.getParameter(1);
340 else if (ret != MTP_RESPONSE_OK)
341 return false;
342
343 mSessionID = newSession;
344 mTransactionID = 1;
345 return true;
346}
347
348bool MtpDevice::closeSession() {
349 // FIXME
350 return true;
351}
352
353MtpDeviceInfo* MtpDevice::getDeviceInfo() {
354 std::lock_guard<std::mutex> lg(mMutex);
355
356 mRequest.reset();
357 if (!sendRequest(MTP_OPERATION_GET_DEVICE_INFO))
358 return NULL;
359 if (!readData())
360 return NULL;
361 MtpResponseCode ret = readResponse();
362 if (ret == MTP_RESPONSE_OK) {
363 MtpDeviceInfo* info = new MtpDeviceInfo;
364 if (info->read(mData))
365 return info;
366 else
367 delete info;
368 }
369 return NULL;
370}
371
372MtpStorageIDList* MtpDevice::getStorageIDs() {
373 std::lock_guard<std::mutex> lg(mMutex);
374
375 mRequest.reset();
376 if (!sendRequest(MTP_OPERATION_GET_STORAGE_IDS))
377 return NULL;
378 if (!readData())
379 return NULL;
380 MtpResponseCode ret = readResponse();
381 if (ret == MTP_RESPONSE_OK) {
382 return mData.getAUInt32();
383 }
384 return NULL;
385}
386
387MtpStorageInfo* MtpDevice::getStorageInfo(MtpStorageID storageID) {
388 std::lock_guard<std::mutex> lg(mMutex);
389
390 mRequest.reset();
391 mRequest.setParameter(1, storageID);
392 if (!sendRequest(MTP_OPERATION_GET_STORAGE_INFO))
393 return NULL;
394 if (!readData())
395 return NULL;
396 MtpResponseCode ret = readResponse();
397 if (ret == MTP_RESPONSE_OK) {
398 MtpStorageInfo* info = new MtpStorageInfo(storageID);
399 if (info->read(mData))
400 return info;
401 else
402 delete info;
403 }
404 return NULL;
405}
406
407MtpObjectHandleList* MtpDevice::getObjectHandles(MtpStorageID storageID,
408 MtpObjectFormat format, MtpObjectHandle parent) {
409 std::lock_guard<std::mutex> lg(mMutex);
410
411 mRequest.reset();
412 mRequest.setParameter(1, storageID);
413 mRequest.setParameter(2, format);
414 mRequest.setParameter(3, parent);
415 if (!sendRequest(MTP_OPERATION_GET_OBJECT_HANDLES))
416 return NULL;
417 if (!readData())
418 return NULL;
419 MtpResponseCode ret = readResponse();
420 if (ret == MTP_RESPONSE_OK) {
421 return mData.getAUInt32();
422 }
423 return NULL;
424}
425
426MtpObjectInfo* MtpDevice::getObjectInfo(MtpObjectHandle handle) {
427 std::lock_guard<std::mutex> lg(mMutex);
428
429 // FIXME - we might want to add some caching here
430
431 mRequest.reset();
432 mRequest.setParameter(1, handle);
433 if (!sendRequest(MTP_OPERATION_GET_OBJECT_INFO))
434 return NULL;
435 if (!readData())
436 return NULL;
437 MtpResponseCode ret = readResponse();
438 if (ret == MTP_RESPONSE_OK) {
439 MtpObjectInfo* info = new MtpObjectInfo(handle);
440 if (info->read(mData))
441 return info;
442 else
443 delete info;
444 }
445 return NULL;
446}
447
448void* MtpDevice::getThumbnail(MtpObjectHandle handle, int& outLength) {
449 std::lock_guard<std::mutex> lg(mMutex);
450
451 mRequest.reset();
452 mRequest.setParameter(1, handle);
453 if (sendRequest(MTP_OPERATION_GET_THUMB) && readData()) {
454 MtpResponseCode ret = readResponse();
455 if (ret == MTP_RESPONSE_OK) {
456 return mData.getData(&outLength);
457 }
458 }
459 outLength = 0;
460 return NULL;
461}
462
463MtpObjectHandle MtpDevice::sendObjectInfo(MtpObjectInfo* info) {
464 std::lock_guard<std::mutex> lg(mMutex);
465
466 mRequest.reset();
467 MtpObjectHandle parent = info->mParent;
468 if (parent == 0)
469 parent = MTP_PARENT_ROOT;
470
471 mRequest.setParameter(1, info->mStorageID);
472 mRequest.setParameter(2, parent);
473
474 mData.reset();
475 mData.putUInt32(info->mStorageID);
476 mData.putUInt16(info->mFormat);
477 mData.putUInt16(info->mProtectionStatus);
478 mData.putUInt32(info->mCompressedSize);
479 mData.putUInt16(info->mThumbFormat);
480 mData.putUInt32(info->mThumbCompressedSize);
481 mData.putUInt32(info->mThumbPixWidth);
482 mData.putUInt32(info->mThumbPixHeight);
483 mData.putUInt32(info->mImagePixWidth);
484 mData.putUInt32(info->mImagePixHeight);
485 mData.putUInt32(info->mImagePixDepth);
486 mData.putUInt32(info->mParent);
487 mData.putUInt16(info->mAssociationType);
488 mData.putUInt32(info->mAssociationDesc);
489 mData.putUInt32(info->mSequenceNumber);
490 mData.putString(info->mName);
491
492 char created[100], modified[100];
493 formatDateTime(info->mDateCreated, created, sizeof(created));
494 formatDateTime(info->mDateModified, modified, sizeof(modified));
495
496 mData.putString(created);
497 mData.putString(modified);
498 if (info->mKeywords)
499 mData.putString(info->mKeywords);
500 else
501 mData.putEmptyString();
502
503 if (sendRequest(MTP_OPERATION_SEND_OBJECT_INFO) && sendData()) {
504 MtpResponseCode ret = readResponse();
505 if (ret == MTP_RESPONSE_OK) {
506 mLastSendObjectInfoTransactionID = mRequest.getTransactionID();
507 mLastSendObjectInfoObjectHandle = mResponse.getParameter(3);
508 info->mStorageID = mResponse.getParameter(1);
509 info->mParent = mResponse.getParameter(2);
510 info->mHandle = mResponse.getParameter(3);
511 return info->mHandle;
512 }
513 }
514 return (MtpObjectHandle)-1;
515}
516
517bool MtpDevice::sendObject(MtpObjectHandle handle, int size, int srcFD) {
518 std::lock_guard<std::mutex> lg(mMutex);
519
520 if (mLastSendObjectInfoTransactionID + 1 != mTransactionID ||
521 mLastSendObjectInfoObjectHandle != handle) {
522 MTPE("A sendObject request must follow the sendObjectInfo request.");
523 return false;
524 }
525
526 mRequest.reset();
527 if (sendRequest(MTP_OPERATION_SEND_OBJECT)) {
528 mData.setOperationCode(mRequest.getOperationCode());
529 mData.setTransactionID(mRequest.getTransactionID());
530 const int writeResult = mData.write(mRequestOut, mPacketDivisionMode, srcFD, size);
531 const MtpResponseCode ret = readResponse();
532 return ret == MTP_RESPONSE_OK && writeResult > 0;
533 }
534 return false;
535}
536
537bool MtpDevice::deleteObject(MtpObjectHandle handle) {
538 std::lock_guard<std::mutex> lg(mMutex);
539
540 mRequest.reset();
541 mRequest.setParameter(1, handle);
542 if (sendRequest(MTP_OPERATION_DELETE_OBJECT)) {
543 MtpResponseCode ret = readResponse();
544 if (ret == MTP_RESPONSE_OK)
545 return true;
546 }
547 return false;
548}
549
550MtpObjectHandle MtpDevice::getParent(MtpObjectHandle handle) {
551 MtpObjectInfo* info = getObjectInfo(handle);
552 if (info) {
553 MtpObjectHandle parent = info->mParent;
554 delete info;
555 return parent;
556 } else {
557 return -1;
558 }
559}
560
561MtpObjectHandle MtpDevice::getStorageID(MtpObjectHandle handle) {
562 MtpObjectInfo* info = getObjectInfo(handle);
563 if (info) {
564 MtpObjectHandle storageId = info->mStorageID;
565 delete info;
566 return storageId;
567 } else {
568 return -1;
569 }
570}
571
572MtpObjectPropertyList* MtpDevice::getObjectPropsSupported(MtpObjectFormat format) {
573 std::lock_guard<std::mutex> lg(mMutex);
574
575 mRequest.reset();
576 mRequest.setParameter(1, format);
577 if (!sendRequest(MTP_OPERATION_GET_OBJECT_PROPS_SUPPORTED))
578 return NULL;
579 if (!readData())
580 return NULL;
581 MtpResponseCode ret = readResponse();
582 if (ret == MTP_RESPONSE_OK) {
583 return mData.getAUInt16();
584 }
585 return NULL;
586
587}
588
589MtpProperty* MtpDevice::getDevicePropDesc(MtpDeviceProperty code) {
590 std::lock_guard<std::mutex> lg(mMutex);
591
592 mRequest.reset();
593 mRequest.setParameter(1, code);
594 if (!sendRequest(MTP_OPERATION_GET_DEVICE_PROP_DESC))
595 return NULL;
596 if (!readData())
597 return NULL;
598 MtpResponseCode ret = readResponse();
599 if (ret == MTP_RESPONSE_OK) {
600 MtpProperty* property = new MtpProperty;
601 if (property->read(mData))
602 return property;
603 else
604 delete property;
605 }
606 return NULL;
607}
608
609MtpProperty* MtpDevice::getObjectPropDesc(MtpObjectProperty code, MtpObjectFormat format) {
610 std::lock_guard<std::mutex> lg(mMutex);
611
612 mRequest.reset();
613 mRequest.setParameter(1, code);
614 mRequest.setParameter(2, format);
615 if (!sendRequest(MTP_OPERATION_GET_OBJECT_PROP_DESC))
616 return NULL;
617 if (!readData())
618 return NULL;
619 const MtpResponseCode ret = readResponse();
620 if (ret == MTP_RESPONSE_OK) {
621 MtpProperty* property = new MtpProperty;
622 if (property->read(mData))
623 return property;
624 else
625 delete property;
626 }
627 return NULL;
628}
629
630bool MtpDevice::getObjectPropValue(MtpObjectHandle handle, MtpProperty* property) {
631 if (property == nullptr)
632 return false;
633
634 std::lock_guard<std::mutex> lg(mMutex);
635
636 mRequest.reset();
637 mRequest.setParameter(1, handle);
638 mRequest.setParameter(2, property->getPropertyCode());
639 if (!sendRequest(MTP_OPERATION_GET_OBJECT_PROP_VALUE))
640 return false;
641 if (!readData())
642 return false;
643 if (readResponse() != MTP_RESPONSE_OK)
644 return false;
645 property->setCurrentValue(mData);
646 return true;
647}
648
649bool MtpDevice::readObject(MtpObjectHandle handle,
650 ReadObjectCallback callback,
651 uint32_t expectedLength,
652 void* clientData) {
653 return readObjectInternal(handle, callback, &expectedLength, clientData);
654}
655
656// reads the object's data and writes it to the specified file path
657bool MtpDevice::readObject(MtpObjectHandle handle, const char* destPath, int group, int perm) {
658 MTPD("readObject: %s", destPath);
659 int fd = ::open(destPath, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
660 if (fd < 0) {
661 MTPE("open failed for %s", destPath);
662 return false;
663 }
664
665 fchown(fd, getuid(), group);
666 // set permissions
667 int mask = umask(0);
668 fchmod(fd, perm);
669 umask(mask);
670
671 bool result = readObject(handle, fd);
672 ::close(fd);
673 return result;
674}
675
676bool MtpDevice::readObject(MtpObjectHandle handle, int fd) {
677 MTPD("readObject: %d", fd);
678 return readObjectInternal(handle, writeToFd, NULL /* expected size */, &fd);
679}
680
681bool MtpDevice::readObjectInternal(MtpObjectHandle handle,
682 ReadObjectCallback callback,
683 const uint32_t* expectedLength,
684 void* clientData) {
685 std::lock_guard<std::mutex> lg(mMutex);
686
687 mRequest.reset();
688 mRequest.setParameter(1, handle);
689 if (!sendRequest(MTP_OPERATION_GET_OBJECT)) {
690 MTPE("Failed to send a read request.");
691 return false;
692 }
693
694 return readData(callback, expectedLength, nullptr, clientData);
695}
696
697bool MtpDevice::readData(ReadObjectCallback callback,
698 const uint32_t* expectedLength,
699 uint32_t* writtenSize,
700 void* clientData) {
701 if (!mData.readDataHeader(mRequestIn1)) {
702 MTPE("Failed to read header.");
703 return false;
704 }
705
706 // If object size 0 byte, the remote device may reply a response packet without sending any data
707 // packets.
708 if (mData.getContainerType() == MTP_CONTAINER_TYPE_RESPONSE) {
709 mResponse.copyFrom(mData);
710 return mResponse.getResponseCode() == MTP_RESPONSE_OK;
711 }
712
713 const uint32_t fullLength = mData.getContainerLength();
714 if (fullLength < MTP_CONTAINER_HEADER_SIZE) {
715 MTPE("fullLength is too short: %d", fullLength);
716 return false;
717 }
718 const uint32_t length = fullLength - MTP_CONTAINER_HEADER_SIZE;
719 if (expectedLength && length != *expectedLength) {
720 MTPE("readObject error length: %d", fullLength);
721 return false;
722 }
723
724 uint32_t offset = 0;
725 bool writingError = false;
726
727 {
728 int initialDataLength = 0;
729 void* const initialData = mData.getData(&initialDataLength);
730 if (fullLength > MTP_CONTAINER_HEADER_SIZE && initialDataLength == 0) {
731 // According to the MTP spec, the responder (MTP device) can choose two ways of sending
732 // data. a) The first packet contains the head and as much of the payload as possible
733 // b) The first packet contains only the header. The initiator (MTP host) needs
734 // to remember which way the responder used, and send upcoming data in the same way.
735 MTPD("Found short packet that contains only a header.");
736 mPacketDivisionMode = FIRST_PACKET_ONLY_HEADER;
737 }
738 if (initialData) {
739 if (initialDataLength > 0) {
740 if (!callback(initialData, offset, initialDataLength, clientData)) {
741 MTPE("Failed to write initial data.");
742 writingError = true;
743 }
744 offset += initialDataLength;
745 }
746 free(initialData);
747 }
748 }
749
750 // USB reads greater than 16K don't work.
751 char buffer1[MTP_BUFFER_SIZE], buffer2[MTP_BUFFER_SIZE];
752 mRequestIn1->buffer = buffer1;
753 mRequestIn2->buffer = buffer2;
754 struct usb_request* req = NULL;
755
756 while (offset < length) {
757 // Wait for previous read to complete.
758 void* writeBuffer = NULL;
759 int writeLength = 0;
760 if (req) {
761 const int read = mData.readDataWait(mDevice);
762 if (read < 0) {
763 MTPE("readDataWait failed.");
764 return false;
765 }
766 writeBuffer = req->buffer;
767 writeLength = read;
768 }
769
770 // Request to read next chunk.
771 const uint32_t nextOffset = offset + writeLength;
772 if (nextOffset < length) {
773 // Queue up a read request.
774 const size_t remaining = length - nextOffset;
775 req = (req == mRequestIn1 ? mRequestIn2 : mRequestIn1);
776 req->buffer_length = remaining > MTP_BUFFER_SIZE ?
777 static_cast<size_t>(MTP_BUFFER_SIZE) : remaining;
778 if (mData.readDataAsync(req) != 0) {
779 MTPE("readDataAsync failed");
780 return false;
781 }
782 }
783
784 // Write previous buffer.
785 if (writeBuffer && !writingError) {
786 if (!callback(writeBuffer, offset, writeLength, clientData)) {
787 MTPE("write failed");
788 writingError = true;
789 }
790 }
791 offset = nextOffset;
792 }
793
794 if (writtenSize) {
795 *writtenSize = length;
796 }
797
798 return readResponse() == MTP_RESPONSE_OK;
799}
800
801bool MtpDevice::readPartialObject(MtpObjectHandle handle,
802 uint32_t offset,
803 uint32_t size,
804 uint32_t *writtenSize,
805 ReadObjectCallback callback,
806 void* clientData) {
807 std::lock_guard<std::mutex> lg(mMutex);
808
809 mRequest.reset();
810 mRequest.setParameter(1, handle);
811 mRequest.setParameter(2, offset);
812 mRequest.setParameter(3, size);
813 if (!sendRequest(MTP_OPERATION_GET_PARTIAL_OBJECT)) {
814 MTPE("Failed to send a read request.");
815 return false;
816 }
817 // The expected size is null because it requires the exact number of bytes to read though
818 // MTP_OPERATION_GET_PARTIAL_OBJECT allows devices to return shorter length of bytes than
819 // requested. Destination's buffer length should be checked in |callback|.
820 return readData(callback, nullptr /* expected size */, writtenSize, clientData);
821}
822
823bool MtpDevice::readPartialObject64(MtpObjectHandle handle,
824 uint64_t offset,
825 uint32_t size,
826 uint32_t *writtenSize,
827 ReadObjectCallback callback,
828 void* clientData) {
829 std::lock_guard<std::mutex> lg(mMutex);
830
831 mRequest.reset();
832 mRequest.setParameter(1, handle);
833 mRequest.setParameter(2, 0xffffffff & offset);
834 mRequest.setParameter(3, 0xffffffff & (offset >> 32));
835 mRequest.setParameter(4, size);
836 if (!sendRequest(MTP_OPERATION_GET_PARTIAL_OBJECT_64)) {
837 MTPE("Failed to send a read request.");
838 return false;
839 }
840 // The expected size is null because it requires the exact number of bytes to read though
841 // MTP_OPERATION_GET_PARTIAL_OBJECT_64 allows devices to return shorter length of bytes than
842 // requested. Destination's buffer length should be checked in |callback|.
843 return readData(callback, nullptr /* expected size */, writtenSize, clientData);
844}
845
846bool MtpDevice::sendRequest(MtpOperationCode operation) {
847 MTPD("sendRequest: %s\n", MtpDebug::getOperationCodeName(operation));
848 mReceivedResponse = false;
849 mRequest.setOperationCode(operation);
850 if (mTransactionID > 0)
851 mRequest.setTransactionID(mTransactionID++);
852 int ret = mRequest.write(mRequestOut);
853 mRequest.dump();
854 return (ret > 0);
855}
856
857bool MtpDevice::sendData() {
858 MTPD("sendData\n");
859 mData.setOperationCode(mRequest.getOperationCode());
860 mData.setTransactionID(mRequest.getTransactionID());
861 int ret = mData.write(mRequestOut, mPacketDivisionMode);
862 mData.dump();
863 return (ret >= 0);
864}
865
866bool MtpDevice::readData() {
867 mData.reset();
868 int ret = mData.read(mRequestIn1);
869 MTPD("readData returned %d\n", ret);
870 if (ret >= MTP_CONTAINER_HEADER_SIZE) {
871 if (mData.getContainerType() == MTP_CONTAINER_TYPE_RESPONSE) {
872 MTPD("got response packet instead of data packet");
873 // we got a response packet rather than data
874 // copy it to mResponse
875 mResponse.copyFrom(mData);
876 mReceivedResponse = true;
877 return false;
878 }
879 mData.dump();
880 return true;
881 }
882 else {
883 MTPD("readResponse failed\n");
884 return false;
885 }
886}
887
888MtpResponseCode MtpDevice::readResponse() {
889 MTPD("readResponse\n");
890 if (mReceivedResponse) {
891 mReceivedResponse = false;
892 return mResponse.getResponseCode();
893 }
894 int ret = mResponse.read(mRequestIn1);
895 // handle zero length packets, which might occur if the data transfer
896 // ends on a packet boundary
897 if (ret == 0)
898 ret = mResponse.read(mRequestIn1);
899 if (ret >= MTP_CONTAINER_HEADER_SIZE) {
900 mResponse.dump();
901 return mResponse.getResponseCode();
902 } else {
903 MTPD("readResponse failed\n");
904 return -1;
905 }
906}
907
908int MtpDevice::submitEventRequest() {
909 if (!mEventMutex.try_lock()) {
910 // An event is being reaped on another thread.
911 return -1;
912 }
913 if (mProcessingEvent) {
914 // An event request was submitted, but no reapEventRequest called so far.
915 return -1;
916 }
917 std::lock_guard<std::mutex> lg(mEventMutexForInterrupt);
918 mEventPacket.sendRequest(mRequestIntr);
919 const int currentHandle = ++mCurrentEventHandle;
920 mProcessingEvent = true;
921 mEventMutex.unlock();
922 return currentHandle;
923}
924
925int MtpDevice::reapEventRequest(int handle, uint32_t (*parameters)[3]) {
926 std::lock_guard<std::mutex> lg(mEventMutex);
927 if (!mProcessingEvent || mCurrentEventHandle != handle || !parameters) {
928 return -1;
929 }
930 mProcessingEvent = false;
931 const int readSize = mEventPacket.readResponse(mRequestIntr->dev);
932 const int result = mEventPacket.getEventCode();
933 // MTP event has three parameters.
934 (*parameters)[0] = mEventPacket.getParameter(1);
935 (*parameters)[1] = mEventPacket.getParameter(2);
936 (*parameters)[2] = mEventPacket.getParameter(3);
937 return readSize != 0 ? result : 0;
938}
939
940void MtpDevice::discardEventRequest(int handle) {
941 std::lock_guard<std::mutex> lg(mEventMutexForInterrupt);
942 if (mCurrentEventHandle != handle) {
943 return;
944 }
945 usb_request_cancel(mRequestIntr);
946}