log storage: change AB device log storage to /data/recovery

This patchset is now exlcuding /data/cache from backup, and removing it
from the wipe exclusion list to prevent errors on restore and wiping
/data.

This patchset changes the directory from /data/cache to /data/recovery for TWRP
to store logs and other file information. This will help with AB
devices that don't want recovery to mess with /data/cache.

This patchset will make ORS use /data/cache for AB devices.

Remove policy code because we don't need to set a policy for the
recovery directory.

Change-Id: Ib06bf7c1e04259bff1e20db70f843371902e62fc
diff --git a/data.cpp b/data.cpp
index 618fc3c..bf6e33b 100755
--- a/data.cpp
+++ b/data.cpp
@@ -1088,30 +1088,30 @@
 	string Path;
 	char version[255];
 
-	std::string cacheDir = TWFunc::get_cache_dir();
-	if (cacheDir.empty()) {
+	std::string logDir = TWFunc::get_log_dir();
+	if (logDir.empty()) {
 		LOGINFO("Unable to find cache directory\n");
 		return;
 	}
 
-	std::string recoveryCacheDir = cacheDir + "recovery/";
+	std::string recoveryLogDir = logDir + "recovery/";
 
-	if (cacheDir == NON_AB_CACHE_DIR) {
-		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
+	if (logDir == CACHE_LOGS_DIR) {
+		if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
 			LOGINFO("Unable to mount '%s' to write version number.\n", Path.c_str());
 			return;
 		}
 
-		if (!TWFunc::Path_Exists(recoveryCacheDir)) {
-			LOGINFO("Recreating %s folder.\n", recoveryCacheDir.c_str());
-			if (!TWFunc::Create_Dir_Recursive(recoveryCacheDir.c_str(), S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
-				LOGERR("DataManager::Output_Version -- Unable to make %s: %s\n", recoveryCacheDir.c_str(), strerror(errno));
+		if (!TWFunc::Path_Exists(recoveryLogDir)) {
+			LOGINFO("Recreating %s folder.\n", recoveryLogDir.c_str());
+			if (!TWFunc::Create_Dir_Recursive(recoveryLogDir.c_str(), S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
+				LOGERR("DataManager::Output_Version -- Unable to make %s: %s\n", recoveryLogDir.c_str(), strerror(errno));
 				return;
 			}
 		}
 	}
 
-	std::string verPath = recoveryCacheDir + ".version";
+	std::string verPath = recoveryLogDir + ".version";
 	if (TWFunc::Path_Exists(verPath)) {
 		unlink(verPath.c_str());
 	}
@@ -1123,7 +1123,7 @@
 	strcpy(version, TW_VERSION_STR);
 	fwrite(version, sizeof(version[0]), strlen(version) / sizeof(version[0]), fp);
 	fclose(fp);
-	TWFunc::copy_file("/etc/recovery.fstab", recoveryCacheDir + "recovery.fstab", 0644);
+	TWFunc::copy_file("/etc/recovery.fstab", recoveryLogDir + "recovery.fstab", 0644);
 	PartitionManager.Output_Storage_Fstab();
 	sync();
 	LOGINFO("Version number saved to '%s'\n", verPath.c_str());
diff --git a/gui/action.cpp b/gui/action.cpp
old mode 100644
new mode 100755
index caa626d..bccf269
--- a/gui/action.cpp
+++ b/gui/action.cpp
@@ -500,7 +500,7 @@
 	DataManager::SetValue("tw_operation", operation_name);
 	DataManager::SetValue("tw_operation_state", 0);
 	DataManager::SetValue("tw_operation_status", 0);
-	bool tw_ab_device = TWFunc::get_cache_dir() != NON_AB_CACHE_DIR;
+	bool tw_ab_device = TWFunc::get_log_dir() != CACHE_LOGS_DIR;
 	DataManager::SetValue("tw_ab_device", tw_ab_device);
 }
 
diff --git a/gui/theme/common/languages/en.xml b/gui/theme/common/languages/en.xml
index fbcf436..e1e36f2 100755
--- a/gui/theme/common/languages/en.xml
+++ b/gui/theme/common/languages/en.xml
@@ -732,7 +732,6 @@
 		<string name="unmount_sys_install">Unmount System before installing a ZIP</string>
 		<string name="unmount_system">Unmounting System...</string>
 		<string name="unmount_system_err">Failed unmounting System</string>
-		<string name="fbe_wipe_msg">WARNING: {1} wiped. FBE device should be booted into Android and not Recovery to set initial FBE policy after wipe.</string>
 		<string name="flash_ab_inactive">Flashing A/B zip to inactive slot: {1}</string>
 		<string name="flash_ab_reboot">To flash additional zips, please reboot recovery to switch to the updated slot.</string>
 		<string name="ozip_decrypt_decryption">Starting Ozip Decryption...</string>
diff --git a/openrecoveryscript.cpp b/openrecoveryscript.cpp
index ad14bc2..5712538 100755
--- a/openrecoveryscript.cpp
+++ b/openrecoveryscript.cpp
@@ -62,10 +62,16 @@
 #define SCRIPT_COMMAND_SIZE 512
 
 int OpenRecoveryScript::check_for_script_file(void) {
-	std::string orsFile = TWFunc::get_cache_dir() + "/recovery/openrecoveryscript";
+	std::string logDir = TWFunc::get_log_dir();
+	std::string orsFile;
+	if (logDir == DATA_LOGS_DIR)
+		orsFile = "/data/cache";
+	else
+		orsFile = logDir;
+	orsFile += "/recovery/openrecoveryscript";
 	if (!PartitionManager.Mount_By_Path(orsFile, false)) {
-		LOGINFO("Unable to mount %s for OpenRecoveryScript support.\n", TWFunc::get_cache_dir().c_str());
-		gui_msg(Msg(msg::kError, "unable_to_mount=Unable to mount {1}")(TWFunc::get_cache_dir()));
+		LOGINFO("Unable to mount %s for OpenRecoveryScript support.\n", logDir.c_str());
+		gui_msg(Msg(msg::kError, "unable_to_mount=Unable to mount {1}")(logDir.c_str()));
 		return 0;
 	}
 	if (TWFunc::Path_Exists(orsFile)) {
@@ -697,7 +703,10 @@
 			gui_msg("decrypt_cmd=Attempting to decrypt data partition or user data via command line.");
 			if (PartitionManager.Decrypt_Device(pass, atoi(userid.c_str())) == 0) {
 				// set_page_done = 1;  // done by singleaction_page anyway
-				std::string orsFile = TWFunc::get_cache_dir() + "/openrecoveryscript";
+				std::string logDir = TWFunc::get_log_dir();
+				if (logDir == DATA_LOGS_DIR)
+					logDir = "/data/cache";
+				std::string orsFile = logDir + "/openrecoveryscript";
 				if (TWFunc::Path_Exists(orsFile)) {
 					Run_OpenRecoveryScript_Action();
 				}
diff --git a/partition.cpp b/partition.cpp
index 1471bd6..9c6a64d 100755
--- a/partition.cpp
+++ b/partition.cpp
@@ -740,7 +740,6 @@
 	ExcludeAll(Mount_Point + "/system_de/0/spblob");  // contains data needed to decrypt pixel 2
 	ExcludeAll(Mount_Point + "/system/users/0/gatekeeper.password.key");
 	ExcludeAll(Mount_Point + "/system/users/0/gatekeeper.pattern.key");
-	ExcludeAll(Mount_Point + "/cache");
 	int retry_count = 3;
 	while (!Decrypt_DE() && --retry_count)
 		usleep(2000);
@@ -1181,6 +1180,7 @@
 		DataManager::SetValue("tw_has_data_media", 1);
 		backup_exclusions.add_absolute_dir("/data/data/com.google.android.music/files");
 		backup_exclusions.add_absolute_dir("/data/per_boot"); // DJ9,14Jan2020 - exclude this dir to prevent "error 255" on AOSP ROMs that create and lock it
+		backup_exclusions.add_absolute_dir("/data/cache");
 		wipe_exclusions.add_absolute_dir(Mount_Point + "/misc/vold"); // adopted storage keys
 		ExcludeAll(Mount_Point + "/.layout_version");
 		ExcludeAll(Mount_Point + "/system/storage.xml");
@@ -1651,11 +1651,6 @@
 	bool wiped = false, update_crypt = false, recreate_media = true;
 	int check;
 	string Layout_Filename = Mount_Point + "/.layout_version";
-	ext4_encryption_policy policy;
-
-	if (Mount_Point == "/data" && TWFunc::get_cache_dir() == AB_CACHE_DIR && Is_Decrypted) {
-		TWFunc::Get_Encryption_Policy(policy, AB_CACHE_DIR);
-	}
 
 	if (!Can_Be_Wiped) {
 		gui_msg(Msg(msg::kError, "cannot_wipe=Partition {1} cannot be wiped.")(Display_Name));
@@ -1672,10 +1667,10 @@
 
 	if (Has_Data_Media && Current_File_System == New_File_System) {
 		wiped = Wipe_Data_Without_Wiping_Media();
-		if (Mount_Point == "/data" && TWFunc::get_cache_dir() == AB_CACHE_DIR) {
-			bool created = Recreate_AB_Cache_Dir(policy);
-			if (created)
-				gui_msg(Msg(msg::kWarning, "fbe_wipe_msg=WARNING: {1} wiped. FBE device should be booted into Android and not Recovery to set initial FBE policy after wipe.")(TWFunc::get_cache_dir()));
+		if (Mount_Point == "/data" && TWFunc::get_log_dir() == DATA_LOGS_DIR) {
+			bool created = Recreate_Logs_Dir();
+			if (!created)
+				LOGERR("Unable to create log directory for TWRP\n");
 		}
 		recreate_media = false;
 	} else {
@@ -2040,10 +2035,7 @@
 		}
 		DataManager::SetValue(TW_IS_ENCRYPTED, 0);
 #ifndef TW_OEM_BUILD
-		if (Is_FBE)
-			gui_msg(Msg(msg::kWarning, "fbe_wipe_msg=WARNING: {1} wiped. FBE device should be booted into Android and not Recovery to set initial FBE policy after wipe.")(TWFunc::get_cache_dir()));
-		else
-			gui_msg("format_data_msg=You may need to reboot recovery to be able to use /data again.");
+		gui_msg("format_data_msg=You may need to reboot recovery to be able to use /data again.");
 #endif
 		ret = true;
 		if (!Key_Directory.empty())
@@ -2473,7 +2465,7 @@
 #endif // ifdef TW_OEM_BUILD
 }
 
-bool TWPartition::Recreate_AB_Cache_Dir(const ext4_encryption_policy &policy) {
+bool TWPartition::Recreate_Logs_Dir() {
 #ifdef TW_INCLUDE_FBE
 	struct passwd pd;
 	struct passwd *pwdptr = &pd;
@@ -2496,30 +2488,15 @@
 		} else {
 			uid = pd.pw_uid;
 			gid = grp.gr_gid;
+			std::string abLogsRecoveryDir(DATA_LOGS_DIR);
+			abLogsRecoveryDir += "/recovery/";
 
-			if (!TWFunc::Create_Dir_Recursive(AB_CACHE_DIR, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
-				LOGERR("Unable to recreate %s\n", AB_CACHE_DIR);
+			if (!TWFunc::Create_Dir_Recursive(abLogsRecoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
+				LOGERR("Unable to recreate %s\n", abLogsRecoveryDir.c_str());
 				return false;
 			}
-			if (setfilecon(AB_CACHE_DIR, "u:object_r:cache_file:s0") != 0) {	
-				LOGERR("Unable to set contexts for %s\n", AB_CACHE_DIR);
-				return false;
-			}
-			char policy_hex[EXT4_KEY_DESCRIPTOR_SIZE_HEX];
-			policy_to_hex(policy.master_key_descriptor, policy_hex);
-			LOGINFO("setting policy for %s: %s\n", policy_hex, AB_CACHE_DIR);
-			if (sizeof(policy.master_key_descriptor) > 0) {
-				if (!TWFunc::Set_Encryption_Policy(AB_CACHE_DIR, policy)) {
-					LOGERR("Unable to set encryption policy for %s\n", AB_CACHE_DIR);
-					LOGINFO("Removing %s\n", AB_CACHE_DIR);
-					int ret = TWFunc::removeDir(AB_CACHE_DIR, true);
-					if (ret == -1) {
-						LOGERR("Unable to remove %s\n", AB_CACHE_DIR);
-					}
-					return false;
-				}
-			} else {
-				LOGERR("Not setting empty policy to %s\n", AB_CACHE_DIR);
+			if (setfilecon(abLogsRecoveryDir.c_str(), "u:object_r:cache_file:s0") != 0) {
+				LOGERR("Unable to set contexts for %s\n", abLogsRecoveryDir.c_str());
 				return false;
 			}
 		}
diff --git a/partitionmanager.cpp b/partitionmanager.cpp
index d5dc9fe..e4f8496 100755
--- a/partitionmanager.cpp
+++ b/partitionmanager.cpp
@@ -1402,10 +1402,10 @@
 
 	dir.push_back("/data/dalvik-cache");
 
-	std::string cacheDir = TWFunc::get_cache_dir();
-	if (cacheDir == NON_AB_CACHE_DIR) {
-		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
-			LOGINFO("Unable to mount %s for wiping cache.\n", NON_AB_CACHE_DIR);
+	std::string cacheDir = TWFunc::get_log_dir();
+	if (cacheDir == CACHE_LOGS_DIR) {
+		if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
+			LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
 		}
 		dir.push_back(cacheDir + "dalvik-cache");
 		dir.push_back(cacheDir + "/dc");
@@ -1420,7 +1420,7 @@
 		}
 	}
 
-	if (cacheDir == NON_AB_CACHE_DIR) {
+	if (cacheDir == CACHE_LOGS_DIR) {
 		gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
 	} else {
 		gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
@@ -1432,7 +1432,7 @@
 		}
 	}
 
-	if (cacheDir == NON_AB_CACHE_DIR) {
+	if (cacheDir == CACHE_LOGS_DIR) {
 		gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
 	} else {
 		gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
@@ -2410,14 +2410,14 @@
 	std::vector<TWPartition*>::iterator iter;
 	char storage_partition[255];
 	std::string Temp;
-	std::string cacheDir = TWFunc::get_cache_dir();
+	std::string cacheDir = TWFunc::get_log_dir();
 
 	if (cacheDir.empty()) {
 		LOGINFO("Unable to find cache directory\n");
 		return;
 	}
 
-	std::string storageFstab = TWFunc::get_cache_dir() + "recovery/storage.fstab";
+	std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
 	FILE *fp = fopen(storageFstab.c_str(), "w");
 
 	if (fp == NULL) {
diff --git a/partitions.hpp b/partitions.hpp
index 424e7dd..6b9f375 100755
--- a/partitions.hpp
+++ b/partitions.hpp
@@ -208,7 +208,7 @@
 	bool Wipe_NTFS();                                                         // Uses mkntfs to wipe
 	bool Wipe_Data_Without_Wiping_Media();                                    // Uses rm -rf to wipe but does not wipe /data/media
 	bool Wipe_Data_Without_Wiping_Media_Func(const string& parent);           // Uses rm -rf to wipe but does not wipe /data/media
-	bool Recreate_AB_Cache_Dir(const ext4_encryption_policy &policy);				  // Recreate AB_CACHE_DIR after wipe
+	bool Recreate_Logs_Dir();                                                 // Recreate TWRP_AB_LOGS_DIR after wipe
 	void Wipe_Crypto_Key();                                                   // Wipe crypto key from either footer or block device
 	bool Backup_Tar(PartitionSettings *part_settings, pid_t *tar_fork_pid);   // Backs up using tar for file systems
 	bool Backup_Image(PartitionSettings *part_settings);                      // Backs up using raw read/write for emmc memory types
diff --git a/twrp-functions.cpp b/twrp-functions.cpp
index d3d1be2..ae1d133 100755
--- a/twrp-functions.cpp
+++ b/twrp-functions.cpp
@@ -584,11 +584,11 @@
 }
 
 void TWFunc::Update_Log_File(void) {
-	std::string recoveryDir = get_cache_dir() + "recovery/";
+	std::string recoveryDir = get_log_dir() + "recovery/";
 
-	if (get_cache_dir() == NON_AB_CACHE_DIR) {
-		if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
-			LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", NON_AB_CACHE_DIR);
+	if (get_log_dir() == CACHE_LOGS_DIR) {
+		if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
+			LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
 		}
 	}
 
@@ -620,7 +620,7 @@
 		}
 	}
 
-	if (get_cache_dir() == NON_AB_CACHE_DIR) {
+	if (get_log_dir() == CACHE_LOGS_DIR) {
 		if (PartitionManager.Mount_By_Path("/cache", false)) {
 			if (unlink("/cache/recovery/command") && errno != ENOENT) {
 				LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
@@ -640,8 +640,7 @@
 int TWFunc::tw_reboot(RebootCommand command)
 {
 	DataManager::Flush();
-	if (!Is_Data_Wiped())
-		Update_Log_File();
+	Update_Log_File();
 
 	// Always force a sync before we reboot
 	sync();
@@ -1248,20 +1247,20 @@
 	return ret;
 }
 
-std::string TWFunc::get_cache_dir() {
-	if (PartitionManager.Find_Partition_By_Path(NON_AB_CACHE_DIR) == NULL) {
-		if (PartitionManager.Find_Partition_By_Path(AB_CACHE_DIR) == NULL) {
-			if (PartitionManager.Find_Partition_By_Path(PERSIST_CACHE_DIR) == NULL) {
+std::string TWFunc::get_log_dir() {
+	if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
+		if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
+			if (PartitionManager.Find_Partition_By_Path(PERSIST_LOGS_DIR) == NULL) {
 				LOGINFO("Unable to find a directory to store TWRP logs.");
 				return "";
 			}
-			return PERSIST_CACHE_DIR;
+			return PERSIST_LOGS_DIR;
 		} else {
-			return AB_CACHE_DIR;
+			return DATA_LOGS_DIR;
 		}
 	}
 	else {
-		return NON_AB_CACHE_DIR;
+		return CACHE_LOGS_DIR;
 	}
 }
 
@@ -1284,12 +1283,12 @@
 		printf("SELinux contexts loaded from /file_contexts\n");
 	{ // Check to ensure SELinux can be supported by the kernel
 		char *contexts = NULL;
-		std::string cacheDir = TWFunc::get_cache_dir();
+		std::string cacheDir = TWFunc::get_log_dir();
 		std::string se_context_check = cacheDir + "recovery/";
 		int ret = 0;
 
-		if (cacheDir == NON_AB_CACHE_DIR) {
-			PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false);
+		if (cacheDir == CACHE_LOGS_DIR) {
+			PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
 		}
 		if (TWFunc::Path_Exists(se_context_check)) {
 			ret = lgetfilecon(se_context_check.c_str(), &contexts);
@@ -1365,27 +1364,4 @@
 #endif
 	return true;
 }
-
-bool TWFunc::Is_Data_Wiped() {
-	std::string data_path = "/data";
-#ifdef TW_INCLUDE_FBE
-	DIR* d = opendir(data_path.c_str());
-	size_t file_count = 0;
-	if (d != NULL) {
-		struct dirent* de;
-		while ((de = readdir(d)) != NULL) {
-			if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
-				continue;
-			if (strncmp(de->d_name, "lost+found", 10) == 0 || strncmp(de->d_name, "media", 5) == 0)
-				continue;
-			file_count++;
-
-		}
-		closedir(d);
-	}
-	return file_count == 0;
-#else
-	return true;
-#endif
-}
 #endif // ndef BUILD_TWRPTAR_MAIN
diff --git a/twrp-functions.hpp b/twrp-functions.hpp
index 8e7005e..9715d78 100755
--- a/twrp-functions.hpp
+++ b/twrp-functions.hpp
@@ -36,9 +36,9 @@
 
 using namespace std;
 
-#define NON_AB_CACHE_DIR "/cache/"
-#define AB_CACHE_DIR "/data/cache/"
-#define PERSIST_CACHE_DIR "/persist/cache/"
+#define CACHE_LOGS_DIR "/cache/"		// For devices with a dedicated cache partition
+#define DATA_LOGS_DIR "/data/"			// For devices that do not have a dedicated cache partition
+#define PERSIST_LOGS_DIR "/persist/"	// For devices with neither cache or dedicated data partition
 
 typedef enum
 {
@@ -116,13 +116,12 @@
 	static void copy_kernel_log(string curr_storage); // Copy Kernel Log to Current Storage (PSTORE/KMSG)
 	static bool isNumber(string strtocheck); // return true if number, false if not a number
 	static int stream_adb_backup(string &Restore_Name); // Tell ADB Backup to Stream to TWRP from GUI selection
-	static std::string get_cache_dir(); // return the cache partition existence
+	static std::string get_log_dir(); // return recovery log storage directory
 	static void check_selinux_support(); // print whether selinux support is enabled to console
 	static bool Is_TWRP_App_In_System(); // Check if the TWRP app is installed in the system partition
 	static int Property_Override(string Prop_Name, string Prop_Value); // Override properties (including ro. properties)
 	static bool Get_Encryption_Policy(ext4_encryption_policy &policy, std::string path); // return encryption policy for path
 	static bool Set_Encryption_Policy(std::string path, const ext4_encryption_policy &policy); // set encryption policy for path
-	static bool Is_Data_Wiped(); // check if directory has been wiped
 
 private:
 	static void Copy_Log(string Source, string Destination);
diff --git a/twrp.cpp b/twrp.cpp
index 1e3f860..f7ad7cb 100755
--- a/twrp.cpp
+++ b/twrp.cpp
@@ -333,7 +333,9 @@
 	GUIConsole::Translate_Now();
 
 	// Run any outstanding OpenRecoveryScript
-	std::string cacheDir = TWFunc::get_cache_dir();
+	std::string cacheDir = TWFunc::get_log_dir();
+	if (cacheDir == DATA_LOGS_DIR)
+		cacheDir = "/data/cache";
 	std::string orsFile = cacheDir + "/recovery/openrecoveryscript";
 
 	if (TWFunc::Path_Exists(SCRIPT_FILE_TMP) ||
@@ -404,8 +406,7 @@
 	// Reboot
 	TWFunc::Update_Intent_File(Send_Intent);
 	delete adb_bu_fifo;
-	if (!TWFunc::Is_Data_Wiped())
-		TWFunc::Update_Log_File();
+	TWFunc::Update_Log_File();
 	gui_msg(Msg("rebooting=Rebooting..."));
 	string Reboot_Arg;
 	DataManager::GetValue("tw_reboot_arg", Reboot_Arg);