MTP: Improve argument checking in SendObjectInfo

In particular, make sure the parent is a folder and make sure file
does not already exist.

Change-Id: Ifa870faba3285f03a92025d9e82f93fed78a761c
Signed-off-by: Mike Lockwood <lockwood@android.com>
diff --git a/media/mtp/MtpServer.cpp b/media/mtp/MtpServer.cpp
index 5c1e02a..d65845d 100644
--- a/media/mtp/MtpServer.cpp
+++ b/media/mtp/MtpServer.cpp
@@ -112,8 +112,10 @@
 }
 
 MtpStorage* MtpServer::getStorage(MtpStorageID id) {
+    if (id == 0)
+        return mStorages[0];
     for (int i = 0; i < mStorages.size(); i++) {
-        MtpStorage* storage =  mStorages[i];
+        MtpStorage* storage = mStorages[i];
         if (storage->getStorageID() == id)
             return storage;
     }
@@ -557,7 +559,8 @@
     MtpObjectHandle handle = mRequest.getParameter(1);
     MtpString pathBuf;
     int64_t fileLength;
-    int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength);
+    MtpObjectFormat format;
+    int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength, format);
     if (result != MTP_RESPONSE_OK)
         return result;
 
@@ -593,7 +596,8 @@
     uint32_t length = mRequest.getParameter(3);
     MtpString pathBuf;
     int64_t fileLength;
-    int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength);
+    MtpObjectFormat format;
+    int result = mDatabase->getObjectFilePath(handle, pathBuf, fileLength, format);
     if (result != MTP_RESPONSE_OK)
         return result;
     if (offset + length > fileLength)
@@ -639,10 +643,13 @@
         path = storage->getPath();
         parent = 0;
     } else {
-        int64_t dummy;
-        int result = mDatabase->getObjectFilePath(parent, path, dummy);
+        int64_t length;
+        MtpObjectFormat format;
+        int result = mDatabase->getObjectFilePath(parent, path, length, format);
         if (result != MTP_RESPONSE_OK)
             return result;
+        if (format != MTP_FORMAT_ASSOCIATION)
+            return MTP_RESPONSE_INVALID_PARENT_OBJECT;
     }
 
     // read only the fields we need
@@ -676,6 +683,10 @@
         path += "/";
     path += (const char *)name;
 
+    // file should not already exist
+    if (access(path, R_OK) == 0)
+        return MTP_RESPONSE_GENERAL_ERROR;
+
     MtpObjectHandle handle = mDatabase->beginSendObject((const char*)path,
             format, parent, storageID, mSendObjectFileSize, modifiedTime);
     if (handle == kInvalidObjectHandle) {
@@ -835,7 +846,7 @@
 
     MtpString filePath;
     int64_t fileLength;
-    int result = mDatabase->getObjectFilePath(handle, filePath, fileLength);
+    int result = mDatabase->getObjectFilePath(handle, filePath, fileLength, format);
     if (result == MTP_RESPONSE_OK) {
         LOGV("deleting %s", (const char *)filePath);
         deletePath((const char *)filePath);