MtpDevice.cpp 31 KB

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