Add a per-boot-key policy reference, apply to per_boot

Includes changes picked from aosp/1119783
570d20d2ac875198416dff280b7a4b7adaacac81 in platform/system/core

Bug: 140882488
Test: Booted twice, checked logs to ensure encryption
    is different each time, adb created files in directory.
Cherry-Picked-From: ab3085004e35cff9517fcedb03317f3f1ac84cf9
Merged-In: I5c962edb316d160dd09c0df893912c6b257d7810
Change-Id: I5c962edb316d160dd09c0df893912c6b257d7810
diff --git a/libfscrypt/fscrypt_init_extensions.cpp b/libfscrypt/fscrypt_init_extensions.cpp
index 9781267..2fd70e7 100644
--- a/libfscrypt/fscrypt_init_extensions.cpp
+++ b/libfscrypt/fscrypt_init_extensions.cpp
@@ -39,7 +39,7 @@
 
 static const std::string arbitrary_sequence_number = "42";
 
-static int set_system_de_policy_on(char const* dir);
+static int set_policy_on(char const* ref_basename, char const* dir);
 
 int fscrypt_install_keyring()
 {
@@ -65,7 +65,7 @@
     // Special-case /data/media/obb per b/64566063
     if (strcmp(dir, "/data/media/obb") == 0) {
         // Try to set policy on this directory, but if it is non-empty this may fail.
-        set_system_de_policy_on(dir);
+        set_policy_on(fscrypt_key_ref, dir);
         return 0;
     }
 
@@ -97,11 +97,20 @@
             return 0;
         }
     }
-    return set_system_de_policy_on(dir);
+    std::vector<std::string> per_boot_directories = {
+        "per_boot",
+    };
+    for (const auto& d : per_boot_directories) {
+        if ((prefix + d) == dir) {
+            LOG(INFO) << "Setting per_boot key on " << dir;
+            return set_policy_on(fscrypt_key_per_boot_ref, dir);
+        }
+    }
+    return set_policy_on(fscrypt_key_ref, dir);
 }
 
-static int set_system_de_policy_on(char const* dir) {
-    std::string ref_filename = std::string("/data") + fscrypt_key_ref;
+static int set_policy_on(char const* ref_basename, char const* dir) {
+    std::string ref_filename = std::string("/data") + ref_basename;
     std::string policy;
     if (!android::base::ReadFileToString(ref_filename, &policy)) {
         LOG(ERROR) << "Unable to read system policy to set on " << dir;
diff --git a/libfscrypt/include/fscrypt/fscrypt.h b/libfscrypt/include/fscrypt/fscrypt.h
index 8a68b93..ff82d47 100644
--- a/libfscrypt/include/fscrypt/fscrypt.h
+++ b/libfscrypt/include/fscrypt/fscrypt.h
@@ -32,6 +32,7 @@
 
 static const char* fscrypt_unencrypted_folder = "/unencrypted";
 static const char* fscrypt_key_ref = "/unencrypted/ref";
+static const char* fscrypt_key_per_boot_ref = "/unencrypted/per_boot_ref";
 static const char* fscrypt_key_mode = "/unencrypted/mode";
 
 __END_DECLS