Merge cherrypicks of [3196053, 3195996, 3195997, 3195998, 3196073, 3196093, 3196113, 3195934, 3195999, 3196074, 3196133, 3196134, 3195914, 3195915, 3195916] into oc-mr1-release

Change-Id: I9a73a0e505eec758623136e9a5ee711b0c85c2a9
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 9d61555..20b2391 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -35,6 +35,7 @@
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/unique_fd.h>
 
 #include <cutils/properties.h>
 
@@ -153,10 +154,29 @@
 }
 
 static bool writeStringToFile(const std::string& payload, const std::string& filename) {
-    if (!android::base::WriteStringToFile(payload, filename)) {
-        PLOG(ERROR) << "Failed to write to " << filename;
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+        open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << filename;
         return false;
     }
+    if (!android::base::WriteStringToFd(payload, fd)) {
+        PLOG(ERROR) << "Failed to write to " << filename;
+        unlink(filename.c_str());
+        return false;
+    }
+    // fsync as close won't guarantee flush data
+    // see close(2), fsync(2) and b/68901441
+    if (fsync(fd) == -1) {
+        if (errno == EROFS || errno == EINVAL) {
+            PLOG(WARNING) << "Skip fsync " << filename
+                          << " on a file system does not support synchronization";
+        } else {
+            PLOG(ERROR) << "Failed to fsync " << filename;
+            unlink(filename.c_str());
+            return false;
+        }
+    }
     return true;
 }