Add NTFS support in vold

This CR, when paired with a functional NTFS implementation and the
corresponding SEPolicy updates, will allow NTFS USB drives to be mounted
on Android.

Bug: 254407246

Test: Extensive testing with an ADT-4 and NTFS USB drives.

Merged-In: If4197c4c588866c611cd6ba3483707d3cb0e0cf8
Change-Id: If4197c4c588866c611cd6ba3483707d3cb0e0cf8
diff --git a/Android.bp b/Android.bp
index 1ccfc09..8f5cae3 100644
--- a/Android.bp
+++ b/Android.bp
@@ -138,6 +138,7 @@
         "fs/Ext4.cpp",
         "fs/F2fs.cpp",
         "fs/Vfat.cpp",
+        "fs/Ntfs.cpp",
         "model/Disk.cpp",
         "model/EmulatedVolume.cpp",
         "model/ObbVolume.cpp",
diff --git a/fs/Ntfs.cpp b/fs/Ntfs.cpp
new file mode 100644
index 0000000..6f57693
--- /dev/null
+++ b/fs/Ntfs.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <linux/fs.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <linux/kdev_t.h>
+
+#define LOG_TAG "Vold"
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <cutils/log.h>
+#include <cutils/properties.h>
+#include <selinux/selinux.h>
+
+#include <logwrap/logwrap.h>
+
+#include "Ntfs.h"
+#include "Utils.h"
+#include "VoldUtil.h"
+
+using android::base::StringPrintf;
+
+namespace android {
+namespace vold {
+namespace ntfs {
+
+static const char* kFsckPath = "/system/bin/ntfsfix";
+static const char* kMkfsPath = "/system/bin/mkntfs";
+
+static const char* fsName = "ntfs3";
+
+bool IsSupported() {
+    return access(kFsckPath, X_OK) == 0 && access(kMkfsPath, X_OK) == 0 &&
+           IsFilesystemSupported(fsName);
+}
+
+status_t Check(const std::string& source) {
+    std::vector<std::string> cmd;
+    cmd.push_back(kFsckPath);
+
+    // ntfsfix sets the dirty bit by default, which prevents mounting the drive.
+    // -d tells it to instead reset the dirty bit. Technically, this could be dangerous,
+    // but since ntfsfix should report any errors with the drive and separately return
+    // a failed check, this should be relatively safe.
+    cmd.push_back("-d");
+
+    cmd.push_back(source);
+
+    int rc = ForkExecvpTimeout(cmd, kUntrustedFsckSleepTime, sFsckUntrustedContext);
+    if (rc == 0) {
+        LOG(INFO) << "Check NTFS OK";
+        return 0;
+    } else {
+        LOG(ERROR) << "Check NTFS failed (code " << rc << ")";
+        errno = EIO;
+        return -1;
+    }
+}
+
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+               bool executable, int ownerUid, int ownerGid, int permMask) {
+    unsigned long flags = MS_NODEV | MS_NOSUID | MS_DIRSYNC | MS_NOATIME;
+
+    flags |= (executable ? 0 : MS_NOEXEC);
+    flags |= (ro ? MS_RDONLY : 0);
+    flags |= (remount ? MS_REMOUNT : 0);
+
+    // Android mount does not support "utf8" as an option. We use the deprecated iocharset instead.
+    auto mountData = android::base::StringPrintf("uid=%d,gid=%d,fmask=%o,dmask=%o,iocharset=%s",
+                                                 ownerUid, ownerGid, permMask, permMask, "utf8");
+
+    int rc = mount(source.c_str(), target.c_str(), fsName, flags, mountData.c_str());
+
+    if (rc && errno == EROFS) {
+        LOG(ERROR) << source << " appears to be a read only filesystem - retrying mount RO";
+        flags |= MS_RDONLY;
+        rc = mount(source.c_str(), target.c_str(), fsName, flags, mountData.c_str());
+    }
+
+    return rc;
+}
+
+status_t Format(const std::string& source, unsigned int numSectors) {
+    std::vector<std::string> cmd;
+    cmd.push_back(kMkfsPath);
+    cmd.push_back(source);
+
+    if (numSectors) {
+        cmd.push_back(StringPrintf("%u", numSectors));
+    }
+
+    int rc = ForkExecvp(cmd);
+    if (rc == 0) {
+        LOG(INFO) << "Filesystem formatted OK";
+        return 0;
+    } else {
+        LOG(ERROR) << "Format failed with error code: " << rc;
+        errno = EIO;
+        return -1;
+    }
+    return 0;
+}
+
+}  // namespace ntfs
+}  // namespace vold
+}  // namespace android
\ No newline at end of file
diff --git a/fs/Ntfs.h b/fs/Ntfs.h
new file mode 100644
index 0000000..0049490
--- /dev/null
+++ b/fs/Ntfs.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_VOLD_NTFS_H
+#define ANDROID_VOLD_NTFS_H
+
+#include <utils/Errors.h>
+
+#include <string>
+
+namespace android {
+namespace vold {
+namespace ntfs {
+
+bool IsSupported();
+
+status_t Check(const std::string& source);
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+               bool executable, int ownerUid, int ownerGid, int permMask);
+status_t Format(const std::string& source, unsigned int numSectors);
+
+}  // namespace ntfs
+}  // namespace vold
+}  // namespace android
+
+#endif
\ No newline at end of file
diff --git a/main.cpp b/main.cpp
index b07ee68..50a02ae 100644
--- a/main.cpp
+++ b/main.cpp
@@ -74,7 +74,8 @@
     LOG(DEBUG) << "Detected support for:"
                << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "")
                << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "")
