blob: 5f17ff2ff4d950f8509f5f658430d03d42e28cd5 [file] [log] [blame]
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <algorithm>
18#include <android-base/logging.h>
19#include <android-base/properties.h>
20#include <chrono>
21#include <dirent.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <inttypes.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/types.h>
28#include <sys/stat.h>
29#include <sys/stat.h>
30#include <sys/time.h>
31
32#define LOG_TAG "MtpServer"
33
34#include "MtpDebug.h"
35#include "mtp_MtpDatabase.hpp"
36#include "MtpDescriptors.h"
37#include "MtpDevHandle.h"
38#include "MtpFfsCompatHandle.h"
39#include "MtpFfsHandle.h"
40#include "MtpObjectInfo.h"
41#include "MtpProperty.h"
42#include "MtpServer.h"
43#include "MtpStorage.h"
44#include "MtpStringBuffer.h"
45
46static const MtpOperationCode kSupportedOperationCodes[] = {
47 MTP_OPERATION_GET_DEVICE_INFO,
48 MTP_OPERATION_OPEN_SESSION,
49 MTP_OPERATION_CLOSE_SESSION,
50 MTP_OPERATION_GET_STORAGE_IDS,
51 MTP_OPERATION_GET_STORAGE_INFO,
52 MTP_OPERATION_GET_NUM_OBJECTS,
53 MTP_OPERATION_GET_OBJECT_HANDLES,
54 MTP_OPERATION_GET_OBJECT_INFO,
55 MTP_OPERATION_GET_OBJECT,
56 MTP_OPERATION_GET_THUMB,
57 MTP_OPERATION_DELETE_OBJECT,
58 MTP_OPERATION_SEND_OBJECT_INFO,
59 MTP_OPERATION_SEND_OBJECT,
60// MTP_OPERATION_INITIATE_CAPTURE,
61// MTP_OPERATION_FORMAT_STORE,
62 MTP_OPERATION_RESET_DEVICE,
63// MTP_OPERATION_SELF_TEST,
64// MTP_OPERATION_SET_OBJECT_PROTECTION,
65// MTP_OPERATION_POWER_DOWN,
66 MTP_OPERATION_GET_DEVICE_PROP_DESC,
67 MTP_OPERATION_GET_DEVICE_PROP_VALUE,
68 MTP_OPERATION_SET_DEVICE_PROP_VALUE,
69 MTP_OPERATION_RESET_DEVICE_PROP_VALUE,
70// MTP_OPERATION_TERMINATE_OPEN_CAPTURE,
71 MTP_OPERATION_MOVE_OBJECT,
72 MTP_OPERATION_COPY_OBJECT,
73 MTP_OPERATION_GET_PARTIAL_OBJECT,
74// MTP_OPERATION_INITIATE_OPEN_CAPTURE,
75 MTP_OPERATION_GET_OBJECT_PROPS_SUPPORTED,
76 MTP_OPERATION_GET_OBJECT_PROP_DESC,
77 MTP_OPERATION_GET_OBJECT_PROP_VALUE,
78 MTP_OPERATION_SET_OBJECT_PROP_VALUE,
79 MTP_OPERATION_GET_OBJECT_PROP_LIST,
80// MTP_OPERATION_SET_OBJECT_PROP_LIST,
81// MTP_OPERATION_GET_INTERDEPENDENT_PROP_DESC,
82// MTP_OPERATION_SEND_OBJECT_PROP_LIST,
83 MTP_OPERATION_GET_OBJECT_REFERENCES,
84 MTP_OPERATION_SET_OBJECT_REFERENCES,
85// MTP_OPERATION_SKIP,
86 // Android extension for direct file IO
87 MTP_OPERATION_GET_PARTIAL_OBJECT_64,
88 MTP_OPERATION_SEND_PARTIAL_OBJECT,
89 MTP_OPERATION_TRUNCATE_OBJECT,
90 MTP_OPERATION_BEGIN_EDIT_OBJECT,
91 MTP_OPERATION_END_EDIT_OBJECT,
92};
93
94static const MtpEventCode kSupportedEventCodes[] = {
95 MTP_EVENT_OBJECT_ADDED,
96 MTP_EVENT_OBJECT_REMOVED,
97 MTP_EVENT_STORE_ADDED,
98 MTP_EVENT_STORE_REMOVED,
99 MTP_EVENT_DEVICE_PROP_CHANGED,
100};
101
102MtpServer::MtpServer(IMtpDatabase* database, int controlFd, bool ptp,
103 const char *deviceInfoManufacturer,
104 const char *deviceInfoModel,
105 const char *deviceInfoDeviceVersion,
106 const char *deviceInfoSerialNumber)
107 : mDatabase(database),
108 mPtp(ptp),
109 mDeviceInfoManufacturer(deviceInfoManufacturer),
110 mDeviceInfoModel(deviceInfoModel),
111 mDeviceInfoDeviceVersion(deviceInfoDeviceVersion),
112 mDeviceInfoSerialNumber(deviceInfoSerialNumber),
113 mSessionID(0),
114 mSessionOpen(false),
115 mSendObjectHandle(kInvalidObjectHandle),
116 mSendObjectFormat(0),
117 mSendObjectFileSize(0),
118 mSendObjectModifiedTime(0)
119{
120 bool ffs_ok = access(FFS_MTP_EP0, W_OK) == 0;
121 if (ffs_ok) {
122 bool aio_compat = android::base::GetBoolProperty("sys.usb.ffs.aio_compat", false);
123 mHandle = aio_compat ? new MtpFfsCompatHandle(controlFd) : new MtpFfsHandle(controlFd);
124 mHandle->writeDescriptors(mPtp);
125 } else {
126 mHandle = new MtpDevHandle();
127 }
128}
129
130MtpServer::~MtpServer() {
131}
132
133void MtpServer::addStorage(MtpStorage* storage) {
134 std::lock_guard<std::mutex> lg(mMutex);
135 mDatabase->createDB(storage, storage->getStorageID());
136 mStorages.push_back(storage);
137 sendStoreAdded(storage->getStorageID());
138}
139
140void MtpServer::removeStorage(MtpStorage* storage) {
141 std::lock_guard<std::mutex> lg(mMutex);
142 auto iter = std::find(mStorages.begin(), mStorages.end(), storage);
143 if (iter != mStorages.end()) {
144 sendStoreRemoved(storage->getStorageID());
145 mStorages.erase(iter);
146 }
147}
148
149MtpStorage* MtpServer::getStorage(MtpStorageID id) {
150 if (id == 0)
151 return mStorages[0];
152 for (MtpStorage *storage : mStorages) {
153 if (storage->getStorageID() == id)
154 return storage;
155 }
156 return nullptr;
157}
158
159bool MtpServer::hasStorage(MtpStorageID id) {
160 if (id == 0 || id == 0xFFFFFFFF)
161 return mStorages.size() > 0;
162 return (getStorage(id) != nullptr);
163}
164
165void MtpServer::run() {
166 if (mHandle->start(mPtp)) {
167 MTPE("Failed to start usb driver!");
168 mHandle->close();
169 return;
170 }
171
172 while (1) {
173 int ret = mRequest.read(mHandle);
174 if (ret < 0) {
175 MTPE("request read returned %d, errno: %d", ret, errno);
176 if (errno == ECANCELED) {
177 // return to top of loop and wait for next command
178 continue;
179 }
180 break;
181 }
182 MtpOperationCode operation = mRequest.getOperationCode();
183 MtpTransactionID transaction = mRequest.getTransactionID();
184
185 MTPD("operation: %s\n", MtpDebug::getOperationCodeName(operation));
186 // FIXME need to generalize this
187 bool dataIn = (operation == MTP_OPERATION_SEND_OBJECT_INFO
188 || operation == MTP_OPERATION_SET_OBJECT_REFERENCES
189 || operation == MTP_OPERATION_SET_OBJECT_PROP_VALUE
190 || operation == MTP_OPERATION_SET_DEVICE_PROP_VALUE);
191 if (dataIn) {
192 int ret = mData.read(mHandle);
193 if (ret < 0) {
194 MTPE("data read returned %d, errno: %d", ret, errno);
195 if (errno == ECANCELED) {
196 // return to top of loop and wait for next command
197 continue;
198 }
199 break;
200 }
201 MTPD("received data:");
202 } else {
203 mData.reset();
204 }
205
206 if (handleRequest()) {
207 if (!dataIn && mData.hasData()) {
208 mData.setOperationCode(operation);
209 mData.setTransactionID(transaction);
210 MTPD("sending data:");
211 ret = mData.write(mHandle);
212 if (ret < 0) {
213 MTPE("request write returned %d, errno: %d", ret, errno);
214 if (errno == ECANCELED) {
215 // return to top of loop and wait for next command
216 continue;
217 }
218 break;
219 }
220 }
221
222 mResponse.setTransactionID(transaction);
223 MTPD("sending response %04X", mResponse.getResponseCode());
224 ret = mResponse.write(mHandle);
225 const int savedErrno = errno;
226 if (ret < 0) {
227 MTPE("request write returned %d, errno: %d", ret, errno);
228 if (savedErrno == ECANCELED) {
229 // return to top of loop and wait for next command
230 continue;
231 }
232 break;
233 }
234 } else {
235 MTPD("skipping response\n");
236 }
237 }
238
239 // commit any open edits
240 int count = mObjectEditList.size();
241 for (int i = 0; i < count; i++) {
242 ObjectEdit* edit = mObjectEditList[i];
243 commitEdit(edit);
244 delete edit;
245 }
246 mObjectEditList.clear();
247
248 mHandle->close();
249}
250
251void MtpServer::sendObjectAdded(MtpObjectHandle handle) {
252 MTPD("MtpServer::sendObjectAdded %d\n", handle);
253 sendEvent(MTP_EVENT_OBJECT_ADDED, handle);
254}
255
256void MtpServer::sendObjectRemoved(MtpObjectHandle handle) {
257 MTPD("MtpServer::sendObjectRemoved %d\n", handle);
258 sendEvent(MTP_EVENT_OBJECT_REMOVED, handle);
259}
260
261void MtpServer::sendStoreRemoved(MtpStorageID id) {
262 MTPD("MtpServer::sendStoreRemoved %08X\n", id);
263 sendEvent(MTP_EVENT_STORE_REMOVED, id);
264}
265
266void MtpServer::sendStoreAdded(MtpStorageID id) {
267 MTPD("MtpServer::sendStoreAdded %08X\n", id);
268 sendEvent(MTP_EVENT_STORE_ADDED, id);
269}
270
271void MtpServer::sendObjectUpdated(MtpObjectHandle handle) {
272 MTPD("MtpServer::sendObjectUpdated %d\n", handle);
273 sendEvent(MTP_EVENT_OBJECT_PROP_CHANGED, handle);
274}
275
276void MtpServer::sendDevicePropertyChanged(MtpDeviceProperty property) {
277 MTPD("MtpServer::sendDevicePropertyChanged %d\n", property);
278 sendEvent(MTP_EVENT_DEVICE_PROP_CHANGED, property);
279}
280
281void MtpServer::sendObjectInfoChanged(MtpObjectHandle handle) {
282 MTPD("MtpServer::sendObjectInfoChanged %d\n", handle);
283 sendEvent(MTP_EVENT_OBJECT_INFO_CHANGED, handle);
284}
285
286void MtpServer::sendEvent(MtpEventCode code, uint32_t param1) {
287 if (mSessionOpen) {
288 mEvent.setEventCode(code);
289 mEvent.setTransactionID(mRequest.getTransactionID());
290 mEvent.setParameter(1, param1);
291 if (mEvent.write(mHandle))
292 MTPE("Mtp send event failed: %s\n", strerror(errno));
293 }
294}
295
296void MtpServer::addEditObject(MtpObjectHandle handle, MtpStringBuffer& path,
297 uint64_t size, MtpObjectFormat format, int fd) {
298 ObjectEdit* edit = new ObjectEdit(handle, path, size, format, fd);
299 mObjectEditList.push_back(edit);
300}
301
302MtpServer::ObjectEdit* MtpServer::getEditObject(MtpObjectHandle handle) {
303 int count = mObjectEditList.size();
304 for (int i = 0; i < count; i++) {
305 ObjectEdit* edit = mObjectEditList[i];
306 if (edit->mHandle == handle) return edit;
307 }
308 return nullptr;
309}
310
311void MtpServer::removeEditObject(MtpObjectHandle handle) {
312 int count = mObjectEditList.size();
313 for (int i = 0; i < count; i++) {
314 ObjectEdit* edit = mObjectEditList[i];
315 if (edit->mHandle == handle) {
316 delete edit;
317 mObjectEditList.erase(mObjectEditList.begin() + i);
318 return;
319 }
320 }
321 MTPE("ObjectEdit not found in removeEditObject");
322}
323
324void MtpServer::commitEdit(ObjectEdit* edit) {
325 mDatabase->rescanFile((const char *)edit->mPath, edit->mHandle, edit->mFormat);
326}
327
328
329bool MtpServer::handleRequest() {
330 std::lock_guard<std::mutex> lg(mMutex);
331
332 MtpOperationCode operation = mRequest.getOperationCode();
333 MtpResponseCode response;
334
335 mResponse.reset();
336
337 if (mSendObjectHandle != kInvalidObjectHandle && operation != MTP_OPERATION_SEND_OBJECT) {
338 mSendObjectHandle = kInvalidObjectHandle;
339 mSendObjectFormat = 0;
340 mSendObjectModifiedTime = 0;
341 }
342
343 int containertype = mRequest.getContainerType();
344 if (containertype != MTP_CONTAINER_TYPE_COMMAND) {
345 MTPE("wrong container type %d", containertype);
346 return false;
347 }
348
349 MTPD("got command %s (%x)\n", MtpDebug::getOperationCodeName(operation), operation);
350
351 switch (operation) {
352 case MTP_OPERATION_GET_DEVICE_INFO:
353 response = doGetDeviceInfo();
354 break;
355 case MTP_OPERATION_OPEN_SESSION:
356 response = doOpenSession();
357 break;
358 case MTP_OPERATION_RESET_DEVICE:
359 case MTP_OPERATION_CLOSE_SESSION:
360 response = doCloseSession();
361 break;
362 case MTP_OPERATION_GET_STORAGE_IDS:
363 response = doGetStorageIDs();
364 break;
365 case MTP_OPERATION_GET_STORAGE_INFO:
366 response = doGetStorageInfo();
367 break;
368 case MTP_OPERATION_GET_OBJECT_PROPS_SUPPORTED:
369 response = doGetObjectPropsSupported();
370 break;
371 case MTP_OPERATION_GET_OBJECT_HANDLES:
372 response = doGetObjectHandles();
373 break;
374 case MTP_OPERATION_GET_NUM_OBJECTS:
375 response = doGetNumObjects();
376 break;
377 case MTP_OPERATION_GET_OBJECT_REFERENCES:
378 response = doGetObjectReferences();
379 break;
380 case MTP_OPERATION_SET_OBJECT_REFERENCES:
381 response = doSetObjectReferences();
382 break;
383 case MTP_OPERATION_GET_OBJECT_PROP_VALUE:
384 response = doGetObjectPropValue();
385 break;
386 case MTP_OPERATION_SET_OBJECT_PROP_VALUE:
387 response = doSetObjectPropValue();
388 break;
389 case MTP_OPERATION_GET_DEVICE_PROP_VALUE:
390 response = doGetDevicePropValue();
391 break;
392 case MTP_OPERATION_SET_DEVICE_PROP_VALUE:
393 response = doSetDevicePropValue();
394 break;
395 case MTP_OPERATION_RESET_DEVICE_PROP_VALUE:
396 response = doResetDevicePropValue();
397 break;
398 case MTP_OPERATION_GET_OBJECT_PROP_LIST:
399 response = doGetObjectPropList();
400 break;
401 case MTP_OPERATION_GET_OBJECT_INFO:
402 response = doGetObjectInfo();
403 break;
404 case MTP_OPERATION_GET_OBJECT:
405 response = doGetObject();
406 break;
407 case MTP_OPERATION_GET_THUMB:
408 response = doGetThumb();
409 break;
410 case MTP_OPERATION_GET_PARTIAL_OBJECT:
411 case MTP_OPERATION_GET_PARTIAL_OBJECT_64:
412 response = doGetPartialObject(operation);
413 break;
414 case MTP_OPERATION_SEND_OBJECT_INFO:
415 response = doSendObjectInfo();
416 break;
417 case MTP_OPERATION_SEND_OBJECT:
418 response = doSendObject();
419 break;
420 case MTP_OPERATION_DELETE_OBJECT:
421 response = doDeleteObject();
422 break;
423 case MTP_OPERATION_COPY_OBJECT:
424 response = doCopyObject();
425 break;
426 case MTP_OPERATION_MOVE_OBJECT:
427 response = doMoveObject();
428 break;
429 case MTP_OPERATION_GET_OBJECT_PROP_DESC:
430 response = doGetObjectPropDesc();
431 break;
432 case MTP_OPERATION_GET_DEVICE_PROP_DESC:
433 response = doGetDevicePropDesc();
434 break;
435 case MTP_OPERATION_SEND_PARTIAL_OBJECT:
436 response = doSendPartialObject();
437 break;
438 case MTP_OPERATION_TRUNCATE_OBJECT:
439 response = doTruncateObject();
440 break;
441 case MTP_OPERATION_BEGIN_EDIT_OBJECT:
442 response = doBeginEditObject();
443 break;
444 case MTP_OPERATION_END_EDIT_OBJECT:
445 response = doEndEditObject();
446 break;
447 default:
448 MTPE("got unsupported command %s (%x)",
449 MtpDebug::getOperationCodeName(operation), operation);
450 response = MTP_RESPONSE_OPERATION_NOT_SUPPORTED;
451 break;
452 }
453
454 if (response == MTP_RESPONSE_TRANSACTION_CANCELLED)
455 return false;
456 mResponse.setResponseCode(response);
457 return true;
458}
459
460MtpResponseCode MtpServer::doGetDeviceInfo() {
461 MtpStringBuffer string;
462
463 MtpObjectFormatList* playbackFormats = mDatabase->getSupportedPlaybackFormats();
464 MtpObjectFormatList* captureFormats = mDatabase->getSupportedCaptureFormats();
465 MtpDevicePropertyList* deviceProperties = mDatabase->getSupportedDeviceProperties();
466
467 // fill in device info
468 mData.putUInt16(MTP_STANDARD_VERSION);
469 if (mPtp) {
470 mData.putUInt32(0);
471 } else {
472 // MTP Vendor Extension ID
473 mData.putUInt32(6);
474 }
475 mData.putUInt16(MTP_STANDARD_VERSION);
476 if (mPtp) {
477 // no extensions
478 string.set("");
479 } else {
480 // MTP extensions
481 string.set("microsoft.com: 1.0; android.com: 1.0;");
482 }
483 mData.putString(string); // MTP Extensions
484 mData.putUInt16(0); //Functional Mode
485 mData.putAUInt16(kSupportedOperationCodes,
486 sizeof(kSupportedOperationCodes) / sizeof(uint16_t)); // Operations Supported
487 mData.putAUInt16(kSupportedEventCodes,
488 sizeof(kSupportedEventCodes) / sizeof(uint16_t)); // Events Supported
489 mData.putAUInt16(deviceProperties); // Device Properties Supported
490 mData.putAUInt16(captureFormats); // Capture Formats
491 mData.putAUInt16(playbackFormats); // Playback Formats
492
493 mData.putString(mDeviceInfoManufacturer); // Manufacturer
494 mData.putString(mDeviceInfoModel); // Model
495 mData.putString(mDeviceInfoDeviceVersion); // Device Version
496 mData.putString(mDeviceInfoSerialNumber); // Serial Number
497
498 delete playbackFormats;
499 delete captureFormats;
500 delete deviceProperties;
501
502 return MTP_RESPONSE_OK;
503}
504
505MtpResponseCode MtpServer::doOpenSession() {
506 if (mSessionOpen) {
507 mResponse.setParameter(1, mSessionID);
508 return MTP_RESPONSE_SESSION_ALREADY_OPEN;
509 }
510 if (mRequest.getParameterCount() < 1)
511 return MTP_RESPONSE_INVALID_PARAMETER;
512
513 mSessionID = mRequest.getParameter(1);
514 mSessionOpen = true;
515
516 return MTP_RESPONSE_OK;
517}
518
519MtpResponseCode MtpServer::doCloseSession() {
520 if (!mSessionOpen)
521 return MTP_RESPONSE_SESSION_NOT_OPEN;
522 mSessionID = 0;
523 mSessionOpen = false;
524 return MTP_RESPONSE_OK;
525}
526
527MtpResponseCode MtpServer::doGetStorageIDs() {
528 if (!mSessionOpen)
529 return MTP_RESPONSE_SESSION_NOT_OPEN;
530
531 int count = mStorages.size();
532 mData.putUInt32(count);
533 for (int i = 0; i < count; i++)
534 mData.putUInt32(mStorages[i]->getStorageID());
535
536 return MTP_RESPONSE_OK;
537}
538
539MtpResponseCode MtpServer::doGetStorageInfo() {
540 MtpStringBuffer string;
541
542 if (!mSessionOpen)
543 return MTP_RESPONSE_SESSION_NOT_OPEN;
544 if (mRequest.getParameterCount() < 1)
545 return MTP_RESPONSE_INVALID_PARAMETER;
546
547 MtpStorageID id = mRequest.getParameter(1);
548 MtpStorage* storage = getStorage(id);
549 if (!storage)
550 return MTP_RESPONSE_INVALID_STORAGE_ID;
551
552 mData.putUInt16(storage->getType());
553 mData.putUInt16(storage->getFileSystemType());
554 mData.putUInt16(storage->getAccessCapability());
555 mData.putUInt64(storage->getMaxCapacity());
556 mData.putUInt64(storage->getFreeSpace());
557 mData.putUInt32(1024*1024*1024); // Free Space in Objects
558 string.set(storage->getDescription());
559 mData.putString(string);
560 mData.putEmptyString(); // Volume Identifier
561
562 return MTP_RESPONSE_OK;
563}
564
565MtpResponseCode MtpServer::doGetObjectPropsSupported() {
566 if (!mSessionOpen)
567 return MTP_RESPONSE_SESSION_NOT_OPEN;
568 if (mRequest.getParameterCount() < 1)
569 return MTP_RESPONSE_INVALID_PARAMETER;
570 MtpObjectFormat format = mRequest.getParameter(1);
571 MtpObjectPropertyList* properties = mDatabase->getSupportedObjectProperties(format);
572 mData.putAUInt16(properties);
573 delete properties;
574 return MTP_RESPONSE_OK;
575}
576
577MtpResponseCode MtpServer::doGetObjectHandles() {
578 if (!mSessionOpen)
579 return MTP_RESPONSE_SESSION_NOT_OPEN;
580 if (mRequest.getParameterCount() < 3)
581 return MTP_RESPONSE_INVALID_PARAMETER;
582 MtpStorageID storageID = mRequest.getParameter(1); // 0xFFFFFFFF for all storage
583 MtpObjectFormat format = mRequest.getParameter(2); // 0 for all formats
584 MtpObjectHandle parent = mRequest.getParameter(3); // 0xFFFFFFFF for objects with no parent
585 // 0x00000000 for all objects
586
587 if (!hasStorage(storageID))
588 return MTP_RESPONSE_INVALID_STORAGE_ID;
589
590 MtpObjectHandleList* handles = mDatabase->getObjectList(storageID, format, parent);
591 if (handles == NULL)
592 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
593 mData.putAUInt32(handles);
594 delete handles;
595 return MTP_RESPONSE_OK;
596}
597
598MtpResponseCode MtpServer::doGetNumObjects() {
599 if (!mSessionOpen)
600 return MTP_RESPONSE_SESSION_NOT_OPEN;
601 if (mRequest.getParameterCount() < 3)
602 return MTP_RESPONSE_INVALID_PARAMETER;
603 MtpStorageID storageID = mRequest.getParameter(1); // 0xFFFFFFFF for all storage
604 MtpObjectFormat format = mRequest.getParameter(2); // 0 for all formats
605 MtpObjectHandle parent = mRequest.getParameter(3); // 0xFFFFFFFF for objects with no parent
606 // 0x00000000 for all objects
607 if (!hasStorage(storageID))
608 return MTP_RESPONSE_INVALID_STORAGE_ID;
609
610 int count = mDatabase->getNumObjects(storageID, format, parent);
611 if (count >= 0) {
612 mResponse.setParameter(1, count);
613 return MTP_RESPONSE_OK;
614 } else {
615 mResponse.setParameter(1, 0);
616 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
617 }
618}
619
620MtpResponseCode MtpServer::doGetObjectReferences() {
621 if (!mSessionOpen)
622 return MTP_RESPONSE_SESSION_NOT_OPEN;
623 if (!hasStorage())
624 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
625 if (mRequest.getParameterCount() < 1)
626 return MTP_RESPONSE_INVALID_PARAMETER;
627 MtpObjectHandle handle = mRequest.getParameter(1);
628
629 // FIXME - check for invalid object handle
630 MtpObjectHandleList* handles = mDatabase->getObjectReferences(handle);
631 if (handles) {
632 mData.putAUInt32(handles);
633 delete handles;
634 } else {
635 mData.putEmptyArray();
636 }
637 return MTP_RESPONSE_OK;
638}
639
640MtpResponseCode MtpServer::doSetObjectReferences() {
641 if (!mSessionOpen)
642 return MTP_RESPONSE_SESSION_NOT_OPEN;
643 if (!hasStorage())
644 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
645 if (mRequest.getParameterCount() < 1)
646 return MTP_RESPONSE_INVALID_PARAMETER;
647 MtpStorageID handle = mRequest.getParameter(1);
648
649 MtpObjectHandleList* references = mData.getAUInt32();
650 if (!references)
651 return MTP_RESPONSE_INVALID_PARAMETER;
652 MtpResponseCode result = mDatabase->setObjectReferences(handle, references);
653 delete references;
654 return result;
655}
656
657MtpResponseCode MtpServer::doGetObjectPropValue() {
658 if (!hasStorage())
659 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
660 if (mRequest.getParameterCount() < 2)
661 return MTP_RESPONSE_INVALID_PARAMETER;
662 MtpObjectHandle handle = mRequest.getParameter(1);
663 MtpObjectProperty property = mRequest.getParameter(2);
664 MTPD("GetObjectPropValue %d %s\n", handle,
665 MtpDebug::getObjectPropCodeName(property));
666
667 return mDatabase->getObjectPropertyValue(handle, property, mData);
668}
669
670MtpResponseCode MtpServer::doSetObjectPropValue() {
671 if (!hasStorage())
672 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
673 if (mRequest.getParameterCount() < 2)
674 return MTP_RESPONSE_INVALID_PARAMETER;
675 MtpObjectHandle handle = mRequest.getParameter(1);
676 MtpObjectProperty property = mRequest.getParameter(2);
677 MTPD("SetObjectPropValue %d %s\n", handle,
678 MtpDebug::getObjectPropCodeName(property));
679
680 return mDatabase->setObjectPropertyValue(handle, property, mData);
681}
682
683MtpResponseCode MtpServer::doGetDevicePropValue() {
684 if (mRequest.getParameterCount() < 1)
685 return MTP_RESPONSE_INVALID_PARAMETER;
686 MtpDeviceProperty property = mRequest.getParameter(1);
687 MTPD("GetDevicePropValue %s\n",
688 MtpDebug::getDevicePropCodeName(property));
689
690 return mDatabase->getDevicePropertyValue(property, mData);
691}
692
693MtpResponseCode MtpServer::doSetDevicePropValue() {
694 if (mRequest.getParameterCount() < 1)
695 return MTP_RESPONSE_INVALID_PARAMETER;
696 MtpDeviceProperty property = mRequest.getParameter(1);
697 MTPD("SetDevicePropValue %s\n",
698 MtpDebug::getDevicePropCodeName(property));
699
700 return mDatabase->setDevicePropertyValue(property, mData);
701}
702
703MtpResponseCode MtpServer::doResetDevicePropValue() {
704 if (mRequest.getParameterCount() < 1)
705 return MTP_RESPONSE_INVALID_PARAMETER;
706 MtpDeviceProperty property = mRequest.getParameter(1);
707 MTPD("ResetDevicePropValue %s\n",
708 MtpDebug::getDevicePropCodeName(property));
709
710 return mDatabase->resetDeviceProperty(property);
711}
712
713MtpResponseCode MtpServer::doGetObjectPropList() {
714 if (!hasStorage())
715 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
716 if (mRequest.getParameterCount() < 5)
717 return MTP_RESPONSE_INVALID_PARAMETER;
718
719 MtpObjectHandle handle = mRequest.getParameter(1);
720 // use uint32_t so we can support 0xFFFFFFFF
721 uint32_t format = mRequest.getParameter(2);
722 uint32_t property = mRequest.getParameter(3);
723 int groupCode = mRequest.getParameter(4);
724 int depth = mRequest.getParameter(5);
725 MTPD("GetObjectPropList %d format: %s property: %s group: %d depth: %d\n",
726 handle, MtpDebug::getFormatCodeName(format),
727 MtpDebug::getObjectPropCodeName(property), groupCode, depth);
728
729 return mDatabase->getObjectPropertyList(handle, format, property, groupCode, depth, mData);
730}
731
732MtpResponseCode MtpServer::doGetObjectInfo() {
733 if (!hasStorage())
734 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
735 if (mRequest.getParameterCount() < 1)
736 return MTP_RESPONSE_INVALID_PARAMETER;
737 MtpObjectHandle handle = mRequest.getParameter(1);
738 MtpObjectInfo info(handle);
739 MtpResponseCode result = mDatabase->getObjectInfo(handle, info);
740 if (result == MTP_RESPONSE_OK) {
741 char date[20];
742
743 mData.putUInt32(info.mStorageID);
744 mData.putUInt16(info.mFormat);
745 mData.putUInt16(info.mProtectionStatus);
746
747 // if object is being edited the database size may be out of date
748 uint32_t size = info.mCompressedSize;
749 ObjectEdit* edit = getEditObject(handle);
750 if (edit)
751 size = (edit->mSize > 0xFFFFFFFFLL ? 0xFFFFFFFF : (uint32_t)edit->mSize);
752 mData.putUInt32(size);
753
754 mData.putUInt16(info.mThumbFormat);
755 mData.putUInt32(info.mThumbCompressedSize);
756 mData.putUInt32(info.mThumbPixWidth);
757 mData.putUInt32(info.mThumbPixHeight);
758 mData.putUInt32(info.mImagePixWidth);
759 mData.putUInt32(info.mImagePixHeight);
760 mData.putUInt32(info.mImagePixDepth);
761 mData.putUInt32(info.mParent);
762 mData.putUInt16(info.mAssociationType);
763 mData.putUInt32(info.mAssociationDesc);
764 mData.putUInt32(info.mSequenceNumber);
765 mData.putString(info.mName);
766 formatDateTime(info.mDateCreated, date, sizeof(date));
767 mData.putString(date); // date created
768 formatDateTime(info.mDateModified, date, sizeof(date));
769 mData.putString(date); // date modified
770 mData.putEmptyString(); // keywords
771 }
772 return result;
773}
774
775MtpResponseCode MtpServer::doGetObject() {
776 if (!hasStorage())
777 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
778 if (mRequest.getParameterCount() < 1)
779 return MTP_RESPONSE_INVALID_PARAMETER;
780 MtpObjectHandle handle = mRequest.getParameter(1);
781 MtpStringBuffer pathBuf;
782 int64_t fileLength;
783 MtpObjectFormat format;
784 int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength, format);
785 if (result != MTP_RESPONSE_OK)
786 return result;
787
788 auto start = std::chrono::steady_clock::now();
789
790 const char* filePath = (const char *)pathBuf;
791 mtp_file_range mfr;
792 mfr.fd = open(filePath, O_RDONLY);
793 if (mfr.fd < 0) {
794 return MTP_RESPONSE_GENERAL_ERROR;
795 }
796 mfr.offset = 0;
797 mfr.length = fileLength;
798 mfr.command = mRequest.getOperationCode();
799 mfr.transaction_id = mRequest.getTransactionID();
800
801 // then transfer the file
802 int ret = mHandle->sendFile(mfr);
803 if (ret < 0) {
804 MTPE("Mtp send file got error %s", strerror(errno));
805 if (errno == ECANCELED) {
806 result = MTP_RESPONSE_TRANSACTION_CANCELLED;
807 } else {
808 result = MTP_RESPONSE_GENERAL_ERROR;
809 }
810 } else {
811 result = MTP_RESPONSE_OK;
812 }
813
814 auto end = std::chrono::steady_clock::now();
815 std::chrono::duration<double> diff = end - start;
816 struct stat sstat;
817 fstat(mfr.fd, &sstat);
818 uint64_t finalsize = sstat.st_size;
819 MTPD("Sent a file over MTP. Time: %f s, Size: %" PRIu64 ", Rate: %f bytes/s",
820 diff.count(), finalsize, ((double) finalsize) / diff.count());
821 closeObjFd(mfr.fd, filePath);
822 return result;
823}
824
825MtpResponseCode MtpServer::doGetThumb() {
826 if (mRequest.getParameterCount() < 1)
827 return MTP_RESPONSE_INVALID_PARAMETER;
828 MtpObjectHandle handle = mRequest.getParameter(1);
829 size_t thumbSize;
830 void* thumb = mDatabase->getThumbnail(handle, thumbSize);
831 if (thumb) {
832 // send data
833 mData.setOperationCode(mRequest.getOperationCode());
834 mData.setTransactionID(mRequest.getTransactionID());
835 mData.writeData(mHandle, thumb, thumbSize);
836 free(thumb);
837 return MTP_RESPONSE_OK;
838 } else {
839 return MTP_RESPONSE_GENERAL_ERROR;
840 }
841}
842
843MtpResponseCode MtpServer::doGetPartialObject(MtpOperationCode operation) {
844 if (!hasStorage())
845 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
846 MtpObjectHandle handle = mRequest.getParameter(1);
847 uint64_t offset;
848 uint32_t length;
849 offset = mRequest.getParameter(2);
850 if (operation == MTP_OPERATION_GET_PARTIAL_OBJECT_64) {
851 // MTP_OPERATION_GET_PARTIAL_OBJECT_64 takes 4 arguments
852 if (mRequest.getParameterCount() < 4)
853 return MTP_RESPONSE_INVALID_PARAMETER;
854
855 // android extension with 64 bit offset
856 uint64_t offset2 = mRequest.getParameter(3);
857 offset = offset | (offset2 << 32);
858 length = mRequest.getParameter(4);
859 } else {
860 // MTP_OPERATION_GET_PARTIAL_OBJECT takes 3 arguments
861 if (mRequest.getParameterCount() < 3)
862 return MTP_RESPONSE_INVALID_PARAMETER;
863
864 // standard GetPartialObject
865 length = mRequest.getParameter(3);
866 }
867 MtpStringBuffer pathBuf;
868 int64_t fileLength;
869 MtpObjectFormat format;
870 int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength, format);
871 if (result != MTP_RESPONSE_OK)
872 return result;
873 if (offset + length > (uint64_t)fileLength)
874 length = fileLength - offset;
875
876 const char* filePath = (const char *)pathBuf;
877 MTPD("sending partial %s\n %" PRIu64 " %" PRIu32, filePath, offset, length);
878 mtp_file_range mfr;
879 mfr.fd = open(filePath, O_RDONLY);
880 if (mfr.fd < 0) {
881 return MTP_RESPONSE_GENERAL_ERROR;
882 }
883 mfr.offset = offset;
884 mfr.length = length;
885 mfr.command = mRequest.getOperationCode();
886 mfr.transaction_id = mRequest.getTransactionID();
887 mResponse.setParameter(1, length);
888
889 // transfer the file
890 int ret = mHandle->sendFile(mfr);
891 MTPD("MTP_SEND_FILE_WITH_HEADER returned %d\n", ret);
892 result = MTP_RESPONSE_OK;
893 if (ret < 0) {
894 if (errno == ECANCELED)
895 result = MTP_RESPONSE_TRANSACTION_CANCELLED;
896 else
897 result = MTP_RESPONSE_GENERAL_ERROR;
898 }
899 closeObjFd(mfr.fd, filePath);
900 return result;
901}
902
903MtpResponseCode MtpServer::doSendObjectInfo() {
904 MtpStringBuffer path;
905 uint16_t temp16;
906 uint32_t temp32;
907
908 if (mRequest.getParameterCount() < 2)
909 return MTP_RESPONSE_INVALID_PARAMETER;
910 MtpStorageID storageID = mRequest.getParameter(1);
911 MtpStorage* storage = getStorage(storageID);
912 MtpObjectHandle parent = mRequest.getParameter(2);
913 if (!storage)
914 return MTP_RESPONSE_INVALID_STORAGE_ID;
915
916 // special case the root
917 if (parent == MTP_PARENT_ROOT) {
918 path.set(storage->getPath());
919 parent = 0;
920 } else {
921 int64_t length;
922 MtpObjectFormat format;
923 int result = mDatabase->getObjectFilePath(parent, path, length, format);
924 if (result != MTP_RESPONSE_OK)
925 return result;
926 if (format != MTP_FORMAT_ASSOCIATION)
927 return MTP_RESPONSE_INVALID_PARENT_OBJECT;
928 }
929
930 // read only the fields we need
931 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // storage ID
932 if (!mData.getUInt16(temp16)) return MTP_RESPONSE_INVALID_PARAMETER;
933 MtpObjectFormat format = temp16;
934 if (!mData.getUInt16(temp16)) return MTP_RESPONSE_INVALID_PARAMETER; // protection status
935 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER;
936 mSendObjectFileSize = temp32;
937 if (!mData.getUInt16(temp16)) return MTP_RESPONSE_INVALID_PARAMETER; // thumb format
938 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // thumb compressed size
939 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // thumb pix width
940 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // thumb pix height
941 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // image pix width
942 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // image pix height
943 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // image bit depth
944 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // parent
945 if (!mData.getUInt16(temp16)) return MTP_RESPONSE_INVALID_PARAMETER;
946 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER;
947 if (!mData.getUInt32(temp32)) return MTP_RESPONSE_INVALID_PARAMETER; // sequence number
948 MtpStringBuffer name, created, modified;
949 if (!mData.getString(name)) return MTP_RESPONSE_INVALID_PARAMETER; // file name
950 if (name.isEmpty()) {
951 MTPE("empty name");
952 return MTP_RESPONSE_INVALID_PARAMETER;
953 }
954 if (!mData.getString(created)) return MTP_RESPONSE_INVALID_PARAMETER; // date created
955 if (!mData.getString(modified)) return MTP_RESPONSE_INVALID_PARAMETER; // date modified
956 // keywords follow
957
958 MTPD("name: %s format: %04X\n", (const char *)name, format);
959 time_t modifiedTime;
960 if (!parseDateTime(modified, modifiedTime))
961 modifiedTime = 0;
962
963 if (path[path.size() - 1] != '/')
964 path.append("/");
965 path.append(name);
966
967 // check space first
968 if (mSendObjectFileSize > storage->getFreeSpace())
969 return MTP_RESPONSE_STORAGE_FULL;
970 uint64_t maxFileSize = storage->getMaxFileSize();
971 // check storage max file size
972 if (maxFileSize != 0) {
973 // if mSendObjectFileSize is 0xFFFFFFFF, then all we know is the file size
974 // is >= 0xFFFFFFFF
975 if (mSendObjectFileSize > maxFileSize || mSendObjectFileSize == 0xFFFFFFFF)
976 return MTP_RESPONSE_OBJECT_TOO_LARGE;
977 }
978
979 MTPD("path: %s parent: %d storageID: %08X", (const char*)path, parent, storageID);
980 uint64_t size = 0; // TODO: this needs to be implemented
981 time_t modified_time = 0; // TODO: this needs to be implemented
982 MtpObjectHandle handle = mDatabase->beginSendObject((const char*)path, format,
983 parent, storageID, size, modified_time);
984 if (handle == kInvalidObjectHandle) {
985 return MTP_RESPONSE_GENERAL_ERROR;
986 }
987
988 if (format == MTP_FORMAT_ASSOCIATION) {
989 int ret = makeFolder((const char *)path);
990 if (ret)
991 return MTP_RESPONSE_GENERAL_ERROR;
992
993 // SendObject does not get sent for directories, so call endSendObject here instead
994 mDatabase->endSendObject((const char*)path, handle, format, MTP_RESPONSE_OK);
995 }
996 mSendObjectFilePath = path;
997 // save the handle for the SendObject call, which should follow
998 mSendObjectHandle = handle;
999 mSendObjectFormat = format;
1000 mSendObjectModifiedTime = modifiedTime;
1001
1002 mResponse.setParameter(1, storageID);
1003 mResponse.setParameter(2, parent);
1004 mResponse.setParameter(3, handle);
1005
1006 return MTP_RESPONSE_OK;
1007}
1008
1009MtpResponseCode MtpServer::doMoveObject() {
1010 if (!hasStorage())
1011 return MTP_RESPONSE_GENERAL_ERROR;
1012 if (mRequest.getParameterCount() < 3)
1013 return MTP_RESPONSE_INVALID_PARAMETER;
1014 MtpObjectHandle objectHandle = mRequest.getParameter(1);
1015 MtpStorageID storageID = mRequest.getParameter(2);
1016 MtpStorage* storage = getStorage(storageID);
1017 MtpObjectHandle parent = mRequest.getParameter(3);
1018 if (!storage)
1019 return MTP_RESPONSE_INVALID_STORAGE_ID;
1020 MtpStringBuffer path;
1021 MtpResponseCode result;
1022
1023 MtpStringBuffer fromPath;
1024 int64_t fileLength;
1025 MtpObjectFormat format;
1026 MtpObjectInfo info(objectHandle);
1027 result = mDatabase->getObjectInfo(objectHandle, info);
1028 if (result != MTP_RESPONSE_OK)
1029 return result;
1030 result = mDatabase->getObjectFilePath(objectHandle, fromPath, fileLength, format);
1031 if (result != MTP_RESPONSE_OK)
1032 return result;
1033
1034 // special case the root
1035 if (parent == 0) {
1036 path.set(storage->getPath());
1037 } else {
1038 int64_t parentLength;
1039 MtpObjectFormat parentFormat;
1040 result = mDatabase->getObjectFilePath(parent, path, parentLength, parentFormat);
1041 if (result != MTP_RESPONSE_OK)
1042 return result;
1043 if (parentFormat != MTP_FORMAT_ASSOCIATION)
1044 return MTP_RESPONSE_INVALID_PARENT_OBJECT;
1045 }
1046
1047 if (path[path.size() - 1] != '/')
1048 path.append("/");
1049 path.append(info.mName);
1050
1051 result = mDatabase->beginMoveObject(objectHandle, parent, storageID);
1052 if (result != MTP_RESPONSE_OK)
1053 return result;
1054
1055 if (info.mStorageID == storageID) {
1056 MTPD("Moving file from %s to %s", (const char*)fromPath, (const char*)path);
1057 if (renameTo(fromPath, path)) {
1058 PLOG(ERROR) << "rename() failed from " << fromPath << " to " << path;
1059 result = MTP_RESPONSE_GENERAL_ERROR;
1060 }
1061 } else {
1062 MTPD("Moving across storages from %s to %s", (const char*)fromPath, (const char*)path);
1063 if (format == MTP_FORMAT_ASSOCIATION) {
1064 int ret = makeFolder((const char *)path);
1065 ret += copyRecursive(fromPath, path);
1066 if (ret) {
1067 result = MTP_RESPONSE_GENERAL_ERROR;
1068 } else {
1069 deletePath(fromPath);
1070 }
1071 } else {
1072 if (copyFile(fromPath, path)) {
1073 result = MTP_RESPONSE_GENERAL_ERROR;
1074 } else {
1075 deletePath(fromPath);
1076 }
1077 }
1078 }
1079
1080 // If the move failed, undo the database change
1081 mDatabase->endMoveObject(info.mParent, parent, info.mStorageID, storageID, objectHandle,
1082 result == MTP_RESPONSE_OK);
1083
1084 return result;
1085}
1086
1087MtpResponseCode MtpServer::doCopyObject() {
1088 if (!hasStorage())
1089 return MTP_RESPONSE_GENERAL_ERROR;
1090 MtpResponseCode result = MTP_RESPONSE_OK;
1091 if (mRequest.getParameterCount() < 3)
1092 return MTP_RESPONSE_INVALID_PARAMETER;
1093 MtpObjectHandle objectHandle = mRequest.getParameter(1);
1094 MtpStorageID storageID = mRequest.getParameter(2);
1095 MtpStorage* storage = getStorage(storageID);
1096 MtpObjectHandle parent = mRequest.getParameter(3);
1097 if (!storage)
1098 return MTP_RESPONSE_INVALID_STORAGE_ID;
1099 MtpStringBuffer path;
1100
1101 MtpStringBuffer fromPath;
1102 int64_t fileLength;
1103 MtpObjectFormat format;
1104 MtpObjectInfo info(objectHandle);
1105 result = mDatabase->getObjectInfo(objectHandle, info);
1106 if (result != MTP_RESPONSE_OK)
1107 return result;
1108 result = mDatabase->getObjectFilePath(objectHandle, fromPath, fileLength, format);
1109 if (result != MTP_RESPONSE_OK)
1110 return result;
1111
1112 // special case the root
1113 if (parent == 0) {
1114 path.set(storage->getPath());
1115 } else {
1116 int64_t parentLength;
1117 MtpObjectFormat parentFormat;
1118 result = mDatabase->getObjectFilePath(parent, path, parentLength, parentFormat);
1119 if (result != MTP_RESPONSE_OK)
1120 return result;
1121 if (parentFormat != MTP_FORMAT_ASSOCIATION)
1122 return MTP_RESPONSE_INVALID_PARENT_OBJECT;
1123 }
1124
1125 // check space first
1126 if ((uint64_t) fileLength > storage->getFreeSpace())
1127 return MTP_RESPONSE_STORAGE_FULL;
1128
1129 if (path[path.size() - 1] != '/')
1130 path.append("/");
1131 path.append(info.mName);
1132
1133 MtpObjectHandle handle = mDatabase->beginCopyObject(objectHandle, parent, storageID);
1134 if (handle == kInvalidObjectHandle) {
1135 return MTP_RESPONSE_GENERAL_ERROR;
1136 }
1137
1138 MTPD("Copying file from %s to %s", (const char*)fromPath, (const char*)path);
1139 if (format == MTP_FORMAT_ASSOCIATION) {
1140 int ret = makeFolder((const char *)path);
1141 ret += copyRecursive(fromPath, path);
1142 if (ret) {
1143 result = MTP_RESPONSE_GENERAL_ERROR;
1144 }
1145 } else {
1146 if (copyFile(fromPath, path)) {
1147 result = MTP_RESPONSE_GENERAL_ERROR;
1148 }
1149 }
1150
1151 mDatabase->endCopyObject(handle, result);
1152 mResponse.setParameter(1, handle);
1153 return result;
1154}
1155
1156MtpResponseCode MtpServer::doSendObject() {
1157 if (!hasStorage())
1158 return MTP_RESPONSE_GENERAL_ERROR;
1159 MtpResponseCode result = MTP_RESPONSE_OK;
1160 mode_t mask;
1161 int ret, initialData;
1162 bool isCanceled = false;
1163 struct stat sstat = {};
1164
1165 auto start = std::chrono::steady_clock::now();
1166
1167 if (mSendObjectHandle == kInvalidObjectHandle) {
1168 MTPE("Expected SendObjectInfo before SendObject");
1169 result = MTP_RESPONSE_NO_VALID_OBJECT_INFO;
1170 goto done;
1171 }
1172
1173 // read the header, and possibly some data
1174 ret = mData.read(mHandle);
1175 if (ret < MTP_CONTAINER_HEADER_SIZE) {
1176 result = MTP_RESPONSE_GENERAL_ERROR;
1177 goto done;
1178 }
1179 initialData = ret - MTP_CONTAINER_HEADER_SIZE;
1180
1181 if (mSendObjectFormat == MTP_FORMAT_ASSOCIATION) {
1182 if (initialData != 0)
1183 MTPE("Expected folder size to be 0!");
1184 mSendObjectHandle = kInvalidObjectHandle;
1185 mSendObjectFormat = 0;
1186 mSendObjectModifiedTime = 0;
1187 return result;
1188 }
1189
1190 mtp_file_range mfr;
1191 mfr.fd = open(mSendObjectFilePath, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
1192 if (mfr.fd < 0) {
1193 result = MTP_RESPONSE_GENERAL_ERROR;
1194 goto done;
1195 }
1196 fchown(mfr.fd, getuid(), FILE_GROUP);
1197 // set permissions
1198 mask = umask(0);
1199 fchmod(mfr.fd, FILE_PERM);
1200 umask(mask);
1201
1202 if (initialData > 0) {
1203 ret = write(mfr.fd, mData.getData(), initialData);
1204 }
1205
1206 if (ret < 0) {
1207 MTPE("failed to write initial data");
1208 result = MTP_RESPONSE_GENERAL_ERROR;
1209 } else {
1210 mfr.offset = initialData;
1211 if (mSendObjectFileSize == 0xFFFFFFFF) {
1212 // tell driver to read until it receives a short packet
1213 mfr.length = 0xFFFFFFFF;
1214 } else {
1215 mfr.length = mSendObjectFileSize - initialData;
1216 }
1217
1218 mfr.command = 0;
1219 mfr.transaction_id = 0;
1220
1221 // transfer the file
1222 ret = mHandle->receiveFile(mfr, mfr.length == 0 &&
1223 initialData == MTP_BUFFER_SIZE - MTP_CONTAINER_HEADER_SIZE);
1224 if ((ret < 0) && (errno == ECANCELED)) {
1225 isCanceled = true;
1226 }
1227 }
1228
1229 if (mSendObjectModifiedTime) {
1230 struct timespec newTime[2];
1231 newTime[0].tv_nsec = UTIME_NOW;
1232 newTime[1].tv_sec = mSendObjectModifiedTime;
1233 newTime[1].tv_nsec = 0;
1234 if (futimens(mfr.fd, newTime) < 0) {
1235 MTPE("changing modified time failed, %s", strerror(errno));
1236 }
1237 }
1238
1239 fstat(mfr.fd, &sstat);
1240 closeObjFd(mfr.fd, mSendObjectFilePath);
1241
1242 if (ret < 0) {
1243 MTPE("Mtp receive file got error %s", strerror(errno));
1244 unlink(mSendObjectFilePath);
1245 if (isCanceled)
1246 result = MTP_RESPONSE_TRANSACTION_CANCELLED;
1247 else
1248 result = MTP_RESPONSE_GENERAL_ERROR;
1249 }
1250
1251done:
1252 // reset so we don't attempt to send the data back
1253 mData.reset();
1254
1255 mDatabase->endSendObject(mSendObjectFilePath, mSendObjectHandle, mSendObjectFormat, result == MTP_RESPONSE_OK);
1256 mSendObjectHandle = kInvalidObjectHandle;
1257 mSendObjectFormat = 0;
1258 mSendObjectModifiedTime = 0;
1259
1260 auto end = std::chrono::steady_clock::now();
1261 std::chrono::duration<double> diff = end - start;
1262 uint64_t finalsize = sstat.st_size;
1263 MTPD("Got a file over MTP. Time: %fs, Size: %" PRIu64 ", Rate: %f bytes/s",
1264 diff.count(), finalsize, ((double) finalsize) / diff.count());
1265 return result;
1266}
1267
1268MtpResponseCode MtpServer::doDeleteObject() {
1269 MTPD("In MtpServer::doDeleteObject\n");
1270 if (!hasStorage())
1271 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
1272 if (mRequest.getParameterCount() < 1)
1273 return MTP_RESPONSE_INVALID_PARAMETER;
1274 MtpObjectHandle handle = mRequest.getParameter(1);
1275 MtpObjectFormat format;
1276 // FIXME - support deleting all objects if handle is 0xFFFFFFFF
1277 // FIXME - implement deleting objects by format
1278
1279 MtpStringBuffer filePath;
1280 int64_t fileLength;
1281 int result = mDatabase->getObjectFilePath(handle, filePath, fileLength, format);
1282 if (result != MTP_RESPONSE_OK)
1283 return result;
1284
1285 // Don't delete the actual files unless the database deletion is allowed
1286 result = mDatabase->beginDeleteObject(handle);
1287 if (result != MTP_RESPONSE_OK)
1288 return result;
1289
1290 bool success = deletePath((const char *)filePath);
1291
1292 mDatabase->endDeleteObject(handle, success);
1293 return success ? result : MTP_RESPONSE_PARTIAL_DELETION;
1294}
1295
1296MtpResponseCode MtpServer::doGetObjectPropDesc() {
1297 if (mRequest.getParameterCount() < 2)
1298 return MTP_RESPONSE_INVALID_PARAMETER;
1299 MtpObjectProperty propCode = mRequest.getParameter(1);
1300 MtpObjectFormat format = mRequest.getParameter(2);
1301 MTPD("GetObjectPropDesc %s %s\n", MtpDebug::getObjectPropCodeName(propCode),
1302 MtpDebug::getFormatCodeName(format));
1303 MtpProperty* property = mDatabase->getObjectPropertyDesc(propCode, format);
1304 if (!property)
1305 return MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
1306 property->write(mData);
1307 delete property;
1308 return MTP_RESPONSE_OK;
1309}
1310
1311MtpResponseCode MtpServer::doGetDevicePropDesc() {
1312 if (mRequest.getParameterCount() < 1)
1313 return MTP_RESPONSE_INVALID_PARAMETER;
1314 MtpDeviceProperty propCode = mRequest.getParameter(1);
1315 MTPD("GetDevicePropDesc %s\n", MtpDebug::getDevicePropCodeName(propCode));
1316 MtpProperty* property = mDatabase->getDevicePropertyDesc(propCode);
1317 if (!property)
1318 return MTP_RESPONSE_DEVICE_PROP_NOT_SUPPORTED;
1319 property->write(mData);
1320 delete property;
1321 return MTP_RESPONSE_OK;
1322}
1323
1324MtpResponseCode MtpServer::doSendPartialObject() {
1325 if (!hasStorage())
1326 return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
1327 if (mRequest.getParameterCount() < 4)
1328 return MTP_RESPONSE_INVALID_PARAMETER;
1329 MtpObjectHandle handle = mRequest.getParameter(1);
1330 uint64_t offset = mRequest.getParameter(2);
1331 uint64_t offset2 = mRequest.getParameter(3);
1332 offset = offset | (offset2 << 32);
1333 uint32_t length = mRequest.getParameter(4);
1334
1335 ObjectEdit* edit = getEditObject(handle);
1336 if (!edit) {
1337 MTPE("object not open for edit in doSendPartialObject");
1338 return MTP_RESPONSE_GENERAL_ERROR;
1339 }
1340
1341 // can't start writing past the end of the file
1342 if (offset > edit->mSize) {
1343 MTPD("writing past end of object, offset: %" PRIu64 ", edit->mSize: %" PRIu64,
1344 offset, edit->mSize);
1345 return MTP_RESPONSE_GENERAL_ERROR;
1346 }
1347
1348 const char* filePath = (const char *)edit->mPath;
1349 MTPD("receiving partial %s %" PRIu64 " %" PRIu32, filePath, offset, length);
1350
1351 // read the header, and possibly some data
1352 int ret = mData.read(mHandle);
1353 if (ret < MTP_CONTAINER_HEADER_SIZE)
1354 return MTP_RESPONSE_GENERAL_ERROR;
1355 int initialData = ret - MTP_CONTAINER_HEADER_SIZE;
1356
1357 if (initialData > 0) {
1358 ret = pwrite(edit->mFD, mData.getData(), initialData, offset);
1359 offset += initialData;
1360 length -= initialData;
1361 }
1362
1363 bool isCanceled = false;
1364 if (ret < 0) {
1365 MTPE("failed to write initial data");
1366 } else {
1367 mtp_file_range mfr;
1368 mfr.fd = edit->mFD;
1369 mfr.offset = offset;
1370 mfr.length = length;
1371 mfr.command = 0;
1372 mfr.transaction_id = 0;
1373
1374 // transfer the file
1375 ret = mHandle->receiveFile(mfr, mfr.length == 0 &&
1376 initialData == MTP_BUFFER_SIZE - MTP_CONTAINER_HEADER_SIZE);
1377 if ((ret < 0) && (errno == ECANCELED)) {
1378 isCanceled = true;
1379 }
1380 }
1381 if (ret < 0) {
1382 mResponse.setParameter(1, 0);
1383 if (isCanceled)
1384 return MTP_RESPONSE_TRANSACTION_CANCELLED;
1385 else
1386 return MTP_RESPONSE_GENERAL_ERROR;
1387 }
1388
1389 // reset so we don't attempt to send this back
1390 mData.reset();
1391 mResponse.setParameter(1, length);
1392 uint64_t end = offset + length;
1393 if (end > edit->mSize) {
1394 edit->mSize = end;
1395 }
1396 return MTP_RESPONSE_OK;
1397}
1398
1399MtpResponseCode MtpServer::doTruncateObject() {
1400 if (mRequest.getParameterCount() < 3)
1401 return MTP_RESPONSE_INVALID_PARAMETER;
1402 MtpObjectHandle handle = mRequest.getParameter(1);
1403 ObjectEdit* edit = getEditObject(handle);
1404 if (!edit) {
1405 MTPE("object not open for edit in doTruncateObject");
1406 return MTP_RESPONSE_GENERAL_ERROR;
1407 }
1408
1409 uint64_t offset = mRequest.getParameter(2);
1410 uint64_t offset2 = mRequest.getParameter(3);
1411 offset |= (offset2 << 32);
1412 if (ftruncate(edit->mFD, offset) != 0) {
1413 return MTP_RESPONSE_GENERAL_ERROR;
1414 } else {
1415 edit->mSize = offset;
1416 return MTP_RESPONSE_OK;
1417 }
1418}
1419
1420MtpResponseCode MtpServer::doBeginEditObject() {
1421 if (mRequest.getParameterCount() < 1)
1422 return MTP_RESPONSE_INVALID_PARAMETER;
1423 MtpObjectHandle handle = mRequest.getParameter(1);
1424 if (getEditObject(handle)) {
1425 MTPE("object already open for edit in doBeginEditObject");
1426 return MTP_RESPONSE_GENERAL_ERROR;
1427 }
1428
1429 MtpStringBuffer path;
1430 int64_t fileLength;
1431 MtpObjectFormat format;
1432 int result = mDatabase->getObjectFilePath(handle, path, fileLength, format);
1433 if (result != MTP_RESPONSE_OK)
1434 return result;
1435
1436 int fd = open((const char *)path, O_RDWR | O_EXCL);
1437 if (fd < 0) {
1438 MTPE("open failed for %s in doBeginEditObject (%d)", (const char *)path, errno);
1439 return MTP_RESPONSE_GENERAL_ERROR;
1440 }
1441
1442 addEditObject(handle, path, fileLength, format, fd);
1443 return MTP_RESPONSE_OK;
1444}
1445
1446MtpResponseCode MtpServer::doEndEditObject() {
1447 if (mRequest.getParameterCount() < 1)
1448 return MTP_RESPONSE_INVALID_PARAMETER;
1449 MtpObjectHandle handle = mRequest.getParameter(1);
1450 ObjectEdit* edit = getEditObject(handle);
1451 if (!edit) {
1452 MTPE("object not open for edit in doEndEditObject");
1453 return MTP_RESPONSE_GENERAL_ERROR;
1454 }
1455
1456 commitEdit(edit);
1457 removeEditObject(handle);
1458 return MTP_RESPONSE_OK;
1459}