blob: f900d9c1d5d9e9a87443a7cce4bf05e25f47d427 [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
Mohd Farazfe8bcd42023-08-26 20:50:26 +053078#ifdef TW_LOAD_VENDOR_MODULES
79#include "kernel_module_loader.hpp"
80#endif
81
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040082#ifdef TW_HAS_MTP
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -050083#ifdef TW_HAS_LEGACY_MTP
84#include "mtp/legacy/mtp_MtpServer.hpp"
85#include "mtp/legacy/twrpMtp.hpp"
86#include "mtp/legacy/MtpMessage.hpp"
87#else
88#include "mtp/ffs/mtp_MtpServer.hpp"
89#include "mtp/ffs/twrpMtp.hpp"
90#include "mtp/ffs/MtpMessage.hpp"
91#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040092#endif
93
Dees Troy6f6441d2014-01-23 02:07:03 +000094extern "C" {
95 #include "cutils/properties.h"
Ethan Yonker74db1572015-10-28 12:44:49 -050096 #include "gui/gui.h"
Dees Troy6f6441d2014-01-23 02:07:03 +000097}
98
Dees_Troy5bf43922012-09-07 16:07:55 -040099#ifdef TW_INCLUDE_CRYPTO
bigbiffdf53b6c2022-01-17 19:31:52 -0500100// #include "crypto/fde/cryptfs.h"
bigbiff7ba75002020-04-11 20:47:09 -0400101#include "gui/rapidxml.hpp"
102#include "gui/pages.hpp"
103#ifdef TW_INCLUDE_FBE
bigbiffa957f072021-03-07 18:20:29 -0500104#include "Decrypt.h"
bigbiff7ba75002020-04-11 20:47:09 -0400105#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
106 #ifdef USE_FSCRYPT
bigbiffdf53b6c2022-01-17 19:31:52 -0500107 #include "cryptfs.h"
108 #include "fscrypt-common.h"
bigbiffa957f072021-03-07 18:20:29 -0500109 #include "MetadataCrypt.h"
bigbiffadc599e2020-05-28 19:36:30 +0000110 #endif
bigbiff7ba75002020-04-11 20:47:09 -0400111#endif
112#endif
Dees_Troy5bf43922012-09-07 16:07:55 -0400113#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400114
Ethan Yonker1b190162016-12-05 15:25:19 -0600115#ifdef AB_OTA_UPDATER
dianlujitaoa90dc462021-12-16 16:56:26 +0800116#include <android/hardware/boot/1.0/IBootControl.h>
117using android::hardware::boot::V1_0::CommandResult;
118using android::hardware::boot::V1_0::IBootControl;
Ethan Yonker1b190162016-12-05 15:25:19 -0600119#endif
120
bigbiffcfa875c2021-06-20 16:20:27 -0400121using android::fs_mgr::DestroyLogicalPartition;
bigbiffee7b7ff2020-03-23 15:08:27 -0400122using android::fs_mgr::Fstab;
123using android::fs_mgr::FstabEntry;
bigbiffcfa875c2021-06-20 16:20:27 -0400124using android::fs_mgr::MetadataBuilder;
Ethan Yonker6277c792014-09-15 14:54:30 -0500125
bigbiffee7b7ff2020-03-23 15:08:27 -0400126extern bool datamedia;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400127std::vector<users_struct> Users_List;
128
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100129std::string additional_fstab = "/etc/additional.fstab";
130
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500131TWPartitionManager::TWPartitionManager(void) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -0400132 mtp_was_enabled = false;
Ethan Yonker726a0202014-12-16 20:01:38 -0600133 mtp_write_fd = -1;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600134 uevent_pfd.fd = -1;
bigbiff7abc5fe2015-01-17 16:53:12 -0500135 stop_backup.set_value(0);
Ethan Yonker1b190162016-12-05 15:25:19 -0600136#ifdef AB_OTA_UPDATER
137 char slot_suffix[PROPERTY_VALUE_MAX];
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500138 property_get("ro.boot.slot_suffix", slot_suffix, "error");
139 if (strcmp(slot_suffix, "error") == 0)
140 property_get("ro.boot.slot", slot_suffix, "error");
Ethan Yonker1b190162016-12-05 15:25:19 -0600141 Active_Slot_Display = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500142 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Ethan Yonker1b190162016-12-05 15:25:19 -0600143 Set_Active_Slot("A");
144 else
145 Set_Active_Slot("B");
146#endif
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500147}
148
Captain Throwback37c3aef2021-10-06 11:38:18 -0400149void TWPartitionManager::Set_Crypto_State() {
150 char crypto_state[PROPERTY_VALUE_MAX];
151 property_get("ro.crypto.state", crypto_state, "error");
152 if (strcmp(crypto_state, "error") == 0)
153 property_set("ro.crypto.state", "encrypted");
154}
155
156int TWPartitionManager::Set_Crypto_Type(const char* crypto_type) {
157 char type_prop[PROPERTY_VALUE_MAX];
158 property_get("ro.crypto.type", type_prop, "error");
159 if (strcmp(type_prop, "error") == 0)
160 property_set("ro.crypto.type", crypto_type);
Captain Throwback18aea272020-10-29 12:43:17 -0400161 // Sleep for a bit so that services can start if needed
162 sleep(1);
163 return 0;
164}
165
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100166void inline Reset_Prop_From_Partition(std::string prop, std::string def, TWPartition *ven, TWPartition *odm) {
167 bool prop_on_odm = false, prop_on_vendor = false;
168 string prop_value;
169 if (odm) {
170 string odm_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/odm", "etc/build.prop");
171 if (!odm_prop.empty()) {
172 prop_on_odm = true;
173 if (TWFunc::Property_Override(prop, odm_prop) == NOT_AVAILABLE) {
174 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
175 } else {
176 prop_value = android::base::GetProperty(prop, "");
177 LOGINFO("Setting '%s' to '%s' from /odm/etc/build.prop\n", prop.c_str(), prop_value.c_str());
178 }
179 }
180 }
181 if (ven) {
182 string vendor_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/vendor", "build.prop");
183 if (!vendor_prop.empty()) {
184 prop_on_vendor = true;
185 if (TWFunc::Property_Override(prop, vendor_prop) == NOT_AVAILABLE) {
186 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
187 } else {
188 prop_value = android::base::GetProperty(prop, "");
189 LOGINFO("Setting '%s' to '%s' from /vendor/build.prop\n", prop.c_str(), prop_value.c_str());
190 }
191 }
192 }
193 if (!prop_on_odm && !prop_on_vendor && !def.empty()) {
194 if (TWFunc::Property_Override(prop, def) == NOT_AVAILABLE) {
195 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
196 } else {
197 prop_value = android::base::GetProperty(prop, "");
198 LOGINFO("Setting '%s' to default value (%s)\n", prop.c_str(), prop_value.c_str());
199 }
200 }
201 prop_value = android::base::GetProperty(prop, "");
202 if (!prop_on_odm && !prop_on_vendor && !prop_value.empty() && def.empty()) {
203 if(TWFunc::Delete_Property(prop) == NOT_AVAILABLE) {
204 LOGERR("Unable to delete '%s' due to missing libresetprop\n", prop.c_str());
205 } else {
206 LOGINFO("Deleting property '%s'\n", prop.c_str());
207 }
208 }
209}
210
Mohd Faraza57874b2023-09-30 00:57:58 +0530211void inline Process_ResetProps(TWPartition *ven, TWPartition *odm) {
212 // Reset the crypto volume props according to os.
213 Reset_Prop_From_Partition("ro.crypto.dm_default_key.options_format.version", "", ven, odm);
214 Reset_Prop_From_Partition("ro.crypto.volume.metadata.method", "", ven, odm);
215 Reset_Prop_From_Partition("ro.crypto.volume.options", "", ven, odm);
216 Reset_Prop_From_Partition("external_storage.projid.enabled", "", ven, odm);
217 Reset_Prop_From_Partition("external_storage.casefold.enabled", "", ven, odm);
218 Reset_Prop_From_Partition("external_storage.sdcardfs.enabled", "", ven, odm);
219}
220
221static inline std::string KM_Ver_From_Manifest(std::string ver) {
222 TWFunc::Get_Service_From_Manifest("/vendor", "android.hardware.keymaster", ver);
223 if (strstr(ver.c_str(), "4")) {
224 ver = "4.x";
225 }
226 return ver;
227}
228
229void inline Process_Keymaster_Version(TWPartition *ven, bool Display_Error) {
230 // Fetch the Keymaster Service version to be started
231 std::string version;
232#ifndef TW_FORCE_KEYMASTER_VER
233 version = KM_Ver_From_Manifest(version);
234
235 /* If we are unable to get the version from device vendor then
236 * set the version from the keymaster_ver prop if set
237 */
238 if (version.empty()) {
239 // unmount partition(s)
240 if (ven) ven->UnMount(Display_Error);
241
242 // Use keymaster_ver prop set from device tree (if exists)
243 version = android::base::GetProperty(TW_KEYMASTER_VERSION_PROP, version);
244 if (version.empty()) {
245 LOGINFO("Keymaster_Ver::Unable to find vendor manifest on the device, and no default value set. Checking the ramdisk manifest\n");
246 version = KM_Ver_From_Manifest(version);
247 } else {
248 LOGINFO("Keymaster_Ver::Unable to find vendor manifest on the device. Setting to default value.\n");
249 }
250 } else {
251 if (ven) ven->UnMount(Display_Error);
252 }
253#else
254 if (ven) ven->UnMount(Display_Error);
255
256 version = android::base::GetProperty(TW_KEYMASTER_VERSION_PROP, version);
257 if (version.empty()) {
258 LOGINFO("Keymaster_Ver::Force Keymaster_Ver flag found, but keymaster_ver prop not set.\n");
259 } else {
260 LOGINFO("Keymaster_Ver::Force Keymaster_Ver flag found.\n");
261 }
262#endif
263 LOGINFO("Keymaster_Ver::Using keymaster version '%s' for decryption\n", version.c_str());
264 android::base::SetProperty(TW_KEYMASTER_VERSION_PROP, version.c_str());
265}
266
bigbiff22851b92021-09-01 16:46:57 -0400267int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool recovery_mode) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400268 FILE *fstabFile;
269 char fstab_line[MAX_FSTAB_LINE_LENGTH];
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100270 bool parse_userdata = false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600271 std::map<string, Flags_Map> twrp_flags;
272
273 fstabFile = fopen("/etc/twrp.flags", "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100274 if (Get_Super_Status()) {
275 Setup_Super_Devices();
276 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600277 if (fstabFile != NULL) {
Ian Macdonald160e8d32020-09-29 20:47:31 +0200278 LOGINFO("Reading /etc/twrp.flags\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600279 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600280 size_t line_size = strlen(fstab_line);
281 if (fstab_line[line_size - 1] != '\n')
282 fstab_line[line_size] = '\n';
283 Flags_Map line_flags;
284 line_flags.Primary_Block_Device = "";
285 line_flags.Alternate_Block_Device = "";
286 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
287 if (!line_flags.fstab_line) {
288 LOGERR("malloc error on line_flags.fstab_line\n");
289 return false;
290 }
291 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
292 bool found_separator = false;
293 char *fs_loc = NULL;
294 char *block_loc = NULL;
295 char *flags_loc = NULL;
296 size_t index, item_index = 0;
297 for (index = 0; index < line_size; index++) {
298 if (fstab_line[index] <= 32) {
299 fstab_line[index] = '\0';
300 found_separator = true;
301 } else if (found_separator) {
302 if (item_index == 0) {
303 fs_loc = fstab_line + index;
304 } else if (item_index == 1) {
305 block_loc = fstab_line + index;
306 } else if (item_index > 1) {
307 char *ptr = fstab_line + index;
308 if (*ptr == '/') {
309 line_flags.Alternate_Block_Device = ptr;
310 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
311 flags_loc = ptr;
312 // Once we find the flags=, we're done scanning the line
313 break;
314 }
315 }
316 found_separator = false;
317 item_index++;
318 }
319 }
320 if (block_loc)
321 line_flags.Primary_Block_Device = block_loc;
322 if (fs_loc)
323 line_flags.File_System = fs_loc;
324 if (flags_loc)
325 line_flags.Flags = flags_loc;
326 string Mount_Point = fstab_line;
327 twrp_flags[Mount_Point] = line_flags;
328 memset(fstab_line, 0, sizeof(fstab_line));
329 }
330 fclose(fstabFile);
331 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100332 TWPartition *data = NULL;
333 TWPartition *meta = NULL;
Mohd Faraza57874b2023-09-30 00:57:58 +0530334#ifndef TW_SKIP_ADDITIONAL_FSTAB
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100335parse:
Mohd Faraza57874b2023-09-30 00:57:58 +0530336#endif
Dees_Troy5bf43922012-09-07 16:07:55 -0400337 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100338 if (!parse_userdata && fstabFile == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000339 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400340 return false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600341 } else
342 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400343
344 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600345 if (strstr(fstab_line, "swap"))
346 continue; // Skip swap in recovery
347
bigbiff998f8392021-08-06 19:19:33 -0400348 if (fstab_line[0] == '#')
349 continue;
350
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100351 if (parse_userdata) {
352 if (strstr(fstab_line, "/metadata") && !strstr(fstab_line, "/data")) {
sekaiacg01ac7722023-08-01 09:32:00 +0800353 if (meta) {
354 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), meta));
355 delete meta;
356 meta = NULL;
357 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100358 } else if (strstr(fstab_line, "/data")) {
sekaiacg01ac7722023-08-01 09:32:00 +0800359 if (data) {
360 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), data));
361 delete data;
362 data = NULL;
363 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100364 } else {
365 continue;
366 }
367 }
368
369
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600370 size_t line_size = strlen(fstab_line);
371 if (fstab_line[line_size - 1] != '\n')
372 fstab_line[line_size] = '\n';
Dees_Troy2a923582012-09-20 12:13:34 -0400373
Matt Mower2b2dd152016-04-26 11:24:08 -0500374 TWPartition* partition = new TWPartition();
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100375 if (partition->Process_Fstab_Line(fstab_line, Display_Error, parse_userdata ? NULL : &twrp_flags)) {
376 if (partition->Mount_Point == "/data") data = partition;
377 if (partition->Mount_Point == "/metadata") meta = partition;
378 if (partition->Is_Super && !Prepare_Super_Volume(partition)) {
379 goto clear;
380 }
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500381 Partitions.push_back(partition);
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100382 }
Matt Mower72c87ce2016-04-26 14:34:56 -0500383 else
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100384clear:
Dees_Troy5bf43922012-09-07 16:07:55 -0400385 delete partition;
Matt Mower2b2dd152016-04-26 11:24:08 -0500386
387 memset(fstab_line, 0, sizeof(fstab_line));
Dees_Troy5bf43922012-09-07 16:07:55 -0400388 }
389 fclose(fstabFile);
Matt Mower72c87ce2016-04-26 14:34:56 -0500390
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100391 if (!parse_userdata && twrp_flags.size() > 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600392 LOGINFO("Processing remaining twrp.flags\n");
393 // Add any items from twrp.flags that did not exist in the recovery.fstab
394 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
395 if (Find_Partition_By_Path(mapit->first) == NULL) {
396 TWPartition* partition = new TWPartition();
bigbiff8da46fa2020-09-08 16:42:34 -0400397 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600398 Partitions.push_back(partition);
399 else
400 delete partition;
401 }
402 if (mapit->second.fstab_line)
403 free(mapit->second.fstab_line);
404 mapit->second.fstab_line = NULL;
405 }
406 }
Mohd Farazfe8bcd42023-08-26 20:50:26 +0530407
408#ifdef TW_LOAD_VENDOR_MODULES
409 KernelModuleLoader::Load_Vendor_Modules();
410#endif
411
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100412 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
413 TWPartition* odm = PartitionManager.Find_Partition_By_Path("/odm");
Mohd Farazfe8bcd42023-08-26 20:50:26 +0530414 if (recovery_mode && !parse_userdata) {
Mohd Farazec370452023-08-28 16:51:35 +0530415 if (ven) ven->Mount(Display_Error);
416 if (odm) odm->Mount(Display_Error);
Mohd Faraza57874b2023-09-30 00:57:58 +0530417
418 Process_ResetProps(ven, odm);
419 parse_userdata = true;
420
421#ifndef TW_SKIP_ADDITIONAL_FSTAB
422 // Now Fetch the additional fstab
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100423 if (TWFunc::Find_Fstab(Fstab_Filename)) {
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100424 LOGINFO("Fstab: %s\n", Fstab_Filename.c_str());
425 TWFunc::copy_file(Fstab_Filename, additional_fstab, 0600, false);
426 Fstab_Filename = additional_fstab;
427 property_set("fstab.additional", "1");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100428 goto parse;
429 } else {
430 LOGINFO("Unable to parse vendor fstab\n");
431 }
Mohd Faraze3948ec2020-08-14 01:40:59 +0000432 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600433 LOGINFO("Done processing fstab files\n");
Mohd Faraza57874b2023-09-30 00:57:58 +0530434#else
435 LOGINFO("Skipping Additional Fstab Processing\n");
436 property_set("fstab.additional", "0");
437 }
438#endif
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600439
Mohd Faraza57874b2023-09-30 00:57:58 +0530440 if (odm) odm->UnMount(Display_Error);
Captain Throwbackf2a4ef32024-02-07 16:12:24 -0500441 if (recovery_mode)
442 Process_Keymaster_Version(ven, false);
Mohd Faraza57874b2023-09-30 00:57:58 +0530443 if (ven) ven->UnMount(Display_Error);
bigbiff7ba75002020-04-11 20:47:09 -0400444 return true;
445}
446
bigbiff22851b92021-09-01 16:46:57 -0400447void TWPartitionManager::Setup_Fstab_Partitions(bool Display_Error) {
448 TWPartition* settings_partition = NULL;
449 TWPartition* andsec_partition = NULL;
450 std::vector<TWPartition*>::iterator iter;
451 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
452
453 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
454 (*iter)->Partition_Post_Processing(Display_Error);
455
456 if ((*iter)->Is_Storage) {
457 ++storageid;
458 (*iter)->MTP_Storage_ID = storageid;
459 }
460
461 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
462 settings_partition = (*iter);
463 else
464 (*iter)->Is_Settings_Storage = false;
465
466 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
467 andsec_partition = (*iter);
468 else
469 (*iter)->Has_Android_Secure = false;
bigbiff22851b92021-09-01 16:46:57 -0400470 }
471
me-cafebabed63fcaa2022-07-28 03:19:20 +0800472 Unlock_Block_Partitions();
473
bigbiff22851b92021-09-01 16:46:57 -0400474 //Setup Apex before decryption
475 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
476 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
477 if (sys) {
478 if (sys->Get_Super_Status()) {
Mohd Farazec370452023-08-28 16:51:35 +0530479 sys->Mount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400480 if (ven) {
Mohd Farazec370452023-08-28 16:51:35 +0530481 ven->Mount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400482 }
483 #ifdef TW_EXCLUDE_APEX
484 LOGINFO("Apex is disabled in this build\n");
485 #else
486 twrpApex apex;
487 if (!apex.loadApexImages()) {
488 LOGERR("Unable to load apex images from %s\n", APEX_DIR);
489 property_set("twrp.apex.loaded", "false");
490 } else {
491 property_set("twrp.apex.loaded", "true");
492 }
493 TWFunc::check_and_run_script("/sbin/resyncapex.sh", "apex");
494 #endif
495 }
496 }
497 #ifndef USE_VENDOR_LIBS
498 if (ven)
Mohd Farazec370452023-08-28 16:51:35 +0530499 ven->UnMount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400500 if (sys)
Mohd Farazec370452023-08-28 16:51:35 +0530501 sys->UnMount(Display_Error);
bigbiff22851b92021-09-01 16:46:57 -0400502 #endif
503
504 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) {
505 // Attempt to automatically identify /data/media emulated storage devices
506 TWPartition* Dat = Find_Partition_By_Path("/data");
507 if (Dat) {
508 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
509 datamedia = true;
510 Dat->Setup_Data_Media();
511 settings_partition = Dat;
512 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
513 ++storageid;
514 Dat->MTP_Storage_ID = storageid;
515 }
516 }
517 if (!settings_partition) {
518 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
519 if ((*iter)->Is_Storage) {
520 settings_partition = (*iter);
521 break;
522 }
523 }
524 if (!settings_partition)
525 LOGERR("Unable to locate storage partition for storing settings file.\n");
526 }
527 if (!Write_Fstab()) {
528 if (Display_Error)
529 LOGERR("Error creating fstab\n");
530 else
531 LOGINFO("Error creating fstab\n");
532 }
533
534 if (andsec_partition) {
535 Setup_Android_Secure_Location(andsec_partition);
536 } else if (settings_partition) {
537 Setup_Android_Secure_Location(settings_partition);
538 }
539 if (settings_partition) {
540 Setup_Settings_Storage_Partition(settings_partition);
541 }
542
543 #ifdef TW_INCLUDE_CRYPTO
544 DataManager::SetValue(TW_IS_ENCRYPTED, 1);
545 Decrypt_Data();
546 #endif
547
548 Update_System_Details();
549 if (Get_Super_Status())
550 Setup_Super_Partition();
551 UnMount_Main_Partitions();
552 #ifdef AB_OTA_UPDATER
553 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
554 #endif
555 setup_uevent();
556}
557
bigbiff7ba75002020-04-11 20:47:09 -0400558int TWPartitionManager::Write_Fstab(void) {
559 FILE *fp;
560 std::vector<TWPartition*>::iterator iter;
561 string Line;
562
563 fp = fopen("/etc/fstab", "w");
564 if (fp == NULL) {
565 LOGINFO("Can not open /etc/fstab.\n");
566 return false;
567 }
568 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
569 if ((*iter)->Can_Be_Mounted) {
Mohd Faraz2a1e3752020-09-30 10:55:48 +0530570 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System +
571 ((*iter)->Mount_Read_Only ? " ro " : " rw ") + "0 0\n";
bigbiff7ba75002020-04-11 20:47:09 -0400572 fputs(Line.c_str(), fp);
573 }
574 // Handle subpartition tracking
575 if ((*iter)->Is_SubPartition) {
576 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
577 if (ParentPartition)
578 ParentPartition->Has_SubPartition = true;
579 else
580 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
581 }
582 }
583 fclose(fp);
584 return true;
585}
586
587void TWPartitionManager::Decrypt_Data() {
588 #ifdef TW_INCLUDE_CRYPTO
Ethan Yonkercceebb82014-11-18 10:17:59 -0600589 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
590 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
Captain Throwback37c3aef2021-10-06 11:38:18 -0400591 Set_Crypto_State();
bigbiff4fa02b52021-12-30 17:01:44 -0500592 TWPartition* Key_Directory_Partition = Find_Partition_By_Path(Decrypt_Data->Key_Directory);
593 if (Key_Directory_Partition != nullptr)
594 if (!Key_Directory_Partition->Is_Mounted())
595 Mount_By_Path(Decrypt_Data->Key_Directory, false);
596 if (!Decrypt_Data->Key_Directory.empty()) {
597 Set_Crypto_Type("file");
Ethan Yonker93382822018-11-01 15:25:31 -0500598#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
bigbiff7ba75002020-04-11 20:47:09 -0400599#ifdef USE_FSCRYPT
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100600 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 -0500601 std::string crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "error");
Mohd Faraze3948ec2020-08-14 01:40:59 +0000602 Decrypt_Data->Decrypted_Block_Device = crypto_blkdev;
bigbiff7ba75002020-04-11 20:47:09 -0400603 LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400604#endif
Ethan Yonker93382822018-11-01 15:25:31 -0500605 Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
606 int retry_count = 10;
607 while (!Decrypt_Data->Mount(false) && --retry_count)
608 usleep(500);
609 if (Decrypt_Data->Mount(false)) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400610 if (!Decrypt_Data->Decrypt_FBE_DE()) {
bigbiff437d86f2021-09-26 16:57:14 -0400611 LOGERR("Unable to decrypt FBE device\n");
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400612 }
613
Ethan Yonker93382822018-11-01 15:25:31 -0500614 } else {
615 LOGINFO("Failed to mount data after metadata decrypt\n");
616 }
617 } else {
618 LOGINFO("Unable to decrypt metadata encryption\n");
619 }
620#else
621 LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
622#endif
623 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600624 if (Decrypt_Data->Is_FBE) {
625 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
626 if (Decrypt_Device("!") == 0) {
627 gui_msg("decrypt_success=Successfully decrypted with default password.");
628 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
629 } else {
630 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
631 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600632 }
633 } else {
Captain Throwback500c3d22023-08-28 17:20:35 -0400634 LOGINFO("FBE setup failed. Trying FDE...\n");
Captain Throwback37c3aef2021-10-06 11:38:18 -0400635 Set_Crypto_State();
636 Set_Crypto_Type("block");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600637 int password_type = cryptfs_get_password_type();
638 if (password_type == CRYPT_TYPE_DEFAULT) {
639 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
640 if (Decrypt_Device("default_password") == 0) {
641 gui_msg("decrypt_success=Successfully decrypted with default password.");
642 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
643 } else {
644 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
645 }
646 } else {
647 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
Noah Jacobson81d638d2019-04-28 00:10:07 -0400648 DataManager::SetValue("tw_crypto_pwtype_0", password_type);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600649 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600650 }
651 }
bigbiff4fa02b52021-12-30 17:01:44 -0500652 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted)) {
Ethan Yonker66a19492015-12-10 10:19:45 -0600653 Decrypt_Adopted();
654 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600655#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400656}
657
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500658void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500659 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500660}
661
Matt Mowerbf4efa32014-04-14 23:25:26 -0500662void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
663 if (Part->Has_Android_Secure)
664 Part->Setup_AndSec();
Ethan Yonker6277c792014-09-15 14:54:30 -0500665 else if (!datamedia)
Matt Mowerbf4efa32014-04-14 23:25:26 -0500666 Part->Setup_AndSec();
Matt Mowerbf4efa32014-04-14 23:25:26 -0500667}
668
Dees_Troy8170a922012-09-18 15:40:25 -0400669void TWPartitionManager::Output_Partition_Logging(void) {
670 std::vector<TWPartition*>::iterator iter;
671
672 printf("\n\nPartition Logs:\n");
673 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
674 Output_Partition((*iter));
675}
676
677void TWPartitionManager::Output_Partition(TWPartition* Part) {
678 unsigned long long mb = 1048576;
679
Gary Peck004d48b2012-11-21 16:28:18 -0800680 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 -0400681 if (Part->Can_Be_Mounted) {
Gary Peck004d48b2012-11-21 16:28:18 -0800682 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 -0400683 }
Gary Peck004d48b2012-11-21 16:28:18 -0800684 printf("\n Flags: ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500685 if (Part->Can_Be_Mounted)
686 printf("Can_Be_Mounted ");
Gary Peck004d48b2012-11-21 16:28:18 -0800687 if (Part->Can_Be_Wiped)
688 printf("Can_Be_Wiped ");
Hashcodedabfd492013-08-29 22:45:30 -0700689 if (Part->Use_Rm_Rf)
690 printf("Use_Rm_Rf ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500691 if (Part->Can_Be_Backed_Up)
692 printf("Can_Be_Backed_Up ");
Gary Peck004d48b2012-11-21 16:28:18 -0800693 if (Part->Wipe_During_Factory_Reset)
694 printf("Wipe_During_Factory_Reset ");
695 if (Part->Wipe_Available_in_GUI)
696 printf("Wipe_Available_in_GUI ");
697 if (Part->Is_SubPartition)
698 printf("Is_SubPartition ");
699 if (Part->Has_SubPartition)
700 printf("Has_SubPartition ");
701 if (Part->Removable)
702 printf("Removable ");
703 if (Part->Is_Present)
704 printf("IsPresent ");
705 if (Part->Can_Be_Encrypted)
706 printf("Can_Be_Encrypted ");
707 if (Part->Is_Encrypted)
708 printf("Is_Encrypted ");
709 if (Part->Is_Decrypted)
710 printf("Is_Decrypted ");
711 if (Part->Has_Data_Media)
712 printf("Has_Data_Media ");
Dees_Troy83bd4832013-05-04 12:39:56 +0000713 if (Part->Can_Encrypt_Backup)
714 printf("Can_Encrypt_Backup ");
715 if (Part->Use_Userdata_Encryption)
716 printf("Use_Userdata_Encryption ");
Gary Peck004d48b2012-11-21 16:28:18 -0800717 if (Part->Has_Android_Secure)
718 printf("Has_Android_Secure ");
719 if (Part->Is_Storage)
720 printf("Is_Storage ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500721 if (Part->Is_Settings_Storage)
722 printf("Is_Settings_Storage ");
Dees_Troy68cab492012-12-12 19:29:35 +0000723 if (Part->Ignore_Blkid)
724 printf("Ignore_Blkid ");
Ethan Yonker253368a2014-11-25 15:00:52 -0600725 if (Part->Mount_To_Decrypt)
726 printf("Mount_To_Decrypt ");
Ethan Yonker96af84a2015-01-05 14:58:36 -0600727 if (Part->Can_Flash_Img)
728 printf("Can_Flash_Img ");
Ethan Yonker66a19492015-12-10 10:19:45 -0600729 if (Part->Is_Adopted_Storage)
730 printf("Is_Adopted_Storage ");
Ethan Yonker1b190162016-12-05 15:25:19 -0600731 if (Part->SlotSelect)
732 printf("SlotSelect ");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600733 if (Part->Mount_Read_Only)
734 printf("Mount_Read_Only ");
bigbiffcfa875c2021-06-20 16:20:27 -0400735 if (Part->Is_Super)
736 printf("Is_Super ");
Gary Peck004d48b2012-11-21 16:28:18 -0800737 printf("\n");
738 if (!Part->SubPartition_Of.empty())
739 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
740 if (!Part->Symlink_Path.empty())
741 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
742 if (!Part->Symlink_Mount_Point.empty())
743 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
744 if (!Part->Primary_Block_Device.empty())
745 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
746 if (!Part->Alternate_Block_Device.empty())
747 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
748 if (!Part->Decrypted_Block_Device.empty())
749 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
dianlujitao4879b372018-12-03 18:45:47 +0800750 if (!Part->Crypto_Key_Location.empty())
Ethan Yonker253368a2014-11-25 15:00:52 -0600751 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800752 if (Part->Length != 0)
753 printf(" Length: %i\n", Part->Length);
754 if (!Part->Display_Name.empty())
755 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500756 if (!Part->Storage_Name.empty())
757 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800758 if (!Part->Backup_Path.empty())
759 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
760 if (!Part->Backup_Name.empty())
761 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500762 if (!Part->Backup_Display_Name.empty())
763 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800764 if (!Part->Backup_FileName.empty())
765 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
766 if (!Part->Storage_Path.empty())
767 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
768 if (!Part->Current_File_System.empty())
769 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
770 if (!Part->Fstab_File_System.empty())
771 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
772 if (Part->Format_Block_Size != 0)
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500773 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
Dees_Troy094207a2012-09-26 12:00:39 -0400774 if (!Part->MTD_Name.empty())
775 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
Matt Mower029a82d2017-01-08 13:12:38 -0600776 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
Hashcode62bd9e02013-11-19 21:59:42 -0800777 if (Part->Mount_Flags || !Part->Mount_Options.empty())
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600778 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -0600779 if (Part->MTP_Storage_ID)
780 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
Ethan Yonker93382822018-11-01 15:25:31 -0500781 if (!Part->Key_Directory.empty())
782 printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
Ethan Yonker6277c792014-09-15 14:54:30 -0500783 printf("\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400784}
785
Dees_Troy51a0e822012-09-05 15:24:24 -0400786int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400787 std::vector<TWPartition*>::iterator iter;
788 int ret = false;
789 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400790 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400791
bigbiffd58ba182020-03-23 10:02:29 -0400792 if (Local_Path == "/tmp" || Local_Path == "/")
Dees_Troy43d8b002012-09-17 16:00:01 -0400793 return true;
794
Dees_Troy5bf43922012-09-07 16:07:55 -0400795 // Iterate through all partitions
796 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400797 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400798 ret = (*iter)->Mount(Display_Error);
799 found = true;
Dees_Troy51127312012-09-08 13:08:49 -0400800 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400801 (*iter)->Mount(Display_Error);
Dees_Troy51127312012-09-08 13:08:49 -0400802 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400803 }
804 if (found) {
805 return ret;
806 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500807 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 -0400808 }
809 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400810}
811
Captain Throwbackb94ce152024-01-28 22:47:42 -0500812int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error, int flags) {
Dees_Troy51127312012-09-08 13:08:49 -0400813 std::vector<TWPartition*>::iterator iter;
814 int ret = false;
815 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400816 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy51127312012-09-08 13:08:49 -0400817
818 // Iterate through all partitions
819 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400820 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Captain Throwbackb94ce152024-01-28 22:47:42 -0500821 ret = (*iter)->UnMount(Display_Error, flags);
Dees_Troy51127312012-09-08 13:08:49 -0400822 found = true;
823 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Captain Throwbackb94ce152024-01-28 22:47:42 -0500824 (*iter)->UnMount(Display_Error, flags);
Dees_Troy51127312012-09-08 13:08:49 -0400825 }
826 }
827 if (found) {
828 return ret;
829 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500830 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 -0400831 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000832 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400833 }
834 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400835}
836
Dees_Troy51a0e822012-09-05 15:24:24 -0400837int TWPartitionManager::Is_Mounted_By_Path(string Path) {
Dees_Troy51127312012-09-08 13:08:49 -0400838 TWPartition* Part = Find_Partition_By_Path(Path);
839
840 if (Part)
841 return Part->Is_Mounted();
842 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000843 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400844 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400845}
846
Dees_Troy5bf43922012-09-07 16:07:55 -0400847int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400848 string current_storage_path = DataManager::GetCurrentStoragePath();
849
850 if (Mount_By_Path(current_storage_path, Display_Error)) {
851 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
852 if (FreeStorage)
853 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
854 return true;
855 }
856 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400857}
858
Dees_Troy5bf43922012-09-07 16:07:55 -0400859int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
860 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
861}
862
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600863TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400864 std::vector<TWPartition*>::iterator iter;
Dees_Troy38bd7602012-09-14 13:33:53 -0400865 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400866
dianlujitaob76a73a2020-04-30 20:33:20 +0800867 if (Local_Path == "/system")
868 Local_Path = Get_Android_Root_Path();
Dees_Troy5bf43922012-09-07 16:07:55 -0400869 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400870 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
Dees_Troy5bf43922012-09-07 16:07:55 -0400871 return (*iter);
872 }
Dees_Troy51a0e822012-09-05 15:24:24 -0400873 return NULL;
874}
875
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600876TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
877 std::vector<TWPartition*>::iterator iter;
878
879 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
880 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
881 return (*iter);
882 }
883 return NULL;
884}
885
Ethan Yonker53796e72019-01-11 22:49:52 -0600886int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400887 // Check the backup name to ensure that it is the correct size and contains only valid characters
888 // and that a backup with that name doesn't already exist
889 char backup_name[MAX_BACKUP_NAME_LEN];
890 char backup_loc[255], tw_image_dir[255];
891 int copy_size;
892 int index, cur_char;
Ethan Yonker53796e72019-01-11 22:49:52 -0600893 string Backup_Loc;
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400894
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400895 copy_size = Backup_Name.size();
896 // Check size
897 if (copy_size > MAX_BACKUP_NAME_LEN) {
898 if (Display_Error)
Ethan Yonker74db1572015-10-28 12:44:49 -0500899 gui_err("backup_name_len=Backup name is too long.");
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400900 return -2;
901 }
902
903 // Check each character
904 strncpy(backup_name, Backup_Name.c_str(), copy_size);
Dees_Troya13d74f2013-03-24 08:54:55 -0500905 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400906 return 0; // A "0" (zero) means to use the current timestamp for the backup name
907 for (index=0; index<copy_size; index++) {
908 cur_char = (int)backup_name[index];
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500909 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 -0400910 // These are valid characters
911 // Numbers
912 // Upper case letters
913 // Lower case letters
914 // Space
915 // and -_.{}[]
916 } else {
917 if (Display_Error)
Ethan Yonker4adc33e2016-01-22 16:07:11 -0600918 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 -0400919 return -3;
920 }
921 }
922
Ethan Yonker53796e72019-01-11 22:49:52 -0600923 if (Must_Be_Unique) {
924 // Check to make sure that a backup with this name doesn't already exist
925 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
926 strcpy(backup_loc, Backup_Loc.c_str());
927 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
928 if (TWFunc::Path_Exists(tw_image_dir)) {
929 if (Display_Error)
930 gui_err("backup_name_exists=A backup with that name already exists!");
bigbiffce8f83c2015-12-12 18:30:21 -0500931
Ethan Yonker53796e72019-01-11 22:49:52 -0600932 return -4;
933 }
934 // Backup is unique
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400935 }
Ethan Yonker53796e72019-01-11 22:49:52 -0600936 // No problems found
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400937 return 0;
938}
939
bigbiffce8f83c2015-12-12 18:30:21 -0500940bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400941 time_t start, stop;
Matt Mower23d8aae2017-01-06 14:30:33 -0600942 int use_compression;
bigbiffce8f83c2015-12-12 18:30:21 -0500943 string backup_log = part_settings->Backup_Folder + "/recovery.log";
Dees_Troy43d8b002012-09-17 16:00:01 -0400944
bigbiffce8f83c2015-12-12 18:30:21 -0500945 if (part_settings->Part == NULL)
Dees_Troy43d8b002012-09-17 16:00:01 -0400946 return true;
947
Dees_Troy093b7642012-09-21 15:59:38 -0400948 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -0400949
Tom Hite5a926722014-09-15 01:31:03 +0000950 TWFunc::SetPerformanceMode(true);
Dees_Troy43d8b002012-09-17 16:00:01 -0400951 time(&start);
952
bigbiffce8f83c2015-12-12 18:30:21 -0500953 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500954 sync();
955 sync();
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400956 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500957 if (!part_settings->adbbackup && part_settings->generate_digest) {
958 if (!twrpDigestDriver::Make_Digest(Full_Filename))
959 goto backup_error;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400960 }
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400961
bigbiffce8f83c2015-12-12 18:30:21 -0500962 if (part_settings->Part->Has_SubPartition) {
Dees_Troy8170a922012-09-18 15:40:25 -0400963 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400964 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -0400965
966 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400967 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500968 part_settings->Part = *subpart;
bigbiffce8f83c2015-12-12 18:30:21 -0500969 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500970 goto backup_error;
Tom Hite5a926722014-09-15 01:31:03 +0000971 }
Dees_Troy2727b992013-08-14 20:09:30 +0000972 sync();
973 sync();
bigbiff bigbifff5955b12019-05-18 17:28:58 -0400974 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400975 if (!part_settings->adbbackup && part_settings->generate_digest) {
976 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500977 goto backup_error;
bigbiffce8f83c2015-12-12 18:30:21 -0500978 }
Tom Hite5a926722014-09-15 01:31:03 +0000979 }
Dees_Troy8170a922012-09-18 15:40:25 -0400980 }
981 }
982 }
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400983
Dees_Troy43d8b002012-09-17 16:00:01 -0400984 time(&stop);
that203bcc92015-05-09 17:27:33 +0200985 int backup_time = (int) difftime(stop, start);
Dees_Troy2673cec2013-04-02 20:22:16 +0000986 LOGINFO("Partition Backup time: %d\n", backup_time);
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400987
bigbiffce8f83c2015-12-12 18:30:21 -0500988 if (part_settings->Part->Backup_Method == BM_FILES) {
989 part_settings->file_time += backup_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400990 } else {
bigbiffce8f83c2015-12-12 18:30:21 -0500991 part_settings->img_time += backup_time;
992
Dees_Troy43d8b002012-09-17 16:00:01 -0400993 }
Tom Hite5a926722014-09-15 01:31:03 +0000994
Matt Mower02899552016-12-30 18:13:51 -0600995 TWFunc::SetPerformanceMode(false);
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500996 return true;
Dees_Troy43d8b002012-09-17 16:00:01 -0400997 }
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500998backup_error:
999 Clean_Backup_Folder(part_settings->Backup_Folder);
1000 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
1001 tw_set_default_metadata(backup_log.c_str());
1002 TWFunc::SetPerformanceMode(false);
1003 return false;
bigbiff7abc5fe2015-01-17 16:53:12 -05001004}
1005
bigbiffbf1d6722015-02-14 16:25:59 -05001006void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
1007 DIR *d = opendir(Backup_Folder.c_str());
1008 struct dirent *p;
1009 int r;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001010 vector<string> ext;
1011
1012 //extensions we should delete when cleaning
1013 ext.push_back("win");
1014 ext.push_back("md5");
1015 ext.push_back("sha2");
1016 ext.push_back("info");
bigbiffbf1d6722015-02-14 16:25:59 -05001017
Ethan Yonker74db1572015-10-28 12:44:49 -05001018 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
bigbiffbf1d6722015-02-14 16:25:59 -05001019
1020 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001021 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
bigbiffbf1d6722015-02-14 16:25:59 -05001022 return;
1023 }
1024
Matt Mower2b18a532015-02-20 16:58:05 -06001025 while ((p = readdir(d))) {
bigbiffbf1d6722015-02-14 16:25:59 -05001026 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
1027 continue;
1028
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001029 string path = Backup_Folder + "/" + p->d_name;
bigbiffbf1d6722015-02-14 16:25:59 -05001030
1031 size_t dot = path.find_last_of(".") + 1;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001032 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
1033 if (path.substr(dot) == *i) {
1034 r = unlink(path.c_str());
1035 if (r != 0)
1036 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
bigbiffbf1d6722015-02-14 16:25:59 -05001037 }
1038 }
1039 }
1040 closedir(d);
1041}
1042
Ethan Yonker472f5062016-02-25 13:47:30 -06001043int TWPartitionManager::Check_Backup_Cancel() {
1044 return stop_backup.get_value();
1045}
1046
bigbiff7abc5fe2015-01-17 16:53:12 -05001047int TWPartitionManager::Cancel_Backup() {
1048 string Backup_Folder, Backup_Name, Full_Backup_Path;
1049
1050 stop_backup.set_value(1);
1051
1052 if (tar_fork_pid != 0) {
1053 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
1054 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001055 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
bigbiff7abc5fe2015-01-17 16:53:12 -05001056 LOGINFO("Killing pid: %d\n", tar_fork_pid);
1057 kill(tar_fork_pid, SIGUSR2);
1058 while (kill(tar_fork_pid, 0) == 0) {
1059 usleep(1000);
1060 }
1061 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
1062 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
1063 TWFunc::removeDir(Full_Backup_Path, false);
1064 tar_fork_pid = 0;
1065 }
1066
1067 return 0;
Dees_Troy43d8b002012-09-17 16:00:01 -04001068}
1069
bigbiffce8f83c2015-12-12 18:30:21 -05001070int TWPartitionManager::Run_Backup(bool adbbackup) {
1071 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001072 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
bigbiffce8f83c2015-12-12 18:30:21 -05001073 string Backup_Name, Backup_List, backup_path;
Matt Mower23d8aae2017-01-06 14:30:33 -06001074 unsigned long long total_bytes = 0, free_space = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -04001075 TWPartition* storage = NULL;
1076 struct tm *t;
Matt Mower23d8aae2017-01-06 14:30:33 -06001077 time_t seconds, total_start, total_stop;
Dees_Troya13d74f2013-03-24 08:54:55 -05001078 size_t start_pos = 0, end_pos = 0;
bigbiff7abc5fe2015-01-17 16:53:12 -05001079 stop_backup.set_value(0);
Dees_Troy43d8b002012-09-17 16:00:01 -04001080 seconds = time(0);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001081 t = localtime(&seconds);
Dees_Troy43d8b002012-09-17 16:00:01 -04001082
bigbiffce8f83c2015-12-12 18:30:21 -05001083 part_settings.img_bytes_remaining = 0;
1084 part_settings.file_bytes_remaining = 0;
1085 part_settings.img_time = 0;
1086 part_settings.file_time = 0;
1087 part_settings.img_bytes = 0;
1088 part_settings.file_bytes = 0;
1089 part_settings.PM_Method = PM_BACKUP;
1090
bigbiffce8f83c2015-12-12 18:30:21 -05001091 part_settings.adbbackup = adbbackup;
Dees_Troy43d8b002012-09-17 16:00:01 -04001092 time(&total_start);
1093
1094 Update_System_Details();
1095
1096 if (!Mount_Current_Storage(true))
1097 return false;
1098
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001099 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
1100 if (skip_digest == 0)
1101 part_settings.generate_digest = true;
Dees_Troyc5865ab2012-09-24 15:08:04 -04001102 else
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001103 part_settings.generate_digest = false;
Dees_Troy4a2a1262012-09-18 09:33:47 -04001104
bigbiffce8f83c2015-12-12 18:30:21 -05001105 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001106 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
1107 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
1108 Backup_Name = TWFunc::Get_Current_Date();
1109 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
Dees Troyb21cc642013-09-10 17:36:41 +00001110 TWFunc::Auto_Generate_Backup_Name();
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001111 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
Dees_Troy43d8b002012-09-17 16:00:01 -04001112 }
bigbiffce8f83c2015-12-12 18:30:21 -05001113
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001114 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001115 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001116
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001117 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -04001118
Dees_Troy2673cec2013-04-02 20:22:16 +00001119 LOGINFO("Calculating backup details...\n");
Dees_Troya13d74f2013-03-24 08:54:55 -05001120 DataManager::GetValue("tw_backup_list", Backup_List);
bigbiff7ba75002020-04-11 20:47:09 -04001121 LOGINFO("Backup_List: %s\n", Backup_List.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05001122 if (!Backup_List.empty()) {
1123 end_pos = Backup_List.find(";", start_pos);
1124 while (end_pos != string::npos && start_pos < Backup_List.size()) {
1125 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiff7ba75002020-04-11 20:47:09 -04001126 LOGINFO("backup_path: %s\n", backup_path.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001127 part_settings.Part = Find_Partition_By_Path(backup_path);
1128 if (part_settings.Part != NULL) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001129 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001130 if (part_settings.Part->Backup_Method == BM_FILES)
1131 part_settings.file_bytes += part_settings.Part->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001132 else
bigbiffce8f83c2015-12-12 18:30:21 -05001133 part_settings.img_bytes += part_settings.Part->Backup_Size;
1134 if (part_settings.Part->Has_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001135 std::vector<TWPartition*>::iterator subpart;
1136
1137 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiffce8f83c2015-12-12 18:30:21 -05001138 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 -05001139 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001140 if ((*subpart)->Backup_Method == BM_FILES)
1141 part_settings.file_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001142 else
bigbiffce8f83c2015-12-12 18:30:21 -05001143 part_settings.img_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001144 }
1145 }
Dees_Troy8170a922012-09-18 15:40:25 -04001146 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001147 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001148 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 -04001149 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001150 start_pos = end_pos + 1;
1151 end_pos = Backup_List.find(";", start_pos);
Dees_Troy43d8b002012-09-17 16:00:01 -04001152 }
1153 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001154
1155 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001156 gui_msg("no_partition_selected=No partitions selected for backup.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001157 return false;
1158 }
bigbiffce8f83c2015-12-12 18:30:21 -05001159 if (adbbackup) {
1160 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
1161 return false;
1162 }
1163 }
1164 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
Ethan Yonker472f5062016-02-25 13:47:30 -06001165 ProgressTracking progress(total_bytes);
bigbiffce8f83c2015-12-12 18:30:21 -05001166 part_settings.progress = &progress;
1167
Ethan Yonker74db1572015-10-28 12:44:49 -05001168 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
1169 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001170 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1171 if (storage != NULL) {
1172 free_space = storage->Free;
Ethan Yonker74db1572015-10-28 12:44:49 -05001173 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001174 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001175 gui_err("unable_locate_storage=Unable to locate storage device.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001176 return false;
1177 }
bigbiffbf1d6722015-02-14 16:25:59 -05001178
Matt Mowerbfccfb82016-04-25 23:22:31 -05001179 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
bigbiffce8f83c2015-12-12 18:30:21 -05001180
1181 if (adbbackup)
1182 disable_free_space_check = true;
1183
bigbiffbf1d6722015-02-14 16:25:59 -05001184 if (!disable_free_space_check) {
1185 if (free_space - (32 * 1024 * 1024) < total_bytes) {
1186 // We require an extra 32MB just in case
Ethan Yonker74db1572015-10-28 12:44:49 -05001187 gui_err("no_space=Not enough free space on storage.");
bigbiffbf1d6722015-02-14 16:25:59 -05001188 return false;
1189 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001190 }
bigbiffce8f83c2015-12-12 18:30:21 -05001191 part_settings.img_bytes_remaining = part_settings.img_bytes;
1192 part_settings.file_bytes_remaining = part_settings.file_bytes;
Dees_Troy43d8b002012-09-17 16:00:01 -04001193
Ethan Yonker74db1572015-10-28 12:44:49 -05001194 gui_msg("backup_started=[BACKUP STARTED]");
bigbiff bigbiffcdd97c72019-03-29 19:12:33 -04001195
1196 int is_decrypted = 0;
1197 int is_encrypted = 0;
1198
1199 DataManager::GetValue(TW_IS_DECRYPTED, is_decrypted);
1200 DataManager::GetValue(TW_IS_ENCRYPTED, is_encrypted);
1201 if (!adbbackup || (!is_encrypted || (is_encrypted && is_decrypted))) {
1202 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
1203 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
1204 gui_err("fail_backup_folder=Failed to make backup folder.");
1205 return false;
1206 }
Dees_Troyd4b22b02013-01-18 17:17:58 +00001207 }
1208
Dees_Troy2673cec2013-04-02 20:22:16 +00001209 DataManager::SetProgress(0.0);
Dees_Troy093b7642012-09-21 15:59:38 -04001210
Dees_Troya13d74f2013-03-24 08:54:55 -05001211 start_pos = 0;
1212 end_pos = Backup_List.find(";", start_pos);
1213 while (end_pos != string::npos && start_pos < Backup_List.size()) {
bigbiff7abc5fe2015-01-17 16:53:12 -05001214 if (stop_backup.get_value() != 0)
1215 return -1;
Dees_Troya13d74f2013-03-24 08:54:55 -05001216 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001217 part_settings.Part = Find_Partition_By_Path(backup_path);
1218 if (part_settings.Part != NULL) {
1219 if (!Backup_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001220 return false;
1221 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001222 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 -05001223 }
1224 start_pos = end_pos + 1;
1225 end_pos = Backup_List.find(";", start_pos);
1226 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001227
1228 // Average BPS
bigbiffce8f83c2015-12-12 18:30:21 -05001229 if (part_settings.img_time == 0)
1230 part_settings.img_time = 1;
1231 if (part_settings.file_time == 0)
1232 part_settings.file_time = 1;
1233 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
1234 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
Dees_Troy43d8b002012-09-17 16:00:01 -04001235
bigbiffce8f83c2015-12-12 18:30:21 -05001236 if (part_settings.file_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001237 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 -05001238 if (part_settings.img_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001239 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 -04001240
1241 time(&total_stop);
1242 int total_time = (int) difftime(total_stop, total_start);
bigbiffce8f83c2015-12-12 18:30:21 -05001243
1244 uint64_t actual_backup_size;
Ethan Yonker3fdcda42016-11-30 12:29:37 -06001245 if (!adbbackup) {
1246 TWExclude twe;
1247 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
1248 } else
bigbiffce8f83c2015-12-12 18:30:21 -05001249 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001250 actual_backup_size /= (1024LLU * 1024LLU);
Dees_Troy43d8b002012-09-17 16:00:01 -04001251
bigbiffce8f83c2015-12-12 18:30:21 -05001252 int prev_img_bps = 0, use_compression = 0;
1253 unsigned long long prev_file_bps = 0;
Matt Mower173cdb92016-12-31 02:49:19 -06001254 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001255 img_bps += (prev_img_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001256 img_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001257
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001258 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -04001259 if (use_compression)
1260 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001261 else
Dees_Troy093b7642012-09-21 15:59:38 -04001262 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
1263 file_bps += (prev_file_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001264 file_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001265
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001266 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001267 if (use_compression)
1268 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
1269 else
1270 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
1271
Ethan Yonker74db1572015-10-28 12:44:49 -05001272 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Dees_Troy43d8b002012-09-17 16:00:01 -04001273 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001274 UnMount_Main_Partitions();
Ethan Yonker56db1c42015-12-20 22:49:00 -06001275 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001276 string backup_log = part_settings.Backup_Folder + "/recovery.log";
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001277 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -06001278 tw_set_default_metadata(backup_log.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001279
1280 if (part_settings.adbbackup) {
1281 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
1282 return false;
1283 }
1284 }
1285 part_settings.adbbackup = false;
1286 DataManager::SetValue("tw_enable_adb_backup", 0);
1287
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001288 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001289}
1290
bigbiffce8f83c2015-12-12 18:30:21 -05001291bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
Dees_Troy4a2a1262012-09-18 09:33:47 -04001292 time_t Start, Stop;
bigbiffce8f83c2015-12-12 18:30:21 -05001293
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001294 if (part_settings->adbbackup) {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001295 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
1296 LOGINFO("setting backup name: %s\n", partName.c_str());
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001297 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
1298 }
1299
Tom Hite5a926722014-09-15 01:31:03 +00001300 TWFunc::SetPerformanceMode(true);
bigbiffce8f83c2015-12-12 18:30:21 -05001301
Dees_Troy4a2a1262012-09-18 09:33:47 -04001302 time(&Start);
Ethan Yonker472f5062016-02-25 13:47:30 -06001303
bigbiffce8f83c2015-12-12 18:30:21 -05001304 if (!part_settings->Part->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001305 TWFunc::SetPerformanceMode(false);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001306 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001307 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001308 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
Dees_Troy8170a922012-09-18 15:40:25 -04001309 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001310 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -04001311
1312 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001313 part_settings->Part = *subpart;
1314 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1315 part_settings->Part = (*subpart);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001316 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
bigbiffce8f83c2015-12-12 18:30:21 -05001317 if (!(*subpart)->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001318 TWFunc::SetPerformanceMode(false);
Dees_Troy8170a922012-09-18 15:40:25 -04001319 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001320 }
Dees_Troy8170a922012-09-18 15:40:25 -04001321 }
1322 }
1323 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001324 time(&Stop);
Tom Hite5a926722014-09-15 01:31:03 +00001325 TWFunc::SetPerformanceMode(false);
bigbiffce8f83c2015-12-12 18:30:21 -05001326 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1327
Dees_Troy4a2a1262012-09-18 09:33:47 -04001328 return true;
1329}
1330
Ethan Yonker472f5062016-02-25 13:47:30 -06001331int TWPartitionManager::Run_Restore(const string& Restore_Name) {
bigbiffce8f83c2015-12-12 18:30:21 -05001332 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001333 int check_digest;
bigbiffce8f83c2015-12-12 18:30:21 -05001334
Dees_Troy4a2a1262012-09-18 09:33:47 -04001335 time_t rStart, rStop;
1336 time(&rStart);
Dees_Troya13d74f2013-03-24 08:54:55 -05001337 string Restore_List, restore_path;
1338 size_t start_pos = 0, end_pos;
bigbiffce8f83c2015-12-12 18:30:21 -05001339
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001340 part_settings.Backup_Folder = Restore_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001341 part_settings.Part = NULL;
1342 part_settings.partition_count = 0;
1343 part_settings.total_restore_size = 0;
1344 part_settings.adbbackup = false;
1345 part_settings.PM_Method = PM_RESTORE;
Dees_Troy43d8b002012-09-17 16:00:01 -04001346
Ethan Yonker74db1572015-10-28 12:44:49 -05001347 gui_msg("restore_started=[RESTORE STARTED]");
1348 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
Dees_Troy43d8b002012-09-17 16:00:01 -04001349
Dees_Troy4a2a1262012-09-18 09:33:47 -04001350 if (!Mount_Current_Storage(true))
1351 return false;
1352
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001353 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1354 if (check_digest > 0) {
1355 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1356 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1357 gui_msg("verifying_digest=Verifying Digest");
Dees_Troya13d74f2013-03-24 08:54:55 -05001358 } else {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001359 gui_msg("skip_digest=Skipping Digest check based on user setting.");
Dees_Troya13d74f2013-03-24 08:54:55 -05001360 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001361 gui_msg("calc_restore=Calculating restore details...");
Dees_Troya13d74f2013-03-24 08:54:55 -05001362 DataManager::GetValue("tw_restore_selected", Restore_List);
bigbiffce8f83c2015-12-12 18:30:21 -05001363
Dees_Troya13d74f2013-03-24 08:54:55 -05001364 if (!Restore_List.empty()) {
1365 end_pos = Restore_List.find(";", start_pos);
1366 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1367 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001368 part_settings.Part = Find_Partition_By_Path(restore_path);
1369 if (part_settings.Part != NULL) {
bigbiffce8f83c2015-12-12 18:30:21 -05001370 if (part_settings.Part->Mount_Read_Only) {
1371 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 -05001372 return false;
1373 }
bigbiffce8f83c2015-12-12 18:30:21 -05001374
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001375 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1376
bigbiff4a60bee2021-01-23 14:08:03 -05001377 if (tw_get_default_metadata(Get_Android_Root_Path().c_str()) != 0) {
1378 gui_msg(Msg(msg::kWarning, "restore_system_context=Unable to get default context for {1} -- Android may not boot.")(Get_Android_Root_Path()));
1379 }
1380
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001381 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001382 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001383 part_settings.partition_count++;
1384 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1385 if (part_settings.Part->Has_SubPartition) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001386 TWPartition *parentPart = part_settings.Part;
Dees_Troya13d74f2013-03-24 08:54:55 -05001387 std::vector<TWPartition*>::iterator subpart;
1388
1389 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001390 part_settings.Part = *subpart;
1391 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001392 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001393 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001394 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
Dees_Troya13d74f2013-03-24 08:54:55 -05001395 }
1396 }
1397 }
1398 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001399 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001400 }
1401 start_pos = end_pos + 1;
1402 end_pos = Restore_List.find(";", start_pos);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001403 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001404 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001405
bigbiffce8f83c2015-12-12 18:30:21 -05001406 if (part_settings.partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001407 gui_err("no_part_restore=No partitions selected for restore.");
Dees_Troy4a2a1262012-09-18 09:33:47 -04001408 return false;
1409 }
1410
bigbiffce8f83c2015-12-12 18:30:21 -05001411 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1412 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 +00001413 DataManager::SetProgress(0.0);
bigbiffce8f83c2015-12-12 18:30:21 -05001414 ProgressTracking progress(part_settings.total_restore_size);
1415 part_settings.progress = &progress;
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001416
Dees_Troya13d74f2013-03-24 08:54:55 -05001417 start_pos = 0;
1418 if (!Restore_List.empty()) {
1419 end_pos = Restore_List.find(";", start_pos);
1420 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1421 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001422
1423 part_settings.Part = Find_Partition_By_Path(restore_path);
1424 if (part_settings.Part != NULL) {
1425 part_settings.partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001426 if (!Restore_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001427 return false;
1428 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001429 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001430 }
1431 start_pos = end_pos + 1;
1432 end_pos = Restore_List.find(";", start_pos);
1433 }
1434 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001435 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
bigbiff4a60bee2021-01-23 14:08:03 -05001436 tw_set_default_metadata(Get_Android_Root_Path().c_str());
Captain Throwback9d6feb52018-07-27 10:05:24 -04001437 UnMount_By_Path(Get_Android_Root_Path(), false);
Dees_Troy43d8b002012-09-17 16:00:01 -04001438 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001439 UnMount_Main_Partitions();
Dees_Troy4a2a1262012-09-18 09:33:47 -04001440 time(&rStop);
Matt Mower3c366972015-12-25 19:28:31 -06001441 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
bigbiff8f5fad32021-11-03 20:39:02 -04001442 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
1443 if (Decrypt_Data && Decrypt_Data->Is_Encrypted)
1444 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 -05001445 DataManager::SetValue("tw_file_progress", "");
bigbiffce8f83c2015-12-12 18:30:21 -05001446
Dees_Troy63c8df72012-09-10 14:02:05 -04001447 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001448}
1449
1450void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001451 // Start with the default values
Dees_Troya13d74f2013-03-24 08:54:55 -05001452 string Restore_List;
Dees_Troy83bd4832013-05-04 12:39:56 +00001453 bool get_date = true, check_encryption = true;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001454 bool adbbackup = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001455
1456 DataManager::SetValue("tw_restore_encrypted", 0);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001457 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1458 vector<string> adb_files;
1459 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1460 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1461 string adb_restore_file = adb_files.at(i);
1462 std::size_t pos = adb_restore_file.find_first_of(".");
1463 std::string path = "/" + adb_restore_file.substr(0, pos);
1464 Restore_List = path + ";";
1465 TWPartition* Part = Find_Partition_By_Path(path);
1466 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1467 adbbackup = true;
1468 }
1469 DataManager::SetValue("tw_enable_adb_backup", 1);
Dees_Troy63c8df72012-09-10 14:02:05 -04001470 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001471 else {
1472 DIR* d;
1473 d = opendir(Restore_Name.c_str());
1474 if (d == NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001475 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001476 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1477 return;
Dees_Troy63c8df72012-09-10 14:02:05 -04001478 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001479
1480 struct dirent* de;
1481 while ((de = readdir(d)) != NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001482 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001483 // Strip off three components
1484 char str[256];
1485 char* label;
1486 char* fstype = NULL;
1487 char* extn = NULL;
1488 char* ptr;
Dees_Troy63c8df72012-09-10 14:02:05 -04001489
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001490 strcpy(str, de->d_name);
1491 if (strlen(str) <= 2)
1492 continue;
Dees_Troy83bd4832013-05-04 12:39:56 +00001493
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001494 if (get_date) {
1495 char file_path[255];
1496 struct stat st;
1497
1498 strcpy(file_path, Restore_Name.c_str());
1499 strcat(file_path, "/");
1500 strcat(file_path, str);
1501 stat(file_path, &st);
1502 string backup_date = ctime((const time_t*)(&st.st_mtime));
1503 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1504 get_date = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001505 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001506
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001507 label = str;
1508 ptr = label;
1509 while (*ptr && *ptr != '.') ptr++;
1510 if (*ptr == '.')
1511 {
1512 *ptr = 0x00;
1513 ptr++;
1514 fstype = ptr;
1515 }
1516 while (*ptr && *ptr != '.') ptr++;
1517 if (*ptr == '.')
1518 {
1519 *ptr = 0x00;
1520 ptr++;
1521 extn = ptr;
1522 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001523
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001524 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1525 int extnlength = strlen(extn);
1526 if (extnlength != 3 && extnlength != 6) continue;
1527 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1528 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
Dees_Troy63c8df72012-09-10 14:02:05 -04001529
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001530 if (check_encryption) {
1531 string filename = Restore_Name + "/";
1532 filename += de->d_name;
1533 if (TWFunc::Get_File_Type(filename) == 2) {
1534 LOGINFO("'%s' is encrypted\n", filename.c_str());
1535 DataManager::SetValue("tw_restore_encrypted", 1);
1536 }
1537 }
1538 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1539
1540 TWPartition* Part = Find_Partition_By_Path(label);
1541 if (Part == NULL)
1542 {
1543 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1544 continue;
1545 }
1546
1547 Part->Backup_FileName = de->d_name;
1548 if (strlen(extn) > 3) {
1549 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1550 }
1551
dianlujitaob76a73a2020-04-30 20:33:20 +08001552 if (!Part->Is_SubPartition) {
1553 if (Part->Backup_Path == Get_Android_Root_Path())
1554 Restore_List += "/system;";
1555 else
1556 Restore_List += Part->Backup_Path + ";";
1557 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001558 }
1559 closedir(d);
Dees_Troy63c8df72012-09-10 14:02:05 -04001560 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001561
1562 if (adbbackup) {
1563 Restore_List = "ADB_Backup;";
1564 adbbackup = false;
1565 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001566
Dees_Troya13d74f2013-03-24 08:54:55 -05001567 // Set the final value
1568 DataManager::SetValue("tw_restore_list", Restore_List);
1569 DataManager::SetValue("tw_restore_selected", Restore_List);
Dees_Troy51a0e822012-09-05 15:24:24 -04001570 return;
1571}
1572
1573int TWPartitionManager::Wipe_By_Path(string Path) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001574 std::vector<TWPartition*>::iterator iter;
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301575 std::vector < TWPartition * >::iterator iter1;
Dees_Troy63c8df72012-09-10 14:02:05 -04001576 int ret = false;
1577 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -04001578 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy63c8df72012-09-10 14:02:05 -04001579
dianlujitaob76a73a2020-04-30 20:33:20 +08001580 if (Local_Path == "/system")
1581 Local_Path = Get_Android_Root_Path();
bigbiffaed1bdf2021-08-03 18:21:39 -04001582 if (Path == "/cache") {
1583 TWPartition* cache = Find_Partition_By_Path("/cache");
1584 if (cache == nullptr) {
1585 TWPartition* dat = Find_Partition_By_Path("/data");
1586 if (dat) {
1587 dat->Wipe_Data_Cache();
1588 found = true;
1589 }
1590 }
1591 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001592 // Iterate through all partitions
1593 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -04001594 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301595 // iterate through all partitions since some legacy devices uses other partitions as vendor causes issues while wiping
1596 (*iter)->Find_Actual_Block_Device();
1597 for (iter1 = Partitions.begin (); iter1 != Partitions.end (); iter1++)
1598 {
1599 (*iter1)->Find_Actual_Block_Device();
1600 if ((*iter)->Actual_Block_Device == (*iter1)->Actual_Block_Device && (*iter)->Mount_Point != (*iter1)->Mount_Point)
1601 (*iter1)->UnMount(false);
1602 }
Dees_Troye58d5262012-09-21 12:27:57 -04001603 if (Path == "/and-sec")
1604 ret = (*iter)->Wipe_AndSec();
1605 else
1606 ret = (*iter)->Wipe();
Dees_Troy63c8df72012-09-10 14:02:05 -04001607 found = true;
1608 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1609 (*iter)->Wipe();
1610 }
1611 }
1612 if (found) {
1613 return ret;
1614 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001615 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 -04001616 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -04001617}
1618
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001619int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1620 std::vector<TWPartition*>::iterator iter;
1621 int ret = false;
1622 bool found = false;
1623 string Local_Path = TWFunc::Get_Root_Path(Path);
1624
1625 // Iterate through all partitions
1626 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1627 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1628 if (Path == "/and-sec")
1629 ret = (*iter)->Wipe_AndSec();
1630 else
1631 ret = (*iter)->Wipe(New_File_System);
1632 found = true;
1633 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1634 (*iter)->Wipe(New_File_System);
1635 }
1636 }
1637 if (found) {
1638 return ret;
1639 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001640 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 -05001641 return false;
1642}
1643
Dees_Troy51a0e822012-09-05 15:24:24 -04001644int TWPartitionManager::Factory_Reset(void) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001645 std::vector<TWPartition*>::iterator iter;
1646 int ret = true;
1647
1648 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001649 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
Ethan Yonker89583ef2015-08-26 09:01:59 -05001650#ifdef TW_OEM_BUILD
1651 if ((*iter)->Mount_Point == "/data") {
1652 if (!(*iter)->Wipe_Encryption())
1653 ret = false;
1654 } else {
1655#endif
1656 if (!(*iter)->Wipe())
1657 ret = false;
1658#ifdef TW_OEM_BUILD
1659 }
1660#endif
Dees_Troy094207a2012-09-26 12:00:39 -04001661 } else if ((*iter)->Has_Android_Secure) {
1662 if (!(*iter)->Wipe_AndSec())
1663 ret = false;
Dees_Troy63c8df72012-09-10 14:02:05 -04001664 }
1665 }
bigbiffad58e1b2020-07-06 20:24:34 -04001666 TWFunc::check_and_run_script("/system/bin/factoryreset.sh", "Factory Reset Script");
Dees_Troy63c8df72012-09-10 14:02:05 -04001667 return ret;
Dees_Troy51a0e822012-09-05 15:24:24 -04001668}
1669
Dees_Troy38bd7602012-09-14 13:33:53 -04001670int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1671 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001672 vector <string> dir;
Dees_Troy38bd7602012-09-14 13:33:53 -04001673
1674 if (!Mount_By_Path("/data", true))
1675 return false;
1676
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001677 dir.push_back("/data/dalvik-cache");
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001678
bigbiff25d25b92020-06-19 16:07:38 -04001679 std::string cacheDir = TWFunc::get_log_dir();
1680 if (cacheDir == CACHE_LOGS_DIR) {
1681 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
1682 LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001683 }
1684 dir.push_back(cacheDir + "dalvik-cache");
1685 dir.push_back(cacheDir + "/dc");
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001686 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001687
Dees_Troy38bd7602012-09-14 13:33:53 -04001688 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001689 if (sdext && sdext->Is_Present && sdext->Mount(false))
1690 {
1691 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1692 {
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001693 dir.push_back("/sd-ext/dalvik-cache");
1694 }
1695 }
1696
bigbiff25d25b92020-06-19 16:07:38 -04001697 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001698 gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
1699 } else {
1700 gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
1701 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001702 for (unsigned i = 0; i < dir.size(); ++i) {
1703 if (stat(dir.at(i).c_str(), &st) == 0) {
1704 TWFunc::removeDir(dir.at(i), false);
1705 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001706 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001707 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001708
bigbiff25d25b92020-06-19 16:07:38 -04001709 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001710 gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1711 } else {
1712 gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
1713 }
1714
Dees_Troy38bd7602012-09-14 13:33:53 -04001715 return true;
1716}
1717
1718int TWPartitionManager::Wipe_Rotate_Data(void) {
1719 if (!Mount_By_Path("/data", true))
1720 return false;
1721
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001722 unlink("/data/misc/akmd*");
1723 unlink("/data/misc/rild*");
Dees_Troy2673cec2013-04-02 20:22:16 +00001724 gui_print("Rotation data wiped.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001725 return true;
1726}
1727
1728int TWPartitionManager::Wipe_Battery_Stats(void) {
1729 struct stat st;
1730
1731 if (!Mount_By_Path("/data", true))
1732 return false;
1733
1734 if (0 != stat("/data/system/batterystats.bin", &st)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001735 gui_print("No Battery Stats Found. No Need To Wipe.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001736 } else {
1737 remove("/data/system/batterystats.bin");
Dees_Troy2673cec2013-04-02 20:22:16 +00001738 gui_print("Cleared battery stats.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001739 }
1740 return true;
1741}
1742
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001743int TWPartitionManager::Wipe_Android_Secure(void) {
1744 std::vector<TWPartition*>::iterator iter;
1745 int ret = false;
1746 bool found = false;
1747
1748 // Iterate through all partitions
1749 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1750 if ((*iter)->Has_Android_Secure) {
1751 ret = (*iter)->Wipe_AndSec();
1752 found = true;
1753 }
1754 }
1755 if (found) {
1756 return ret;
1757 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001758 gui_err("no_andsec=No android secure partitions found.");
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001759 }
1760 return false;
1761}
1762
Dees_Troy38bd7602012-09-14 13:33:53 -04001763int TWPartitionManager::Format_Data(void) {
1764 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffcfa875c2021-06-20 16:20:27 -04001765 TWPartition* metadata = Find_Partition_By_Path("/metadata");
Captain Throwbackab76e402023-10-04 10:01:17 -04001766 int ret = false;
bigbiffcfa875c2021-06-20 16:20:27 -04001767 if (metadata != NULL)
1768 metadata->UnMount(false);
Dees_Troy38bd7602012-09-14 13:33:53 -04001769
1770 if (dat != NULL) {
bigbiffab76bd72021-10-11 10:17:48 -04001771 if (android::base::GetBoolProperty("ro.virtual_ab.enabled", false)) {
bigbiffcfa875c2021-06-20 16:20:27 -04001772#ifndef TW_EXCLUDE_APEX
1773 twrpApex apex;
1774 apex.Unmount();
1775#endif
1776 if (metadata != NULL)
1777 metadata->Mount(true);
bigbiffd21252f2021-09-18 15:56:32 -04001778 if (!Check_Pending_Merges())
bigbiffcfa875c2021-06-20 16:20:27 -04001779 return false;
1780 }
Captain Throwbackab76e402023-10-04 10:01:17 -04001781 ret = dat->Wipe_Encryption();
1782 if (ret)
1783 TWFunc::check_and_run_script("/system/bin/formatdata.sh", "Format Data Script");
1784 return ret;
Dees_Troy38bd7602012-09-14 13:33:53 -04001785 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001786 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001787 return false;
1788 }
1789 return false;
1790}
1791
1792int TWPartitionManager::Wipe_Media_From_Data(void) {
1793 TWPartition* dat = Find_Partition_By_Path("/data");
1794
1795 if (dat != NULL) {
1796 if (!dat->Has_Data_Media) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001797 LOGERR("This device does not have /data/media\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001798 return false;
1799 }
1800 if (!dat->Mount(true))
1801 return false;
1802
Ethan Yonker74db1572015-10-28 12:44:49 -05001803 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
Ethan Yonker726a0202014-12-16 20:01:38 -06001804 Remove_MTP_Storage(dat->MTP_Storage_ID);
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001805 TWFunc::removeDir("/data/media", false);
xiaolu9416f4f2015-06-04 08:22:23 +08001806 dat->Recreate_Media_Folder();
Ethan Yonker726a0202014-12-16 20:01:38 -06001807 Add_MTP_Storage(dat->MTP_Storage_ID);
Dees_Troy38bd7602012-09-14 13:33:53 -04001808 return true;
1809 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001810 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001811 return false;
1812 }
1813 return false;
1814}
1815
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001816int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1817 std::vector<TWPartition*>::iterator iter;
1818 int ret = false;
1819 bool found = false;
1820 string Local_Path = TWFunc::Get_Root_Path(Path);
1821
1822 if (Local_Path == "/tmp" || Local_Path == "/")
1823 return true;
1824
1825 // Iterate through all partitions
1826 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1827 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1828 ret = (*iter)->Repair();
1829 found = true;
1830 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1831 (*iter)->Repair();
1832 }
1833 }
1834 if (found) {
1835 return ret;
1836 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001837 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 -05001838 } else {
1839 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1840 }
1841 return false;
1842}
1843
Ethan Yonkera2719152015-05-28 09:44:41 -05001844int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1845 std::vector<TWPartition*>::iterator iter;
1846 int ret = false;
1847 bool found = false;
1848 string Local_Path = TWFunc::Get_Root_Path(Path);
1849
1850 if (Local_Path == "/tmp" || Local_Path == "/")
1851 return true;
1852
1853 // Iterate through all partitions
1854 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1855 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1856 ret = (*iter)->Resize();
1857 found = true;
1858 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1859 (*iter)->Resize();
1860 }
1861 }
1862 if (found) {
1863 return ret;
1864 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001865 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 -05001866 } else {
1867 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1868 }
1869 return false;
1870}
1871
Dees_Troy51a0e822012-09-05 15:24:24 -04001872void TWPartitionManager::Update_System_Details(void) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001873 std::vector<TWPartition*>::iterator iter;
Dees_Troy51127312012-09-08 13:08:49 -04001874 int data_size = 0;
Dees_Troy5bf43922012-09-07 16:07:55 -04001875
Ethan Yonker74db1572015-10-28 12:44:49 -05001876 gui_msg("update_part_details=Updating partition details...");
Dees_Troy5bf43922012-09-07 16:07:55 -04001877 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker1b190162016-12-05 15:25:19 -06001878 (*iter)->Update_Size(true);
Dees_Troy51127312012-09-08 13:08:49 -04001879 if ((*iter)->Can_Be_Mounted) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001880 if ((*iter)->Mount_Point == Get_Android_Root_Path()) {
Dees_Troy51127312012-09-08 13:08:49 -04001881 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1882 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001883 TWFunc::Is_TWRP_App_In_System();
Dees_Troy51127312012-09-08 13:08:49 -04001884 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1885 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1886 } else if ((*iter)->Mount_Point == "/cache") {
1887 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1888 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1889 } else if ((*iter)->Mount_Point == "/sd-ext") {
1890 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1891 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1892 if ((*iter)->Backup_Size == 0) {
1893 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1894 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1895 } else
1896 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
Dees_Troye58d5262012-09-21 12:27:57 -04001897 } else if ((*iter)->Has_Android_Secure) {
Dees_Troy8170a922012-09-18 15:40:25 -04001898 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troye58d5262012-09-21 12:27:57 -04001899 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
Dees_Troy8170a922012-09-18 15:40:25 -04001900 if ((*iter)->Backup_Size == 0) {
1901 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1902 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1903 } else
1904 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
Dees_Troy2c50e182012-09-26 20:05:28 -04001905 } else if ((*iter)->Mount_Point == "/boot") {
1906 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1907 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1908 if ((*iter)->Backup_Size == 0) {
1909 DataManager::SetValue("tw_has_boot_partition", 0);
1910 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1911 } else
1912 DataManager::SetValue("tw_has_boot_partition", 1);
Dees_Troy51127312012-09-08 13:08:49 -04001913 }
Dees_Troyaa9cc402012-10-13 12:14:05 -04001914 } else {
1915 // Handle unmountable partitions in case we reset defaults
1916 if ((*iter)->Mount_Point == "/boot") {
1917 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1918 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1919 if ((*iter)->Backup_Size == 0) {
1920 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1921 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1922 } else
1923 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1924 } else if ((*iter)->Mount_Point == "/recovery") {
1925 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1926 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1927 if ((*iter)->Backup_Size == 0) {
1928 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1929 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1930 } else
1931 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
Gary Peck82599a82012-11-21 16:23:12 -08001932 } else if ((*iter)->Mount_Point == "/data") {
1933 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troyaa9cc402012-10-13 12:14:05 -04001934 }
Dees_Troy51127312012-09-08 13:08:49 -04001935 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001936 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001937 gui_msg("update_part_details_done=...done");
Dees_Troy51127312012-09-08 13:08:49 -04001938 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1939 string current_storage_path = DataManager::GetCurrentStoragePath();
1940 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
Dees_Troy8170a922012-09-18 15:40:25 -04001941 if (FreeStorage != NULL) {
1942 // Attempt to mount storage
bigbiff25d25b92020-06-19 16:07:38 -04001943 if (!FreeStorage->Mount(false)) {
1944 gui_msg(Msg(msg::kWarning, "unable_to_mount_storage=Unable to mount storage"));
1945 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
1946 } else {
1947 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
Dees_Troy8170a922012-09-18 15:40:25 -04001948 }
1949 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00001950 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
Dees_Troy8170a922012-09-18 15:40:25 -04001951 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001952 if (!Write_Fstab())
Dees_Troy2673cec2013-04-02 20:22:16 +00001953 LOGERR("Error creating fstab\n");
Dees_Troy51a0e822012-09-05 15:24:24 -04001954 return;
1955}
1956
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001957void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1958 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffc2cb3852020-09-11 14:03:31 -04001959
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001960 if (dat != NULL) {
bigbiffaed1bdf2021-08-03 18:21:39 -04001961 // reparse for /cache/recovery/command
1962 static constexpr const char* COMMAND_FILE = "/data/cache/command";
1963 if (TWFunc::Path_Exists(COMMAND_FILE)) {
1964 startupArgs startup;
1965 std::string content;
1966 TWFunc::read_file(COMMAND_FILE, content);
1967 std::vector<std::string> args = {content};
1968 startup.processRecoveryArgs(args, 0);
1969 }
1970
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001971 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1972 dat->Is_Decrypted = true;
1973 if (!Block_Device.empty()) {
1974 dat->Decrypted_Block_Device = Block_Device;
1975 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1976 } else {
1977 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1978 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001979 property_set("twrp.decrypt.done", "true");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001980 dat->Setup_File_System(false);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001981 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 -06001982
Noah Jacobson81d638d2019-04-28 00:10:07 -04001983 sleep(1); // Sleep for a bit so that the device will be ready
me-cafebabe09649612022-06-10 21:53:31 +08001984
1985 // Mount only /data
1986 dat->Symlink_Path = ""; // Not to let it to bind mount /data/media again
1987 if (!dat->Mount(false)) {
1988 LOGERR("Unable to mount /data after decryption");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001989 }
me-cafebabe09649612022-06-10 21:53:31 +08001990
1991 if (dat->Has_Data_Media && TWFunc::Path_Exists("/data/media/0")) {
1992 dat->Storage_Path = "/data/media/0";
1993 } else {
1994 dat->Storage_Path = "/data/media";
1995 }
1996 dat->Symlink_Path = dat->Storage_Path;
1997 DataManager::SetValue("tw_storage_path", dat->Symlink_Path);
Mohd Farazf9231102022-06-18 22:51:55 +02001998 DataManager::SetValue("tw_settings_path", TW_STORAGE_PATH);
me-cafebabe09649612022-06-10 21:53:31 +08001999 LOGINFO("New storage path after decryption: %s\n", dat->Storage_Path.c_str());
2000
epicXa721f952021-01-04 13:01:31 +05302001 DataManager::LoadTWRPFolderInfo();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002002 Update_System_Details();
nkk71ffb02bd2017-06-04 23:12:16 +03002003 Output_Partition(dat);
bigbiff4fa02b52021-12-30 17:01:44 -05002004 if (!android::base::StartsWith(dat->Actual_Block_Device, "/dev/block/mmcblk")) {
2005 if (!dat->Bind_Mount(false))
2006 LOGERR("Unable to bind mount /sdcard to %s\n", dat->Storage_Path.c_str());
2007 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002008 } else
2009 LOGERR("Unable to locate data partition.\n");
2010}
2011
Noah Jacobson81d638d2019-04-28 00:10:07 -04002012void TWPartitionManager::Parse_Users() {
2013#ifdef TW_INCLUDE_FBE
2014 char user_check_result[PROPERTY_VALUE_MAX];
2015 for (int userId = 0; userId <= 9999; userId++) {
2016 string prop = "twrp.user." + to_string(userId) + ".decrypt";
2017 property_get(prop.c_str(), user_check_result, "-1");
2018 if (strcmp(user_check_result, "-1") != 0) {
2019 if (userId < 0 || userId > 9999) {
2020 LOGINFO("Incorrect user id %d\n", userId);
2021 continue;
2022 }
2023 struct users_struct user;
2024 user.userId = to_string(userId);
2025
2026 // Attempt to get name of user. Fallback to user ID if this fails.
Darth98f775972022-08-05 09:39:03 +01002027 std::string path = "/data/system/users/" + to_string(userId) + ".xml";
2028 if (!TWFunc::Check_Xml_Format(path)) {
2029 string oldpath = path;
2030 if (TWFunc::abx_to_xml(oldpath, path)) {
2031 LOGINFO("Android 12+: '%s' has been converted into plain text xml (for user %s).\n", oldpath.c_str(), user.userId.c_str());
2032 }
2033 }
2034 char* userFile = PageManager::LoadFileToBuffer(path, NULL);
me-cafebabec46981d2022-07-29 01:54:43 +08002035 if (userFile == NULL) {
2036 user.userName = to_string(userId);
bigbiffa957f072021-03-07 18:20:29 -05002037 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04002038 else {
me-cafebabec46981d2022-07-29 01:54:43 +08002039 xml_document<> *userXml = new xml_document<>();
2040 userXml->parse<0>(userFile);
2041 xml_node<>* userNode = userXml->first_node("user");
2042 if (userNode == nullptr) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04002043 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08002044 } else {
2045 xml_node<>* nameNode = userNode->first_node("name");
2046 if (nameNode == nullptr)
Noah Jacobson81d638d2019-04-28 00:10:07 -04002047 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08002048 else {
2049 string userName = nameNode->value();
2050 user.userName = userName + " (" + to_string(userId) + ")";
Noah Jacobson81d638d2019-04-28 00:10:07 -04002051 }
2052 }
2053 }
2054
2055 string filename;
bigbiffdf53b6c2022-01-17 19:31:52 -05002056 user.type = android::keystore::Get_Password_Type(userId, filename);
Noah Jacobson81d638d2019-04-28 00:10:07 -04002057
2058 user.isDecrypted = false;
2059 if (strcmp(user_check_result, "1") == 0)
2060 user.isDecrypted = true;
2061 Users_List.push_back(user);
2062 }
2063 }
2064 Check_Users_Decryption_Status();
2065#endif
2066}
2067
2068std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
2069 return &Users_List;
2070}
2071
2072void TWPartitionManager::Mark_User_Decrypted(int userID) {
2073#ifdef TW_INCLUDE_FBE
2074 std::vector<users_struct>::iterator iter;
2075 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2076 if (atoi((*iter).userId.c_str()) == userID) {
2077 (*iter).isDecrypted = true;
2078 string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
2079 property_set(user_prop_decrypted.c_str(), "1");
2080 break;
2081 }
2082 }
2083 Check_Users_Decryption_Status();
2084#endif
2085}
2086
2087void TWPartitionManager::Check_Users_Decryption_Status() {
2088#ifdef TW_INCLUDE_FBE
2089 int all_is_decrypted = 1;
2090 std::vector<users_struct>::iterator iter;
2091 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2092 if (!(*iter).isDecrypted) {
2093 LOGINFO("User %s is not decrypted.\n", (*iter).userId.c_str());
2094 all_is_decrypted = 0;
2095 break;
2096 }
2097 }
2098 if (all_is_decrypted == 1) {
2099 LOGINFO("All found users are decrypted.\n");
2100 DataManager::SetValue("tw_all_users_decrypted", "1");
2101 property_set("twrp.all.users.decrypted", "true");
2102 } else
2103 DataManager::SetValue("tw_all_users_decrypted", "0");
2104#endif
2105}
2106
2107int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
Dees_Troy5bf43922012-09-07 16:07:55 -04002108#ifdef TW_INCLUDE_CRYPTO
Captain Throwback37c3aef2021-10-06 11:38:18 -04002109 char crypto_blkdev[PROPERTY_VALUE_MAX];
Ethan Yonker253368a2014-11-25 15:00:52 -06002110 std::vector<TWPartition*>::iterator iter;
Dees_Troy5bf43922012-09-07 16:07:55 -04002111
Ethan Yonker253368a2014-11-25 15:00:52 -06002112 // Mount any partitions that need to be mounted for decrypt
2113 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2114 if ((*iter)->Mount_To_Decrypt) {
2115 (*iter)->Mount(true);
2116 }
a39552696ff55ce2013-01-08 16:14:56 +00002117 }
oshmouna82a7542018-04-10 17:45:55 +02002118 property_set("twrp.mount_to_decrypt", "1");
a39552696ff55ce2013-01-08 16:14:56 +00002119
Captain Throwback37c3aef2021-10-06 11:38:18 -04002120 Set_Crypto_State();
2121 Set_Crypto_Type("block");
Ethan Yonkera1de1492015-11-04 11:58:27 -06002122
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002123 if (DataManager::GetIntValue(TW_IS_FBE)) {
2124#ifdef TW_INCLUDE_FBE
2125 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
2126 return -1;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002127
2128 bool user_need_decrypt = false;
2129 std::vector<users_struct>::iterator iter;
2130 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2131 if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
2132 user_need_decrypt = true;
2133 }
2134 }
2135 if (!user_need_decrypt) {
2136 LOGINFO("User %d does not require decryption\n", user_id);
2137 return 0;
2138 }
2139
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002140 int retry_count = 10;
2141 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
Noah Jacobson81d638d2019-04-28 00:10:07 -04002142 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
2143 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002144 if (android::keystore::Decrypt_User(user_id, Password)) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04002145 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
2146 Mark_User_Decrypted(user_id);
2147 if (user_id == 0) {
2148 // When decrypting user 0 also try all other users
2149 std::vector<users_struct>::iterator iter;
2150 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2151 if ((*iter).userId == "0" || (*iter).isDecrypted)
2152 continue;
2153
2154 int tmp_user_id = atoi((*iter).userId.c_str());
2155 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002156 if (android::keystore::Decrypt_User(tmp_user_id, Password) ||
2157 (Password != "!" && android::keystore::Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
Noah Jacobson81d638d2019-04-28 00:10:07 -04002158 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
2159 Mark_User_Decrypted(tmp_user_id);
2160 } else {
2161 gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
2162 }
2163 }
2164 Post_Decrypt("");
2165 }
2166
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002167 return 0;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002168 } else {
2169 gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002170 }
2171#else
2172 LOGERR("FBE support is not present\n");
2173#endif
2174 return -1;
2175 }
2176
Noah Jacobson81d638d2019-04-28 00:10:07 -04002177 char isdecrypteddata[PROPERTY_VALUE_MAX];
2178 property_get("twrp.decrypt.done", isdecrypteddata, "");
2179 if (strcmp(isdecrypteddata, "true") == 0) {
2180 LOGINFO("Data has no decryption required\n");
2181 return 0;
2182 }
2183
Ethan Yonkerddb63e22017-01-19 14:01:57 -06002184 int pwret = -1;
2185 pid_t pid = fork();
2186 if (pid < 0) {
2187 LOGERR("fork failed\n");
2188 return -1;
2189 } else if (pid == 0) {
2190 // Child process
2191 char cPassword[255];
2192 strcpy(cPassword, Password.c_str());
2193 int ret = cryptfs_check_passwd(cPassword);
2194 exit(ret);
2195 } else {
2196 // Parent
2197 int status;
2198 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
2199 pwret = -1;
2200 else
2201 pwret = WEXITSTATUS(status) ? -1 : 0;
2202 }
a39552696ff55ce2013-01-08 16:14:56 +00002203
Ethan Yonker253368a2014-11-25 15:00:52 -06002204 // Unmount any partitions that were needed for decrypt
2205 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2206 if ((*iter)->Mount_To_Decrypt) {
2207 (*iter)->UnMount(false);
2208 }
2209 }
oshmouna82a7542018-04-10 17:45:55 +02002210 property_set("twrp.mount_to_decrypt", "0");
Ethan Yonker253368a2014-11-25 15:00:52 -06002211
a39552696ff55ce2013-01-08 16:14:56 +00002212 if (pwret != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002213 gui_err("fail_decrypt=Failed to decrypt data.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002214 return -1;
2215 }
a39552696ff55ce2013-01-08 16:14:56 +00002216
Dees_Troy5bf43922012-09-07 16:07:55 -04002217 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
2218 if (strcmp(crypto_blkdev, "error") == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002219 LOGERR("Error retrieving decrypted data block device.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -04002220 } else {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002221 Post_Decrypt(crypto_blkdev);
Dees_Troy5bf43922012-09-07 16:07:55 -04002222 }
2223 return 0;
2224#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002225 gui_err("no_crypto_support=No crypto support was compiled into this build.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002226 return -1;
2227#endif
Dees_Troy51a0e822012-09-05 15:24:24 -04002228 return 1;
Dees_Troy51127312012-09-08 13:08:49 -04002229}
2230
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002231int TWPartitionManager::Fix_Contexts(void) {
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002232 std::vector<TWPartition*>::iterator iter;
2233 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2234 if ((*iter)->Has_Data_Media) {
2235 if ((*iter)->Mount(true)) {
2236 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
2237 return -1;
2238 }
2239 }
2240 }
Dees_Troy1a650e62012-10-19 20:54:32 -04002241 UnMount_Main_Partitions();
Ethan Yonker74db1572015-10-28 12:44:49 -05002242 gui_msg("done=Done.");
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002243 return 0;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002244}
2245
Ethan Yonker66a19492015-12-10 10:19:45 -06002246TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002247 std::vector<TWPartition*>::iterator iter = Partitions.begin();
2248
2249 if (!Path.empty()) {
2250 string Search_Path = TWFunc::Get_Root_Path(Path);
2251 for (; iter != Partitions.end(); iter++) {
Matt Mower9a561dd2016-02-22 21:25:51 -06002252 if ((*iter)->Mount_Point == Search_Path) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002253 iter++;
2254 break;
2255 }
2256 }
2257 }
2258
2259 for (; iter != Partitions.end(); iter++) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002260 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
2261 // do nothing, do not return this type of partition
2262 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002263 return (*iter);
2264 }
2265 }
2266
2267 return NULL;
2268}
2269
Dees_Troyd21618c2012-10-14 18:48:49 -04002270int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
Dees_Troyd21618c2012-10-14 18:48:49 -04002271 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
2272
2273 if (Part == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002274 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
2275 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 -04002276 return false;
2277 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002278 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
2279 if (!Part->UnMount(true) || !Part->Is_Present)
Dees_Troyd21618c2012-10-14 18:48:49 -04002280 return false;
2281
bigbiff22851b92021-09-01 16:46:57 -04002282 if (!TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002283 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
Dees_Troyd21618c2012-10-14 18:48:49 -04002284 return false;
2285 }
Dees_Troyd21618c2012-10-14 18:48:49 -04002286 return true;
2287}
2288
Dees_Troy8170a922012-09-18 15:40:25 -04002289int TWPartitionManager::usb_storage_enable(void) {
Dees_Troy8170a922012-09-18 15:40:25 -04002290 char lun_file[255];
Dees_Troyd21618c2012-10-14 18:48:49 -04002291 bool has_multiple_lun = false;
Dees_Troy8170a922012-09-18 15:40:25 -04002292
Ethan Yonker47360be2014-04-01 10:34:34 -05002293 string Lun_File_str = CUSTOM_LUN_FILE;
2294 size_t found = Lun_File_str.find("%");
2295 if (found != string::npos) {
2296 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
2297 if (TWFunc::Path_Exists(lun_file))
2298 has_multiple_lun = true;
2299 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002300 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
Ethan Yonker47360be2014-04-01 10:34:34 -05002301 if (!has_multiple_lun) {
2302 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
2303 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
2304 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
Ethan Yonker66a19492015-12-10 10:19:45 -06002305 TWPartition* Mount = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002306 if (Mount) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002307 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
2308 goto error_handle;
2309 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002310 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002311 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002312 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002313 }
2314 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002315 goto error_handle;
Dees_Troy8170a922012-09-18 15:40:25 -04002316 }
Dees_Troy8170a922012-09-18 15:40:25 -04002317 } else {
Ethan Yonker47360be2014-04-01 10:34:34 -05002318 LOGINFO("Device has multiple lun files\n");
2319 TWPartition* Mount1;
2320 TWPartition* Mount2;
Dees_Troy8170a922012-09-18 15:40:25 -04002321 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
Ethan Yonker66a19492015-12-10 10:19:45 -06002322 Mount1 = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002323 if (Mount1) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002324 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
2325 goto error_handle;
2326 }
Matt Moweree717062014-04-26 01:46:46 -05002327 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
Ethan Yonker66a19492015-12-10 10:19:45 -06002328 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
Matt Mower1fdcdb72016-01-25 20:53:47 -06002329 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
Matt Moweree717062014-04-26 01:46:46 -05002330 Open_Lun_File(Mount2->Mount_Point, lun_file);
nkk717aa6fc62017-03-24 18:28:03 +02002331 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2332 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data") {
2333 Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file);
Ethan Yonker47360be2014-04-01 10:34:34 -05002334 }
nkk717aa6fc62017-03-24 18:28:03 +02002335 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2336 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data" && !Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002337 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002338 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002339 }
Dees_Troy8170a922012-09-18 15:40:25 -04002340 }
Matt Mowerb6ef4782014-11-06 02:24:36 -06002341 property_set("sys.storage.ums_enabled", "1");
HandyMenny37d42992014-10-26 22:15:59 +01002342 property_set("sys.usb.config", "mass_storage,adb");
Dees_Troy8170a922012-09-18 15:40:25 -04002343 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002344error_handle:
2345 if (mtp_was_enabled)
2346 if (!Enable_MTP())
2347 Disable_MTP();
2348 return false;
Dees_Troy8170a922012-09-18 15:40:25 -04002349}
2350
2351int TWPartitionManager::usb_storage_disable(void) {
bigbiff22851b92021-09-01 16:46:57 -04002352 int index, ret = 0;
Dees_Troy2673cec2013-04-02 20:22:16 +00002353 char lun_file[255], ch[2] = {0, 0};
2354 string str = ch;
Dees_Troy8170a922012-09-18 15:40:25 -04002355
2356 for (index=0; index<2; index++) {
2357 sprintf(lun_file, CUSTOM_LUN_FILE, index);
bigbiff22851b92021-09-01 16:46:57 -04002358 if (!TWFunc::write_to_file(lun_file, str)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002359 break;
bigbiff22851b92021-09-01 16:46:57 -04002360 ret = -1;
Dees_Troy8170a922012-09-18 15:40:25 -04002361 }
Dees_Troy8170a922012-09-18 15:40:25 -04002362 }
Dees_Troye58d5262012-09-21 12:27:57 -04002363 Mount_All_Storage();
2364 Update_System_Details();
Dees_Troycfd73ef2012-10-12 16:52:00 -04002365 UnMount_Main_Partitions();
Matt Mowerd9cb9062013-12-14 20:34:45 -06002366 property_set("sys.storage.ums_enabled", "0");
HandyMenny37d42992014-10-26 22:15:59 +01002367 property_set("sys.usb.config", "adb");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002368 if (mtp_was_enabled)
2369 if (!Enable_MTP())
2370 Disable_MTP();
Dees_Troy2673cec2013-04-02 20:22:16 +00002371 if (ret < 0 && index == 0) {
2372 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
2373 return false;
2374 } else {
2375 return true;
2376 }
Dees_Troy8170a922012-09-18 15:40:25 -04002377 return true;
Dees_Troy812660f2012-09-20 09:55:17 -04002378}
2379
2380void TWPartitionManager::Mount_All_Storage(void) {
2381 std::vector<TWPartition*>::iterator iter;
2382
2383 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2384 if ((*iter)->Is_Storage)
2385 (*iter)->Mount(false);
2386 }
Dees_Troy2c50e182012-09-26 20:05:28 -04002387}
Dees_Troy9350b8d2012-09-27 12:38:38 -04002388
Dees_Troyd0384ef2012-10-12 12:15:42 -04002389void TWPartitionManager::UnMount_Main_Partitions(void) {
2390 // Unmounts system and data if data is not data/media
2391 // Also unmounts boot if boot is mountable
Dees_Troy2673cec2013-04-02 20:22:16 +00002392 LOGINFO("Unmounting main partitions...\n");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002393
Mohd Faraze3948ec2020-08-14 01:40:59 +00002394 TWPartition *Partition = Find_Partition_By_Path ("/vendor");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002395
Mohd Faraze3948ec2020-08-14 01:40:59 +00002396 if (Partition != NULL) UnMount_By_Path("/vendor", false);
2397 UnMount_By_Path (Get_Android_Root_Path(), true);
2398 Partition = Find_Partition_By_Path ("/product");
2399 if (Partition != NULL) UnMount_By_Path("/product", false);
Ethan Yonker6277c792014-09-15 14:54:30 -05002400 if (!datamedia)
2401 UnMount_By_Path("/data", true);
2402
Mohd Faraze3948ec2020-08-14 01:40:59 +00002403 Partition = Find_Partition_By_Path ("/boot");
2404 if (Partition != NULL && Partition->Can_Be_Mounted)
2405 Partition->UnMount(true);
Dees_Troyd0384ef2012-10-12 12:15:42 -04002406}
2407
Dees_Troy9350b8d2012-09-27 12:38:38 -04002408int TWPartitionManager::Partition_SDCard(void) {
Matt Mower23d8aae2017-01-06 14:30:33 -06002409 char temp[255];
Ethan Yonker483e9f42016-01-11 22:21:18 -06002410 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 -04002411 int ext, swap, total_size = 0, fat_size;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002412
Ethan Yonker74db1572015-10-28 12:44:49 -05002413 gui_msg("start_partition_sd=Partitioning SD Card...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002414
2415 // Locate and validate device to partition
2416 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
2417
Ethan Yonker66a19492015-12-10 10:19:45 -06002418 if (SDCard->Is_Adopted_Storage)
2419 SDCard->Revert_Adopted();
2420
Ethan Yonker1eff6cd2014-09-15 13:30:42 -05002421 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002422 gui_err("partition_sd_locate=Unable to locate device to partition.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002423 return false;
2424 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002425
2426 // Unmount everything
Dees_Troy9350b8d2012-09-27 12:38:38 -04002427 if (!SDCard->UnMount(true))
2428 return false;
2429 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
2430 if (SDext != NULL) {
2431 if (!SDext->UnMount(true))
2432 return false;
2433 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002434 char* swappath = getenv("SWAPPATH");
2435 if (swappath != NULL) {
2436 LOGINFO("Unmounting swap at '%s'\n", swappath);
2437 umount(swappath);
2438 }
Vojtech Bocek05534202013-09-11 08:11:56 +02002439
Ethan Yonker483e9f42016-01-11 22:21:18 -06002440 // Determine block device
2441 if (SDCard->Alternate_Block_Device.empty()) {
2442 SDCard->Find_Actual_Block_Device();
2443 Device = SDCard->Actual_Block_Device;
2444 // Just use the root block device
2445 Device.resize(strlen("/dev/block/mmcblkX"));
2446 } else {
2447 Device = SDCard->Alternate_Block_Device;
2448 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002449
2450 // Find the size of the block device:
Ethan Yonker483e9f42016-01-11 22:21:18 -06002451 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002452
2453 DataManager::GetValue("tw_sdext_size", ext);
2454 DataManager::GetValue("tw_swap_size", swap);
2455 DataManager::GetValue("tw_sdpart_file_system", ext_format);
2456 fat_size = total_size - ext - swap;
Ethan Yonker483e9f42016-01-11 22:21:18 -06002457 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);
2458
2459 // Determine partition sizes
2460 if (swap == 0 && ext == 0) {
2461 fat_str = "-0";
2462 } else {
2463 memset(temp, 0, sizeof(temp));
2464 sprintf(temp, "%i", fat_size);
2465 fat_str = temp;
2466 fat_str += "MB";
2467 }
2468 if (swap == 0) {
2469 ext_str = "-0";
2470 } else {
2471 memset(temp, 0, sizeof(temp));
2472 sprintf(temp, "%i", ext);
2473 ext_str = "+";
2474 ext_str += temp;
2475 ext_str += "MB";
2476 }
2477
Dees_Troy9350b8d2012-09-27 12:38:38 -04002478 if (ext + swap > total_size) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002479 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002480 return false;
2481 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002482
Ethan Yonker74db1572015-10-28 12:44:49 -05002483 gui_msg("remove_part_table=Removing partition table...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002484 Command = "sgdisk --zap-all " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002485 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002486 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002487 gui_err("unable_rm_part=Unable to remove partition table.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002488 Update_System_Details();
2489 return false;
2490 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002491 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
Captain Throwback9643a802016-05-27 11:44:51 -04002492 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 +00002493 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002494 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002495 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002496 return false;
2497 }
2498 if (ext > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002499 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002500 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002501 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002502 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002503 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002504 Update_System_Details();
2505 return false;
2506 }
2507 }
2508 if (swap > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002509 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002510 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 +00002511 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002512 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002513 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002514 Update_System_Details();
2515 return false;
2516 }
2517 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002518
2519 // Convert GPT to MBR
2520 Command = "sgdisk --gpttombr " + Device;
2521 if (TWFunc::Exec_Cmd(Command) != 0)
2522 LOGINFO("Failed to covert partition GPT to MBR\n");
2523
2524 // Tell the kernel to rescan the partition table
2525 int fd = open(Device.c_str(), O_RDONLY);
2526 ioctl(fd, BLKRRPART, 0);
2527 close(fd);
2528
2529 string format_device = Device;
2530 if (Device.substr(0, 17) == "/dev/block/mmcblk")
2531 format_device += "p";
2532
2533 // Format new partitions to proper file system
2534 if (fat_size > 0) {
2535 Command = "mkfs.fat " + format_device + "1";
2536 TWFunc::Exec_Cmd(Command);
2537 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002538 if (ext > 0) {
2539 if (SDext == NULL) {
Ethan Yonker483e9f42016-01-11 22:21:18 -06002540 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2541 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2542 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2543 TWFunc::Exec_Cmd(Command);
2544 } else {
2545 SDext->Wipe(ext_format);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002546 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002547 }
2548 if (swap > 0) {
2549 Command = "mkswap " + format_device;
2550 if (ext > 0)
2551 Command += "3";
2552 else
2553 Command += "2";
Vojtech Bocek05534202013-09-11 08:11:56 +02002554 TWFunc::Exec_Cmd(Command);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002555 }
2556
Ethan Yonker483e9f42016-01-11 22:21:18 -06002557 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2558 if (SDCard->Mount(true)) {
2559 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2560 mkdir(TWRP_Folder.c_str(), 0777);
2561 DataManager::Flush();
2562 }
2563
Dees_Troy9350b8d2012-09-27 12:38:38 -04002564 Update_System_Details();
Ethan Yonker74db1572015-10-28 12:44:49 -05002565 gui_msg("part_complete=Partitioning complete.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002566 return true;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002567}
Dees_Troya13d74f2013-03-24 08:54:55 -05002568
2569void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2570 std::vector<TWPartition*>::iterator iter;
2571 if (ListType == "mount") {
2572 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002573 if ((*iter)->Can_Be_Mounted) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002574 struct PartitionList part;
2575 part.Display_Name = (*iter)->Display_Name;
2576 part.Mount_Point = (*iter)->Mount_Point;
2577 part.selected = (*iter)->Is_Mounted();
2578 Partition_List->push_back(part);
2579 }
2580 }
2581 } else if (ListType == "storage") {
2582 char free_space[255];
2583 string Current_Storage = DataManager::GetCurrentStoragePath();
2584 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2585 if ((*iter)->Is_Storage) {
2586 struct PartitionList part;
2587 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2588 part.Display_Name = (*iter)->Storage_Name + " (";
2589 part.Display_Name += free_space;
2590 part.Display_Name += "MB)";
2591 part.Mount_Point = (*iter)->Storage_Path;
2592 if ((*iter)->Storage_Path == Current_Storage)
2593 part.selected = 1;
2594 else
2595 part.selected = 0;
2596 Partition_List->push_back(part);
2597 }
2598 }
2599 } else if (ListType == "backup") {
2600 char backup_size[255];
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002601 unsigned long long Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05002602 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002603 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002604 struct PartitionList part;
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002605 Backup_Size = (*iter)->Backup_Size;
2606 if ((*iter)->Has_SubPartition) {
2607 std::vector<TWPartition*>::iterator subpart;
2608
2609 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2610 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2611 Backup_Size += (*subpart)->Backup_Size;
2612 }
2613 }
2614 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
Dees_Troya13d74f2013-03-24 08:54:55 -05002615 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2616 part.Display_Name += backup_size;
2617 part.Display_Name += "MB)";
2618 part.Mount_Point = (*iter)->Backup_Path;
2619 part.selected = 0;
2620 Partition_List->push_back(part);
2621 }
2622 }
2623 } else if (ListType == "restore") {
2624 string Restore_List, restore_path;
2625 TWPartition* restore_part = NULL;
2626
2627 DataManager::GetValue("tw_restore_list", Restore_List);
2628 if (!Restore_List.empty()) {
2629 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2630 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2631 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002632 struct PartitionList part;
2633 if (restore_path.compare("ADB_Backup") == 0) {
2634 part.Display_Name = "ADB Backup";
2635 part.Mount_Point = "ADB Backup";
2636 part.selected = 1;
2637 Partition_List->push_back(part);
2638 break;
2639 }
Dees_Troy59df9262013-06-19 14:53:57 -05002640 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
Dees Troy4159aed2014-02-28 17:24:43 +00002641 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002642 // Don't allow restore of recovery (causes problems on some devices)
Dees_Troy59df9262013-06-19 14:53:57 -05002643 // Don't add subpartitions to the list of items
Dees_Troya13d74f2013-03-24 08:54:55 -05002644 } else {
Dees_Troya13d74f2013-03-24 08:54:55 -05002645 part.Display_Name = restore_part->Backup_Display_Name;
2646 part.Mount_Point = restore_part->Backup_Path;
2647 part.selected = 1;
2648 Partition_List->push_back(part);
2649 }
2650 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002651 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05002652 }
2653 start_pos = end_pos + 1;
2654 end_pos = Restore_List.find(";", start_pos);
2655 }
2656 }
2657 } else if (ListType == "wipe") {
2658 struct PartitionList dalvik;
Ethan Yonker74db1572015-10-28 12:44:49 -05002659 dalvik.Display_Name = gui_parse_text("{@dalvik}");
Dees_Troya13d74f2013-03-24 08:54:55 -05002660 dalvik.Mount_Point = "DALVIK";
2661 dalvik.selected = 0;
2662 Partition_List->push_back(dalvik);
2663 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2664 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2665 struct PartitionList part;
2666 part.Display_Name = (*iter)->Display_Name;
2667 part.Mount_Point = (*iter)->Mount_Point;
2668 part.selected = 0;
2669 Partition_List->push_back(part);
2670 }
2671 if ((*iter)->Has_Android_Secure) {
2672 struct PartitionList part;
2673 part.Display_Name = (*iter)->Backup_Display_Name;
2674 part.Mount_Point = (*iter)->Backup_Path;
2675 part.selected = 0;
2676 Partition_List->push_back(part);
2677 }
Dees_Troy74fb2e92013-04-15 14:35:47 +00002678 if ((*iter)->Has_Data_Media) {
2679 struct PartitionList datamedia;
2680 datamedia.Display_Name = (*iter)->Storage_Name;
2681 datamedia.Mount_Point = "INTERNAL";
2682 datamedia.selected = 0;
2683 Partition_List->push_back(datamedia);
2684 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002685 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002686 } else if (ListType == "flashimg") {
2687 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2688 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2689 struct PartitionList part;
2690 part.Display_Name = (*iter)->Backup_Display_Name;
2691 part.Mount_Point = (*iter)->Backup_Path;
2692 part.selected = 0;
2693 Partition_List->push_back(part);
2694 }
2695 }
Darth98af7fe22024-01-18 20:00:44 +00002696 if (DataManager::GetIntValue("tw_has_repack_tools") != 0 && DataManager::GetIntValue("tw_has_boot_slots") != 0 && DataManager::GetIntValue("tw_include_install_recovery_ramdisk") != 0) {
2697 std::string dest_partition = "/boot";
2698 #ifdef BOARD_MOVE_RECOVERY_RESOURCES_TO_VENDOR_BOOT
2699 dest_partition = "/vendor_boot";
2700 #endif
2701
2702 TWPartition* boot = Find_Partition_By_Path(dest_partition);
Ethan Yonker53796e72019-01-11 22:49:52 -06002703 if (boot) {
2704 // Allow flashing kernels and ramdisks
2705 struct PartitionList repack_ramdisk;
2706 repack_ramdisk.Display_Name = gui_lookup("install_twrp_ramdisk", "Install Recovery Ramdisk");
2707 repack_ramdisk.Mount_Point = "/repack_ramdisk";
2708 repack_ramdisk.selected = 0;
2709 Partition_List->push_back(repack_ramdisk);
Darth98af7fe22024-01-18 20:00:44 +00002710 LOGINFO("Install Recovery Ramdisk: target partition=%s\n", dest_partition.c_str());
Ethan Yonker53796e72019-01-11 22:49:52 -06002711 /*struct PartitionList repack_kernel; For now let's leave repacking kernels under advanced only
2712 repack_kernel.Display_Name = gui_lookup("install_kernel", "Install Kernel");
2713 repack_kernel.Mount_Point = "/repack_kernel";
2714 repack_kernel.selected = 0;
2715 Partition_List->push_back(repack_kernel);*/
2716 }
2717 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002718 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00002719 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05002720 }
2721}
2722
2723int TWPartitionManager::Fstab_Processed(void) {
2724 return Partitions.size();
2725}
Dees_Troyd93bda52013-07-03 19:55:19 +00002726
2727void TWPartitionManager::Output_Storage_Fstab(void) {
2728 std::vector<TWPartition*>::iterator iter;
2729 char storage_partition[255];
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002730 std::string Temp;
bigbiff25d25b92020-06-19 16:07:38 -04002731 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002732
2733 if (cacheDir.empty()) {
2734 LOGINFO("Unable to find cache directory\n");
2735 return;
2736 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002737
bigbiff25d25b92020-06-19 16:07:38 -04002738 std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002739 FILE *fp = fopen(storageFstab.c_str(), "w");
Dees_Troyd93bda52013-07-03 19:55:19 +00002740
2741 if (fp == NULL) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002742 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
Dees_Troyd93bda52013-07-03 19:55:19 +00002743 return;
2744 }
2745
2746 // Iterate through all partitions
2747 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2748 if ((*iter)->Is_Storage) {
2749 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2750 strcpy(storage_partition, Temp.c_str());
2751 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2752 }
2753 }
2754 fclose(fp);
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02002755}
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002756
2757TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2758{
2759 TWPartition *res = NULL;
2760 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
Matt Mowera8a89d12016-12-30 18:10:37 -06002761 if (!(*iter)->Is_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002762 continue;
2763
Matt Mowera8a89d12016-12-30 18:10:37 -06002764 if ((*iter)->Is_Settings_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002765 return *iter;
2766
Matt Mowera8a89d12016-12-30 18:10:37 -06002767 if (!res)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002768 res = *iter;
2769 }
2770 return res;
2771}
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002772
2773bool TWPartitionManager::Enable_MTP(void) {
2774#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002775 if (mtppid) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002776 gui_err("mtp_already_enabled=MTP already enabled");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002777 return true;
2778 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002779
2780 int mtppipe[2];
2781
2782 if (pipe(mtppipe) < 0) {
2783 LOGERR("Error creating MTP pipe\n");
2784 return false;
2785 }
2786
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002787 char old_value[PROPERTY_VALUE_MAX];
Matt Mowere07f0102017-02-23 17:40:00 -06002788 property_get("sys.usb.config", old_value, "");
2789 if (strcmp(old_value, "mtp,adb") != 0) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002790 char vendor[PROPERTY_VALUE_MAX];
2791 char product[PROPERTY_VALUE_MAX];
2792 property_set("sys.usb.config", "none");
2793 property_get("usb.vendor", vendor, "18D1");
2794 property_get("usb.product.mtpadb", product, "4EE2");
2795 string vendorstr = vendor;
2796 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002797 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2798 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002799 property_set("sys.usb.config", "mtp,adb");
2800 }
Matt Mower653a1702017-02-16 10:38:52 -06002801 /* To enable MTP debug, use the twrp command line feature:
Ethan Yonker6d154c42014-09-03 14:19:43 -05002802 * twrp set tw_mtp_debug 1
2803 */
2804 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
Ethan Yonker1b039202015-01-30 10:08:48 -06002805 mtppid = mtp->forkserver(mtppipe);
2806 if (mtppid) {
2807 close(mtppipe[0]); // Host closes read side
2808 mtp_write_fd = mtppipe[1];
2809 DataManager::SetValue("tw_mtp_enabled", 1);
2810 Add_All_MTP_Storage();
2811 return true;
Ethan Yonker726a0202014-12-16 20:01:38 -06002812 } else {
2813 close(mtppipe[0]);
2814 close(mtppipe[1]);
Ethan Yonker74db1572015-10-28 12:44:49 -05002815 gui_err("mtp_fail=Failed to enable MTP");
Ethan Yonker1b039202015-01-30 10:08:48 -06002816 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002817 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002818#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002819 gui_err("no_mtp=MTP support not included");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002820#endif
2821 DataManager::SetValue("tw_mtp_enabled", 0);
2822 return false;
2823}
2824
Ethan Yonker1b039202015-01-30 10:08:48 -06002825void TWPartitionManager::Add_All_MTP_Storage(void) {
2826#ifdef TW_HAS_MTP
2827 std::vector<TWPartition*>::iterator iter;
2828
2829 if (!mtppid)
2830 return; // MTP is not enabled
2831
2832 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2833 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2834 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2835 }
2836#else
2837 return;
2838#endif
2839}
2840
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002841bool TWPartitionManager::Disable_MTP(void) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002842 char old_value[PROPERTY_VALUE_MAX];
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05002843 property_set("sys.usb.ffs.mtp.ready", "0");
Matt Mowere07f0102017-02-23 17:40:00 -06002844 property_get("sys.usb.config", old_value, "");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002845 if (strcmp(old_value, "adb") != 0) {
2846 char vendor[PROPERTY_VALUE_MAX];
2847 char product[PROPERTY_VALUE_MAX];
2848 property_set("sys.usb.config", "none");
2849 property_get("usb.vendor", vendor, "18D1");
Matt Mowere07f0102017-02-23 17:40:00 -06002850 property_get("usb.product.adb", product, "D001");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002851 string vendorstr = vendor;
2852 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002853 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2854 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002855 usleep(2000);
2856 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002857#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002858 if (mtppid) {
Ethan Yonker8613dc02014-09-11 09:28:20 -05002859 LOGINFO("Disabling MTP\n");
2860 int status;
2861 kill(mtppid, SIGKILL);
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002862 mtppid = 0;
Ethan Yonker8613dc02014-09-11 09:28:20 -05002863 // We don't care about the exit value, but this prevents a zombie process
2864 waitpid(mtppid, &status, 0);
Ethan Yonker726a0202014-12-16 20:01:38 -06002865 close(mtp_write_fd);
2866 mtp_write_fd = -1;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002867 }
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002868#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002869 property_set("sys.usb.config", "adb");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002870#ifdef TW_HAS_MTP
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002871 DataManager::SetValue("tw_mtp_enabled", 0);
2872 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002873#endif
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002874 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002875}
Ethan Yonker726a0202014-12-16 20:01:38 -06002876
2877TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2878 std::vector<TWPartition*>::iterator iter;
2879
2880 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2881 if ((*iter)->MTP_Storage_ID == Storage_ID)
2882 return (*iter);
2883 }
2884 return NULL;
2885}
2886
2887bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2888#ifdef TW_HAS_MTP
2889 struct mtpmsg mtp_message;
2890
2891 if (!mtppid)
2892 return false; // MTP is disabled
2893
2894 if (mtp_write_fd < 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002895 LOGINFO("MTP: mtp_write_fd is not set\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002896 return false;
2897 }
2898
2899 if (Part) {
Ethan Yonker4bfabab2014-12-29 09:15:37 -06002900 if (Part->MTP_Storage_ID == 0)
2901 return false;
Ethan Yonker726a0202014-12-16 20:01:38 -06002902 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2903 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2904 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2905 mtp_message.storage_id = Part->MTP_Storage_ID;
2906 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002907 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002908 return false;
2909 } else {
2910 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2911 return true;
2912 }
2913 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2914 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2915 mtp_message.storage_id = Part->MTP_Storage_ID;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002916 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2917 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2918 return false;
2919 }
2920 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2921 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2922 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2923 return false;
2924 }
2925 strcpy(mtp_message.display, Part->Storage_Name.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002926 mtp_message.maxFileSize = Part->Get_Max_FileSize();
Ethan Yonker1b039202015-01-30 10:08:48 -06002927 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 -06002928 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002929 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002930 return false;
2931 } else {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002932 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
Ethan Yonker726a0202014-12-16 20:01:38 -06002933 return true;
2934 }
2935 } else {
2936 LOGERR("Unknown MTP message type: %i\n", message_type);
2937 }
2938 } else {
2939 // This hopefully never happens as the error handling should
2940 // occur in the calling function.
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002941 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002942 }
2943 return true;
2944#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002945 gui_err("no_mtp=MTP support not included");
Ethan Yonker726a0202014-12-16 20:01:38 -06002946 DataManager::SetValue("tw_mtp_enabled", 0);
2947 return false;
2948#endif
2949}
2950
2951bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2952#ifdef TW_HAS_MTP
2953 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2954 if (Part) {
2955 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2956 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002957 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002958 }
2959#endif
2960 return false;
2961}
2962
2963bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2964#ifdef TW_HAS_MTP
2965 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2966 if (Part) {
2967 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2968 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002969 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002970 }
2971#endif
2972 return false;
2973}
2974
2975bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2976#ifdef TW_HAS_MTP
2977 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2978 if (Part) {
2979 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2980 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002981 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002982 }
2983#endif
2984 return false;
2985}
2986
2987bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2988#ifdef TW_HAS_MTP
2989 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2990 if (Part) {
2991 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2992 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002993 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002994 }
2995#endif
2996 return false;
2997}
Ethan Yonker96af84a2015-01-05 14:58:36 -06002998
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002999bool TWPartitionManager::Flash_Image(string& path, string& filename) {
bigbiffad58e1b2020-07-06 20:24:34 -04003000 twrpRepacker repacker;
Matt Mower23d8aae2017-01-06 14:30:33 -06003001 int partition_count = 0;
Ethan Yonker96af84a2015-01-05 14:58:36 -06003002 TWPartition* flash_part = NULL;
bigbiffce8f83c2015-12-12 18:30:21 -05003003 string Flash_List, flash_path, full_filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06003004 size_t start_pos = 0, end_pos = 0;
3005
Ethan Yonkere080c1f2016-09-19 13:50:25 -05003006 full_filename = path + "/" + filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06003007
bigbiffce8f83c2015-12-12 18:30:21 -05003008 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
3009 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
3010
3011 if (!TWFunc::Path_Exists(full_filename)) {
3012 if (!Mount_By_Path(full_filename, true)) {
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06003013 return false;
3014 }
bigbiffce8f83c2015-12-12 18:30:21 -05003015 if (!TWFunc::Path_Exists(full_filename)) {
3016 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06003017 return false;
3018 }
3019 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06003020
Ethan Yonker53796e72019-01-11 22:49:52 -06003021 DataManager::GetValue("tw_flash_partition", Flash_List);
3022 Repack_Type repack = REPLACE_NONE;
3023 if (Flash_List == "/repack_ramdisk;") {
3024 repack = REPLACE_RAMDISK;
3025 } else if (Flash_List == "/repack_kernel;") {
3026 repack = REPLACE_KERNEL;
3027 }
3028 if (repack != REPLACE_NONE) {
3029 Repack_Options_struct Repack_Options;
3030 Repack_Options.Type = repack;
3031 Repack_Options.Disable_Verity = false;
3032 Repack_Options.Disable_Force_Encrypt = false;
3033 Repack_Options.Backup_First = DataManager::GetIntValue("tw_repack_backup_first") != 0;
bigbiffad58e1b2020-07-06 20:24:34 -04003034 return repacker.Repack_Image_And_Flash(full_filename, Repack_Options);
Ethan Yonker53796e72019-01-11 22:49:52 -06003035 }
Ethan Yonkere080c1f2016-09-19 13:50:25 -05003036 PartitionSettings part_settings;
3037 part_settings.Backup_Folder = path;
3038 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
3039 ProgressTracking progress(total_bytes);
3040 part_settings.progress = &progress;
3041 part_settings.adbbackup = false;
3042 part_settings.PM_Method = PM_RESTORE;
Ethan Yonker74db1572015-10-28 12:44:49 -05003043 gui_msg("calc_restore=Calculating restore details...");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003044 if (!Flash_List.empty()) {
3045 end_pos = Flash_List.find(";", start_pos);
3046 while (end_pos != string::npos && start_pos < Flash_List.size()) {
3047 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
3048 flash_part = Find_Partition_By_Path(flash_path);
3049 if (flash_part != NULL) {
3050 partition_count++;
3051 if (partition_count > 1) {
Ethan Yonker74db1572015-10-28 12:44:49 -05003052 gui_err("too_many_flash=Too many partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003053 return false;
3054 }
3055 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05003056 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
Ethan Yonker96af84a2015-01-05 14:58:36 -06003057 return false;
3058 }
3059 start_pos = end_pos + 1;
3060 end_pos = Flash_List.find(";", start_pos);
3061 }
3062 }
3063
3064 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05003065 gui_err("no_part_flash=No partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003066 return false;
3067 }
3068
3069 DataManager::SetProgress(0.0);
3070 if (flash_part) {
Ethan Yonkere080c1f2016-09-19 13:50:25 -05003071 flash_part->Backup_FileName = filename;
3072 if (!flash_part->Flash_Image(&part_settings))
Ethan Yonker96af84a2015-01-05 14:58:36 -06003073 return false;
3074 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05003075 gui_err("invalid_flash=Invalid flash partition specified.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003076 return false;
3077 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003078 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
Ethan Yonker96af84a2015-01-05 14:58:36 -06003079 return true;
3080}
Ethan Yonker74db1572015-10-28 12:44:49 -05003081
3082void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
3083 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3084 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003085 if (part->Is_Adopted_Storage) {
3086 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3087 part->Backup_Display_Name = part->Display_Name;
3088 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3089 } else {
3090 part->Display_Name = gui_lookup(resource_name, default_value);
3091 part->Backup_Display_Name = part->Display_Name;
3092 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003093 }
3094}
3095
3096void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
3097 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3098 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003099 if (part->Is_Adopted_Storage) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003100 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
Ethan Yonker66a19492015-12-10 10:19:45 -06003101 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
Ethan Yonker66a19492015-12-10 10:19:45 -06003102 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3103 } else {
3104 part->Display_Name = gui_lookup(resource_name, default_value);
3105 part->Backup_Display_Name = part->Display_Name;
3106 if (part->Is_Storage)
3107 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3108 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003109 }
3110}
3111
Ethan Yonker01f4e032017-02-03 15:30:52 -06003112void 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) {
3113 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3114 if (part) {
3115 if (part->Is_Adopted_Storage) {
3116 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
3117 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3118 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3119 } else {
3120 part->Display_Name = gui_lookup(resource_name, default_value);
3121 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
3122 if (part->Is_Storage)
3123 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3124 }
3125 }
3126}
3127
Ethan Yonker74db1572015-10-28 12:44:49 -05003128void TWPartitionManager::Translate_Partition_Display_Names() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003129 LOGINFO("Translating partition display names\n");
Ethan Yonker74db1572015-10-28 12:44:49 -05003130 Translate_Partition("/system", "system", "System");
3131 Translate_Partition("/system_image", "system_image", "System Image");
3132 Translate_Partition("/vendor", "vendor", "Vendor");
3133 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
3134 Translate_Partition("/cache", "cache", "Cache");
Ethan Yonker74db1572015-10-28 12:44:49 -05003135 Translate_Partition("/boot", "boot", "Boot");
3136 Translate_Partition("/recovery", "recovery", "Recovery");
3137 if (!datamedia) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003138 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
Ethan Yonker74db1572015-10-28 12:44:49 -05003139 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3140 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
3141 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3142 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
Ethan Yonker01f4e032017-02-03 15:30:52 -06003143 } else {
3144 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003145 }
Ethan Yonker01f4e032017-02-03 15:30:52 -06003146 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
3147 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003148 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
3149 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
3150
3151 // Android secure is a special case
3152 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
3153 if (part)
3154 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
3155
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003156 std::vector<TWPartition*>::iterator sysfs;
3157 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
3158 if (!(*sysfs)->Sysfs_Entry.empty()) {
3159 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
3160 }
3161 }
3162
Ethan Yonker74db1572015-10-28 12:44:49 -05003163 // This updates the text on all of the storage selection buttons in the GUI
3164 DataManager::SetBackupFolder();
3165}
Ethan Yonker66a19492015-12-10 10:19:45 -06003166
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003167bool TWPartitionManager::Decrypt_Adopted() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003168#ifdef TW_INCLUDE_CRYPTO
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003169 bool ret = false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003170 if (!Mount_By_Path("/data", false)) {
3171 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003172 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003173 }
Darth98f775972022-08-05 09:39:03 +01003174
3175 std::string path = "/data/system/storage.xml";
3176 if (!TWFunc::Check_Xml_Format(path)) {
3177 std::string oldpath = path;
3178 if (TWFunc::abx_to_xml(oldpath, path)) {
3179 LOGINFO("Android 12+: '%s' has been converted into plain text xml (%s).\n", oldpath.c_str(), path.c_str());
3180 }
3181 }
3182
Fernando Oliveiraa4a754d2024-01-28 13:40:23 -03003183 DataManager::SetValue("tw_settings_path", TW_STORAGE_PATH);
Ethan Yonker66a19492015-12-10 10:19:45 -06003184 LOGINFO("Decrypt adopted storage starting\n");
Darth98f775972022-08-05 09:39:03 +01003185 char* xmlFile = PageManager::LoadFileToBuffer(path, NULL);
Ethan Yonker66a19492015-12-10 10:19:45 -06003186 xml_document<> *doc = NULL;
3187 xml_node<>* volumes = NULL;
Ethan Yonker66a19492015-12-10 10:19:45 -06003188 string Primary_Storage_UUID = "";
3189 if (xmlFile != NULL) {
3190 LOGINFO("successfully loaded storage.xml\n");
3191 doc = new xml_document<>();
3192 doc->parse<0>(xmlFile);
3193 volumes = doc->first_node("volumes");
3194 if (volumes) {
3195 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
3196 if (psuuid) {
3197 Primary_Storage_UUID = psuuid->value();
3198 }
3199 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003200 } else {
3201 LOGINFO("No /data/system/storage.xml for adopted storage\n");
3202 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003203 }
3204 std::vector<TWPartition*>::iterator adopt;
3205 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
Peter Cai439d60c2019-10-17 08:49:10 +08003206 if ((*adopt)->Removable && !(*adopt)->Is_Present && (*adopt)->Adopted_Mount_Delay > 0) {
3207 // On some devices, the external mmc driver takes some time
3208 // to recognize the card, in which case the "actual block device"
3209 // would not have been found yet. We wait the specified delay
3210 // and then try again.
3211 LOGINFO("Sleeping %d seconds for adopted storage.\n", (*adopt)->Adopted_Mount_Delay);
3212 sleep((*adopt)->Adopted_Mount_Delay);
3213 (*adopt)->Find_Actual_Block_Device();
3214 }
3215
Ethan Yonker66a19492015-12-10 10:19:45 -06003216 if ((*adopt)->Removable && (*adopt)->Is_Present) {
3217 if ((*adopt)->Decrypt_Adopted() == 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003218 ret = true;
Ethan Yonker66a19492015-12-10 10:19:45 -06003219 if (volumes) {
3220 xml_node<>* volume = volumes->first_node("volume");
3221 while (volume) {
3222 xml_attribute<>* guid = volume->first_attribute("partGuid");
3223 if (guid) {
3224 string GUID = (*adopt)->Adopted_GUID.c_str();
3225 GUID.insert(8, "-");
3226 GUID.insert(13, "-");
3227 GUID.insert(18, "-");
3228 GUID.insert(23, "-");
3229
3230 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
3231 xml_attribute<>* attr = volume->first_attribute("nickname");
nkk71ffb02bd2017-06-04 23:12:16 +03003232 if (attr && attr->value() && strlen(attr->value()) > 0) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003233 (*adopt)->Storage_Name = attr->value();
3234 (*adopt)->Display_Name = (*adopt)->Storage_Name;
3235 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
3236 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
3237 }
3238 attr = volume->first_attribute("fsUuid");
3239 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
3240 TWPartition* Dat = Find_Partition_By_Path("/data");
3241 if (Dat) {
3242 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
3243 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
3244 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
3245 Dat->Symlink_Mount_Point = "";
3246 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
3247 Dat->UnMount(false);
3248 Dat->Mount(false);
3249 (*adopt)->UnMount(false);
3250 (*adopt)->Mount(false);
Ethan Yonker66a19492015-12-10 10:19:45 -06003251 }
3252 }
3253 break;
3254 }
3255 }
3256 volume = volume->next_sibling("volume");
3257 }
3258 }
nkk71ffb02bd2017-06-04 23:12:16 +03003259 Update_System_Details();
3260 Output_Partition((*adopt));
Ethan Yonker66a19492015-12-10 10:19:45 -06003261 }
3262 }
3263 }
3264 if (xmlFile) {
3265 doc->clear();
3266 delete doc;
3267 free(xmlFile);
3268 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003269 return ret;
Ethan Yonker66a19492015-12-10 10:19:45 -06003270#else
3271 LOGINFO("Decrypt_Adopted: no crypto support\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003272 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003273#endif
3274}
Ethan Yonkerfcf3f242016-02-16 12:30:26 -06003275
3276void TWPartitionManager::Remove_Partition_By_Path(string Path) {
3277 std::vector<TWPartition*>::iterator iter;
3278 string Local_Path = TWFunc::Get_Root_Path(Path);
3279
3280 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3281 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
3282 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
3283 Partitions.erase(iter);
3284 return;
3285 }
3286 }
3287}
Ethan Yonker1b190162016-12-05 15:25:19 -06003288
bigbiff74a46272021-07-31 19:02:26 -04003289void TWPartitionManager::Override_Active_Slot(const string& Slot) {
3290 LOGINFO("Overriding slot to '%s'\n", Slot.c_str());
3291 Active_Slot_Display = Slot;
3292 DataManager::SetValue("tw_active_slot", Slot);
nebrassy07c4b902021-11-21 03:32:47 +01003293 PartitionManager.Update_System_Details();
bigbiff74a46272021-07-31 19:02:26 -04003294}
3295
Ethan Yonker1b190162016-12-05 15:25:19 -06003296void TWPartitionManager::Set_Active_Slot(const string& Slot) {
3297 if (Slot != "A" && Slot != "B") {
3298 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
3299 return;
3300 }
3301 if (Active_Slot_Display == Slot)
3302 return;
3303 LOGINFO("Setting active slot %s\n", Slot.c_str());
3304#ifdef AB_OTA_UPDATER
3305 if (!Active_Slot_Display.empty()) {
dianlujitaoa90dc462021-12-16 16:56:26 +08003306 android::sp<IBootControl> module = IBootControl::getService();
3307 if (module == nullptr) {
Ethan Yonker1b190162016-12-05 15:25:19 -06003308 LOGERR("Error getting bootctrl module.\n");
3309 } else {
dianlujitaoa90dc462021-12-16 16:56:26 +08003310 uint32_t slot_number = 0;
Ethan Yonker1b190162016-12-05 15:25:19 -06003311 if (Slot == "B")
3312 slot_number = 1;
dianlujitaoa90dc462021-12-16 16:56:26 +08003313 CommandResult result;
3314 auto ret = module->setActiveBootSlot(slot_number, [&result]
3315 (const CommandResult &cb_result) { result = cb_result; });
3316 if (!ret.isOk() || !result.success)
Ethan Yonker1b190162016-12-05 15:25:19 -06003317 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
3318 }
3319 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
3320 }
3321#else
3322 LOGERR("Boot slot feature not present\n");
3323#endif
3324 Active_Slot_Display = Slot;
3325 if (Fstab_Processed())
3326 Update_System_Details();
3327}
3328string TWPartitionManager::Get_Active_Slot_Suffix() {
3329 if (Active_Slot_Display == "A")
3330 return "_a";
3331 return "_b";
3332}
3333string TWPartitionManager::Get_Active_Slot_Display() {
3334 return Active_Slot_Display;
3335}
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003336
Captain Throwback9d6feb52018-07-27 10:05:24 -04003337string TWPartitionManager::Get_Android_Root_Path() {
bigbiff8da46fa2020-09-08 16:42:34 -04003338 return "/system_root";
Captain Throwback9d6feb52018-07-27 10:05:24 -04003339}
3340
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003341void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
3342 std::vector<TWPartition*>::iterator iter;
3343
3344 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
3345 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
3346 TWPartition *part = *iter;
3347 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
3348 (*iter)->UnMount(false);
3349 rmdir((*iter)->Mount_Point.c_str());
3350 iter = Partitions.erase(iter);
3351 delete part;
3352 } else {
3353 iter++;
3354 }
3355 }
3356}
3357
3358void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
3359 std::vector<TWPartition*>::iterator iter;
3360
3361 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3362 if (!(*iter)->Sysfs_Entry.empty()) {
3363 string device;
3364 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
3365 if (wildcard != string::npos) {
3366 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
3367 } else {
3368 device = (*iter)->Sysfs_Entry;
3369 }
3370 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
3371 // Found a match
3372 if (uevent_data.action == "add") {
3373 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
3374 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
3375 (*iter)->Is_Present = true;
3376 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
3377 if (!Decrypt_Adopted()) {
3378 LOGINFO("No adopted storage so finding actual block device\n");
3379 (*iter)->Find_Actual_Block_Device();
3380 }
3381 return;
3382 } else if (uevent_data.action == "remove") {
3383 (*iter)->Is_Present = false;
3384 (*iter)->Primary_Block_Device = "";
3385 (*iter)->Actual_Block_Device = "";
3386 Remove_Uevent_Devices((*iter)->Mount_Point);
3387 return;
3388 }
3389 }
3390 }
3391 }
bigbiffee7b7ff2020-03-23 15:08:27 -04003392
3393 if (!PartitionManager.Get_Super_Status())
3394 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 -06003395}
3396
3397void TWPartitionManager::setup_uevent() {
3398 struct sockaddr_nl nls;
3399
3400 if (uevent_pfd.fd >= 0) {
3401 LOGINFO("uevent already set up\n");
3402 return;
3403 }
3404
3405 // Open hotplug event netlink socket
3406 memset(&nls,0,sizeof(struct sockaddr_nl));
3407 nls.nl_family = AF_NETLINK;
3408 nls.nl_pid = getpid();
3409 nls.nl_groups = -1;
3410 uevent_pfd.events = POLLIN;
3411 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
3412 if (uevent_pfd.fd==-1) {
3413 LOGERR("uevent not root\n");
3414 return;
3415 }
3416
3417 // Listen to netlink socket
3418 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
3419 LOGERR("Bind failed\n");
3420 return;
3421 }
3422 set_select_fd();
3423 Coldboot();
3424}
3425
3426Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
3427 Uevent_Block_Data ret;
3428 ret.subsystem = "";
3429 char *ptr = buf;
3430 const char *end = buf + len;
3431
3432 buf[len - 1] = '\0';
3433 while (ptr < end) {
3434 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
3435 ptr += strlen("ACTION=");
3436 ret.action = ptr;
3437 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
3438 ptr += strlen("SUBSYSTEM=");
3439 ret.subsystem = ptr;
3440 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
3441 ptr += strlen("DEVTYPE=");
3442 ret.type = ptr;
3443 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
3444 ptr += strlen("DEVPATH=");
3445 ret.sysfs_path += ptr;
3446 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
3447 ptr += strlen("DEVNAME=");
3448 ret.block_device += ptr;
3449 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
3450 ptr += strlen("MAJOR=");
3451 ret.major = atoi(ptr);
3452 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
3453 ptr += strlen("MINOR=");
3454 ret.minor = atoi(ptr);
3455 }
3456 ptr += strlen(ptr) + 1;
3457 }
3458 return ret;
3459}
3460
3461void TWPartitionManager::read_uevent() {
3462 char buf[1024];
3463
3464 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
3465 if (len == -1) {
Mauronofrio Matarresec1bb76e2019-08-04 17:02:41 +01003466 LOGINFO("recv error on uevent\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003467 return;
3468 }
3469 /*int i = 0; // Print all uevent output for test /debug
3470 while (i<len) {
3471 printf("%s\n", buf+i);
3472 i += strlen(buf+i)+1;
3473 }*/
3474 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
3475 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
3476 PartitionManager.Handle_Uevent(uevent_data);
3477 }
3478}
3479
3480void TWPartitionManager::close_uevent() {
3481 if (uevent_pfd.fd > 0)
3482 close(uevent_pfd.fd);
3483 uevent_pfd.fd = -1;
3484}
3485
3486void TWPartitionManager::Add_Partition(TWPartition* Part) {
3487 Partitions.push_back(Part);
3488}
3489
3490void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
3491 string Real_Path = Path;
3492 char real_path[PATH_MAX];
3493 if (realpath(Path.c_str(), &real_path[0])) {
3494 string Real_Path = real_path;
3495 std::vector<string>::iterator iter;
3496 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
3497 if (Real_Path.find((*iter)) != string::npos) {
3498 string Write_Path = Real_Path + "/uevent";
3499 if (TWFunc::Path_Exists(Write_Path)) {
3500 const char* write_val = "add\n";
3501 TWFunc::write_to_file(Write_Path, write_val);
3502 break;
3503 }
3504 }
3505 }
3506 }
3507
3508 DIR* d = opendir(Path.c_str());
3509 if (d != NULL) {
3510 struct dirent* de;
3511 while ((de = readdir(d)) != NULL) {
3512 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
3513 continue;
3514 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
3515 continue;
3516
3517 string item = Path + "/";
3518 item.append(de->d_name);
3519 Coldboot_Scan(sysfs_entries, item, depth + 1);
3520 }
3521 closedir(d);
3522 }
3523}
3524
3525void TWPartitionManager::Coldboot() {
3526 std::vector<TWPartition*>::iterator iter;
3527 std::vector<string> sysfs_entries;
3528
3529 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3530 if (!(*iter)->Sysfs_Entry.empty()) {
3531 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
3532 if (wildcard_pos == string::npos)
3533 wildcard_pos = (*iter)->Sysfs_Entry.size();
3534 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
3535 }
3536 }
3537
3538 if (sysfs_entries.size() > 0)
3539 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
3540}
Ethan Yonker53796e72019-01-11 22:49:52 -06003541
3542bool TWPartitionManager::Prepare_Empty_Folder(const std::string& Folder) {
3543 if (TWFunc::Path_Exists(Folder))
3544 TWFunc::removeDir(Folder, false);
3545 return TWFunc::Recursive_Mkdir(Folder);
3546}
3547
bigbiffcfa875c2021-06-20 16:20:27 -04003548std::string TWPartitionManager::Get_Bare_Partition_Name(std::string Mount_Point) {
3549 if (Mount_Point == "/system_root")
3550 return "system";
3551 else
3552 return TWFunc::Remove_Beginning_Slash(Mount_Point);
3553}
3554
bigbiffee7b7ff2020-03-23 15:08:27 -04003555bool TWPartitionManager::Prepare_Super_Volume(TWPartition* twrpPart) {
3556 Fstab fstab;
bigbiffcfa875c2021-06-20 16:20:27 -04003557 std::string bare_partition_name = Get_Bare_Partition_Name(twrpPart->Get_Mount_Point());
bigbiffee7b7ff2020-03-23 15:08:27 -04003558
bigbiff998f8392021-08-06 19:19:33 -04003559 Super_Partition_List.push_back(bare_partition_name);
bigbiffee7b7ff2020-03-23 15:08:27 -04003560 LOGINFO("Trying to prepare %s from super partition\n", bare_partition_name.c_str());
3561
3562 std::string blk_device_partition;
3563#ifdef AB_OTA_UPDATER
3564 blk_device_partition = bare_partition_name + PartitionManager.Get_Active_Slot_Suffix();
3565#else
3566 blk_device_partition = bare_partition_name;
3567#endif
3568
3569 FstabEntry fstabEntry = {
3570 .blk_device = blk_device_partition,
3571 .mount_point = twrpPart->Get_Mount_Point(),
3572 .fs_type = twrpPart->Current_File_System,
3573 .fs_mgr_flags.logical = twrpPart->Is_Super,
3574 };
3575
3576 fstab.emplace_back(fstabEntry);
3577 if (!fs_mgr_update_logical_partition(&fstabEntry)) {
Captain Throwbackc6939102021-04-06 12:57:30 -04003578 LOGINFO("unable to update logical partition: %s\n", twrpPart->Get_Mount_Point().c_str());
bigbiffee7b7ff2020-03-23 15:08:27 -04003579 return false;
3580 }
3581
bigbiff32cbabe2020-04-12 19:16:19 -04003582 while (access(fstabEntry.blk_device.c_str(), F_OK) != 0) {
3583 usleep(100);
3584 }
3585
bigbiffee7b7ff2020-03-23 15:08:27 -04003586 twrpPart->Set_Block_Device(fstabEntry.blk_device);
3587 twrpPart->Update_Size(true);
bigbiffee7b7ff2020-03-23 15:08:27 -04003588 twrpPart->Set_Can_Be_Backed_Up(false);
3589 twrpPart->Set_Can_Be_Wiped(false);
me-cafebabe928234b2022-07-28 04:07:04 +08003590 if (access(("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str(), F_OK) == -1) {
3591 LOGINFO("Symlinking %s => /dev/block/bootdevice/by-name/%s \n", fstabEntry.blk_device.c_str(), bare_partition_name.c_str());
3592 symlink(fstabEntry.blk_device.c_str(), ("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str());
Captain Throwback88c6e652023-01-16 15:32:26 -05003593 property_set("twrp.super.symlinks_created", "true");
me-cafebabe928234b2022-07-28 04:07:04 +08003594 }
Mohd Faraz7fc70502021-04-22 20:44:11 +02003595
bigbiffee7b7ff2020-03-23 15:08:27 -04003596 return true;
3597}
3598
3599bool TWPartitionManager::Prepare_All_Super_Volumes() {
3600 bool status = true;
3601 std::vector<TWPartition*>::iterator iter;
3602
3603 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3604 if ((*iter)->Is_Super) {
3605 if (!Prepare_Super_Volume(*iter)) {
3606 status = false;
Mohd Faraz787cc612023-01-02 22:47:51 +01003607 Partitions.erase(iter--);
bigbiffee7b7ff2020-03-23 15:08:27 -04003608 }
3609 PartitionManager.Output_Partition(*iter);
3610 }
3611 }
3612 Update_System_Details();
3613 return status;
3614}
3615
bigbiffee7b7ff2020-03-23 15:08:27 -04003616std::string TWPartitionManager::Get_Super_Partition() {
3617 int slot_number = Get_Active_Slot_Display() == "A" ? 0 : 1;
bigbiff998f8392021-08-06 19:19:33 -04003618 std::string super_device = fs_mgr_get_super_partition_name(slot_number);
bigbiffee7b7ff2020-03-23 15:08:27 -04003619 return "/dev/block/by-name/" + super_device;
3620}
3621
3622void TWPartitionManager::Setup_Super_Devices() {
3623 std::string superPart = Get_Super_Partition();
3624 android::fs_mgr::CreateLogicalPartitions(superPart);
bigbiff7ba75002020-04-11 20:47:09 -04003625}
3626
3627void TWPartitionManager::Setup_Super_Partition() {
bigbiffee7b7ff2020-03-23 15:08:27 -04003628 TWPartition* superPartition = new TWPartition();
bigbiff7ba75002020-04-11 20:47:09 -04003629 std::string superPart = Get_Super_Partition();
3630
3631 superPartition->Backup_Path = "/super";
3632 superPartition->Mount_Point = "/super";
bigbiffee7b7ff2020-03-23 15:08:27 -04003633 superPartition->Actual_Block_Device = superPart;
3634 superPartition->Alternate_Block_Device = superPart;
bigbiff998f8392021-08-06 19:19:33 -04003635 superPartition->Backup_Display_Name = "Super (";
3636 // Add first 4 items to fstab as logical that you would like to display in Backup_Display_Name
3637 // for the Super partition
3638 int list_size = Super_Partition_List.size();
3639 int orig_list_size = list_size;
3640 int max_display_size = 3; // total of 4 items since we start at 0
3641
3642 for (auto partition: Super_Partition_List) {
3643 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + partition;
3644 if ((orig_list_size - list_size) == max_display_size) {
3645 break;
3646 }
3647 if (list_size != 1)
3648 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + " ";
3649 list_size--;
3650 }
3651 superPartition->Backup_Display_Name += ")";
bigbiffee7b7ff2020-03-23 15:08:27 -04003652 superPartition->Can_Flash_Img = true;
bigbiffee7b7ff2020-03-23 15:08:27 -04003653 superPartition->Current_File_System = "emmc";
3654 superPartition->Can_Be_Backed_Up = true;
3655 superPartition->Is_Present = true;
3656 superPartition->Is_SubPartition = false;
bigbiff7ba75002020-04-11 20:47:09 -04003657 superPartition->Setup_Image();
bigbiffee7b7ff2020-03-23 15:08:27 -04003658 Add_Partition(superPartition);
3659 PartitionManager.Output_Partition(superPartition);
bigbiffee7b7ff2020-03-23 15:08:27 -04003660}
3661
3662bool TWPartitionManager::Get_Super_Status() {
Mohd Faraz88b4bab2023-01-01 02:43:01 +05303663 return access(Get_Super_Partition().c_str(), F_OK) == 0;
bigbiffee7b7ff2020-03-23 15:08:27 -04003664}
bigbiff25d25b92020-06-19 16:07:38 -04003665
3666bool TWPartitionManager::Recreate_Logs_Dir() {
3667#ifdef TW_INCLUDE_FBE
3668 struct passwd pd;
3669 struct passwd *pwdptr = &pd;
3670 struct passwd *tempPd;
3671 char pwdBuf[512];
3672 int uid = 0, gid = 0;
3673
3674 if ((getpwnam_r("system", pwdptr, pwdBuf, sizeof(pwdBuf), &tempPd)) != 0) {
3675 LOGERR("unable to get system user id\n");
3676 return false;
3677 } else {
3678 struct group grp;
3679 struct group *grpptr = &grp;
3680 struct group *tempGrp;
3681 char grpBuf[512];
3682
3683 if ((getgrnam_r("cache", grpptr, grpBuf, sizeof(grpBuf), &tempGrp)) != 0) {
3684 LOGERR("unable to get cache group id\n");
3685 return false;
3686 } else {
3687 uid = pd.pw_uid;
3688 gid = grp.gr_gid;
3689 std::string abLogsRecoveryDir(DATA_LOGS_DIR);
3690 abLogsRecoveryDir += "/recovery/";
3691
3692 if (!TWFunc::Create_Dir_Recursive(abLogsRecoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
3693 LOGERR("Unable to recreate %s\n", abLogsRecoveryDir.c_str());
3694 return false;
3695 }
3696 if (setfilecon(abLogsRecoveryDir.c_str(), "u:object_r:cache_file:s0") != 0) {
3697 LOGERR("Unable to set contexts for %s\n", abLogsRecoveryDir.c_str());
3698 return false;
3699 }
3700 }
3701 }
3702#endif
3703 return true;
3704}
bigbiff1f9e4842020-10-31 11:33:15 -04003705
3706void TWPartitionManager::Unlock_Block_Partitions() {
3707 int fd, OFF = 0;
3708
3709 const std::string block_path = "/dev/block/";
3710 DIR* d = opendir(block_path.c_str());
3711 if (d != NULL) {
3712 struct dirent* de;
3713 while ((de = readdir(d)) != NULL) {
3714 if (de->d_type == DT_BLK) {
3715 std::string block_device = block_path + de->d_name;
bigbiff1f9e4842020-10-31 11:33:15 -04003716 if ((fd = open(block_device.c_str(), O_RDONLY | O_CLOEXEC)) < 0) {
3717 LOGERR("unable to open block device %s: %s\n", block_device.c_str(), strerror(errno));
3718 continue;
3719 }
3720 if (ioctl(fd, BLKROSET, &OFF) == -1) {
me-cafebabed63fcaa2022-07-28 03:19:20 +08003721 LOGERR("Unable to unlock %s: %s\n", block_device.c_str());
bigbiff1f9e4842020-10-31 11:33:15 -04003722 continue;
3723 }
3724 close(fd);
3725 }
3726 }
3727 closedir(d);
3728 }
bigbiffaf253cd2020-12-06 16:50:55 -05003729}
bigbiffcfa875c2021-06-20 16:20:27 -04003730
3731bool TWPartitionManager::Unmap_Super_Devices() {
3732 bool destroyed = false;
3733#ifndef TW_EXCLUDE_APEX
3734 twrpApex apex;
3735 apex.Unmount();
3736#endif
3737 for (auto iter = Partitions.begin(); iter != Partitions.end();) {
3738 LOGINFO("Checking partition: %s\n", (*iter)->Get_Mount_Point().c_str());
3739 if ((*iter)->Is_Super) {
3740 TWPartition *part = *iter;
3741 std::string bare_partition_name = Get_Bare_Partition_Name((*iter)->Get_Mount_Point());
me-cafebabe2136fc52022-07-20 06:42:18 +08003742 std::string blk_device_partition = bare_partition_name;
Captain Throwbackf2a4ef32024-02-07 16:12:24 -05003743 if (DataManager::GetStrValue("tw_has_boot_slots") == "1")
me-cafebabe2136fc52022-07-20 06:42:18 +08003744 blk_device_partition.append(PartitionManager.Get_Active_Slot_Suffix());
bigbiffcfa875c2021-06-20 16:20:27 -04003745 (*iter)->UnMount(false);
3746 LOGINFO("removing dynamic partition: %s\n", blk_device_partition.c_str());
3747 destroyed = DestroyLogicalPartition(blk_device_partition);
3748 std::string cow_partition = blk_device_partition + "-cow";
3749 std::string cow_partition_path = "/dev/block/mapper/" + cow_partition;
3750 struct stat st;
3751 if (lstat(cow_partition_path.c_str(), &st) == 0) {
3752 LOGINFO("removing cow partition: %s\n", cow_partition.c_str());
3753 destroyed = DestroyLogicalPartition(cow_partition);
3754 }
bigbiffcfa875c2021-06-20 16:20:27 -04003755 iter = Partitions.erase(iter);
3756 delete part;
3757 if (!destroyed) {
3758 return false;
3759 }
3760 } else {
3761 ++iter;
3762 }
3763 }
3764 return true;
3765}
bigbiffd21252f2021-09-18 15:56:32 -04003766
3767
3768bool TWPartitionManager::Check_Pending_Merges() {
3769 auto sm = android::snapshot::SnapshotManager::NewForFirstStageMount();
3770 if (!sm) {
3771 LOGERR("Unable to call snapshot manager\n");
3772 return false;
3773 }
3774
3775 if (!Unmap_Super_Devices()) {
3776 LOGERR("Unable to unmap dynamic partitions.\n");
3777 return false;
3778 }
3779
3780 auto callback = [&]() -> void {
3781 double progress;
3782 sm->GetUpdateState(&progress);
3783 LOGINFO("waiting for merge to complete: %.2f\n", progress);
3784 };
3785
3786 LOGINFO("checking for merges\n");
3787 if (!sm->HandleImminentDataWipe(callback)) {
3788 LOGERR("Unable to check merge status\n");
3789 return false;
3790 }
3791 return true;
Darth98f775972022-08-05 09:39:03 +01003792}