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