-               << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : "");
+               << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : "")
+               << (android::vold::IsFilesystemSupported("ntfs3") ? " ntfs3" : "");
 
     VolumeManager* vm;
     NetlinkManager* nm;
diff --git a/model/PublicVolume.cpp b/model/PublicVolume.cpp
index bf54c95..20015af 100644
--- a/model/PublicVolume.cpp
+++ b/model/PublicVolume.cpp
@@ -20,6 +20,7 @@
 #include "Utils.h"
 #include "VolumeManager.h"
 #include "fs/Exfat.h"
+#include "fs/Ntfs.h"
 #include "fs/Vfat.h"
 
 #include <android-base/logging.h>
@@ -110,6 +111,11 @@
             LOG(ERROR) << getId() << " failed filesystem check";
             return -EIO;
         }
+    } else if (mFsType == "ntfs" && ntfs::IsSupported()) {
+        if (ntfs::Check(mDevPath)) {
+            LOG(ERROR) << getId() << " failed filesystem check";
+            return -EIO;
+        }
     } else {
         LOG(ERROR) << getId() << " unsupported filesystem " << mFsType;
         return -EIO;
@@ -152,6 +158,12 @@
             PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
             return -EIO;
         }
+    } else if (mFsType == "ntfs") {
+        if (ntfs::Mount(mDevPath, mRawPath, false, false, false, AID_ROOT,
+                        (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007)) {
+            PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
+            return -EIO;
+        }
     }
 
     if (getMountFlags() & MountFlags::kPrimary) {
@@ -308,12 +320,15 @@
 }
 
 status_t PublicVolume::doFormat(const std::string& fsType) {
-    bool useVfat = vfat::IsSupported();
-    bool useExfat = exfat::IsSupported();
+    bool isVfatSup = vfat::IsSupported();
+    bool isExfatSup = exfat::IsSupported();
+    bool isNtfsSup = ntfs::IsSupported();
     status_t res = OK;
 
-    // Resolve the target filesystem type
-    if (fsType == "auto" && useVfat && useExfat) {
+    enum { NONE, VFAT, EXFAT, NTFS } fsPick = NONE;
+
+    // Resolve auto requests
+    if (fsType == "auto" && isVfatSup && isExfatSup) {
         uint64_t size = 0;
 
         res = GetBlockDevSize(mDevPath, &size);
@@ -324,29 +339,38 @@
 
         // If both vfat & exfat are supported use exfat for SDXC (>~32GiB) cards
         if (size > 32896LL * 1024 * 1024) {
-            useVfat = false;
+            fsPick = EXFAT;
         } else {
-            useExfat = false;
+            fsPick = VFAT;
         }
-    } else if (fsType == "vfat") {
-        useExfat = false;
-    } else if (fsType == "exfat") {
-        useVfat = false;
+    } else if (fsType == "auto" && isExfatSup) {
+        fsPick = EXFAT;
+    } else if (fsType == "auto" && isVfatSup) {
+        fsPick = VFAT;
     }
 
-    if (!useVfat && !useExfat) {
-        LOG(ERROR) << "Unsupported filesystem " << fsType;
-        return -EINVAL;
+    // Resolve explicit requests
+    if (fsType == "vfat" && isVfatSup) {
+        fsPick = VFAT;
+    } else if (fsType == "exfat" && isExfatSup) {
+        fsPick = EXFAT;
+    } else if (fsType == "ntfs" && isNtfsSup) {
+        fsPick = NTFS;
     }
 
     if (WipeBlockDevice(mDevPath) != OK) {
         LOG(WARNING) << getId() << " failed to wipe";
     }
 
-    if (useVfat) {
+    if (fsPick == VFAT) {
         res = vfat::Format(mDevPath, 0);
-    } else if (useExfat) {
+    } else if (fsPick == EXFAT) {
         res = exfat::Format(mDevPath);
+    } else if (fsPick == NTFS) {
+        res = ntfs::Format(mDevPath, 0);
+    } else {
+        LOG(ERROR) << "Unsupported filesystem " << fsType;
+        return -EINVAL;
     }
 
     if (res != OK) {