blob: 64723490f242df1bac4527c5a2b3fea1e63adbd5 [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002 Copyright 2014 to 2017 TeamWin
Dees Troy3be70a82013-10-22 14:25:12 +00003 This file is part of TWRP/TeamWin Recovery Project.
4
5 TWRP is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 TWRP is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with TWRP. If not, see <http://www.gnu.org/licenses/>.
17*/
Dees_Troy51a0e822012-09-05 15:24:24 -040018
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <sys/stat.h>
23#include <sys/vfs.h>
24#include <unistd.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060025#include <map>
Dees_Troy5bf43922012-09-07 16:07:55 -040026#include <vector>
Dees_Troy63c8df72012-09-10 14:02:05 -040027#include <dirent.h>
28#include <time.h>
Dees_Troy8170a922012-09-18 15:40:25 -040029#include <errno.h>
30#include <fcntl.h>
bigbiffce8f83c2015-12-12 18:30:21 -050031#include <zlib.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050032#include <iostream>
33#include <iomanip>
Ethan Yonker8613dc02014-09-11 09:28:20 -050034#include <sys/wait.h>
Ethan Yonker483e9f42016-01-11 22:21:18 -060035#include <linux/fs.h>
36#include <sys/mount.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060037
38#include <sys/poll.h>
39#include <sys/socket.h>
40#include <linux/types.h>
41#include <linux/netlink.h>
42
Dees_Troy51a0e822012-09-05 15:24:24 -040043#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000044#include "twcommon.h"
Dees_Troy51a0e822012-09-05 15:24:24 -040045#include "partitions.hpp"
Dees_Troy5bf43922012-09-07 16:07:55 -040046#include "data.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040047#include "twrp-functions.hpp"
Ethan Yonkerb5fab762016-01-28 14:03:33 -060048#include "fixContexts.hpp"
Ethan Yonker3fdcda42016-11-30 12:29:37 -060049#include "exclude.hpp"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060050#include "set_metadata.h"
bigbiff7abc5fe2015-01-17 16:53:12 -050051#include "tw_atomic.hpp"
Ethan Yonker74db1572015-10-28 12:44:49 -050052#include "gui/gui.hpp"
Ethan Yonker472f5062016-02-25 13:47:30 -060053#include "progresstracking.hpp"
bigbiff bigbiff56cf5642016-08-19 17:43:45 -040054#include "twrpDigestDriver.hpp"
bigbiff56b02eb2020-07-06 20:24:34 -040055#include "twrpRepacker.hpp"
bigbiffce8f83c2015-12-12 18:30:21 -050056#include "adbbu/libtwadbbu.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040057
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040058#ifdef TW_HAS_MTP
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -050059#ifdef TW_HAS_LEGACY_MTP
60#include "mtp/legacy/mtp_MtpServer.hpp"
61#include "mtp/legacy/twrpMtp.hpp"
62#include "mtp/legacy/MtpMessage.hpp"
63#else
64#include "mtp/ffs/mtp_MtpServer.hpp"
65#include "mtp/ffs/twrpMtp.hpp"
66#include "mtp/ffs/MtpMessage.hpp"
67#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040068#endif
69
Dees Troy6f6441d2014-01-23 02:07:03 +000070extern "C" {
71 #include "cutils/properties.h"
Ethan Yonker74db1572015-10-28 12:44:49 -050072 #include "gui/gui.h"
Dees Troy6f6441d2014-01-23 02:07:03 +000073}
74
Dees_Troy5bf43922012-09-07 16:07:55 -040075#ifdef TW_INCLUDE_CRYPTO
Noah Jacobson5a79f672019-04-28 00:10:07 -040076#include "crypto/fde/cryptfs.h"
77#include "gui/rapidxml.hpp"
78#include "gui/pages.hpp"
79#ifdef TW_INCLUDE_FBE
80#include "crypto/ext4crypt/Decrypt.h"
81#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
82#include "crypto/ext4crypt/MetadataCrypt.h"
83#endif
84#endif
85#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
86#include "crypto/vold_decrypt/vold_decrypt.h"
87#endif
Dees_Troy5bf43922012-09-07 16:07:55 -040088#endif
Dees_Troy51a0e822012-09-05 15:24:24 -040089
Ethan Yonker1b190162016-12-05 15:25:19 -060090#ifdef AB_OTA_UPDATER
91#include <hardware/hardware.h>
92#include <hardware/boot_control.h>
93#endif
94
Ethan Yonker6277c792014-09-15 14:54:30 -050095extern bool datamedia;
Noah Jacobson5a79f672019-04-28 00:10:07 -040096std::vector<users_struct> Users_List;
Ethan Yonker6277c792014-09-15 14:54:30 -050097
bigbiff bigbiff34684ff2013-12-01 21:03:45 -050098TWPartitionManager::TWPartitionManager(void) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040099 mtp_was_enabled = false;
Ethan Yonker726a0202014-12-16 20:01:38 -0600100 mtp_write_fd = -1;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600101 uevent_pfd.fd = -1;
bigbiff7abc5fe2015-01-17 16:53:12 -0500102 stop_backup.set_value(0);
Ethan Yonker1b190162016-12-05 15:25:19 -0600103#ifdef AB_OTA_UPDATER
104 char slot_suffix[PROPERTY_VALUE_MAX];
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500105 property_get("ro.boot.slot_suffix", slot_suffix, "error");
106 if (strcmp(slot_suffix, "error") == 0)
107 property_get("ro.boot.slot", slot_suffix, "error");
Ethan Yonker1b190162016-12-05 15:25:19 -0600108 Active_Slot_Display = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500109 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Ethan Yonker1b190162016-12-05 15:25:19 -0600110 Set_Active_Slot("A");
111 else
112 Set_Active_Slot("B");
113#endif
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500114}
115
Captain Throwback07b8e052020-10-29 12:43:17 -0400116int TWPartitionManager::Set_FDE_Encrypt_Status(void) {
117 property_set("ro.crypto.state", "encrypted");
118 property_set("ro.crypto.type", "block");
119 // Sleep for a bit so that services can start if needed
120 sleep(1);
121 return 0;
122}
123
Chaosmasterf6e42ce2020-01-27 00:17:04 +0100124int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool Sar_Detect) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400125 FILE *fstabFile;
126 char fstab_line[MAX_FSTAB_LINE_LENGTH];
Dees Troy02a64532014-03-19 15:23:32 +0000127 TWPartition* settings_partition = NULL;
Matt Mowerbf4efa32014-04-14 23:25:26 -0500128 TWPartition* andsec_partition = NULL;
Ethan Yonker726a0202014-12-16 20:01:38 -0600129 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600130 std::map<string, Flags_Map> twrp_flags;
131
132 fstabFile = fopen("/etc/twrp.flags", "rt");
133 if (fstabFile != NULL) {
134 LOGINFO("reading /etc/twrp.flags\n");
135 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
136 if (fstab_line[0] != '/')
137 continue;
138
139 size_t line_size = strlen(fstab_line);
140 if (fstab_line[line_size - 1] != '\n')
141 fstab_line[line_size] = '\n';
142 Flags_Map line_flags;
143 line_flags.Primary_Block_Device = "";
144 line_flags.Alternate_Block_Device = "";
145 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
146 if (!line_flags.fstab_line) {
147 LOGERR("malloc error on line_flags.fstab_line\n");
148 return false;
149 }
150 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
151 bool found_separator = false;
152 char *fs_loc = NULL;
153 char *block_loc = NULL;
154 char *flags_loc = NULL;
155 size_t index, item_index = 0;
156 for (index = 0; index < line_size; index++) {
157 if (fstab_line[index] <= 32) {
158 fstab_line[index] = '\0';
159 found_separator = true;
160 } else if (found_separator) {
161 if (item_index == 0) {
162 fs_loc = fstab_line + index;
163 } else if (item_index == 1) {
164 block_loc = fstab_line + index;
165 } else if (item_index > 1) {
166 char *ptr = fstab_line + index;
167 if (*ptr == '/') {
168 line_flags.Alternate_Block_Device = ptr;
169 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
170 flags_loc = ptr;
171 // Once we find the flags=, we're done scanning the line
172 break;
173 }
174 }
175 found_separator = false;
176 item_index++;
177 }
178 }
179 if (block_loc)
180 line_flags.Primary_Block_Device = block_loc;
181 if (fs_loc)
182 line_flags.File_System = fs_loc;
183 if (flags_loc)
184 line_flags.Flags = flags_loc;
185 string Mount_Point = fstab_line;
186 twrp_flags[Mount_Point] = line_flags;
187 memset(fstab_line, 0, sizeof(fstab_line));
188 }
189 fclose(fstabFile);
190 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400191
192 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
193 if (fstabFile == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000194 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400195 return false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600196 } else
197 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400198
199 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
200 if (fstab_line[0] != '/')
201 continue;
202
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600203 if (strstr(fstab_line, "swap"))
204 continue; // Skip swap in recovery
205
206 size_t line_size = strlen(fstab_line);
207 if (fstab_line[line_size - 1] != '\n')
208 fstab_line[line_size] = '\n';
Dees_Troy2a923582012-09-20 12:13:34 -0400209
Matt Mower2b2dd152016-04-26 11:24:08 -0500210 TWPartition* partition = new TWPartition();
Chaosmasterf6e42ce2020-01-27 00:17:04 +0100211 if (partition->Process_Fstab_Line(fstab_line, Display_Error, &twrp_flags, Sar_Detect))
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500212 Partitions.push_back(partition);
Matt Mower72c87ce2016-04-26 14:34:56 -0500213 else
Dees_Troy5bf43922012-09-07 16:07:55 -0400214 delete partition;
Matt Mower2b2dd152016-04-26 11:24:08 -0500215
216 memset(fstab_line, 0, sizeof(fstab_line));
Dees_Troy5bf43922012-09-07 16:07:55 -0400217 }
218 fclose(fstabFile);
Matt Mower72c87ce2016-04-26 14:34:56 -0500219
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600220 if (twrp_flags.size() > 0) {
221 LOGINFO("Processing remaining twrp.flags\n");
222 // Add any items from twrp.flags that did not exist in the recovery.fstab
223 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
224 if (Find_Partition_By_Path(mapit->first) == NULL) {
225 TWPartition* partition = new TWPartition();
Chaosmasterf6e42ce2020-01-27 00:17:04 +0100226 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL, Sar_Detect))
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600227 Partitions.push_back(partition);
228 else
229 delete partition;
230 }
231 if (mapit->second.fstab_line)
232 free(mapit->second.fstab_line);
233 mapit->second.fstab_line = NULL;
234 }
235 }
236 LOGINFO("Done processing fstab files\n");
237
Matt Mower72c87ce2016-04-26 14:34:56 -0500238 std::vector<TWPartition*>::iterator iter;
239 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Chaosmasterf6e42ce2020-01-27 00:17:04 +0100240 if (Sar_Detect) {
241 if ((*iter)->Mount_Point == "/s")
242 return true;
243 else
244 continue;
245 }
246
Matt Mower72c87ce2016-04-26 14:34:56 -0500247 (*iter)->Partition_Post_Processing(Display_Error);
248
249 if ((*iter)->Is_Storage) {
250 ++storageid;
251 (*iter)->MTP_Storage_ID = storageid;
252 }
253
254 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
255 settings_partition = (*iter);
256 else
257 (*iter)->Is_Settings_Storage = false;
258
259 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
260 andsec_partition = (*iter);
261 else
262 (*iter)->Has_Android_Secure = false;
263 }
264
Ethan Yonker6277c792014-09-15 14:54:30 -0500265 if (!datamedia && !settings_partition && Find_Partition_By_Path("/sdcard") == NULL && Find_Partition_By_Path("/internal_sd") == NULL && Find_Partition_By_Path("/internal_sdcard") == NULL && Find_Partition_By_Path("/emmc") == NULL) {
266 // Attempt to automatically identify /data/media emulated storage devices
267 TWPartition* Dat = Find_Partition_By_Path("/data");
268 if (Dat) {
269 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
270 datamedia = true;
that9e0593e2014-10-08 00:01:24 +0200271 Dat->Setup_Data_Media();
Ethan Yonker6277c792014-09-15 14:54:30 -0500272 settings_partition = Dat;
Ethan Yonker726a0202014-12-16 20:01:38 -0600273 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
274 ++storageid;
275 Dat->MTP_Storage_ID = storageid;
Ethan Yonker6277c792014-09-15 14:54:30 -0500276 }
277 }
Dees Troy02a64532014-03-19 15:23:32 +0000278 if (!settings_partition) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500279 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
280 if ((*iter)->Is_Storage) {
Dees Troy02a64532014-03-19 15:23:32 +0000281 settings_partition = (*iter);
Dees_Troya13d74f2013-03-24 08:54:55 -0500282 break;
283 }
284 }
Dees Troy02a64532014-03-19 15:23:32 +0000285 if (!settings_partition)
Dees_Troy2673cec2013-04-02 20:22:16 +0000286 LOGERR("Unable to locate storage partition for storing settings file.\n");
Dees_Troya13d74f2013-03-24 08:54:55 -0500287 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400288 if (!Write_Fstab()) {
289 if (Display_Error)
Dees_Troy2673cec2013-04-02 20:22:16 +0000290 LOGERR("Error creating fstab\n");
Dees_Troy5bf43922012-09-07 16:07:55 -0400291 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000292 LOGINFO("Error creating fstab\n");
Dees_Troy5bf43922012-09-07 16:07:55 -0400293 }
Matt Mowered71fa32014-04-16 13:21:47 -0500294
Matt Mowerbf4efa32014-04-14 23:25:26 -0500295 if (andsec_partition) {
296 Setup_Android_Secure_Location(andsec_partition);
Matt Mowered71fa32014-04-16 13:21:47 -0500297 } else if (settings_partition) {
Matt Mowerbf4efa32014-04-14 23:25:26 -0500298 Setup_Android_Secure_Location(settings_partition);
299 }
Matt Mowered71fa32014-04-16 13:21:47 -0500300 if (settings_partition) {
301 Setup_Settings_Storage_Partition(settings_partition);
302 }
Ethan Yonker253368a2014-11-25 15:00:52 -0600303#ifdef TW_INCLUDE_CRYPTO
Ethan Yonkercceebb82014-11-18 10:17:59 -0600304 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
305 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
nebrassy674bb0c2020-10-24 21:08:20 +0200306 property_set("ro.crypto.state", "encrypted");
Ethan Yonker93382822018-11-01 15:25:31 -0500307 if (!Decrypt_Data->Key_Directory.empty() && Mount_By_Path(Decrypt_Data->Key_Directory, false)) {
nebrassy674bb0c2020-10-24 21:08:20 +0200308 property_set("ro.crypto.type", "file");
Ethan Yonker93382822018-11-01 15:25:31 -0500309#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
310 if (e4crypt_mount_metadata_encrypted(Decrypt_Data->Mount_Point, false, Decrypt_Data->Key_Directory, Decrypt_Data->Actual_Block_Device, &Decrypt_Data->Decrypted_Block_Device)) {
311 LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", Decrypt_Data->Decrypted_Block_Device.c_str());
Ethan Yonker93382822018-11-01 15:25:31 -0500312 Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
313 int retry_count = 10;
314 while (!Decrypt_Data->Mount(false) && --retry_count)
315 usleep(500);
316 if (Decrypt_Data->Mount(false)) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400317 if (!Decrypt_Data->Decrypt_FBE_DE()) {
mauronofrio1db94322019-11-23 23:13:04 +0100318 char wrappedvalue[PROPERTY_VALUE_MAX];
319 property_get("fbe.data.wrappedkey", wrappedvalue, "");
320 std::string wrappedkeyvalue(wrappedvalue);
321 if (wrappedkeyvalue == "true") {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400322 LOGERR("Unable to decrypt FBE device\n");
mauronofrio1db94322019-11-23 23:13:04 +0100323 } else {
324 LOGINFO("Trying wrapped key.\n");
325 property_set("fbe.data.wrappedkey", "true");
326 if (!Decrypt_Data->Decrypt_FBE_DE()) {
327 LOGERR("Unable to decrypt FBE device\n");
328 }
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400329 }
330 }
331
Ethan Yonker93382822018-11-01 15:25:31 -0500332 } else {
333 LOGINFO("Failed to mount data after metadata decrypt\n");
334 }
335 } else {
336 LOGINFO("Unable to decrypt metadata encryption\n");
337 }
338#else
339 LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
340#endif
341 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600342 if (Decrypt_Data->Is_FBE) {
343 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
344 if (Decrypt_Device("!") == 0) {
345 gui_msg("decrypt_success=Successfully decrypted with default password.");
346 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
347 } else {
348 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
349 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600350 }
351 } else {
Captain Throwback07b8e052020-10-29 12:43:17 -0400352 Set_FDE_Encrypt_Status();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600353 int password_type = cryptfs_get_password_type();
354 if (password_type == CRYPT_TYPE_DEFAULT) {
355 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
356 if (Decrypt_Device("default_password") == 0) {
357 gui_msg("decrypt_success=Successfully decrypted with default password.");
358 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
359 } else {
360 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
361 }
362 } else {
363 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
Noah Jacobson5a79f672019-04-28 00:10:07 -0400364 DataManager::SetValue("tw_crypto_pwtype_0", password_type);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600365 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600366 }
367 }
Noah Jacobson5a79f672019-04-28 00:10:07 -0400368 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) &&
369 Decrypt_Data->Mount(false)) {
Ethan Yonker66a19492015-12-10 10:19:45 -0600370 Decrypt_Adopted();
371 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600372#endif
Dees_Troy51127312012-09-08 13:08:49 -0400373 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -0400374 UnMount_Main_Partitions();
Ethan Yonker1b190162016-12-05 15:25:19 -0600375#ifdef AB_OTA_UPDATER
376 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
377#endif
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600378 setup_uevent();
Dees_Troy5bf43922012-09-07 16:07:55 -0400379 return true;
380}
381
382int TWPartitionManager::Write_Fstab(void) {
383 FILE *fp;
384 std::vector<TWPartition*>::iterator iter;
385 string Line;
386
387 fp = fopen("/etc/fstab", "w");
388 if (fp == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000389 LOGINFO("Can not open /etc/fstab.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -0400390 return false;
391 }
Dees_Troy63c8df72012-09-10 14:02:05 -0400392 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy51127312012-09-08 13:08:49 -0400393 if ((*iter)->Can_Be_Mounted) {
dianlujitao7d304c72016-01-02 12:15:50 +0800394 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System + " rw 0 0\n";
Dees_Troy5bf43922012-09-07 16:07:55 -0400395 fputs(Line.c_str(), fp);
Dees_Troy91862e62013-04-04 23:48:21 +0000396 }
397 // Handle subpartition tracking
398 if ((*iter)->Is_SubPartition) {
399 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
400 if (ParentPartition)
401 ParentPartition->Has_SubPartition = true;
402 else
403 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400404 }
405 }
406 fclose(fp);
407 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -0400408}
409
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500410void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500411 DataManager::SetValue("tw_settings_path", Part->Storage_Path);
412 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
413 LOGINFO("Settings storage is '%s'\n", Part->Storage_Path.c_str());
414}
415
Matt Mowerbf4efa32014-04-14 23:25:26 -0500416void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
417 if (Part->Has_Android_Secure)
418 Part->Setup_AndSec();
Ethan Yonker6277c792014-09-15 14:54:30 -0500419 else if (!datamedia)
Matt Mowerbf4efa32014-04-14 23:25:26 -0500420 Part->Setup_AndSec();
Matt Mowerbf4efa32014-04-14 23:25:26 -0500421}
422
Dees_Troy8170a922012-09-18 15:40:25 -0400423void TWPartitionManager::Output_Partition_Logging(void) {
424 std::vector<TWPartition*>::iterator iter;
425
426 printf("\n\nPartition Logs:\n");
427 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
428 Output_Partition((*iter));
429}
430
431void TWPartitionManager::Output_Partition(TWPartition* Part) {
432 unsigned long long mb = 1048576;
433
Gary Peck004d48b2012-11-21 16:28:18 -0800434 printf("%s | %s | Size: %iMB", Part->Mount_Point.c_str(), Part->Actual_Block_Device.c_str(), (int)(Part->Size / mb));
Dees_Troy8170a922012-09-18 15:40:25 -0400435 if (Part->Can_Be_Mounted) {
Gary Peck004d48b2012-11-21 16:28:18 -0800436 printf(" Used: %iMB Free: %iMB Backup Size: %iMB", (int)(Part->Used / mb), (int)(Part->Free / mb), (int)(Part->Backup_Size / mb));
Dees_Troy8170a922012-09-18 15:40:25 -0400437 }
Gary Peck004d48b2012-11-21 16:28:18 -0800438 printf("\n Flags: ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500439 if (Part->Can_Be_Mounted)
440 printf("Can_Be_Mounted ");
Gary Peck004d48b2012-11-21 16:28:18 -0800441 if (Part->Can_Be_Wiped)
442 printf("Can_Be_Wiped ");
Hashcodedabfd492013-08-29 22:45:30 -0700443 if (Part->Use_Rm_Rf)
444 printf("Use_Rm_Rf ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500445 if (Part->Can_Be_Backed_Up)
446 printf("Can_Be_Backed_Up ");
Gary Peck004d48b2012-11-21 16:28:18 -0800447 if (Part->Wipe_During_Factory_Reset)
448 printf("Wipe_During_Factory_Reset ");
449 if (Part->Wipe_Available_in_GUI)
450 printf("Wipe_Available_in_GUI ");
451 if (Part->Is_SubPartition)
452 printf("Is_SubPartition ");
453 if (Part->Has_SubPartition)
454 printf("Has_SubPartition ");
455 if (Part->Removable)
456 printf("Removable ");
457 if (Part->Is_Present)
458 printf("IsPresent ");
459 if (Part->Can_Be_Encrypted)
460 printf("Can_Be_Encrypted ");
461 if (Part->Is_Encrypted)
462 printf("Is_Encrypted ");
463 if (Part->Is_Decrypted)
464 printf("Is_Decrypted ");
465 if (Part->Has_Data_Media)
466 printf("Has_Data_Media ");
Dees_Troy83bd4832013-05-04 12:39:56 +0000467 if (Part->Can_Encrypt_Backup)
468 printf("Can_Encrypt_Backup ");
469 if (Part->Use_Userdata_Encryption)
470 printf("Use_Userdata_Encryption ");
Gary Peck004d48b2012-11-21 16:28:18 -0800471 if (Part->Has_Android_Secure)
472 printf("Has_Android_Secure ");
473 if (Part->Is_Storage)
474 printf("Is_Storage ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500475 if (Part->Is_Settings_Storage)
476 printf("Is_Settings_Storage ");
Dees_Troy68cab492012-12-12 19:29:35 +0000477 if (Part->Ignore_Blkid)
478 printf("Ignore_Blkid ");
Dees_Troy16c2b312013-01-15 16:51:18 +0000479 if (Part->Retain_Layout_Version)
480 printf("Retain_Layout_Version ");
Ethan Yonker253368a2014-11-25 15:00:52 -0600481 if (Part->Mount_To_Decrypt)
482 printf("Mount_To_Decrypt ");
Ethan Yonker96af84a2015-01-05 14:58:36 -0600483 if (Part->Can_Flash_Img)
484 printf("Can_Flash_Img ");
Ethan Yonker66a19492015-12-10 10:19:45 -0600485 if (Part->Is_Adopted_Storage)
486 printf("Is_Adopted_Storage ");
Ethan Yonker1b190162016-12-05 15:25:19 -0600487 if (Part->SlotSelect)
488 printf("SlotSelect ");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600489 if (Part->Mount_Read_Only)
490 printf("Mount_Read_Only ");
Gary Peck004d48b2012-11-21 16:28:18 -0800491 printf("\n");
492 if (!Part->SubPartition_Of.empty())
493 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
494 if (!Part->Symlink_Path.empty())
495 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
496 if (!Part->Symlink_Mount_Point.empty())
497 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
498 if (!Part->Primary_Block_Device.empty())
499 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
500 if (!Part->Alternate_Block_Device.empty())
501 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
502 if (!Part->Decrypted_Block_Device.empty())
503 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
dianlujitao4879b372018-12-03 18:45:47 +0800504 if (!Part->Crypto_Key_Location.empty())
Ethan Yonker253368a2014-11-25 15:00:52 -0600505 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800506 if (Part->Length != 0)
507 printf(" Length: %i\n", Part->Length);
508 if (!Part->Display_Name.empty())
509 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500510 if (!Part->Storage_Name.empty())
511 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800512 if (!Part->Backup_Path.empty())
513 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
514 if (!Part->Backup_Name.empty())
515 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500516 if (!Part->Backup_Display_Name.empty())
517 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800518 if (!Part->Backup_FileName.empty())
519 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
520 if (!Part->Storage_Path.empty())
521 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
522 if (!Part->Current_File_System.empty())
523 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
524 if (!Part->Fstab_File_System.empty())
525 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
526 if (Part->Format_Block_Size != 0)
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500527 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
Dees_Troy094207a2012-09-26 12:00:39 -0400528 if (!Part->MTD_Name.empty())
529 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
Matt Mower029a82d2017-01-08 13:12:38 -0600530 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
Hashcode62bd9e02013-11-19 21:59:42 -0800531 if (Part->Mount_Flags || !Part->Mount_Options.empty())
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600532 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -0600533 if (Part->MTP_Storage_ID)
534 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
Ethan Yonker93382822018-11-01 15:25:31 -0500535 if (!Part->Key_Directory.empty())
536 printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
Ethan Yonker6277c792014-09-15 14:54:30 -0500537 printf("\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400538}
539
Dees_Troy51a0e822012-09-05 15:24:24 -0400540int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400541 std::vector<TWPartition*>::iterator iter;
542 int ret = false;
543 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400544 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400545
Captain Throwbackd54e1da2020-03-04 16:49:51 -0500546 if (Local_Path == "/tmp" || Local_Path == "/" || Local_Path == "/etc")
Dees_Troy43d8b002012-09-17 16:00:01 -0400547 return true;
548
Dees_Troy5bf43922012-09-07 16:07:55 -0400549 // Iterate through all partitions
550 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400551 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400552 ret = (*iter)->Mount(Display_Error);
553 found = true;
Dees_Troy51127312012-09-08 13:08:49 -0400554 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400555 (*iter)->Mount(Display_Error);
Dees_Troy51127312012-09-08 13:08:49 -0400556 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400557 }
558 if (found) {
559 return ret;
560 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500561 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Dees_Troy5bf43922012-09-07 16:07:55 -0400562 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000563 LOGINFO("Mount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400564 }
565 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400566}
567
Dees_Troy51a0e822012-09-05 15:24:24 -0400568int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400569 std::vector<TWPartition*>::iterator iter;
570 int ret = false;
571 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400572 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy51127312012-09-08 13:08:49 -0400573
574 // Iterate through all partitions
575 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400576 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy51127312012-09-08 13:08:49 -0400577 ret = (*iter)->UnMount(Display_Error);
578 found = true;
579 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
580 (*iter)->UnMount(Display_Error);
581 }
582 }
583 if (found) {
584 return ret;
585 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500586 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Dees_Troy51127312012-09-08 13:08:49 -0400587 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000588 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400589 }
590 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400591}
592
Dees_Troy51a0e822012-09-05 15:24:24 -0400593int TWPartitionManager::Is_Mounted_By_Path(string Path) {
Dees_Troy51127312012-09-08 13:08:49 -0400594 TWPartition* Part = Find_Partition_By_Path(Path);
595
596 if (Part)
597 return Part->Is_Mounted();
598 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000599 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400600 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400601}
602
Dees_Troy5bf43922012-09-07 16:07:55 -0400603int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400604 string current_storage_path = DataManager::GetCurrentStoragePath();
605
606 if (Mount_By_Path(current_storage_path, Display_Error)) {
607 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
608 if (FreeStorage)
609 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
610 return true;
611 }
612 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400613}
614
Dees_Troy5bf43922012-09-07 16:07:55 -0400615int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
616 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
617}
618
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600619TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400620 std::vector<TWPartition*>::iterator iter;
Dees_Troy38bd7602012-09-14 13:33:53 -0400621 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400622
dianlujitaob76a73a2020-04-30 20:33:20 +0800623 if (Local_Path == "/system")
624 Local_Path = Get_Android_Root_Path();
Dees_Troy5bf43922012-09-07 16:07:55 -0400625 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400626 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
Dees_Troy5bf43922012-09-07 16:07:55 -0400627 return (*iter);
628 }
Dees_Troy51a0e822012-09-05 15:24:24 -0400629 return NULL;
630}
631
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600632TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
633 std::vector<TWPartition*>::iterator iter;
634
635 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
636 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
637 return (*iter);
638 }
639 return NULL;
640}
641
Ethan Yonker53796e72019-01-11 22:49:52 -0600642int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400643 // Check the backup name to ensure that it is the correct size and contains only valid characters
644 // and that a backup with that name doesn't already exist
645 char backup_name[MAX_BACKUP_NAME_LEN];
646 char backup_loc[255], tw_image_dir[255];
647 int copy_size;
648 int index, cur_char;
Ethan Yonker53796e72019-01-11 22:49:52 -0600649 string Backup_Loc;
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400650
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400651 copy_size = Backup_Name.size();
652 // Check size
653 if (copy_size > MAX_BACKUP_NAME_LEN) {
654 if (Display_Error)
Ethan Yonker74db1572015-10-28 12:44:49 -0500655 gui_err("backup_name_len=Backup name is too long.");
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400656 return -2;
657 }
658
659 // Check each character
660 strncpy(backup_name, Backup_Name.c_str(), copy_size);
Dees_Troya13d74f2013-03-24 08:54:55 -0500661 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400662 return 0; // A "0" (zero) means to use the current timestamp for the backup name
663 for (index=0; index<copy_size; index++) {
664 cur_char = (int)backup_name[index];
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500665 if (cur_char == 32 || (cur_char >= 48 && cur_char <= 57) || (cur_char >= 65 && cur_char <= 91) || cur_char == 93 || cur_char == 95 || (cur_char >= 97 && cur_char <= 123) || cur_char == 125 || cur_char == 45 || cur_char == 46) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400666 // These are valid characters
667 // Numbers
668 // Upper case letters
669 // Lower case letters
670 // Space
671 // and -_.{}[]
672 } else {
673 if (Display_Error)
Ethan Yonker4adc33e2016-01-22 16:07:11 -0600674 gui_msg(Msg(msg::kError, "backup_name_invalid=Backup name '{1}' contains invalid character: '{1}'")(Backup_Name)((char)cur_char));
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400675 return -3;
676 }
677 }
678
Ethan Yonker53796e72019-01-11 22:49:52 -0600679 if (Must_Be_Unique) {
680 // Check to make sure that a backup with this name doesn't already exist
681 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
682 strcpy(backup_loc, Backup_Loc.c_str());
683 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
684 if (TWFunc::Path_Exists(tw_image_dir)) {
685 if (Display_Error)
686 gui_err("backup_name_exists=A backup with that name already exists!");
bigbiffce8f83c2015-12-12 18:30:21 -0500687
Ethan Yonker53796e72019-01-11 22:49:52 -0600688 return -4;
689 }
690 // Backup is unique
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400691 }
Ethan Yonker53796e72019-01-11 22:49:52 -0600692 // No problems found
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400693 return 0;
694}
695
bigbiffce8f83c2015-12-12 18:30:21 -0500696bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400697 time_t start, stop;
Matt Mower23d8aae2017-01-06 14:30:33 -0600698 int use_compression;
bigbiffce8f83c2015-12-12 18:30:21 -0500699 string backup_log = part_settings->Backup_Folder + "/recovery.log";
Dees_Troy43d8b002012-09-17 16:00:01 -0400700
bigbiffce8f83c2015-12-12 18:30:21 -0500701 if (part_settings->Part == NULL)
Dees_Troy43d8b002012-09-17 16:00:01 -0400702 return true;
703
Dees_Troy093b7642012-09-21 15:59:38 -0400704 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -0400705
Tom Hite5a926722014-09-15 01:31:03 +0000706 TWFunc::SetPerformanceMode(true);
Dees_Troy43d8b002012-09-17 16:00:01 -0400707 time(&start);
708
bigbiffce8f83c2015-12-12 18:30:21 -0500709 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500710 sync();
711 sync();
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400712 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500713 if (!part_settings->adbbackup && part_settings->generate_digest) {
714 if (!twrpDigestDriver::Make_Digest(Full_Filename))
715 goto backup_error;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400716 }
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400717
bigbiffce8f83c2015-12-12 18:30:21 -0500718 if (part_settings->Part->Has_SubPartition) {
Dees_Troy8170a922012-09-18 15:40:25 -0400719 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400720 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -0400721
722 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400723 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500724 part_settings->Part = *subpart;
bigbiffce8f83c2015-12-12 18:30:21 -0500725 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500726 goto backup_error;
Tom Hite5a926722014-09-15 01:31:03 +0000727 }
Dees_Troy2727b992013-08-14 20:09:30 +0000728 sync();
729 sync();
bigbiff bigbifff5955b12019-05-18 17:28:58 -0400730 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400731 if (!part_settings->adbbackup && part_settings->generate_digest) {
732 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500733 goto backup_error;
bigbiffce8f83c2015-12-12 18:30:21 -0500734 }
Tom Hite5a926722014-09-15 01:31:03 +0000735 }
Dees_Troy8170a922012-09-18 15:40:25 -0400736 }
737 }
738 }
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400739
Dees_Troy43d8b002012-09-17 16:00:01 -0400740 time(&stop);
that203bcc92015-05-09 17:27:33 +0200741 int backup_time = (int) difftime(stop, start);
Dees_Troy2673cec2013-04-02 20:22:16 +0000742 LOGINFO("Partition Backup time: %d\n", backup_time);
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400743
bigbiffce8f83c2015-12-12 18:30:21 -0500744 if (part_settings->Part->Backup_Method == BM_FILES) {
745 part_settings->file_time += backup_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400746 } else {
bigbiffce8f83c2015-12-12 18:30:21 -0500747 part_settings->img_time += backup_time;
748
Dees_Troy43d8b002012-09-17 16:00:01 -0400749 }
Tom Hite5a926722014-09-15 01:31:03 +0000750
Matt Mower02899552016-12-30 18:13:51 -0600751 TWFunc::SetPerformanceMode(false);
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500752 return true;
Dees_Troy43d8b002012-09-17 16:00:01 -0400753 }
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500754backup_error:
755 Clean_Backup_Folder(part_settings->Backup_Folder);
756 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
757 tw_set_default_metadata(backup_log.c_str());
758 TWFunc::SetPerformanceMode(false);
759 return false;
bigbiff7abc5fe2015-01-17 16:53:12 -0500760}
761
bigbiffbf1d6722015-02-14 16:25:59 -0500762void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
763 DIR *d = opendir(Backup_Folder.c_str());
764 struct dirent *p;
765 int r;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400766 vector<string> ext;
767
768 //extensions we should delete when cleaning
769 ext.push_back("win");
770 ext.push_back("md5");
771 ext.push_back("sha2");
772 ext.push_back("info");
bigbiffbf1d6722015-02-14 16:25:59 -0500773
Ethan Yonker74db1572015-10-28 12:44:49 -0500774 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
bigbiffbf1d6722015-02-14 16:25:59 -0500775
776 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500777 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
bigbiffbf1d6722015-02-14 16:25:59 -0500778 return;
779 }
780
Matt Mower2b18a532015-02-20 16:58:05 -0600781 while ((p = readdir(d))) {
bigbiffbf1d6722015-02-14 16:25:59 -0500782 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
783 continue;
784
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500785 string path = Backup_Folder + "/" + p->d_name;
bigbiffbf1d6722015-02-14 16:25:59 -0500786
787 size_t dot = path.find_last_of(".") + 1;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400788 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
789 if (path.substr(dot) == *i) {
790 r = unlink(path.c_str());
791 if (r != 0)
792 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
bigbiffbf1d6722015-02-14 16:25:59 -0500793 }
794 }
795 }
796 closedir(d);
797}
798
Ethan Yonker472f5062016-02-25 13:47:30 -0600799int TWPartitionManager::Check_Backup_Cancel() {
800 return stop_backup.get_value();
801}
802
bigbiff7abc5fe2015-01-17 16:53:12 -0500803int TWPartitionManager::Cancel_Backup() {
804 string Backup_Folder, Backup_Name, Full_Backup_Path;
805
806 stop_backup.set_value(1);
807
808 if (tar_fork_pid != 0) {
809 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
810 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500811 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
bigbiff7abc5fe2015-01-17 16:53:12 -0500812 LOGINFO("Killing pid: %d\n", tar_fork_pid);
813 kill(tar_fork_pid, SIGUSR2);
814 while (kill(tar_fork_pid, 0) == 0) {
815 usleep(1000);
816 }
817 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
818 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
819 TWFunc::removeDir(Full_Backup_Path, false);
820 tar_fork_pid = 0;
821 }
822
823 return 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400824}
825
bigbiffce8f83c2015-12-12 18:30:21 -0500826int TWPartitionManager::Run_Backup(bool adbbackup) {
827 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400828 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
bigbiffce8f83c2015-12-12 18:30:21 -0500829 string Backup_Name, Backup_List, backup_path;
Matt Mower23d8aae2017-01-06 14:30:33 -0600830 unsigned long long total_bytes = 0, free_space = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400831 TWPartition* storage = NULL;
Dees_Troy8170a922012-09-18 15:40:25 -0400832 std::vector<TWPartition*>::iterator subpart;
Dees_Troy43d8b002012-09-17 16:00:01 -0400833 struct tm *t;
Matt Mower23d8aae2017-01-06 14:30:33 -0600834 time_t seconds, total_start, total_stop;
Dees_Troya13d74f2013-03-24 08:54:55 -0500835 size_t start_pos = 0, end_pos = 0;
bigbiff7abc5fe2015-01-17 16:53:12 -0500836 stop_backup.set_value(0);
Dees_Troy43d8b002012-09-17 16:00:01 -0400837 seconds = time(0);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500838 t = localtime(&seconds);
Dees_Troy43d8b002012-09-17 16:00:01 -0400839
bigbiffce8f83c2015-12-12 18:30:21 -0500840 part_settings.img_bytes_remaining = 0;
841 part_settings.file_bytes_remaining = 0;
842 part_settings.img_time = 0;
843 part_settings.file_time = 0;
844 part_settings.img_bytes = 0;
845 part_settings.file_bytes = 0;
846 part_settings.PM_Method = PM_BACKUP;
847
bigbiffce8f83c2015-12-12 18:30:21 -0500848 part_settings.adbbackup = adbbackup;
Dees_Troy43d8b002012-09-17 16:00:01 -0400849 time(&total_start);
850
851 Update_System_Details();
852
853 if (!Mount_Current_Storage(true))
854 return false;
855
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400856 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
857 if (skip_digest == 0)
858 part_settings.generate_digest = true;
Dees_Troyc5865ab2012-09-24 15:08:04 -0400859 else
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400860 part_settings.generate_digest = false;
Dees_Troy4a2a1262012-09-18 09:33:47 -0400861
bigbiffce8f83c2015-12-12 18:30:21 -0500862 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500863 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
864 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
865 Backup_Name = TWFunc::Get_Current_Date();
866 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
Dees Troyb21cc642013-09-10 17:36:41 +0000867 TWFunc::Auto_Generate_Backup_Name();
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500868 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
Dees_Troy43d8b002012-09-17 16:00:01 -0400869 }
bigbiffce8f83c2015-12-12 18:30:21 -0500870
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500871 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500872 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
bigbiffce8f83c2015-12-12 18:30:21 -0500873
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500874 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -0400875
Dees_Troy2673cec2013-04-02 20:22:16 +0000876 LOGINFO("Calculating backup details...\n");
Dees_Troya13d74f2013-03-24 08:54:55 -0500877 DataManager::GetValue("tw_backup_list", Backup_List);
878 if (!Backup_List.empty()) {
879 end_pos = Backup_List.find(";", start_pos);
880 while (end_pos != string::npos && start_pos < Backup_List.size()) {
881 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -0500882 part_settings.Part = Find_Partition_By_Path(backup_path);
883 if (part_settings.Part != NULL) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500884 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -0500885 if (part_settings.Part->Backup_Method == BM_FILES)
886 part_settings.file_bytes += part_settings.Part->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500887 else
bigbiffce8f83c2015-12-12 18:30:21 -0500888 part_settings.img_bytes += part_settings.Part->Backup_Size;
889 if (part_settings.Part->Has_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500890 std::vector<TWPartition*>::iterator subpart;
891
892 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiffce8f83c2015-12-12 18:30:21 -0500893 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == part_settings.Part->Mount_Point) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500894 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -0500895 if ((*subpart)->Backup_Method == BM_FILES)
896 part_settings.file_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500897 else
bigbiffce8f83c2015-12-12 18:30:21 -0500898 part_settings.img_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500899 }
900 }
Dees_Troy8170a922012-09-18 15:40:25 -0400901 }
Dees_Troya13d74f2013-03-24 08:54:55 -0500902 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500903 gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
Dees_Troy8170a922012-09-18 15:40:25 -0400904 }
Dees_Troya13d74f2013-03-24 08:54:55 -0500905 start_pos = end_pos + 1;
906 end_pos = Backup_List.find(";", start_pos);
Dees_Troy43d8b002012-09-17 16:00:01 -0400907 }
908 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400909
910 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500911 gui_msg("no_partition_selected=No partitions selected for backup.");
Dees_Troy43d8b002012-09-17 16:00:01 -0400912 return false;
913 }
bigbiffce8f83c2015-12-12 18:30:21 -0500914 if (adbbackup) {
915 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
916 return false;
917 }
918 }
919 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
Ethan Yonker472f5062016-02-25 13:47:30 -0600920 ProgressTracking progress(total_bytes);
bigbiffce8f83c2015-12-12 18:30:21 -0500921 part_settings.progress = &progress;
922
Ethan Yonker74db1572015-10-28 12:44:49 -0500923 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
924 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -0400925 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
926 if (storage != NULL) {
927 free_space = storage->Free;
Ethan Yonker74db1572015-10-28 12:44:49 -0500928 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -0400929 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500930 gui_err("unable_locate_storage=Unable to locate storage device.");
Dees_Troy43d8b002012-09-17 16:00:01 -0400931 return false;
932 }
bigbiffbf1d6722015-02-14 16:25:59 -0500933
Matt Mowerbfccfb82016-04-25 23:22:31 -0500934 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
bigbiffce8f83c2015-12-12 18:30:21 -0500935
936 if (adbbackup)
937 disable_free_space_check = true;
938
bigbiffbf1d6722015-02-14 16:25:59 -0500939 if (!disable_free_space_check) {
940 if (free_space - (32 * 1024 * 1024) < total_bytes) {
941 // We require an extra 32MB just in case
Ethan Yonker74db1572015-10-28 12:44:49 -0500942 gui_err("no_space=Not enough free space on storage.");
bigbiffbf1d6722015-02-14 16:25:59 -0500943 return false;
944 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400945 }
bigbiffce8f83c2015-12-12 18:30:21 -0500946 part_settings.img_bytes_remaining = part_settings.img_bytes;
947 part_settings.file_bytes_remaining = part_settings.file_bytes;
Dees_Troy43d8b002012-09-17 16:00:01 -0400948
Ethan Yonker74db1572015-10-28 12:44:49 -0500949 gui_msg("backup_started=[BACKUP STARTED]");
bigbiff bigbiffcdd97c72019-03-29 19:12:33 -0400950
951 int is_decrypted = 0;
952 int is_encrypted = 0;
953
954 DataManager::GetValue(TW_IS_DECRYPTED, is_decrypted);
955 DataManager::GetValue(TW_IS_ENCRYPTED, is_encrypted);
956 if (!adbbackup || (!is_encrypted || (is_encrypted && is_decrypted))) {
957 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
958 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
959 gui_err("fail_backup_folder=Failed to make backup folder.");
960 return false;
961 }
Dees_Troyd4b22b02013-01-18 17:17:58 +0000962 }
963
Dees_Troy2673cec2013-04-02 20:22:16 +0000964 DataManager::SetProgress(0.0);
Dees_Troy093b7642012-09-21 15:59:38 -0400965
Dees_Troya13d74f2013-03-24 08:54:55 -0500966 start_pos = 0;
967 end_pos = Backup_List.find(";", start_pos);
968 while (end_pos != string::npos && start_pos < Backup_List.size()) {
bigbiff7abc5fe2015-01-17 16:53:12 -0500969 if (stop_backup.get_value() != 0)
970 return -1;
Dees_Troya13d74f2013-03-24 08:54:55 -0500971 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -0500972 part_settings.Part = Find_Partition_By_Path(backup_path);
973 if (part_settings.Part != NULL) {
974 if (!Backup_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -0500975 return false;
976 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500977 gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
Dees_Troya13d74f2013-03-24 08:54:55 -0500978 }
979 start_pos = end_pos + 1;
980 end_pos = Backup_List.find(";", start_pos);
981 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400982
983 // Average BPS
bigbiffce8f83c2015-12-12 18:30:21 -0500984 if (part_settings.img_time == 0)
985 part_settings.img_time = 1;
986 if (part_settings.file_time == 0)
987 part_settings.file_time = 1;
988 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
989 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400990
bigbiffce8f83c2015-12-12 18:30:21 -0500991 if (part_settings.file_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -0600992 gui_msg(Msg("avg_backup_fs=Average backup rate for file systems: {1} MB/sec")(file_bps / (1024 * 1024)));
bigbiffce8f83c2015-12-12 18:30:21 -0500993 if (part_settings.img_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -0600994 gui_msg(Msg("avg_backup_img=Average backup rate for imaged drives: {1} MB/sec")(img_bps / (1024 * 1024)));
Dees_Troy43d8b002012-09-17 16:00:01 -0400995
996 time(&total_stop);
997 int total_time = (int) difftime(total_stop, total_start);
bigbiffce8f83c2015-12-12 18:30:21 -0500998
999 uint64_t actual_backup_size;
Ethan Yonker3fdcda42016-11-30 12:29:37 -06001000 if (!adbbackup) {
1001 TWExclude twe;
1002 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
1003 } else
bigbiffce8f83c2015-12-12 18:30:21 -05001004 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001005 actual_backup_size /= (1024LLU * 1024LLU);
Dees_Troy43d8b002012-09-17 16:00:01 -04001006
bigbiffce8f83c2015-12-12 18:30:21 -05001007 int prev_img_bps = 0, use_compression = 0;
1008 unsigned long long prev_file_bps = 0;
Matt Mower173cdb92016-12-31 02:49:19 -06001009 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001010 img_bps += (prev_img_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001011 img_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001012
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001013 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -04001014 if (use_compression)
1015 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001016 else
Dees_Troy093b7642012-09-21 15:59:38 -04001017 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
1018 file_bps += (prev_file_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001019 file_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001020
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001021 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001022 if (use_compression)
1023 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
1024 else
1025 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
1026
Ethan Yonker74db1572015-10-28 12:44:49 -05001027 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Dees_Troy43d8b002012-09-17 16:00:01 -04001028 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001029 UnMount_Main_Partitions();
Ethan Yonker56db1c42015-12-20 22:49:00 -06001030 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001031 string backup_log = part_settings.Backup_Folder + "/recovery.log";
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001032 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -06001033 tw_set_default_metadata(backup_log.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001034
1035 if (part_settings.adbbackup) {
1036 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
1037 return false;
1038 }
1039 }
1040 part_settings.adbbackup = false;
1041 DataManager::SetValue("tw_enable_adb_backup", 0);
1042
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001043 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001044}
1045
bigbiffce8f83c2015-12-12 18:30:21 -05001046bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
Dees_Troy4a2a1262012-09-18 09:33:47 -04001047 time_t Start, Stop;
bigbiffce8f83c2015-12-12 18:30:21 -05001048
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001049 if (part_settings->adbbackup) {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001050 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
1051 LOGINFO("setting backup name: %s\n", partName.c_str());
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001052 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
1053 }
1054
Tom Hite5a926722014-09-15 01:31:03 +00001055 TWFunc::SetPerformanceMode(true);
bigbiffce8f83c2015-12-12 18:30:21 -05001056
Dees_Troy4a2a1262012-09-18 09:33:47 -04001057 time(&Start);
Ethan Yonker472f5062016-02-25 13:47:30 -06001058
bigbiffce8f83c2015-12-12 18:30:21 -05001059 if (!part_settings->Part->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001060 TWFunc::SetPerformanceMode(false);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001061 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001062 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001063 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
Dees_Troy8170a922012-09-18 15:40:25 -04001064 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001065 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -04001066
1067 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001068 part_settings->Part = *subpart;
1069 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1070 part_settings->Part = (*subpart);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001071 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
bigbiffce8f83c2015-12-12 18:30:21 -05001072 if (!(*subpart)->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001073 TWFunc::SetPerformanceMode(false);
Dees_Troy8170a922012-09-18 15:40:25 -04001074 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001075 }
Dees_Troy8170a922012-09-18 15:40:25 -04001076 }
1077 }
1078 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001079 time(&Stop);
Tom Hite5a926722014-09-15 01:31:03 +00001080 TWFunc::SetPerformanceMode(false);
bigbiffce8f83c2015-12-12 18:30:21 -05001081 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1082
Dees_Troy4a2a1262012-09-18 09:33:47 -04001083 return true;
1084}
1085
Ethan Yonker472f5062016-02-25 13:47:30 -06001086int TWPartitionManager::Run_Restore(const string& Restore_Name) {
bigbiffce8f83c2015-12-12 18:30:21 -05001087 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001088 int check_digest;
bigbiffce8f83c2015-12-12 18:30:21 -05001089
Dees_Troy4a2a1262012-09-18 09:33:47 -04001090 time_t rStart, rStop;
1091 time(&rStart);
Dees_Troya13d74f2013-03-24 08:54:55 -05001092 string Restore_List, restore_path;
1093 size_t start_pos = 0, end_pos;
bigbiffce8f83c2015-12-12 18:30:21 -05001094
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001095 part_settings.Backup_Folder = Restore_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001096 part_settings.Part = NULL;
1097 part_settings.partition_count = 0;
1098 part_settings.total_restore_size = 0;
1099 part_settings.adbbackup = false;
1100 part_settings.PM_Method = PM_RESTORE;
Dees_Troy43d8b002012-09-17 16:00:01 -04001101
Ethan Yonker74db1572015-10-28 12:44:49 -05001102 gui_msg("restore_started=[RESTORE STARTED]");
1103 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
Dees_Troy43d8b002012-09-17 16:00:01 -04001104
Dees_Troy4a2a1262012-09-18 09:33:47 -04001105 if (!Mount_Current_Storage(true))
1106 return false;
1107
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001108 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1109 if (check_digest > 0) {
1110 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1111 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1112 gui_msg("verifying_digest=Verifying Digest");
Dees_Troya13d74f2013-03-24 08:54:55 -05001113 } else {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001114 gui_msg("skip_digest=Skipping Digest check based on user setting.");
Dees_Troya13d74f2013-03-24 08:54:55 -05001115 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001116 gui_msg("calc_restore=Calculating restore details...");
Dees_Troya13d74f2013-03-24 08:54:55 -05001117 DataManager::GetValue("tw_restore_selected", Restore_List);
bigbiffce8f83c2015-12-12 18:30:21 -05001118
Dees_Troya13d74f2013-03-24 08:54:55 -05001119 if (!Restore_List.empty()) {
1120 end_pos = Restore_List.find(";", start_pos);
1121 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1122 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001123 part_settings.Part = Find_Partition_By_Path(restore_path);
1124 if (part_settings.Part != NULL) {
bigbiffce8f83c2015-12-12 18:30:21 -05001125 if (part_settings.Part->Mount_Read_Only) {
1126 gui_msg(Msg(msg::kError, "restore_read_only=Cannot restore {1} -- mounted read only.")(part_settings.Part->Backup_Display_Name));
Ethan Yonkereb32b1f2015-05-18 10:23:03 -05001127 return false;
1128 }
bigbiffce8f83c2015-12-12 18:30:21 -05001129
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001130 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1131
bigbiff35d2bfd2021-01-23 14:08:03 -05001132 if (tw_get_default_metadata(Get_Android_Root_Path().c_str()) != 0) {
1133 gui_msg(Msg(msg::kWarning, "restore_system_context=Unable to get default context for {1} -- Android may not boot.")(Get_Android_Root_Path()));
1134 }
1135
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001136 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001137 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001138 part_settings.partition_count++;
1139 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1140 if (part_settings.Part->Has_SubPartition) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001141 TWPartition *parentPart = part_settings.Part;
Dees_Troya13d74f2013-03-24 08:54:55 -05001142 std::vector<TWPartition*>::iterator subpart;
1143
1144 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001145 part_settings.Part = *subpart;
1146 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001147 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001148 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001149 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
Dees_Troya13d74f2013-03-24 08:54:55 -05001150 }
1151 }
1152 }
1153 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001154 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001155 }
1156 start_pos = end_pos + 1;
1157 end_pos = Restore_List.find(";", start_pos);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001158 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001159 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001160
bigbiffce8f83c2015-12-12 18:30:21 -05001161 if (part_settings.partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001162 gui_err("no_part_restore=No partitions selected for restore.");
Dees_Troy4a2a1262012-09-18 09:33:47 -04001163 return false;
1164 }
1165
bigbiffce8f83c2015-12-12 18:30:21 -05001166 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1167 gui_msg(Msg("total_restore_size=Total restore size is {1}MB")(part_settings.total_restore_size / 1048576));
Dees_Troy2673cec2013-04-02 20:22:16 +00001168 DataManager::SetProgress(0.0);
bigbiffce8f83c2015-12-12 18:30:21 -05001169 ProgressTracking progress(part_settings.total_restore_size);
1170 part_settings.progress = &progress;
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001171
Dees_Troya13d74f2013-03-24 08:54:55 -05001172 start_pos = 0;
1173 if (!Restore_List.empty()) {
1174 end_pos = Restore_List.find(";", start_pos);
1175 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1176 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001177
1178 part_settings.Part = Find_Partition_By_Path(restore_path);
1179 if (part_settings.Part != NULL) {
1180 part_settings.partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001181 if (!Restore_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001182 return false;
1183 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001184 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001185 }
1186 start_pos = end_pos + 1;
1187 end_pos = Restore_List.find(";", start_pos);
1188 }
1189 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001190 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
bigbiff35d2bfd2021-01-23 14:08:03 -05001191 tw_set_default_metadata(Get_Android_Root_Path().c_str());
Captain Throwback9d6feb52018-07-27 10:05:24 -04001192 UnMount_By_Path(Get_Android_Root_Path(), false);
Dees_Troy43d8b002012-09-17 16:00:01 -04001193 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001194 UnMount_Main_Partitions();
Dees_Troy4a2a1262012-09-18 09:33:47 -04001195 time(&rStop);
Matt Mower3c366972015-12-25 19:28:31 -06001196 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001197 DataManager::SetValue("tw_file_progress", "");
bigbiffce8f83c2015-12-12 18:30:21 -05001198
Dees_Troy63c8df72012-09-10 14:02:05 -04001199 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001200}
1201
1202void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001203 // Start with the default values
Dees_Troya13d74f2013-03-24 08:54:55 -05001204 string Restore_List;
Dees_Troy83bd4832013-05-04 12:39:56 +00001205 bool get_date = true, check_encryption = true;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001206 bool adbbackup = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001207
1208 DataManager::SetValue("tw_restore_encrypted", 0);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001209 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1210 vector<string> adb_files;
1211 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1212 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1213 string adb_restore_file = adb_files.at(i);
1214 std::size_t pos = adb_restore_file.find_first_of(".");
1215 std::string path = "/" + adb_restore_file.substr(0, pos);
1216 Restore_List = path + ";";
1217 TWPartition* Part = Find_Partition_By_Path(path);
1218 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1219 adbbackup = true;
1220 }
1221 DataManager::SetValue("tw_enable_adb_backup", 1);
Dees_Troy63c8df72012-09-10 14:02:05 -04001222 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001223 else {
1224 DIR* d;
1225 d = opendir(Restore_Name.c_str());
1226 if (d == NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001227 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001228 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1229 return;
Dees_Troy63c8df72012-09-10 14:02:05 -04001230 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001231
1232 struct dirent* de;
1233 while ((de = readdir(d)) != NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001234 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001235 // Strip off three components
1236 char str[256];
1237 char* label;
1238 char* fstype = NULL;
1239 char* extn = NULL;
1240 char* ptr;
Dees_Troy63c8df72012-09-10 14:02:05 -04001241
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001242 strcpy(str, de->d_name);
1243 if (strlen(str) <= 2)
1244 continue;
Dees_Troy83bd4832013-05-04 12:39:56 +00001245
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001246 if (get_date) {
1247 char file_path[255];
1248 struct stat st;
1249
1250 strcpy(file_path, Restore_Name.c_str());
1251 strcat(file_path, "/");
1252 strcat(file_path, str);
1253 stat(file_path, &st);
1254 string backup_date = ctime((const time_t*)(&st.st_mtime));
1255 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1256 get_date = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001257 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001258
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001259 label = str;
1260 ptr = label;
1261 while (*ptr && *ptr != '.') ptr++;
1262 if (*ptr == '.')
1263 {
1264 *ptr = 0x00;
1265 ptr++;
1266 fstype = ptr;
1267 }
1268 while (*ptr && *ptr != '.') ptr++;
1269 if (*ptr == '.')
1270 {
1271 *ptr = 0x00;
1272 ptr++;
1273 extn = ptr;
1274 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001275
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001276 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1277 int extnlength = strlen(extn);
1278 if (extnlength != 3 && extnlength != 6) continue;
1279 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1280 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
Dees_Troy63c8df72012-09-10 14:02:05 -04001281
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001282 if (check_encryption) {
1283 string filename = Restore_Name + "/";
1284 filename += de->d_name;
1285 if (TWFunc::Get_File_Type(filename) == 2) {
1286 LOGINFO("'%s' is encrypted\n", filename.c_str());
1287 DataManager::SetValue("tw_restore_encrypted", 1);
1288 }
1289 }
1290 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1291
1292 TWPartition* Part = Find_Partition_By_Path(label);
1293 if (Part == NULL)
1294 {
1295 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1296 continue;
1297 }
1298
1299 Part->Backup_FileName = de->d_name;
1300 if (strlen(extn) > 3) {
1301 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1302 }
1303
dianlujitaob76a73a2020-04-30 20:33:20 +08001304 if (!Part->Is_SubPartition) {
1305 if (Part->Backup_Path == Get_Android_Root_Path())
1306 Restore_List += "/system;";
1307 else
1308 Restore_List += Part->Backup_Path + ";";
1309 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001310 }
1311 closedir(d);
Dees_Troy63c8df72012-09-10 14:02:05 -04001312 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001313
1314 if (adbbackup) {
1315 Restore_List = "ADB_Backup;";
1316 adbbackup = false;
1317 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001318
Dees_Troya13d74f2013-03-24 08:54:55 -05001319 // Set the final value
1320 DataManager::SetValue("tw_restore_list", Restore_List);
1321 DataManager::SetValue("tw_restore_selected", Restore_List);
Dees_Troy51a0e822012-09-05 15:24:24 -04001322 return;
1323}
1324
1325int TWPartitionManager::Wipe_By_Path(string Path) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001326 std::vector<TWPartition*>::iterator iter;
Mohd Faraz77a31912020-04-21 18:56:44 +05301327 std::vector < TWPartition * >::iterator iter1;
Dees_Troy63c8df72012-09-10 14:02:05 -04001328 int ret = false;
1329 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -04001330 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy63c8df72012-09-10 14:02:05 -04001331
dianlujitaob76a73a2020-04-30 20:33:20 +08001332 if (Local_Path == "/system")
1333 Local_Path = Get_Android_Root_Path();
Dees_Troy63c8df72012-09-10 14:02:05 -04001334 // Iterate through all partitions
1335 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -04001336 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Mohd Faraz77a31912020-04-21 18:56:44 +05301337 // iterate through all partitions since some legacy devices uses other partitions as vendor causes issues while wiping
1338 (*iter)->Find_Actual_Block_Device();
1339 for (iter1 = Partitions.begin (); iter1 != Partitions.end (); iter1++)
1340 {
1341 (*iter1)->Find_Actual_Block_Device();
1342 if ((*iter)->Actual_Block_Device == (*iter1)->Actual_Block_Device && (*iter)->Mount_Point != (*iter1)->Mount_Point)
1343 (*iter1)->UnMount(false);
1344 }
Dees_Troye58d5262012-09-21 12:27:57 -04001345 if (Path == "/and-sec")
1346 ret = (*iter)->Wipe_AndSec();
1347 else
1348 ret = (*iter)->Wipe();
Dees_Troy63c8df72012-09-10 14:02:05 -04001349 found = true;
1350 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1351 (*iter)->Wipe();
1352 }
1353 }
1354 if (found) {
1355 return ret;
1356 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001357 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Dees_Troy63c8df72012-09-10 14:02:05 -04001358 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -04001359}
1360
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001361int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1362 std::vector<TWPartition*>::iterator iter;
1363 int ret = false;
1364 bool found = false;
1365 string Local_Path = TWFunc::Get_Root_Path(Path);
1366
1367 // Iterate through all partitions
1368 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1369 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1370 if (Path == "/and-sec")
1371 ret = (*iter)->Wipe_AndSec();
1372 else
1373 ret = (*iter)->Wipe(New_File_System);
1374 found = true;
1375 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1376 (*iter)->Wipe(New_File_System);
1377 }
1378 }
1379 if (found) {
1380 return ret;
1381 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001382 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001383 return false;
1384}
1385
Dees_Troy51a0e822012-09-05 15:24:24 -04001386int TWPartitionManager::Factory_Reset(void) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001387 std::vector<TWPartition*>::iterator iter;
1388 int ret = true;
1389
1390 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001391 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
Ethan Yonker89583ef2015-08-26 09:01:59 -05001392#ifdef TW_OEM_BUILD
1393 if ((*iter)->Mount_Point == "/data") {
1394 if (!(*iter)->Wipe_Encryption())
1395 ret = false;
1396 } else {
1397#endif
1398 if (!(*iter)->Wipe())
1399 ret = false;
1400#ifdef TW_OEM_BUILD
1401 }
1402#endif
Dees_Troy094207a2012-09-26 12:00:39 -04001403 } else if ((*iter)->Has_Android_Secure) {
1404 if (!(*iter)->Wipe_AndSec())
1405 ret = false;
Dees_Troy63c8df72012-09-10 14:02:05 -04001406 }
1407 }
Ethan Yonker9fa76ba2016-06-30 14:05:43 -05001408 TWFunc::check_and_run_script("/sbin/factoryreset.sh", "Factory Reset Script");
Dees_Troy63c8df72012-09-10 14:02:05 -04001409 return ret;
Dees_Troy51a0e822012-09-05 15:24:24 -04001410}
1411
Dees_Troy38bd7602012-09-14 13:33:53 -04001412int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1413 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001414 vector <string> dir;
Dees_Troy38bd7602012-09-14 13:33:53 -04001415
1416 if (!Mount_By_Path("/data", true))
1417 return false;
1418
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001419 dir.push_back("/data/dalvik-cache");
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001420
bigbiff349ea552020-06-19 16:07:38 -04001421 std::string cacheDir = TWFunc::get_log_dir();
1422 if (cacheDir == CACHE_LOGS_DIR) {
1423 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
1424 LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001425 }
1426 dir.push_back(cacheDir + "dalvik-cache");
1427 dir.push_back(cacheDir + "/dc");
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001428 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001429
Dees_Troy38bd7602012-09-14 13:33:53 -04001430 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001431 if (sdext && sdext->Is_Present && sdext->Mount(false))
1432 {
1433 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1434 {
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001435 dir.push_back("/sd-ext/dalvik-cache");
1436 }
1437 }
1438
bigbiff349ea552020-06-19 16:07:38 -04001439 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001440 gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
1441 } else {
1442 gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
1443 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001444 for (unsigned i = 0; i < dir.size(); ++i) {
1445 if (stat(dir.at(i).c_str(), &st) == 0) {
1446 TWFunc::removeDir(dir.at(i), false);
1447 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001448 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001449 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001450
bigbiff349ea552020-06-19 16:07:38 -04001451 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001452 gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1453 } else {
1454 gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
1455 }
1456
Dees_Troy38bd7602012-09-14 13:33:53 -04001457 return true;
1458}
1459
1460int TWPartitionManager::Wipe_Rotate_Data(void) {
1461 if (!Mount_By_Path("/data", true))
1462 return false;
1463
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001464 unlink("/data/misc/akmd*");
1465 unlink("/data/misc/rild*");
Dees_Troy2673cec2013-04-02 20:22:16 +00001466 gui_print("Rotation data wiped.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001467 return true;
1468}
1469
1470int TWPartitionManager::Wipe_Battery_Stats(void) {
1471 struct stat st;
1472
1473 if (!Mount_By_Path("/data", true))
1474 return false;
1475
1476 if (0 != stat("/data/system/batterystats.bin", &st)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001477 gui_print("No Battery Stats Found. No Need To Wipe.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001478 } else {
1479 remove("/data/system/batterystats.bin");
Dees_Troy2673cec2013-04-02 20:22:16 +00001480 gui_print("Cleared battery stats.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001481 }
1482 return true;
1483}
1484
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001485int TWPartitionManager::Wipe_Android_Secure(void) {
1486 std::vector<TWPartition*>::iterator iter;
1487 int ret = false;
1488 bool found = false;
1489
1490 // Iterate through all partitions
1491 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1492 if ((*iter)->Has_Android_Secure) {
1493 ret = (*iter)->Wipe_AndSec();
1494 found = true;
1495 }
1496 }
1497 if (found) {
1498 return ret;
1499 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001500 gui_err("no_andsec=No android secure partitions found.");
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001501 }
1502 return false;
1503}
1504
Dees_Troy38bd7602012-09-14 13:33:53 -04001505int TWPartitionManager::Format_Data(void) {
1506 TWPartition* dat = Find_Partition_By_Path("/data");
1507
1508 if (dat != NULL) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001509 return dat->Wipe_Encryption();
1510 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001511 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001512 return false;
1513 }
1514 return false;
1515}
1516
1517int TWPartitionManager::Wipe_Media_From_Data(void) {
1518 TWPartition* dat = Find_Partition_By_Path("/data");
1519
1520 if (dat != NULL) {
1521 if (!dat->Has_Data_Media) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001522 LOGERR("This device does not have /data/media\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001523 return false;
1524 }
1525 if (!dat->Mount(true))
1526 return false;
1527
Ethan Yonker74db1572015-10-28 12:44:49 -05001528 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
Ethan Yonker726a0202014-12-16 20:01:38 -06001529 Remove_MTP_Storage(dat->MTP_Storage_ID);
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001530 TWFunc::removeDir("/data/media", false);
xiaolu9416f4f2015-06-04 08:22:23 +08001531 dat->Recreate_Media_Folder();
Ethan Yonker726a0202014-12-16 20:01:38 -06001532 Add_MTP_Storage(dat->MTP_Storage_ID);
Dees_Troy38bd7602012-09-14 13:33:53 -04001533 return true;
1534 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001535 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001536 return false;
1537 }
1538 return false;
1539}
1540
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001541int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1542 std::vector<TWPartition*>::iterator iter;
1543 int ret = false;
1544 bool found = false;
1545 string Local_Path = TWFunc::Get_Root_Path(Path);
1546
1547 if (Local_Path == "/tmp" || Local_Path == "/")
1548 return true;
1549
1550 // Iterate through all partitions
1551 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1552 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1553 ret = (*iter)->Repair();
1554 found = true;
1555 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1556 (*iter)->Repair();
1557 }
1558 }
1559 if (found) {
1560 return ret;
1561 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001562 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001563 } else {
1564 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1565 }
1566 return false;
1567}
1568
Ethan Yonkera2719152015-05-28 09:44:41 -05001569int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1570 std::vector<TWPartition*>::iterator iter;
1571 int ret = false;
1572 bool found = false;
1573 string Local_Path = TWFunc::Get_Root_Path(Path);
1574
1575 if (Local_Path == "/tmp" || Local_Path == "/")
1576 return true;
1577
1578 // Iterate through all partitions
1579 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1580 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1581 ret = (*iter)->Resize();
1582 found = true;
1583 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1584 (*iter)->Resize();
1585 }
1586 }
1587 if (found) {
1588 return ret;
1589 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001590 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
Ethan Yonkera2719152015-05-28 09:44:41 -05001591 } else {
1592 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1593 }
1594 return false;
1595}
1596
Dees_Troy51a0e822012-09-05 15:24:24 -04001597void TWPartitionManager::Update_System_Details(void) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001598 std::vector<TWPartition*>::iterator iter;
Dees_Troy51127312012-09-08 13:08:49 -04001599 int data_size = 0;
Dees_Troy5bf43922012-09-07 16:07:55 -04001600
Ethan Yonker74db1572015-10-28 12:44:49 -05001601 gui_msg("update_part_details=Updating partition details...");
Dees_Troy5bf43922012-09-07 16:07:55 -04001602 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker1b190162016-12-05 15:25:19 -06001603 (*iter)->Update_Size(true);
Dees_Troy51127312012-09-08 13:08:49 -04001604 if ((*iter)->Can_Be_Mounted) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001605 if ((*iter)->Mount_Point == Get_Android_Root_Path()) {
Dees_Troy51127312012-09-08 13:08:49 -04001606 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1607 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001608 TWFunc::Is_TWRP_App_In_System();
Dees_Troy51127312012-09-08 13:08:49 -04001609 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1610 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1611 } else if ((*iter)->Mount_Point == "/cache") {
1612 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1613 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1614 } else if ((*iter)->Mount_Point == "/sd-ext") {
1615 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1616 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1617 if ((*iter)->Backup_Size == 0) {
1618 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1619 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1620 } else
1621 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
Dees_Troye58d5262012-09-21 12:27:57 -04001622 } else if ((*iter)->Has_Android_Secure) {
Dees_Troy8170a922012-09-18 15:40:25 -04001623 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troye58d5262012-09-21 12:27:57 -04001624 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
Dees_Troy8170a922012-09-18 15:40:25 -04001625 if ((*iter)->Backup_Size == 0) {
1626 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1627 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1628 } else
1629 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
Dees_Troy2c50e182012-09-26 20:05:28 -04001630 } else if ((*iter)->Mount_Point == "/boot") {
1631 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1632 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1633 if ((*iter)->Backup_Size == 0) {
1634 DataManager::SetValue("tw_has_boot_partition", 0);
1635 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1636 } else
1637 DataManager::SetValue("tw_has_boot_partition", 1);
Dees_Troy51127312012-09-08 13:08:49 -04001638 }
Dees_Troyaa9cc402012-10-13 12:14:05 -04001639 } else {
1640 // Handle unmountable partitions in case we reset defaults
1641 if ((*iter)->Mount_Point == "/boot") {
1642 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1643 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1644 if ((*iter)->Backup_Size == 0) {
1645 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1646 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1647 } else
1648 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1649 } else if ((*iter)->Mount_Point == "/recovery") {
1650 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1651 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1652 if ((*iter)->Backup_Size == 0) {
1653 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1654 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1655 } else
1656 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
Gary Peck82599a82012-11-21 16:23:12 -08001657 } else if ((*iter)->Mount_Point == "/data") {
1658 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troyaa9cc402012-10-13 12:14:05 -04001659 }
Dees_Troy51127312012-09-08 13:08:49 -04001660 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001661 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001662 gui_msg("update_part_details_done=...done");
Dees_Troy51127312012-09-08 13:08:49 -04001663 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1664 string current_storage_path = DataManager::GetCurrentStoragePath();
1665 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
Dees_Troy8170a922012-09-18 15:40:25 -04001666 if (FreeStorage != NULL) {
1667 // Attempt to mount storage
1668 if (!FreeStorage->Mount(false)) {
Matt Mower2d50cad2015-12-03 22:26:55 -06001669 gui_msg(Msg(msg::kError, "unable_to_mount_storage=Unable to mount storage"));
1670 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
Dees_Troy8170a922012-09-18 15:40:25 -04001671 } else {
1672 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
1673 }
1674 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00001675 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
Dees_Troy8170a922012-09-18 15:40:25 -04001676 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001677 if (!Write_Fstab())
Dees_Troy2673cec2013-04-02 20:22:16 +00001678 LOGERR("Error creating fstab\n");
Dees_Troy51a0e822012-09-05 15:24:24 -04001679 return;
1680}
1681
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001682void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1683 TWPartition* dat = Find_Partition_By_Path("/data");
1684 if (dat != NULL) {
1685 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1686 dat->Is_Decrypted = true;
1687 if (!Block_Device.empty()) {
1688 dat->Decrypted_Block_Device = Block_Device;
1689 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1690 } else {
1691 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1692 }
Noah Jacobson5a79f672019-04-28 00:10:07 -04001693 property_set("twrp.decrypt.done", "true");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001694 dat->Setup_File_System(false);
Noah Jacobson5a79f672019-04-28 00:10:07 -04001695 dat->Current_File_System = dat->Fstab_File_System; // Needed if we're ignoring blkid because encrypted devices start out as emmc
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001696
Noah Jacobson5a79f672019-04-28 00:10:07 -04001697 sleep(1); // Sleep for a bit so that the device will be ready
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001698 if (dat->Has_Data_Media && dat->Mount(false) && TWFunc::Path_Exists("/data/media/0")) {
1699 dat->Storage_Path = "/data/media/0";
1700 dat->Symlink_Path = dat->Storage_Path;
1701 DataManager::SetValue("tw_storage_path", "/data/media/0");
1702 DataManager::SetValue("tw_settings_path", "/data/media/0");
1703 dat->UnMount(false);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001704 }
epicX98053c32021-01-04 13:01:31 +05301705 DataManager::LoadTWRPFolderInfo();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001706 Update_System_Details();
nkk71ffb02bd2017-06-04 23:12:16 +03001707 Output_Partition(dat);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001708 UnMount_Main_Partitions();
1709 } else
1710 LOGERR("Unable to locate data partition.\n");
1711}
1712
Noah Jacobson5a79f672019-04-28 00:10:07 -04001713void TWPartitionManager::Parse_Users() {
1714#ifdef TW_INCLUDE_FBE
1715 char user_check_result[PROPERTY_VALUE_MAX];
1716 for (int userId = 0; userId <= 9999; userId++) {
1717 string prop = "twrp.user." + to_string(userId) + ".decrypt";
1718 property_get(prop.c_str(), user_check_result, "-1");
1719 if (strcmp(user_check_result, "-1") != 0) {
1720 if (userId < 0 || userId > 9999) {
1721 LOGINFO("Incorrect user id %d\n", userId);
1722 continue;
1723 }
1724 struct users_struct user;
1725 user.userId = to_string(userId);
1726
1727 // Attempt to get name of user. Fallback to user ID if this fails.
1728 char* userFile = PageManager::LoadFileToBuffer("/data/system/users/" + to_string(userId) + ".xml", NULL);
1729 if (userFile == NULL)
1730 user.userName = to_string(userId);
1731 else {
1732 xml_document<> *userXml = new xml_document<>();
1733 userXml->parse<0>(userFile);
1734 xml_node<>* userNode = userXml->first_node("user");
1735 if (userNode == nullptr) {
1736 user.userName = to_string(userId);
1737 } else {
1738 xml_node<>* nameNode = userNode->first_node("name");
1739 if (nameNode == nullptr)
1740 user.userName = to_string(userId);
1741 else {
1742 string userName = nameNode->value();
1743 user.userName = userName + " (" + to_string(userId) + ")";
1744 }
1745 }
1746 }
1747
1748 string filename;
1749 user.type = Get_Password_Type(userId, filename);
1750
1751 user.isDecrypted = false;
1752 if (strcmp(user_check_result, "1") == 0)
1753 user.isDecrypted = true;
1754 Users_List.push_back(user);
1755 }
1756 }
1757 Check_Users_Decryption_Status();
1758#endif
1759}
1760
1761std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
1762 return &Users_List;
1763}
1764
1765void TWPartitionManager::Mark_User_Decrypted(int userID) {
1766#ifdef TW_INCLUDE_FBE
1767 std::vector<users_struct>::iterator iter;
1768 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1769 if (atoi((*iter).userId.c_str()) == userID) {
1770 (*iter).isDecrypted = true;
1771 string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
1772 property_set(user_prop_decrypted.c_str(), "1");
1773 break;
1774 }
1775 }
1776 Check_Users_Decryption_Status();
1777#endif
1778}
1779
1780void TWPartitionManager::Check_Users_Decryption_Status() {
1781#ifdef TW_INCLUDE_FBE
1782 int all_is_decrypted = 1;
1783 std::vector<users_struct>::iterator iter;
1784 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1785 if (!(*iter).isDecrypted) {
Noah Jacobsonbf0b0fb2020-06-05 12:47:20 -04001786 LOGINFO("User %s is not decrypted.\n", (*iter).userId.c_str());
Noah Jacobson5a79f672019-04-28 00:10:07 -04001787 all_is_decrypted = 0;
1788 break;
1789 }
1790 }
1791 if (all_is_decrypted == 1) {
Noah Jacobsonbf0b0fb2020-06-05 12:47:20 -04001792 LOGINFO("All found users are decrypted.\n");
Noah Jacobson5a79f672019-04-28 00:10:07 -04001793 DataManager::SetValue("tw_all_users_decrypted", "1");
1794 property_set("twrp.all.users.decrypted", "true");
1795 } else
1796 DataManager::SetValue("tw_all_users_decrypted", "0");
1797#endif
1798}
1799
1800int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001801#ifdef TW_INCLUDE_CRYPTO
Ethan Yonkerddb63e22017-01-19 14:01:57 -06001802 char crypto_state[PROPERTY_VALUE_MAX], crypto_blkdev[PROPERTY_VALUE_MAX];
Ethan Yonker253368a2014-11-25 15:00:52 -06001803 std::vector<TWPartition*>::iterator iter;
Dees_Troy5bf43922012-09-07 16:07:55 -04001804
Ethan Yonker253368a2014-11-25 15:00:52 -06001805 // Mount any partitions that need to be mounted for decrypt
1806 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1807 if ((*iter)->Mount_To_Decrypt) {
1808 (*iter)->Mount(true);
1809 }
a39552696ff55ce2013-01-08 16:14:56 +00001810 }
oshmouna82a7542018-04-10 17:45:55 +02001811 property_set("twrp.mount_to_decrypt", "1");
a39552696ff55ce2013-01-08 16:14:56 +00001812
Ethan Yonkera1de1492015-11-04 11:58:27 -06001813 property_get("ro.crypto.state", crypto_state, "error");
1814 if (strcmp(crypto_state, "error") == 0) {
Captain Throwback07b8e052020-10-29 12:43:17 -04001815 Set_FDE_Encrypt_Status();
Ethan Yonkera1de1492015-11-04 11:58:27 -06001816 }
1817
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001818 if (DataManager::GetIntValue(TW_IS_FBE)) {
1819#ifdef TW_INCLUDE_FBE
1820 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
1821 return -1;
Noah Jacobson5a79f672019-04-28 00:10:07 -04001822
1823 bool user_need_decrypt = false;
1824 std::vector<users_struct>::iterator iter;
1825 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1826 if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
1827 user_need_decrypt = true;
1828 }
1829 }
1830 if (!user_need_decrypt) {
1831 LOGINFO("User %d does not require decryption\n", user_id);
1832 return 0;
1833 }
1834
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001835 int retry_count = 10;
1836 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
Noah Jacobson5a79f672019-04-28 00:10:07 -04001837 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
1838 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001839 if (Decrypt_User(user_id, Password)) {
Noah Jacobson5a79f672019-04-28 00:10:07 -04001840 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
1841 Mark_User_Decrypted(user_id);
1842 if (user_id == 0) {
1843 // When decrypting user 0 also try all other users
1844 std::vector<users_struct>::iterator iter;
1845 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1846 if ((*iter).userId == "0" || (*iter).isDecrypted)
1847 continue;
1848
1849 int tmp_user_id = atoi((*iter).userId.c_str());
1850 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
1851 if (Decrypt_User(tmp_user_id, Password) ||
1852 (Password != "!" && Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
1853 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
1854 Mark_User_Decrypted(tmp_user_id);
1855 } else {
1856 gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
1857 }
1858 }
1859 Post_Decrypt("");
1860 }
1861
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001862 return 0;
Noah Jacobson5a79f672019-04-28 00:10:07 -04001863 } else {
1864 gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001865 }
1866#else
1867 LOGERR("FBE support is not present\n");
1868#endif
1869 return -1;
1870 }
1871
Noah Jacobson5a79f672019-04-28 00:10:07 -04001872 char isdecrypteddata[PROPERTY_VALUE_MAX];
1873 property_get("twrp.decrypt.done", isdecrypteddata, "");
1874 if (strcmp(isdecrypteddata, "true") == 0) {
1875 LOGINFO("Data has no decryption required\n");
1876 return 0;
1877 }
1878
Ethan Yonkerddb63e22017-01-19 14:01:57 -06001879 int pwret = -1;
1880 pid_t pid = fork();
1881 if (pid < 0) {
1882 LOGERR("fork failed\n");
1883 return -1;
1884 } else if (pid == 0) {
1885 // Child process
1886 char cPassword[255];
1887 strcpy(cPassword, Password.c_str());
1888 int ret = cryptfs_check_passwd(cPassword);
1889 exit(ret);
1890 } else {
1891 // Parent
1892 int status;
1893 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
1894 pwret = -1;
1895 else
1896 pwret = WEXITSTATUS(status) ? -1 : 0;
1897 }
a39552696ff55ce2013-01-08 16:14:56 +00001898
nkk7171c6c502017-01-05 23:55:05 +02001899#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
1900 if (pwret != 0) {
1901 pwret = vold_decrypt(Password);
nkk717d1222a2017-11-06 17:27:21 +02001902 switch (pwret) {
1903 case VD_SUCCESS:
1904 break;
1905 case VD_ERR_MISSING_VDC:
1906 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vdc"));
1907 break;
1908 case VD_ERR_MISSING_VOLD:
1909 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vold"));
1910 break;
1911 }
nkk7171c6c502017-01-05 23:55:05 +02001912 }
1913#endif // TW_CRYPTO_USE_SYSTEM_VOLD
1914
Ethan Yonker253368a2014-11-25 15:00:52 -06001915 // Unmount any partitions that were needed for decrypt
1916 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1917 if ((*iter)->Mount_To_Decrypt) {
1918 (*iter)->UnMount(false);
1919 }
1920 }
oshmouna82a7542018-04-10 17:45:55 +02001921 property_set("twrp.mount_to_decrypt", "0");
Ethan Yonker253368a2014-11-25 15:00:52 -06001922
a39552696ff55ce2013-01-08 16:14:56 +00001923 if (pwret != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001924 gui_err("fail_decrypt=Failed to decrypt data.");
Dees_Troy5bf43922012-09-07 16:07:55 -04001925 return -1;
1926 }
a39552696ff55ce2013-01-08 16:14:56 +00001927
Dees_Troy5bf43922012-09-07 16:07:55 -04001928 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
1929 if (strcmp(crypto_blkdev, "error") == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001930 LOGERR("Error retrieving decrypted data block device.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -04001931 } else {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001932 Post_Decrypt(crypto_blkdev);
Dees_Troy5bf43922012-09-07 16:07:55 -04001933 }
1934 return 0;
1935#else
Ethan Yonker74db1572015-10-28 12:44:49 -05001936 gui_err("no_crypto_support=No crypto support was compiled into this build.");
Dees_Troy5bf43922012-09-07 16:07:55 -04001937 return -1;
1938#endif
Dees_Troy51a0e822012-09-05 15:24:24 -04001939 return 1;
Dees_Troy51127312012-09-08 13:08:49 -04001940}
1941
Ethan Yonkerb5fab762016-01-28 14:03:33 -06001942int TWPartitionManager::Fix_Contexts(void) {
Ethan Yonkerb5fab762016-01-28 14:03:33 -06001943 std::vector<TWPartition*>::iterator iter;
1944 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1945 if ((*iter)->Has_Data_Media) {
1946 if ((*iter)->Mount(true)) {
1947 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
1948 return -1;
1949 }
1950 }
1951 }
Dees_Troy1a650e62012-10-19 20:54:32 -04001952 UnMount_Main_Partitions();
Ethan Yonker74db1572015-10-28 12:44:49 -05001953 gui_msg("done=Done.");
Ethan Yonkerb5fab762016-01-28 14:03:33 -06001954 return 0;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04001955}
1956
Ethan Yonker66a19492015-12-10 10:19:45 -06001957TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
Ethan Yonker47360be2014-04-01 10:34:34 -05001958 std::vector<TWPartition*>::iterator iter = Partitions.begin();
1959
1960 if (!Path.empty()) {
1961 string Search_Path = TWFunc::Get_Root_Path(Path);
1962 for (; iter != Partitions.end(); iter++) {
Matt Mower9a561dd2016-02-22 21:25:51 -06001963 if ((*iter)->Mount_Point == Search_Path) {
Ethan Yonker47360be2014-04-01 10:34:34 -05001964 iter++;
1965 break;
1966 }
1967 }
1968 }
1969
1970 for (; iter != Partitions.end(); iter++) {
Ethan Yonker66a19492015-12-10 10:19:45 -06001971 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
1972 // do nothing, do not return this type of partition
1973 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
Ethan Yonker47360be2014-04-01 10:34:34 -05001974 return (*iter);
1975 }
1976 }
1977
1978 return NULL;
1979}
1980
Dees_Troyd21618c2012-10-14 18:48:49 -04001981int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
Dees_Troyd21618c2012-10-14 18:48:49 -04001982 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
1983
1984 if (Part == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001985 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
1986 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Partition_Path));
Dees_Troyd21618c2012-10-14 18:48:49 -04001987 return false;
1988 }
Ethan Yonker47360be2014-04-01 10:34:34 -05001989 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
1990 if (!Part->UnMount(true) || !Part->Is_Present)
Dees_Troyd21618c2012-10-14 18:48:49 -04001991 return false;
1992
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001993 if (TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001994 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
Dees_Troyd21618c2012-10-14 18:48:49 -04001995 return false;
1996 }
Dees_Troyd21618c2012-10-14 18:48:49 -04001997 return true;
1998}
1999
Dees_Troy8170a922012-09-18 15:40:25 -04002000int TWPartitionManager::usb_storage_enable(void) {
Dees_Troy8170a922012-09-18 15:40:25 -04002001 char lun_file[255];
Dees_Troyd21618c2012-10-14 18:48:49 -04002002 bool has_multiple_lun = false;
Dees_Troy8170a922012-09-18 15:40:25 -04002003
Ethan Yonker47360be2014-04-01 10:34:34 -05002004 string Lun_File_str = CUSTOM_LUN_FILE;
2005 size_t found = Lun_File_str.find("%");
2006 if (found != string::npos) {
2007 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
2008 if (TWFunc::Path_Exists(lun_file))
2009 has_multiple_lun = true;
2010 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002011 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
Ethan Yonker47360be2014-04-01 10:34:34 -05002012 if (!has_multiple_lun) {
2013 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
2014 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
2015 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
Ethan Yonker66a19492015-12-10 10:19:45 -06002016 TWPartition* Mount = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002017 if (Mount) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002018 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
2019 goto error_handle;
2020 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002021 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002022 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002023 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002024 }
2025 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002026 goto error_handle;
Dees_Troy8170a922012-09-18 15:40:25 -04002027 }
Dees_Troy8170a922012-09-18 15:40:25 -04002028 } else {
Ethan Yonker47360be2014-04-01 10:34:34 -05002029 LOGINFO("Device has multiple lun files\n");
2030 TWPartition* Mount1;
2031 TWPartition* Mount2;
Dees_Troy8170a922012-09-18 15:40:25 -04002032 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
Ethan Yonker66a19492015-12-10 10:19:45 -06002033 Mount1 = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002034 if (Mount1) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002035 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
2036 goto error_handle;
2037 }
Matt Moweree717062014-04-26 01:46:46 -05002038 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
Ethan Yonker66a19492015-12-10 10:19:45 -06002039 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
Matt Mower1fdcdb72016-01-25 20:53:47 -06002040 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
Matt Moweree717062014-04-26 01:46:46 -05002041 Open_Lun_File(Mount2->Mount_Point, lun_file);
Ethan Yonker47360be2014-04-01 10:34:34 -05002042 }
2043 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002044 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002045 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002046 }
Dees_Troy8170a922012-09-18 15:40:25 -04002047 }
Matt Mowerb6ef4782014-11-06 02:24:36 -06002048 property_set("sys.storage.ums_enabled", "1");
HandyMenny37d42992014-10-26 22:15:59 +01002049 property_set("sys.usb.config", "mass_storage,adb");
Dees_Troy8170a922012-09-18 15:40:25 -04002050 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002051error_handle:
2052 if (mtp_was_enabled)
2053 if (!Enable_MTP())
2054 Disable_MTP();
2055 return false;
Dees_Troy8170a922012-09-18 15:40:25 -04002056}
2057
2058int TWPartitionManager::usb_storage_disable(void) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002059 int index, ret;
2060 char lun_file[255], ch[2] = {0, 0};
2061 string str = ch;
Dees_Troy8170a922012-09-18 15:40:25 -04002062
2063 for (index=0; index<2; index++) {
2064 sprintf(lun_file, CUSTOM_LUN_FILE, index);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002065 ret = TWFunc::write_to_file(lun_file, str);
Dees_Troy2673cec2013-04-02 20:22:16 +00002066 if (ret < 0) {
2067 break;
Dees_Troy8170a922012-09-18 15:40:25 -04002068 }
Dees_Troy8170a922012-09-18 15:40:25 -04002069 }
Dees_Troye58d5262012-09-21 12:27:57 -04002070 Mount_All_Storage();
2071 Update_System_Details();
Dees_Troycfd73ef2012-10-12 16:52:00 -04002072 UnMount_Main_Partitions();
Matt Mowerd9cb9062013-12-14 20:34:45 -06002073 property_set("sys.storage.ums_enabled", "0");
HandyMenny37d42992014-10-26 22:15:59 +01002074 property_set("sys.usb.config", "adb");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002075 if (mtp_was_enabled)
2076 if (!Enable_MTP())
2077 Disable_MTP();
Dees_Troy2673cec2013-04-02 20:22:16 +00002078 if (ret < 0 && index == 0) {
2079 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
2080 return false;
2081 } else {
2082 return true;
2083 }
Dees_Troy8170a922012-09-18 15:40:25 -04002084 return true;
Dees_Troy812660f2012-09-20 09:55:17 -04002085}
2086
2087void TWPartitionManager::Mount_All_Storage(void) {
2088 std::vector<TWPartition*>::iterator iter;
2089
2090 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2091 if ((*iter)->Is_Storage)
2092 (*iter)->Mount(false);
2093 }
Dees_Troy2c50e182012-09-26 20:05:28 -04002094}
Dees_Troy9350b8d2012-09-27 12:38:38 -04002095
Dees_Troyd0384ef2012-10-12 12:15:42 -04002096void TWPartitionManager::UnMount_Main_Partitions(void) {
2097 // Unmounts system and data if data is not data/media
2098 // Also unmounts boot if boot is mountable
Dees_Troy2673cec2013-04-02 20:22:16 +00002099 LOGINFO("Unmounting main partitions...\n");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002100
2101 TWPartition* Boot_Partition = Find_Partition_By_Path("/boot");
2102
Captain Throwback9d6feb52018-07-27 10:05:24 -04002103 UnMount_By_Path(Get_Android_Root_Path(), true);
Ethan Yonker6277c792014-09-15 14:54:30 -05002104 if (!datamedia)
2105 UnMount_By_Path("/data", true);
2106
Dees_Troyd0384ef2012-10-12 12:15:42 -04002107 if (Boot_Partition != NULL && Boot_Partition->Can_Be_Mounted)
2108 Boot_Partition->UnMount(true);
2109}
2110
Dees_Troy9350b8d2012-09-27 12:38:38 -04002111int TWPartitionManager::Partition_SDCard(void) {
Matt Mower23d8aae2017-01-06 14:30:33 -06002112 char temp[255];
Ethan Yonker483e9f42016-01-11 22:21:18 -06002113 string Storage_Path, Command, Device, fat_str, ext_str, start_loc, end_loc, ext_format, sd_path, tmpdevice;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002114 int ext, swap, total_size = 0, fat_size;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002115
Ethan Yonker74db1572015-10-28 12:44:49 -05002116 gui_msg("start_partition_sd=Partitioning SD Card...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002117
2118 // Locate and validate device to partition
2119 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
2120
Ethan Yonker66a19492015-12-10 10:19:45 -06002121 if (SDCard->Is_Adopted_Storage)
2122 SDCard->Revert_Adopted();
2123
Ethan Yonker1eff6cd2014-09-15 13:30:42 -05002124 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002125 gui_err("partition_sd_locate=Unable to locate device to partition.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002126 return false;
2127 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002128
2129 // Unmount everything
Dees_Troy9350b8d2012-09-27 12:38:38 -04002130 if (!SDCard->UnMount(true))
2131 return false;
2132 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
2133 if (SDext != NULL) {
2134 if (!SDext->UnMount(true))
2135 return false;
2136 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002137 char* swappath = getenv("SWAPPATH");
2138 if (swappath != NULL) {
2139 LOGINFO("Unmounting swap at '%s'\n", swappath);
2140 umount(swappath);
2141 }
Vojtech Bocek05534202013-09-11 08:11:56 +02002142
Ethan Yonker483e9f42016-01-11 22:21:18 -06002143 // Determine block device
2144 if (SDCard->Alternate_Block_Device.empty()) {
2145 SDCard->Find_Actual_Block_Device();
2146 Device = SDCard->Actual_Block_Device;
2147 // Just use the root block device
2148 Device.resize(strlen("/dev/block/mmcblkX"));
2149 } else {
2150 Device = SDCard->Alternate_Block_Device;
2151 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002152
2153 // Find the size of the block device:
Ethan Yonker483e9f42016-01-11 22:21:18 -06002154 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002155
2156 DataManager::GetValue("tw_sdext_size", ext);
2157 DataManager::GetValue("tw_swap_size", swap);
2158 DataManager::GetValue("tw_sdpart_file_system", ext_format);
2159 fat_size = total_size - ext - swap;
Ethan Yonker483e9f42016-01-11 22:21:18 -06002160 LOGINFO("sd card mount point %s block device is '%s', sdcard size is: %iMB, fat size: %iMB, ext size: %iMB, ext system: '%s', swap size: %iMB\n", DataManager::GetCurrentStoragePath().c_str(), Device.c_str(), total_size, fat_size, ext, ext_format.c_str(), swap);
2161
2162 // Determine partition sizes
2163 if (swap == 0 && ext == 0) {
2164 fat_str = "-0";
2165 } else {
2166 memset(temp, 0, sizeof(temp));
2167 sprintf(temp, "%i", fat_size);
2168 fat_str = temp;
2169 fat_str += "MB";
2170 }
2171 if (swap == 0) {
2172 ext_str = "-0";
2173 } else {
2174 memset(temp, 0, sizeof(temp));
2175 sprintf(temp, "%i", ext);
2176 ext_str = "+";
2177 ext_str += temp;
2178 ext_str += "MB";
2179 }
2180
Dees_Troy9350b8d2012-09-27 12:38:38 -04002181 if (ext + swap > total_size) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002182 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002183 return false;
2184 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002185
Ethan Yonker74db1572015-10-28 12:44:49 -05002186 gui_msg("remove_part_table=Removing partition table...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002187 Command = "sgdisk --zap-all " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002188 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002189 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002190 gui_err("unable_rm_part=Unable to remove partition table.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002191 Update_System_Details();
2192 return false;
2193 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002194 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
Captain Throwback9643a802016-05-27 11:44:51 -04002195 Command = "sgdisk --new=0:0:" + fat_str + " --change-name=0:\"Microsoft basic data\" --typecode=0:EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002196 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002197 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002198 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002199 return false;
2200 }
2201 if (ext > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002202 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002203 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002204 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002205 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002206 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002207 Update_System_Details();
2208 return false;
2209 }
2210 }
2211 if (swap > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002212 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002213 Command = "sgdisk --new=0:0:-0 --change-name=0:\"Linux swap\" --typecode=0:0657FD6D-A4AB-43C4-84E5-0933C84B4F4F " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002214 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002215 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002216 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002217 Update_System_Details();
2218 return false;
2219 }
2220 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002221
2222 // Convert GPT to MBR
2223 Command = "sgdisk --gpttombr " + Device;
2224 if (TWFunc::Exec_Cmd(Command) != 0)
2225 LOGINFO("Failed to covert partition GPT to MBR\n");
2226
2227 // Tell the kernel to rescan the partition table
2228 int fd = open(Device.c_str(), O_RDONLY);
2229 ioctl(fd, BLKRRPART, 0);
2230 close(fd);
2231
2232 string format_device = Device;
2233 if (Device.substr(0, 17) == "/dev/block/mmcblk")
2234 format_device += "p";
2235
2236 // Format new partitions to proper file system
2237 if (fat_size > 0) {
2238 Command = "mkfs.fat " + format_device + "1";
2239 TWFunc::Exec_Cmd(Command);
2240 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002241 if (ext > 0) {
2242 if (SDext == NULL) {
Ethan Yonker483e9f42016-01-11 22:21:18 -06002243 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2244 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2245 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2246 TWFunc::Exec_Cmd(Command);
2247 } else {
2248 SDext->Wipe(ext_format);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002249 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002250 }
2251 if (swap > 0) {
2252 Command = "mkswap " + format_device;
2253 if (ext > 0)
2254 Command += "3";
2255 else
2256 Command += "2";
Vojtech Bocek05534202013-09-11 08:11:56 +02002257 TWFunc::Exec_Cmd(Command);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002258 }
2259
Ethan Yonker483e9f42016-01-11 22:21:18 -06002260 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2261 if (SDCard->Mount(true)) {
2262 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2263 mkdir(TWRP_Folder.c_str(), 0777);
2264 DataManager::Flush();
2265 }
2266
Dees_Troy9350b8d2012-09-27 12:38:38 -04002267 Update_System_Details();
Ethan Yonker74db1572015-10-28 12:44:49 -05002268 gui_msg("part_complete=Partitioning complete.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002269 return true;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002270}
Dees_Troya13d74f2013-03-24 08:54:55 -05002271
2272void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2273 std::vector<TWPartition*>::iterator iter;
2274 if (ListType == "mount") {
2275 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002276 if ((*iter)->Can_Be_Mounted) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002277 struct PartitionList part;
2278 part.Display_Name = (*iter)->Display_Name;
2279 part.Mount_Point = (*iter)->Mount_Point;
2280 part.selected = (*iter)->Is_Mounted();
2281 Partition_List->push_back(part);
2282 }
2283 }
2284 } else if (ListType == "storage") {
2285 char free_space[255];
2286 string Current_Storage = DataManager::GetCurrentStoragePath();
2287 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2288 if ((*iter)->Is_Storage) {
2289 struct PartitionList part;
2290 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2291 part.Display_Name = (*iter)->Storage_Name + " (";
2292 part.Display_Name += free_space;
2293 part.Display_Name += "MB)";
2294 part.Mount_Point = (*iter)->Storage_Path;
2295 if ((*iter)->Storage_Path == Current_Storage)
2296 part.selected = 1;
2297 else
2298 part.selected = 0;
2299 Partition_List->push_back(part);
2300 }
2301 }
2302 } else if (ListType == "backup") {
2303 char backup_size[255];
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002304 unsigned long long Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05002305 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002306 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002307 struct PartitionList part;
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002308 Backup_Size = (*iter)->Backup_Size;
2309 if ((*iter)->Has_SubPartition) {
2310 std::vector<TWPartition*>::iterator subpart;
2311
2312 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2313 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2314 Backup_Size += (*subpart)->Backup_Size;
2315 }
2316 }
2317 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
Dees_Troya13d74f2013-03-24 08:54:55 -05002318 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2319 part.Display_Name += backup_size;
2320 part.Display_Name += "MB)";
2321 part.Mount_Point = (*iter)->Backup_Path;
2322 part.selected = 0;
2323 Partition_List->push_back(part);
2324 }
2325 }
2326 } else if (ListType == "restore") {
2327 string Restore_List, restore_path;
2328 TWPartition* restore_part = NULL;
2329
2330 DataManager::GetValue("tw_restore_list", Restore_List);
2331 if (!Restore_List.empty()) {
2332 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2333 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2334 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002335 struct PartitionList part;
2336 if (restore_path.compare("ADB_Backup") == 0) {
2337 part.Display_Name = "ADB Backup";
2338 part.Mount_Point = "ADB Backup";
2339 part.selected = 1;
2340 Partition_List->push_back(part);
2341 break;
2342 }
Dees_Troy59df9262013-06-19 14:53:57 -05002343 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
Dees Troy4159aed2014-02-28 17:24:43 +00002344 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002345 // Don't allow restore of recovery (causes problems on some devices)
Dees_Troy59df9262013-06-19 14:53:57 -05002346 // Don't add subpartitions to the list of items
Dees_Troya13d74f2013-03-24 08:54:55 -05002347 } else {
Dees_Troya13d74f2013-03-24 08:54:55 -05002348 part.Display_Name = restore_part->Backup_Display_Name;
2349 part.Mount_Point = restore_part->Backup_Path;
2350 part.selected = 1;
2351 Partition_List->push_back(part);
2352 }
2353 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002354 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05002355 }
2356 start_pos = end_pos + 1;
2357 end_pos = Restore_List.find(";", start_pos);
2358 }
2359 }
2360 } else if (ListType == "wipe") {
2361 struct PartitionList dalvik;
Ethan Yonker74db1572015-10-28 12:44:49 -05002362 dalvik.Display_Name = gui_parse_text("{@dalvik}");
Dees_Troya13d74f2013-03-24 08:54:55 -05002363 dalvik.Mount_Point = "DALVIK";
2364 dalvik.selected = 0;
2365 Partition_List->push_back(dalvik);
2366 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2367 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2368 struct PartitionList part;
2369 part.Display_Name = (*iter)->Display_Name;
2370 part.Mount_Point = (*iter)->Mount_Point;
2371 part.selected = 0;
2372 Partition_List->push_back(part);
2373 }
2374 if ((*iter)->Has_Android_Secure) {
2375 struct PartitionList part;
2376 part.Display_Name = (*iter)->Backup_Display_Name;
2377 part.Mount_Point = (*iter)->Backup_Path;
2378 part.selected = 0;
2379 Partition_List->push_back(part);
2380 }
Dees_Troy74fb2e92013-04-15 14:35:47 +00002381 if ((*iter)->Has_Data_Media) {
2382 struct PartitionList datamedia;
2383 datamedia.Display_Name = (*iter)->Storage_Name;
2384 datamedia.Mount_Point = "INTERNAL";
2385 datamedia.selected = 0;
2386 Partition_List->push_back(datamedia);
2387 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002388 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002389 } else if (ListType == "flashimg") {
2390 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2391 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2392 struct PartitionList part;
2393 part.Display_Name = (*iter)->Backup_Display_Name;
2394 part.Mount_Point = (*iter)->Backup_Path;
2395 part.selected = 0;
2396 Partition_List->push_back(part);
2397 }
2398 }
Ethan Yonker53796e72019-01-11 22:49:52 -06002399 if (DataManager::GetIntValue("tw_has_repack_tools") != 0 && DataManager::GetIntValue("tw_has_boot_slots") != 0) {
2400 TWPartition* boot = Find_Partition_By_Path("/boot");
2401 if (boot) {
2402 // Allow flashing kernels and ramdisks
2403 struct PartitionList repack_ramdisk;
2404 repack_ramdisk.Display_Name = gui_lookup("install_twrp_ramdisk", "Install Recovery Ramdisk");
2405 repack_ramdisk.Mount_Point = "/repack_ramdisk";
2406 repack_ramdisk.selected = 0;
2407 Partition_List->push_back(repack_ramdisk);
2408 /*struct PartitionList repack_kernel; For now let's leave repacking kernels under advanced only
2409 repack_kernel.Display_Name = gui_lookup("install_kernel", "Install Kernel");
2410 repack_kernel.Mount_Point = "/repack_kernel";
2411 repack_kernel.selected = 0;
2412 Partition_List->push_back(repack_kernel);*/
2413 }
2414 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002415 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00002416 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05002417 }
2418}
2419
2420int TWPartitionManager::Fstab_Processed(void) {
2421 return Partitions.size();
2422}
Dees_Troyd93bda52013-07-03 19:55:19 +00002423
2424void TWPartitionManager::Output_Storage_Fstab(void) {
2425 std::vector<TWPartition*>::iterator iter;
2426 char storage_partition[255];
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002427 std::string Temp;
bigbiff349ea552020-06-19 16:07:38 -04002428 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002429
2430 if (cacheDir.empty()) {
2431 LOGINFO("Unable to find cache directory\n");
2432 return;
2433 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002434
bigbiff349ea552020-06-19 16:07:38 -04002435 std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002436 FILE *fp = fopen(storageFstab.c_str(), "w");
Dees_Troyd93bda52013-07-03 19:55:19 +00002437
2438 if (fp == NULL) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002439 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
Dees_Troyd93bda52013-07-03 19:55:19 +00002440 return;
2441 }
2442
2443 // Iterate through all partitions
2444 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2445 if ((*iter)->Is_Storage) {
2446 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2447 strcpy(storage_partition, Temp.c_str());
2448 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2449 }
2450 }
2451 fclose(fp);
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02002452}
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002453
2454TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2455{
2456 TWPartition *res = NULL;
2457 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
Matt Mowera8a89d12016-12-30 18:10:37 -06002458 if (!(*iter)->Is_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002459 continue;
2460
Matt Mowera8a89d12016-12-30 18:10:37 -06002461 if ((*iter)->Is_Settings_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002462 return *iter;
2463
Matt Mowera8a89d12016-12-30 18:10:37 -06002464 if (!res)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002465 res = *iter;
2466 }
2467 return res;
2468}
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002469
2470bool TWPartitionManager::Enable_MTP(void) {
2471#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002472 if (mtppid) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002473 gui_err("mtp_already_enabled=MTP already enabled");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002474 return true;
2475 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002476
2477 int mtppipe[2];
2478
2479 if (pipe(mtppipe) < 0) {
2480 LOGERR("Error creating MTP pipe\n");
2481 return false;
2482 }
2483
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002484 char old_value[PROPERTY_VALUE_MAX];
Matt Mowere07f0102017-02-23 17:40:00 -06002485 property_get("sys.usb.config", old_value, "");
2486 if (strcmp(old_value, "mtp,adb") != 0) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002487 char vendor[PROPERTY_VALUE_MAX];
2488 char product[PROPERTY_VALUE_MAX];
2489 property_set("sys.usb.config", "none");
2490 property_get("usb.vendor", vendor, "18D1");
2491 property_get("usb.product.mtpadb", product, "4EE2");
2492 string vendorstr = vendor;
2493 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002494 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2495 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002496 property_set("sys.usb.config", "mtp,adb");
2497 }
Matt Mower653a1702017-02-16 10:38:52 -06002498 /* To enable MTP debug, use the twrp command line feature:
Ethan Yonker6d154c42014-09-03 14:19:43 -05002499 * twrp set tw_mtp_debug 1
2500 */
2501 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
Ethan Yonker1b039202015-01-30 10:08:48 -06002502 mtppid = mtp->forkserver(mtppipe);
2503 if (mtppid) {
2504 close(mtppipe[0]); // Host closes read side
2505 mtp_write_fd = mtppipe[1];
2506 DataManager::SetValue("tw_mtp_enabled", 1);
2507 Add_All_MTP_Storage();
2508 return true;
Ethan Yonker726a0202014-12-16 20:01:38 -06002509 } else {
2510 close(mtppipe[0]);
2511 close(mtppipe[1]);
Ethan Yonker74db1572015-10-28 12:44:49 -05002512 gui_err("mtp_fail=Failed to enable MTP");
Ethan Yonker1b039202015-01-30 10:08:48 -06002513 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002514 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002515#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002516 gui_err("no_mtp=MTP support not included");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002517#endif
2518 DataManager::SetValue("tw_mtp_enabled", 0);
2519 return false;
2520}
2521
Ethan Yonker1b039202015-01-30 10:08:48 -06002522void TWPartitionManager::Add_All_MTP_Storage(void) {
2523#ifdef TW_HAS_MTP
2524 std::vector<TWPartition*>::iterator iter;
2525
2526 if (!mtppid)
2527 return; // MTP is not enabled
2528
2529 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2530 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2531 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2532 }
2533#else
2534 return;
2535#endif
2536}
2537
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002538bool TWPartitionManager::Disable_MTP(void) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002539 char old_value[PROPERTY_VALUE_MAX];
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05002540 property_set("sys.usb.ffs.mtp.ready", "0");
Matt Mowere07f0102017-02-23 17:40:00 -06002541 property_get("sys.usb.config", old_value, "");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002542 if (strcmp(old_value, "adb") != 0) {
2543 char vendor[PROPERTY_VALUE_MAX];
2544 char product[PROPERTY_VALUE_MAX];
2545 property_set("sys.usb.config", "none");
2546 property_get("usb.vendor", vendor, "18D1");
Matt Mowere07f0102017-02-23 17:40:00 -06002547 property_get("usb.product.adb", product, "D001");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002548 string vendorstr = vendor;
2549 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002550 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2551 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002552 usleep(2000);
2553 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002554#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002555 if (mtppid) {
Ethan Yonker8613dc02014-09-11 09:28:20 -05002556 LOGINFO("Disabling MTP\n");
2557 int status;
2558 kill(mtppid, SIGKILL);
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002559 mtppid = 0;
Ethan Yonker8613dc02014-09-11 09:28:20 -05002560 // We don't care about the exit value, but this prevents a zombie process
2561 waitpid(mtppid, &status, 0);
Ethan Yonker726a0202014-12-16 20:01:38 -06002562 close(mtp_write_fd);
2563 mtp_write_fd = -1;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002564 }
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002565#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002566 property_set("sys.usb.config", "adb");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002567#ifdef TW_HAS_MTP
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002568 DataManager::SetValue("tw_mtp_enabled", 0);
2569 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002570#endif
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002571 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002572}
Ethan Yonker726a0202014-12-16 20:01:38 -06002573
2574TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2575 std::vector<TWPartition*>::iterator iter;
2576
2577 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2578 if ((*iter)->MTP_Storage_ID == Storage_ID)
2579 return (*iter);
2580 }
2581 return NULL;
2582}
2583
2584bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2585#ifdef TW_HAS_MTP
2586 struct mtpmsg mtp_message;
2587
2588 if (!mtppid)
2589 return false; // MTP is disabled
2590
2591 if (mtp_write_fd < 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002592 LOGINFO("MTP: mtp_write_fd is not set\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002593 return false;
2594 }
2595
2596 if (Part) {
Ethan Yonker4bfabab2014-12-29 09:15:37 -06002597 if (Part->MTP_Storage_ID == 0)
2598 return false;
Ethan Yonker726a0202014-12-16 20:01:38 -06002599 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2600 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2601 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2602 mtp_message.storage_id = Part->MTP_Storage_ID;
2603 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002604 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002605 return false;
2606 } else {
2607 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2608 return true;
2609 }
2610 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2611 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2612 mtp_message.storage_id = Part->MTP_Storage_ID;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002613 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2614 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2615 return false;
2616 }
2617 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2618 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2619 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2620 return false;
2621 }
2622 strcpy(mtp_message.display, Part->Storage_Name.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002623 mtp_message.maxFileSize = Part->Get_Max_FileSize();
Ethan Yonker1b039202015-01-30 10:08:48 -06002624 LOGINFO("sending message to add %i '%s' '%s'\n", mtp_message.storage_id, mtp_message.path, mtp_message.display);
Ethan Yonker726a0202014-12-16 20:01:38 -06002625 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002626 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002627 return false;
2628 } else {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002629 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
Ethan Yonker726a0202014-12-16 20:01:38 -06002630 return true;
2631 }
2632 } else {
2633 LOGERR("Unknown MTP message type: %i\n", message_type);
2634 }
2635 } else {
2636 // This hopefully never happens as the error handling should
2637 // occur in the calling function.
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002638 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002639 }
2640 return true;
2641#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002642 gui_err("no_mtp=MTP support not included");
Ethan Yonker726a0202014-12-16 20:01:38 -06002643 DataManager::SetValue("tw_mtp_enabled", 0);
2644 return false;
2645#endif
2646}
2647
2648bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2649#ifdef TW_HAS_MTP
2650 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2651 if (Part) {
2652 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2653 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002654 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002655 }
2656#endif
2657 return false;
2658}
2659
2660bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2661#ifdef TW_HAS_MTP
2662 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2663 if (Part) {
2664 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2665 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002666 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002667 }
2668#endif
2669 return false;
2670}
2671
2672bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2673#ifdef TW_HAS_MTP
2674 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2675 if (Part) {
2676 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2677 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002678 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002679 }
2680#endif
2681 return false;
2682}
2683
2684bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2685#ifdef TW_HAS_MTP
2686 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2687 if (Part) {
2688 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2689 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002690 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002691 }
2692#endif
2693 return false;
2694}
Ethan Yonker96af84a2015-01-05 14:58:36 -06002695
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002696bool TWPartitionManager::Flash_Image(string& path, string& filename) {
bigbiff56b02eb2020-07-06 20:24:34 -04002697 twrpRepacker repacker;
Matt Mower23d8aae2017-01-06 14:30:33 -06002698 int partition_count = 0;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002699 TWPartition* flash_part = NULL;
bigbiffce8f83c2015-12-12 18:30:21 -05002700 string Flash_List, flash_path, full_filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002701 size_t start_pos = 0, end_pos = 0;
2702
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002703 full_filename = path + "/" + filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002704
bigbiffce8f83c2015-12-12 18:30:21 -05002705 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
2706 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
2707
2708 if (!TWFunc::Path_Exists(full_filename)) {
2709 if (!Mount_By_Path(full_filename, true)) {
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002710 return false;
2711 }
bigbiffce8f83c2015-12-12 18:30:21 -05002712 if (!TWFunc::Path_Exists(full_filename)) {
2713 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002714 return false;
2715 }
2716 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002717
Ethan Yonker53796e72019-01-11 22:49:52 -06002718 DataManager::GetValue("tw_flash_partition", Flash_List);
2719 Repack_Type repack = REPLACE_NONE;
2720 if (Flash_List == "/repack_ramdisk;") {
2721 repack = REPLACE_RAMDISK;
2722 } else if (Flash_List == "/repack_kernel;") {
2723 repack = REPLACE_KERNEL;
2724 }
2725 if (repack != REPLACE_NONE) {
2726 Repack_Options_struct Repack_Options;
2727 Repack_Options.Type = repack;
2728 Repack_Options.Disable_Verity = false;
2729 Repack_Options.Disable_Force_Encrypt = false;
2730 Repack_Options.Backup_First = DataManager::GetIntValue("tw_repack_backup_first") != 0;
bigbiff56b02eb2020-07-06 20:24:34 -04002731 return repacker.Repack_Image_And_Flash(full_filename, Repack_Options);
Ethan Yonker53796e72019-01-11 22:49:52 -06002732 }
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002733 PartitionSettings part_settings;
2734 part_settings.Backup_Folder = path;
2735 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
2736 ProgressTracking progress(total_bytes);
2737 part_settings.progress = &progress;
2738 part_settings.adbbackup = false;
2739 part_settings.PM_Method = PM_RESTORE;
Ethan Yonker74db1572015-10-28 12:44:49 -05002740 gui_msg("calc_restore=Calculating restore details...");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002741 if (!Flash_List.empty()) {
2742 end_pos = Flash_List.find(";", start_pos);
2743 while (end_pos != string::npos && start_pos < Flash_List.size()) {
2744 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
2745 flash_part = Find_Partition_By_Path(flash_path);
2746 if (flash_part != NULL) {
2747 partition_count++;
2748 if (partition_count > 1) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002749 gui_err("too_many_flash=Too many partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002750 return false;
2751 }
2752 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002753 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
Ethan Yonker96af84a2015-01-05 14:58:36 -06002754 return false;
2755 }
2756 start_pos = end_pos + 1;
2757 end_pos = Flash_List.find(";", start_pos);
2758 }
2759 }
2760
2761 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002762 gui_err("no_part_flash=No partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002763 return false;
2764 }
2765
2766 DataManager::SetProgress(0.0);
2767 if (flash_part) {
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002768 flash_part->Backup_FileName = filename;
2769 if (!flash_part->Flash_Image(&part_settings))
Ethan Yonker96af84a2015-01-05 14:58:36 -06002770 return false;
2771 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002772 gui_err("invalid_flash=Invalid flash partition specified.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002773 return false;
2774 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002775 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002776 return true;
2777}
Ethan Yonker74db1572015-10-28 12:44:49 -05002778
2779void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
2780 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2781 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002782 if (part->Is_Adopted_Storage) {
2783 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2784 part->Backup_Display_Name = part->Display_Name;
2785 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2786 } else {
2787 part->Display_Name = gui_lookup(resource_name, default_value);
2788 part->Backup_Display_Name = part->Display_Name;
2789 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002790 }
2791}
2792
2793void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
2794 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2795 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002796 if (part->Is_Adopted_Storage) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06002797 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
Ethan Yonker66a19492015-12-10 10:19:45 -06002798 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
Ethan Yonker66a19492015-12-10 10:19:45 -06002799 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2800 } else {
2801 part->Display_Name = gui_lookup(resource_name, default_value);
2802 part->Backup_Display_Name = part->Display_Name;
2803 if (part->Is_Storage)
2804 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2805 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002806 }
2807}
2808
Ethan Yonker01f4e032017-02-03 15:30:52 -06002809void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value, const char* backup_name, const char* backup_default) {
2810 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2811 if (part) {
2812 if (part->Is_Adopted_Storage) {
2813 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
2814 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2815 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2816 } else {
2817 part->Display_Name = gui_lookup(resource_name, default_value);
2818 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
2819 if (part->Is_Storage)
2820 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2821 }
2822 }
2823}
2824
Ethan Yonker74db1572015-10-28 12:44:49 -05002825void TWPartitionManager::Translate_Partition_Display_Names() {
Ethan Yonker66a19492015-12-10 10:19:45 -06002826 LOGINFO("Translating partition display names\n");
Ethan Yonker74db1572015-10-28 12:44:49 -05002827 Translate_Partition("/system", "system", "System");
2828 Translate_Partition("/system_image", "system_image", "System Image");
2829 Translate_Partition("/vendor", "vendor", "Vendor");
2830 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
2831 Translate_Partition("/cache", "cache", "Cache");
Ethan Yonker74db1572015-10-28 12:44:49 -05002832 Translate_Partition("/boot", "boot", "Boot");
2833 Translate_Partition("/recovery", "recovery", "Recovery");
2834 if (!datamedia) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06002835 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
Ethan Yonker74db1572015-10-28 12:44:49 -05002836 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2837 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
2838 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2839 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
Ethan Yonker01f4e032017-02-03 15:30:52 -06002840 } else {
2841 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05002842 }
Ethan Yonker01f4e032017-02-03 15:30:52 -06002843 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
2844 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05002845 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
2846 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
2847
2848 // Android secure is a special case
2849 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
2850 if (part)
2851 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
2852
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002853 std::vector<TWPartition*>::iterator sysfs;
2854 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
2855 if (!(*sysfs)->Sysfs_Entry.empty()) {
2856 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
2857 }
2858 }
2859
Ethan Yonker74db1572015-10-28 12:44:49 -05002860 // This updates the text on all of the storage selection buttons in the GUI
2861 DataManager::SetBackupFolder();
2862}
Ethan Yonker66a19492015-12-10 10:19:45 -06002863
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002864bool TWPartitionManager::Decrypt_Adopted() {
Ethan Yonker66a19492015-12-10 10:19:45 -06002865#ifdef TW_INCLUDE_CRYPTO
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002866 bool ret = false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002867 if (!Mount_By_Path("/data", false)) {
2868 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002869 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002870 }
2871 LOGINFO("Decrypt adopted storage starting\n");
2872 char* xmlFile = PageManager::LoadFileToBuffer("/data/system/storage.xml", NULL);
2873 xml_document<> *doc = NULL;
2874 xml_node<>* volumes = NULL;
Ethan Yonker66a19492015-12-10 10:19:45 -06002875 string Primary_Storage_UUID = "";
2876 if (xmlFile != NULL) {
2877 LOGINFO("successfully loaded storage.xml\n");
2878 doc = new xml_document<>();
2879 doc->parse<0>(xmlFile);
2880 volumes = doc->first_node("volumes");
2881 if (volumes) {
2882 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
2883 if (psuuid) {
2884 Primary_Storage_UUID = psuuid->value();
2885 }
2886 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002887 } else {
2888 LOGINFO("No /data/system/storage.xml for adopted storage\n");
2889 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002890 }
2891 std::vector<TWPartition*>::iterator adopt;
2892 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
Peter Caic50044b2019-10-17 08:49:10 +08002893 if ((*adopt)->Removable && !(*adopt)->Is_Present && (*adopt)->Adopted_Mount_Delay > 0) {
2894 // On some devices, the external mmc driver takes some time
2895 // to recognize the card, in which case the "actual block device"
2896 // would not have been found yet. We wait the specified delay
2897 // and then try again.
2898 LOGINFO("Sleeping %d seconds for adopted storage.\n", (*adopt)->Adopted_Mount_Delay);
2899 sleep((*adopt)->Adopted_Mount_Delay);
2900 (*adopt)->Find_Actual_Block_Device();
2901 }
2902
Ethan Yonker66a19492015-12-10 10:19:45 -06002903 if ((*adopt)->Removable && (*adopt)->Is_Present) {
2904 if ((*adopt)->Decrypt_Adopted() == 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002905 ret = true;
Ethan Yonker66a19492015-12-10 10:19:45 -06002906 if (volumes) {
2907 xml_node<>* volume = volumes->first_node("volume");
2908 while (volume) {
2909 xml_attribute<>* guid = volume->first_attribute("partGuid");
2910 if (guid) {
2911 string GUID = (*adopt)->Adopted_GUID.c_str();
2912 GUID.insert(8, "-");
2913 GUID.insert(13, "-");
2914 GUID.insert(18, "-");
2915 GUID.insert(23, "-");
2916
2917 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
2918 xml_attribute<>* attr = volume->first_attribute("nickname");
nkk71ffb02bd2017-06-04 23:12:16 +03002919 if (attr && attr->value() && strlen(attr->value()) > 0) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002920 (*adopt)->Storage_Name = attr->value();
2921 (*adopt)->Display_Name = (*adopt)->Storage_Name;
2922 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
2923 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
2924 }
2925 attr = volume->first_attribute("fsUuid");
2926 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
2927 TWPartition* Dat = Find_Partition_By_Path("/data");
2928 if (Dat) {
2929 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
2930 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
2931 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
2932 Dat->Symlink_Mount_Point = "";
2933 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
2934 Dat->UnMount(false);
2935 Dat->Mount(false);
2936 (*adopt)->UnMount(false);
2937 (*adopt)->Mount(false);
Ethan Yonker66a19492015-12-10 10:19:45 -06002938 }
2939 }
2940 break;
2941 }
2942 }
2943 volume = volume->next_sibling("volume");
2944 }
2945 }
nkk71ffb02bd2017-06-04 23:12:16 +03002946 Update_System_Details();
2947 Output_Partition((*adopt));
Ethan Yonker66a19492015-12-10 10:19:45 -06002948 }
2949 }
2950 }
2951 if (xmlFile) {
2952 doc->clear();
2953 delete doc;
2954 free(xmlFile);
2955 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002956 return ret;
Ethan Yonker66a19492015-12-10 10:19:45 -06002957#else
2958 LOGINFO("Decrypt_Adopted: no crypto support\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002959 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002960#endif
2961}
Ethan Yonkerfcf3f242016-02-16 12:30:26 -06002962
2963void TWPartitionManager::Remove_Partition_By_Path(string Path) {
2964 std::vector<TWPartition*>::iterator iter;
2965 string Local_Path = TWFunc::Get_Root_Path(Path);
2966
2967 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2968 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
2969 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
2970 Partitions.erase(iter);
2971 return;
2972 }
2973 }
2974}
Ethan Yonker1b190162016-12-05 15:25:19 -06002975
2976void TWPartitionManager::Set_Active_Slot(const string& Slot) {
2977 if (Slot != "A" && Slot != "B") {
2978 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
2979 return;
2980 }
2981 if (Active_Slot_Display == Slot)
2982 return;
2983 LOGINFO("Setting active slot %s\n", Slot.c_str());
2984#ifdef AB_OTA_UPDATER
2985 if (!Active_Slot_Display.empty()) {
2986 const hw_module_t *hw_module;
2987 boot_control_module_t *module;
2988 int ret;
2989 ret = hw_get_module("bootctrl", &hw_module);
2990 if (ret != 0) {
2991 LOGERR("Error getting bootctrl module.\n");
2992 } else {
2993 module = (boot_control_module_t*) hw_module;
2994 module->init(module);
2995 int slot_number = 0;
2996 if (Slot == "B")
2997 slot_number = 1;
2998 if (module->setActiveBootSlot(module, slot_number))
2999 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
3000 }
3001 DataManager::SetValue("tw_active_slot", Slot); // Doing this outside of this if block may result in a seg fault because the DataManager may not be ready yet
3002 }
3003#else
3004 LOGERR("Boot slot feature not present\n");
3005#endif
3006 Active_Slot_Display = Slot;
3007 if (Fstab_Processed())
3008 Update_System_Details();
3009}
3010string TWPartitionManager::Get_Active_Slot_Suffix() {
3011 if (Active_Slot_Display == "A")
3012 return "_a";
3013 return "_b";
3014}
3015string TWPartitionManager::Get_Active_Slot_Display() {
3016 return Active_Slot_Display;
3017}
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003018
Captain Throwback9d6feb52018-07-27 10:05:24 -04003019string TWPartitionManager::Get_Android_Root_Path() {
Chaosmasterf6e42ce2020-01-27 00:17:04 +01003020 if (property_get_bool("ro.twrp.sar", false))
dianlujitao58f1a632020-01-16 23:03:56 +08003021 return "/system_root";
3022 return "/system";
Captain Throwback9d6feb52018-07-27 10:05:24 -04003023}
3024
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003025void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
3026 std::vector<TWPartition*>::iterator iter;
3027
3028 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
3029 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
3030 TWPartition *part = *iter;
3031 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
3032 (*iter)->UnMount(false);
3033 rmdir((*iter)->Mount_Point.c_str());
3034 iter = Partitions.erase(iter);
3035 delete part;
3036 } else {
3037 iter++;
3038 }
3039 }
3040}
3041
3042void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
3043 std::vector<TWPartition*>::iterator iter;
3044
3045 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3046 if (!(*iter)->Sysfs_Entry.empty()) {
3047 string device;
3048 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
3049 if (wildcard != string::npos) {
3050 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
3051 } else {
3052 device = (*iter)->Sysfs_Entry;
3053 }
3054 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
3055 // Found a match
3056 if (uevent_data.action == "add") {
3057 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
3058 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
3059 (*iter)->Is_Present = true;
3060 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
3061 if (!Decrypt_Adopted()) {
3062 LOGINFO("No adopted storage so finding actual block device\n");
3063 (*iter)->Find_Actual_Block_Device();
3064 }
3065 return;
3066 } else if (uevent_data.action == "remove") {
3067 (*iter)->Is_Present = false;
3068 (*iter)->Primary_Block_Device = "";
3069 (*iter)->Actual_Block_Device = "";
3070 Remove_Uevent_Devices((*iter)->Mount_Point);
3071 return;
3072 }
3073 }
3074 }
3075 }
3076 LOGINFO("Found no matching fstab entry for uevent device '%s' - %s\n", uevent_data.sysfs_path.c_str(), uevent_data.action.c_str());
3077}
3078
3079void TWPartitionManager::setup_uevent() {
3080 struct sockaddr_nl nls;
3081
3082 if (uevent_pfd.fd >= 0) {
3083 LOGINFO("uevent already set up\n");
3084 return;
3085 }
3086
3087 // Open hotplug event netlink socket
3088 memset(&nls,0,sizeof(struct sockaddr_nl));
3089 nls.nl_family = AF_NETLINK;
3090 nls.nl_pid = getpid();
3091 nls.nl_groups = -1;
3092 uevent_pfd.events = POLLIN;
3093 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
3094 if (uevent_pfd.fd==-1) {
3095 LOGERR("uevent not root\n");
3096 return;
3097 }
3098
3099 // Listen to netlink socket
3100 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
3101 LOGERR("Bind failed\n");
3102 return;
3103 }
3104 set_select_fd();
3105 Coldboot();
3106}
3107
3108Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
3109 Uevent_Block_Data ret;
3110 ret.subsystem = "";
3111 char *ptr = buf;
3112 const char *end = buf + len;
3113
3114 buf[len - 1] = '\0';
3115 while (ptr < end) {
3116 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
3117 ptr += strlen("ACTION=");
3118 ret.action = ptr;
3119 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
3120 ptr += strlen("SUBSYSTEM=");
3121 ret.subsystem = ptr;
3122 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
3123 ptr += strlen("DEVTYPE=");
3124 ret.type = ptr;
3125 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
3126 ptr += strlen("DEVPATH=");
3127 ret.sysfs_path += ptr;
3128 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
3129 ptr += strlen("DEVNAME=");
3130 ret.block_device += ptr;
3131 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
3132 ptr += strlen("MAJOR=");
3133 ret.major = atoi(ptr);
3134 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
3135 ptr += strlen("MINOR=");
3136 ret.minor = atoi(ptr);
3137 }
3138 ptr += strlen(ptr) + 1;
3139 }
3140 return ret;
3141}
3142
3143void TWPartitionManager::read_uevent() {
3144 char buf[1024];
3145
3146 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
3147 if (len == -1) {
Mauronofrio Matarrese9632f302019-08-04 17:02:41 +01003148 LOGINFO("recv error on uevent\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003149 return;
3150 }
3151 /*int i = 0; // Print all uevent output for test /debug
3152 while (i<len) {
3153 printf("%s\n", buf+i);
3154 i += strlen(buf+i)+1;
3155 }*/
3156 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
3157 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
3158 PartitionManager.Handle_Uevent(uevent_data);
3159 }
3160}
3161
3162void TWPartitionManager::close_uevent() {
3163 if (uevent_pfd.fd > 0)
3164 close(uevent_pfd.fd);
3165 uevent_pfd.fd = -1;
3166}
3167
3168void TWPartitionManager::Add_Partition(TWPartition* Part) {
3169 Partitions.push_back(Part);
3170}
3171
3172void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
3173 string Real_Path = Path;
3174 char real_path[PATH_MAX];
3175 if (realpath(Path.c_str(), &real_path[0])) {
3176 string Real_Path = real_path;
3177 std::vector<string>::iterator iter;
3178 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
3179 if (Real_Path.find((*iter)) != string::npos) {
3180 string Write_Path = Real_Path + "/uevent";
3181 if (TWFunc::Path_Exists(Write_Path)) {
3182 const char* write_val = "add\n";
3183 TWFunc::write_to_file(Write_Path, write_val);
3184 break;
3185 }
3186 }
3187 }
3188 }
3189
3190 DIR* d = opendir(Path.c_str());
3191 if (d != NULL) {
3192 struct dirent* de;
3193 while ((de = readdir(d)) != NULL) {
3194 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
3195 continue;
3196 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
3197 continue;
3198
3199 string item = Path + "/";
3200 item.append(de->d_name);
3201 Coldboot_Scan(sysfs_entries, item, depth + 1);
3202 }
3203 closedir(d);
3204 }
3205}
3206
3207void TWPartitionManager::Coldboot() {
3208 std::vector<TWPartition*>::iterator iter;
3209 std::vector<string> sysfs_entries;
3210
3211 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3212 if (!(*iter)->Sysfs_Entry.empty()) {
3213 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
3214 if (wildcard_pos == string::npos)
3215 wildcard_pos = (*iter)->Sysfs_Entry.size();
3216 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
3217 }
3218 }
3219
3220 if (sysfs_entries.size() > 0)
3221 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
3222}
Ethan Yonker53796e72019-01-11 22:49:52 -06003223
3224bool TWPartitionManager::Prepare_Empty_Folder(const std::string& Folder) {
3225 if (TWFunc::Path_Exists(Folder))
3226 TWFunc::removeDir(Folder, false);
3227 return TWFunc::Recursive_Mkdir(Folder);
3228}