blob: b983e73e8cb53628cf2a1c6b12ea9a0cdd3c024a [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
bigbiffaed1bdf2021-08-03 18:21:39 -04002 Copyright 2014 to 2021 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>
bigbiff25d25b92020-06-19 16:07:38 -040031#include <grp.h>
32#include <pwd.h>
bigbiffce8f83c2015-12-12 18:30:21 -050033#include <zlib.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050034#include <iostream>
35#include <iomanip>
Ethan Yonker8613dc02014-09-11 09:28:20 -050036#include <sys/wait.h>
Ethan Yonker483e9f42016-01-11 22:21:18 -060037#include <linux/fs.h>
38#include <sys/mount.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060039#include <sys/poll.h>
40#include <sys/socket.h>
bigbiffcfa875c2021-06-20 16:20:27 -040041#include <sys/stat.h>
42#include <sys/types.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060043#include <linux/types.h>
44#include <linux/netlink.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040045#include <android-base/chrono_utils.h>
46#include <android-base/file.h>
47#include <android-base/logging.h>
bigbiff7ba75002020-04-11 20:47:09 -040048#include <android-base/properties.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040049#include <android-base/strings.h>
50#include <fstab/fstab.h>
51#include <fs_avb/fs_avb.h>
52#include <fs_mgr.h>
53#include <fs_mgr_dm_linear.h>
54#include <fs_mgr_overlayfs.h>
bigbiffcfa875c2021-06-20 16:20:27 -040055#include <fs_mgr/roots.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040056#include <libgsi/libgsi.h>
57#include <liblp/liblp.h>
bigbiffcfa875c2021-06-20 16:20:27 -040058#include <libgsi/libgsi.h>
59#include <liblp/builder.h>
60#include <libsnapshot/snapshot.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060061
Dees_Troy51a0e822012-09-05 15:24:24 -040062#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000063#include "twcommon.h"
Dees_Troy51a0e822012-09-05 15:24:24 -040064#include "partitions.hpp"
Dees_Troy5bf43922012-09-07 16:07:55 -040065#include "data.hpp"
bigbiffaed1bdf2021-08-03 18:21:39 -040066#include "startupArgs.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040067#include "twrp-functions.hpp"
Ethan Yonkerb5fab762016-01-28 14:03:33 -060068#include "fixContexts.hpp"
Ethan Yonker3fdcda42016-11-30 12:29:37 -060069#include "exclude.hpp"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060070#include "set_metadata.h"
bigbiff7abc5fe2015-01-17 16:53:12 -050071#include "tw_atomic.hpp"
Ethan Yonker74db1572015-10-28 12:44:49 -050072#include "gui/gui.hpp"
Ethan Yonker472f5062016-02-25 13:47:30 -060073#include "progresstracking.hpp"
bigbiff bigbiff56cf5642016-08-19 17:43:45 -040074#include "twrpDigestDriver.hpp"
bigbiffad58e1b2020-07-06 20:24:34 -040075#include "twrpRepacker.hpp"
bigbiffce8f83c2015-12-12 18:30:21 -050076#include "adbbu/libtwadbbu.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040077
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040078#ifdef TW_HAS_MTP
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -050079#ifdef TW_HAS_LEGACY_MTP
80#include "mtp/legacy/mtp_MtpServer.hpp"
81#include "mtp/legacy/twrpMtp.hpp"
82#include "mtp/legacy/MtpMessage.hpp"
83#else
84#include "mtp/ffs/mtp_MtpServer.hpp"
85#include "mtp/ffs/twrpMtp.hpp"
86#include "mtp/ffs/MtpMessage.hpp"
87#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040088#endif
89
Dees Troy6f6441d2014-01-23 02:07:03 +000090extern "C" {
91 #include "cutils/properties.h"
Ethan Yonker74db1572015-10-28 12:44:49 -050092 #include "gui/gui.h"
Dees Troy6f6441d2014-01-23 02:07:03 +000093}
94
Dees_Troy5bf43922012-09-07 16:07:55 -040095#ifdef TW_INCLUDE_CRYPTO
bigbiff7ba75002020-04-11 20:47:09 -040096#include "crypto/fde/cryptfs.h"
97#include "gui/rapidxml.hpp"
98#include "gui/pages.hpp"
99#ifdef TW_INCLUDE_FBE
bigbiffa957f072021-03-07 18:20:29 -0500100#include "Decrypt.h"
bigbiff7ba75002020-04-11 20:47:09 -0400101#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
102 #ifdef USE_FSCRYPT
bigbiffa957f072021-03-07 18:20:29 -0500103 #include "MetadataCrypt.h"
bigbiffadc599e2020-05-28 19:36:30 +0000104 #endif
bigbiff7ba75002020-04-11 20:47:09 -0400105#endif
106#endif
107#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
108#include "crypto/vold_decrypt/vold_decrypt.h"
109#endif
Dees_Troy5bf43922012-09-07 16:07:55 -0400110#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400111
Ethan Yonker1b190162016-12-05 15:25:19 -0600112#ifdef AB_OTA_UPDATER
113#include <hardware/hardware.h>
114#include <hardware/boot_control.h>
115#endif
116
bigbiffcfa875c2021-06-20 16:20:27 -0400117using android::fs_mgr::DestroyLogicalPartition;
bigbiffee7b7ff2020-03-23 15:08:27 -0400118using android::fs_mgr::Fstab;
119using android::fs_mgr::FstabEntry;
bigbiffcfa875c2021-06-20 16:20:27 -0400120using android::fs_mgr::MetadataBuilder;
Ethan Yonker6277c792014-09-15 14:54:30 -0500121
bigbiffee7b7ff2020-03-23 15:08:27 -0400122extern bool datamedia;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400123std::vector<users_struct> Users_List;
124
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500125TWPartitionManager::TWPartitionManager(void) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -0400126 mtp_was_enabled = false;
Ethan Yonker726a0202014-12-16 20:01:38 -0600127 mtp_write_fd = -1;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600128 uevent_pfd.fd = -1;
bigbiff7abc5fe2015-01-17 16:53:12 -0500129 stop_backup.set_value(0);
Ethan Yonker1b190162016-12-05 15:25:19 -0600130#ifdef AB_OTA_UPDATER
131 char slot_suffix[PROPERTY_VALUE_MAX];
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500132 property_get("ro.boot.slot_suffix", slot_suffix, "error");
133 if (strcmp(slot_suffix, "error") == 0)
134 property_get("ro.boot.slot", slot_suffix, "error");
Ethan Yonker1b190162016-12-05 15:25:19 -0600135 Active_Slot_Display = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500136 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Ethan Yonker1b190162016-12-05 15:25:19 -0600137 Set_Active_Slot("A");
138 else
139 Set_Active_Slot("B");
140#endif
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500141}
142
Captain Throwback37c3aef2021-10-06 11:38:18 -0400143void TWPartitionManager::Set_Crypto_State() {
144 char crypto_state[PROPERTY_VALUE_MAX];
145 property_get("ro.crypto.state", crypto_state, "error");
146 if (strcmp(crypto_state, "error") == 0)
147 property_set("ro.crypto.state", "encrypted");
148}
149
150int TWPartitionManager::Set_Crypto_Type(const char* crypto_type) {
151 char type_prop[PROPERTY_VALUE_MAX];
152 property_get("ro.crypto.type", type_prop, "error");
153 if (strcmp(type_prop, "error") == 0)
154 property_set("ro.crypto.type", crypto_type);
Captain Throwback18aea272020-10-29 12:43:17 -0400155 // Sleep for a bit so that services can start if needed
156 sleep(1);
157 return 0;
158}
159
bigbiff22851b92021-09-01 16:46:57 -0400160int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool recovery_mode) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400161 FILE *fstabFile;
162 char fstab_line[MAX_FSTAB_LINE_LENGTH];
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600163 std::map<string, Flags_Map> twrp_flags;
164
165 fstabFile = fopen("/etc/twrp.flags", "rt");
166 if (fstabFile != NULL) {
Ian Macdonald160e8d32020-09-29 20:47:31 +0200167 LOGINFO("Reading /etc/twrp.flags\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600168 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600169 size_t line_size = strlen(fstab_line);
170 if (fstab_line[line_size - 1] != '\n')
171 fstab_line[line_size] = '\n';
172 Flags_Map line_flags;
173 line_flags.Primary_Block_Device = "";
174 line_flags.Alternate_Block_Device = "";
175 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
176 if (!line_flags.fstab_line) {
177 LOGERR("malloc error on line_flags.fstab_line\n");
178 return false;
179 }
180 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
181 bool found_separator = false;
182 char *fs_loc = NULL;
183 char *block_loc = NULL;
184 char *flags_loc = NULL;
185 size_t index, item_index = 0;
186 for (index = 0; index < line_size; index++) {
187 if (fstab_line[index] <= 32) {
188 fstab_line[index] = '\0';
189 found_separator = true;
190 } else if (found_separator) {
191 if (item_index == 0) {
192 fs_loc = fstab_line + index;
193 } else if (item_index == 1) {
194 block_loc = fstab_line + index;
195 } else if (item_index > 1) {
196 char *ptr = fstab_line + index;
197 if (*ptr == '/') {
198 line_flags.Alternate_Block_Device = ptr;
199 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
200 flags_loc = ptr;
201 // Once we find the flags=, we're done scanning the line
202 break;
203 }
204 }
205 found_separator = false;
206 item_index++;
207 }
208 }
209 if (block_loc)
210 line_flags.Primary_Block_Device = block_loc;
211 if (fs_loc)
212 line_flags.File_System = fs_loc;
213 if (flags_loc)
214 line_flags.Flags = flags_loc;
215 string Mount_Point = fstab_line;
216 twrp_flags[Mount_Point] = line_flags;
217 memset(fstab_line, 0, sizeof(fstab_line));
218 }
219 fclose(fstabFile);
220 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400221
222 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
223 if (fstabFile == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000224 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400225 return false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600226 } else
227 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400228
229 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600230 if (strstr(fstab_line, "swap"))
231 continue; // Skip swap in recovery
232
bigbiff998f8392021-08-06 19:19:33 -0400233 if (fstab_line[0] == '#')
234 continue;
235
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600236 size_t line_size = strlen(fstab_line);
237 if (fstab_line[line_size - 1] != '\n')
238 fstab_line[line_size] = '\n';
Dees_Troy2a923582012-09-20 12:13:34 -0400239
Matt Mower2b2dd152016-04-26 11:24:08 -0500240 TWPartition* partition = new TWPartition();
bigbiff8da46fa2020-09-08 16:42:34 -0400241 if (partition->Process_Fstab_Line(fstab_line, Display_Error, &twrp_flags))
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500242 Partitions.push_back(partition);
Matt Mower72c87ce2016-04-26 14:34:56 -0500243 else
Dees_Troy5bf43922012-09-07 16:07:55 -0400244 delete partition;
Matt Mower2b2dd152016-04-26 11:24:08 -0500245
246 memset(fstab_line, 0, sizeof(fstab_line));
Dees_Troy5bf43922012-09-07 16:07:55 -0400247 }
248 fclose(fstabFile);
Matt Mower72c87ce2016-04-26 14:34:56 -0500249
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600250 if (twrp_flags.size() > 0) {
251 LOGINFO("Processing remaining twrp.flags\n");
252 // Add any items from twrp.flags that did not exist in the recovery.fstab
253 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
254 if (Find_Partition_By_Path(mapit->first) == NULL) {
255 TWPartition* partition = new TWPartition();
bigbiff8da46fa2020-09-08 16:42:34 -0400256 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600257 Partitions.push_back(partition);
258 else
259 delete partition;
260 }
261 if (mapit->second.fstab_line)
262 free(mapit->second.fstab_line);
263 mapit->second.fstab_line = NULL;
264 }
265 }
Mohd Faraze3948ec2020-08-14 01:40:59 +0000266 if (Get_Super_Status()) {
267 Setup_Super_Devices();
268 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600269 LOGINFO("Done processing fstab files\n");
270
bigbiff22851b92021-09-01 16:46:57 -0400271 if (recovery_mode) {
272 Setup_Fstab_Partitions(Display_Error);
Mohd Faraze3948ec2020-08-14 01:40:59 +0000273 }
bigbiff7ba75002020-04-11 20:47:09 -0400274 return true;
275}
276
bigbiff22851b92021-09-01 16:46:57 -0400277void TWPartitionManager::Setup_Fstab_Partitions(bool Display_Error) {
278 TWPartition* settings_partition = NULL;
279 TWPartition* andsec_partition = NULL;
280 std::vector<TWPartition*>::iterator iter;
281 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
282
283 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
284 (*iter)->Partition_Post_Processing(Display_Error);
285
286 if ((*iter)->Is_Storage) {
287 ++storageid;
288 (*iter)->MTP_Storage_ID = storageid;
289 }
290
291 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
292 settings_partition = (*iter);
293 else
294 (*iter)->Is_Settings_Storage = false;
295
296 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
297 andsec_partition = (*iter);
298 else
299 (*iter)->Has_Android_Secure = false;
300
301 if ((*iter)->Is_Super)
302 Prepare_Super_Volume((*iter));
303 }
304
305 //Setup Apex before decryption
306 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
307 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
308 if (sys) {
309 if (sys->Get_Super_Status()) {
310 sys->Mount(true);
311 if (ven) {
312 ven->Mount(true);
313 }
314 #ifdef TW_EXCLUDE_APEX
315 LOGINFO("Apex is disabled in this build\n");
316 #else
317 twrpApex apex;
318 if (!apex.loadApexImages()) {
319 LOGERR("Unable to load apex images from %s\n", APEX_DIR);
320 property_set("twrp.apex.loaded", "false");
321 } else {
322 property_set("twrp.apex.loaded", "true");
323 }
324 TWFunc::check_and_run_script("/sbin/resyncapex.sh", "apex");
325 #endif
326 }
327 }
328 #ifndef USE_VENDOR_LIBS
329 if (ven)
330 ven->UnMount(true);
331 if (sys)
332 sys->UnMount(true);
333 #endif
334
335 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) {
336 // Attempt to automatically identify /data/media emulated storage devices
337 TWPartition* Dat = Find_Partition_By_Path("/data");
338 if (Dat) {
339 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
340 datamedia = true;
341 Dat->Setup_Data_Media();
342 settings_partition = Dat;
343 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
344 ++storageid;
345 Dat->MTP_Storage_ID = storageid;
346 }
347 }
348 if (!settings_partition) {
349 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
350 if ((*iter)->Is_Storage) {
351 settings_partition = (*iter);
352 break;
353 }
354 }
355 if (!settings_partition)
356 LOGERR("Unable to locate storage partition for storing settings file.\n");
357 }
358 if (!Write_Fstab()) {
359 if (Display_Error)
360 LOGERR("Error creating fstab\n");
361 else
362 LOGINFO("Error creating fstab\n");
363 }
364
365 if (andsec_partition) {
366 Setup_Android_Secure_Location(andsec_partition);
367 } else if (settings_partition) {
368 Setup_Android_Secure_Location(settings_partition);
369 }
370 if (settings_partition) {
371 Setup_Settings_Storage_Partition(settings_partition);
372 }
373
374 #ifdef TW_INCLUDE_CRYPTO
375 DataManager::SetValue(TW_IS_ENCRYPTED, 1);
376 Decrypt_Data();
377 #endif
378
379 Update_System_Details();
380 if (Get_Super_Status())
381 Setup_Super_Partition();
382 UnMount_Main_Partitions();
383 #ifdef AB_OTA_UPDATER
384 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
385 #endif
386 setup_uevent();
387}
388
bigbiff7ba75002020-04-11 20:47:09 -0400389int TWPartitionManager::Write_Fstab(void) {
390 FILE *fp;
391 std::vector<TWPartition*>::iterator iter;
392 string Line;
393
394 fp = fopen("/etc/fstab", "w");
395 if (fp == NULL) {
396 LOGINFO("Can not open /etc/fstab.\n");
397 return false;
398 }
399 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
400 if ((*iter)->Can_Be_Mounted) {
Mohd Faraz2a1e3752020-09-30 10:55:48 +0530401 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System +
402 ((*iter)->Mount_Read_Only ? " ro " : " rw ") + "0 0\n";
bigbiff7ba75002020-04-11 20:47:09 -0400403 fputs(Line.c_str(), fp);
404 }
405 // Handle subpartition tracking
406 if ((*iter)->Is_SubPartition) {
407 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
408 if (ParentPartition)
409 ParentPartition->Has_SubPartition = true;
410 else
411 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
412 }
413 }
414 fclose(fp);
415 return true;
416}
417
418void TWPartitionManager::Decrypt_Data() {
419 #ifdef TW_INCLUDE_CRYPTO
Ethan Yonkercceebb82014-11-18 10:17:59 -0600420 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
421 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
Captain Throwback37c3aef2021-10-06 11:38:18 -0400422 Set_Crypto_State();
Ethan Yonker93382822018-11-01 15:25:31 -0500423 if (!Decrypt_Data->Key_Directory.empty() && Mount_By_Path(Decrypt_Data->Key_Directory, false)) {
Captain Throwback37c3aef2021-10-06 11:38:18 -0400424 Set_Crypto_Type("file");
Ethan Yonker93382822018-11-01 15:25:31 -0500425#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
bigbiff7ba75002020-04-11 20:47:09 -0400426#ifdef USE_FSCRYPT
427 if (fscrypt_mount_metadata_encrypted(Decrypt_Data->Actual_Block_Device, Decrypt_Data->Mount_Point, false)) {
bigbiffa957f072021-03-07 18:20:29 -0500428 std::string crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "error");
Mohd Faraze3948ec2020-08-14 01:40:59 +0000429 Decrypt_Data->Decrypted_Block_Device = crypto_blkdev;
bigbiff7ba75002020-04-11 20:47:09 -0400430 LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400431#endif
Ethan Yonker93382822018-11-01 15:25:31 -0500432 Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
433 int retry_count = 10;
434 while (!Decrypt_Data->Mount(false) && --retry_count)
435 usleep(500);
436 if (Decrypt_Data->Mount(false)) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400437 if (!Decrypt_Data->Decrypt_FBE_DE()) {
bigbiff437d86f2021-09-26 16:57:14 -0400438 LOGERR("Unable to decrypt FBE device\n");
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400439 }
440
Ethan Yonker93382822018-11-01 15:25:31 -0500441 } else {
442 LOGINFO("Failed to mount data after metadata decrypt\n");
443 }
444 } else {
445 LOGINFO("Unable to decrypt metadata encryption\n");
446 }
447#else
448 LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
449#endif
450 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600451 if (Decrypt_Data->Is_FBE) {
452 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
453 if (Decrypt_Device("!") == 0) {
454 gui_msg("decrypt_success=Successfully decrypted with default password.");
455 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
456 } else {
457 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
458 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600459 }
460 } else {
bigbiffbbbfe172021-05-30 15:52:41 -0400461 LOGINFO("FBE setup failed. Trying FDE...");
Captain Throwback37c3aef2021-10-06 11:38:18 -0400462 Set_Crypto_State();
463 Set_Crypto_Type("block");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600464 int password_type = cryptfs_get_password_type();
465 if (password_type == CRYPT_TYPE_DEFAULT) {
466 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
467 if (Decrypt_Device("default_password") == 0) {
468 gui_msg("decrypt_success=Successfully decrypted with default password.");
469 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
470 } else {
471 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
472 }
473 } else {
474 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
Noah Jacobson81d638d2019-04-28 00:10:07 -0400475 DataManager::SetValue("tw_crypto_pwtype_0", password_type);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600476 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600477 }
478 }
Noah Jacobson81d638d2019-04-28 00:10:07 -0400479 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) &&
480 Decrypt_Data->Mount(false)) {
Ethan Yonker66a19492015-12-10 10:19:45 -0600481 Decrypt_Adopted();
482 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600483#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400484}
485
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500486void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500487 DataManager::SetValue("tw_settings_path", Part->Storage_Path);
488 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
489 LOGINFO("Settings storage is '%s'\n", Part->Storage_Path.c_str());
490}
491
Matt Mowerbf4efa32014-04-14 23:25:26 -0500492void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
493 if (Part->Has_Android_Secure)
494 Part->Setup_AndSec();
Ethan Yonker6277c792014-09-15 14:54:30 -0500495 else if (!datamedia)
Matt Mowerbf4efa32014-04-14 23:25:26 -0500496 Part->Setup_AndSec();
Matt Mowerbf4efa32014-04-14 23:25:26 -0500497}
498
Dees_Troy8170a922012-09-18 15:40:25 -0400499void TWPartitionManager::Output_Partition_Logging(void) {
500 std::vector<TWPartition*>::iterator iter;
501
502 printf("\n\nPartition Logs:\n");
503 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
504 Output_Partition((*iter));
505}
506
507void TWPartitionManager::Output_Partition(TWPartition* Part) {
508 unsigned long long mb = 1048576;
509
Gary Peck004d48b2012-11-21 16:28:18 -0800510 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 -0400511 if (Part->Can_Be_Mounted) {
Gary Peck004d48b2012-11-21 16:28:18 -0800512 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 -0400513 }
Gary Peck004d48b2012-11-21 16:28:18 -0800514 printf("\n Flags: ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500515 if (Part->Can_Be_Mounted)
516 printf("Can_Be_Mounted ");
Gary Peck004d48b2012-11-21 16:28:18 -0800517 if (Part->Can_Be_Wiped)
518 printf("Can_Be_Wiped ");
Hashcodedabfd492013-08-29 22:45:30 -0700519 if (Part->Use_Rm_Rf)
520 printf("Use_Rm_Rf ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500521 if (Part->Can_Be_Backed_Up)
522 printf("Can_Be_Backed_Up ");
Gary Peck004d48b2012-11-21 16:28:18 -0800523 if (Part->Wipe_During_Factory_Reset)
524 printf("Wipe_During_Factory_Reset ");
525 if (Part->Wipe_Available_in_GUI)
526 printf("Wipe_Available_in_GUI ");
527 if (Part->Is_SubPartition)
528 printf("Is_SubPartition ");
529 if (Part->Has_SubPartition)
530 printf("Has_SubPartition ");
531 if (Part->Removable)
532 printf("Removable ");
533 if (Part->Is_Present)
534 printf("IsPresent ");
535 if (Part->Can_Be_Encrypted)
536 printf("Can_Be_Encrypted ");
537 if (Part->Is_Encrypted)
538 printf("Is_Encrypted ");
539 if (Part->Is_Decrypted)
540 printf("Is_Decrypted ");
541 if (Part->Has_Data_Media)
542 printf("Has_Data_Media ");
Dees_Troy83bd4832013-05-04 12:39:56 +0000543 if (Part->Can_Encrypt_Backup)
544 printf("Can_Encrypt_Backup ");
545 if (Part->Use_Userdata_Encryption)
546 printf("Use_Userdata_Encryption ");
Gary Peck004d48b2012-11-21 16:28:18 -0800547 if (Part->Has_Android_Secure)
548 printf("Has_Android_Secure ");
549 if (Part->Is_Storage)
550 printf("Is_Storage ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500551 if (Part->Is_Settings_Storage)
552 printf("Is_Settings_Storage ");
Dees_Troy68cab492012-12-12 19:29:35 +0000553 if (Part->Ignore_Blkid)
554 printf("Ignore_Blkid ");
Ethan Yonker253368a2014-11-25 15:00:52 -0600555 if (Part->Mount_To_Decrypt)
556 printf("Mount_To_Decrypt ");
Ethan Yonker96af84a2015-01-05 14:58:36 -0600557 if (Part->Can_Flash_Img)
558 printf("Can_Flash_Img ");
Ethan Yonker66a19492015-12-10 10:19:45 -0600559 if (Part->Is_Adopted_Storage)
560 printf("Is_Adopted_Storage ");
Ethan Yonker1b190162016-12-05 15:25:19 -0600561 if (Part->SlotSelect)
562 printf("SlotSelect ");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600563 if (Part->Mount_Read_Only)
564 printf("Mount_Read_Only ");
bigbiffcfa875c2021-06-20 16:20:27 -0400565 if (Part->Is_Super)
566 printf("Is_Super ");
Gary Peck004d48b2012-11-21 16:28:18 -0800567 printf("\n");
568 if (!Part->SubPartition_Of.empty())
569 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
570 if (!Part->Symlink_Path.empty())
571 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
572 if (!Part->Symlink_Mount_Point.empty())
573 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
574 if (!Part->Primary_Block_Device.empty())
575 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
576 if (!Part->Alternate_Block_Device.empty())
577 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
578 if (!Part->Decrypted_Block_Device.empty())
579 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
dianlujitao4879b372018-12-03 18:45:47 +0800580 if (!Part->Crypto_Key_Location.empty())
Ethan Yonker253368a2014-11-25 15:00:52 -0600581 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800582 if (Part->Length != 0)
583 printf(" Length: %i\n", Part->Length);
584 if (!Part->Display_Name.empty())
585 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500586 if (!Part->Storage_Name.empty())
587 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800588 if (!Part->Backup_Path.empty())
589 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
590 if (!Part->Backup_Name.empty())
591 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500592 if (!Part->Backup_Display_Name.empty())
593 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800594 if (!Part->Backup_FileName.empty())
595 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
596 if (!Part->Storage_Path.empty())
597 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
598 if (!Part->Current_File_System.empty())
599 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
600 if (!Part->Fstab_File_System.empty())
601 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
602 if (Part->Format_Block_Size != 0)
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500603 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
Dees_Troy094207a2012-09-26 12:00:39 -0400604 if (!Part->MTD_Name.empty())
605 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
Matt Mower029a82d2017-01-08 13:12:38 -0600606 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
Hashcode62bd9e02013-11-19 21:59:42 -0800607 if (Part->Mount_Flags || !Part->Mount_Options.empty())
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600608 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -0600609 if (Part->MTP_Storage_ID)
610 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
Ethan Yonker93382822018-11-01 15:25:31 -0500611 if (!Part->Key_Directory.empty())
612 printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
Ethan Yonker6277c792014-09-15 14:54:30 -0500613 printf("\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400614}
615
Dees_Troy51a0e822012-09-05 15:24:24 -0400616int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400617 std::vector<TWPartition*>::iterator iter;
618 int ret = false;
619 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400620 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400621
bigbiffd58ba182020-03-23 10:02:29 -0400622 if (Local_Path == "/tmp" || Local_Path == "/")
Dees_Troy43d8b002012-09-17 16:00:01 -0400623 return true;
624
Dees_Troy5bf43922012-09-07 16:07:55 -0400625 // Iterate through all partitions
626 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400627 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400628 ret = (*iter)->Mount(Display_Error);
629 found = true;
Dees_Troy51127312012-09-08 13:08:49 -0400630 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400631 (*iter)->Mount(Display_Error);
Dees_Troy51127312012-09-08 13:08:49 -0400632 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400633 }
634 if (found) {
635 return ret;
636 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500637 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 -0400638 }
639 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400640}
641
Dees_Troy51a0e822012-09-05 15:24:24 -0400642int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400643 std::vector<TWPartition*>::iterator iter;
644 int ret = false;
645 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400646 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy51127312012-09-08 13:08:49 -0400647
648 // Iterate through all partitions
649 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400650 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy51127312012-09-08 13:08:49 -0400651 ret = (*iter)->UnMount(Display_Error);
652 found = true;
653 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
654 (*iter)->UnMount(Display_Error);
655 }
656 }
657 if (found) {
658 return ret;
659 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500660 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 -0400661 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000662 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400663 }
664 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400665}
666
Dees_Troy51a0e822012-09-05 15:24:24 -0400667int TWPartitionManager::Is_Mounted_By_Path(string Path) {
Dees_Troy51127312012-09-08 13:08:49 -0400668 TWPartition* Part = Find_Partition_By_Path(Path);
669
670 if (Part)
671 return Part->Is_Mounted();
672 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000673 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400674 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400675}
676
Dees_Troy5bf43922012-09-07 16:07:55 -0400677int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400678 string current_storage_path = DataManager::GetCurrentStoragePath();
679
680 if (Mount_By_Path(current_storage_path, Display_Error)) {
681 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
682 if (FreeStorage)
683 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
684 return true;
685 }
686 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400687}
688
Dees_Troy5bf43922012-09-07 16:07:55 -0400689int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
690 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
691}
692
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600693TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400694 std::vector<TWPartition*>::iterator iter;
Dees_Troy38bd7602012-09-14 13:33:53 -0400695 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400696
dianlujitaob76a73a2020-04-30 20:33:20 +0800697 if (Local_Path == "/system")
698 Local_Path = Get_Android_Root_Path();
Dees_Troy5bf43922012-09-07 16:07:55 -0400699 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400700 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
Dees_Troy5bf43922012-09-07 16:07:55 -0400701 return (*iter);
702 }
Dees_Troy51a0e822012-09-05 15:24:24 -0400703 return NULL;
704}
705
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600706TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
707 std::vector<TWPartition*>::iterator iter;
708
709 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
710 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
711 return (*iter);
712 }
713 return NULL;
714}
715
Ethan Yonker53796e72019-01-11 22:49:52 -0600716int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400717 // Check the backup name to ensure that it is the correct size and contains only valid characters
718 // and that a backup with that name doesn't already exist
719 char backup_name[MAX_BACKUP_NAME_LEN];
720 char backup_loc[255], tw_image_dir[255];
721 int copy_size;
722 int index, cur_char;
Ethan Yonker53796e72019-01-11 22:49:52 -0600723 string Backup_Loc;
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400724
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400725 copy_size = Backup_Name.size();
726 // Check size
727 if (copy_size > MAX_BACKUP_NAME_LEN) {
728 if (Display_Error)
Ethan Yonker74db1572015-10-28 12:44:49 -0500729 gui_err("backup_name_len=Backup name is too long.");
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400730 return -2;
731 }
732
733 // Check each character
734 strncpy(backup_name, Backup_Name.c_str(), copy_size);
Dees_Troya13d74f2013-03-24 08:54:55 -0500735 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400736 return 0; // A "0" (zero) means to use the current timestamp for the backup name
737 for (index=0; index<copy_size; index++) {
738 cur_char = (int)backup_name[index];
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500739 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 -0400740 // These are valid characters
741 // Numbers
742 // Upper case letters
743 // Lower case letters
744 // Space
745 // and -_.{}[]
746 } else {
747 if (Display_Error)
Ethan Yonker4adc33e2016-01-22 16:07:11 -0600748 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 -0400749 return -3;
750 }
751 }
752
Ethan Yonker53796e72019-01-11 22:49:52 -0600753 if (Must_Be_Unique) {
754 // Check to make sure that a backup with this name doesn't already exist
755 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
756 strcpy(backup_loc, Backup_Loc.c_str());
757 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
758 if (TWFunc::Path_Exists(tw_image_dir)) {
759 if (Display_Error)
760 gui_err("backup_name_exists=A backup with that name already exists!");
bigbiffce8f83c2015-12-12 18:30:21 -0500761
Ethan Yonker53796e72019-01-11 22:49:52 -0600762 return -4;
763 }
764 // Backup is unique
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400765 }
Ethan Yonker53796e72019-01-11 22:49:52 -0600766 // No problems found
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400767 return 0;
768}
769
bigbiffce8f83c2015-12-12 18:30:21 -0500770bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400771 time_t start, stop;
Matt Mower23d8aae2017-01-06 14:30:33 -0600772 int use_compression;
bigbiffce8f83c2015-12-12 18:30:21 -0500773 string backup_log = part_settings->Backup_Folder + "/recovery.log";
Dees_Troy43d8b002012-09-17 16:00:01 -0400774
bigbiffce8f83c2015-12-12 18:30:21 -0500775 if (part_settings->Part == NULL)
Dees_Troy43d8b002012-09-17 16:00:01 -0400776 return true;
777
Dees_Troy093b7642012-09-21 15:59:38 -0400778 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -0400779
Tom Hite5a926722014-09-15 01:31:03 +0000780 TWFunc::SetPerformanceMode(true);
Dees_Troy43d8b002012-09-17 16:00:01 -0400781 time(&start);
782
bigbiffce8f83c2015-12-12 18:30:21 -0500783 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500784 sync();
785 sync();
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400786 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500787 if (!part_settings->adbbackup && part_settings->generate_digest) {
788 if (!twrpDigestDriver::Make_Digest(Full_Filename))
789 goto backup_error;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400790 }
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400791
bigbiffce8f83c2015-12-12 18:30:21 -0500792 if (part_settings->Part->Has_SubPartition) {
Dees_Troy8170a922012-09-18 15:40:25 -0400793 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400794 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -0400795
796 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400797 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500798 part_settings->Part = *subpart;
bigbiffce8f83c2015-12-12 18:30:21 -0500799 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500800 goto backup_error;
Tom Hite5a926722014-09-15 01:31:03 +0000801 }
Dees_Troy2727b992013-08-14 20:09:30 +0000802 sync();
803 sync();
bigbiff bigbifff5955b12019-05-18 17:28:58 -0400804 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400805 if (!part_settings->adbbackup && part_settings->generate_digest) {
806 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500807 goto backup_error;
bigbiffce8f83c2015-12-12 18:30:21 -0500808 }
Tom Hite5a926722014-09-15 01:31:03 +0000809 }
Dees_Troy8170a922012-09-18 15:40:25 -0400810 }
811 }
812 }
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400813
Dees_Troy43d8b002012-09-17 16:00:01 -0400814 time(&stop);
that203bcc92015-05-09 17:27:33 +0200815 int backup_time = (int) difftime(stop, start);
Dees_Troy2673cec2013-04-02 20:22:16 +0000816 LOGINFO("Partition Backup time: %d\n", backup_time);
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400817
bigbiffce8f83c2015-12-12 18:30:21 -0500818 if (part_settings->Part->Backup_Method == BM_FILES) {
819 part_settings->file_time += backup_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400820 } else {
bigbiffce8f83c2015-12-12 18:30:21 -0500821 part_settings->img_time += backup_time;
822
Dees_Troy43d8b002012-09-17 16:00:01 -0400823 }
Tom Hite5a926722014-09-15 01:31:03 +0000824
Matt Mower02899552016-12-30 18:13:51 -0600825 TWFunc::SetPerformanceMode(false);
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500826 return true;
Dees_Troy43d8b002012-09-17 16:00:01 -0400827 }
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500828backup_error:
829 Clean_Backup_Folder(part_settings->Backup_Folder);
830 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
831 tw_set_default_metadata(backup_log.c_str());
832 TWFunc::SetPerformanceMode(false);
833 return false;
bigbiff7abc5fe2015-01-17 16:53:12 -0500834}
835
bigbiffbf1d6722015-02-14 16:25:59 -0500836void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
837 DIR *d = opendir(Backup_Folder.c_str());
838 struct dirent *p;
839 int r;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400840 vector<string> ext;
841
842 //extensions we should delete when cleaning
843 ext.push_back("win");
844 ext.push_back("md5");
845 ext.push_back("sha2");
846 ext.push_back("info");
bigbiffbf1d6722015-02-14 16:25:59 -0500847
Ethan Yonker74db1572015-10-28 12:44:49 -0500848 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
bigbiffbf1d6722015-02-14 16:25:59 -0500849
850 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500851 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
bigbiffbf1d6722015-02-14 16:25:59 -0500852 return;
853 }
854
Matt Mower2b18a532015-02-20 16:58:05 -0600855 while ((p = readdir(d))) {
bigbiffbf1d6722015-02-14 16:25:59 -0500856 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
857 continue;
858
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500859 string path = Backup_Folder + "/" + p->d_name;
bigbiffbf1d6722015-02-14 16:25:59 -0500860
861 size_t dot = path.find_last_of(".") + 1;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400862 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
863 if (path.substr(dot) == *i) {
864 r = unlink(path.c_str());
865 if (r != 0)
866 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
bigbiffbf1d6722015-02-14 16:25:59 -0500867 }
868 }
869 }
870 closedir(d);
871}
872
Ethan Yonker472f5062016-02-25 13:47:30 -0600873int TWPartitionManager::Check_Backup_Cancel() {
874 return stop_backup.get_value();
875}
876
bigbiff7abc5fe2015-01-17 16:53:12 -0500877int TWPartitionManager::Cancel_Backup() {
878 string Backup_Folder, Backup_Name, Full_Backup_Path;
879
880 stop_backup.set_value(1);
881
882 if (tar_fork_pid != 0) {
883 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
884 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500885 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
bigbiff7abc5fe2015-01-17 16:53:12 -0500886 LOGINFO("Killing pid: %d\n", tar_fork_pid);
887 kill(tar_fork_pid, SIGUSR2);
888 while (kill(tar_fork_pid, 0) == 0) {
889 usleep(1000);
890 }
891 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
892 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
893 TWFunc::removeDir(Full_Backup_Path, false);
894 tar_fork_pid = 0;
895 }
896
897 return 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400898}
899
bigbiffce8f83c2015-12-12 18:30:21 -0500900int TWPartitionManager::Run_Backup(bool adbbackup) {
901 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400902 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
bigbiffce8f83c2015-12-12 18:30:21 -0500903 string Backup_Name, Backup_List, backup_path;
Matt Mower23d8aae2017-01-06 14:30:33 -0600904 unsigned long long total_bytes = 0, free_space = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400905 TWPartition* storage = NULL;
906 struct tm *t;
Matt Mower23d8aae2017-01-06 14:30:33 -0600907 time_t seconds, total_start, total_stop;
Dees_Troya13d74f2013-03-24 08:54:55 -0500908 size_t start_pos = 0, end_pos = 0;
bigbiff7abc5fe2015-01-17 16:53:12 -0500909 stop_backup.set_value(0);
Dees_Troy43d8b002012-09-17 16:00:01 -0400910 seconds = time(0);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500911 t = localtime(&seconds);
Dees_Troy43d8b002012-09-17 16:00:01 -0400912
bigbiffce8f83c2015-12-12 18:30:21 -0500913 part_settings.img_bytes_remaining = 0;
914 part_settings.file_bytes_remaining = 0;
915 part_settings.img_time = 0;
916 part_settings.file_time = 0;
917 part_settings.img_bytes = 0;
918 part_settings.file_bytes = 0;
919 part_settings.PM_Method = PM_BACKUP;
920
bigbiffce8f83c2015-12-12 18:30:21 -0500921 part_settings.adbbackup = adbbackup;
Dees_Troy43d8b002012-09-17 16:00:01 -0400922 time(&total_start);
923
924 Update_System_Details();
925
926 if (!Mount_Current_Storage(true))
927 return false;
928
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400929 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
930 if (skip_digest == 0)
931 part_settings.generate_digest = true;
Dees_Troyc5865ab2012-09-24 15:08:04 -0400932 else
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400933 part_settings.generate_digest = false;
Dees_Troy4a2a1262012-09-18 09:33:47 -0400934
bigbiffce8f83c2015-12-12 18:30:21 -0500935 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500936 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
937 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
938 Backup_Name = TWFunc::Get_Current_Date();
939 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
Dees Troyb21cc642013-09-10 17:36:41 +0000940 TWFunc::Auto_Generate_Backup_Name();
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500941 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
Dees_Troy43d8b002012-09-17 16:00:01 -0400942 }
bigbiffce8f83c2015-12-12 18:30:21 -0500943
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500944 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500945 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
bigbiffce8f83c2015-12-12 18:30:21 -0500946
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500947 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -0400948
Dees_Troy2673cec2013-04-02 20:22:16 +0000949 LOGINFO("Calculating backup details...\n");
Dees_Troya13d74f2013-03-24 08:54:55 -0500950 DataManager::GetValue("tw_backup_list", Backup_List);
bigbiff7ba75002020-04-11 20:47:09 -0400951 LOGINFO("Backup_List: %s\n", Backup_List.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500952 if (!Backup_List.empty()) {
953 end_pos = Backup_List.find(";", start_pos);
954 while (end_pos != string::npos && start_pos < Backup_List.size()) {
955 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiff7ba75002020-04-11 20:47:09 -0400956 LOGINFO("backup_path: %s\n", backup_path.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -0500957 part_settings.Part = Find_Partition_By_Path(backup_path);
958 if (part_settings.Part != NULL) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500959 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -0500960 if (part_settings.Part->Backup_Method == BM_FILES)
961 part_settings.file_bytes += part_settings.Part->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500962 else
bigbiffce8f83c2015-12-12 18:30:21 -0500963 part_settings.img_bytes += part_settings.Part->Backup_Size;
964 if (part_settings.Part->Has_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -0500965 std::vector<TWPartition*>::iterator subpart;
966
967 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiffce8f83c2015-12-12 18:30:21 -0500968 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 -0500969 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -0500970 if ((*subpart)->Backup_Method == BM_FILES)
971 part_settings.file_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500972 else
bigbiffce8f83c2015-12-12 18:30:21 -0500973 part_settings.img_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -0500974 }
975 }
Dees_Troy8170a922012-09-18 15:40:25 -0400976 }
Dees_Troya13d74f2013-03-24 08:54:55 -0500977 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500978 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 -0400979 }
Dees_Troya13d74f2013-03-24 08:54:55 -0500980 start_pos = end_pos + 1;
981 end_pos = Backup_List.find(";", start_pos);
Dees_Troy43d8b002012-09-17 16:00:01 -0400982 }
983 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400984
985 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500986 gui_msg("no_partition_selected=No partitions selected for backup.");
Dees_Troy43d8b002012-09-17 16:00:01 -0400987 return false;
988 }
bigbiffce8f83c2015-12-12 18:30:21 -0500989 if (adbbackup) {
990 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
991 return false;
992 }
993 }
994 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
Ethan Yonker472f5062016-02-25 13:47:30 -0600995 ProgressTracking progress(total_bytes);
bigbiffce8f83c2015-12-12 18:30:21 -0500996 part_settings.progress = &progress;
997
Ethan Yonker74db1572015-10-28 12:44:49 -0500998 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
999 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001000 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1001 if (storage != NULL) {
1002 free_space = storage->Free;
Ethan Yonker74db1572015-10-28 12:44:49 -05001003 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001004 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001005 gui_err("unable_locate_storage=Unable to locate storage device.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001006 return false;
1007 }
bigbiffbf1d6722015-02-14 16:25:59 -05001008
Matt Mowerbfccfb82016-04-25 23:22:31 -05001009 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
bigbiffce8f83c2015-12-12 18:30:21 -05001010
1011 if (adbbackup)
1012 disable_free_space_check = true;
1013
bigbiffbf1d6722015-02-14 16:25:59 -05001014 if (!disable_free_space_check) {
1015 if (free_space - (32 * 1024 * 1024) < total_bytes) {
1016 // We require an extra 32MB just in case
Ethan Yonker74db1572015-10-28 12:44:49 -05001017 gui_err("no_space=Not enough free space on storage.");
bigbiffbf1d6722015-02-14 16:25:59 -05001018 return false;
1019 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001020 }
bigbiffce8f83c2015-12-12 18:30:21 -05001021 part_settings.img_bytes_remaining = part_settings.img_bytes;
1022 part_settings.file_bytes_remaining = part_settings.file_bytes;
Dees_Troy43d8b002012-09-17 16:00:01 -04001023
Ethan Yonker74db1572015-10-28 12:44:49 -05001024 gui_msg("backup_started=[BACKUP STARTED]");
bigbiff bigbiffcdd97c72019-03-29 19:12:33 -04001025
1026 int is_decrypted = 0;
1027 int is_encrypted = 0;
1028
1029 DataManager::GetValue(TW_IS_DECRYPTED, is_decrypted);
1030 DataManager::GetValue(TW_IS_ENCRYPTED, is_encrypted);
1031 if (!adbbackup || (!is_encrypted || (is_encrypted && is_decrypted))) {
1032 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
1033 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
1034 gui_err("fail_backup_folder=Failed to make backup folder.");
1035 return false;
1036 }
Dees_Troyd4b22b02013-01-18 17:17:58 +00001037 }
1038
Dees_Troy2673cec2013-04-02 20:22:16 +00001039 DataManager::SetProgress(0.0);
Dees_Troy093b7642012-09-21 15:59:38 -04001040
Dees_Troya13d74f2013-03-24 08:54:55 -05001041 start_pos = 0;
1042 end_pos = Backup_List.find(";", start_pos);
1043 while (end_pos != string::npos && start_pos < Backup_List.size()) {
bigbiff7abc5fe2015-01-17 16:53:12 -05001044 if (stop_backup.get_value() != 0)
1045 return -1;
Dees_Troya13d74f2013-03-24 08:54:55 -05001046 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001047 part_settings.Part = Find_Partition_By_Path(backup_path);
1048 if (part_settings.Part != NULL) {
1049 if (!Backup_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001050 return false;
1051 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001052 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 -05001053 }
1054 start_pos = end_pos + 1;
1055 end_pos = Backup_List.find(";", start_pos);
1056 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001057
1058 // Average BPS
bigbiffce8f83c2015-12-12 18:30:21 -05001059 if (part_settings.img_time == 0)
1060 part_settings.img_time = 1;
1061 if (part_settings.file_time == 0)
1062 part_settings.file_time = 1;
1063 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
1064 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
Dees_Troy43d8b002012-09-17 16:00:01 -04001065
bigbiffce8f83c2015-12-12 18:30:21 -05001066 if (part_settings.file_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001067 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 -05001068 if (part_settings.img_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001069 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 -04001070
1071 time(&total_stop);
1072 int total_time = (int) difftime(total_stop, total_start);
bigbiffce8f83c2015-12-12 18:30:21 -05001073
1074 uint64_t actual_backup_size;
Ethan Yonker3fdcda42016-11-30 12:29:37 -06001075 if (!adbbackup) {
1076 TWExclude twe;
1077 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
1078 } else
bigbiffce8f83c2015-12-12 18:30:21 -05001079 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001080 actual_backup_size /= (1024LLU * 1024LLU);
Dees_Troy43d8b002012-09-17 16:00:01 -04001081
bigbiffce8f83c2015-12-12 18:30:21 -05001082 int prev_img_bps = 0, use_compression = 0;
1083 unsigned long long prev_file_bps = 0;
Matt Mower173cdb92016-12-31 02:49:19 -06001084 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001085 img_bps += (prev_img_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001086 img_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001087
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001088 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -04001089 if (use_compression)
1090 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001091 else
Dees_Troy093b7642012-09-21 15:59:38 -04001092 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
1093 file_bps += (prev_file_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001094 file_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001095
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001096 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001097 if (use_compression)
1098 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
1099 else
1100 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
1101
Ethan Yonker74db1572015-10-28 12:44:49 -05001102 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Dees_Troy43d8b002012-09-17 16:00:01 -04001103 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001104 UnMount_Main_Partitions();
Ethan Yonker56db1c42015-12-20 22:49:00 -06001105 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001106 string backup_log = part_settings.Backup_Folder + "/recovery.log";
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001107 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -06001108 tw_set_default_metadata(backup_log.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001109
1110 if (part_settings.adbbackup) {
1111 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
1112 return false;
1113 }
1114 }
1115 part_settings.adbbackup = false;
1116 DataManager::SetValue("tw_enable_adb_backup", 0);
1117
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001118 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001119}
1120
bigbiffce8f83c2015-12-12 18:30:21 -05001121bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
Dees_Troy4a2a1262012-09-18 09:33:47 -04001122 time_t Start, Stop;
bigbiffce8f83c2015-12-12 18:30:21 -05001123
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001124 if (part_settings->adbbackup) {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001125 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
1126 LOGINFO("setting backup name: %s\n", partName.c_str());
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001127 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
1128 }
1129
Tom Hite5a926722014-09-15 01:31:03 +00001130 TWFunc::SetPerformanceMode(true);
bigbiffce8f83c2015-12-12 18:30:21 -05001131
Dees_Troy4a2a1262012-09-18 09:33:47 -04001132 time(&Start);
Ethan Yonker472f5062016-02-25 13:47:30 -06001133
bigbiffce8f83c2015-12-12 18:30:21 -05001134 if (!part_settings->Part->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001135 TWFunc::SetPerformanceMode(false);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001136 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001137 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001138 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
Dees_Troy8170a922012-09-18 15:40:25 -04001139 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001140 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -04001141
1142 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001143 part_settings->Part = *subpart;
1144 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1145 part_settings->Part = (*subpart);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001146 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
bigbiffce8f83c2015-12-12 18:30:21 -05001147 if (!(*subpart)->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001148 TWFunc::SetPerformanceMode(false);
Dees_Troy8170a922012-09-18 15:40:25 -04001149 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001150 }
Dees_Troy8170a922012-09-18 15:40:25 -04001151 }
1152 }
1153 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001154 time(&Stop);
Tom Hite5a926722014-09-15 01:31:03 +00001155 TWFunc::SetPerformanceMode(false);
bigbiffce8f83c2015-12-12 18:30:21 -05001156 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1157
Dees_Troy4a2a1262012-09-18 09:33:47 -04001158 return true;
1159}
1160
Ethan Yonker472f5062016-02-25 13:47:30 -06001161int TWPartitionManager::Run_Restore(const string& Restore_Name) {
bigbiffce8f83c2015-12-12 18:30:21 -05001162 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001163 int check_digest;
bigbiffce8f83c2015-12-12 18:30:21 -05001164
Dees_Troy4a2a1262012-09-18 09:33:47 -04001165 time_t rStart, rStop;
1166 time(&rStart);
Dees_Troya13d74f2013-03-24 08:54:55 -05001167 string Restore_List, restore_path;
1168 size_t start_pos = 0, end_pos;
bigbiffce8f83c2015-12-12 18:30:21 -05001169
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001170 part_settings.Backup_Folder = Restore_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001171 part_settings.Part = NULL;
1172 part_settings.partition_count = 0;
1173 part_settings.total_restore_size = 0;
1174 part_settings.adbbackup = false;
1175 part_settings.PM_Method = PM_RESTORE;
Dees_Troy43d8b002012-09-17 16:00:01 -04001176
Ethan Yonker74db1572015-10-28 12:44:49 -05001177 gui_msg("restore_started=[RESTORE STARTED]");
1178 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
Dees_Troy43d8b002012-09-17 16:00:01 -04001179
Dees_Troy4a2a1262012-09-18 09:33:47 -04001180 if (!Mount_Current_Storage(true))
1181 return false;
1182
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001183 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1184 if (check_digest > 0) {
1185 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1186 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1187 gui_msg("verifying_digest=Verifying Digest");
Dees_Troya13d74f2013-03-24 08:54:55 -05001188 } else {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001189 gui_msg("skip_digest=Skipping Digest check based on user setting.");
Dees_Troya13d74f2013-03-24 08:54:55 -05001190 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001191 gui_msg("calc_restore=Calculating restore details...");
Dees_Troya13d74f2013-03-24 08:54:55 -05001192 DataManager::GetValue("tw_restore_selected", Restore_List);
bigbiffce8f83c2015-12-12 18:30:21 -05001193
Dees_Troya13d74f2013-03-24 08:54:55 -05001194 if (!Restore_List.empty()) {
1195 end_pos = Restore_List.find(";", start_pos);
1196 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1197 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001198 part_settings.Part = Find_Partition_By_Path(restore_path);
1199 if (part_settings.Part != NULL) {
bigbiffce8f83c2015-12-12 18:30:21 -05001200 if (part_settings.Part->Mount_Read_Only) {
1201 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 -05001202 return false;
1203 }
bigbiffce8f83c2015-12-12 18:30:21 -05001204
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001205 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1206
bigbiff4a60bee2021-01-23 14:08:03 -05001207 if (tw_get_default_metadata(Get_Android_Root_Path().c_str()) != 0) {
1208 gui_msg(Msg(msg::kWarning, "restore_system_context=Unable to get default context for {1} -- Android may not boot.")(Get_Android_Root_Path()));
1209 }
1210
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001211 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001212 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001213 part_settings.partition_count++;
1214 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1215 if (part_settings.Part->Has_SubPartition) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001216 TWPartition *parentPart = part_settings.Part;
Dees_Troya13d74f2013-03-24 08:54:55 -05001217 std::vector<TWPartition*>::iterator subpart;
1218
1219 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001220 part_settings.Part = *subpart;
1221 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001222 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001223 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001224 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
Dees_Troya13d74f2013-03-24 08:54:55 -05001225 }
1226 }
1227 }
1228 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001229 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001230 }
1231 start_pos = end_pos + 1;
1232 end_pos = Restore_List.find(";", start_pos);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001233 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001234 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001235
bigbiffce8f83c2015-12-12 18:30:21 -05001236 if (part_settings.partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001237 gui_err("no_part_restore=No partitions selected for restore.");
Dees_Troy4a2a1262012-09-18 09:33:47 -04001238 return false;
1239 }
1240
bigbiffce8f83c2015-12-12 18:30:21 -05001241 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1242 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 +00001243 DataManager::SetProgress(0.0);
bigbiffce8f83c2015-12-12 18:30:21 -05001244 ProgressTracking progress(part_settings.total_restore_size);
1245 part_settings.progress = &progress;
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001246
Dees_Troya13d74f2013-03-24 08:54:55 -05001247 start_pos = 0;
1248 if (!Restore_List.empty()) {
1249 end_pos = Restore_List.find(";", start_pos);
1250 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1251 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001252
1253 part_settings.Part = Find_Partition_By_Path(restore_path);
1254 if (part_settings.Part != NULL) {
1255 part_settings.partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001256 if (!Restore_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001257 return false;
1258 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001259 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001260 }
1261 start_pos = end_pos + 1;
1262 end_pos = Restore_List.find(";", start_pos);
1263 }
1264 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001265 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
bigbiff4a60bee2021-01-23 14:08:03 -05001266 tw_set_default_metadata(Get_Android_Root_Path().c_str());
Captain Throwback9d6feb52018-07-27 10:05:24 -04001267 UnMount_By_Path(Get_Android_Root_Path(), false);
Dees_Troy43d8b002012-09-17 16:00:01 -04001268 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001269 UnMount_Main_Partitions();
Dees_Troy4a2a1262012-09-18 09:33:47 -04001270 time(&rStop);
Matt Mower3c366972015-12-25 19:28:31 -06001271 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
bigbiff8f5fad32021-11-03 20:39:02 -04001272 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
1273 if (Decrypt_Data && Decrypt_Data->Is_Encrypted)
1274 gui_msg(Msg(msg::kWarning, "reboot_after_restore=It is recommended to reboot Android once after first boot."));
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001275 DataManager::SetValue("tw_file_progress", "");
bigbiffce8f83c2015-12-12 18:30:21 -05001276
Dees_Troy63c8df72012-09-10 14:02:05 -04001277 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001278}
1279
1280void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001281 // Start with the default values
Dees_Troya13d74f2013-03-24 08:54:55 -05001282 string Restore_List;
Dees_Troy83bd4832013-05-04 12:39:56 +00001283 bool get_date = true, check_encryption = true;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001284 bool adbbackup = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001285
1286 DataManager::SetValue("tw_restore_encrypted", 0);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001287 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1288 vector<string> adb_files;
1289 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1290 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1291 string adb_restore_file = adb_files.at(i);
1292 std::size_t pos = adb_restore_file.find_first_of(".");
1293 std::string path = "/" + adb_restore_file.substr(0, pos);
1294 Restore_List = path + ";";
1295 TWPartition* Part = Find_Partition_By_Path(path);
1296 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1297 adbbackup = true;
1298 }
1299 DataManager::SetValue("tw_enable_adb_backup", 1);
Dees_Troy63c8df72012-09-10 14:02:05 -04001300 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001301 else {
1302 DIR* d;
1303 d = opendir(Restore_Name.c_str());
1304 if (d == NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001305 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001306 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1307 return;
Dees_Troy63c8df72012-09-10 14:02:05 -04001308 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001309
1310 struct dirent* de;
1311 while ((de = readdir(d)) != NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001312 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001313 // Strip off three components
1314 char str[256];
1315 char* label;
1316 char* fstype = NULL;
1317 char* extn = NULL;
1318 char* ptr;
Dees_Troy63c8df72012-09-10 14:02:05 -04001319
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001320 strcpy(str, de->d_name);
1321 if (strlen(str) <= 2)
1322 continue;
Dees_Troy83bd4832013-05-04 12:39:56 +00001323
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001324 if (get_date) {
1325 char file_path[255];
1326 struct stat st;
1327
1328 strcpy(file_path, Restore_Name.c_str());
1329 strcat(file_path, "/");
1330 strcat(file_path, str);
1331 stat(file_path, &st);
1332 string backup_date = ctime((const time_t*)(&st.st_mtime));
1333 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1334 get_date = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001335 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001336
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001337 label = str;
1338 ptr = label;
1339 while (*ptr && *ptr != '.') ptr++;
1340 if (*ptr == '.')
1341 {
1342 *ptr = 0x00;
1343 ptr++;
1344 fstype = ptr;
1345 }
1346 while (*ptr && *ptr != '.') ptr++;
1347 if (*ptr == '.')
1348 {
1349 *ptr = 0x00;
1350 ptr++;
1351 extn = ptr;
1352 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001353
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001354 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1355 int extnlength = strlen(extn);
1356 if (extnlength != 3 && extnlength != 6) continue;
1357 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1358 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
Dees_Troy63c8df72012-09-10 14:02:05 -04001359
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001360 if (check_encryption) {
1361 string filename = Restore_Name + "/";
1362 filename += de->d_name;
1363 if (TWFunc::Get_File_Type(filename) == 2) {
1364 LOGINFO("'%s' is encrypted\n", filename.c_str());
1365 DataManager::SetValue("tw_restore_encrypted", 1);
1366 }
1367 }
1368 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1369
1370 TWPartition* Part = Find_Partition_By_Path(label);
1371 if (Part == NULL)
1372 {
1373 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1374 continue;
1375 }
1376
1377 Part->Backup_FileName = de->d_name;
1378 if (strlen(extn) > 3) {
1379 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1380 }
1381
dianlujitaob76a73a2020-04-30 20:33:20 +08001382 if (!Part->Is_SubPartition) {
1383 if (Part->Backup_Path == Get_Android_Root_Path())
1384 Restore_List += "/system;";
1385 else
1386 Restore_List += Part->Backup_Path + ";";
1387 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001388 }
1389 closedir(d);
Dees_Troy63c8df72012-09-10 14:02:05 -04001390 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001391
1392 if (adbbackup) {
1393 Restore_List = "ADB_Backup;";
1394 adbbackup = false;
1395 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001396
Dees_Troya13d74f2013-03-24 08:54:55 -05001397 // Set the final value
1398 DataManager::SetValue("tw_restore_list", Restore_List);
1399 DataManager::SetValue("tw_restore_selected", Restore_List);
Dees_Troy51a0e822012-09-05 15:24:24 -04001400 return;
1401}
1402
1403int TWPartitionManager::Wipe_By_Path(string Path) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001404 std::vector<TWPartition*>::iterator iter;
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301405 std::vector < TWPartition * >::iterator iter1;
Dees_Troy63c8df72012-09-10 14:02:05 -04001406 int ret = false;
1407 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -04001408 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy63c8df72012-09-10 14:02:05 -04001409
dianlujitaob76a73a2020-04-30 20:33:20 +08001410 if (Local_Path == "/system")
1411 Local_Path = Get_Android_Root_Path();
bigbiffaed1bdf2021-08-03 18:21:39 -04001412 if (Path == "/cache") {
1413 TWPartition* cache = Find_Partition_By_Path("/cache");
1414 if (cache == nullptr) {
1415 TWPartition* dat = Find_Partition_By_Path("/data");
1416 if (dat) {
1417 dat->Wipe_Data_Cache();
1418 found = true;
1419 }
1420 }
1421 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001422 // Iterate through all partitions
1423 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -04001424 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301425 // iterate through all partitions since some legacy devices uses other partitions as vendor causes issues while wiping
1426 (*iter)->Find_Actual_Block_Device();
1427 for (iter1 = Partitions.begin (); iter1 != Partitions.end (); iter1++)
1428 {
1429 (*iter1)->Find_Actual_Block_Device();
1430 if ((*iter)->Actual_Block_Device == (*iter1)->Actual_Block_Device && (*iter)->Mount_Point != (*iter1)->Mount_Point)
1431 (*iter1)->UnMount(false);
1432 }
Dees_Troye58d5262012-09-21 12:27:57 -04001433 if (Path == "/and-sec")
1434 ret = (*iter)->Wipe_AndSec();
1435 else
1436 ret = (*iter)->Wipe();
Dees_Troy63c8df72012-09-10 14:02:05 -04001437 found = true;
1438 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1439 (*iter)->Wipe();
1440 }
1441 }
1442 if (found) {
1443 return ret;
1444 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001445 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 -04001446 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -04001447}
1448
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001449int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1450 std::vector<TWPartition*>::iterator iter;
1451 int ret = false;
1452 bool found = false;
1453 string Local_Path = TWFunc::Get_Root_Path(Path);
1454
1455 // Iterate through all partitions
1456 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1457 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1458 if (Path == "/and-sec")
1459 ret = (*iter)->Wipe_AndSec();
1460 else
1461 ret = (*iter)->Wipe(New_File_System);
1462 found = true;
1463 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1464 (*iter)->Wipe(New_File_System);
1465 }
1466 }
1467 if (found) {
1468 return ret;
1469 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001470 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 -05001471 return false;
1472}
1473
Dees_Troy51a0e822012-09-05 15:24:24 -04001474int TWPartitionManager::Factory_Reset(void) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001475 std::vector<TWPartition*>::iterator iter;
1476 int ret = true;
1477
1478 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001479 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
Ethan Yonker89583ef2015-08-26 09:01:59 -05001480#ifdef TW_OEM_BUILD
1481 if ((*iter)->Mount_Point == "/data") {
1482 if (!(*iter)->Wipe_Encryption())
1483 ret = false;
1484 } else {
1485#endif
1486 if (!(*iter)->Wipe())
1487 ret = false;
1488#ifdef TW_OEM_BUILD
1489 }
1490#endif
Dees_Troy094207a2012-09-26 12:00:39 -04001491 } else if ((*iter)->Has_Android_Secure) {
1492 if (!(*iter)->Wipe_AndSec())
1493 ret = false;
Dees_Troy63c8df72012-09-10 14:02:05 -04001494 }
1495 }
bigbiffad58e1b2020-07-06 20:24:34 -04001496 TWFunc::check_and_run_script("/system/bin/factoryreset.sh", "Factory Reset Script");
Dees_Troy63c8df72012-09-10 14:02:05 -04001497 return ret;
Dees_Troy51a0e822012-09-05 15:24:24 -04001498}
1499
Dees_Troy38bd7602012-09-14 13:33:53 -04001500int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1501 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001502 vector <string> dir;
Dees_Troy38bd7602012-09-14 13:33:53 -04001503
1504 if (!Mount_By_Path("/data", true))
1505 return false;
1506
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001507 dir.push_back("/data/dalvik-cache");
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001508
bigbiff25d25b92020-06-19 16:07:38 -04001509 std::string cacheDir = TWFunc::get_log_dir();
1510 if (cacheDir == CACHE_LOGS_DIR) {
1511 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
1512 LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001513 }
1514 dir.push_back(cacheDir + "dalvik-cache");
1515 dir.push_back(cacheDir + "/dc");
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001516 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001517
Dees_Troy38bd7602012-09-14 13:33:53 -04001518 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001519 if (sdext && sdext->Is_Present && sdext->Mount(false))
1520 {
1521 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1522 {
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001523 dir.push_back("/sd-ext/dalvik-cache");
1524 }
1525 }
1526
bigbiff25d25b92020-06-19 16:07:38 -04001527 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001528 gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
1529 } else {
1530 gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
1531 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001532 for (unsigned i = 0; i < dir.size(); ++i) {
1533 if (stat(dir.at(i).c_str(), &st) == 0) {
1534 TWFunc::removeDir(dir.at(i), false);
1535 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001536 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001537 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001538
bigbiff25d25b92020-06-19 16:07:38 -04001539 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001540 gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1541 } else {
1542 gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
1543 }
1544
Dees_Troy38bd7602012-09-14 13:33:53 -04001545 return true;
1546}
1547
1548int TWPartitionManager::Wipe_Rotate_Data(void) {
1549 if (!Mount_By_Path("/data", true))
1550 return false;
1551
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001552 unlink("/data/misc/akmd*");
1553 unlink("/data/misc/rild*");
Dees_Troy2673cec2013-04-02 20:22:16 +00001554 gui_print("Rotation data wiped.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001555 return true;
1556}
1557
1558int TWPartitionManager::Wipe_Battery_Stats(void) {
1559 struct stat st;
1560
1561 if (!Mount_By_Path("/data", true))
1562 return false;
1563
1564 if (0 != stat("/data/system/batterystats.bin", &st)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001565 gui_print("No Battery Stats Found. No Need To Wipe.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001566 } else {
1567 remove("/data/system/batterystats.bin");
Dees_Troy2673cec2013-04-02 20:22:16 +00001568 gui_print("Cleared battery stats.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001569 }
1570 return true;
1571}
1572
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001573int TWPartitionManager::Wipe_Android_Secure(void) {
1574 std::vector<TWPartition*>::iterator iter;
1575 int ret = false;
1576 bool found = false;
1577
1578 // Iterate through all partitions
1579 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1580 if ((*iter)->Has_Android_Secure) {
1581 ret = (*iter)->Wipe_AndSec();
1582 found = true;
1583 }
1584 }
1585 if (found) {
1586 return ret;
1587 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001588 gui_err("no_andsec=No android secure partitions found.");
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001589 }
1590 return false;
1591}
1592
Dees_Troy38bd7602012-09-14 13:33:53 -04001593int TWPartitionManager::Format_Data(void) {
1594 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffcfa875c2021-06-20 16:20:27 -04001595 TWPartition* metadata = Find_Partition_By_Path("/metadata");
1596 if (metadata != NULL)
1597 metadata->UnMount(false);
Dees_Troy38bd7602012-09-14 13:33:53 -04001598
1599 if (dat != NULL) {
bigbiffab76bd72021-10-11 10:17:48 -04001600 if (android::base::GetBoolProperty("ro.virtual_ab.enabled", false)) {
bigbiffcfa875c2021-06-20 16:20:27 -04001601#ifndef TW_EXCLUDE_APEX
1602 twrpApex apex;
1603 apex.Unmount();
1604#endif
1605 if (metadata != NULL)
1606 metadata->Mount(true);
bigbiffd21252f2021-09-18 15:56:32 -04001607 if (!Check_Pending_Merges())
bigbiffcfa875c2021-06-20 16:20:27 -04001608 return false;
1609 }
Dees_Troy38bd7602012-09-14 13:33:53 -04001610 return dat->Wipe_Encryption();
1611 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001612 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001613 return false;
1614 }
1615 return false;
1616}
1617
1618int TWPartitionManager::Wipe_Media_From_Data(void) {
1619 TWPartition* dat = Find_Partition_By_Path("/data");
1620
1621 if (dat != NULL) {
1622 if (!dat->Has_Data_Media) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001623 LOGERR("This device does not have /data/media\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001624 return false;
1625 }
1626 if (!dat->Mount(true))
1627 return false;
1628
Ethan Yonker74db1572015-10-28 12:44:49 -05001629 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
Ethan Yonker726a0202014-12-16 20:01:38 -06001630 Remove_MTP_Storage(dat->MTP_Storage_ID);
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001631 TWFunc::removeDir("/data/media", false);
xiaolu9416f4f2015-06-04 08:22:23 +08001632 dat->Recreate_Media_Folder();
Ethan Yonker726a0202014-12-16 20:01:38 -06001633 Add_MTP_Storage(dat->MTP_Storage_ID);
Dees_Troy38bd7602012-09-14 13:33:53 -04001634 return true;
1635 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001636 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001637 return false;
1638 }
1639 return false;
1640}
1641
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001642int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1643 std::vector<TWPartition*>::iterator iter;
1644 int ret = false;
1645 bool found = false;
1646 string Local_Path = TWFunc::Get_Root_Path(Path);
1647
1648 if (Local_Path == "/tmp" || Local_Path == "/")
1649 return true;
1650
1651 // Iterate through all partitions
1652 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1653 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1654 ret = (*iter)->Repair();
1655 found = true;
1656 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1657 (*iter)->Repair();
1658 }
1659 }
1660 if (found) {
1661 return ret;
1662 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001663 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 -05001664 } else {
1665 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1666 }
1667 return false;
1668}
1669
Ethan Yonkera2719152015-05-28 09:44:41 -05001670int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1671 std::vector<TWPartition*>::iterator iter;
1672 int ret = false;
1673 bool found = false;
1674 string Local_Path = TWFunc::Get_Root_Path(Path);
1675
1676 if (Local_Path == "/tmp" || Local_Path == "/")
1677 return true;
1678
1679 // Iterate through all partitions
1680 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1681 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1682 ret = (*iter)->Resize();
1683 found = true;
1684 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1685 (*iter)->Resize();
1686 }
1687 }
1688 if (found) {
1689 return ret;
1690 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001691 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 -05001692 } else {
1693 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1694 }
1695 return false;
1696}
1697
Dees_Troy51a0e822012-09-05 15:24:24 -04001698void TWPartitionManager::Update_System_Details(void) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001699 std::vector<TWPartition*>::iterator iter;
Dees_Troy51127312012-09-08 13:08:49 -04001700 int data_size = 0;
Dees_Troy5bf43922012-09-07 16:07:55 -04001701
Ethan Yonker74db1572015-10-28 12:44:49 -05001702 gui_msg("update_part_details=Updating partition details...");
Dees_Troy5bf43922012-09-07 16:07:55 -04001703 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker1b190162016-12-05 15:25:19 -06001704 (*iter)->Update_Size(true);
Dees_Troy51127312012-09-08 13:08:49 -04001705 if ((*iter)->Can_Be_Mounted) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001706 if ((*iter)->Mount_Point == Get_Android_Root_Path()) {
Dees_Troy51127312012-09-08 13:08:49 -04001707 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1708 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001709 TWFunc::Is_TWRP_App_In_System();
Dees_Troy51127312012-09-08 13:08:49 -04001710 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1711 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1712 } else if ((*iter)->Mount_Point == "/cache") {
1713 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1714 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1715 } else if ((*iter)->Mount_Point == "/sd-ext") {
1716 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1717 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1718 if ((*iter)->Backup_Size == 0) {
1719 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1720 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1721 } else
1722 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
Dees_Troye58d5262012-09-21 12:27:57 -04001723 } else if ((*iter)->Has_Android_Secure) {
Dees_Troy8170a922012-09-18 15:40:25 -04001724 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troye58d5262012-09-21 12:27:57 -04001725 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
Dees_Troy8170a922012-09-18 15:40:25 -04001726 if ((*iter)->Backup_Size == 0) {
1727 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1728 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1729 } else
1730 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
Dees_Troy2c50e182012-09-26 20:05:28 -04001731 } else if ((*iter)->Mount_Point == "/boot") {
1732 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1733 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1734 if ((*iter)->Backup_Size == 0) {
1735 DataManager::SetValue("tw_has_boot_partition", 0);
1736 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1737 } else
1738 DataManager::SetValue("tw_has_boot_partition", 1);
Dees_Troy51127312012-09-08 13:08:49 -04001739 }
Dees_Troyaa9cc402012-10-13 12:14:05 -04001740 } else {
1741 // Handle unmountable partitions in case we reset defaults
1742 if ((*iter)->Mount_Point == "/boot") {
1743 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1744 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1745 if ((*iter)->Backup_Size == 0) {
1746 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1747 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1748 } else
1749 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1750 } else if ((*iter)->Mount_Point == "/recovery") {
1751 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1752 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1753 if ((*iter)->Backup_Size == 0) {
1754 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1755 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1756 } else
1757 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
Gary Peck82599a82012-11-21 16:23:12 -08001758 } else if ((*iter)->Mount_Point == "/data") {
1759 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troyaa9cc402012-10-13 12:14:05 -04001760 }
Dees_Troy51127312012-09-08 13:08:49 -04001761 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001762 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001763 gui_msg("update_part_details_done=...done");
Dees_Troy51127312012-09-08 13:08:49 -04001764 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1765 string current_storage_path = DataManager::GetCurrentStoragePath();
1766 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
Dees_Troy8170a922012-09-18 15:40:25 -04001767 if (FreeStorage != NULL) {
1768 // Attempt to mount storage
bigbiff25d25b92020-06-19 16:07:38 -04001769 if (!FreeStorage->Mount(false)) {
1770 gui_msg(Msg(msg::kWarning, "unable_to_mount_storage=Unable to mount storage"));
1771 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
1772 } else {
1773 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
Dees_Troy8170a922012-09-18 15:40:25 -04001774 }
1775 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00001776 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
Dees_Troy8170a922012-09-18 15:40:25 -04001777 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001778 if (!Write_Fstab())
Dees_Troy2673cec2013-04-02 20:22:16 +00001779 LOGERR("Error creating fstab\n");
Dees_Troy51a0e822012-09-05 15:24:24 -04001780 return;
1781}
1782
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001783void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1784 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffc2cb3852020-09-11 14:03:31 -04001785
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001786 if (dat != NULL) {
bigbiffaed1bdf2021-08-03 18:21:39 -04001787 // reparse for /cache/recovery/command
1788 static constexpr const char* COMMAND_FILE = "/data/cache/command";
1789 if (TWFunc::Path_Exists(COMMAND_FILE)) {
1790 startupArgs startup;
1791 std::string content;
1792 TWFunc::read_file(COMMAND_FILE, content);
1793 std::vector<std::string> args = {content};
1794 startup.processRecoveryArgs(args, 0);
1795 }
1796
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001797 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1798 dat->Is_Decrypted = true;
1799 if (!Block_Device.empty()) {
1800 dat->Decrypted_Block_Device = Block_Device;
1801 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1802 } else {
1803 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1804 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001805 property_set("twrp.decrypt.done", "true");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001806 dat->Setup_File_System(false);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001807 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 -06001808
Noah Jacobson81d638d2019-04-28 00:10:07 -04001809 sleep(1); // Sleep for a bit so that the device will be ready
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001810 if (dat->Has_Data_Media && dat->Mount(false) && TWFunc::Path_Exists("/data/media/0")) {
1811 dat->Storage_Path = "/data/media/0";
1812 dat->Symlink_Path = dat->Storage_Path;
1813 DataManager::SetValue("tw_storage_path", "/data/media/0");
1814 DataManager::SetValue("tw_settings_path", "/data/media/0");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001815 }
epicXa721f952021-01-04 13:01:31 +05301816 DataManager::LoadTWRPFolderInfo();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001817 Update_System_Details();
nkk71ffb02bd2017-06-04 23:12:16 +03001818 Output_Partition(dat);
bigbiffbe4f46c2021-04-24 11:48:54 -04001819 if (!dat->Bind_Mount(false))
1820 LOGERR("Unable to bind mount /sdcard to %s\n", dat->Storage_Path.c_str());
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001821 } else
1822 LOGERR("Unable to locate data partition.\n");
1823}
1824
Noah Jacobson81d638d2019-04-28 00:10:07 -04001825void TWPartitionManager::Parse_Users() {
1826#ifdef TW_INCLUDE_FBE
1827 char user_check_result[PROPERTY_VALUE_MAX];
1828 for (int userId = 0; userId <= 9999; userId++) {
1829 string prop = "twrp.user." + to_string(userId) + ".decrypt";
1830 property_get(prop.c_str(), user_check_result, "-1");
1831 if (strcmp(user_check_result, "-1") != 0) {
1832 if (userId < 0 || userId > 9999) {
1833 LOGINFO("Incorrect user id %d\n", userId);
1834 continue;
1835 }
1836 struct users_struct user;
1837 user.userId = to_string(userId);
1838
1839 // Attempt to get name of user. Fallback to user ID if this fails.
1840 char* userFile = PageManager::LoadFileToBuffer("/data/system/users/" + to_string(userId) + ".xml", NULL);
bigbiffa957f072021-03-07 18:20:29 -05001841 if (userFile == NULL) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04001842 user.userName = to_string(userId);
bigbiffa957f072021-03-07 18:20:29 -05001843 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001844 else {
1845 xml_document<> *userXml = new xml_document<>();
1846 userXml->parse<0>(userFile);
1847 xml_node<>* userNode = userXml->first_node("user");
1848 if (userNode == nullptr) {
1849 user.userName = to_string(userId);
1850 } else {
1851 xml_node<>* nameNode = userNode->first_node("name");
1852 if (nameNode == nullptr)
1853 user.userName = to_string(userId);
1854 else {
1855 string userName = nameNode->value();
1856 user.userName = userName + " (" + to_string(userId) + ")";
1857 }
1858 }
1859 }
1860
1861 string filename;
1862 user.type = Get_Password_Type(userId, filename);
1863
1864 user.isDecrypted = false;
1865 if (strcmp(user_check_result, "1") == 0)
1866 user.isDecrypted = true;
1867 Users_List.push_back(user);
1868 }
1869 }
1870 Check_Users_Decryption_Status();
1871#endif
1872}
1873
1874std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
1875 return &Users_List;
1876}
1877
1878void TWPartitionManager::Mark_User_Decrypted(int userID) {
1879#ifdef TW_INCLUDE_FBE
1880 std::vector<users_struct>::iterator iter;
1881 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1882 if (atoi((*iter).userId.c_str()) == userID) {
1883 (*iter).isDecrypted = true;
1884 string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
1885 property_set(user_prop_decrypted.c_str(), "1");
1886 break;
1887 }
1888 }
1889 Check_Users_Decryption_Status();
1890#endif
1891}
1892
1893void TWPartitionManager::Check_Users_Decryption_Status() {
1894#ifdef TW_INCLUDE_FBE
1895 int all_is_decrypted = 1;
1896 std::vector<users_struct>::iterator iter;
1897 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1898 if (!(*iter).isDecrypted) {
1899 LOGINFO("User %s is not decrypted.\n", (*iter).userId.c_str());
1900 all_is_decrypted = 0;
1901 break;
1902 }
1903 }
1904 if (all_is_decrypted == 1) {
1905 LOGINFO("All found users are decrypted.\n");
1906 DataManager::SetValue("tw_all_users_decrypted", "1");
1907 property_set("twrp.all.users.decrypted", "true");
1908 } else
1909 DataManager::SetValue("tw_all_users_decrypted", "0");
1910#endif
1911}
1912
1913int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001914#ifdef TW_INCLUDE_CRYPTO
Captain Throwback37c3aef2021-10-06 11:38:18 -04001915 char crypto_blkdev[PROPERTY_VALUE_MAX];
Ethan Yonker253368a2014-11-25 15:00:52 -06001916 std::vector<TWPartition*>::iterator iter;
Dees_Troy5bf43922012-09-07 16:07:55 -04001917
Ethan Yonker253368a2014-11-25 15:00:52 -06001918 // Mount any partitions that need to be mounted for decrypt
1919 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1920 if ((*iter)->Mount_To_Decrypt) {
1921 (*iter)->Mount(true);
1922 }
a39552696ff55ce2013-01-08 16:14:56 +00001923 }
oshmouna82a7542018-04-10 17:45:55 +02001924 property_set("twrp.mount_to_decrypt", "1");
a39552696ff55ce2013-01-08 16:14:56 +00001925
Captain Throwback37c3aef2021-10-06 11:38:18 -04001926 Set_Crypto_State();
1927 Set_Crypto_Type("block");
Ethan Yonkera1de1492015-11-04 11:58:27 -06001928
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001929 if (DataManager::GetIntValue(TW_IS_FBE)) {
1930#ifdef TW_INCLUDE_FBE
1931 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
1932 return -1;
Noah Jacobson81d638d2019-04-28 00:10:07 -04001933
1934 bool user_need_decrypt = false;
1935 std::vector<users_struct>::iterator iter;
1936 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1937 if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
1938 user_need_decrypt = true;
1939 }
1940 }
1941 if (!user_need_decrypt) {
1942 LOGINFO("User %d does not require decryption\n", user_id);
1943 return 0;
1944 }
1945
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001946 int retry_count = 10;
1947 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
Noah Jacobson81d638d2019-04-28 00:10:07 -04001948 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
1949 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001950 if (Decrypt_User(user_id, Password)) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04001951 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
1952 Mark_User_Decrypted(user_id);
1953 if (user_id == 0) {
1954 // When decrypting user 0 also try all other users
1955 std::vector<users_struct>::iterator iter;
1956 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
1957 if ((*iter).userId == "0" || (*iter).isDecrypted)
1958 continue;
1959
1960 int tmp_user_id = atoi((*iter).userId.c_str());
1961 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
1962 if (Decrypt_User(tmp_user_id, Password) ||
1963 (Password != "!" && Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
1964 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
1965 Mark_User_Decrypted(tmp_user_id);
1966 } else {
1967 gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
1968 }
1969 }
1970 Post_Decrypt("");
1971 }
1972
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001973 return 0;
Noah Jacobson81d638d2019-04-28 00:10:07 -04001974 } else {
1975 gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001976 }
1977#else
1978 LOGERR("FBE support is not present\n");
1979#endif
1980 return -1;
1981 }
1982
Noah Jacobson81d638d2019-04-28 00:10:07 -04001983 char isdecrypteddata[PROPERTY_VALUE_MAX];
1984 property_get("twrp.decrypt.done", isdecrypteddata, "");
1985 if (strcmp(isdecrypteddata, "true") == 0) {
1986 LOGINFO("Data has no decryption required\n");
1987 return 0;
1988 }
1989
Ethan Yonkerddb63e22017-01-19 14:01:57 -06001990 int pwret = -1;
1991 pid_t pid = fork();
1992 if (pid < 0) {
1993 LOGERR("fork failed\n");
1994 return -1;
1995 } else if (pid == 0) {
1996 // Child process
1997 char cPassword[255];
1998 strcpy(cPassword, Password.c_str());
1999 int ret = cryptfs_check_passwd(cPassword);
2000 exit(ret);
2001 } else {
2002 // Parent
2003 int status;
2004 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
2005 pwret = -1;
2006 else
2007 pwret = WEXITSTATUS(status) ? -1 : 0;
2008 }
a39552696ff55ce2013-01-08 16:14:56 +00002009
nkk7171c6c502017-01-05 23:55:05 +02002010#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
2011 if (pwret != 0) {
2012 pwret = vold_decrypt(Password);
nkk717d1222a2017-11-06 17:27:21 +02002013 switch (pwret) {
2014 case VD_SUCCESS:
2015 break;
2016 case VD_ERR_MISSING_VDC:
2017 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vdc"));
2018 break;
2019 case VD_ERR_MISSING_VOLD:
2020 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vold"));
2021 break;
2022 }
nkk7171c6c502017-01-05 23:55:05 +02002023 }
2024#endif // TW_CRYPTO_USE_SYSTEM_VOLD
2025
Ethan Yonker253368a2014-11-25 15:00:52 -06002026 // Unmount any partitions that were needed for decrypt
2027 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2028 if ((*iter)->Mount_To_Decrypt) {
2029 (*iter)->UnMount(false);
2030 }
2031 }
oshmouna82a7542018-04-10 17:45:55 +02002032 property_set("twrp.mount_to_decrypt", "0");
Ethan Yonker253368a2014-11-25 15:00:52 -06002033
a39552696ff55ce2013-01-08 16:14:56 +00002034 if (pwret != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002035 gui_err("fail_decrypt=Failed to decrypt data.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002036 return -1;
2037 }
a39552696ff55ce2013-01-08 16:14:56 +00002038
Dees_Troy5bf43922012-09-07 16:07:55 -04002039 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
2040 if (strcmp(crypto_blkdev, "error") == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002041 LOGERR("Error retrieving decrypted data block device.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -04002042 } else {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002043 Post_Decrypt(crypto_blkdev);
Dees_Troy5bf43922012-09-07 16:07:55 -04002044 }
2045 return 0;
2046#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002047 gui_err("no_crypto_support=No crypto support was compiled into this build.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002048 return -1;
2049#endif
Dees_Troy51a0e822012-09-05 15:24:24 -04002050 return 1;
Dees_Troy51127312012-09-08 13:08:49 -04002051}
2052
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002053int TWPartitionManager::Fix_Contexts(void) {
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002054 std::vector<TWPartition*>::iterator iter;
2055 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2056 if ((*iter)->Has_Data_Media) {
2057 if ((*iter)->Mount(true)) {
2058 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
2059 return -1;
2060 }
2061 }
2062 }
Dees_Troy1a650e62012-10-19 20:54:32 -04002063 UnMount_Main_Partitions();
Ethan Yonker74db1572015-10-28 12:44:49 -05002064 gui_msg("done=Done.");
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002065 return 0;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002066}
2067
Ethan Yonker66a19492015-12-10 10:19:45 -06002068TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002069 std::vector<TWPartition*>::iterator iter = Partitions.begin();
2070
2071 if (!Path.empty()) {
2072 string Search_Path = TWFunc::Get_Root_Path(Path);
2073 for (; iter != Partitions.end(); iter++) {
Matt Mower9a561dd2016-02-22 21:25:51 -06002074 if ((*iter)->Mount_Point == Search_Path) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002075 iter++;
2076 break;
2077 }
2078 }
2079 }
2080
2081 for (; iter != Partitions.end(); iter++) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002082 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
2083 // do nothing, do not return this type of partition
2084 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002085 return (*iter);
2086 }
2087 }
2088
2089 return NULL;
2090}
2091
Dees_Troyd21618c2012-10-14 18:48:49 -04002092int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
Dees_Troyd21618c2012-10-14 18:48:49 -04002093 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
2094
2095 if (Part == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002096 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
2097 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 -04002098 return false;
2099 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002100 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
2101 if (!Part->UnMount(true) || !Part->Is_Present)
Dees_Troyd21618c2012-10-14 18:48:49 -04002102 return false;
2103
bigbiff22851b92021-09-01 16:46:57 -04002104 if (!TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002105 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
Dees_Troyd21618c2012-10-14 18:48:49 -04002106 return false;
2107 }
Dees_Troyd21618c2012-10-14 18:48:49 -04002108 return true;
2109}
2110
Dees_Troy8170a922012-09-18 15:40:25 -04002111int TWPartitionManager::usb_storage_enable(void) {
Dees_Troy8170a922012-09-18 15:40:25 -04002112 char lun_file[255];
Dees_Troyd21618c2012-10-14 18:48:49 -04002113 bool has_multiple_lun = false;
Dees_Troy8170a922012-09-18 15:40:25 -04002114
Ethan Yonker47360be2014-04-01 10:34:34 -05002115 string Lun_File_str = CUSTOM_LUN_FILE;
2116 size_t found = Lun_File_str.find("%");
2117 if (found != string::npos) {
2118 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
2119 if (TWFunc::Path_Exists(lun_file))
2120 has_multiple_lun = true;
2121 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002122 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
Ethan Yonker47360be2014-04-01 10:34:34 -05002123 if (!has_multiple_lun) {
2124 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
2125 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
2126 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
Ethan Yonker66a19492015-12-10 10:19:45 -06002127 TWPartition* Mount = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002128 if (Mount) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002129 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
2130 goto error_handle;
2131 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002132 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002133 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002134 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002135 }
2136 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002137 goto error_handle;
Dees_Troy8170a922012-09-18 15:40:25 -04002138 }
Dees_Troy8170a922012-09-18 15:40:25 -04002139 } else {
Ethan Yonker47360be2014-04-01 10:34:34 -05002140 LOGINFO("Device has multiple lun files\n");
2141 TWPartition* Mount1;
2142 TWPartition* Mount2;
Dees_Troy8170a922012-09-18 15:40:25 -04002143 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
Ethan Yonker66a19492015-12-10 10:19:45 -06002144 Mount1 = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002145 if (Mount1) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002146 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
2147 goto error_handle;
2148 }
Matt Moweree717062014-04-26 01:46:46 -05002149 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
Ethan Yonker66a19492015-12-10 10:19:45 -06002150 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
Matt Mower1fdcdb72016-01-25 20:53:47 -06002151 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
Matt Moweree717062014-04-26 01:46:46 -05002152 Open_Lun_File(Mount2->Mount_Point, lun_file);
Ethan Yonker47360be2014-04-01 10:34:34 -05002153 }
2154 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002155 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002156 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002157 }
Dees_Troy8170a922012-09-18 15:40:25 -04002158 }
Matt Mowerb6ef4782014-11-06 02:24:36 -06002159 property_set("sys.storage.ums_enabled", "1");
HandyMenny37d42992014-10-26 22:15:59 +01002160 property_set("sys.usb.config", "mass_storage,adb");
Dees_Troy8170a922012-09-18 15:40:25 -04002161 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002162error_handle:
2163 if (mtp_was_enabled)
2164 if (!Enable_MTP())
2165 Disable_MTP();
2166 return false;
Dees_Troy8170a922012-09-18 15:40:25 -04002167}
2168
2169int TWPartitionManager::usb_storage_disable(void) {
bigbiff22851b92021-09-01 16:46:57 -04002170 int index, ret = 0;
Dees_Troy2673cec2013-04-02 20:22:16 +00002171 char lun_file[255], ch[2] = {0, 0};
2172 string str = ch;
Dees_Troy8170a922012-09-18 15:40:25 -04002173
2174 for (index=0; index<2; index++) {
2175 sprintf(lun_file, CUSTOM_LUN_FILE, index);
bigbiff22851b92021-09-01 16:46:57 -04002176 if (!TWFunc::write_to_file(lun_file, str)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002177 break;
bigbiff22851b92021-09-01 16:46:57 -04002178 ret = -1;
Dees_Troy8170a922012-09-18 15:40:25 -04002179 }
Dees_Troy8170a922012-09-18 15:40:25 -04002180 }
Dees_Troye58d5262012-09-21 12:27:57 -04002181 Mount_All_Storage();
2182 Update_System_Details();
Dees_Troycfd73ef2012-10-12 16:52:00 -04002183 UnMount_Main_Partitions();
Matt Mowerd9cb9062013-12-14 20:34:45 -06002184 property_set("sys.storage.ums_enabled", "0");
HandyMenny37d42992014-10-26 22:15:59 +01002185 property_set("sys.usb.config", "adb");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002186 if (mtp_was_enabled)
2187 if (!Enable_MTP())
2188 Disable_MTP();
Dees_Troy2673cec2013-04-02 20:22:16 +00002189 if (ret < 0 && index == 0) {
2190 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
2191 return false;
2192 } else {
2193 return true;
2194 }
Dees_Troy8170a922012-09-18 15:40:25 -04002195 return true;
Dees_Troy812660f2012-09-20 09:55:17 -04002196}
2197
2198void TWPartitionManager::Mount_All_Storage(void) {
2199 std::vector<TWPartition*>::iterator iter;
2200
2201 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2202 if ((*iter)->Is_Storage)
2203 (*iter)->Mount(false);
2204 }
Dees_Troy2c50e182012-09-26 20:05:28 -04002205}
Dees_Troy9350b8d2012-09-27 12:38:38 -04002206
Dees_Troyd0384ef2012-10-12 12:15:42 -04002207void TWPartitionManager::UnMount_Main_Partitions(void) {
2208 // Unmounts system and data if data is not data/media
2209 // Also unmounts boot if boot is mountable
Dees_Troy2673cec2013-04-02 20:22:16 +00002210 LOGINFO("Unmounting main partitions...\n");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002211
Mohd Faraze3948ec2020-08-14 01:40:59 +00002212 TWPartition *Partition = Find_Partition_By_Path ("/vendor");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002213
Mohd Faraze3948ec2020-08-14 01:40:59 +00002214 if (Partition != NULL) UnMount_By_Path("/vendor", false);
2215 UnMount_By_Path (Get_Android_Root_Path(), true);
2216 Partition = Find_Partition_By_Path ("/product");
2217 if (Partition != NULL) UnMount_By_Path("/product", false);
Ethan Yonker6277c792014-09-15 14:54:30 -05002218 if (!datamedia)
2219 UnMount_By_Path("/data", true);
2220
Mohd Faraze3948ec2020-08-14 01:40:59 +00002221 Partition = Find_Partition_By_Path ("/boot");
2222 if (Partition != NULL && Partition->Can_Be_Mounted)
2223 Partition->UnMount(true);
Dees_Troyd0384ef2012-10-12 12:15:42 -04002224}
2225
Dees_Troy9350b8d2012-09-27 12:38:38 -04002226int TWPartitionManager::Partition_SDCard(void) {
Matt Mower23d8aae2017-01-06 14:30:33 -06002227 char temp[255];
Ethan Yonker483e9f42016-01-11 22:21:18 -06002228 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 -04002229 int ext, swap, total_size = 0, fat_size;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002230
Ethan Yonker74db1572015-10-28 12:44:49 -05002231 gui_msg("start_partition_sd=Partitioning SD Card...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002232
2233 // Locate and validate device to partition
2234 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
2235
Ethan Yonker66a19492015-12-10 10:19:45 -06002236 if (SDCard->Is_Adopted_Storage)
2237 SDCard->Revert_Adopted();
2238
Ethan Yonker1eff6cd2014-09-15 13:30:42 -05002239 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002240 gui_err("partition_sd_locate=Unable to locate device to partition.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002241 return false;
2242 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002243
2244 // Unmount everything
Dees_Troy9350b8d2012-09-27 12:38:38 -04002245 if (!SDCard->UnMount(true))
2246 return false;
2247 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
2248 if (SDext != NULL) {
2249 if (!SDext->UnMount(true))
2250 return false;
2251 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002252 char* swappath = getenv("SWAPPATH");
2253 if (swappath != NULL) {
2254 LOGINFO("Unmounting swap at '%s'\n", swappath);
2255 umount(swappath);
2256 }
Vojtech Bocek05534202013-09-11 08:11:56 +02002257
Ethan Yonker483e9f42016-01-11 22:21:18 -06002258 // Determine block device
2259 if (SDCard->Alternate_Block_Device.empty()) {
2260 SDCard->Find_Actual_Block_Device();
2261 Device = SDCard->Actual_Block_Device;
2262 // Just use the root block device
2263 Device.resize(strlen("/dev/block/mmcblkX"));
2264 } else {
2265 Device = SDCard->Alternate_Block_Device;
2266 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002267
2268 // Find the size of the block device:
Ethan Yonker483e9f42016-01-11 22:21:18 -06002269 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002270
2271 DataManager::GetValue("tw_sdext_size", ext);
2272 DataManager::GetValue("tw_swap_size", swap);
2273 DataManager::GetValue("tw_sdpart_file_system", ext_format);
2274 fat_size = total_size - ext - swap;
Ethan Yonker483e9f42016-01-11 22:21:18 -06002275 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);
2276
2277 // Determine partition sizes
2278 if (swap == 0 && ext == 0) {
2279 fat_str = "-0";
2280 } else {
2281 memset(temp, 0, sizeof(temp));
2282 sprintf(temp, "%i", fat_size);
2283 fat_str = temp;
2284 fat_str += "MB";
2285 }
2286 if (swap == 0) {
2287 ext_str = "-0";
2288 } else {
2289 memset(temp, 0, sizeof(temp));
2290 sprintf(temp, "%i", ext);
2291 ext_str = "+";
2292 ext_str += temp;
2293 ext_str += "MB";
2294 }
2295
Dees_Troy9350b8d2012-09-27 12:38:38 -04002296 if (ext + swap > total_size) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002297 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002298 return false;
2299 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002300
Ethan Yonker74db1572015-10-28 12:44:49 -05002301 gui_msg("remove_part_table=Removing partition table...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002302 Command = "sgdisk --zap-all " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002303 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002304 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002305 gui_err("unable_rm_part=Unable to remove partition table.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002306 Update_System_Details();
2307 return false;
2308 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002309 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
Captain Throwback9643a802016-05-27 11:44:51 -04002310 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 +00002311 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002312 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002313 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002314 return false;
2315 }
2316 if (ext > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002317 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002318 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002319 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002320 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002321 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002322 Update_System_Details();
2323 return false;
2324 }
2325 }
2326 if (swap > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002327 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002328 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 +00002329 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002330 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002331 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002332 Update_System_Details();
2333 return false;
2334 }
2335 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002336
2337 // Convert GPT to MBR
2338 Command = "sgdisk --gpttombr " + Device;
2339 if (TWFunc::Exec_Cmd(Command) != 0)
2340 LOGINFO("Failed to covert partition GPT to MBR\n");
2341
2342 // Tell the kernel to rescan the partition table
2343 int fd = open(Device.c_str(), O_RDONLY);
2344 ioctl(fd, BLKRRPART, 0);
2345 close(fd);
2346
2347 string format_device = Device;
2348 if (Device.substr(0, 17) == "/dev/block/mmcblk")
2349 format_device += "p";
2350
2351 // Format new partitions to proper file system
2352 if (fat_size > 0) {
2353 Command = "mkfs.fat " + format_device + "1";
2354 TWFunc::Exec_Cmd(Command);
2355 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002356 if (ext > 0) {
2357 if (SDext == NULL) {
Ethan Yonker483e9f42016-01-11 22:21:18 -06002358 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2359 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2360 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2361 TWFunc::Exec_Cmd(Command);
2362 } else {
2363 SDext->Wipe(ext_format);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002364 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002365 }
2366 if (swap > 0) {
2367 Command = "mkswap " + format_device;
2368 if (ext > 0)
2369 Command += "3";
2370 else
2371 Command += "2";
Vojtech Bocek05534202013-09-11 08:11:56 +02002372 TWFunc::Exec_Cmd(Command);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002373 }
2374
Ethan Yonker483e9f42016-01-11 22:21:18 -06002375 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2376 if (SDCard->Mount(true)) {
2377 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2378 mkdir(TWRP_Folder.c_str(), 0777);
2379 DataManager::Flush();
2380 }
2381
Dees_Troy9350b8d2012-09-27 12:38:38 -04002382 Update_System_Details();
Ethan Yonker74db1572015-10-28 12:44:49 -05002383 gui_msg("part_complete=Partitioning complete.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002384 return true;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002385}
Dees_Troya13d74f2013-03-24 08:54:55 -05002386
2387void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2388 std::vector<TWPartition*>::iterator iter;
2389 if (ListType == "mount") {
2390 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002391 if ((*iter)->Can_Be_Mounted) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002392 struct PartitionList part;
2393 part.Display_Name = (*iter)->Display_Name;
2394 part.Mount_Point = (*iter)->Mount_Point;
2395 part.selected = (*iter)->Is_Mounted();
2396 Partition_List->push_back(part);
2397 }
2398 }
2399 } else if (ListType == "storage") {
2400 char free_space[255];
2401 string Current_Storage = DataManager::GetCurrentStoragePath();
2402 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2403 if ((*iter)->Is_Storage) {
2404 struct PartitionList part;
2405 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2406 part.Display_Name = (*iter)->Storage_Name + " (";
2407 part.Display_Name += free_space;
2408 part.Display_Name += "MB)";
2409 part.Mount_Point = (*iter)->Storage_Path;
2410 if ((*iter)->Storage_Path == Current_Storage)
2411 part.selected = 1;
2412 else
2413 part.selected = 0;
2414 Partition_List->push_back(part);
2415 }
2416 }
2417 } else if (ListType == "backup") {
2418 char backup_size[255];
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002419 unsigned long long Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05002420 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002421 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002422 struct PartitionList part;
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002423 Backup_Size = (*iter)->Backup_Size;
2424 if ((*iter)->Has_SubPartition) {
2425 std::vector<TWPartition*>::iterator subpart;
2426
2427 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2428 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2429 Backup_Size += (*subpart)->Backup_Size;
2430 }
2431 }
2432 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
Dees_Troya13d74f2013-03-24 08:54:55 -05002433 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2434 part.Display_Name += backup_size;
2435 part.Display_Name += "MB)";
2436 part.Mount_Point = (*iter)->Backup_Path;
2437 part.selected = 0;
2438 Partition_List->push_back(part);
2439 }
2440 }
2441 } else if (ListType == "restore") {
2442 string Restore_List, restore_path;
2443 TWPartition* restore_part = NULL;
2444
2445 DataManager::GetValue("tw_restore_list", Restore_List);
2446 if (!Restore_List.empty()) {
2447 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2448 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2449 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002450 struct PartitionList part;
2451 if (restore_path.compare("ADB_Backup") == 0) {
2452 part.Display_Name = "ADB Backup";
2453 part.Mount_Point = "ADB Backup";
2454 part.selected = 1;
2455 Partition_List->push_back(part);
2456 break;
2457 }
Dees_Troy59df9262013-06-19 14:53:57 -05002458 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
Dees Troy4159aed2014-02-28 17:24:43 +00002459 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002460 // Don't allow restore of recovery (causes problems on some devices)
Dees_Troy59df9262013-06-19 14:53:57 -05002461 // Don't add subpartitions to the list of items
Dees_Troya13d74f2013-03-24 08:54:55 -05002462 } else {
Dees_Troya13d74f2013-03-24 08:54:55 -05002463 part.Display_Name = restore_part->Backup_Display_Name;
2464 part.Mount_Point = restore_part->Backup_Path;
2465 part.selected = 1;
2466 Partition_List->push_back(part);
2467 }
2468 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002469 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05002470 }
2471 start_pos = end_pos + 1;
2472 end_pos = Restore_List.find(";", start_pos);
2473 }
2474 }
2475 } else if (ListType == "wipe") {
2476 struct PartitionList dalvik;
Ethan Yonker74db1572015-10-28 12:44:49 -05002477 dalvik.Display_Name = gui_parse_text("{@dalvik}");
Dees_Troya13d74f2013-03-24 08:54:55 -05002478 dalvik.Mount_Point = "DALVIK";
2479 dalvik.selected = 0;
2480 Partition_List->push_back(dalvik);
2481 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2482 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2483 struct PartitionList part;
2484 part.Display_Name = (*iter)->Display_Name;
2485 part.Mount_Point = (*iter)->Mount_Point;
2486 part.selected = 0;
2487 Partition_List->push_back(part);
2488 }
2489 if ((*iter)->Has_Android_Secure) {
2490 struct PartitionList part;
2491 part.Display_Name = (*iter)->Backup_Display_Name;
2492 part.Mount_Point = (*iter)->Backup_Path;
2493 part.selected = 0;
2494 Partition_List->push_back(part);
2495 }
Dees_Troy74fb2e92013-04-15 14:35:47 +00002496 if ((*iter)->Has_Data_Media) {
2497 struct PartitionList datamedia;
2498 datamedia.Display_Name = (*iter)->Storage_Name;
2499 datamedia.Mount_Point = "INTERNAL";
2500 datamedia.selected = 0;
2501 Partition_List->push_back(datamedia);
2502 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002503 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002504 } else if (ListType == "flashimg") {
2505 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2506 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2507 struct PartitionList part;
2508 part.Display_Name = (*iter)->Backup_Display_Name;
2509 part.Mount_Point = (*iter)->Backup_Path;
2510 part.selected = 0;
2511 Partition_List->push_back(part);
2512 }
2513 }
Ethan Yonker53796e72019-01-11 22:49:52 -06002514 if (DataManager::GetIntValue("tw_has_repack_tools") != 0 && DataManager::GetIntValue("tw_has_boot_slots") != 0) {
2515 TWPartition* boot = Find_Partition_By_Path("/boot");
2516 if (boot) {
2517 // Allow flashing kernels and ramdisks
2518 struct PartitionList repack_ramdisk;
2519 repack_ramdisk.Display_Name = gui_lookup("install_twrp_ramdisk", "Install Recovery Ramdisk");
2520 repack_ramdisk.Mount_Point = "/repack_ramdisk";
2521 repack_ramdisk.selected = 0;
2522 Partition_List->push_back(repack_ramdisk);
2523 /*struct PartitionList repack_kernel; For now let's leave repacking kernels under advanced only
2524 repack_kernel.Display_Name = gui_lookup("install_kernel", "Install Kernel");
2525 repack_kernel.Mount_Point = "/repack_kernel";
2526 repack_kernel.selected = 0;
2527 Partition_List->push_back(repack_kernel);*/
2528 }
2529 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002530 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00002531 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05002532 }
2533}
2534
2535int TWPartitionManager::Fstab_Processed(void) {
2536 return Partitions.size();
2537}
Dees_Troyd93bda52013-07-03 19:55:19 +00002538
2539void TWPartitionManager::Output_Storage_Fstab(void) {
2540 std::vector<TWPartition*>::iterator iter;
2541 char storage_partition[255];
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002542 std::string Temp;
bigbiff25d25b92020-06-19 16:07:38 -04002543 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002544
2545 if (cacheDir.empty()) {
2546 LOGINFO("Unable to find cache directory\n");
2547 return;
2548 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002549
bigbiff25d25b92020-06-19 16:07:38 -04002550 std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002551 FILE *fp = fopen(storageFstab.c_str(), "w");
Dees_Troyd93bda52013-07-03 19:55:19 +00002552
2553 if (fp == NULL) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002554 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
Dees_Troyd93bda52013-07-03 19:55:19 +00002555 return;
2556 }
2557
2558 // Iterate through all partitions
2559 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2560 if ((*iter)->Is_Storage) {
2561 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2562 strcpy(storage_partition, Temp.c_str());
2563 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2564 }
2565 }
2566 fclose(fp);
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02002567}
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002568
2569TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2570{
2571 TWPartition *res = NULL;
2572 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
Matt Mowera8a89d12016-12-30 18:10:37 -06002573 if (!(*iter)->Is_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002574 continue;
2575
Matt Mowera8a89d12016-12-30 18:10:37 -06002576 if ((*iter)->Is_Settings_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002577 return *iter;
2578
Matt Mowera8a89d12016-12-30 18:10:37 -06002579 if (!res)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002580 res = *iter;
2581 }
2582 return res;
2583}
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002584
2585bool TWPartitionManager::Enable_MTP(void) {
2586#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002587 if (mtppid) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002588 gui_err("mtp_already_enabled=MTP already enabled");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002589 return true;
2590 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002591
2592 int mtppipe[2];
2593
2594 if (pipe(mtppipe) < 0) {
2595 LOGERR("Error creating MTP pipe\n");
2596 return false;
2597 }
2598
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002599 char old_value[PROPERTY_VALUE_MAX];
Matt Mowere07f0102017-02-23 17:40:00 -06002600 property_get("sys.usb.config", old_value, "");
2601 if (strcmp(old_value, "mtp,adb") != 0) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002602 char vendor[PROPERTY_VALUE_MAX];
2603 char product[PROPERTY_VALUE_MAX];
2604 property_set("sys.usb.config", "none");
2605 property_get("usb.vendor", vendor, "18D1");
2606 property_get("usb.product.mtpadb", product, "4EE2");
2607 string vendorstr = vendor;
2608 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002609 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2610 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002611 property_set("sys.usb.config", "mtp,adb");
2612 }
Matt Mower653a1702017-02-16 10:38:52 -06002613 /* To enable MTP debug, use the twrp command line feature:
Ethan Yonker6d154c42014-09-03 14:19:43 -05002614 * twrp set tw_mtp_debug 1
2615 */
2616 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
Ethan Yonker1b039202015-01-30 10:08:48 -06002617 mtppid = mtp->forkserver(mtppipe);
2618 if (mtppid) {
2619 close(mtppipe[0]); // Host closes read side
2620 mtp_write_fd = mtppipe[1];
2621 DataManager::SetValue("tw_mtp_enabled", 1);
2622 Add_All_MTP_Storage();
2623 return true;
Ethan Yonker726a0202014-12-16 20:01:38 -06002624 } else {
2625 close(mtppipe[0]);
2626 close(mtppipe[1]);
Ethan Yonker74db1572015-10-28 12:44:49 -05002627 gui_err("mtp_fail=Failed to enable MTP");
Ethan Yonker1b039202015-01-30 10:08:48 -06002628 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002629 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002630#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002631 gui_err("no_mtp=MTP support not included");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002632#endif
2633 DataManager::SetValue("tw_mtp_enabled", 0);
2634 return false;
2635}
2636
Ethan Yonker1b039202015-01-30 10:08:48 -06002637void TWPartitionManager::Add_All_MTP_Storage(void) {
2638#ifdef TW_HAS_MTP
2639 std::vector<TWPartition*>::iterator iter;
2640
2641 if (!mtppid)
2642 return; // MTP is not enabled
2643
2644 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2645 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2646 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2647 }
2648#else
2649 return;
2650#endif
2651}
2652
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002653bool TWPartitionManager::Disable_MTP(void) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002654 char old_value[PROPERTY_VALUE_MAX];
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05002655 property_set("sys.usb.ffs.mtp.ready", "0");
Matt Mowere07f0102017-02-23 17:40:00 -06002656 property_get("sys.usb.config", old_value, "");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002657 if (strcmp(old_value, "adb") != 0) {
2658 char vendor[PROPERTY_VALUE_MAX];
2659 char product[PROPERTY_VALUE_MAX];
2660 property_set("sys.usb.config", "none");
2661 property_get("usb.vendor", vendor, "18D1");
Matt Mowere07f0102017-02-23 17:40:00 -06002662 property_get("usb.product.adb", product, "D001");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002663 string vendorstr = vendor;
2664 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002665 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2666 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002667 usleep(2000);
2668 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002669#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002670 if (mtppid) {
Ethan Yonker8613dc02014-09-11 09:28:20 -05002671 LOGINFO("Disabling MTP\n");
2672 int status;
2673 kill(mtppid, SIGKILL);
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002674 mtppid = 0;
Ethan Yonker8613dc02014-09-11 09:28:20 -05002675 // We don't care about the exit value, but this prevents a zombie process
2676 waitpid(mtppid, &status, 0);
Ethan Yonker726a0202014-12-16 20:01:38 -06002677 close(mtp_write_fd);
2678 mtp_write_fd = -1;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002679 }
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002680#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002681 property_set("sys.usb.config", "adb");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002682#ifdef TW_HAS_MTP
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002683 DataManager::SetValue("tw_mtp_enabled", 0);
2684 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002685#endif
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002686 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002687}
Ethan Yonker726a0202014-12-16 20:01:38 -06002688
2689TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2690 std::vector<TWPartition*>::iterator iter;
2691
2692 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2693 if ((*iter)->MTP_Storage_ID == Storage_ID)
2694 return (*iter);
2695 }
2696 return NULL;
2697}
2698
2699bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2700#ifdef TW_HAS_MTP
2701 struct mtpmsg mtp_message;
2702
2703 if (!mtppid)
2704 return false; // MTP is disabled
2705
2706 if (mtp_write_fd < 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002707 LOGINFO("MTP: mtp_write_fd is not set\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002708 return false;
2709 }
2710
2711 if (Part) {
Ethan Yonker4bfabab2014-12-29 09:15:37 -06002712 if (Part->MTP_Storage_ID == 0)
2713 return false;
Ethan Yonker726a0202014-12-16 20:01:38 -06002714 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2715 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2716 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2717 mtp_message.storage_id = Part->MTP_Storage_ID;
2718 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002719 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002720 return false;
2721 } else {
2722 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2723 return true;
2724 }
2725 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2726 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2727 mtp_message.storage_id = Part->MTP_Storage_ID;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002728 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2729 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2730 return false;
2731 }
2732 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2733 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2734 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2735 return false;
2736 }
2737 strcpy(mtp_message.display, Part->Storage_Name.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002738 mtp_message.maxFileSize = Part->Get_Max_FileSize();
Ethan Yonker1b039202015-01-30 10:08:48 -06002739 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 -06002740 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002741 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002742 return false;
2743 } else {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002744 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
Ethan Yonker726a0202014-12-16 20:01:38 -06002745 return true;
2746 }
2747 } else {
2748 LOGERR("Unknown MTP message type: %i\n", message_type);
2749 }
2750 } else {
2751 // This hopefully never happens as the error handling should
2752 // occur in the calling function.
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002753 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002754 }
2755 return true;
2756#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002757 gui_err("no_mtp=MTP support not included");
Ethan Yonker726a0202014-12-16 20:01:38 -06002758 DataManager::SetValue("tw_mtp_enabled", 0);
2759 return false;
2760#endif
2761}
2762
2763bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2764#ifdef TW_HAS_MTP
2765 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2766 if (Part) {
2767 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2768 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002769 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002770 }
2771#endif
2772 return false;
2773}
2774
2775bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2776#ifdef TW_HAS_MTP
2777 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2778 if (Part) {
2779 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2780 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002781 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002782 }
2783#endif
2784 return false;
2785}
2786
2787bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2788#ifdef TW_HAS_MTP
2789 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2790 if (Part) {
2791 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2792 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002793 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002794 }
2795#endif
2796 return false;
2797}
2798
2799bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2800#ifdef TW_HAS_MTP
2801 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2802 if (Part) {
2803 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2804 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002805 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002806 }
2807#endif
2808 return false;
2809}
Ethan Yonker96af84a2015-01-05 14:58:36 -06002810
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002811bool TWPartitionManager::Flash_Image(string& path, string& filename) {
bigbiffad58e1b2020-07-06 20:24:34 -04002812 twrpRepacker repacker;
Matt Mower23d8aae2017-01-06 14:30:33 -06002813 int partition_count = 0;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002814 TWPartition* flash_part = NULL;
bigbiffce8f83c2015-12-12 18:30:21 -05002815 string Flash_List, flash_path, full_filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002816 size_t start_pos = 0, end_pos = 0;
2817
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002818 full_filename = path + "/" + filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002819
bigbiff1f9e4842020-10-31 11:33:15 -04002820 Unlock_Block_Partitions();
2821
bigbiffce8f83c2015-12-12 18:30:21 -05002822 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
2823 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
2824
2825 if (!TWFunc::Path_Exists(full_filename)) {
2826 if (!Mount_By_Path(full_filename, true)) {
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002827 return false;
2828 }
bigbiffce8f83c2015-12-12 18:30:21 -05002829 if (!TWFunc::Path_Exists(full_filename)) {
2830 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002831 return false;
2832 }
2833 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002834
Ethan Yonker53796e72019-01-11 22:49:52 -06002835 DataManager::GetValue("tw_flash_partition", Flash_List);
2836 Repack_Type repack = REPLACE_NONE;
2837 if (Flash_List == "/repack_ramdisk;") {
2838 repack = REPLACE_RAMDISK;
2839 } else if (Flash_List == "/repack_kernel;") {
2840 repack = REPLACE_KERNEL;
2841 }
2842 if (repack != REPLACE_NONE) {
2843 Repack_Options_struct Repack_Options;
2844 Repack_Options.Type = repack;
2845 Repack_Options.Disable_Verity = false;
2846 Repack_Options.Disable_Force_Encrypt = false;
2847 Repack_Options.Backup_First = DataManager::GetIntValue("tw_repack_backup_first") != 0;
bigbiffad58e1b2020-07-06 20:24:34 -04002848 return repacker.Repack_Image_And_Flash(full_filename, Repack_Options);
Ethan Yonker53796e72019-01-11 22:49:52 -06002849 }
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002850 PartitionSettings part_settings;
2851 part_settings.Backup_Folder = path;
2852 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
2853 ProgressTracking progress(total_bytes);
2854 part_settings.progress = &progress;
2855 part_settings.adbbackup = false;
2856 part_settings.PM_Method = PM_RESTORE;
Ethan Yonker74db1572015-10-28 12:44:49 -05002857 gui_msg("calc_restore=Calculating restore details...");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002858 if (!Flash_List.empty()) {
2859 end_pos = Flash_List.find(";", start_pos);
2860 while (end_pos != string::npos && start_pos < Flash_List.size()) {
2861 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
2862 flash_part = Find_Partition_By_Path(flash_path);
2863 if (flash_part != NULL) {
2864 partition_count++;
2865 if (partition_count > 1) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002866 gui_err("too_many_flash=Too many partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002867 return false;
2868 }
2869 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002870 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
Ethan Yonker96af84a2015-01-05 14:58:36 -06002871 return false;
2872 }
2873 start_pos = end_pos + 1;
2874 end_pos = Flash_List.find(";", start_pos);
2875 }
2876 }
2877
2878 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002879 gui_err("no_part_flash=No partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002880 return false;
2881 }
2882
2883 DataManager::SetProgress(0.0);
2884 if (flash_part) {
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002885 flash_part->Backup_FileName = filename;
2886 if (!flash_part->Flash_Image(&part_settings))
Ethan Yonker96af84a2015-01-05 14:58:36 -06002887 return false;
2888 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002889 gui_err("invalid_flash=Invalid flash partition specified.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002890 return false;
2891 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002892 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002893 return true;
2894}
Ethan Yonker74db1572015-10-28 12:44:49 -05002895
2896void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
2897 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2898 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002899 if (part->Is_Adopted_Storage) {
2900 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2901 part->Backup_Display_Name = part->Display_Name;
2902 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2903 } else {
2904 part->Display_Name = gui_lookup(resource_name, default_value);
2905 part->Backup_Display_Name = part->Display_Name;
2906 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002907 }
2908}
2909
2910void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
2911 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2912 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002913 if (part->Is_Adopted_Storage) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06002914 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
Ethan Yonker66a19492015-12-10 10:19:45 -06002915 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
Ethan Yonker66a19492015-12-10 10:19:45 -06002916 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2917 } else {
2918 part->Display_Name = gui_lookup(resource_name, default_value);
2919 part->Backup_Display_Name = part->Display_Name;
2920 if (part->Is_Storage)
2921 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2922 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002923 }
2924}
2925
Ethan Yonker01f4e032017-02-03 15:30:52 -06002926void 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) {
2927 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2928 if (part) {
2929 if (part->Is_Adopted_Storage) {
2930 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
2931 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2932 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2933 } else {
2934 part->Display_Name = gui_lookup(resource_name, default_value);
2935 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
2936 if (part->Is_Storage)
2937 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2938 }
2939 }
2940}
2941
Ethan Yonker74db1572015-10-28 12:44:49 -05002942void TWPartitionManager::Translate_Partition_Display_Names() {
Ethan Yonker66a19492015-12-10 10:19:45 -06002943 LOGINFO("Translating partition display names\n");
Ethan Yonker74db1572015-10-28 12:44:49 -05002944 Translate_Partition("/system", "system", "System");
2945 Translate_Partition("/system_image", "system_image", "System Image");
2946 Translate_Partition("/vendor", "vendor", "Vendor");
2947 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
2948 Translate_Partition("/cache", "cache", "Cache");
Ethan Yonker74db1572015-10-28 12:44:49 -05002949 Translate_Partition("/boot", "boot", "Boot");
2950 Translate_Partition("/recovery", "recovery", "Recovery");
2951 if (!datamedia) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06002952 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
Ethan Yonker74db1572015-10-28 12:44:49 -05002953 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2954 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
2955 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2956 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
Ethan Yonker01f4e032017-02-03 15:30:52 -06002957 } else {
2958 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05002959 }
Ethan Yonker01f4e032017-02-03 15:30:52 -06002960 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
2961 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05002962 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
2963 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
2964
2965 // Android secure is a special case
2966 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
2967 if (part)
2968 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
2969
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002970 std::vector<TWPartition*>::iterator sysfs;
2971 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
2972 if (!(*sysfs)->Sysfs_Entry.empty()) {
2973 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
2974 }
2975 }
2976
Ethan Yonker74db1572015-10-28 12:44:49 -05002977 // This updates the text on all of the storage selection buttons in the GUI
2978 DataManager::SetBackupFolder();
2979}
Ethan Yonker66a19492015-12-10 10:19:45 -06002980
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002981bool TWPartitionManager::Decrypt_Adopted() {
Ethan Yonker66a19492015-12-10 10:19:45 -06002982#ifdef TW_INCLUDE_CRYPTO
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002983 bool ret = false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002984 if (!Mount_By_Path("/data", false)) {
2985 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002986 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06002987 }
2988 LOGINFO("Decrypt adopted storage starting\n");
2989 char* xmlFile = PageManager::LoadFileToBuffer("/data/system/storage.xml", NULL);
2990 xml_document<> *doc = NULL;
2991 xml_node<>* volumes = NULL;
Ethan Yonker66a19492015-12-10 10:19:45 -06002992 string Primary_Storage_UUID = "";
2993 if (xmlFile != NULL) {
2994 LOGINFO("successfully loaded storage.xml\n");
2995 doc = new xml_document<>();
2996 doc->parse<0>(xmlFile);
2997 volumes = doc->first_node("volumes");
2998 if (volumes) {
2999 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
3000 if (psuuid) {
3001 Primary_Storage_UUID = psuuid->value();
3002 }
3003 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003004 } else {
3005 LOGINFO("No /data/system/storage.xml for adopted storage\n");
3006 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003007 }
3008 std::vector<TWPartition*>::iterator adopt;
3009 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
Peter Cai439d60c2019-10-17 08:49:10 +08003010 if ((*adopt)->Removable && !(*adopt)->Is_Present && (*adopt)->Adopted_Mount_Delay > 0) {
3011 // On some devices, the external mmc driver takes some time
3012 // to recognize the card, in which case the "actual block device"
3013 // would not have been found yet. We wait the specified delay
3014 // and then try again.
3015 LOGINFO("Sleeping %d seconds for adopted storage.\n", (*adopt)->Adopted_Mount_Delay);
3016 sleep((*adopt)->Adopted_Mount_Delay);
3017 (*adopt)->Find_Actual_Block_Device();
3018 }
3019
Ethan Yonker66a19492015-12-10 10:19:45 -06003020 if ((*adopt)->Removable && (*adopt)->Is_Present) {
3021 if ((*adopt)->Decrypt_Adopted() == 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003022 ret = true;
Ethan Yonker66a19492015-12-10 10:19:45 -06003023 if (volumes) {
3024 xml_node<>* volume = volumes->first_node("volume");
3025 while (volume) {
3026 xml_attribute<>* guid = volume->first_attribute("partGuid");
3027 if (guid) {
3028 string GUID = (*adopt)->Adopted_GUID.c_str();
3029 GUID.insert(8, "-");
3030 GUID.insert(13, "-");
3031 GUID.insert(18, "-");
3032 GUID.insert(23, "-");
3033
3034 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
3035 xml_attribute<>* attr = volume->first_attribute("nickname");
nkk71ffb02bd2017-06-04 23:12:16 +03003036 if (attr && attr->value() && strlen(attr->value()) > 0) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003037 (*adopt)->Storage_Name = attr->value();
3038 (*adopt)->Display_Name = (*adopt)->Storage_Name;
3039 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
3040 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
3041 }
3042 attr = volume->first_attribute("fsUuid");
3043 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
3044 TWPartition* Dat = Find_Partition_By_Path("/data");
3045 if (Dat) {
3046 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
3047 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
3048 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
3049 Dat->Symlink_Mount_Point = "";
3050 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
3051 Dat->UnMount(false);
3052 Dat->Mount(false);
3053 (*adopt)->UnMount(false);
3054 (*adopt)->Mount(false);
Ethan Yonker66a19492015-12-10 10:19:45 -06003055 }
3056 }
3057 break;
3058 }
3059 }
3060 volume = volume->next_sibling("volume");
3061 }
3062 }
nkk71ffb02bd2017-06-04 23:12:16 +03003063 Update_System_Details();
3064 Output_Partition((*adopt));
Ethan Yonker66a19492015-12-10 10:19:45 -06003065 }
3066 }
3067 }
3068 if (xmlFile) {
3069 doc->clear();
3070 delete doc;
3071 free(xmlFile);
3072 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003073 return ret;
Ethan Yonker66a19492015-12-10 10:19:45 -06003074#else
3075 LOGINFO("Decrypt_Adopted: no crypto support\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003076 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003077#endif
3078}
Ethan Yonkerfcf3f242016-02-16 12:30:26 -06003079
3080void TWPartitionManager::Remove_Partition_By_Path(string Path) {
3081 std::vector<TWPartition*>::iterator iter;
3082 string Local_Path = TWFunc::Get_Root_Path(Path);
3083
3084 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3085 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
3086 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
3087 Partitions.erase(iter);
3088 return;
3089 }
3090 }
3091}
Ethan Yonker1b190162016-12-05 15:25:19 -06003092
bigbiff74a46272021-07-31 19:02:26 -04003093void TWPartitionManager::Override_Active_Slot(const string& Slot) {
3094 LOGINFO("Overriding slot to '%s'\n", Slot.c_str());
3095 Active_Slot_Display = Slot;
3096 DataManager::SetValue("tw_active_slot", Slot);
3097}
3098
Ethan Yonker1b190162016-12-05 15:25:19 -06003099void TWPartitionManager::Set_Active_Slot(const string& Slot) {
3100 if (Slot != "A" && Slot != "B") {
3101 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
3102 return;
3103 }
3104 if (Active_Slot_Display == Slot)
3105 return;
3106 LOGINFO("Setting active slot %s\n", Slot.c_str());
3107#ifdef AB_OTA_UPDATER
3108 if (!Active_Slot_Display.empty()) {
3109 const hw_module_t *hw_module;
3110 boot_control_module_t *module;
3111 int ret;
3112 ret = hw_get_module("bootctrl", &hw_module);
3113 if (ret != 0) {
3114 LOGERR("Error getting bootctrl module.\n");
3115 } else {
3116 module = (boot_control_module_t*) hw_module;
3117 module->init(module);
3118 int slot_number = 0;
3119 if (Slot == "B")
3120 slot_number = 1;
3121 if (module->setActiveBootSlot(module, slot_number))
3122 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
3123 }
3124 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
3125 }
3126#else
3127 LOGERR("Boot slot feature not present\n");
3128#endif
3129 Active_Slot_Display = Slot;
3130 if (Fstab_Processed())
3131 Update_System_Details();
3132}
3133string TWPartitionManager::Get_Active_Slot_Suffix() {
3134 if (Active_Slot_Display == "A")
3135 return "_a";
3136 return "_b";
3137}
3138string TWPartitionManager::Get_Active_Slot_Display() {
3139 return Active_Slot_Display;
3140}
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003141
Captain Throwback9d6feb52018-07-27 10:05:24 -04003142string TWPartitionManager::Get_Android_Root_Path() {
bigbiff8da46fa2020-09-08 16:42:34 -04003143 return "/system_root";
Captain Throwback9d6feb52018-07-27 10:05:24 -04003144}
3145
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003146void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
3147 std::vector<TWPartition*>::iterator iter;
3148
3149 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
3150 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
3151 TWPartition *part = *iter;
3152 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
3153 (*iter)->UnMount(false);
3154 rmdir((*iter)->Mount_Point.c_str());
3155 iter = Partitions.erase(iter);
3156 delete part;
3157 } else {
3158 iter++;
3159 }
3160 }
3161}
3162
3163void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
3164 std::vector<TWPartition*>::iterator iter;
3165
3166 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3167 if (!(*iter)->Sysfs_Entry.empty()) {
3168 string device;
3169 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
3170 if (wildcard != string::npos) {
3171 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
3172 } else {
3173 device = (*iter)->Sysfs_Entry;
3174 }
3175 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
3176 // Found a match
3177 if (uevent_data.action == "add") {
3178 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
3179 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
3180 (*iter)->Is_Present = true;
3181 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
3182 if (!Decrypt_Adopted()) {
3183 LOGINFO("No adopted storage so finding actual block device\n");
3184 (*iter)->Find_Actual_Block_Device();
3185 }
3186 return;
3187 } else if (uevent_data.action == "remove") {
3188 (*iter)->Is_Present = false;
3189 (*iter)->Primary_Block_Device = "";
3190 (*iter)->Actual_Block_Device = "";
3191 Remove_Uevent_Devices((*iter)->Mount_Point);
3192 return;
3193 }
3194 }
3195 }
3196 }
bigbiffee7b7ff2020-03-23 15:08:27 -04003197
3198 if (!PartitionManager.Get_Super_Status())
3199 LOGINFO("Found no matching fstab entry for uevent device '%s' - %s\n", uevent_data.sysfs_path.c_str(), uevent_data.action.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003200}
3201
3202void TWPartitionManager::setup_uevent() {
3203 struct sockaddr_nl nls;
3204
3205 if (uevent_pfd.fd >= 0) {
3206 LOGINFO("uevent already set up\n");
3207 return;
3208 }
3209
3210 // Open hotplug event netlink socket
3211 memset(&nls,0,sizeof(struct sockaddr_nl));
3212 nls.nl_family = AF_NETLINK;
3213 nls.nl_pid = getpid();
3214 nls.nl_groups = -1;
3215 uevent_pfd.events = POLLIN;
3216 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
3217 if (uevent_pfd.fd==-1) {
3218 LOGERR("uevent not root\n");
3219 return;
3220 }
3221
3222 // Listen to netlink socket
3223 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
3224 LOGERR("Bind failed\n");
3225 return;
3226 }
3227 set_select_fd();
3228 Coldboot();
3229}
3230
3231Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
3232 Uevent_Block_Data ret;
3233 ret.subsystem = "";
3234 char *ptr = buf;
3235 const char *end = buf + len;
3236
3237 buf[len - 1] = '\0';
3238 while (ptr < end) {
3239 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
3240 ptr += strlen("ACTION=");
3241 ret.action = ptr;
3242 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
3243 ptr += strlen("SUBSYSTEM=");
3244 ret.subsystem = ptr;
3245 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
3246 ptr += strlen("DEVTYPE=");
3247 ret.type = ptr;
3248 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
3249 ptr += strlen("DEVPATH=");
3250 ret.sysfs_path += ptr;
3251 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
3252 ptr += strlen("DEVNAME=");
3253 ret.block_device += ptr;
3254 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
3255 ptr += strlen("MAJOR=");
3256 ret.major = atoi(ptr);
3257 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
3258 ptr += strlen("MINOR=");
3259 ret.minor = atoi(ptr);
3260 }
3261 ptr += strlen(ptr) + 1;
3262 }
3263 return ret;
3264}
3265
3266void TWPartitionManager::read_uevent() {
3267 char buf[1024];
3268
3269 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
3270 if (len == -1) {
Mauronofrio Matarresec1bb76e2019-08-04 17:02:41 +01003271 LOGINFO("recv error on uevent\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003272 return;
3273 }
3274 /*int i = 0; // Print all uevent output for test /debug
3275 while (i<len) {
3276 printf("%s\n", buf+i);
3277 i += strlen(buf+i)+1;
3278 }*/
3279 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
3280 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
3281 PartitionManager.Handle_Uevent(uevent_data);
3282 }
3283}
3284
3285void TWPartitionManager::close_uevent() {
3286 if (uevent_pfd.fd > 0)
3287 close(uevent_pfd.fd);
3288 uevent_pfd.fd = -1;
3289}
3290
3291void TWPartitionManager::Add_Partition(TWPartition* Part) {
3292 Partitions.push_back(Part);
3293}
3294
3295void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
3296 string Real_Path = Path;
3297 char real_path[PATH_MAX];
3298 if (realpath(Path.c_str(), &real_path[0])) {
3299 string Real_Path = real_path;
3300 std::vector<string>::iterator iter;
3301 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
3302 if (Real_Path.find((*iter)) != string::npos) {
3303 string Write_Path = Real_Path + "/uevent";
3304 if (TWFunc::Path_Exists(Write_Path)) {
3305 const char* write_val = "add\n";
3306 TWFunc::write_to_file(Write_Path, write_val);
3307 break;
3308 }
3309 }
3310 }
3311 }
3312
3313 DIR* d = opendir(Path.c_str());
3314 if (d != NULL) {
3315 struct dirent* de;
3316 while ((de = readdir(d)) != NULL) {
3317 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
3318 continue;
3319 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
3320 continue;
3321
3322 string item = Path + "/";
3323 item.append(de->d_name);
3324 Coldboot_Scan(sysfs_entries, item, depth + 1);
3325 }
3326 closedir(d);
3327 }
3328}
3329
3330void TWPartitionManager::Coldboot() {
3331 std::vector<TWPartition*>::iterator iter;
3332 std::vector<string> sysfs_entries;
3333
3334 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3335 if (!(*iter)->Sysfs_Entry.empty()) {
3336 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
3337 if (wildcard_pos == string::npos)
3338 wildcard_pos = (*iter)->Sysfs_Entry.size();
3339 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
3340 }
3341 }
3342
3343 if (sysfs_entries.size() > 0)
3344 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
3345}
Ethan Yonker53796e72019-01-11 22:49:52 -06003346
3347bool TWPartitionManager::Prepare_Empty_Folder(const std::string& Folder) {
3348 if (TWFunc::Path_Exists(Folder))
3349 TWFunc::removeDir(Folder, false);
3350 return TWFunc::Recursive_Mkdir(Folder);
3351}
3352
bigbiffcfa875c2021-06-20 16:20:27 -04003353std::string TWPartitionManager::Get_Bare_Partition_Name(std::string Mount_Point) {
3354 if (Mount_Point == "/system_root")
3355 return "system";
3356 else
3357 return TWFunc::Remove_Beginning_Slash(Mount_Point);
3358}
3359
bigbiffee7b7ff2020-03-23 15:08:27 -04003360bool TWPartitionManager::Prepare_Super_Volume(TWPartition* twrpPart) {
3361 Fstab fstab;
bigbiffcfa875c2021-06-20 16:20:27 -04003362 std::string bare_partition_name = Get_Bare_Partition_Name(twrpPart->Get_Mount_Point());
bigbiffee7b7ff2020-03-23 15:08:27 -04003363
bigbiff998f8392021-08-06 19:19:33 -04003364 Super_Partition_List.push_back(bare_partition_name);
bigbiffee7b7ff2020-03-23 15:08:27 -04003365 LOGINFO("Trying to prepare %s from super partition\n", bare_partition_name.c_str());
3366
3367 std::string blk_device_partition;
3368#ifdef AB_OTA_UPDATER
3369 blk_device_partition = bare_partition_name + PartitionManager.Get_Active_Slot_Suffix();
3370#else
3371 blk_device_partition = bare_partition_name;
3372#endif
3373
3374 FstabEntry fstabEntry = {
3375 .blk_device = blk_device_partition,
3376 .mount_point = twrpPart->Get_Mount_Point(),
3377 .fs_type = twrpPart->Current_File_System,
3378 .fs_mgr_flags.logical = twrpPart->Is_Super,
3379 };
3380
3381 fstab.emplace_back(fstabEntry);
3382 if (!fs_mgr_update_logical_partition(&fstabEntry)) {
Captain Throwbackc6939102021-04-06 12:57:30 -04003383 LOGINFO("unable to update logical partition: %s\n", twrpPart->Get_Mount_Point().c_str());
bigbiffee7b7ff2020-03-23 15:08:27 -04003384 return false;
3385 }
3386
bigbiff32cbabe2020-04-12 19:16:19 -04003387 while (access(fstabEntry.blk_device.c_str(), F_OK) != 0) {
3388 usleep(100);
3389 }
3390
bigbiffee7b7ff2020-03-23 15:08:27 -04003391 twrpPart->Set_Block_Device(fstabEntry.blk_device);
3392 twrpPart->Update_Size(true);
3393 twrpPart->Change_Mount_Read_Only(true);
3394 twrpPart->Set_Can_Be_Backed_Up(false);
3395 twrpPart->Set_Can_Be_Wiped(false);
Mohd Faraz7fc70502021-04-22 20:44:11 +02003396 LOGINFO("Symlinking %s => /dev/block/bootdevice/by-name/%s \n", fstabEntry.blk_device.c_str(), bare_partition_name.c_str());
3397 symlink(fstabEntry.blk_device.c_str(), ("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str());
3398
bigbiffee7b7ff2020-03-23 15:08:27 -04003399 return true;
3400}
3401
3402bool TWPartitionManager::Prepare_All_Super_Volumes() {
3403 bool status = true;
3404 std::vector<TWPartition*>::iterator iter;
3405
3406 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3407 if ((*iter)->Is_Super) {
3408 if (!Prepare_Super_Volume(*iter)) {
3409 status = false;
3410 }
3411 PartitionManager.Output_Partition(*iter);
3412 }
3413 }
3414 Update_System_Details();
3415 return status;
3416}
3417
bigbiffee7b7ff2020-03-23 15:08:27 -04003418std::string TWPartitionManager::Get_Super_Partition() {
3419 int slot_number = Get_Active_Slot_Display() == "A" ? 0 : 1;
bigbiff998f8392021-08-06 19:19:33 -04003420 std::string super_device = fs_mgr_get_super_partition_name(slot_number);
bigbiffee7b7ff2020-03-23 15:08:27 -04003421 return "/dev/block/by-name/" + super_device;
3422}
3423
3424void TWPartitionManager::Setup_Super_Devices() {
3425 std::string superPart = Get_Super_Partition();
3426 android::fs_mgr::CreateLogicalPartitions(superPart);
bigbiff7ba75002020-04-11 20:47:09 -04003427}
3428
3429void TWPartitionManager::Setup_Super_Partition() {
bigbiffee7b7ff2020-03-23 15:08:27 -04003430 TWPartition* superPartition = new TWPartition();
bigbiff7ba75002020-04-11 20:47:09 -04003431 std::string superPart = Get_Super_Partition();
3432
3433 superPartition->Backup_Path = "/super";
3434 superPartition->Mount_Point = "/super";
bigbiffee7b7ff2020-03-23 15:08:27 -04003435 superPartition->Actual_Block_Device = superPart;
3436 superPartition->Alternate_Block_Device = superPart;
bigbiff998f8392021-08-06 19:19:33 -04003437 superPartition->Backup_Display_Name = "Super (";
3438 // Add first 4 items to fstab as logical that you would like to display in Backup_Display_Name
3439 // for the Super partition
3440 int list_size = Super_Partition_List.size();
3441 int orig_list_size = list_size;
3442 int max_display_size = 3; // total of 4 items since we start at 0
3443
3444 for (auto partition: Super_Partition_List) {
3445 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + partition;
3446 if ((orig_list_size - list_size) == max_display_size) {
3447 break;
3448 }
3449 if (list_size != 1)
3450 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + " ";
3451 list_size--;
3452 }
3453 superPartition->Backup_Display_Name += ")";
bigbiffee7b7ff2020-03-23 15:08:27 -04003454 superPartition->Can_Flash_Img = true;
bigbiffee7b7ff2020-03-23 15:08:27 -04003455 superPartition->Current_File_System = "emmc";
3456 superPartition->Can_Be_Backed_Up = true;
3457 superPartition->Is_Present = true;
3458 superPartition->Is_SubPartition = false;
bigbiff7ba75002020-04-11 20:47:09 -04003459 superPartition->Setup_Image();
bigbiffee7b7ff2020-03-23 15:08:27 -04003460 Add_Partition(superPartition);
3461 PartitionManager.Output_Partition(superPartition);
bigbiffee7b7ff2020-03-23 15:08:27 -04003462}
3463
3464bool TWPartitionManager::Get_Super_Status() {
bigbiffdf8436b2020-08-30 16:22:34 -04003465 std::string fastboot_mode = android::base::GetProperty("sys.usb.config", "");
3466 if (fastboot_mode == "fastboot") {
3467 return false;
3468 }
3469 else
3470 return access(Get_Super_Partition().c_str(), F_OK) == 0;
bigbiffee7b7ff2020-03-23 15:08:27 -04003471}
bigbiff25d25b92020-06-19 16:07:38 -04003472
3473bool TWPartitionManager::Recreate_Logs_Dir() {
3474#ifdef TW_INCLUDE_FBE
3475 struct passwd pd;
3476 struct passwd *pwdptr = &pd;
3477 struct passwd *tempPd;
3478 char pwdBuf[512];
3479 int uid = 0, gid = 0;
3480
3481 if ((getpwnam_r("system", pwdptr, pwdBuf, sizeof(pwdBuf), &tempPd)) != 0) {
3482 LOGERR("unable to get system user id\n");
3483 return false;
3484 } else {
3485 struct group grp;
3486 struct group *grpptr = &grp;
3487 struct group *tempGrp;
3488 char grpBuf[512];
3489
3490 if ((getgrnam_r("cache", grpptr, grpBuf, sizeof(grpBuf), &tempGrp)) != 0) {
3491 LOGERR("unable to get cache group id\n");
3492 return false;
3493 } else {
3494 uid = pd.pw_uid;
3495 gid = grp.gr_gid;
3496 std::string abLogsRecoveryDir(DATA_LOGS_DIR);
3497 abLogsRecoveryDir += "/recovery/";
3498
3499 if (!TWFunc::Create_Dir_Recursive(abLogsRecoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
3500 LOGERR("Unable to recreate %s\n", abLogsRecoveryDir.c_str());
3501 return false;
3502 }
3503 if (setfilecon(abLogsRecoveryDir.c_str(), "u:object_r:cache_file:s0") != 0) {
3504 LOGERR("Unable to set contexts for %s\n", abLogsRecoveryDir.c_str());
3505 return false;
3506 }
3507 }
3508 }
3509#endif
3510 return true;
3511}
bigbiff1f9e4842020-10-31 11:33:15 -04003512
3513void TWPartitionManager::Unlock_Block_Partitions() {
3514 int fd, OFF = 0;
3515
3516 const std::string block_path = "/dev/block/";
3517 DIR* d = opendir(block_path.c_str());
3518 if (d != NULL) {
3519 struct dirent* de;
3520 while ((de = readdir(d)) != NULL) {
3521 if (de->d_type == DT_BLK) {
3522 std::string block_device = block_path + de->d_name;
bigbiff1f9e4842020-10-31 11:33:15 -04003523 if ((fd = open(block_device.c_str(), O_RDONLY | O_CLOEXEC)) < 0) {
3524 LOGERR("unable to open block device %s: %s\n", block_device.c_str(), strerror(errno));
3525 continue;
3526 }
3527 if (ioctl(fd, BLKROSET, &OFF) == -1) {
3528 LOGERR("Unable to unlock %s for flashing: %s\n", block_device.c_str());
3529 continue;
3530 }
3531 close(fd);
3532 }
3533 }
3534 closedir(d);
3535 }
bigbiffaf253cd2020-12-06 16:50:55 -05003536}
bigbiffcfa875c2021-06-20 16:20:27 -04003537
3538bool TWPartitionManager::Unmap_Super_Devices() {
3539 bool destroyed = false;
3540#ifndef TW_EXCLUDE_APEX
3541 twrpApex apex;
3542 apex.Unmount();
3543#endif
3544 for (auto iter = Partitions.begin(); iter != Partitions.end();) {
3545 LOGINFO("Checking partition: %s\n", (*iter)->Get_Mount_Point().c_str());
3546 if ((*iter)->Is_Super) {
3547 TWPartition *part = *iter;
3548 std::string bare_partition_name = Get_Bare_Partition_Name((*iter)->Get_Mount_Point());
3549 std::string blk_device_partition = bare_partition_name + PartitionManager.Get_Active_Slot_Suffix();
3550 (*iter)->UnMount(false);
3551 LOGINFO("removing dynamic partition: %s\n", blk_device_partition.c_str());
3552 destroyed = DestroyLogicalPartition(blk_device_partition);
3553 std::string cow_partition = blk_device_partition + "-cow";
3554 std::string cow_partition_path = "/dev/block/mapper/" + cow_partition;
3555 struct stat st;
3556 if (lstat(cow_partition_path.c_str(), &st) == 0) {
3557 LOGINFO("removing cow partition: %s\n", cow_partition.c_str());
3558 destroyed = DestroyLogicalPartition(cow_partition);
3559 }
bigbiffcfa875c2021-06-20 16:20:27 -04003560 iter = Partitions.erase(iter);
3561 delete part;
3562 if (!destroyed) {
3563 return false;
3564 }
3565 } else {
3566 ++iter;
3567 }
3568 }
3569 return true;
3570}
bigbiffd21252f2021-09-18 15:56:32 -04003571
3572
3573bool TWPartitionManager::Check_Pending_Merges() {
3574 auto sm = android::snapshot::SnapshotManager::NewForFirstStageMount();
3575 if (!sm) {
3576 LOGERR("Unable to call snapshot manager\n");
3577 return false;
3578 }
3579
3580 if (!Unmap_Super_Devices()) {
3581 LOGERR("Unable to unmap dynamic partitions.\n");
3582 return false;
3583 }
3584
3585 auto callback = [&]() -> void {
3586 double progress;
3587 sm->GetUpdateState(&progress);
3588 LOGINFO("waiting for merge to complete: %.2f\n", progress);
3589 };
3590
3591 LOGINFO("checking for merges\n");
3592 if (!sm->HandleImminentDataWipe(callback)) {
3593 LOGERR("Unable to check merge status\n");
3594 return false;
3595 }
3596 return true;
3597}