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