blob: 88e2dbd49e9f2c3e0257b1912579f19ed93e76d7 [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
bigbiffdf53b6c2022-01-17 19:31:52 -050096// #include "crypto/fde/cryptfs.h"
bigbiff7ba75002020-04-11 20:47:09 -040097#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
bigbiffdf53b6c2022-01-17 19:31:52 -0500103 #include "cryptfs.h"
104 #include "fscrypt-common.h"
bigbiffa957f072021-03-07 18:20:29 -0500105 #include "MetadataCrypt.h"
bigbiffadc599e2020-05-28 19:36:30 +0000106 #endif
bigbiff7ba75002020-04-11 20:47:09 -0400107#endif
108#endif
Dees_Troy5bf43922012-09-07 16:07:55 -0400109#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400110
Ethan Yonker1b190162016-12-05 15:25:19 -0600111#ifdef AB_OTA_UPDATER
dianlujitaoa90dc462021-12-16 16:56:26 +0800112#include <android/hardware/boot/1.0/IBootControl.h>
113using android::hardware::boot::V1_0::CommandResult;
114using android::hardware::boot::V1_0::IBootControl;
Ethan Yonker1b190162016-12-05 15:25:19 -0600115#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
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100125std::string additional_fstab = "/etc/additional.fstab";
126
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500127TWPartitionManager::TWPartitionManager(void) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -0400128 mtp_was_enabled = false;
Ethan Yonker726a0202014-12-16 20:01:38 -0600129 mtp_write_fd = -1;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600130 uevent_pfd.fd = -1;
bigbiff7abc5fe2015-01-17 16:53:12 -0500131 stop_backup.set_value(0);
Ethan Yonker1b190162016-12-05 15:25:19 -0600132#ifdef AB_OTA_UPDATER
133 char slot_suffix[PROPERTY_VALUE_MAX];
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500134 property_get("ro.boot.slot_suffix", slot_suffix, "error");
135 if (strcmp(slot_suffix, "error") == 0)
136 property_get("ro.boot.slot", slot_suffix, "error");
Ethan Yonker1b190162016-12-05 15:25:19 -0600137 Active_Slot_Display = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500138 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Ethan Yonker1b190162016-12-05 15:25:19 -0600139 Set_Active_Slot("A");
140 else
141 Set_Active_Slot("B");
142#endif
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500143}
144
Captain Throwback37c3aef2021-10-06 11:38:18 -0400145void TWPartitionManager::Set_Crypto_State() {
146 char crypto_state[PROPERTY_VALUE_MAX];
147 property_get("ro.crypto.state", crypto_state, "error");
148 if (strcmp(crypto_state, "error") == 0)
149 property_set("ro.crypto.state", "encrypted");
150}
151
152int TWPartitionManager::Set_Crypto_Type(const char* crypto_type) {
153 char type_prop[PROPERTY_VALUE_MAX];
154 property_get("ro.crypto.type", type_prop, "error");
155 if (strcmp(type_prop, "error") == 0)
156 property_set("ro.crypto.type", crypto_type);
Captain Throwback18aea272020-10-29 12:43:17 -0400157 // Sleep for a bit so that services can start if needed
158 sleep(1);
159 return 0;
160}
161
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100162void inline Reset_Prop_From_Partition(std::string prop, std::string def, TWPartition *ven, TWPartition *odm) {
163 bool prop_on_odm = false, prop_on_vendor = false;
164 string prop_value;
165 if (odm) {
166 string odm_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/odm", "etc/build.prop");
167 if (!odm_prop.empty()) {
168 prop_on_odm = true;
169 if (TWFunc::Property_Override(prop, odm_prop) == NOT_AVAILABLE) {
170 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
171 } else {
172 prop_value = android::base::GetProperty(prop, "");
173 LOGINFO("Setting '%s' to '%s' from /odm/etc/build.prop\n", prop.c_str(), prop_value.c_str());
174 }
175 }
176 }
177 if (ven) {
178 string vendor_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/vendor", "build.prop");
179 if (!vendor_prop.empty()) {
180 prop_on_vendor = true;
181 if (TWFunc::Property_Override(prop, vendor_prop) == NOT_AVAILABLE) {
182 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
183 } else {
184 prop_value = android::base::GetProperty(prop, "");
185 LOGINFO("Setting '%s' to '%s' from /vendor/build.prop\n", prop.c_str(), prop_value.c_str());
186 }
187 }
188 }
189 if (!prop_on_odm && !prop_on_vendor && !def.empty()) {
190 if (TWFunc::Property_Override(prop, def) == NOT_AVAILABLE) {
191 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
192 } else {
193 prop_value = android::base::GetProperty(prop, "");
194 LOGINFO("Setting '%s' to default value (%s)\n", prop.c_str(), prop_value.c_str());
195 }
196 }
197 prop_value = android::base::GetProperty(prop, "");
198 if (!prop_on_odm && !prop_on_vendor && !prop_value.empty() && def.empty()) {
199 if(TWFunc::Delete_Property(prop) == NOT_AVAILABLE) {
200 LOGERR("Unable to delete '%s' due to missing libresetprop\n", prop.c_str());
201 } else {
202 LOGINFO("Deleting property '%s'\n", prop.c_str());
203 }
204 }
205}
206
bigbiff22851b92021-09-01 16:46:57 -0400207int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool recovery_mode) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400208 FILE *fstabFile;
209 char fstab_line[MAX_FSTAB_LINE_LENGTH];
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100210 bool parse_userdata = false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600211 std::map<string, Flags_Map> twrp_flags;
212
213 fstabFile = fopen("/etc/twrp.flags", "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100214 if (Get_Super_Status()) {
215 Setup_Super_Devices();
216 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600217 if (fstabFile != NULL) {
Ian Macdonald160e8d32020-09-29 20:47:31 +0200218 LOGINFO("Reading /etc/twrp.flags\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600219 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600220 size_t line_size = strlen(fstab_line);
221 if (fstab_line[line_size - 1] != '\n')
222 fstab_line[line_size] = '\n';
223 Flags_Map line_flags;
224 line_flags.Primary_Block_Device = "";
225 line_flags.Alternate_Block_Device = "";
226 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
227 if (!line_flags.fstab_line) {
228 LOGERR("malloc error on line_flags.fstab_line\n");
229 return false;
230 }
231 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
232 bool found_separator = false;
233 char *fs_loc = NULL;
234 char *block_loc = NULL;
235 char *flags_loc = NULL;
236 size_t index, item_index = 0;
237 for (index = 0; index < line_size; index++) {
238 if (fstab_line[index] <= 32) {
239 fstab_line[index] = '\0';
240 found_separator = true;
241 } else if (found_separator) {
242 if (item_index == 0) {
243 fs_loc = fstab_line + index;
244 } else if (item_index == 1) {
245 block_loc = fstab_line + index;
246 } else if (item_index > 1) {
247 char *ptr = fstab_line + index;
248 if (*ptr == '/') {
249 line_flags.Alternate_Block_Device = ptr;
250 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
251 flags_loc = ptr;
252 // Once we find the flags=, we're done scanning the line
253 break;
254 }
255 }
256 found_separator = false;
257 item_index++;
258 }
259 }
260 if (block_loc)
261 line_flags.Primary_Block_Device = block_loc;
262 if (fs_loc)
263 line_flags.File_System = fs_loc;
264 if (flags_loc)
265 line_flags.Flags = flags_loc;
266 string Mount_Point = fstab_line;
267 twrp_flags[Mount_Point] = line_flags;
268 memset(fstab_line, 0, sizeof(fstab_line));
269 }
270 fclose(fstabFile);
271 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100272 TWPartition *data = NULL;
273 TWPartition *meta = NULL;
274parse:
Dees_Troy5bf43922012-09-07 16:07:55 -0400275 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100276 if (!parse_userdata && fstabFile == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000277 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400278 return false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600279 } else
280 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400281
282 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600283 if (strstr(fstab_line, "swap"))
284 continue; // Skip swap in recovery
285
bigbiff998f8392021-08-06 19:19:33 -0400286 if (fstab_line[0] == '#')
287 continue;
288
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100289 if (parse_userdata) {
290 if (strstr(fstab_line, "/metadata") && !strstr(fstab_line, "/data")) {
sekaiacg01ac7722023-08-01 09:32:00 +0800291 if (meta) {
292 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), meta));
293 delete meta;
294 meta = NULL;
295 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100296 } else if (strstr(fstab_line, "/data")) {
sekaiacg01ac7722023-08-01 09:32:00 +0800297 if (data) {
298 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), data));
299 delete data;
300 data = NULL;
301 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100302 } else {
303 continue;
304 }
305 }
306
307
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600308 size_t line_size = strlen(fstab_line);
309 if (fstab_line[line_size - 1] != '\n')
310 fstab_line[line_size] = '\n';
Dees_Troy2a923582012-09-20 12:13:34 -0400311
Matt Mower2b2dd152016-04-26 11:24:08 -0500312 TWPartition* partition = new TWPartition();
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100313 if (partition->Process_Fstab_Line(fstab_line, Display_Error, parse_userdata ? NULL : &twrp_flags)) {
314 if (partition->Mount_Point == "/data") data = partition;
315 if (partition->Mount_Point == "/metadata") meta = partition;
316 if (partition->Is_Super && !Prepare_Super_Volume(partition)) {
317 goto clear;
318 }
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500319 Partitions.push_back(partition);
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100320 }
Matt Mower72c87ce2016-04-26 14:34:56 -0500321 else
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100322clear:
Dees_Troy5bf43922012-09-07 16:07:55 -0400323 delete partition;
Matt Mower2b2dd152016-04-26 11:24:08 -0500324
325 memset(fstab_line, 0, sizeof(fstab_line));
Dees_Troy5bf43922012-09-07 16:07:55 -0400326 }
327 fclose(fstabFile);
Matt Mower72c87ce2016-04-26 14:34:56 -0500328
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100329 if (!parse_userdata && twrp_flags.size() > 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600330 LOGINFO("Processing remaining twrp.flags\n");
331 // Add any items from twrp.flags that did not exist in the recovery.fstab
332 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
333 if (Find_Partition_By_Path(mapit->first) == NULL) {
334 TWPartition* partition = new TWPartition();
bigbiff8da46fa2020-09-08 16:42:34 -0400335 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600336 Partitions.push_back(partition);
337 else
338 delete partition;
339 }
340 if (mapit->second.fstab_line)
341 free(mapit->second.fstab_line);
342 mapit->second.fstab_line = NULL;
343 }
344 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100345 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
346 TWPartition* odm = PartitionManager.Find_Partition_By_Path("/odm");
347 if (!parse_userdata) {
348
Mohd Farazec370452023-08-28 16:51:35 +0530349 if (ven) ven->Mount(Display_Error);
350 if (odm) odm->Mount(Display_Error);
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100351 if (TWFunc::Find_Fstab(Fstab_Filename)) {
352 string service;
353 LOGINFO("Fstab: %s\n", Fstab_Filename.c_str());
354 TWFunc::copy_file(Fstab_Filename, additional_fstab, 0600, false);
355 Fstab_Filename = additional_fstab;
356 property_set("fstab.additional", "1");
357 TWFunc::Get_Service_From(ven, "keymaster", service);
Captain Throwback500c3d22023-08-28 17:20:35 -0400358 LOGINFO("Keymaster version: '%s'\n", TWFunc::Get_Version_From_Service(service).c_str());
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100359 property_set("keymaster_ver", TWFunc::Get_Version_From_Service(service).c_str());
360 parse_userdata = true;
361 Reset_Prop_From_Partition("ro.crypto.dm_default_key.options_format.version", "", ven, odm);
362 Reset_Prop_From_Partition("ro.crypto.volume.metadata.method", "", ven, odm);
363 Reset_Prop_From_Partition("ro.crypto.volume.options", "", ven, odm);
364 Reset_Prop_From_Partition("external_storage.projid.enabled", "", ven, odm);
365 Reset_Prop_From_Partition("external_storage.casefold.enabled", "", ven, odm);
366 Reset_Prop_From_Partition("external_storage.sdcardfs.enabled", "", ven, odm);
367 goto parse;
368 } else {
369 LOGINFO("Unable to parse vendor fstab\n");
370 }
Mohd Faraze3948ec2020-08-14 01:40:59 +0000371 }
Mohd Farazec370452023-08-28 16:51:35 +0530372 if (ven) ven->UnMount(Display_Error);
373 if (odm) odm->UnMount(Display_Error);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600374 LOGINFO("Done processing fstab files\n");
375
bigbiff7ba75002020-04-11 20:47:09 -0400376 return true;
377}
378
bigbiff22851b92021-09-01 16:46:57 -0400379void TWPartitionManager::Setup_Fstab_Partitions(bool Display_Error) {
380 TWPartition* settings_partition = NULL;
381 TWPartition* andsec_partition = NULL;
382 std::vector<TWPartition*>::iterator iter;
383 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
384
385 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
386 (*iter)->Partition_Post_Processing(Display_Error);
387
388 if ((*iter)->Is_Storage) {
389 ++storageid;
390 (*iter)->MTP_Storage_ID = storageid;
391 }
392
393 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
394 settings_partition = (*iter);
395 else
396 (*iter)->Is_Settings_Storage = false;
397
398 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
399 andsec_partition = (*iter);
400 else
401 (*iter)->Has_Android_Secure = false;
bigbiff22851b92021-09-01 16:46:57 -0400402 }
403
me-cafebabed63fcaa2022-07-28 03:19:20 +0800404 Unlock_Block_Partitions();
405
bigbiff22851b92021-09-01 16:46:57 -0400406 //Setup Apex before decryption
407 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
408 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
409 if (sys) {
410 if (sys->Get_Super_Status()) {
Mohd Farazec370452023-08-28 16:51:35 +0530411 sys->Mount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400412 if (ven) {
Mohd Farazec370452023-08-28 16:51:35 +0530413 ven->Mount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400414 }
415 #ifdef TW_EXCLUDE_APEX
416 LOGINFO("Apex is disabled in this build\n");
417 #else
418 twrpApex apex;
419 if (!apex.loadApexImages()) {
420 LOGERR("Unable to load apex images from %s\n", APEX_DIR);
421 property_set("twrp.apex.loaded", "false");
422 } else {
423 property_set("twrp.apex.loaded", "true");
424 }
425 TWFunc::check_and_run_script("/sbin/resyncapex.sh", "apex");
426 #endif
427 }
428 }
429 #ifndef USE_VENDOR_LIBS
430 if (ven)
Mohd Farazec370452023-08-28 16:51:35 +0530431 ven->UnMount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400432 if (sys)
Mohd Farazec370452023-08-28 16:51:35 +0530433 sys->UnMount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400434 #endif
435
436 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) {
437 // Attempt to automatically identify /data/media emulated storage devices
438 TWPartition* Dat = Find_Partition_By_Path("/data");
439 if (Dat) {
440 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
441 datamedia = true;
442 Dat->Setup_Data_Media();
443 settings_partition = Dat;
444 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
445 ++storageid;
446 Dat->MTP_Storage_ID = storageid;
447 }
448 }
449 if (!settings_partition) {
450 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
451 if ((*iter)->Is_Storage) {
452 settings_partition = (*iter);
453 break;
454 }
455 }
456 if (!settings_partition)
457 LOGERR("Unable to locate storage partition for storing settings file.\n");
458 }
459 if (!Write_Fstab()) {
460 if (Display_Error)
461 LOGERR("Error creating fstab\n");
462 else
463 LOGINFO("Error creating fstab\n");
464 }
465
466 if (andsec_partition) {
467 Setup_Android_Secure_Location(andsec_partition);
468 } else if (settings_partition) {
469 Setup_Android_Secure_Location(settings_partition);
470 }
471 if (settings_partition) {
472 Setup_Settings_Storage_Partition(settings_partition);
473 }
474
475 #ifdef TW_INCLUDE_CRYPTO
476 DataManager::SetValue(TW_IS_ENCRYPTED, 1);
477 Decrypt_Data();
478 #endif
479
480 Update_System_Details();
481 if (Get_Super_Status())
482 Setup_Super_Partition();
483 UnMount_Main_Partitions();
484 #ifdef AB_OTA_UPDATER
485 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
486 #endif
487 setup_uevent();
488}
489
bigbiff7ba75002020-04-11 20:47:09 -0400490int TWPartitionManager::Write_Fstab(void) {
491 FILE *fp;
492 std::vector<TWPartition*>::iterator iter;
493 string Line;
494
495 fp = fopen("/etc/fstab", "w");
496 if (fp == NULL) {
497 LOGINFO("Can not open /etc/fstab.\n");
498 return false;
499 }
500 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
501 if ((*iter)->Can_Be_Mounted) {
Mohd Faraz2a1e3752020-09-30 10:55:48 +0530502 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System +
503 ((*iter)->Mount_Read_Only ? " ro " : " rw ") + "0 0\n";
bigbiff7ba75002020-04-11 20:47:09 -0400504 fputs(Line.c_str(), fp);
505 }
506 // Handle subpartition tracking
507 if ((*iter)->Is_SubPartition) {
508 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
509 if (ParentPartition)
510 ParentPartition->Has_SubPartition = true;
511 else
512 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
513 }
514 }
515 fclose(fp);
516 return true;
517}
518
519void TWPartitionManager::Decrypt_Data() {
520 #ifdef TW_INCLUDE_CRYPTO
Ethan Yonkercceebb82014-11-18 10:17:59 -0600521 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
522 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
Captain Throwback37c3aef2021-10-06 11:38:18 -0400523 Set_Crypto_State();
bigbiff4fa02b52021-12-30 17:01:44 -0500524 TWPartition* Key_Directory_Partition = Find_Partition_By_Path(Decrypt_Data->Key_Directory);
525 if (Key_Directory_Partition != nullptr)
526 if (!Key_Directory_Partition->Is_Mounted())
527 Mount_By_Path(Decrypt_Data->Key_Directory, false);
528 if (!Decrypt_Data->Key_Directory.empty()) {
529 Set_Crypto_Type("file");
Ethan Yonker93382822018-11-01 15:25:31 -0500530#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
bigbiff7ba75002020-04-11 20:47:09 -0400531#ifdef USE_FSCRYPT
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100532 if (android::vold::fscrypt_mount_metadata_encrypted(Decrypt_Data->Actual_Block_Device, Decrypt_Data->Mount_Point, false, false, Decrypt_Data->Current_File_System, TWFunc::Path_Exists(additional_fstab) ? additional_fstab : "")) {
bigbiffa957f072021-03-07 18:20:29 -0500533 std::string crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "error");
Mohd Faraze3948ec2020-08-14 01:40:59 +0000534 Decrypt_Data->Decrypted_Block_Device = crypto_blkdev;
bigbiff7ba75002020-04-11 20:47:09 -0400535 LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400536#endif
Ethan Yonker93382822018-11-01 15:25:31 -0500537 Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
538 int retry_count = 10;
539 while (!Decrypt_Data->Mount(false) && --retry_count)
540 usleep(500);
541 if (Decrypt_Data->Mount(false)) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400542 if (!Decrypt_Data->Decrypt_FBE_DE()) {
bigbiff437d86f2021-09-26 16:57:14 -0400543 LOGERR("Unable to decrypt FBE device\n");
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400544 }
545
Ethan Yonker93382822018-11-01 15:25:31 -0500546 } else {
547 LOGINFO("Failed to mount data after metadata decrypt\n");
548 }
549 } else {
550 LOGINFO("Unable to decrypt metadata encryption\n");
551 }
552#else
553 LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
554#endif
555 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600556 if (Decrypt_Data->Is_FBE) {
557 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
558 if (Decrypt_Device("!") == 0) {
559 gui_msg("decrypt_success=Successfully decrypted with default password.");
560 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
561 } else {
562 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
563 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600564 }
565 } else {
Captain Throwback500c3d22023-08-28 17:20:35 -0400566 LOGINFO("FBE setup failed. Trying FDE...\n");
Captain Throwback37c3aef2021-10-06 11:38:18 -0400567 Set_Crypto_State();
568 Set_Crypto_Type("block");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600569 int password_type = cryptfs_get_password_type();
570 if (password_type == CRYPT_TYPE_DEFAULT) {
571 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
572 if (Decrypt_Device("default_password") == 0) {
573 gui_msg("decrypt_success=Successfully decrypted with default password.");
574 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
575 } else {
576 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
577 }
578 } else {
579 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
Noah Jacobson81d638d2019-04-28 00:10:07 -0400580 DataManager::SetValue("tw_crypto_pwtype_0", password_type);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600581 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600582 }
583 }
bigbiff4fa02b52021-12-30 17:01:44 -0500584 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted)) {
Ethan Yonker66a19492015-12-10 10:19:45 -0600585 Decrypt_Adopted();
586 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600587#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400588}
589
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500590void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500591 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500592}
593
Matt Mowerbf4efa32014-04-14 23:25:26 -0500594void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
595 if (Part->Has_Android_Secure)
596 Part->Setup_AndSec();
Ethan Yonker6277c792014-09-15 14:54:30 -0500597 else if (!datamedia)
Matt Mowerbf4efa32014-04-14 23:25:26 -0500598 Part->Setup_AndSec();
Matt Mowerbf4efa32014-04-14 23:25:26 -0500599}
600
Dees_Troy8170a922012-09-18 15:40:25 -0400601void TWPartitionManager::Output_Partition_Logging(void) {
602 std::vector<TWPartition*>::iterator iter;
603
604 printf("\n\nPartition Logs:\n");
605 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
606 Output_Partition((*iter));
607}
608
609void TWPartitionManager::Output_Partition(TWPartition* Part) {
610 unsigned long long mb = 1048576;
611
Gary Peck004d48b2012-11-21 16:28:18 -0800612 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 -0400613 if (Part->Can_Be_Mounted) {
Gary Peck004d48b2012-11-21 16:28:18 -0800614 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 -0400615 }
Gary Peck004d48b2012-11-21 16:28:18 -0800616 printf("\n Flags: ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500617 if (Part->Can_Be_Mounted)
618 printf("Can_Be_Mounted ");
Gary Peck004d48b2012-11-21 16:28:18 -0800619 if (Part->Can_Be_Wiped)
620 printf("Can_Be_Wiped ");
Hashcodedabfd492013-08-29 22:45:30 -0700621 if (Part->Use_Rm_Rf)
622 printf("Use_Rm_Rf ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500623 if (Part->Can_Be_Backed_Up)
624 printf("Can_Be_Backed_Up ");
Gary Peck004d48b2012-11-21 16:28:18 -0800625 if (Part->Wipe_During_Factory_Reset)
626 printf("Wipe_During_Factory_Reset ");
627 if (Part->Wipe_Available_in_GUI)
628 printf("Wipe_Available_in_GUI ");
629 if (Part->Is_SubPartition)
630 printf("Is_SubPartition ");
631 if (Part->Has_SubPartition)
632 printf("Has_SubPartition ");
633 if (Part->Removable)
634 printf("Removable ");
635 if (Part->Is_Present)
636 printf("IsPresent ");
637 if (Part->Can_Be_Encrypted)
638 printf("Can_Be_Encrypted ");
639 if (Part->Is_Encrypted)
640 printf("Is_Encrypted ");
641 if (Part->Is_Decrypted)
642 printf("Is_Decrypted ");
643 if (Part->Has_Data_Media)
644 printf("Has_Data_Media ");
Dees_Troy83bd4832013-05-04 12:39:56 +0000645 if (Part->Can_Encrypt_Backup)
646 printf("Can_Encrypt_Backup ");
647 if (Part->Use_Userdata_Encryption)
648 printf("Use_Userdata_Encryption ");
Gary Peck004d48b2012-11-21 16:28:18 -0800649 if (Part->Has_Android_Secure)
650 printf("Has_Android_Secure ");
651 if (Part->Is_Storage)
652 printf("Is_Storage ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500653 if (Part->Is_Settings_Storage)
654 printf("Is_Settings_Storage ");
Dees_Troy68cab492012-12-12 19:29:35 +0000655 if (Part->Ignore_Blkid)
656 printf("Ignore_Blkid ");
Ethan Yonker253368a2014-11-25 15:00:52 -0600657 if (Part->Mount_To_Decrypt)
658 printf("Mount_To_Decrypt ");
Ethan Yonker96af84a2015-01-05 14:58:36 -0600659 if (Part->Can_Flash_Img)
660 printf("Can_Flash_Img ");
Ethan Yonker66a19492015-12-10 10:19:45 -0600661 if (Part->Is_Adopted_Storage)
662 printf("Is_Adopted_Storage ");
Ethan Yonker1b190162016-12-05 15:25:19 -0600663 if (Part->SlotSelect)
664 printf("SlotSelect ");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600665 if (Part->Mount_Read_Only)
666 printf("Mount_Read_Only ");
bigbiffcfa875c2021-06-20 16:20:27 -0400667 if (Part->Is_Super)
668 printf("Is_Super ");
Gary Peck004d48b2012-11-21 16:28:18 -0800669 printf("\n");
670 if (!Part->SubPartition_Of.empty())
671 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
672 if (!Part->Symlink_Path.empty())
673 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
674 if (!Part->Symlink_Mount_Point.empty())
675 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
676 if (!Part->Primary_Block_Device.empty())
677 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
678 if (!Part->Alternate_Block_Device.empty())
679 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
680 if (!Part->Decrypted_Block_Device.empty())
681 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
dianlujitao4879b372018-12-03 18:45:47 +0800682 if (!Part->Crypto_Key_Location.empty())
Ethan Yonker253368a2014-11-25 15:00:52 -0600683 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800684 if (Part->Length != 0)
685 printf(" Length: %i\n", Part->Length);
686 if (!Part->Display_Name.empty())
687 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500688 if (!Part->Storage_Name.empty())
689 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800690 if (!Part->Backup_Path.empty())
691 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
692 if (!Part->Backup_Name.empty())
693 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500694 if (!Part->Backup_Display_Name.empty())
695 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800696 if (!Part->Backup_FileName.empty())
697 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
698 if (!Part->Storage_Path.empty())
699 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
700 if (!Part->Current_File_System.empty())
701 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
702 if (!Part->Fstab_File_System.empty())
703 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
704 if (Part->Format_Block_Size != 0)
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500705 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
Dees_Troy094207a2012-09-26 12:00:39 -0400706 if (!Part->MTD_Name.empty())
707 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
Matt Mower029a82d2017-01-08 13:12:38 -0600708 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
Hashcode62bd9e02013-11-19 21:59:42 -0800709 if (Part->Mount_Flags || !Part->Mount_Options.empty())
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600710 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -0600711 if (Part->MTP_Storage_ID)
712 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
Ethan Yonker93382822018-11-01 15:25:31 -0500713 if (!Part->Key_Directory.empty())
714 printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
Ethan Yonker6277c792014-09-15 14:54:30 -0500715 printf("\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400716}
717
Dees_Troy51a0e822012-09-05 15:24:24 -0400718int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400719 std::vector<TWPartition*>::iterator iter;
720 int ret = false;
721 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400722 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400723
bigbiffd58ba182020-03-23 10:02:29 -0400724 if (Local_Path == "/tmp" || Local_Path == "/")
Dees_Troy43d8b002012-09-17 16:00:01 -0400725 return true;
726
Dees_Troy5bf43922012-09-07 16:07:55 -0400727 // Iterate through all partitions
728 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400729 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400730 ret = (*iter)->Mount(Display_Error);
731 found = true;
Dees_Troy51127312012-09-08 13:08:49 -0400732 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400733 (*iter)->Mount(Display_Error);
Dees_Troy51127312012-09-08 13:08:49 -0400734 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400735 }
736 if (found) {
737 return ret;
738 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500739 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 -0400740 }
741 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400742}
743
Dees_Troy51a0e822012-09-05 15:24:24 -0400744int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400745 std::vector<TWPartition*>::iterator iter;
746 int ret = false;
747 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400748 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy51127312012-09-08 13:08:49 -0400749
750 // Iterate through all partitions
751 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400752 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy51127312012-09-08 13:08:49 -0400753 ret = (*iter)->UnMount(Display_Error);
754 found = true;
755 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
756 (*iter)->UnMount(Display_Error);
757 }
758 }
759 if (found) {
760 return ret;
761 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500762 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 -0400763 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000764 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400765 }
766 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400767}
768
Dees_Troy51a0e822012-09-05 15:24:24 -0400769int TWPartitionManager::Is_Mounted_By_Path(string Path) {
Dees_Troy51127312012-09-08 13:08:49 -0400770 TWPartition* Part = Find_Partition_By_Path(Path);
771
772 if (Part)
773 return Part->Is_Mounted();
774 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000775 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400776 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400777}
778
Dees_Troy5bf43922012-09-07 16:07:55 -0400779int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400780 string current_storage_path = DataManager::GetCurrentStoragePath();
781
782 if (Mount_By_Path(current_storage_path, Display_Error)) {
783 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
784 if (FreeStorage)
785 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
786 return true;
787 }
788 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400789}
790
Dees_Troy5bf43922012-09-07 16:07:55 -0400791int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
792 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
793}
794
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600795TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400796 std::vector<TWPartition*>::iterator iter;
Dees_Troy38bd7602012-09-14 13:33:53 -0400797 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400798
dianlujitaob76a73a2020-04-30 20:33:20 +0800799 if (Local_Path == "/system")
800 Local_Path = Get_Android_Root_Path();
Dees_Troy5bf43922012-09-07 16:07:55 -0400801 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400802 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
Dees_Troy5bf43922012-09-07 16:07:55 -0400803 return (*iter);
804 }
Dees_Troy51a0e822012-09-05 15:24:24 -0400805 return NULL;
806}
807
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600808TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
809 std::vector<TWPartition*>::iterator iter;
810
811 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
812 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
813 return (*iter);
814 }
815 return NULL;
816}
817
Ethan Yonker53796e72019-01-11 22:49:52 -0600818int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400819 // Check the backup name to ensure that it is the correct size and contains only valid characters
820 // and that a backup with that name doesn't already exist
821 char backup_name[MAX_BACKUP_NAME_LEN];
822 char backup_loc[255], tw_image_dir[255];
823 int copy_size;
824 int index, cur_char;
Ethan Yonker53796e72019-01-11 22:49:52 -0600825 string Backup_Loc;
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400826
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400827 copy_size = Backup_Name.size();
828 // Check size
829 if (copy_size > MAX_BACKUP_NAME_LEN) {
830 if (Display_Error)
Ethan Yonker74db1572015-10-28 12:44:49 -0500831 gui_err("backup_name_len=Backup name is too long.");
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400832 return -2;
833 }
834
835 // Check each character
836 strncpy(backup_name, Backup_Name.c_str(), copy_size);
Dees_Troya13d74f2013-03-24 08:54:55 -0500837 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400838 return 0; // A "0" (zero) means to use the current timestamp for the backup name
839 for (index=0; index<copy_size; index++) {
840 cur_char = (int)backup_name[index];
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500841 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 -0400842 // These are valid characters
843 // Numbers
844 // Upper case letters
845 // Lower case letters
846 // Space
847 // and -_.{}[]
848 } else {
849 if (Display_Error)
Ethan Yonker4adc33e2016-01-22 16:07:11 -0600850 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 -0400851 return -3;
852 }
853 }
854
Ethan Yonker53796e72019-01-11 22:49:52 -0600855 if (Must_Be_Unique) {
856 // Check to make sure that a backup with this name doesn't already exist
857 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
858 strcpy(backup_loc, Backup_Loc.c_str());
859 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
860 if (TWFunc::Path_Exists(tw_image_dir)) {
861 if (Display_Error)
862 gui_err("backup_name_exists=A backup with that name already exists!");
bigbiffce8f83c2015-12-12 18:30:21 -0500863
Ethan Yonker53796e72019-01-11 22:49:52 -0600864 return -4;
865 }
866 // Backup is unique
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400867 }
Ethan Yonker53796e72019-01-11 22:49:52 -0600868 // No problems found
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400869 return 0;
870}
871
bigbiffce8f83c2015-12-12 18:30:21 -0500872bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400873 time_t start, stop;
Matt Mower23d8aae2017-01-06 14:30:33 -0600874 int use_compression;
bigbiffce8f83c2015-12-12 18:30:21 -0500875 string backup_log = part_settings->Backup_Folder + "/recovery.log";
Dees_Troy43d8b002012-09-17 16:00:01 -0400876
bigbiffce8f83c2015-12-12 18:30:21 -0500877 if (part_settings->Part == NULL)
Dees_Troy43d8b002012-09-17 16:00:01 -0400878 return true;
879
Dees_Troy093b7642012-09-21 15:59:38 -0400880 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -0400881
Tom Hite5a926722014-09-15 01:31:03 +0000882 TWFunc::SetPerformanceMode(true);
Dees_Troy43d8b002012-09-17 16:00:01 -0400883 time(&start);
884
bigbiffce8f83c2015-12-12 18:30:21 -0500885 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500886 sync();
887 sync();
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400888 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500889 if (!part_settings->adbbackup && part_settings->generate_digest) {
890 if (!twrpDigestDriver::Make_Digest(Full_Filename))
891 goto backup_error;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400892 }
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400893
bigbiffce8f83c2015-12-12 18:30:21 -0500894 if (part_settings->Part->Has_SubPartition) {
Dees_Troy8170a922012-09-18 15:40:25 -0400895 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400896 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -0400897
898 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400899 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500900 part_settings->Part = *subpart;
bigbiffce8f83c2015-12-12 18:30:21 -0500901 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500902 goto backup_error;
Tom Hite5a926722014-09-15 01:31:03 +0000903 }
Dees_Troy2727b992013-08-14 20:09:30 +0000904 sync();
905 sync();
bigbiff bigbifff5955b12019-05-18 17:28:58 -0400906 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400907 if (!part_settings->adbbackup && part_settings->generate_digest) {
908 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500909 goto backup_error;
bigbiffce8f83c2015-12-12 18:30:21 -0500910 }
Tom Hite5a926722014-09-15 01:31:03 +0000911 }
Dees_Troy8170a922012-09-18 15:40:25 -0400912 }
913 }
914 }
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400915
Dees_Troy43d8b002012-09-17 16:00:01 -0400916 time(&stop);
that203bcc92015-05-09 17:27:33 +0200917 int backup_time = (int) difftime(stop, start);
Dees_Troy2673cec2013-04-02 20:22:16 +0000918 LOGINFO("Partition Backup time: %d\n", backup_time);
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400919
bigbiffce8f83c2015-12-12 18:30:21 -0500920 if (part_settings->Part->Backup_Method == BM_FILES) {
921 part_settings->file_time += backup_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400922 } else {
bigbiffce8f83c2015-12-12 18:30:21 -0500923 part_settings->img_time += backup_time;
924
Dees_Troy43d8b002012-09-17 16:00:01 -0400925 }
Tom Hite5a926722014-09-15 01:31:03 +0000926
Matt Mower02899552016-12-30 18:13:51 -0600927 TWFunc::SetPerformanceMode(false);
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500928 return true;
Dees_Troy43d8b002012-09-17 16:00:01 -0400929 }
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500930backup_error:
931 Clean_Backup_Folder(part_settings->Backup_Folder);
932 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
933 tw_set_default_metadata(backup_log.c_str());
934 TWFunc::SetPerformanceMode(false);
935 return false;
bigbiff7abc5fe2015-01-17 16:53:12 -0500936}
937
bigbiffbf1d6722015-02-14 16:25:59 -0500938void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
939 DIR *d = opendir(Backup_Folder.c_str());
940 struct dirent *p;
941 int r;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400942 vector<string> ext;
943
944 //extensions we should delete when cleaning
945 ext.push_back("win");
946 ext.push_back("md5");
947 ext.push_back("sha2");
948 ext.push_back("info");
bigbiffbf1d6722015-02-14 16:25:59 -0500949
Ethan Yonker74db1572015-10-28 12:44:49 -0500950 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
bigbiffbf1d6722015-02-14 16:25:59 -0500951
952 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500953 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
bigbiffbf1d6722015-02-14 16:25:59 -0500954 return;
955 }
956
Matt Mower2b18a532015-02-20 16:58:05 -0600957 while ((p = readdir(d))) {
bigbiffbf1d6722015-02-14 16:25:59 -0500958 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
959 continue;
960
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500961 string path = Backup_Folder + "/" + p->d_name;
bigbiffbf1d6722015-02-14 16:25:59 -0500962
963 size_t dot = path.find_last_of(".") + 1;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400964 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
965 if (path.substr(dot) == *i) {
966 r = unlink(path.c_str());
967 if (r != 0)
968 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
bigbiffbf1d6722015-02-14 16:25:59 -0500969 }
970 }
971 }
972 closedir(d);
973}
974
Ethan Yonker472f5062016-02-25 13:47:30 -0600975int TWPartitionManager::Check_Backup_Cancel() {
976 return stop_backup.get_value();
977}
978
bigbiff7abc5fe2015-01-17 16:53:12 -0500979int TWPartitionManager::Cancel_Backup() {
980 string Backup_Folder, Backup_Name, Full_Backup_Path;
981
982 stop_backup.set_value(1);
983
984 if (tar_fork_pid != 0) {
985 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
986 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500987 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
bigbiff7abc5fe2015-01-17 16:53:12 -0500988 LOGINFO("Killing pid: %d\n", tar_fork_pid);
989 kill(tar_fork_pid, SIGUSR2);
990 while (kill(tar_fork_pid, 0) == 0) {
991 usleep(1000);
992 }
993 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
994 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
995 TWFunc::removeDir(Full_Backup_Path, false);
996 tar_fork_pid = 0;
997 }
998
999 return 0;
Dees_Troy43d8b002012-09-17 16:00:01 -04001000}
1001
bigbiffce8f83c2015-12-12 18:30:21 -05001002int TWPartitionManager::Run_Backup(bool adbbackup) {
1003 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001004 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
bigbiffce8f83c2015-12-12 18:30:21 -05001005 string Backup_Name, Backup_List, backup_path;
Matt Mower23d8aae2017-01-06 14:30:33 -06001006 unsigned long long total_bytes = 0, free_space = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -04001007 TWPartition* storage = NULL;
1008 struct tm *t;
Matt Mower23d8aae2017-01-06 14:30:33 -06001009 time_t seconds, total_start, total_stop;
Dees_Troya13d74f2013-03-24 08:54:55 -05001010 size_t start_pos = 0, end_pos = 0;
bigbiff7abc5fe2015-01-17 16:53:12 -05001011 stop_backup.set_value(0);
Dees_Troy43d8b002012-09-17 16:00:01 -04001012 seconds = time(0);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001013 t = localtime(&seconds);
Dees_Troy43d8b002012-09-17 16:00:01 -04001014
bigbiffce8f83c2015-12-12 18:30:21 -05001015 part_settings.img_bytes_remaining = 0;
1016 part_settings.file_bytes_remaining = 0;
1017 part_settings.img_time = 0;
1018 part_settings.file_time = 0;
1019 part_settings.img_bytes = 0;
1020 part_settings.file_bytes = 0;
1021 part_settings.PM_Method = PM_BACKUP;
1022
bigbiffce8f83c2015-12-12 18:30:21 -05001023 part_settings.adbbackup = adbbackup;
Dees_Troy43d8b002012-09-17 16:00:01 -04001024 time(&total_start);
1025
1026 Update_System_Details();
1027
1028 if (!Mount_Current_Storage(true))
1029 return false;
1030
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001031 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
1032 if (skip_digest == 0)
1033 part_settings.generate_digest = true;
Dees_Troyc5865ab2012-09-24 15:08:04 -04001034 else
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001035 part_settings.generate_digest = false;
Dees_Troy4a2a1262012-09-18 09:33:47 -04001036
bigbiffce8f83c2015-12-12 18:30:21 -05001037 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001038 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
1039 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
1040 Backup_Name = TWFunc::Get_Current_Date();
1041 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
Dees Troyb21cc642013-09-10 17:36:41 +00001042 TWFunc::Auto_Generate_Backup_Name();
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001043 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
Dees_Troy43d8b002012-09-17 16:00:01 -04001044 }
bigbiffce8f83c2015-12-12 18:30:21 -05001045
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001046 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001047 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001048
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001049 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -04001050
Dees_Troy2673cec2013-04-02 20:22:16 +00001051 LOGINFO("Calculating backup details...\n");
Dees_Troya13d74f2013-03-24 08:54:55 -05001052 DataManager::GetValue("tw_backup_list", Backup_List);
bigbiff7ba75002020-04-11 20:47:09 -04001053 LOGINFO("Backup_List: %s\n", Backup_List.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05001054 if (!Backup_List.empty()) {
1055 end_pos = Backup_List.find(";", start_pos);
1056 while (end_pos != string::npos && start_pos < Backup_List.size()) {
1057 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiff7ba75002020-04-11 20:47:09 -04001058 LOGINFO("backup_path: %s\n", backup_path.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001059 part_settings.Part = Find_Partition_By_Path(backup_path);
1060 if (part_settings.Part != NULL) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001061 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001062 if (part_settings.Part->Backup_Method == BM_FILES)
1063 part_settings.file_bytes += part_settings.Part->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001064 else
bigbiffce8f83c2015-12-12 18:30:21 -05001065 part_settings.img_bytes += part_settings.Part->Backup_Size;
1066 if (part_settings.Part->Has_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001067 std::vector<TWPartition*>::iterator subpart;
1068
1069 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiffce8f83c2015-12-12 18:30:21 -05001070 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 -05001071 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001072 if ((*subpart)->Backup_Method == BM_FILES)
1073 part_settings.file_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001074 else
bigbiffce8f83c2015-12-12 18:30:21 -05001075 part_settings.img_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001076 }
1077 }
Dees_Troy8170a922012-09-18 15:40:25 -04001078 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001079 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001080 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 -04001081 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001082 start_pos = end_pos + 1;
1083 end_pos = Backup_List.find(";", start_pos);
Dees_Troy43d8b002012-09-17 16:00:01 -04001084 }
1085 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001086
1087 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001088 gui_msg("no_partition_selected=No partitions selected for backup.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001089 return false;
1090 }
bigbiffce8f83c2015-12-12 18:30:21 -05001091 if (adbbackup) {
1092 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
1093 return false;
1094 }
1095 }
1096 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
Ethan Yonker472f5062016-02-25 13:47:30 -06001097 ProgressTracking progress(total_bytes);
bigbiffce8f83c2015-12-12 18:30:21 -05001098 part_settings.progress = &progress;
1099
Ethan Yonker74db1572015-10-28 12:44:49 -05001100 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
1101 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001102 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1103 if (storage != NULL) {
1104 free_space = storage->Free;
Ethan Yonker74db1572015-10-28 12:44:49 -05001105 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001106 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001107 gui_err("unable_locate_storage=Unable to locate storage device.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001108 return false;
1109 }
bigbiffbf1d6722015-02-14 16:25:59 -05001110
Matt Mowerbfccfb82016-04-25 23:22:31 -05001111 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
bigbiffce8f83c2015-12-12 18:30:21 -05001112
1113 if (adbbackup)
1114 disable_free_space_check = true;
1115
bigbiffbf1d6722015-02-14 16:25:59 -05001116 if (!disable_free_space_check) {
1117 if (free_space - (32 * 1024 * 1024) < total_bytes) {
1118 // We require an extra 32MB just in case
Ethan Yonker74db1572015-10-28 12:44:49 -05001119 gui_err("no_space=Not enough free space on storage.");
bigbiffbf1d6722015-02-14 16:25:59 -05001120 return false;
1121 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001122 }
bigbiffce8f83c2015-12-12 18:30:21 -05001123 part_settings.img_bytes_remaining = part_settings.img_bytes;
1124 part_settings.file_bytes_remaining = part_settings.file_bytes;
Dees_Troy43d8b002012-09-17 16:00:01 -04001125
Ethan Yonker74db1572015-10-28 12:44:49 -05001126 gui_msg("backup_started=[BACKUP STARTED]");
bigbiff bigbiffcdd97c72019-03-29 19:12:33 -04001127
1128 int is_decrypted = 0;
1129 int is_encrypted = 0;
1130
1131 DataManager::GetValue(TW_IS_DECRYPTED, is_decrypted);
1132 DataManager::GetValue(TW_IS_ENCRYPTED, is_encrypted);
1133 if (!adbbackup || (!is_encrypted || (is_encrypted && is_decrypted))) {
1134 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
1135 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
1136 gui_err("fail_backup_folder=Failed to make backup folder.");
1137 return false;
1138 }
Dees_Troyd4b22b02013-01-18 17:17:58 +00001139 }
1140
Dees_Troy2673cec2013-04-02 20:22:16 +00001141 DataManager::SetProgress(0.0);
Dees_Troy093b7642012-09-21 15:59:38 -04001142
Dees_Troya13d74f2013-03-24 08:54:55 -05001143 start_pos = 0;
1144 end_pos = Backup_List.find(";", start_pos);
1145 while (end_pos != string::npos && start_pos < Backup_List.size()) {
bigbiff7abc5fe2015-01-17 16:53:12 -05001146 if (stop_backup.get_value() != 0)
1147 return -1;
Dees_Troya13d74f2013-03-24 08:54:55 -05001148 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001149 part_settings.Part = Find_Partition_By_Path(backup_path);
1150 if (part_settings.Part != NULL) {
1151 if (!Backup_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001152 return false;
1153 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001154 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 -05001155 }
1156 start_pos = end_pos + 1;
1157 end_pos = Backup_List.find(";", start_pos);
1158 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001159
1160 // Average BPS
bigbiffce8f83c2015-12-12 18:30:21 -05001161 if (part_settings.img_time == 0)
1162 part_settings.img_time = 1;
1163 if (part_settings.file_time == 0)
1164 part_settings.file_time = 1;
1165 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
1166 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
Dees_Troy43d8b002012-09-17 16:00:01 -04001167
bigbiffce8f83c2015-12-12 18:30:21 -05001168 if (part_settings.file_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001169 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 -05001170 if (part_settings.img_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001171 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 -04001172
1173 time(&total_stop);
1174 int total_time = (int) difftime(total_stop, total_start);
bigbiffce8f83c2015-12-12 18:30:21 -05001175
1176 uint64_t actual_backup_size;
Ethan Yonker3fdcda42016-11-30 12:29:37 -06001177 if (!adbbackup) {
1178 TWExclude twe;
1179 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
1180 } else
bigbiffce8f83c2015-12-12 18:30:21 -05001181 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001182 actual_backup_size /= (1024LLU * 1024LLU);
Dees_Troy43d8b002012-09-17 16:00:01 -04001183
bigbiffce8f83c2015-12-12 18:30:21 -05001184 int prev_img_bps = 0, use_compression = 0;
1185 unsigned long long prev_file_bps = 0;
Matt Mower173cdb92016-12-31 02:49:19 -06001186 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001187 img_bps += (prev_img_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001188 img_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001189
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001190 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -04001191 if (use_compression)
1192 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001193 else
Dees_Troy093b7642012-09-21 15:59:38 -04001194 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
1195 file_bps += (prev_file_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001196 file_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001197
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001198 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001199 if (use_compression)
1200 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
1201 else
1202 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
1203
Ethan Yonker74db1572015-10-28 12:44:49 -05001204 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Dees_Troy43d8b002012-09-17 16:00:01 -04001205 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001206 UnMount_Main_Partitions();
Ethan Yonker56db1c42015-12-20 22:49:00 -06001207 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001208 string backup_log = part_settings.Backup_Folder + "/recovery.log";
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001209 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -06001210 tw_set_default_metadata(backup_log.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001211
1212 if (part_settings.adbbackup) {
1213 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
1214 return false;
1215 }
1216 }
1217 part_settings.adbbackup = false;
1218 DataManager::SetValue("tw_enable_adb_backup", 0);
1219
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001220 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001221}
1222
bigbiffce8f83c2015-12-12 18:30:21 -05001223bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
Dees_Troy4a2a1262012-09-18 09:33:47 -04001224 time_t Start, Stop;
bigbiffce8f83c2015-12-12 18:30:21 -05001225
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001226 if (part_settings->adbbackup) {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001227 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
1228 LOGINFO("setting backup name: %s\n", partName.c_str());
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001229 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
1230 }
1231
Tom Hite5a926722014-09-15 01:31:03 +00001232 TWFunc::SetPerformanceMode(true);
bigbiffce8f83c2015-12-12 18:30:21 -05001233
Dees_Troy4a2a1262012-09-18 09:33:47 -04001234 time(&Start);
Ethan Yonker472f5062016-02-25 13:47:30 -06001235
bigbiffce8f83c2015-12-12 18:30:21 -05001236 if (!part_settings->Part->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001237 TWFunc::SetPerformanceMode(false);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001238 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001239 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001240 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
Dees_Troy8170a922012-09-18 15:40:25 -04001241 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001242 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -04001243
1244 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001245 part_settings->Part = *subpart;
1246 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1247 part_settings->Part = (*subpart);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001248 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
bigbiffce8f83c2015-12-12 18:30:21 -05001249 if (!(*subpart)->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001250 TWFunc::SetPerformanceMode(false);
Dees_Troy8170a922012-09-18 15:40:25 -04001251 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001252 }
Dees_Troy8170a922012-09-18 15:40:25 -04001253 }
1254 }
1255 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001256 time(&Stop);
Tom Hite5a926722014-09-15 01:31:03 +00001257 TWFunc::SetPerformanceMode(false);
bigbiffce8f83c2015-12-12 18:30:21 -05001258 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1259
Dees_Troy4a2a1262012-09-18 09:33:47 -04001260 return true;
1261}
1262
Ethan Yonker472f5062016-02-25 13:47:30 -06001263int TWPartitionManager::Run_Restore(const string& Restore_Name) {
bigbiffce8f83c2015-12-12 18:30:21 -05001264 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001265 int check_digest;
bigbiffce8f83c2015-12-12 18:30:21 -05001266
Dees_Troy4a2a1262012-09-18 09:33:47 -04001267 time_t rStart, rStop;
1268 time(&rStart);
Dees_Troya13d74f2013-03-24 08:54:55 -05001269 string Restore_List, restore_path;
1270 size_t start_pos = 0, end_pos;
bigbiffce8f83c2015-12-12 18:30:21 -05001271
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001272 part_settings.Backup_Folder = Restore_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001273 part_settings.Part = NULL;
1274 part_settings.partition_count = 0;
1275 part_settings.total_restore_size = 0;
1276 part_settings.adbbackup = false;
1277 part_settings.PM_Method = PM_RESTORE;
Dees_Troy43d8b002012-09-17 16:00:01 -04001278
Ethan Yonker74db1572015-10-28 12:44:49 -05001279 gui_msg("restore_started=[RESTORE STARTED]");
1280 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
Dees_Troy43d8b002012-09-17 16:00:01 -04001281
Dees_Troy4a2a1262012-09-18 09:33:47 -04001282 if (!Mount_Current_Storage(true))
1283 return false;
1284
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001285 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1286 if (check_digest > 0) {
1287 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1288 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1289 gui_msg("verifying_digest=Verifying Digest");
Dees_Troya13d74f2013-03-24 08:54:55 -05001290 } else {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001291 gui_msg("skip_digest=Skipping Digest check based on user setting.");
Dees_Troya13d74f2013-03-24 08:54:55 -05001292 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001293 gui_msg("calc_restore=Calculating restore details...");
Dees_Troya13d74f2013-03-24 08:54:55 -05001294 DataManager::GetValue("tw_restore_selected", Restore_List);
bigbiffce8f83c2015-12-12 18:30:21 -05001295
Dees_Troya13d74f2013-03-24 08:54:55 -05001296 if (!Restore_List.empty()) {
1297 end_pos = Restore_List.find(";", start_pos);
1298 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1299 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001300 part_settings.Part = Find_Partition_By_Path(restore_path);
1301 if (part_settings.Part != NULL) {
bigbiffce8f83c2015-12-12 18:30:21 -05001302 if (part_settings.Part->Mount_Read_Only) {
1303 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 -05001304 return false;
1305 }
bigbiffce8f83c2015-12-12 18:30:21 -05001306
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001307 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1308
bigbiff4a60bee2021-01-23 14:08:03 -05001309 if (tw_get_default_metadata(Get_Android_Root_Path().c_str()) != 0) {
1310 gui_msg(Msg(msg::kWarning, "restore_system_context=Unable to get default context for {1} -- Android may not boot.")(Get_Android_Root_Path()));
1311 }
1312
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001313 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001314 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001315 part_settings.partition_count++;
1316 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1317 if (part_settings.Part->Has_SubPartition) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001318 TWPartition *parentPart = part_settings.Part;
Dees_Troya13d74f2013-03-24 08:54:55 -05001319 std::vector<TWPartition*>::iterator subpart;
1320
1321 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001322 part_settings.Part = *subpart;
1323 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001324 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001325 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001326 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
Dees_Troya13d74f2013-03-24 08:54:55 -05001327 }
1328 }
1329 }
1330 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001331 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001332 }
1333 start_pos = end_pos + 1;
1334 end_pos = Restore_List.find(";", start_pos);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001335 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001336 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001337
bigbiffce8f83c2015-12-12 18:30:21 -05001338 if (part_settings.partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001339 gui_err("no_part_restore=No partitions selected for restore.");
Dees_Troy4a2a1262012-09-18 09:33:47 -04001340 return false;
1341 }
1342
bigbiffce8f83c2015-12-12 18:30:21 -05001343 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1344 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 +00001345 DataManager::SetProgress(0.0);
bigbiffce8f83c2015-12-12 18:30:21 -05001346 ProgressTracking progress(part_settings.total_restore_size);
1347 part_settings.progress = &progress;
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001348
Dees_Troya13d74f2013-03-24 08:54:55 -05001349 start_pos = 0;
1350 if (!Restore_List.empty()) {
1351 end_pos = Restore_List.find(";", start_pos);
1352 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1353 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001354
1355 part_settings.Part = Find_Partition_By_Path(restore_path);
1356 if (part_settings.Part != NULL) {
1357 part_settings.partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001358 if (!Restore_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001359 return false;
1360 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001361 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001362 }
1363 start_pos = end_pos + 1;
1364 end_pos = Restore_List.find(";", start_pos);
1365 }
1366 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001367 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
bigbiff4a60bee2021-01-23 14:08:03 -05001368 tw_set_default_metadata(Get_Android_Root_Path().c_str());
Captain Throwback9d6feb52018-07-27 10:05:24 -04001369 UnMount_By_Path(Get_Android_Root_Path(), false);
Dees_Troy43d8b002012-09-17 16:00:01 -04001370 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001371 UnMount_Main_Partitions();
Dees_Troy4a2a1262012-09-18 09:33:47 -04001372 time(&rStop);
Matt Mower3c366972015-12-25 19:28:31 -06001373 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
bigbiff8f5fad32021-11-03 20:39:02 -04001374 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
1375 if (Decrypt_Data && Decrypt_Data->Is_Encrypted)
1376 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 -05001377 DataManager::SetValue("tw_file_progress", "");
bigbiffce8f83c2015-12-12 18:30:21 -05001378
Dees_Troy63c8df72012-09-10 14:02:05 -04001379 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001380}
1381
1382void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001383 // Start with the default values
Dees_Troya13d74f2013-03-24 08:54:55 -05001384 string Restore_List;
Dees_Troy83bd4832013-05-04 12:39:56 +00001385 bool get_date = true, check_encryption = true;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001386 bool adbbackup = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001387
1388 DataManager::SetValue("tw_restore_encrypted", 0);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001389 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1390 vector<string> adb_files;
1391 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1392 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1393 string adb_restore_file = adb_files.at(i);
1394 std::size_t pos = adb_restore_file.find_first_of(".");
1395 std::string path = "/" + adb_restore_file.substr(0, pos);
1396 Restore_List = path + ";";
1397 TWPartition* Part = Find_Partition_By_Path(path);
1398 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1399 adbbackup = true;
1400 }
1401 DataManager::SetValue("tw_enable_adb_backup", 1);
Dees_Troy63c8df72012-09-10 14:02:05 -04001402 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001403 else {
1404 DIR* d;
1405 d = opendir(Restore_Name.c_str());
1406 if (d == NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001407 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001408 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1409 return;
Dees_Troy63c8df72012-09-10 14:02:05 -04001410 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001411
1412 struct dirent* de;
1413 while ((de = readdir(d)) != NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001414 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001415 // Strip off three components
1416 char str[256];
1417 char* label;
1418 char* fstype = NULL;
1419 char* extn = NULL;
1420 char* ptr;
Dees_Troy63c8df72012-09-10 14:02:05 -04001421
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001422 strcpy(str, de->d_name);
1423 if (strlen(str) <= 2)
1424 continue;
Dees_Troy83bd4832013-05-04 12:39:56 +00001425
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001426 if (get_date) {
1427 char file_path[255];
1428 struct stat st;
1429
1430 strcpy(file_path, Restore_Name.c_str());
1431 strcat(file_path, "/");
1432 strcat(file_path, str);
1433 stat(file_path, &st);
1434 string backup_date = ctime((const time_t*)(&st.st_mtime));
1435 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1436 get_date = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001437 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001438
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001439 label = str;
1440 ptr = label;
1441 while (*ptr && *ptr != '.') ptr++;
1442 if (*ptr == '.')
1443 {
1444 *ptr = 0x00;
1445 ptr++;
1446 fstype = ptr;
1447 }
1448 while (*ptr && *ptr != '.') ptr++;
1449 if (*ptr == '.')
1450 {
1451 *ptr = 0x00;
1452 ptr++;
1453 extn = ptr;
1454 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001455
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001456 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1457 int extnlength = strlen(extn);
1458 if (extnlength != 3 && extnlength != 6) continue;
1459 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1460 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
Dees_Troy63c8df72012-09-10 14:02:05 -04001461
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001462 if (check_encryption) {
1463 string filename = Restore_Name + "/";
1464 filename += de->d_name;
1465 if (TWFunc::Get_File_Type(filename) == 2) {
1466 LOGINFO("'%s' is encrypted\n", filename.c_str());
1467 DataManager::SetValue("tw_restore_encrypted", 1);
1468 }
1469 }
1470 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1471
1472 TWPartition* Part = Find_Partition_By_Path(label);
1473 if (Part == NULL)
1474 {
1475 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1476 continue;
1477 }
1478
1479 Part->Backup_FileName = de->d_name;
1480 if (strlen(extn) > 3) {
1481 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1482 }
1483
dianlujitaob76a73a2020-04-30 20:33:20 +08001484 if (!Part->Is_SubPartition) {
1485 if (Part->Backup_Path == Get_Android_Root_Path())
1486 Restore_List += "/system;";
1487 else
1488 Restore_List += Part->Backup_Path + ";";
1489 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001490 }
1491 closedir(d);
Dees_Troy63c8df72012-09-10 14:02:05 -04001492 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001493
1494 if (adbbackup) {
1495 Restore_List = "ADB_Backup;";
1496 adbbackup = false;
1497 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001498
Dees_Troya13d74f2013-03-24 08:54:55 -05001499 // Set the final value
1500 DataManager::SetValue("tw_restore_list", Restore_List);
1501 DataManager::SetValue("tw_restore_selected", Restore_List);
Dees_Troy51a0e822012-09-05 15:24:24 -04001502 return;
1503}
1504
1505int TWPartitionManager::Wipe_By_Path(string Path) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001506 std::vector<TWPartition*>::iterator iter;
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301507 std::vector < TWPartition * >::iterator iter1;
Dees_Troy63c8df72012-09-10 14:02:05 -04001508 int ret = false;
1509 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -04001510 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy63c8df72012-09-10 14:02:05 -04001511
dianlujitaob76a73a2020-04-30 20:33:20 +08001512 if (Local_Path == "/system")
1513 Local_Path = Get_Android_Root_Path();
bigbiffaed1bdf2021-08-03 18:21:39 -04001514 if (Path == "/cache") {
1515 TWPartition* cache = Find_Partition_By_Path("/cache");
1516 if (cache == nullptr) {
1517 TWPartition* dat = Find_Partition_By_Path("/data");
1518 if (dat) {
1519 dat->Wipe_Data_Cache();
1520 found = true;
1521 }
1522 }
1523 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001524 // Iterate through all partitions
1525 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -04001526 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301527 // iterate through all partitions since some legacy devices uses other partitions as vendor causes issues while wiping
1528 (*iter)->Find_Actual_Block_Device();
1529 for (iter1 = Partitions.begin (); iter1 != Partitions.end (); iter1++)
1530 {
1531 (*iter1)->Find_Actual_Block_Device();
1532 if ((*iter)->Actual_Block_Device == (*iter1)->Actual_Block_Device && (*iter)->Mount_Point != (*iter1)->Mount_Point)
1533 (*iter1)->UnMount(false);
1534 }
Dees_Troye58d5262012-09-21 12:27:57 -04001535 if (Path == "/and-sec")
1536 ret = (*iter)->Wipe_AndSec();
1537 else
1538 ret = (*iter)->Wipe();
Dees_Troy63c8df72012-09-10 14:02:05 -04001539 found = true;
1540 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1541 (*iter)->Wipe();
1542 }
1543 }
1544 if (found) {
1545 return ret;
1546 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001547 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 -04001548 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -04001549}
1550
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001551int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1552 std::vector<TWPartition*>::iterator iter;
1553 int ret = false;
1554 bool found = false;
1555 string Local_Path = TWFunc::Get_Root_Path(Path);
1556
1557 // Iterate through all partitions
1558 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1559 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1560 if (Path == "/and-sec")
1561 ret = (*iter)->Wipe_AndSec();
1562 else
1563 ret = (*iter)->Wipe(New_File_System);
1564 found = true;
1565 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1566 (*iter)->Wipe(New_File_System);
1567 }
1568 }
1569 if (found) {
1570 return ret;
1571 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001572 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 -05001573 return false;
1574}
1575
Dees_Troy51a0e822012-09-05 15:24:24 -04001576int TWPartitionManager::Factory_Reset(void) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001577 std::vector<TWPartition*>::iterator iter;
1578 int ret = true;
1579
1580 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001581 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
Ethan Yonker89583ef2015-08-26 09:01:59 -05001582#ifdef TW_OEM_BUILD
1583 if ((*iter)->Mount_Point == "/data") {
1584 if (!(*iter)->Wipe_Encryption())
1585 ret = false;
1586 } else {
1587#endif
1588 if (!(*iter)->Wipe())
1589 ret = false;
1590#ifdef TW_OEM_BUILD
1591 }
1592#endif
Dees_Troy094207a2012-09-26 12:00:39 -04001593 } else if ((*iter)->Has_Android_Secure) {
1594 if (!(*iter)->Wipe_AndSec())
1595 ret = false;
Dees_Troy63c8df72012-09-10 14:02:05 -04001596 }
1597 }
bigbiffad58e1b2020-07-06 20:24:34 -04001598 TWFunc::check_and_run_script("/system/bin/factoryreset.sh", "Factory Reset Script");
Dees_Troy63c8df72012-09-10 14:02:05 -04001599 return ret;
Dees_Troy51a0e822012-09-05 15:24:24 -04001600}
1601
Dees_Troy38bd7602012-09-14 13:33:53 -04001602int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1603 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001604 vector <string> dir;
Dees_Troy38bd7602012-09-14 13:33:53 -04001605
1606 if (!Mount_By_Path("/data", true))
1607 return false;
1608
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001609 dir.push_back("/data/dalvik-cache");
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001610
bigbiff25d25b92020-06-19 16:07:38 -04001611 std::string cacheDir = TWFunc::get_log_dir();
1612 if (cacheDir == CACHE_LOGS_DIR) {
1613 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
1614 LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001615 }
1616 dir.push_back(cacheDir + "dalvik-cache");
1617 dir.push_back(cacheDir + "/dc");
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001618 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001619
Dees_Troy38bd7602012-09-14 13:33:53 -04001620 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001621 if (sdext && sdext->Is_Present && sdext->Mount(false))
1622 {
1623 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1624 {
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001625 dir.push_back("/sd-ext/dalvik-cache");
1626 }
1627 }
1628
bigbiff25d25b92020-06-19 16:07:38 -04001629 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001630 gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
1631 } else {
1632 gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
1633 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001634 for (unsigned i = 0; i < dir.size(); ++i) {
1635 if (stat(dir.at(i).c_str(), &st) == 0) {
1636 TWFunc::removeDir(dir.at(i), false);
1637 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001638 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001639 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001640
bigbiff25d25b92020-06-19 16:07:38 -04001641 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001642 gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1643 } else {
1644 gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
1645 }
1646
Dees_Troy38bd7602012-09-14 13:33:53 -04001647 return true;
1648}
1649
1650int TWPartitionManager::Wipe_Rotate_Data(void) {
1651 if (!Mount_By_Path("/data", true))
1652 return false;
1653
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001654 unlink("/data/misc/akmd*");
1655 unlink("/data/misc/rild*");
Dees_Troy2673cec2013-04-02 20:22:16 +00001656 gui_print("Rotation data wiped.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001657 return true;
1658}
1659
1660int TWPartitionManager::Wipe_Battery_Stats(void) {
1661 struct stat st;
1662
1663 if (!Mount_By_Path("/data", true))
1664 return false;
1665
1666 if (0 != stat("/data/system/batterystats.bin", &st)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001667 gui_print("No Battery Stats Found. No Need To Wipe.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001668 } else {
1669 remove("/data/system/batterystats.bin");
Dees_Troy2673cec2013-04-02 20:22:16 +00001670 gui_print("Cleared battery stats.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001671 }
1672 return true;
1673}
1674
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001675int TWPartitionManager::Wipe_Android_Secure(void) {
1676 std::vector<TWPartition*>::iterator iter;
1677 int ret = false;
1678 bool found = false;
1679
1680 // Iterate through all partitions
1681 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1682 if ((*iter)->Has_Android_Secure) {
1683 ret = (*iter)->Wipe_AndSec();
1684 found = true;
1685 }
1686 }
1687 if (found) {
1688 return ret;
1689 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001690 gui_err("no_andsec=No android secure partitions found.");
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001691 }
1692 return false;
1693}
1694
Dees_Troy38bd7602012-09-14 13:33:53 -04001695int TWPartitionManager::Format_Data(void) {
1696 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffcfa875c2021-06-20 16:20:27 -04001697 TWPartition* metadata = Find_Partition_By_Path("/metadata");
1698 if (metadata != NULL)
1699 metadata->UnMount(false);
Dees_Troy38bd7602012-09-14 13:33:53 -04001700
1701 if (dat != NULL) {
bigbiffab76bd72021-10-11 10:17:48 -04001702 if (android::base::GetBoolProperty("ro.virtual_ab.enabled", false)) {
bigbiffcfa875c2021-06-20 16:20:27 -04001703#ifndef TW_EXCLUDE_APEX
1704 twrpApex apex;
1705 apex.Unmount();
1706#endif
1707 if (metadata != NULL)
1708 metadata->Mount(true);
bigbiffd21252f2021-09-18 15:56:32 -04001709 if (!Check_Pending_Merges())
bigbiffcfa875c2021-06-20 16:20:27 -04001710 return false;
1711 }
Dees_Troy38bd7602012-09-14 13:33:53 -04001712 return dat->Wipe_Encryption();
1713 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001714 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001715 return false;
1716 }
1717 return false;
1718}
1719
1720int TWPartitionManager::Wipe_Media_From_Data(void) {
1721 TWPartition* dat = Find_Partition_By_Path("/data");
1722
1723 if (dat != NULL) {
1724 if (!dat->Has_Data_Media) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001725 LOGERR("This device does not have /data/media\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001726 return false;
1727 }
1728 if (!dat->Mount(true))
1729 return false;
1730
Ethan Yonker74db1572015-10-28 12:44:49 -05001731 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
Ethan Yonker726a0202014-12-16 20:01:38 -06001732 Remove_MTP_Storage(dat->MTP_Storage_ID);
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001733 TWFunc::removeDir("/data/media", false);
xiaolu9416f4f2015-06-04 08:22:23 +08001734 dat->Recreate_Media_Folder();
Ethan Yonker726a0202014-12-16 20:01:38 -06001735 Add_MTP_Storage(dat->MTP_Storage_ID);
Dees_Troy38bd7602012-09-14 13:33:53 -04001736 return true;
1737 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001738 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001739 return false;
1740 }
1741 return false;
1742}
1743
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001744int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1745 std::vector<TWPartition*>::iterator iter;
1746 int ret = false;
1747 bool found = false;
1748 string Local_Path = TWFunc::Get_Root_Path(Path);
1749
1750 if (Local_Path == "/tmp" || Local_Path == "/")
1751 return true;
1752
1753 // Iterate through all partitions
1754 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1755 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1756 ret = (*iter)->Repair();
1757 found = true;
1758 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1759 (*iter)->Repair();
1760 }
1761 }
1762 if (found) {
1763 return ret;
1764 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001765 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 -05001766 } else {
1767 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1768 }
1769 return false;
1770}
1771
Ethan Yonkera2719152015-05-28 09:44:41 -05001772int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1773 std::vector<TWPartition*>::iterator iter;
1774 int ret = false;
1775 bool found = false;
1776 string Local_Path = TWFunc::Get_Root_Path(Path);
1777
1778 if (Local_Path == "/tmp" || Local_Path == "/")
1779 return true;
1780
1781 // Iterate through all partitions
1782 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1783 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1784 ret = (*iter)->Resize();
1785 found = true;
1786 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1787 (*iter)->Resize();
1788 }
1789 }
1790 if (found) {
1791 return ret;
1792 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001793 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 -05001794 } else {
1795 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1796 }
1797 return false;
1798}
1799
Dees_Troy51a0e822012-09-05 15:24:24 -04001800void TWPartitionManager::Update_System_Details(void) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001801 std::vector<TWPartition*>::iterator iter;
Dees_Troy51127312012-09-08 13:08:49 -04001802 int data_size = 0;
Dees_Troy5bf43922012-09-07 16:07:55 -04001803
Ethan Yonker74db1572015-10-28 12:44:49 -05001804 gui_msg("update_part_details=Updating partition details...");
Dees_Troy5bf43922012-09-07 16:07:55 -04001805 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker1b190162016-12-05 15:25:19 -06001806 (*iter)->Update_Size(true);
Dees_Troy51127312012-09-08 13:08:49 -04001807 if ((*iter)->Can_Be_Mounted) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001808 if ((*iter)->Mount_Point == Get_Android_Root_Path()) {
Dees_Troy51127312012-09-08 13:08:49 -04001809 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1810 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001811 TWFunc::Is_TWRP_App_In_System();
Dees_Troy51127312012-09-08 13:08:49 -04001812 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1813 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1814 } else if ((*iter)->Mount_Point == "/cache") {
1815 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1816 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1817 } else if ((*iter)->Mount_Point == "/sd-ext") {
1818 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1819 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1820 if ((*iter)->Backup_Size == 0) {
1821 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1822 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1823 } else
1824 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
Dees_Troye58d5262012-09-21 12:27:57 -04001825 } else if ((*iter)->Has_Android_Secure) {
Dees_Troy8170a922012-09-18 15:40:25 -04001826 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troye58d5262012-09-21 12:27:57 -04001827 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
Dees_Troy8170a922012-09-18 15:40:25 -04001828 if ((*iter)->Backup_Size == 0) {
1829 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1830 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1831 } else
1832 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
Dees_Troy2c50e182012-09-26 20:05:28 -04001833 } else if ((*iter)->Mount_Point == "/boot") {
1834 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1835 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1836 if ((*iter)->Backup_Size == 0) {
1837 DataManager::SetValue("tw_has_boot_partition", 0);
1838 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1839 } else
1840 DataManager::SetValue("tw_has_boot_partition", 1);
Dees_Troy51127312012-09-08 13:08:49 -04001841 }
Dees_Troyaa9cc402012-10-13 12:14:05 -04001842 } else {
1843 // Handle unmountable partitions in case we reset defaults
1844 if ((*iter)->Mount_Point == "/boot") {
1845 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1846 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1847 if ((*iter)->Backup_Size == 0) {
1848 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1849 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1850 } else
1851 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1852 } else if ((*iter)->Mount_Point == "/recovery") {
1853 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1854 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1855 if ((*iter)->Backup_Size == 0) {
1856 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1857 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1858 } else
1859 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
Gary Peck82599a82012-11-21 16:23:12 -08001860 } else if ((*iter)->Mount_Point == "/data") {
1861 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troyaa9cc402012-10-13 12:14:05 -04001862 }
Dees_Troy51127312012-09-08 13:08:49 -04001863 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001864 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001865 gui_msg("update_part_details_done=...done");
Dees_Troy51127312012-09-08 13:08:49 -04001866 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1867 string current_storage_path = DataManager::GetCurrentStoragePath();
1868 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
Dees_Troy8170a922012-09-18 15:40:25 -04001869 if (FreeStorage != NULL) {
1870 // Attempt to mount storage
bigbiff25d25b92020-06-19 16:07:38 -04001871 if (!FreeStorage->Mount(false)) {
1872 gui_msg(Msg(msg::kWarning, "unable_to_mount_storage=Unable to mount storage"));
1873 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
1874 } else {
1875 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
Dees_Troy8170a922012-09-18 15:40:25 -04001876 }
1877 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00001878 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
Dees_Troy8170a922012-09-18 15:40:25 -04001879 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001880 if (!Write_Fstab())
Dees_Troy2673cec2013-04-02 20:22:16 +00001881 LOGERR("Error creating fstab\n");
Dees_Troy51a0e822012-09-05 15:24:24 -04001882 return;
1883}
1884
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001885void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1886 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffc2cb3852020-09-11 14:03:31 -04001887
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001888 if (dat != NULL) {
bigbiffaed1bdf2021-08-03 18:21:39 -04001889 // reparse for /cache/recovery/command
1890 static constexpr const char* COMMAND_FILE = "/data/cache/command";
1891 if (TWFunc::Path_Exists(COMMAND_FILE)) {
1892 startupArgs startup;
1893 std::string content;
1894 TWFunc::read_file(COMMAND_FILE, content);
1895 std::vector<std::string> args = {content};
1896 startup.processRecoveryArgs(args, 0);
1897 }
1898
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001899 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1900 dat->Is_Decrypted = true;
1901 if (!Block_Device.empty()) {
1902 dat->Decrypted_Block_Device = Block_Device;
1903 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1904 } else {
1905 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1906 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001907 property_set("twrp.decrypt.done", "true");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001908 dat->Setup_File_System(false);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001909 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 -06001910
Noah Jacobson81d638d2019-04-28 00:10:07 -04001911 sleep(1); // Sleep for a bit so that the device will be ready
me-cafebabe09649612022-06-10 21:53:31 +08001912
1913 // Mount only /data
1914 dat->Symlink_Path = ""; // Not to let it to bind mount /data/media again
1915 if (!dat->Mount(false)) {
1916 LOGERR("Unable to mount /data after decryption");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001917 }
me-cafebabe09649612022-06-10 21:53:31 +08001918
1919 if (dat->Has_Data_Media && TWFunc::Path_Exists("/data/media/0")) {
1920 dat->Storage_Path = "/data/media/0";
1921 } else {
1922 dat->Storage_Path = "/data/media";
1923 }
1924 dat->Symlink_Path = dat->Storage_Path;
1925 DataManager::SetValue("tw_storage_path", dat->Symlink_Path);
Mohd Farazf9231102022-06-18 22:51:55 +02001926 DataManager::SetValue("tw_settings_path", TW_STORAGE_PATH);
me-cafebabe09649612022-06-10 21:53:31 +08001927 LOGINFO("New storage path after decryption: %s\n", dat->Storage_Path.c_str());
1928
epicXa721f952021-01-04 13:01:31 +05301929 DataManager::LoadTWRPFolderInfo();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001930 Update_System_Details();
nkk71ffb02bd2017-06-04 23:12:16 +03001931 Output_Partition(dat);
bigbiff4fa02b52021-12-30 17:01:44 -05001932 if (!android::base::StartsWith(dat->Actual_Block_Device, "/dev/block/mmcblk")) {
1933 if (!dat->Bind_Mount(false))
1934 LOGERR("Unable to bind mount /sdcard to %s\n", dat->Storage_Path.c_str());
1935 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001936 } else
1937 LOGERR("Unable to locate data partition.\n");
1938}
1939
Noah Jacobson81d638d2019-04-28 00:10:07 -04001940void TWPartitionManager::Parse_Users() {
1941#ifdef TW_INCLUDE_FBE
1942 char user_check_result[PROPERTY_VALUE_MAX];
1943 for (int userId = 0; userId <= 9999; userId++) {
1944 string prop = "twrp.user." + to_string(userId) + ".decrypt";
1945 property_get(prop.c_str(), user_check_result, "-1");
1946 if (strcmp(user_check_result, "-1") != 0) {
1947 if (userId < 0 || userId > 9999) {
1948 LOGINFO("Incorrect user id %d\n", userId);
1949 continue;
1950 }
1951 struct users_struct user;
1952 user.userId = to_string(userId);
1953
1954 // Attempt to get name of user. Fallback to user ID if this fails.
Darth98f775972022-08-05 09:39:03 +01001955 std::string path = "/data/system/users/" + to_string(userId) + ".xml";
1956 if (!TWFunc::Check_Xml_Format(path)) {
1957 string oldpath = path;
1958 if (TWFunc::abx_to_xml(oldpath, path)) {
1959 LOGINFO("Android 12+: '%s' has been converted into plain text xml (for user %s).\n", oldpath.c_str(), user.userId.c_str());
1960 }
1961 }
1962 char* userFile = PageManager::LoadFileToBuffer(path, NULL);
me-cafebabec46981d2022-07-29 01:54:43 +08001963 if (userFile == NULL) {
1964 user.userName = to_string(userId);
bigbiffa957f072021-03-07 18:20:29 -05001965 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001966 else {
me-cafebabec46981d2022-07-29 01:54:43 +08001967 xml_document<> *userXml = new xml_document<>();
1968 userXml->parse<0>(userFile);
1969 xml_node<>* userNode = userXml->first_node("user");
1970 if (userNode == nullptr) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04001971 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08001972 } else {
1973 xml_node<>* nameNode = userNode->first_node("name");
1974 if (nameNode == nullptr)
Noah Jacobson81d638d2019-04-28 00:10:07 -04001975 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08001976 else {
1977 string userName = nameNode->value();
1978 user.userName = userName + " (" + to_string(userId) + ")";
Noah Jacobson81d638d2019-04-28 00:10:07 -04001979 }
1980 }
1981 }
1982
1983 string filename;
bigbiffdf53b6c2022-01-17 19:31:52 -05001984 user.type = android::keystore::Get_Password_Type(userId, filename);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001985
1986 user.isDecrypted = false;
1987 if (strcmp(user_check_result, "1") == 0)
1988 user.isDecrypted = true;
1989 Users_List.push_back(user);
1990 }
1991 }
1992 Check_Users_Decryption_Status();
1993#endif
1994}
1995
1996std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
1997 return &Users_List;
1998}
1999
2000void TWPartitionManager::Mark_User_Decrypted(int userID) {
2001#ifdef TW_INCLUDE_FBE
2002 std::vector<users_struct>::iterator iter;
2003 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2004 if (atoi((*iter).userId.c_str()) == userID) {
2005 (*iter).isDecrypted = true;
2006 string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
2007 property_set(user_prop_decrypted.c_str(), "1");
2008 break;
2009 }
2010 }
2011 Check_Users_Decryption_Status();
2012#endif
2013}
2014
2015void TWPartitionManager::Check_Users_Decryption_Status() {
2016#ifdef TW_INCLUDE_FBE
2017 int all_is_decrypted = 1;
2018 std::vector<users_struct>::iterator iter;
2019 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2020 if (!(*iter).isDecrypted) {
2021 LOGINFO("User %s is not decrypted.\n", (*iter).userId.c_str());
2022 all_is_decrypted = 0;
2023 break;
2024 }
2025 }
2026 if (all_is_decrypted == 1) {
2027 LOGINFO("All found users are decrypted.\n");
2028 DataManager::SetValue("tw_all_users_decrypted", "1");
2029 property_set("twrp.all.users.decrypted", "true");
2030 } else
2031 DataManager::SetValue("tw_all_users_decrypted", "0");
2032#endif
2033}
2034
2035int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
Dees_Troy5bf43922012-09-07 16:07:55 -04002036#ifdef TW_INCLUDE_CRYPTO
Captain Throwback37c3aef2021-10-06 11:38:18 -04002037 char crypto_blkdev[PROPERTY_VALUE_MAX];
Ethan Yonker253368a2014-11-25 15:00:52 -06002038 std::vector<TWPartition*>::iterator iter;
Dees_Troy5bf43922012-09-07 16:07:55 -04002039
Ethan Yonker253368a2014-11-25 15:00:52 -06002040 // Mount any partitions that need to be mounted for decrypt
2041 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2042 if ((*iter)->Mount_To_Decrypt) {
2043 (*iter)->Mount(true);
2044 }
a39552696ff55ce2013-01-08 16:14:56 +00002045 }
oshmouna82a7542018-04-10 17:45:55 +02002046 property_set("twrp.mount_to_decrypt", "1");
a39552696ff55ce2013-01-08 16:14:56 +00002047
Captain Throwback37c3aef2021-10-06 11:38:18 -04002048 Set_Crypto_State();
2049 Set_Crypto_Type("block");
Ethan Yonkera1de1492015-11-04 11:58:27 -06002050
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002051 if (DataManager::GetIntValue(TW_IS_FBE)) {
2052#ifdef TW_INCLUDE_FBE
2053 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
2054 return -1;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002055
2056 bool user_need_decrypt = false;
2057 std::vector<users_struct>::iterator iter;
2058 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2059 if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
2060 user_need_decrypt = true;
2061 }
2062 }
2063 if (!user_need_decrypt) {
2064 LOGINFO("User %d does not require decryption\n", user_id);
2065 return 0;
2066 }
2067
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002068 int retry_count = 10;
2069 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
Noah Jacobson81d638d2019-04-28 00:10:07 -04002070 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
2071 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002072 if (android::keystore::Decrypt_User(user_id, Password)) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04002073 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
2074 Mark_User_Decrypted(user_id);
2075 if (user_id == 0) {
2076 // When decrypting user 0 also try all other users
2077 std::vector<users_struct>::iterator iter;
2078 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2079 if ((*iter).userId == "0" || (*iter).isDecrypted)
2080 continue;
2081
2082 int tmp_user_id = atoi((*iter).userId.c_str());
2083 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002084 if (android::keystore::Decrypt_User(tmp_user_id, Password) ||
2085 (Password != "!" && android::keystore::Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
Noah Jacobson81d638d2019-04-28 00:10:07 -04002086 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
2087 Mark_User_Decrypted(tmp_user_id);
2088 } else {
2089 gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
2090 }
2091 }
2092 Post_Decrypt("");
2093 }
2094
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002095 return 0;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002096 } else {
2097 gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002098 }
2099#else
2100 LOGERR("FBE support is not present\n");
2101#endif
2102 return -1;
2103 }
2104
Noah Jacobson81d638d2019-04-28 00:10:07 -04002105 char isdecrypteddata[PROPERTY_VALUE_MAX];
2106 property_get("twrp.decrypt.done", isdecrypteddata, "");
2107 if (strcmp(isdecrypteddata, "true") == 0) {
2108 LOGINFO("Data has no decryption required\n");
2109 return 0;
2110 }
2111
Ethan Yonkerddb63e22017-01-19 14:01:57 -06002112 int pwret = -1;
2113 pid_t pid = fork();
2114 if (pid < 0) {
2115 LOGERR("fork failed\n");
2116 return -1;
2117 } else if (pid == 0) {
2118 // Child process
2119 char cPassword[255];
2120 strcpy(cPassword, Password.c_str());
2121 int ret = cryptfs_check_passwd(cPassword);
2122 exit(ret);
2123 } else {
2124 // Parent
2125 int status;
2126 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
2127 pwret = -1;
2128 else
2129 pwret = WEXITSTATUS(status) ? -1 : 0;
2130 }
a39552696ff55ce2013-01-08 16:14:56 +00002131
Ethan Yonker253368a2014-11-25 15:00:52 -06002132 // Unmount any partitions that were needed for decrypt
2133 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2134 if ((*iter)->Mount_To_Decrypt) {
2135 (*iter)->UnMount(false);
2136 }
2137 }
oshmouna82a7542018-04-10 17:45:55 +02002138 property_set("twrp.mount_to_decrypt", "0");
Ethan Yonker253368a2014-11-25 15:00:52 -06002139
a39552696ff55ce2013-01-08 16:14:56 +00002140 if (pwret != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002141 gui_err("fail_decrypt=Failed to decrypt data.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002142 return -1;
2143 }
a39552696ff55ce2013-01-08 16:14:56 +00002144
Dees_Troy5bf43922012-09-07 16:07:55 -04002145 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
2146 if (strcmp(crypto_blkdev, "error") == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002147 LOGERR("Error retrieving decrypted data block device.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -04002148 } else {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002149 Post_Decrypt(crypto_blkdev);
Dees_Troy5bf43922012-09-07 16:07:55 -04002150 }
2151 return 0;
2152#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002153 gui_err("no_crypto_support=No crypto support was compiled into this build.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002154 return -1;
2155#endif
Dees_Troy51a0e822012-09-05 15:24:24 -04002156 return 1;
Dees_Troy51127312012-09-08 13:08:49 -04002157}
2158
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002159int TWPartitionManager::Fix_Contexts(void) {
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002160 std::vector<TWPartition*>::iterator iter;
2161 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2162 if ((*iter)->Has_Data_Media) {
2163 if ((*iter)->Mount(true)) {
2164 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
2165 return -1;
2166 }
2167 }
2168 }
Dees_Troy1a650e62012-10-19 20:54:32 -04002169 UnMount_Main_Partitions();
Ethan Yonker74db1572015-10-28 12:44:49 -05002170 gui_msg("done=Done.");
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002171 return 0;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002172}
2173
Ethan Yonker66a19492015-12-10 10:19:45 -06002174TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002175 std::vector<TWPartition*>::iterator iter = Partitions.begin();
2176
2177 if (!Path.empty()) {
2178 string Search_Path = TWFunc::Get_Root_Path(Path);
2179 for (; iter != Partitions.end(); iter++) {
Matt Mower9a561dd2016-02-22 21:25:51 -06002180 if ((*iter)->Mount_Point == Search_Path) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002181 iter++;
2182 break;
2183 }
2184 }
2185 }
2186
2187 for (; iter != Partitions.end(); iter++) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002188 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
2189 // do nothing, do not return this type of partition
2190 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002191 return (*iter);
2192 }
2193 }
2194
2195 return NULL;
2196}
2197
Dees_Troyd21618c2012-10-14 18:48:49 -04002198int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
Dees_Troyd21618c2012-10-14 18:48:49 -04002199 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
2200
2201 if (Part == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002202 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
2203 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 -04002204 return false;
2205 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002206 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
2207 if (!Part->UnMount(true) || !Part->Is_Present)
Dees_Troyd21618c2012-10-14 18:48:49 -04002208 return false;
2209
bigbiff22851b92021-09-01 16:46:57 -04002210 if (!TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002211 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
Dees_Troyd21618c2012-10-14 18:48:49 -04002212 return false;
2213 }
Dees_Troyd21618c2012-10-14 18:48:49 -04002214 return true;
2215}
2216
Dees_Troy8170a922012-09-18 15:40:25 -04002217int TWPartitionManager::usb_storage_enable(void) {
Dees_Troy8170a922012-09-18 15:40:25 -04002218 char lun_file[255];
Dees_Troyd21618c2012-10-14 18:48:49 -04002219 bool has_multiple_lun = false;
Dees_Troy8170a922012-09-18 15:40:25 -04002220
Ethan Yonker47360be2014-04-01 10:34:34 -05002221 string Lun_File_str = CUSTOM_LUN_FILE;
2222 size_t found = Lun_File_str.find("%");
2223 if (found != string::npos) {
2224 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
2225 if (TWFunc::Path_Exists(lun_file))
2226 has_multiple_lun = true;
2227 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002228 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
Ethan Yonker47360be2014-04-01 10:34:34 -05002229 if (!has_multiple_lun) {
2230 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
2231 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
2232 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
Ethan Yonker66a19492015-12-10 10:19:45 -06002233 TWPartition* Mount = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002234 if (Mount) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002235 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
2236 goto error_handle;
2237 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002238 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002239 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002240 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002241 }
2242 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002243 goto error_handle;
Dees_Troy8170a922012-09-18 15:40:25 -04002244 }
Dees_Troy8170a922012-09-18 15:40:25 -04002245 } else {
Ethan Yonker47360be2014-04-01 10:34:34 -05002246 LOGINFO("Device has multiple lun files\n");
2247 TWPartition* Mount1;
2248 TWPartition* Mount2;
Dees_Troy8170a922012-09-18 15:40:25 -04002249 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
Ethan Yonker66a19492015-12-10 10:19:45 -06002250 Mount1 = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002251 if (Mount1) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002252 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
2253 goto error_handle;
2254 }
Matt Moweree717062014-04-26 01:46:46 -05002255 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
Ethan Yonker66a19492015-12-10 10:19:45 -06002256 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
Matt Mower1fdcdb72016-01-25 20:53:47 -06002257 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
Matt Moweree717062014-04-26 01:46:46 -05002258 Open_Lun_File(Mount2->Mount_Point, lun_file);
nkk717aa6fc62017-03-24 18:28:03 +02002259 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2260 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data") {
2261 Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file);
Ethan Yonker47360be2014-04-01 10:34:34 -05002262 }
nkk717aa6fc62017-03-24 18:28:03 +02002263 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2264 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data" && !Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002265 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002266 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002267 }
Dees_Troy8170a922012-09-18 15:40:25 -04002268 }
Matt Mowerb6ef4782014-11-06 02:24:36 -06002269 property_set("sys.storage.ums_enabled", "1");
HandyMenny37d42992014-10-26 22:15:59 +01002270 property_set("sys.usb.config", "mass_storage,adb");
Dees_Troy8170a922012-09-18 15:40:25 -04002271 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002272error_handle:
2273 if (mtp_was_enabled)
2274 if (!Enable_MTP())
2275 Disable_MTP();
2276 return false;
Dees_Troy8170a922012-09-18 15:40:25 -04002277}
2278
2279int TWPartitionManager::usb_storage_disable(void) {
bigbiff22851b92021-09-01 16:46:57 -04002280 int index, ret = 0;
Dees_Troy2673cec2013-04-02 20:22:16 +00002281 char lun_file[255], ch[2] = {0, 0};
2282 string str = ch;
Dees_Troy8170a922012-09-18 15:40:25 -04002283
2284 for (index=0; index<2; index++) {
2285 sprintf(lun_file, CUSTOM_LUN_FILE, index);
bigbiff22851b92021-09-01 16:46:57 -04002286 if (!TWFunc::write_to_file(lun_file, str)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002287 break;
bigbiff22851b92021-09-01 16:46:57 -04002288 ret = -1;
Dees_Troy8170a922012-09-18 15:40:25 -04002289 }
Dees_Troy8170a922012-09-18 15:40:25 -04002290 }
Dees_Troye58d5262012-09-21 12:27:57 -04002291 Mount_All_Storage();
2292 Update_System_Details();
Dees_Troycfd73ef2012-10-12 16:52:00 -04002293 UnMount_Main_Partitions();
Matt Mowerd9cb9062013-12-14 20:34:45 -06002294 property_set("sys.storage.ums_enabled", "0");
HandyMenny37d42992014-10-26 22:15:59 +01002295 property_set("sys.usb.config", "adb");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002296 if (mtp_was_enabled)
2297 if (!Enable_MTP())
2298 Disable_MTP();
Dees_Troy2673cec2013-04-02 20:22:16 +00002299 if (ret < 0 && index == 0) {
2300 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
2301 return false;
2302 } else {
2303 return true;
2304 }
Dees_Troy8170a922012-09-18 15:40:25 -04002305 return true;
Dees_Troy812660f2012-09-20 09:55:17 -04002306}
2307
2308void TWPartitionManager::Mount_All_Storage(void) {
2309 std::vector<TWPartition*>::iterator iter;
2310
2311 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2312 if ((*iter)->Is_Storage)
2313 (*iter)->Mount(false);
2314 }
Dees_Troy2c50e182012-09-26 20:05:28 -04002315}
Dees_Troy9350b8d2012-09-27 12:38:38 -04002316
Dees_Troyd0384ef2012-10-12 12:15:42 -04002317void TWPartitionManager::UnMount_Main_Partitions(void) {
2318 // Unmounts system and data if data is not data/media
2319 // Also unmounts boot if boot is mountable
Dees_Troy2673cec2013-04-02 20:22:16 +00002320 LOGINFO("Unmounting main partitions...\n");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002321
Mohd Faraze3948ec2020-08-14 01:40:59 +00002322 TWPartition *Partition = Find_Partition_By_Path ("/vendor");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002323
Mohd Faraze3948ec2020-08-14 01:40:59 +00002324 if (Partition != NULL) UnMount_By_Path("/vendor", false);
2325 UnMount_By_Path (Get_Android_Root_Path(), true);
2326 Partition = Find_Partition_By_Path ("/product");
2327 if (Partition != NULL) UnMount_By_Path("/product", false);
Ethan Yonker6277c792014-09-15 14:54:30 -05002328 if (!datamedia)
2329 UnMount_By_Path("/data", true);
2330
Mohd Faraze3948ec2020-08-14 01:40:59 +00002331 Partition = Find_Partition_By_Path ("/boot");
2332 if (Partition != NULL && Partition->Can_Be_Mounted)
2333 Partition->UnMount(true);
Dees_Troyd0384ef2012-10-12 12:15:42 -04002334}
2335
Dees_Troy9350b8d2012-09-27 12:38:38 -04002336int TWPartitionManager::Partition_SDCard(void) {
Matt Mower23d8aae2017-01-06 14:30:33 -06002337 char temp[255];
Ethan Yonker483e9f42016-01-11 22:21:18 -06002338 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 -04002339 int ext, swap, total_size = 0, fat_size;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002340
Ethan Yonker74db1572015-10-28 12:44:49 -05002341 gui_msg("start_partition_sd=Partitioning SD Card...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002342
2343 // Locate and validate device to partition
2344 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
2345
Ethan Yonker66a19492015-12-10 10:19:45 -06002346 if (SDCard->Is_Adopted_Storage)
2347 SDCard->Revert_Adopted();
2348
Ethan Yonker1eff6cd2014-09-15 13:30:42 -05002349 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002350 gui_err("partition_sd_locate=Unable to locate device to partition.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002351 return false;
2352 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002353
2354 // Unmount everything
Dees_Troy9350b8d2012-09-27 12:38:38 -04002355 if (!SDCard->UnMount(true))
2356 return false;
2357 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
2358 if (SDext != NULL) {
2359 if (!SDext->UnMount(true))
2360 return false;
2361 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002362 char* swappath = getenv("SWAPPATH");
2363 if (swappath != NULL) {
2364 LOGINFO("Unmounting swap at '%s'\n", swappath);
2365 umount(swappath);
2366 }
Vojtech Bocek05534202013-09-11 08:11:56 +02002367
Ethan Yonker483e9f42016-01-11 22:21:18 -06002368 // Determine block device
2369 if (SDCard->Alternate_Block_Device.empty()) {
2370 SDCard->Find_Actual_Block_Device();
2371 Device = SDCard->Actual_Block_Device;
2372 // Just use the root block device
2373 Device.resize(strlen("/dev/block/mmcblkX"));
2374 } else {
2375 Device = SDCard->Alternate_Block_Device;
2376 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002377
2378 // Find the size of the block device:
Ethan Yonker483e9f42016-01-11 22:21:18 -06002379 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002380
2381 DataManager::GetValue("tw_sdext_size", ext);
2382 DataManager::GetValue("tw_swap_size", swap);
2383 DataManager::GetValue("tw_sdpart_file_system", ext_format);
2384 fat_size = total_size - ext - swap;
Ethan Yonker483e9f42016-01-11 22:21:18 -06002385 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);
2386
2387 // Determine partition sizes
2388 if (swap == 0 && ext == 0) {
2389 fat_str = "-0";
2390 } else {
2391 memset(temp, 0, sizeof(temp));
2392 sprintf(temp, "%i", fat_size);
2393 fat_str = temp;
2394 fat_str += "MB";
2395 }
2396 if (swap == 0) {
2397 ext_str = "-0";
2398 } else {
2399 memset(temp, 0, sizeof(temp));
2400 sprintf(temp, "%i", ext);
2401 ext_str = "+";
2402 ext_str += temp;
2403 ext_str += "MB";
2404 }
2405
Dees_Troy9350b8d2012-09-27 12:38:38 -04002406 if (ext + swap > total_size) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002407 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002408 return false;
2409 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002410
Ethan Yonker74db1572015-10-28 12:44:49 -05002411 gui_msg("remove_part_table=Removing partition table...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002412 Command = "sgdisk --zap-all " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002413 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002414 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002415 gui_err("unable_rm_part=Unable to remove partition table.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002416 Update_System_Details();
2417 return false;
2418 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002419 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
Captain Throwback9643a802016-05-27 11:44:51 -04002420 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 +00002421 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002422 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002423 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002424 return false;
2425 }
2426 if (ext > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002427 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002428 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002429 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002430 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002431 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002432 Update_System_Details();
2433 return false;
2434 }
2435 }
2436 if (swap > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002437 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002438 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 +00002439 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002440 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002441 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002442 Update_System_Details();
2443 return false;
2444 }
2445 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002446
2447 // Convert GPT to MBR
2448 Command = "sgdisk --gpttombr " + Device;
2449 if (TWFunc::Exec_Cmd(Command) != 0)
2450 LOGINFO("Failed to covert partition GPT to MBR\n");
2451
2452 // Tell the kernel to rescan the partition table
2453 int fd = open(Device.c_str(), O_RDONLY);
2454 ioctl(fd, BLKRRPART, 0);
2455 close(fd);
2456
2457 string format_device = Device;
2458 if (Device.substr(0, 17) == "/dev/block/mmcblk")
2459 format_device += "p";
2460
2461 // Format new partitions to proper file system
2462 if (fat_size > 0) {
2463 Command = "mkfs.fat " + format_device + "1";
2464 TWFunc::Exec_Cmd(Command);
2465 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002466 if (ext > 0) {
2467 if (SDext == NULL) {
Ethan Yonker483e9f42016-01-11 22:21:18 -06002468 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2469 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2470 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2471 TWFunc::Exec_Cmd(Command);
2472 } else {
2473 SDext->Wipe(ext_format);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002474 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002475 }
2476 if (swap > 0) {
2477 Command = "mkswap " + format_device;
2478 if (ext > 0)
2479 Command += "3";
2480 else
2481 Command += "2";
Vojtech Bocek05534202013-09-11 08:11:56 +02002482 TWFunc::Exec_Cmd(Command);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002483 }
2484
Ethan Yonker483e9f42016-01-11 22:21:18 -06002485 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2486 if (SDCard->Mount(true)) {
2487 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2488 mkdir(TWRP_Folder.c_str(), 0777);
2489 DataManager::Flush();
2490 }
2491
Dees_Troy9350b8d2012-09-27 12:38:38 -04002492 Update_System_Details();
Ethan Yonker74db1572015-10-28 12:44:49 -05002493 gui_msg("part_complete=Partitioning complete.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002494 return true;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002495}
Dees_Troya13d74f2013-03-24 08:54:55 -05002496
2497void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2498 std::vector<TWPartition*>::iterator iter;
2499 if (ListType == "mount") {
2500 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002501 if ((*iter)->Can_Be_Mounted) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002502 struct PartitionList part;
2503 part.Display_Name = (*iter)->Display_Name;
2504 part.Mount_Point = (*iter)->Mount_Point;
2505 part.selected = (*iter)->Is_Mounted();
2506 Partition_List->push_back(part);
2507 }
2508 }
2509 } else if (ListType == "storage") {
2510 char free_space[255];
2511 string Current_Storage = DataManager::GetCurrentStoragePath();
2512 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2513 if ((*iter)->Is_Storage) {
2514 struct PartitionList part;
2515 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2516 part.Display_Name = (*iter)->Storage_Name + " (";
2517 part.Display_Name += free_space;
2518 part.Display_Name += "MB)";
2519 part.Mount_Point = (*iter)->Storage_Path;
2520 if ((*iter)->Storage_Path == Current_Storage)
2521 part.selected = 1;
2522 else
2523 part.selected = 0;
2524 Partition_List->push_back(part);
2525 }
2526 }
2527 } else if (ListType == "backup") {
2528 char backup_size[255];
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002529 unsigned long long Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05002530 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002531 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002532 struct PartitionList part;
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002533 Backup_Size = (*iter)->Backup_Size;
2534 if ((*iter)->Has_SubPartition) {
2535 std::vector<TWPartition*>::iterator subpart;
2536
2537 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2538 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2539 Backup_Size += (*subpart)->Backup_Size;
2540 }
2541 }
2542 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
Dees_Troya13d74f2013-03-24 08:54:55 -05002543 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2544 part.Display_Name += backup_size;
2545 part.Display_Name += "MB)";
2546 part.Mount_Point = (*iter)->Backup_Path;
2547 part.selected = 0;
2548 Partition_List->push_back(part);
2549 }
2550 }
2551 } else if (ListType == "restore") {
2552 string Restore_List, restore_path;
2553 TWPartition* restore_part = NULL;
2554
2555 DataManager::GetValue("tw_restore_list", Restore_List);
2556 if (!Restore_List.empty()) {
2557 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2558 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2559 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002560 struct PartitionList part;
2561 if (restore_path.compare("ADB_Backup") == 0) {
2562 part.Display_Name = "ADB Backup";
2563 part.Mount_Point = "ADB Backup";
2564 part.selected = 1;
2565 Partition_List->push_back(part);
2566 break;
2567 }
Dees_Troy59df9262013-06-19 14:53:57 -05002568 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
Dees Troy4159aed2014-02-28 17:24:43 +00002569 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002570 // Don't allow restore of recovery (causes problems on some devices)
Dees_Troy59df9262013-06-19 14:53:57 -05002571 // Don't add subpartitions to the list of items
Dees_Troya13d74f2013-03-24 08:54:55 -05002572 } else {
Dees_Troya13d74f2013-03-24 08:54:55 -05002573 part.Display_Name = restore_part->Backup_Display_Name;
2574 part.Mount_Point = restore_part->Backup_Path;
2575 part.selected = 1;
2576 Partition_List->push_back(part);
2577 }
2578 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002579 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05002580 }
2581 start_pos = end_pos + 1;
2582 end_pos = Restore_List.find(";", start_pos);
2583 }
2584 }
2585 } else if (ListType == "wipe") {
2586 struct PartitionList dalvik;
Ethan Yonker74db1572015-10-28 12:44:49 -05002587 dalvik.Display_Name = gui_parse_text("{@dalvik}");
Dees_Troya13d74f2013-03-24 08:54:55 -05002588 dalvik.Mount_Point = "DALVIK";
2589 dalvik.selected = 0;
2590 Partition_List->push_back(dalvik);
2591 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2592 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2593 struct PartitionList part;
2594 part.Display_Name = (*iter)->Display_Name;
2595 part.Mount_Point = (*iter)->Mount_Point;
2596 part.selected = 0;
2597 Partition_List->push_back(part);
2598 }
2599 if ((*iter)->Has_Android_Secure) {
2600 struct PartitionList part;
2601 part.Display_Name = (*iter)->Backup_Display_Name;
2602 part.Mount_Point = (*iter)->Backup_Path;
2603 part.selected = 0;
2604 Partition_List->push_back(part);
2605 }
Dees_Troy74fb2e92013-04-15 14:35:47 +00002606 if ((*iter)->Has_Data_Media) {
2607 struct PartitionList datamedia;
2608 datamedia.Display_Name = (*iter)->Storage_Name;
2609 datamedia.Mount_Point = "INTERNAL";
2610 datamedia.selected = 0;
2611 Partition_List->push_back(datamedia);
2612 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002613 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002614 } else if (ListType == "flashimg") {
2615 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2616 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2617 struct PartitionList part;
2618 part.Display_Name = (*iter)->Backup_Display_Name;
2619 part.Mount_Point = (*iter)->Backup_Path;
2620 part.selected = 0;
2621 Partition_List->push_back(part);
2622 }
2623 }
Ethan Yonker53796e72019-01-11 22:49:52 -06002624 if (DataManager::GetIntValue("tw_has_repack_tools") != 0 && DataManager::GetIntValue("tw_has_boot_slots") != 0) {
2625 TWPartition* boot = Find_Partition_By_Path("/boot");
2626 if (boot) {
2627 // Allow flashing kernels and ramdisks
2628 struct PartitionList repack_ramdisk;
2629 repack_ramdisk.Display_Name = gui_lookup("install_twrp_ramdisk", "Install Recovery Ramdisk");
2630 repack_ramdisk.Mount_Point = "/repack_ramdisk";
2631 repack_ramdisk.selected = 0;
2632 Partition_List->push_back(repack_ramdisk);
2633 /*struct PartitionList repack_kernel; For now let's leave repacking kernels under advanced only
2634 repack_kernel.Display_Name = gui_lookup("install_kernel", "Install Kernel");
2635 repack_kernel.Mount_Point = "/repack_kernel";
2636 repack_kernel.selected = 0;
2637 Partition_List->push_back(repack_kernel);*/
2638 }
2639 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002640 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00002641 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05002642 }
2643}
2644
2645int TWPartitionManager::Fstab_Processed(void) {
2646 return Partitions.size();
2647}
Dees_Troyd93bda52013-07-03 19:55:19 +00002648
2649void TWPartitionManager::Output_Storage_Fstab(void) {
2650 std::vector<TWPartition*>::iterator iter;
2651 char storage_partition[255];
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002652 std::string Temp;
bigbiff25d25b92020-06-19 16:07:38 -04002653 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002654
2655 if (cacheDir.empty()) {
2656 LOGINFO("Unable to find cache directory\n");
2657 return;
2658 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002659
bigbiff25d25b92020-06-19 16:07:38 -04002660 std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002661 FILE *fp = fopen(storageFstab.c_str(), "w");
Dees_Troyd93bda52013-07-03 19:55:19 +00002662
2663 if (fp == NULL) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002664 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
Dees_Troyd93bda52013-07-03 19:55:19 +00002665 return;
2666 }
2667
2668 // Iterate through all partitions
2669 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2670 if ((*iter)->Is_Storage) {
2671 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2672 strcpy(storage_partition, Temp.c_str());
2673 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2674 }
2675 }
2676 fclose(fp);
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02002677}
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002678
2679TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2680{
2681 TWPartition *res = NULL;
2682 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
Matt Mowera8a89d12016-12-30 18:10:37 -06002683 if (!(*iter)->Is_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002684 continue;
2685
Matt Mowera8a89d12016-12-30 18:10:37 -06002686 if ((*iter)->Is_Settings_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002687 return *iter;
2688
Matt Mowera8a89d12016-12-30 18:10:37 -06002689 if (!res)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002690 res = *iter;
2691 }
2692 return res;
2693}
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002694
2695bool TWPartitionManager::Enable_MTP(void) {
2696#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002697 if (mtppid) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002698 gui_err("mtp_already_enabled=MTP already enabled");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002699 return true;
2700 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002701
2702 int mtppipe[2];
2703
2704 if (pipe(mtppipe) < 0) {
2705 LOGERR("Error creating MTP pipe\n");
2706 return false;
2707 }
2708
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002709 char old_value[PROPERTY_VALUE_MAX];
Matt Mowere07f0102017-02-23 17:40:00 -06002710 property_get("sys.usb.config", old_value, "");
2711 if (strcmp(old_value, "mtp,adb") != 0) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002712 char vendor[PROPERTY_VALUE_MAX];
2713 char product[PROPERTY_VALUE_MAX];
2714 property_set("sys.usb.config", "none");
2715 property_get("usb.vendor", vendor, "18D1");
2716 property_get("usb.product.mtpadb", product, "4EE2");
2717 string vendorstr = vendor;
2718 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002719 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2720 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002721 property_set("sys.usb.config", "mtp,adb");
2722 }
Matt Mower653a1702017-02-16 10:38:52 -06002723 /* To enable MTP debug, use the twrp command line feature:
Ethan Yonker6d154c42014-09-03 14:19:43 -05002724 * twrp set tw_mtp_debug 1
2725 */
2726 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
Ethan Yonker1b039202015-01-30 10:08:48 -06002727 mtppid = mtp->forkserver(mtppipe);
2728 if (mtppid) {
2729 close(mtppipe[0]); // Host closes read side
2730 mtp_write_fd = mtppipe[1];
2731 DataManager::SetValue("tw_mtp_enabled", 1);
2732 Add_All_MTP_Storage();
2733 return true;
Ethan Yonker726a0202014-12-16 20:01:38 -06002734 } else {
2735 close(mtppipe[0]);
2736 close(mtppipe[1]);
Ethan Yonker74db1572015-10-28 12:44:49 -05002737 gui_err("mtp_fail=Failed to enable MTP");
Ethan Yonker1b039202015-01-30 10:08:48 -06002738 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002739 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002740#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002741 gui_err("no_mtp=MTP support not included");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002742#endif
2743 DataManager::SetValue("tw_mtp_enabled", 0);
2744 return false;
2745}
2746
Ethan Yonker1b039202015-01-30 10:08:48 -06002747void TWPartitionManager::Add_All_MTP_Storage(void) {
2748#ifdef TW_HAS_MTP
2749 std::vector<TWPartition*>::iterator iter;
2750
2751 if (!mtppid)
2752 return; // MTP is not enabled
2753
2754 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2755 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2756 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2757 }
2758#else
2759 return;
2760#endif
2761}
2762
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002763bool TWPartitionManager::Disable_MTP(void) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002764 char old_value[PROPERTY_VALUE_MAX];
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05002765 property_set("sys.usb.ffs.mtp.ready", "0");
Matt Mowere07f0102017-02-23 17:40:00 -06002766 property_get("sys.usb.config", old_value, "");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002767 if (strcmp(old_value, "adb") != 0) {
2768 char vendor[PROPERTY_VALUE_MAX];
2769 char product[PROPERTY_VALUE_MAX];
2770 property_set("sys.usb.config", "none");
2771 property_get("usb.vendor", vendor, "18D1");
Matt Mowere07f0102017-02-23 17:40:00 -06002772 property_get("usb.product.adb", product, "D001");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002773 string vendorstr = vendor;
2774 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002775 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2776 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002777 usleep(2000);
2778 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002779#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002780 if (mtppid) {
Ethan Yonker8613dc02014-09-11 09:28:20 -05002781 LOGINFO("Disabling MTP\n");
2782 int status;
2783 kill(mtppid, SIGKILL);
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002784 mtppid = 0;
Ethan Yonker8613dc02014-09-11 09:28:20 -05002785 // We don't care about the exit value, but this prevents a zombie process
2786 waitpid(mtppid, &status, 0);
Ethan Yonker726a0202014-12-16 20:01:38 -06002787 close(mtp_write_fd);
2788 mtp_write_fd = -1;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002789 }
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002790#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002791 property_set("sys.usb.config", "adb");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002792#ifdef TW_HAS_MTP
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002793 DataManager::SetValue("tw_mtp_enabled", 0);
2794 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002795#endif
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002796 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002797}
Ethan Yonker726a0202014-12-16 20:01:38 -06002798
2799TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2800 std::vector<TWPartition*>::iterator iter;
2801
2802 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2803 if ((*iter)->MTP_Storage_ID == Storage_ID)
2804 return (*iter);
2805 }
2806 return NULL;
2807}
2808
2809bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2810#ifdef TW_HAS_MTP
2811 struct mtpmsg mtp_message;
2812
2813 if (!mtppid)
2814 return false; // MTP is disabled
2815
2816 if (mtp_write_fd < 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002817 LOGINFO("MTP: mtp_write_fd is not set\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002818 return false;
2819 }
2820
2821 if (Part) {
Ethan Yonker4bfabab2014-12-29 09:15:37 -06002822 if (Part->MTP_Storage_ID == 0)
2823 return false;
Ethan Yonker726a0202014-12-16 20:01:38 -06002824 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2825 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2826 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2827 mtp_message.storage_id = Part->MTP_Storage_ID;
2828 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002829 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002830 return false;
2831 } else {
2832 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2833 return true;
2834 }
2835 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2836 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2837 mtp_message.storage_id = Part->MTP_Storage_ID;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002838 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2839 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2840 return false;
2841 }
2842 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2843 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2844 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2845 return false;
2846 }
2847 strcpy(mtp_message.display, Part->Storage_Name.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002848 mtp_message.maxFileSize = Part->Get_Max_FileSize();
Ethan Yonker1b039202015-01-30 10:08:48 -06002849 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 -06002850 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002851 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002852 return false;
2853 } else {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002854 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
Ethan Yonker726a0202014-12-16 20:01:38 -06002855 return true;
2856 }
2857 } else {
2858 LOGERR("Unknown MTP message type: %i\n", message_type);
2859 }
2860 } else {
2861 // This hopefully never happens as the error handling should
2862 // occur in the calling function.
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002863 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002864 }
2865 return true;
2866#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002867 gui_err("no_mtp=MTP support not included");
Ethan Yonker726a0202014-12-16 20:01:38 -06002868 DataManager::SetValue("tw_mtp_enabled", 0);
2869 return false;
2870#endif
2871}
2872
2873bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2874#ifdef TW_HAS_MTP
2875 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2876 if (Part) {
2877 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2878 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002879 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002880 }
2881#endif
2882 return false;
2883}
2884
2885bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2886#ifdef TW_HAS_MTP
2887 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2888 if (Part) {
2889 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2890 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002891 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002892 }
2893#endif
2894 return false;
2895}
2896
2897bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2898#ifdef TW_HAS_MTP
2899 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2900 if (Part) {
2901 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2902 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002903 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002904 }
2905#endif
2906 return false;
2907}
2908
2909bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2910#ifdef TW_HAS_MTP
2911 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2912 if (Part) {
2913 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2914 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002915 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002916 }
2917#endif
2918 return false;
2919}
Ethan Yonker96af84a2015-01-05 14:58:36 -06002920
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002921bool TWPartitionManager::Flash_Image(string& path, string& filename) {
bigbiffad58e1b2020-07-06 20:24:34 -04002922 twrpRepacker repacker;
Matt Mower23d8aae2017-01-06 14:30:33 -06002923 int partition_count = 0;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002924 TWPartition* flash_part = NULL;
bigbiffce8f83c2015-12-12 18:30:21 -05002925 string Flash_List, flash_path, full_filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002926 size_t start_pos = 0, end_pos = 0;
2927
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002928 full_filename = path + "/" + filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002929
bigbiffce8f83c2015-12-12 18:30:21 -05002930 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
2931 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
2932
2933 if (!TWFunc::Path_Exists(full_filename)) {
2934 if (!Mount_By_Path(full_filename, true)) {
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002935 return false;
2936 }
bigbiffce8f83c2015-12-12 18:30:21 -05002937 if (!TWFunc::Path_Exists(full_filename)) {
2938 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002939 return false;
2940 }
2941 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002942
Ethan Yonker53796e72019-01-11 22:49:52 -06002943 DataManager::GetValue("tw_flash_partition", Flash_List);
2944 Repack_Type repack = REPLACE_NONE;
2945 if (Flash_List == "/repack_ramdisk;") {
2946 repack = REPLACE_RAMDISK;
2947 } else if (Flash_List == "/repack_kernel;") {
2948 repack = REPLACE_KERNEL;
2949 }
2950 if (repack != REPLACE_NONE) {
2951 Repack_Options_struct Repack_Options;
2952 Repack_Options.Type = repack;
2953 Repack_Options.Disable_Verity = false;
2954 Repack_Options.Disable_Force_Encrypt = false;
2955 Repack_Options.Backup_First = DataManager::GetIntValue("tw_repack_backup_first") != 0;
bigbiffad58e1b2020-07-06 20:24:34 -04002956 return repacker.Repack_Image_And_Flash(full_filename, Repack_Options);
Ethan Yonker53796e72019-01-11 22:49:52 -06002957 }
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002958 PartitionSettings part_settings;
2959 part_settings.Backup_Folder = path;
2960 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
2961 ProgressTracking progress(total_bytes);
2962 part_settings.progress = &progress;
2963 part_settings.adbbackup = false;
2964 part_settings.PM_Method = PM_RESTORE;
Ethan Yonker74db1572015-10-28 12:44:49 -05002965 gui_msg("calc_restore=Calculating restore details...");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002966 if (!Flash_List.empty()) {
2967 end_pos = Flash_List.find(";", start_pos);
2968 while (end_pos != string::npos && start_pos < Flash_List.size()) {
2969 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
2970 flash_part = Find_Partition_By_Path(flash_path);
2971 if (flash_part != NULL) {
2972 partition_count++;
2973 if (partition_count > 1) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002974 gui_err("too_many_flash=Too many partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002975 return false;
2976 }
2977 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002978 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
Ethan Yonker96af84a2015-01-05 14:58:36 -06002979 return false;
2980 }
2981 start_pos = end_pos + 1;
2982 end_pos = Flash_List.find(";", start_pos);
2983 }
2984 }
2985
2986 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002987 gui_err("no_part_flash=No partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002988 return false;
2989 }
2990
2991 DataManager::SetProgress(0.0);
2992 if (flash_part) {
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002993 flash_part->Backup_FileName = filename;
2994 if (!flash_part->Flash_Image(&part_settings))
Ethan Yonker96af84a2015-01-05 14:58:36 -06002995 return false;
2996 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002997 gui_err("invalid_flash=Invalid flash partition specified.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002998 return false;
2999 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003000 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003001 return true;
3002}
Ethan Yonker74db1572015-10-28 12:44:49 -05003003
3004void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
3005 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3006 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003007 if (part->Is_Adopted_Storage) {
3008 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3009 part->Backup_Display_Name = part->Display_Name;
3010 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3011 } else {
3012 part->Display_Name = gui_lookup(resource_name, default_value);
3013 part->Backup_Display_Name = part->Display_Name;
3014 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003015 }
3016}
3017
3018void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
3019 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3020 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003021 if (part->Is_Adopted_Storage) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003022 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
Ethan Yonker66a19492015-12-10 10:19:45 -06003023 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
Ethan Yonker66a19492015-12-10 10:19:45 -06003024 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3025 } else {
3026 part->Display_Name = gui_lookup(resource_name, default_value);
3027 part->Backup_Display_Name = part->Display_Name;
3028 if (part->Is_Storage)
3029 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3030 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003031 }
3032}
3033
Ethan Yonker01f4e032017-02-03 15:30:52 -06003034void 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) {
3035 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3036 if (part) {
3037 if (part->Is_Adopted_Storage) {
3038 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
3039 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3040 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3041 } else {
3042 part->Display_Name = gui_lookup(resource_name, default_value);
3043 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
3044 if (part->Is_Storage)
3045 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3046 }
3047 }
3048}
3049
Ethan Yonker74db1572015-10-28 12:44:49 -05003050void TWPartitionManager::Translate_Partition_Display_Names() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003051 LOGINFO("Translating partition display names\n");
Ethan Yonker74db1572015-10-28 12:44:49 -05003052 Translate_Partition("/system", "system", "System");
3053 Translate_Partition("/system_image", "system_image", "System Image");
3054 Translate_Partition("/vendor", "vendor", "Vendor");
3055 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
3056 Translate_Partition("/cache", "cache", "Cache");
Ethan Yonker74db1572015-10-28 12:44:49 -05003057 Translate_Partition("/boot", "boot", "Boot");
3058 Translate_Partition("/recovery", "recovery", "Recovery");
3059 if (!datamedia) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003060 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
Ethan Yonker74db1572015-10-28 12:44:49 -05003061 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3062 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
3063 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3064 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
Ethan Yonker01f4e032017-02-03 15:30:52 -06003065 } else {
3066 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003067 }
Ethan Yonker01f4e032017-02-03 15:30:52 -06003068 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
3069 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003070 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
3071 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
3072
3073 // Android secure is a special case
3074 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
3075 if (part)
3076 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
3077
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003078 std::vector<TWPartition*>::iterator sysfs;
3079 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
3080 if (!(*sysfs)->Sysfs_Entry.empty()) {
3081 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
3082 }
3083 }
3084
Ethan Yonker74db1572015-10-28 12:44:49 -05003085 // This updates the text on all of the storage selection buttons in the GUI
3086 DataManager::SetBackupFolder();
3087}
Ethan Yonker66a19492015-12-10 10:19:45 -06003088
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003089bool TWPartitionManager::Decrypt_Adopted() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003090#ifdef TW_INCLUDE_CRYPTO
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003091 bool ret = false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003092 if (!Mount_By_Path("/data", false)) {
3093 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003094 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003095 }
Darth98f775972022-08-05 09:39:03 +01003096
3097 std::string path = "/data/system/storage.xml";
3098 if (!TWFunc::Check_Xml_Format(path)) {
3099 std::string oldpath = path;
3100 if (TWFunc::abx_to_xml(oldpath, path)) {
3101 LOGINFO("Android 12+: '%s' has been converted into plain text xml (%s).\n", oldpath.c_str(), path.c_str());
3102 }
3103 }
3104
Fernando Oliveira25062d72023-02-01 12:52:32 -03003105 //Devices without encryption do not run the Post_Decrypt function so the "data/recovery" folder was not being created on these devices
3106 DataManager::SetValue("tw_settings_path", TW_STORAGE_PATH);
Ethan Yonker66a19492015-12-10 10:19:45 -06003107 LOGINFO("Decrypt adopted storage starting\n");
Darth98f775972022-08-05 09:39:03 +01003108 char* xmlFile = PageManager::LoadFileToBuffer(path, NULL);
Ethan Yonker66a19492015-12-10 10:19:45 -06003109 xml_document<> *doc = NULL;
3110 xml_node<>* volumes = NULL;
Ethan Yonker66a19492015-12-10 10:19:45 -06003111 string Primary_Storage_UUID = "";
3112 if (xmlFile != NULL) {
3113 LOGINFO("successfully loaded storage.xml\n");
3114 doc = new xml_document<>();
3115 doc->parse<0>(xmlFile);
3116 volumes = doc->first_node("volumes");
3117 if (volumes) {
3118 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
3119 if (psuuid) {
3120 Primary_Storage_UUID = psuuid->value();
3121 }
3122 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003123 } else {
3124 LOGINFO("No /data/system/storage.xml for adopted storage\n");
3125 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003126 }
3127 std::vector<TWPartition*>::iterator adopt;
3128 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
Peter Cai439d60c2019-10-17 08:49:10 +08003129 if ((*adopt)->Removable && !(*adopt)->Is_Present && (*adopt)->Adopted_Mount_Delay > 0) {
3130 // On some devices, the external mmc driver takes some time
3131 // to recognize the card, in which case the "actual block device"
3132 // would not have been found yet. We wait the specified delay
3133 // and then try again.
3134 LOGINFO("Sleeping %d seconds for adopted storage.\n", (*adopt)->Adopted_Mount_Delay);
3135 sleep((*adopt)->Adopted_Mount_Delay);
3136 (*adopt)->Find_Actual_Block_Device();
3137 }
3138
Ethan Yonker66a19492015-12-10 10:19:45 -06003139 if ((*adopt)->Removable && (*adopt)->Is_Present) {
3140 if ((*adopt)->Decrypt_Adopted() == 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003141 ret = true;
Ethan Yonker66a19492015-12-10 10:19:45 -06003142 if (volumes) {
3143 xml_node<>* volume = volumes->first_node("volume");
3144 while (volume) {
3145 xml_attribute<>* guid = volume->first_attribute("partGuid");
3146 if (guid) {
3147 string GUID = (*adopt)->Adopted_GUID.c_str();
3148 GUID.insert(8, "-");
3149 GUID.insert(13, "-");
3150 GUID.insert(18, "-");
3151 GUID.insert(23, "-");
3152
3153 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
3154 xml_attribute<>* attr = volume->first_attribute("nickname");
nkk71ffb02bd2017-06-04 23:12:16 +03003155 if (attr && attr->value() && strlen(attr->value()) > 0) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003156 (*adopt)->Storage_Name = attr->value();
3157 (*adopt)->Display_Name = (*adopt)->Storage_Name;
3158 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
3159 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
3160 }
3161 attr = volume->first_attribute("fsUuid");
3162 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
3163 TWPartition* Dat = Find_Partition_By_Path("/data");
3164 if (Dat) {
3165 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
3166 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
3167 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
3168 Dat->Symlink_Mount_Point = "";
3169 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
3170 Dat->UnMount(false);
3171 Dat->Mount(false);
3172 (*adopt)->UnMount(false);
3173 (*adopt)->Mount(false);
Ethan Yonker66a19492015-12-10 10:19:45 -06003174 }
3175 }
3176 break;
3177 }
3178 }
3179 volume = volume->next_sibling("volume");
3180 }
3181 }
nkk71ffb02bd2017-06-04 23:12:16 +03003182 Update_System_Details();
3183 Output_Partition((*adopt));
Ethan Yonker66a19492015-12-10 10:19:45 -06003184 }
3185 }
3186 }
3187 if (xmlFile) {
3188 doc->clear();
3189 delete doc;
3190 free(xmlFile);
3191 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003192 return ret;
Ethan Yonker66a19492015-12-10 10:19:45 -06003193#else
3194 LOGINFO("Decrypt_Adopted: no crypto support\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003195 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003196#endif
3197}
Ethan Yonkerfcf3f242016-02-16 12:30:26 -06003198
3199void TWPartitionManager::Remove_Partition_By_Path(string Path) {
3200 std::vector<TWPartition*>::iterator iter;
3201 string Local_Path = TWFunc::Get_Root_Path(Path);
3202
3203 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3204 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
3205 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
3206 Partitions.erase(iter);
3207 return;
3208 }
3209 }
3210}
Ethan Yonker1b190162016-12-05 15:25:19 -06003211
bigbiff74a46272021-07-31 19:02:26 -04003212void TWPartitionManager::Override_Active_Slot(const string& Slot) {
3213 LOGINFO("Overriding slot to '%s'\n", Slot.c_str());
3214 Active_Slot_Display = Slot;
3215 DataManager::SetValue("tw_active_slot", Slot);
nebrassy07c4b902021-11-21 03:32:47 +01003216 PartitionManager.Update_System_Details();
bigbiff74a46272021-07-31 19:02:26 -04003217}
3218
Ethan Yonker1b190162016-12-05 15:25:19 -06003219void TWPartitionManager::Set_Active_Slot(const string& Slot) {
3220 if (Slot != "A" && Slot != "B") {
3221 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
3222 return;
3223 }
3224 if (Active_Slot_Display == Slot)
3225 return;
3226 LOGINFO("Setting active slot %s\n", Slot.c_str());
3227#ifdef AB_OTA_UPDATER
3228 if (!Active_Slot_Display.empty()) {
dianlujitaoa90dc462021-12-16 16:56:26 +08003229 android::sp<IBootControl> module = IBootControl::getService();
3230 if (module == nullptr) {
Ethan Yonker1b190162016-12-05 15:25:19 -06003231 LOGERR("Error getting bootctrl module.\n");
3232 } else {
dianlujitaoa90dc462021-12-16 16:56:26 +08003233 uint32_t slot_number = 0;
Ethan Yonker1b190162016-12-05 15:25:19 -06003234 if (Slot == "B")
3235 slot_number = 1;
dianlujitaoa90dc462021-12-16 16:56:26 +08003236 CommandResult result;
3237 auto ret = module->setActiveBootSlot(slot_number, [&result]
3238 (const CommandResult &cb_result) { result = cb_result; });
3239 if (!ret.isOk() || !result.success)
Ethan Yonker1b190162016-12-05 15:25:19 -06003240 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
3241 }
3242 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
3243 }
3244#else
3245 LOGERR("Boot slot feature not present\n");
3246#endif
3247 Active_Slot_Display = Slot;
3248 if (Fstab_Processed())
3249 Update_System_Details();
3250}
3251string TWPartitionManager::Get_Active_Slot_Suffix() {
3252 if (Active_Slot_Display == "A")
3253 return "_a";
3254 return "_b";
3255}
3256string TWPartitionManager::Get_Active_Slot_Display() {
3257 return Active_Slot_Display;
3258}
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003259
Captain Throwback9d6feb52018-07-27 10:05:24 -04003260string TWPartitionManager::Get_Android_Root_Path() {
bigbiff8da46fa2020-09-08 16:42:34 -04003261 return "/system_root";
Captain Throwback9d6feb52018-07-27 10:05:24 -04003262}
3263
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003264void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
3265 std::vector<TWPartition*>::iterator iter;
3266
3267 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
3268 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
3269 TWPartition *part = *iter;
3270 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
3271 (*iter)->UnMount(false);
3272 rmdir((*iter)->Mount_Point.c_str());
3273 iter = Partitions.erase(iter);
3274 delete part;
3275 } else {
3276 iter++;
3277 }
3278 }
3279}
3280
3281void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
3282 std::vector<TWPartition*>::iterator iter;
3283
3284 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3285 if (!(*iter)->Sysfs_Entry.empty()) {
3286 string device;
3287 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
3288 if (wildcard != string::npos) {
3289 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
3290 } else {
3291 device = (*iter)->Sysfs_Entry;
3292 }
3293 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
3294 // Found a match
3295 if (uevent_data.action == "add") {
3296 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
3297 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
3298 (*iter)->Is_Present = true;
3299 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
3300 if (!Decrypt_Adopted()) {
3301 LOGINFO("No adopted storage so finding actual block device\n");
3302 (*iter)->Find_Actual_Block_Device();
3303 }
3304 return;
3305 } else if (uevent_data.action == "remove") {
3306 (*iter)->Is_Present = false;
3307 (*iter)->Primary_Block_Device = "";
3308 (*iter)->Actual_Block_Device = "";
3309 Remove_Uevent_Devices((*iter)->Mount_Point);
3310 return;
3311 }
3312 }
3313 }
3314 }
bigbiffee7b7ff2020-03-23 15:08:27 -04003315
3316 if (!PartitionManager.Get_Super_Status())
3317 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 -06003318}
3319
3320void TWPartitionManager::setup_uevent() {
3321 struct sockaddr_nl nls;
3322
3323 if (uevent_pfd.fd >= 0) {
3324 LOGINFO("uevent already set up\n");
3325 return;
3326 }
3327
3328 // Open hotplug event netlink socket
3329 memset(&nls,0,sizeof(struct sockaddr_nl));
3330 nls.nl_family = AF_NETLINK;
3331 nls.nl_pid = getpid();
3332 nls.nl_groups = -1;
3333 uevent_pfd.events = POLLIN;
3334 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
3335 if (uevent_pfd.fd==-1) {
3336 LOGERR("uevent not root\n");
3337 return;
3338 }
3339
3340 // Listen to netlink socket
3341 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
3342 LOGERR("Bind failed\n");
3343 return;
3344 }
3345 set_select_fd();
3346 Coldboot();
3347}
3348
3349Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
3350 Uevent_Block_Data ret;
3351 ret.subsystem = "";
3352 char *ptr = buf;
3353 const char *end = buf + len;
3354
3355 buf[len - 1] = '\0';
3356 while (ptr < end) {
3357 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
3358 ptr += strlen("ACTION=");
3359 ret.action = ptr;
3360 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
3361 ptr += strlen("SUBSYSTEM=");
3362 ret.subsystem = ptr;
3363 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
3364 ptr += strlen("DEVTYPE=");
3365 ret.type = ptr;
3366 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
3367 ptr += strlen("DEVPATH=");
3368 ret.sysfs_path += ptr;
3369 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
3370 ptr += strlen("DEVNAME=");
3371 ret.block_device += ptr;
3372 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
3373 ptr += strlen("MAJOR=");
3374 ret.major = atoi(ptr);
3375 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
3376 ptr += strlen("MINOR=");
3377 ret.minor = atoi(ptr);
3378 }
3379 ptr += strlen(ptr) + 1;
3380 }
3381 return ret;
3382}
3383
3384void TWPartitionManager::read_uevent() {
3385 char buf[1024];
3386
3387 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
3388 if (len == -1) {
Mauronofrio Matarresec1bb76e2019-08-04 17:02:41 +01003389 LOGINFO("recv error on uevent\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003390 return;
3391 }
3392 /*int i = 0; // Print all uevent output for test /debug
3393 while (i<len) {
3394 printf("%s\n", buf+i);
3395 i += strlen(buf+i)+1;
3396 }*/
3397 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
3398 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
3399 PartitionManager.Handle_Uevent(uevent_data);
3400 }
3401}
3402
3403void TWPartitionManager::close_uevent() {
3404 if (uevent_pfd.fd > 0)
3405 close(uevent_pfd.fd);
3406 uevent_pfd.fd = -1;
3407}
3408
3409void TWPartitionManager::Add_Partition(TWPartition* Part) {
3410 Partitions.push_back(Part);
3411}
3412
3413void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
3414 string Real_Path = Path;
3415 char real_path[PATH_MAX];
3416 if (realpath(Path.c_str(), &real_path[0])) {
3417 string Real_Path = real_path;
3418 std::vector<string>::iterator iter;
3419 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
3420 if (Real_Path.find((*iter)) != string::npos) {
3421 string Write_Path = Real_Path + "/uevent";
3422 if (TWFunc::Path_Exists(Write_Path)) {
3423 const char* write_val = "add\n";
3424 TWFunc::write_to_file(Write_Path, write_val);
3425 break;
3426 }
3427 }
3428 }
3429 }
3430
3431 DIR* d = opendir(Path.c_str());
3432 if (d != NULL) {
3433 struct dirent* de;
3434 while ((de = readdir(d)) != NULL) {
3435 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
3436 continue;
3437 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
3438 continue;
3439
3440 string item = Path + "/";
3441 item.append(de->d_name);
3442 Coldboot_Scan(sysfs_entries, item, depth + 1);
3443 }
3444 closedir(d);
3445 }
3446}
3447
3448void TWPartitionManager::Coldboot() {
3449 std::vector<TWPartition*>::iterator iter;
3450 std::vector<string> sysfs_entries;
3451
3452 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3453 if (!(*iter)->Sysfs_Entry.empty()) {
3454 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
3455 if (wildcard_pos == string::npos)
3456 wildcard_pos = (*iter)->Sysfs_Entry.size();
3457 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
3458 }
3459 }
3460
3461 if (sysfs_entries.size() > 0)
3462 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
3463}
Ethan Yonker53796e72019-01-11 22:49:52 -06003464
3465bool TWPartitionManager::Prepare_Empty_Folder(const std::string& Folder) {
3466 if (TWFunc::Path_Exists(Folder))
3467 TWFunc::removeDir(Folder, false);
3468 return TWFunc::Recursive_Mkdir(Folder);
3469}
3470
bigbiffcfa875c2021-06-20 16:20:27 -04003471std::string TWPartitionManager::Get_Bare_Partition_Name(std::string Mount_Point) {
3472 if (Mount_Point == "/system_root")
3473 return "system";
3474 else
3475 return TWFunc::Remove_Beginning_Slash(Mount_Point);
3476}
3477
bigbiffee7b7ff2020-03-23 15:08:27 -04003478bool TWPartitionManager::Prepare_Super_Volume(TWPartition* twrpPart) {
3479 Fstab fstab;
bigbiffcfa875c2021-06-20 16:20:27 -04003480 std::string bare_partition_name = Get_Bare_Partition_Name(twrpPart->Get_Mount_Point());
bigbiffee7b7ff2020-03-23 15:08:27 -04003481
bigbiff998f8392021-08-06 19:19:33 -04003482 Super_Partition_List.push_back(bare_partition_name);
bigbiffee7b7ff2020-03-23 15:08:27 -04003483 LOGINFO("Trying to prepare %s from super partition\n", bare_partition_name.c_str());
3484
3485 std::string blk_device_partition;
3486#ifdef AB_OTA_UPDATER
3487 blk_device_partition = bare_partition_name + PartitionManager.Get_Active_Slot_Suffix();
3488#else
3489 blk_device_partition = bare_partition_name;
3490#endif
3491
3492 FstabEntry fstabEntry = {
3493 .blk_device = blk_device_partition,
3494 .mount_point = twrpPart->Get_Mount_Point(),
3495 .fs_type = twrpPart->Current_File_System,
3496 .fs_mgr_flags.logical = twrpPart->Is_Super,
3497 };
3498
3499 fstab.emplace_back(fstabEntry);
3500 if (!fs_mgr_update_logical_partition(&fstabEntry)) {
Captain Throwbackc6939102021-04-06 12:57:30 -04003501 LOGINFO("unable to update logical partition: %s\n", twrpPart->Get_Mount_Point().c_str());
bigbiffee7b7ff2020-03-23 15:08:27 -04003502 return false;
3503 }
3504
bigbiff32cbabe2020-04-12 19:16:19 -04003505 while (access(fstabEntry.blk_device.c_str(), F_OK) != 0) {
3506 usleep(100);
3507 }
3508
bigbiffee7b7ff2020-03-23 15:08:27 -04003509 twrpPart->Set_Block_Device(fstabEntry.blk_device);
3510 twrpPart->Update_Size(true);
bigbiffee7b7ff2020-03-23 15:08:27 -04003511 twrpPart->Set_Can_Be_Backed_Up(false);
3512 twrpPart->Set_Can_Be_Wiped(false);
me-cafebabe928234b2022-07-28 04:07:04 +08003513 if (access(("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str(), F_OK) == -1) {
3514 LOGINFO("Symlinking %s => /dev/block/bootdevice/by-name/%s \n", fstabEntry.blk_device.c_str(), bare_partition_name.c_str());
3515 symlink(fstabEntry.blk_device.c_str(), ("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str());
Captain Throwback88c6e652023-01-16 15:32:26 -05003516 property_set("twrp.super.symlinks_created", "true");
me-cafebabe928234b2022-07-28 04:07:04 +08003517 }
Mohd Faraz7fc70502021-04-22 20:44:11 +02003518
bigbiffee7b7ff2020-03-23 15:08:27 -04003519 return true;
3520}
3521
3522bool TWPartitionManager::Prepare_All_Super_Volumes() {
3523 bool status = true;
3524 std::vector<TWPartition*>::iterator iter;
3525
3526 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3527 if ((*iter)->Is_Super) {
3528 if (!Prepare_Super_Volume(*iter)) {
3529 status = false;
Mohd Faraz787cc612023-01-02 22:47:51 +01003530 Partitions.erase(iter--);
bigbiffee7b7ff2020-03-23 15:08:27 -04003531 }
3532 PartitionManager.Output_Partition(*iter);
3533 }
3534 }
3535 Update_System_Details();
3536 return status;
3537}
3538
bigbiffee7b7ff2020-03-23 15:08:27 -04003539std::string TWPartitionManager::Get_Super_Partition() {
3540 int slot_number = Get_Active_Slot_Display() == "A" ? 0 : 1;
bigbiff998f8392021-08-06 19:19:33 -04003541 std::string super_device = fs_mgr_get_super_partition_name(slot_number);
bigbiffee7b7ff2020-03-23 15:08:27 -04003542 return "/dev/block/by-name/" + super_device;
3543}
3544
3545void TWPartitionManager::Setup_Super_Devices() {
3546 std::string superPart = Get_Super_Partition();
3547 android::fs_mgr::CreateLogicalPartitions(superPart);
bigbiff7ba75002020-04-11 20:47:09 -04003548}
3549
3550void TWPartitionManager::Setup_Super_Partition() {
bigbiffee7b7ff2020-03-23 15:08:27 -04003551 TWPartition* superPartition = new TWPartition();
bigbiff7ba75002020-04-11 20:47:09 -04003552 std::string superPart = Get_Super_Partition();
3553
3554 superPartition->Backup_Path = "/super";
3555 superPartition->Mount_Point = "/super";
bigbiffee7b7ff2020-03-23 15:08:27 -04003556 superPartition->Actual_Block_Device = superPart;
3557 superPartition->Alternate_Block_Device = superPart;
bigbiff998f8392021-08-06 19:19:33 -04003558 superPartition->Backup_Display_Name = "Super (";
3559 // Add first 4 items to fstab as logical that you would like to display in Backup_Display_Name
3560 // for the Super partition
3561 int list_size = Super_Partition_List.size();
3562 int orig_list_size = list_size;
3563 int max_display_size = 3; // total of 4 items since we start at 0
3564
3565 for (auto partition: Super_Partition_List) {
3566 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + partition;
3567 if ((orig_list_size - list_size) == max_display_size) {
3568 break;
3569 }
3570 if (list_size != 1)
3571 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + " ";
3572 list_size--;
3573 }
3574 superPartition->Backup_Display_Name += ")";
bigbiffee7b7ff2020-03-23 15:08:27 -04003575 superPartition->Can_Flash_Img = true;
bigbiffee7b7ff2020-03-23 15:08:27 -04003576 superPartition->Current_File_System = "emmc";
3577 superPartition->Can_Be_Backed_Up = true;
3578 superPartition->Is_Present = true;
3579 superPartition->Is_SubPartition = false;
bigbiff7ba75002020-04-11 20:47:09 -04003580 superPartition->Setup_Image();
bigbiffee7b7ff2020-03-23 15:08:27 -04003581 Add_Partition(superPartition);
3582 PartitionManager.Output_Partition(superPartition);
bigbiffee7b7ff2020-03-23 15:08:27 -04003583}
3584
3585bool TWPartitionManager::Get_Super_Status() {
Mohd Faraz88b4bab2023-01-01 02:43:01 +05303586 return access(Get_Super_Partition().c_str(), F_OK) == 0;
bigbiffee7b7ff2020-03-23 15:08:27 -04003587}
bigbiff25d25b92020-06-19 16:07:38 -04003588
3589bool TWPartitionManager::Recreate_Logs_Dir() {
3590#ifdef TW_INCLUDE_FBE
3591 struct passwd pd;
3592 struct passwd *pwdptr = &pd;
3593 struct passwd *tempPd;
3594 char pwdBuf[512];
3595 int uid = 0, gid = 0;
3596
3597 if ((getpwnam_r("system", pwdptr, pwdBuf, sizeof(pwdBuf), &tempPd)) != 0) {
3598 LOGERR("unable to get system user id\n");
3599 return false;
3600 } else {
3601 struct group grp;
3602 struct group *grpptr = &grp;
3603 struct group *tempGrp;
3604 char grpBuf[512];
3605
3606 if ((getgrnam_r("cache", grpptr, grpBuf, sizeof(grpBuf), &tempGrp)) != 0) {
3607 LOGERR("unable to get cache group id\n");
3608 return false;
3609 } else {
3610 uid = pd.pw_uid;
3611 gid = grp.gr_gid;
3612 std::string abLogsRecoveryDir(DATA_LOGS_DIR);
3613 abLogsRecoveryDir += "/recovery/";
3614
3615 if (!TWFunc::Create_Dir_Recursive(abLogsRecoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
3616 LOGERR("Unable to recreate %s\n", abLogsRecoveryDir.c_str());
3617 return false;
3618 }
3619 if (setfilecon(abLogsRecoveryDir.c_str(), "u:object_r:cache_file:s0") != 0) {
3620 LOGERR("Unable to set contexts for %s\n", abLogsRecoveryDir.c_str());
3621 return false;
3622 }
3623 }
3624 }
3625#endif
3626 return true;
3627}
bigbiff1f9e4842020-10-31 11:33:15 -04003628
3629void TWPartitionManager::Unlock_Block_Partitions() {
3630 int fd, OFF = 0;
3631
3632 const std::string block_path = "/dev/block/";
3633 DIR* d = opendir(block_path.c_str());
3634 if (d != NULL) {
3635 struct dirent* de;
3636 while ((de = readdir(d)) != NULL) {
3637 if (de->d_type == DT_BLK) {
3638 std::string block_device = block_path + de->d_name;
bigbiff1f9e4842020-10-31 11:33:15 -04003639 if ((fd = open(block_device.c_str(), O_RDONLY | O_CLOEXEC)) < 0) {
3640 LOGERR("unable to open block device %s: %s\n", block_device.c_str(), strerror(errno));
3641 continue;
3642 }
3643 if (ioctl(fd, BLKROSET, &OFF) == -1) {
me-cafebabed63fcaa2022-07-28 03:19:20 +08003644 LOGERR("Unable to unlock %s: %s\n", block_device.c_str());
bigbiff1f9e4842020-10-31 11:33:15 -04003645 continue;
3646 }
3647 close(fd);
3648 }
3649 }
3650 closedir(d);
3651 }
bigbiffaf253cd2020-12-06 16:50:55 -05003652}
bigbiffcfa875c2021-06-20 16:20:27 -04003653
3654bool TWPartitionManager::Unmap_Super_Devices() {
3655 bool destroyed = false;
3656#ifndef TW_EXCLUDE_APEX
3657 twrpApex apex;
3658 apex.Unmount();
3659#endif
3660 for (auto iter = Partitions.begin(); iter != Partitions.end();) {
3661 LOGINFO("Checking partition: %s\n", (*iter)->Get_Mount_Point().c_str());
3662 if ((*iter)->Is_Super) {
3663 TWPartition *part = *iter;
3664 std::string bare_partition_name = Get_Bare_Partition_Name((*iter)->Get_Mount_Point());
me-cafebabe2136fc52022-07-20 06:42:18 +08003665 std::string blk_device_partition = bare_partition_name;
3666 if (DataManager::GetStrValue(TW_VIRTUAL_AB_ENABLED) == "1")
3667 blk_device_partition.append(PartitionManager.Get_Active_Slot_Suffix());
bigbiffcfa875c2021-06-20 16:20:27 -04003668 (*iter)->UnMount(false);
3669 LOGINFO("removing dynamic partition: %s\n", blk_device_partition.c_str());
3670 destroyed = DestroyLogicalPartition(blk_device_partition);
3671 std::string cow_partition = blk_device_partition + "-cow";
3672 std::string cow_partition_path = "/dev/block/mapper/" + cow_partition;
3673 struct stat st;
3674 if (lstat(cow_partition_path.c_str(), &st) == 0) {
3675 LOGINFO("removing cow partition: %s\n", cow_partition.c_str());
3676 destroyed = DestroyLogicalPartition(cow_partition);
3677 }
bigbiffcfa875c2021-06-20 16:20:27 -04003678 iter = Partitions.erase(iter);
3679 delete part;
3680 if (!destroyed) {
3681 return false;
3682 }
3683 } else {
3684 ++iter;
3685 }
3686 }
3687 return true;
3688}
bigbiffd21252f2021-09-18 15:56:32 -04003689
3690
3691bool TWPartitionManager::Check_Pending_Merges() {
3692 auto sm = android::snapshot::SnapshotManager::NewForFirstStageMount();
3693 if (!sm) {
3694 LOGERR("Unable to call snapshot manager\n");
3695 return false;
3696 }
3697
3698 if (!Unmap_Super_Devices()) {
3699 LOGERR("Unable to unmap dynamic partitions.\n");
3700 return false;
3701 }
3702
3703 auto callback = [&]() -> void {
3704 double progress;
3705 sm->GetUpdateState(&progress);
3706 LOGINFO("waiting for merge to complete: %.2f\n", progress);
3707 };
3708
3709 LOGINFO("checking for merges\n");
3710 if (!sm->HandleImminentDataWipe(callback)) {
3711 LOGERR("Unable to check merge status\n");
3712 return false;
3713 }
3714 return true;
Darth98f775972022-08-05 09:39:03 +01003715}