MtpDevice.cpp revision 95faffd31926e2e0b83923c181629d1cea29e88f
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
40namespace android {
41
42#if 0
43static 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
54namespace {
55
56bool 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
67MtpDevice* 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
208MtpDevice::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
231MtpDevice::~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
241void 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
257void MtpDevice::close() {
258    if (mDevice) {
259        usb_device_release_interface(mDevice, mInterface);
260        usb_device_close(mDevice);
261        mDevice = NULL;
262    }
263}
264
265void 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
307const char* MtpDevice::getDeviceName() {
308    if (mDevice)
309        return usb_device_get_name(mDevice);
310    else
311        return "???";
312}
313
314bool 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
335bool MtpDevice::closeSession() {
336    // FIXME
337    return true;
338}
339
340MtpDeviceInfo* 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
359MtpStorageIDList* 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
374MtpStorageInfo* 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
394MtpObjectHandleList* 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
413MtpObjectInfo* 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
435void* 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
450MtpObjectHandle 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
502bool 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
532bool 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
545MtpObjectHandle 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
556MtpObjectHandle 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
567MtpObjectPropertyList* 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
584MtpProperty* 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
604MtpProperty* 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    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
625bool MtpDevice::readObject(MtpObjectHandle handle,
626                           ReadObjectCallback callback,
627                           uint32_t expectedLength,
628                           void* clientData) {
629    return readObjectInternal(handle, callback, &expectedLength, clientData);
630}
631
632// reads the object's data and writes it to the specified file path
633bool MtpDevice::readObject(MtpObjectHandle handle, const char* destPath, int group, int perm) {
634    ALOGD("readObject: %s", destPath);
635    int fd = ::open(destPath, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
636    if (fd < 0) {
637        ALOGE("open failed for %s", destPath);
638        return false;
639    }
640
641    fchown(fd, getuid(), group);
642    // set permissions
643    int mask = umask(0);
644    fchmod(fd, perm);
645    umask(mask);
646
647    bool result = readObject(handle, fd);
648    ::close(fd);
649    return result;
650}
651
652bool MtpDevice::readObject(MtpObjectHandle handle, int fd) {
653    ALOGD("readObject: %d", fd);
654    return readObjectInternal(handle, writeToFd, NULL /* expected size */, &fd);
655}
656
657bool MtpDevice::readObjectInternal(MtpObjectHandle handle,
658                                   ReadObjectCallback callback,
659                                   const uint32_t* expectedLength,
660                                   void* clientData) {
661    Mutex::Autolock autoLock(mMutex);
662
663    mRequest.reset();
664    mRequest.setParameter(1, handle);
665    if (!sendRequest(MTP_OPERATION_GET_OBJECT)) {
666        ALOGE("Failed to send a read request.");
667        return false;
668    }
669
670    return readData(callback, expectedLength, nullptr, clientData);
671}
672
673bool MtpDevice::readData(ReadObjectCallback callback,
674                            const uint32_t* expectedLength,
675                            uint32_t* writtenSize,
676                            void* clientData) {
677    if (!mData.readDataHeader(mRequestIn1)) {
678        ALOGE("Failed to read header.");
679        return false;
680    }
681
682    // If object size 0 byte, the remote device can reply response packet
683    // without sending any data packets.
684    if (mData.getContainerType() == MTP_CONTAINER_TYPE_RESPONSE) {
685        mResponse.copyFrom(mData);
686        return mResponse.getResponseCode() == MTP_RESPONSE_OK;
687    }
688
689    const uint32_t fullLength = mData.getContainerLength();
690    if (fullLength < MTP_CONTAINER_HEADER_SIZE) {
691        ALOGE("fullLength is too short: %d", fullLength);
692        return false;
693    }
694    const uint32_t length = fullLength - MTP_CONTAINER_HEADER_SIZE;
695    if (expectedLength && length != *expectedLength) {
696        ALOGE("readObject error length: %d", fullLength);
697        return false;
698    }
699
700    uint32_t offset = 0;
701    bool writingError = false;
702
703    {
704        int initialDataLength = 0;
705        void* const initialData = mData.getData(&initialDataLength);
706        if (initialData) {
707            if (initialDataLength > 0) {
708                if (!callback(initialData, offset, initialDataLength, clientData)) {
709                    ALOGE("Failed to write initial data.");
710                    writingError = true;
711                }
712                offset += initialDataLength;
713            }
714            free(initialData);
715        }
716    }
717
718    // USB reads greater than 16K don't work.
719    char buffer1[MTP_BUFFER_SIZE], buffer2[MTP_BUFFER_SIZE];
720    mRequestIn1->buffer = buffer1;
721    mRequestIn2->buffer = buffer2;
722    struct usb_request* req = NULL;
723
724    while (offset < length) {
725        // Wait for previous read to complete.
726        void* writeBuffer = NULL;
727        int writeLength = 0;
728        if (req) {
729            const int read = mData.readDataWait(mDevice);
730            if (read < 0) {
731                ALOGE("readDataWait failed.");
732                return false;
733            }
734            writeBuffer = req->buffer;
735            writeLength = read;
736        }
737
738        // Request to read next chunk.
739        const uint32_t nextOffset = offset + writeLength;
740        if (nextOffset < length) {
741            // Queue up a read request.
742            const size_t remaining = length - nextOffset;
743            req = (req == mRequestIn1 ? mRequestIn2 : mRequestIn1);
744            req->buffer_length = remaining > MTP_BUFFER_SIZE ?
745                    static_cast<size_t>(MTP_BUFFER_SIZE) : remaining;
746            if (mData.readDataAsync(req) != 0) {
747                ALOGE("readDataAsync failed");
748                return false;
749            }
750        }
751
752        // Write previous buffer.
753        if (writeBuffer && !writingError) {
754            if (!callback(writeBuffer, offset, writeLength, clientData)) {
755                ALOGE("write failed");
756                writingError = true;
757            }
758        }
759        offset = nextOffset;
760    }
761
762    if (writtenSize) {
763        *writtenSize = length;
764    }
765
766    return readResponse() == MTP_RESPONSE_OK;
767}
768
769bool MtpDevice::readPartialObject(MtpObjectHandle handle,
770                                  uint32_t offset,
771                                  uint32_t size,
772                                  uint32_t *writtenSize,
773                                  ReadObjectCallback callback,
774                                  void* clientData) {
775    Mutex::Autolock autoLock(mMutex);
776
777    mRequest.reset();
778    mRequest.setParameter(1, handle);
779    mRequest.setParameter(2, offset);
780    mRequest.setParameter(3, size);
781    if (!sendRequest(MTP_OPERATION_GET_PARTIAL_OBJECT)) {
782        ALOGE("Failed to send a read request.");
783        return false;
784    }
785    // The expected size is null because it requires the exact number of bytes to read though
786    // MTP_OPERATION_GET_PARTIAL_OBJECT allows devices to return shorter length of bytes than
787    // requested. Destination's buffer length should be checked in |callback|.
788    return readData(callback, nullptr /* expected size */, writtenSize, clientData);
789}
790
791bool MtpDevice::readPartialObject64(MtpObjectHandle handle,
792                                    uint64_t offset,
793                                    uint32_t size,
794                                    uint32_t *writtenSize,
795                                    ReadObjectCallback callback,
796                                    void* clientData) {
797    Mutex::Autolock autoLock(mMutex);
798
799    mRequest.reset();
800    mRequest.setParameter(1, handle);
801    mRequest.setParameter(2, 0xffffffff & offset);
802    mRequest.setParameter(3, 0xffffffff & (offset >> 32));
803    mRequest.setParameter(4, size);
804    if (!sendRequest(MTP_OPERATION_GET_PARTIAL_OBJECT_64)) {
805        ALOGE("Failed to send a read request.");
806        return false;
807    }
808    // The expected size is null because it requires the exact number of bytes to read though
809    // MTP_OPERATION_GET_PARTIAL_OBJECT_64 allows devices to return shorter length of bytes than
810    // requested. Destination's buffer length should be checked in |callback|.
811    return readData(callback, nullptr /* expected size */, writtenSize, clientData);
812}
813
814bool MtpDevice::sendRequest(MtpOperationCode operation) {
815    ALOGV("sendRequest: %s\n", MtpDebug::getOperationCodeName(operation));
816    mReceivedResponse = false;
817    mRequest.setOperationCode(operation);
818    if (mTransactionID > 0)
819        mRequest.setTransactionID(mTransactionID++);
820    int ret = mRequest.write(mRequestOut);
821    mRequest.dump();
822    return (ret > 0);
823}
824
825bool MtpDevice::sendData() {
826    ALOGV("sendData\n");
827    mData.setOperationCode(mRequest.getOperationCode());
828    mData.setTransactionID(mRequest.getTransactionID());
829    int ret = mData.write(mRequestOut);
830    mData.dump();
831    return (ret >= 0);
832}
833
834bool MtpDevice::readData() {
835    mData.reset();
836    int ret = mData.read(mRequestIn1);
837    ALOGV("readData returned %d\n", ret);
838    if (ret >= MTP_CONTAINER_HEADER_SIZE) {
839        if (mData.getContainerType() == MTP_CONTAINER_TYPE_RESPONSE) {
840            ALOGD("got response packet instead of data packet");
841            // we got a response packet rather than data
842            // copy it to mResponse
843            mResponse.copyFrom(mData);
844            mReceivedResponse = true;
845            return false;
846        }
847        mData.dump();
848        return true;
849    }
850    else {
851        ALOGV("readResponse failed\n");
852        return false;
853    }
854}
855
856bool MtpDevice::writeDataHeader(MtpOperationCode operation, int dataLength) {
857    mData.setOperationCode(operation);
858    mData.setTransactionID(mRequest.getTransactionID());
859    return (!mData.writeDataHeader(mRequestOut, dataLength));
860}
861
862MtpResponseCode MtpDevice::readResponse() {
863    ALOGV("readResponse\n");
864    if (mReceivedResponse) {
865        mReceivedResponse = false;
866        return mResponse.getResponseCode();
867    }
868    int ret = mResponse.read(mRequestIn1);
869    // handle zero length packets, which might occur if the data transfer
870    // ends on a packet boundary
871    if (ret == 0)
872        ret = mResponse.read(mRequestIn1);
873    if (ret >= MTP_CONTAINER_HEADER_SIZE) {
874        mResponse.dump();
875        return mResponse.getResponseCode();
876    } else {
877        ALOGD("readResponse failed\n");
878        return -1;
879    }
880}
881
882int MtpDevice::submitEventRequest() {
883    if (mEventMutex.tryLock()) {
884        // An event is being reaped on another thread.
885        return -1;
886    }
887    if (mProcessingEvent) {
888        // An event request was submitted, but no reapEventRequest called so far.
889        return -1;
890    }
891    Mutex::Autolock autoLock(mEventMutexForInterrupt);
892    mEventPacket.sendRequest(mRequestIntr);
893    const int currentHandle = ++mCurrentEventHandle;
894    mProcessingEvent = true;
895    mEventMutex.unlock();
896    return currentHandle;
897}
898
899int MtpDevice::reapEventRequest(int handle, uint32_t (*parameters)[3]) {
900    Mutex::Autolock autoLock(mEventMutex);
901    if (!mProcessingEvent || mCurrentEventHandle != handle || !parameters) {
902        return -1;
903    }
904    mProcessingEvent = false;
905    const int readSize = mEventPacket.readResponse(mRequestIntr->dev);
906    const int result = mEventPacket.getEventCode();
907    // MTP event has three parameters.
908    (*parameters)[0] = mEventPacket.getParameter(1);
909    (*parameters)[1] = mEventPacket.getParameter(2);
910    (*parameters)[2] = mEventPacket.getParameter(3);
911    return readSize != 0 ? result : 0;
912}
913
914void MtpDevice::discardEventRequest(int handle) {
915    Mutex::Autolock autoLock(mEventMutexForInterrupt);
916    if (mCurrentEventHandle != handle) {
917        return;
918    }
919    usb_request_cancel(mRequestIntr);
920}
921
922}  // namespace android
923