blob: 9a2a3aa8f22e362aa5efeef9efb81b67a10869e8 [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
bigbiffaed1bdf2021-08-03 18:21:39 -04002 Copyright 2014 to 2021 TeamWin
Dees Troy3be70a82013-10-22 14:25:12 +00003 This file is part of TWRP/TeamWin Recovery Project.
4
5 TWRP is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 TWRP is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with TWRP. If not, see <http://www.gnu.org/licenses/>.
17*/
Dees_Troy51a0e822012-09-05 15:24:24 -040018
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <sys/stat.h>
23#include <sys/vfs.h>
24#include <unistd.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060025#include <map>
Dees_Troy5bf43922012-09-07 16:07:55 -040026#include <vector>
Dees_Troy63c8df72012-09-10 14:02:05 -040027#include <dirent.h>
28#include <time.h>
Dees_Troy8170a922012-09-18 15:40:25 -040029#include <errno.h>
30#include <fcntl.h>
bigbiff25d25b92020-06-19 16:07:38 -040031#include <grp.h>
32#include <pwd.h>
bigbiffce8f83c2015-12-12 18:30:21 -050033#include <zlib.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050034#include <iostream>
35#include <iomanip>
Ethan Yonker8613dc02014-09-11 09:28:20 -050036#include <sys/wait.h>
Ethan Yonker483e9f42016-01-11 22:21:18 -060037#include <linux/fs.h>
38#include <sys/mount.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060039#include <sys/poll.h>
40#include <sys/socket.h>
bigbiffcfa875c2021-06-20 16:20:27 -040041#include <sys/stat.h>
42#include <sys/types.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060043#include <linux/types.h>
44#include <linux/netlink.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040045#include <android-base/chrono_utils.h>
46#include <android-base/file.h>
47#include <android-base/logging.h>
bigbiff7ba75002020-04-11 20:47:09 -040048#include <android-base/properties.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040049#include <android-base/strings.h>
50#include <fstab/fstab.h>
51#include <fs_avb/fs_avb.h>
52#include <fs_mgr.h>
53#include <fs_mgr_dm_linear.h>
54#include <fs_mgr_overlayfs.h>
bigbiffcfa875c2021-06-20 16:20:27 -040055#include <fs_mgr/roots.h>
bigbiffee7b7ff2020-03-23 15:08:27 -040056#include <libgsi/libgsi.h>
57#include <liblp/liblp.h>
bigbiffcfa875c2021-06-20 16:20:27 -040058#include <libgsi/libgsi.h>
59#include <liblp/builder.h>
60#include <libsnapshot/snapshot.h>
Ethan Yonker6e8c27a2016-12-22 17:55:57 -060061
Dees_Troy51a0e822012-09-05 15:24:24 -040062#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000063#include "twcommon.h"
Dees_Troy51a0e822012-09-05 15:24:24 -040064#include "partitions.hpp"
Dees_Troy5bf43922012-09-07 16:07:55 -040065#include "data.hpp"
bigbiffaed1bdf2021-08-03 18:21:39 -040066#include "startupArgs.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040067#include "twrp-functions.hpp"
Ethan Yonkerb5fab762016-01-28 14:03:33 -060068#include "fixContexts.hpp"
Ethan Yonker3fdcda42016-11-30 12:29:37 -060069#include "exclude.hpp"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060070#include "set_metadata.h"
bigbiff7abc5fe2015-01-17 16:53:12 -050071#include "tw_atomic.hpp"
Ethan Yonker74db1572015-10-28 12:44:49 -050072#include "gui/gui.hpp"
Ethan Yonker472f5062016-02-25 13:47:30 -060073#include "progresstracking.hpp"
bigbiff bigbiff56cf5642016-08-19 17:43:45 -040074#include "twrpDigestDriver.hpp"
bigbiffad58e1b2020-07-06 20:24:34 -040075#include "twrpRepacker.hpp"
bigbiffce8f83c2015-12-12 18:30:21 -050076#include "adbbu/libtwadbbu.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040077
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040078#ifdef TW_HAS_MTP
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -050079#ifdef TW_HAS_LEGACY_MTP
80#include "mtp/legacy/mtp_MtpServer.hpp"
81#include "mtp/legacy/twrpMtp.hpp"
82#include "mtp/legacy/MtpMessage.hpp"
83#else
84#include "mtp/ffs/mtp_MtpServer.hpp"
85#include "mtp/ffs/twrpMtp.hpp"
86#include "mtp/ffs/MtpMessage.hpp"
87#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -040088#endif
89
Dees Troy6f6441d2014-01-23 02:07:03 +000090extern "C" {
91 #include "cutils/properties.h"
Ethan Yonker74db1572015-10-28 12:44:49 -050092 #include "gui/gui.h"
Dees Troy6f6441d2014-01-23 02:07:03 +000093}
94
Dees_Troy5bf43922012-09-07 16:07:55 -040095#ifdef TW_INCLUDE_CRYPTO
bigbiffdf53b6c2022-01-17 19:31:52 -050096// #include "crypto/fde/cryptfs.h"
bigbiff7ba75002020-04-11 20:47:09 -040097#include "gui/rapidxml.hpp"
98#include "gui/pages.hpp"
99#ifdef TW_INCLUDE_FBE
bigbiffa957f072021-03-07 18:20:29 -0500100#include "Decrypt.h"
bigbiff7ba75002020-04-11 20:47:09 -0400101#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
102 #ifdef USE_FSCRYPT
bigbiffdf53b6c2022-01-17 19:31:52 -0500103 #include "cryptfs.h"
104 #include "fscrypt-common.h"
bigbiffa957f072021-03-07 18:20:29 -0500105 #include "MetadataCrypt.h"
bigbiffadc599e2020-05-28 19:36:30 +0000106 #endif
bigbiff7ba75002020-04-11 20:47:09 -0400107#endif
108#endif
Dees_Troy5bf43922012-09-07 16:07:55 -0400109#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400110
Ethan Yonker1b190162016-12-05 15:25:19 -0600111#ifdef AB_OTA_UPDATER
dianlujitaoa90dc462021-12-16 16:56:26 +0800112#include <android/hardware/boot/1.0/IBootControl.h>
113using android::hardware::boot::V1_0::CommandResult;
114using android::hardware::boot::V1_0::IBootControl;
Ethan Yonker1b190162016-12-05 15:25:19 -0600115#endif
116
bigbiffcfa875c2021-06-20 16:20:27 -0400117using android::fs_mgr::DestroyLogicalPartition;
bigbiffee7b7ff2020-03-23 15:08:27 -0400118using android::fs_mgr::Fstab;
119using android::fs_mgr::FstabEntry;
bigbiffcfa875c2021-06-20 16:20:27 -0400120using android::fs_mgr::MetadataBuilder;
Ethan Yonker6277c792014-09-15 14:54:30 -0500121
bigbiffee7b7ff2020-03-23 15:08:27 -0400122extern bool datamedia;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400123std::vector<users_struct> Users_List;
124
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100125std::string additional_fstab = "/etc/additional.fstab";
126
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500127TWPartitionManager::TWPartitionManager(void) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -0400128 mtp_was_enabled = false;
Ethan Yonker726a0202014-12-16 20:01:38 -0600129 mtp_write_fd = -1;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600130 uevent_pfd.fd = -1;
bigbiff7abc5fe2015-01-17 16:53:12 -0500131 stop_backup.set_value(0);
Ethan Yonker1b190162016-12-05 15:25:19 -0600132#ifdef AB_OTA_UPDATER
133 char slot_suffix[PROPERTY_VALUE_MAX];
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500134 property_get("ro.boot.slot_suffix", slot_suffix, "error");
135 if (strcmp(slot_suffix, "error") == 0)
136 property_get("ro.boot.slot", slot_suffix, "error");
Ethan Yonker1b190162016-12-05 15:25:19 -0600137 Active_Slot_Display = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500138 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Ethan Yonker1b190162016-12-05 15:25:19 -0600139 Set_Active_Slot("A");
140 else
141 Set_Active_Slot("B");
142#endif
bigbiff bigbiff34684ff2013-12-01 21:03:45 -0500143}
144
Captain Throwback37c3aef2021-10-06 11:38:18 -0400145void TWPartitionManager::Set_Crypto_State() {
146 char crypto_state[PROPERTY_VALUE_MAX];
147 property_get("ro.crypto.state", crypto_state, "error");
148 if (strcmp(crypto_state, "error") == 0)
149 property_set("ro.crypto.state", "encrypted");
150}
151
152int TWPartitionManager::Set_Crypto_Type(const char* crypto_type) {
153 char type_prop[PROPERTY_VALUE_MAX];
154 property_get("ro.crypto.type", type_prop, "error");
155 if (strcmp(type_prop, "error") == 0)
156 property_set("ro.crypto.type", crypto_type);
Captain Throwback18aea272020-10-29 12:43:17 -0400157 // Sleep for a bit so that services can start if needed
158 sleep(1);
159 return 0;
160}
161
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100162void inline Reset_Prop_From_Partition(std::string prop, std::string def, TWPartition *ven, TWPartition *odm) {
163 bool prop_on_odm = false, prop_on_vendor = false;
164 string prop_value;
165 if (odm) {
166 string odm_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/odm", "etc/build.prop");
167 if (!odm_prop.empty()) {
168 prop_on_odm = true;
169 if (TWFunc::Property_Override(prop, odm_prop) == NOT_AVAILABLE) {
170 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
171 } else {
172 prop_value = android::base::GetProperty(prop, "");
173 LOGINFO("Setting '%s' to '%s' from /odm/etc/build.prop\n", prop.c_str(), prop_value.c_str());
174 }
175 }
176 }
177 if (ven) {
178 string vendor_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/vendor", "build.prop");
179 if (!vendor_prop.empty()) {
180 prop_on_vendor = true;
181 if (TWFunc::Property_Override(prop, vendor_prop) == NOT_AVAILABLE) {
182 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
183 } else {
184 prop_value = android::base::GetProperty(prop, "");
185 LOGINFO("Setting '%s' to '%s' from /vendor/build.prop\n", prop.c_str(), prop_value.c_str());
186 }
187 }
188 }
189 if (!prop_on_odm && !prop_on_vendor && !def.empty()) {
190 if (TWFunc::Property_Override(prop, def) == NOT_AVAILABLE) {
191 LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
192 } else {
193 prop_value = android::base::GetProperty(prop, "");
194 LOGINFO("Setting '%s' to default value (%s)\n", prop.c_str(), prop_value.c_str());
195 }
196 }
197 prop_value = android::base::GetProperty(prop, "");
198 if (!prop_on_odm && !prop_on_vendor && !prop_value.empty() && def.empty()) {
199 if(TWFunc::Delete_Property(prop) == NOT_AVAILABLE) {
200 LOGERR("Unable to delete '%s' due to missing libresetprop\n", prop.c_str());
201 } else {
202 LOGINFO("Deleting property '%s'\n", prop.c_str());
203 }
204 }
205}
206
bigbiff22851b92021-09-01 16:46:57 -0400207int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool recovery_mode) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400208 FILE *fstabFile;
209 char fstab_line[MAX_FSTAB_LINE_LENGTH];
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100210 bool parse_userdata = false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600211 std::map<string, Flags_Map> twrp_flags;
212
213 fstabFile = fopen("/etc/twrp.flags", "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100214 if (Get_Super_Status()) {
215 Setup_Super_Devices();
216 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600217 if (fstabFile != NULL) {
Ian Macdonald160e8d32020-09-29 20:47:31 +0200218 LOGINFO("Reading /etc/twrp.flags\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600219 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600220 size_t line_size = strlen(fstab_line);
221 if (fstab_line[line_size - 1] != '\n')
222 fstab_line[line_size] = '\n';
223 Flags_Map line_flags;
224 line_flags.Primary_Block_Device = "";
225 line_flags.Alternate_Block_Device = "";
226 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
227 if (!line_flags.fstab_line) {
228 LOGERR("malloc error on line_flags.fstab_line\n");
229 return false;
230 }
231 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
232 bool found_separator = false;
233 char *fs_loc = NULL;
234 char *block_loc = NULL;
235 char *flags_loc = NULL;
236 size_t index, item_index = 0;
237 for (index = 0; index < line_size; index++) {
238 if (fstab_line[index] <= 32) {
239 fstab_line[index] = '\0';
240 found_separator = true;
241 } else if (found_separator) {
242 if (item_index == 0) {
243 fs_loc = fstab_line + index;
244 } else if (item_index == 1) {
245 block_loc = fstab_line + index;
246 } else if (item_index > 1) {
247 char *ptr = fstab_line + index;
248 if (*ptr == '/') {
249 line_flags.Alternate_Block_Device = ptr;
250 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
251 flags_loc = ptr;
252 // Once we find the flags=, we're done scanning the line
253 break;
254 }
255 }
256 found_separator = false;
257 item_index++;
258 }
259 }
260 if (block_loc)
261 line_flags.Primary_Block_Device = block_loc;
262 if (fs_loc)
263 line_flags.File_System = fs_loc;
264 if (flags_loc)
265 line_flags.Flags = flags_loc;
266 string Mount_Point = fstab_line;
267 twrp_flags[Mount_Point] = line_flags;
268 memset(fstab_line, 0, sizeof(fstab_line));
269 }
270 fclose(fstabFile);
271 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100272 TWPartition *data = NULL;
273 TWPartition *meta = NULL;
274parse:
Dees_Troy5bf43922012-09-07 16:07:55 -0400275 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100276 if (!parse_userdata && fstabFile == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000277 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400278 return false;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600279 } else
280 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
Dees_Troy5bf43922012-09-07 16:07:55 -0400281
282 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600283 if (strstr(fstab_line, "swap"))
284 continue; // Skip swap in recovery
285
bigbiff998f8392021-08-06 19:19:33 -0400286 if (fstab_line[0] == '#')
287 continue;
288
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100289 if (parse_userdata) {
290 if (strstr(fstab_line, "/metadata") && !strstr(fstab_line, "/data")) {
291 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), meta));
292 delete meta;
293 } else if (strstr(fstab_line, "/data")) {
294 Partitions.erase(std::find(Partitions.begin(), Partitions.end(), data));
295 delete data;
296 } else {
297 continue;
298 }
299 }
300
301
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600302 size_t line_size = strlen(fstab_line);
303 if (fstab_line[line_size - 1] != '\n')
304 fstab_line[line_size] = '\n';
Dees_Troy2a923582012-09-20 12:13:34 -0400305
Matt Mower2b2dd152016-04-26 11:24:08 -0500306 TWPartition* partition = new TWPartition();
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100307 if (partition->Process_Fstab_Line(fstab_line, Display_Error, parse_userdata ? NULL : &twrp_flags)) {
308 if (partition->Mount_Point == "/data") data = partition;
309 if (partition->Mount_Point == "/metadata") meta = partition;
310 if (partition->Is_Super && !Prepare_Super_Volume(partition)) {
311 goto clear;
312 }
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500313 Partitions.push_back(partition);
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100314 }
Matt Mower72c87ce2016-04-26 14:34:56 -0500315 else
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100316clear:
Dees_Troy5bf43922012-09-07 16:07:55 -0400317 delete partition;
Matt Mower2b2dd152016-04-26 11:24:08 -0500318
319 memset(fstab_line, 0, sizeof(fstab_line));
Dees_Troy5bf43922012-09-07 16:07:55 -0400320 }
321 fclose(fstabFile);
Matt Mower72c87ce2016-04-26 14:34:56 -0500322
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100323 if (!parse_userdata && twrp_flags.size() > 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600324 LOGINFO("Processing remaining twrp.flags\n");
325 // Add any items from twrp.flags that did not exist in the recovery.fstab
326 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
327 if (Find_Partition_By_Path(mapit->first) == NULL) {
328 TWPartition* partition = new TWPartition();
bigbiff8da46fa2020-09-08 16:42:34 -0400329 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600330 Partitions.push_back(partition);
331 else
332 delete partition;
333 }
334 if (mapit->second.fstab_line)
335 free(mapit->second.fstab_line);
336 mapit->second.fstab_line = NULL;
337 }
338 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100339 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
340 TWPartition* odm = PartitionManager.Find_Partition_By_Path("/odm");
341 if (!parse_userdata) {
342
343 if (ven) ven->Mount(true);
344 if (odm) odm->Mount(true);
345 if (TWFunc::Find_Fstab(Fstab_Filename)) {
346 string service;
347 LOGINFO("Fstab: %s\n", Fstab_Filename.c_str());
348 TWFunc::copy_file(Fstab_Filename, additional_fstab, 0600, false);
349 Fstab_Filename = additional_fstab;
350 property_set("fstab.additional", "1");
351 TWFunc::Get_Service_From(ven, "keymaster", service);
352 LOGINFO("Keymaster version: '%s' \n", TWFunc::Get_Version_From_Service(service).c_str());
353 property_set("keymaster_ver", TWFunc::Get_Version_From_Service(service).c_str());
354 parse_userdata = true;
355 Reset_Prop_From_Partition("ro.crypto.dm_default_key.options_format.version", "", ven, odm);
356 Reset_Prop_From_Partition("ro.crypto.volume.metadata.method", "", ven, odm);
357 Reset_Prop_From_Partition("ro.crypto.volume.options", "", ven, odm);
358 Reset_Prop_From_Partition("external_storage.projid.enabled", "", ven, odm);
359 Reset_Prop_From_Partition("external_storage.casefold.enabled", "", ven, odm);
360 Reset_Prop_From_Partition("external_storage.sdcardfs.enabled", "", ven, odm);
361 goto parse;
362 } else {
363 LOGINFO("Unable to parse vendor fstab\n");
364 }
Mohd Faraze3948ec2020-08-14 01:40:59 +0000365 }
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100366 if (ven) ven->UnMount(true);
367 if (odm) odm->UnMount(true);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600368 LOGINFO("Done processing fstab files\n");
369
bigbiff22851b92021-09-01 16:46:57 -0400370 if (recovery_mode) {
371 Setup_Fstab_Partitions(Display_Error);
Mohd Faraze3948ec2020-08-14 01:40:59 +0000372 }
bigbiff7ba75002020-04-11 20:47:09 -0400373 return true;
374}
375
bigbiff22851b92021-09-01 16:46:57 -0400376void TWPartitionManager::Setup_Fstab_Partitions(bool Display_Error) {
377 TWPartition* settings_partition = NULL;
378 TWPartition* andsec_partition = NULL;
379 std::vector<TWPartition*>::iterator iter;
380 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
381
382 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
383 (*iter)->Partition_Post_Processing(Display_Error);
384
385 if ((*iter)->Is_Storage) {
386 ++storageid;
387 (*iter)->MTP_Storage_ID = storageid;
388 }
389
390 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
391 settings_partition = (*iter);
392 else
393 (*iter)->Is_Settings_Storage = false;
394
395 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
396 andsec_partition = (*iter);
397 else
398 (*iter)->Has_Android_Secure = false;
bigbiff22851b92021-09-01 16:46:57 -0400399 }
400
me-cafebabed63fcaa2022-07-28 03:19:20 +0800401 Unlock_Block_Partitions();
402
bigbiff22851b92021-09-01 16:46:57 -0400403 //Setup Apex before decryption
404 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
405 TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
406 if (sys) {
407 if (sys->Get_Super_Status()) {
408 sys->Mount(true);
409 if (ven) {
410 ven->Mount(true);
411 }
412 #ifdef TW_EXCLUDE_APEX
413 LOGINFO("Apex is disabled in this build\n");
414 #else
415 twrpApex apex;
416 if (!apex.loadApexImages()) {
417 LOGERR("Unable to load apex images from %s\n", APEX_DIR);
418 property_set("twrp.apex.loaded", "false");
419 } else {
420 property_set("twrp.apex.loaded", "true");
421 }
422 TWFunc::check_and_run_script("/sbin/resyncapex.sh", "apex");
423 #endif
424 }
425 }
426 #ifndef USE_VENDOR_LIBS
427 if (ven)
428 ven->UnMount(true);
429 if (sys)
430 sys->UnMount(true);
431 #endif
432
433 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) {
434 // Attempt to automatically identify /data/media emulated storage devices
435 TWPartition* Dat = Find_Partition_By_Path("/data");
436 if (Dat) {
437 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
438 datamedia = true;
439 Dat->Setup_Data_Media();
440 settings_partition = Dat;
441 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
442 ++storageid;
443 Dat->MTP_Storage_ID = storageid;
444 }
445 }
446 if (!settings_partition) {
447 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
448 if ((*iter)->Is_Storage) {
449 settings_partition = (*iter);
450 break;
451 }
452 }
453 if (!settings_partition)
454 LOGERR("Unable to locate storage partition for storing settings file.\n");
455 }
456 if (!Write_Fstab()) {
457 if (Display_Error)
458 LOGERR("Error creating fstab\n");
459 else
460 LOGINFO("Error creating fstab\n");
461 }
462
463 if (andsec_partition) {
464 Setup_Android_Secure_Location(andsec_partition);
465 } else if (settings_partition) {
466 Setup_Android_Secure_Location(settings_partition);
467 }
468 if (settings_partition) {
469 Setup_Settings_Storage_Partition(settings_partition);
470 }
471
472 #ifdef TW_INCLUDE_CRYPTO
473 DataManager::SetValue(TW_IS_ENCRYPTED, 1);
474 Decrypt_Data();
475 #endif
476
477 Update_System_Details();
478 if (Get_Super_Status())
479 Setup_Super_Partition();
480 UnMount_Main_Partitions();
481 #ifdef AB_OTA_UPDATER
482 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
483 #endif
484 setup_uevent();
485}
486
bigbiff7ba75002020-04-11 20:47:09 -0400487int TWPartitionManager::Write_Fstab(void) {
488 FILE *fp;
489 std::vector<TWPartition*>::iterator iter;
490 string Line;
491
492 fp = fopen("/etc/fstab", "w");
493 if (fp == NULL) {
494 LOGINFO("Can not open /etc/fstab.\n");
495 return false;
496 }
497 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
498 if ((*iter)->Can_Be_Mounted) {
Mohd Faraz2a1e3752020-09-30 10:55:48 +0530499 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System +
500 ((*iter)->Mount_Read_Only ? " ro " : " rw ") + "0 0\n";
bigbiff7ba75002020-04-11 20:47:09 -0400501 fputs(Line.c_str(), fp);
502 }
503 // Handle subpartition tracking
504 if ((*iter)->Is_SubPartition) {
505 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
506 if (ParentPartition)
507 ParentPartition->Has_SubPartition = true;
508 else
509 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
510 }
511 }
512 fclose(fp);
513 return true;
514}
515
516void TWPartitionManager::Decrypt_Data() {
517 #ifdef TW_INCLUDE_CRYPTO
Ethan Yonkercceebb82014-11-18 10:17:59 -0600518 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
519 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
Captain Throwback37c3aef2021-10-06 11:38:18 -0400520 Set_Crypto_State();
bigbiff4fa02b52021-12-30 17:01:44 -0500521 TWPartition* Key_Directory_Partition = Find_Partition_By_Path(Decrypt_Data->Key_Directory);
522 if (Key_Directory_Partition != nullptr)
523 if (!Key_Directory_Partition->Is_Mounted())
524 Mount_By_Path(Decrypt_Data->Key_Directory, false);
525 if (!Decrypt_Data->Key_Directory.empty()) {
526 Set_Crypto_Type("file");
Ethan Yonker93382822018-11-01 15:25:31 -0500527#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
bigbiff7ba75002020-04-11 20:47:09 -0400528#ifdef USE_FSCRYPT
Mohd Faraz446ccbf2023-01-24 19:58:24 +0100529 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 -0500530 std::string crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "error");
Mohd Faraze3948ec2020-08-14 01:40:59 +0000531 Decrypt_Data->Decrypted_Block_Device = crypto_blkdev;
bigbiff7ba75002020-04-11 20:47:09 -0400532 LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", crypto_blkdev.c_str());
bigbiff7ba75002020-04-11 20:47:09 -0400533#endif
Ethan Yonker93382822018-11-01 15:25:31 -0500534 Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
535 int retry_count = 10;
536 while (!Decrypt_Data->Mount(false) && --retry_count)
537 usleep(500);
538 if (Decrypt_Data->Mount(false)) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400539 if (!Decrypt_Data->Decrypt_FBE_DE()) {
bigbiff437d86f2021-09-26 16:57:14 -0400540 LOGERR("Unable to decrypt FBE device\n");
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400541 }
542
Ethan Yonker93382822018-11-01 15:25:31 -0500543 } else {
544 LOGINFO("Failed to mount data after metadata decrypt\n");
545 }
546 } else {
547 LOGINFO("Unable to decrypt metadata encryption\n");
548 }
549#else
550 LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
551#endif
552 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600553 if (Decrypt_Data->Is_FBE) {
554 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
555 if (Decrypt_Device("!") == 0) {
556 gui_msg("decrypt_success=Successfully decrypted with default password.");
557 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
558 } else {
559 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
560 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600561 }
562 } else {
bigbiffbbbfe172021-05-30 15:52:41 -0400563 LOGINFO("FBE setup failed. Trying FDE...");
Captain Throwback37c3aef2021-10-06 11:38:18 -0400564 Set_Crypto_State();
565 Set_Crypto_Type("block");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600566 int password_type = cryptfs_get_password_type();
567 if (password_type == CRYPT_TYPE_DEFAULT) {
568 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
569 if (Decrypt_Device("default_password") == 0) {
570 gui_msg("decrypt_success=Successfully decrypted with default password.");
571 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
572 } else {
573 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
574 }
575 } else {
576 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
Noah Jacobson81d638d2019-04-28 00:10:07 -0400577 DataManager::SetValue("tw_crypto_pwtype_0", password_type);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600578 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600579 }
580 }
bigbiff4fa02b52021-12-30 17:01:44 -0500581 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted)) {
Ethan Yonker66a19492015-12-10 10:19:45 -0600582 Decrypt_Adopted();
583 }
Ethan Yonkercceebb82014-11-18 10:17:59 -0600584#endif
Dees_Troy51a0e822012-09-05 15:24:24 -0400585}
586
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500587void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500588 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
Ethan Yonkerc05c5982014-03-13 09:19:56 -0500589}
590
Matt Mowerbf4efa32014-04-14 23:25:26 -0500591void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
592 if (Part->Has_Android_Secure)
593 Part->Setup_AndSec();
Ethan Yonker6277c792014-09-15 14:54:30 -0500594 else if (!datamedia)
Matt Mowerbf4efa32014-04-14 23:25:26 -0500595 Part->Setup_AndSec();
Matt Mowerbf4efa32014-04-14 23:25:26 -0500596}
597
Dees_Troy8170a922012-09-18 15:40:25 -0400598void TWPartitionManager::Output_Partition_Logging(void) {
599 std::vector<TWPartition*>::iterator iter;
600
601 printf("\n\nPartition Logs:\n");
602 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
603 Output_Partition((*iter));
604}
605
606void TWPartitionManager::Output_Partition(TWPartition* Part) {
607 unsigned long long mb = 1048576;
608
Gary Peck004d48b2012-11-21 16:28:18 -0800609 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 -0400610 if (Part->Can_Be_Mounted) {
Gary Peck004d48b2012-11-21 16:28:18 -0800611 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 -0400612 }
Gary Peck004d48b2012-11-21 16:28:18 -0800613 printf("\n Flags: ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500614 if (Part->Can_Be_Mounted)
615 printf("Can_Be_Mounted ");
Gary Peck004d48b2012-11-21 16:28:18 -0800616 if (Part->Can_Be_Wiped)
617 printf("Can_Be_Wiped ");
Hashcodedabfd492013-08-29 22:45:30 -0700618 if (Part->Use_Rm_Rf)
619 printf("Use_Rm_Rf ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500620 if (Part->Can_Be_Backed_Up)
621 printf("Can_Be_Backed_Up ");
Gary Peck004d48b2012-11-21 16:28:18 -0800622 if (Part->Wipe_During_Factory_Reset)
623 printf("Wipe_During_Factory_Reset ");
624 if (Part->Wipe_Available_in_GUI)
625 printf("Wipe_Available_in_GUI ");
626 if (Part->Is_SubPartition)
627 printf("Is_SubPartition ");
628 if (Part->Has_SubPartition)
629 printf("Has_SubPartition ");
630 if (Part->Removable)
631 printf("Removable ");
632 if (Part->Is_Present)
633 printf("IsPresent ");
634 if (Part->Can_Be_Encrypted)
635 printf("Can_Be_Encrypted ");
636 if (Part->Is_Encrypted)
637 printf("Is_Encrypted ");
638 if (Part->Is_Decrypted)
639 printf("Is_Decrypted ");
640 if (Part->Has_Data_Media)
641 printf("Has_Data_Media ");
Dees_Troy83bd4832013-05-04 12:39:56 +0000642 if (Part->Can_Encrypt_Backup)
643 printf("Can_Encrypt_Backup ");
644 if (Part->Use_Userdata_Encryption)
645 printf("Use_Userdata_Encryption ");
Gary Peck004d48b2012-11-21 16:28:18 -0800646 if (Part->Has_Android_Secure)
647 printf("Has_Android_Secure ");
648 if (Part->Is_Storage)
649 printf("Is_Storage ");
Dees_Troya13d74f2013-03-24 08:54:55 -0500650 if (Part->Is_Settings_Storage)
651 printf("Is_Settings_Storage ");
Dees_Troy68cab492012-12-12 19:29:35 +0000652 if (Part->Ignore_Blkid)
653 printf("Ignore_Blkid ");
Ethan Yonker253368a2014-11-25 15:00:52 -0600654 if (Part->Mount_To_Decrypt)
655 printf("Mount_To_Decrypt ");
Ethan Yonker96af84a2015-01-05 14:58:36 -0600656 if (Part->Can_Flash_Img)
657 printf("Can_Flash_Img ");
Ethan Yonker66a19492015-12-10 10:19:45 -0600658 if (Part->Is_Adopted_Storage)
659 printf("Is_Adopted_Storage ");
Ethan Yonker1b190162016-12-05 15:25:19 -0600660 if (Part->SlotSelect)
661 printf("SlotSelect ");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600662 if (Part->Mount_Read_Only)
663 printf("Mount_Read_Only ");
bigbiffcfa875c2021-06-20 16:20:27 -0400664 if (Part->Is_Super)
665 printf("Is_Super ");
Gary Peck004d48b2012-11-21 16:28:18 -0800666 printf("\n");
667 if (!Part->SubPartition_Of.empty())
668 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
669 if (!Part->Symlink_Path.empty())
670 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
671 if (!Part->Symlink_Mount_Point.empty())
672 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
673 if (!Part->Primary_Block_Device.empty())
674 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
675 if (!Part->Alternate_Block_Device.empty())
676 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
677 if (!Part->Decrypted_Block_Device.empty())
678 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
dianlujitao4879b372018-12-03 18:45:47 +0800679 if (!Part->Crypto_Key_Location.empty())
Ethan Yonker253368a2014-11-25 15:00:52 -0600680 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800681 if (Part->Length != 0)
682 printf(" Length: %i\n", Part->Length);
683 if (!Part->Display_Name.empty())
684 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500685 if (!Part->Storage_Name.empty())
686 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800687 if (!Part->Backup_Path.empty())
688 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
689 if (!Part->Backup_Name.empty())
690 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -0500691 if (!Part->Backup_Display_Name.empty())
692 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
Gary Peck004d48b2012-11-21 16:28:18 -0800693 if (!Part->Backup_FileName.empty())
694 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
695 if (!Part->Storage_Path.empty())
696 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
697 if (!Part->Current_File_System.empty())
698 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
699 if (!Part->Fstab_File_System.empty())
700 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
701 if (Part->Format_Block_Size != 0)
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500702 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
Dees_Troy094207a2012-09-26 12:00:39 -0400703 if (!Part->MTD_Name.empty())
704 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
Matt Mower029a82d2017-01-08 13:12:38 -0600705 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
Hashcode62bd9e02013-11-19 21:59:42 -0800706 if (Part->Mount_Flags || !Part->Mount_Options.empty())
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600707 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -0600708 if (Part->MTP_Storage_ID)
709 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
Ethan Yonker93382822018-11-01 15:25:31 -0500710 if (!Part->Key_Directory.empty())
711 printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
Ethan Yonker6277c792014-09-15 14:54:30 -0500712 printf("\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400713}
714
Dees_Troy51a0e822012-09-05 15:24:24 -0400715int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400716 std::vector<TWPartition*>::iterator iter;
717 int ret = false;
718 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400719 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400720
bigbiffd58ba182020-03-23 10:02:29 -0400721 if (Local_Path == "/tmp" || Local_Path == "/")
Dees_Troy43d8b002012-09-17 16:00:01 -0400722 return true;
723
Dees_Troy5bf43922012-09-07 16:07:55 -0400724 // Iterate through all partitions
725 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400726 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400727 ret = (*iter)->Mount(Display_Error);
728 found = true;
Dees_Troy51127312012-09-08 13:08:49 -0400729 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400730 (*iter)->Mount(Display_Error);
Dees_Troy51127312012-09-08 13:08:49 -0400731 }
Dees_Troy5bf43922012-09-07 16:07:55 -0400732 }
733 if (found) {
734 return ret;
735 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500736 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 -0400737 }
738 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400739}
740
Dees_Troy51a0e822012-09-05 15:24:24 -0400741int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400742 std::vector<TWPartition*>::iterator iter;
743 int ret = false;
744 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -0400745 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy51127312012-09-08 13:08:49 -0400746
747 // Iterate through all partitions
748 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400749 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Dees_Troy51127312012-09-08 13:08:49 -0400750 ret = (*iter)->UnMount(Display_Error);
751 found = true;
752 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
753 (*iter)->UnMount(Display_Error);
754 }
755 }
756 if (found) {
757 return ret;
758 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500759 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 -0400760 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000761 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400762 }
763 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400764}
765
Dees_Troy51a0e822012-09-05 15:24:24 -0400766int TWPartitionManager::Is_Mounted_By_Path(string Path) {
Dees_Troy51127312012-09-08 13:08:49 -0400767 TWPartition* Part = Find_Partition_By_Path(Path);
768
769 if (Part)
770 return Part->Is_Mounted();
771 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000772 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
Dees_Troy51127312012-09-08 13:08:49 -0400773 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400774}
775
Dees_Troy5bf43922012-09-07 16:07:55 -0400776int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
Dees_Troy51127312012-09-08 13:08:49 -0400777 string current_storage_path = DataManager::GetCurrentStoragePath();
778
779 if (Mount_By_Path(current_storage_path, Display_Error)) {
780 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
781 if (FreeStorage)
782 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
783 return true;
784 }
785 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -0400786}
787
Dees_Troy5bf43922012-09-07 16:07:55 -0400788int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
789 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
790}
791
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600792TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
Dees_Troy5bf43922012-09-07 16:07:55 -0400793 std::vector<TWPartition*>::iterator iter;
Dees_Troy38bd7602012-09-14 13:33:53 -0400794 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy5bf43922012-09-07 16:07:55 -0400795
dianlujitaob76a73a2020-04-30 20:33:20 +0800796 if (Local_Path == "/system")
797 Local_Path = Get_Android_Root_Path();
Dees_Troy5bf43922012-09-07 16:07:55 -0400798 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -0400799 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
Dees_Troy5bf43922012-09-07 16:07:55 -0400800 return (*iter);
801 }
Dees_Troy51a0e822012-09-05 15:24:24 -0400802 return NULL;
803}
804
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600805TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
806 std::vector<TWPartition*>::iterator iter;
807
808 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
809 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
810 return (*iter);
811 }
812 return NULL;
813}
814
Ethan Yonker53796e72019-01-11 22:49:52 -0600815int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400816 // Check the backup name to ensure that it is the correct size and contains only valid characters
817 // and that a backup with that name doesn't already exist
818 char backup_name[MAX_BACKUP_NAME_LEN];
819 char backup_loc[255], tw_image_dir[255];
820 int copy_size;
821 int index, cur_char;
Ethan Yonker53796e72019-01-11 22:49:52 -0600822 string Backup_Loc;
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400823
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400824 copy_size = Backup_Name.size();
825 // Check size
826 if (copy_size > MAX_BACKUP_NAME_LEN) {
827 if (Display_Error)
Ethan Yonker74db1572015-10-28 12:44:49 -0500828 gui_err("backup_name_len=Backup name is too long.");
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400829 return -2;
830 }
831
832 // Check each character
833 strncpy(backup_name, Backup_Name.c_str(), copy_size);
Dees_Troya13d74f2013-03-24 08:54:55 -0500834 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400835 return 0; // A "0" (zero) means to use the current timestamp for the backup name
836 for (index=0; index<copy_size; index++) {
837 cur_char = (int)backup_name[index];
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500838 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 -0400839 // These are valid characters
840 // Numbers
841 // Upper case letters
842 // Lower case letters
843 // Space
844 // and -_.{}[]
845 } else {
846 if (Display_Error)
Ethan Yonker4adc33e2016-01-22 16:07:11 -0600847 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 -0400848 return -3;
849 }
850 }
851
Ethan Yonker53796e72019-01-11 22:49:52 -0600852 if (Must_Be_Unique) {
853 // Check to make sure that a backup with this name doesn't already exist
854 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
855 strcpy(backup_loc, Backup_Loc.c_str());
856 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
857 if (TWFunc::Path_Exists(tw_image_dir)) {
858 if (Display_Error)
859 gui_err("backup_name_exists=A backup with that name already exists!");
bigbiffce8f83c2015-12-12 18:30:21 -0500860
Ethan Yonker53796e72019-01-11 22:49:52 -0600861 return -4;
862 }
863 // Backup is unique
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400864 }
Ethan Yonker53796e72019-01-11 22:49:52 -0600865 // No problems found
Dees_Troyc9ff7a32012-09-27 10:09:41 -0400866 return 0;
867}
868
bigbiffce8f83c2015-12-12 18:30:21 -0500869bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400870 time_t start, stop;
Matt Mower23d8aae2017-01-06 14:30:33 -0600871 int use_compression;
bigbiffce8f83c2015-12-12 18:30:21 -0500872 string backup_log = part_settings->Backup_Folder + "/recovery.log";
Dees_Troy43d8b002012-09-17 16:00:01 -0400873
bigbiffce8f83c2015-12-12 18:30:21 -0500874 if (part_settings->Part == NULL)
Dees_Troy43d8b002012-09-17 16:00:01 -0400875 return true;
876
Dees_Troy093b7642012-09-21 15:59:38 -0400877 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -0400878
Tom Hite5a926722014-09-15 01:31:03 +0000879 TWFunc::SetPerformanceMode(true);
Dees_Troy43d8b002012-09-17 16:00:01 -0400880 time(&start);
881
bigbiffce8f83c2015-12-12 18:30:21 -0500882 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500883 sync();
884 sync();
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400885 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500886 if (!part_settings->adbbackup && part_settings->generate_digest) {
887 if (!twrpDigestDriver::Make_Digest(Full_Filename))
888 goto backup_error;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400889 }
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400890
bigbiffce8f83c2015-12-12 18:30:21 -0500891 if (part_settings->Part->Has_SubPartition) {
Dees_Troy8170a922012-09-18 15:40:25 -0400892 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400893 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -0400894
895 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400896 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
Ethan Yonkerdcf2b672016-09-13 14:41:53 -0500897 part_settings->Part = *subpart;
bigbiffce8f83c2015-12-12 18:30:21 -0500898 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500899 goto backup_error;
Tom Hite5a926722014-09-15 01:31:03 +0000900 }
Dees_Troy2727b992013-08-14 20:09:30 +0000901 sync();
902 sync();
bigbiff bigbifff5955b12019-05-18 17:28:58 -0400903 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400904 if (!part_settings->adbbackup && part_settings->generate_digest) {
905 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500906 goto backup_error;
bigbiffce8f83c2015-12-12 18:30:21 -0500907 }
Tom Hite5a926722014-09-15 01:31:03 +0000908 }
Dees_Troy8170a922012-09-18 15:40:25 -0400909 }
910 }
911 }
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400912
Dees_Troy43d8b002012-09-17 16:00:01 -0400913 time(&stop);
that203bcc92015-05-09 17:27:33 +0200914 int backup_time = (int) difftime(stop, start);
Dees_Troy2673cec2013-04-02 20:22:16 +0000915 LOGINFO("Partition Backup time: %d\n", backup_time);
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -0400916
bigbiffce8f83c2015-12-12 18:30:21 -0500917 if (part_settings->Part->Backup_Method == BM_FILES) {
918 part_settings->file_time += backup_time;
Dees_Troy43d8b002012-09-17 16:00:01 -0400919 } else {
bigbiffce8f83c2015-12-12 18:30:21 -0500920 part_settings->img_time += backup_time;
921
Dees_Troy43d8b002012-09-17 16:00:01 -0400922 }
Tom Hite5a926722014-09-15 01:31:03 +0000923
Matt Mower02899552016-12-30 18:13:51 -0600924 TWFunc::SetPerformanceMode(false);
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500925 return true;
Dees_Troy43d8b002012-09-17 16:00:01 -0400926 }
Ethan Yonkercd00a8b2017-07-06 10:23:30 -0500927backup_error:
928 Clean_Backup_Folder(part_settings->Backup_Folder);
929 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
930 tw_set_default_metadata(backup_log.c_str());
931 TWFunc::SetPerformanceMode(false);
932 return false;
bigbiff7abc5fe2015-01-17 16:53:12 -0500933}
934
bigbiffbf1d6722015-02-14 16:25:59 -0500935void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
936 DIR *d = opendir(Backup_Folder.c_str());
937 struct dirent *p;
938 int r;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400939 vector<string> ext;
940
941 //extensions we should delete when cleaning
942 ext.push_back("win");
943 ext.push_back("md5");
944 ext.push_back("sha2");
945 ext.push_back("info");
bigbiffbf1d6722015-02-14 16:25:59 -0500946
Ethan Yonker74db1572015-10-28 12:44:49 -0500947 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
bigbiffbf1d6722015-02-14 16:25:59 -0500948
949 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500950 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
bigbiffbf1d6722015-02-14 16:25:59 -0500951 return;
952 }
953
Matt Mower2b18a532015-02-20 16:58:05 -0600954 while ((p = readdir(d))) {
bigbiffbf1d6722015-02-14 16:25:59 -0500955 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
956 continue;
957
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500958 string path = Backup_Folder + "/" + p->d_name;
bigbiffbf1d6722015-02-14 16:25:59 -0500959
960 size_t dot = path.find_last_of(".") + 1;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -0400961 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
962 if (path.substr(dot) == *i) {
963 r = unlink(path.c_str());
964 if (r != 0)
965 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
bigbiffbf1d6722015-02-14 16:25:59 -0500966 }
967 }
968 }
969 closedir(d);
970}
971
Ethan Yonker472f5062016-02-25 13:47:30 -0600972int TWPartitionManager::Check_Backup_Cancel() {
973 return stop_backup.get_value();
974}
975
bigbiff7abc5fe2015-01-17 16:53:12 -0500976int TWPartitionManager::Cancel_Backup() {
977 string Backup_Folder, Backup_Name, Full_Backup_Path;
978
979 stop_backup.set_value(1);
980
981 if (tar_fork_pid != 0) {
982 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
983 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Ethan Yonkere080c1f2016-09-19 13:50:25 -0500984 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
bigbiff7abc5fe2015-01-17 16:53:12 -0500985 LOGINFO("Killing pid: %d\n", tar_fork_pid);
986 kill(tar_fork_pid, SIGUSR2);
987 while (kill(tar_fork_pid, 0) == 0) {
988 usleep(1000);
989 }
990 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
991 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
992 TWFunc::removeDir(Full_Backup_Path, false);
993 tar_fork_pid = 0;
994 }
995
996 return 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400997}
998
bigbiffce8f83c2015-12-12 18:30:21 -0500999int TWPartitionManager::Run_Backup(bool adbbackup) {
1000 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001001 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
bigbiffce8f83c2015-12-12 18:30:21 -05001002 string Backup_Name, Backup_List, backup_path;
Matt Mower23d8aae2017-01-06 14:30:33 -06001003 unsigned long long total_bytes = 0, free_space = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -04001004 TWPartition* storage = NULL;
1005 struct tm *t;
Matt Mower23d8aae2017-01-06 14:30:33 -06001006 time_t seconds, total_start, total_stop;
Dees_Troya13d74f2013-03-24 08:54:55 -05001007 size_t start_pos = 0, end_pos = 0;
bigbiff7abc5fe2015-01-17 16:53:12 -05001008 stop_backup.set_value(0);
Dees_Troy43d8b002012-09-17 16:00:01 -04001009 seconds = time(0);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001010 t = localtime(&seconds);
Dees_Troy43d8b002012-09-17 16:00:01 -04001011
bigbiffce8f83c2015-12-12 18:30:21 -05001012 part_settings.img_bytes_remaining = 0;
1013 part_settings.file_bytes_remaining = 0;
1014 part_settings.img_time = 0;
1015 part_settings.file_time = 0;
1016 part_settings.img_bytes = 0;
1017 part_settings.file_bytes = 0;
1018 part_settings.PM_Method = PM_BACKUP;
1019
bigbiffce8f83c2015-12-12 18:30:21 -05001020 part_settings.adbbackup = adbbackup;
Dees_Troy43d8b002012-09-17 16:00:01 -04001021 time(&total_start);
1022
1023 Update_System_Details();
1024
1025 if (!Mount_Current_Storage(true))
1026 return false;
1027
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001028 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
1029 if (skip_digest == 0)
1030 part_settings.generate_digest = true;
Dees_Troyc5865ab2012-09-24 15:08:04 -04001031 else
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001032 part_settings.generate_digest = false;
Dees_Troy4a2a1262012-09-18 09:33:47 -04001033
bigbiffce8f83c2015-12-12 18:30:21 -05001034 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001035 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
1036 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
1037 Backup_Name = TWFunc::Get_Current_Date();
1038 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
Dees Troyb21cc642013-09-10 17:36:41 +00001039 TWFunc::Auto_Generate_Backup_Name();
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001040 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
Dees_Troy43d8b002012-09-17 16:00:01 -04001041 }
bigbiffce8f83c2015-12-12 18:30:21 -05001042
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001043 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001044 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001045
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001046 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -04001047
Dees_Troy2673cec2013-04-02 20:22:16 +00001048 LOGINFO("Calculating backup details...\n");
Dees_Troya13d74f2013-03-24 08:54:55 -05001049 DataManager::GetValue("tw_backup_list", Backup_List);
bigbiff7ba75002020-04-11 20:47:09 -04001050 LOGINFO("Backup_List: %s\n", Backup_List.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05001051 if (!Backup_List.empty()) {
1052 end_pos = Backup_List.find(";", start_pos);
1053 while (end_pos != string::npos && start_pos < Backup_List.size()) {
1054 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiff7ba75002020-04-11 20:47:09 -04001055 LOGINFO("backup_path: %s\n", backup_path.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001056 part_settings.Part = Find_Partition_By_Path(backup_path);
1057 if (part_settings.Part != NULL) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001058 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001059 if (part_settings.Part->Backup_Method == BM_FILES)
1060 part_settings.file_bytes += part_settings.Part->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001061 else
bigbiffce8f83c2015-12-12 18:30:21 -05001062 part_settings.img_bytes += part_settings.Part->Backup_Size;
1063 if (part_settings.Part->Has_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05001064 std::vector<TWPartition*>::iterator subpart;
1065
1066 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiffce8f83c2015-12-12 18:30:21 -05001067 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 -05001068 partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001069 if ((*subpart)->Backup_Method == BM_FILES)
1070 part_settings.file_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001071 else
bigbiffce8f83c2015-12-12 18:30:21 -05001072 part_settings.img_bytes += (*subpart)->Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05001073 }
1074 }
Dees_Troy8170a922012-09-18 15:40:25 -04001075 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001076 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001077 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 -04001078 }
Dees_Troya13d74f2013-03-24 08:54:55 -05001079 start_pos = end_pos + 1;
1080 end_pos = Backup_List.find(";", start_pos);
Dees_Troy43d8b002012-09-17 16:00:01 -04001081 }
1082 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001083
1084 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001085 gui_msg("no_partition_selected=No partitions selected for backup.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001086 return false;
1087 }
bigbiffce8f83c2015-12-12 18:30:21 -05001088 if (adbbackup) {
1089 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
1090 return false;
1091 }
1092 }
1093 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
Ethan Yonker472f5062016-02-25 13:47:30 -06001094 ProgressTracking progress(total_bytes);
bigbiffce8f83c2015-12-12 18:30:21 -05001095 part_settings.progress = &progress;
1096
Ethan Yonker74db1572015-10-28 12:44:49 -05001097 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
1098 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001099 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1100 if (storage != NULL) {
1101 free_space = storage->Free;
Ethan Yonker74db1572015-10-28 12:44:49 -05001102 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
Dees_Troy43d8b002012-09-17 16:00:01 -04001103 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001104 gui_err("unable_locate_storage=Unable to locate storage device.");
Dees_Troy43d8b002012-09-17 16:00:01 -04001105 return false;
1106 }
bigbiffbf1d6722015-02-14 16:25:59 -05001107
Matt Mowerbfccfb82016-04-25 23:22:31 -05001108 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
bigbiffce8f83c2015-12-12 18:30:21 -05001109
1110 if (adbbackup)
1111 disable_free_space_check = true;
1112
bigbiffbf1d6722015-02-14 16:25:59 -05001113 if (!disable_free_space_check) {
1114 if (free_space - (32 * 1024 * 1024) < total_bytes) {
1115 // We require an extra 32MB just in case
Ethan Yonker74db1572015-10-28 12:44:49 -05001116 gui_err("no_space=Not enough free space on storage.");
bigbiffbf1d6722015-02-14 16:25:59 -05001117 return false;
1118 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001119 }
bigbiffce8f83c2015-12-12 18:30:21 -05001120 part_settings.img_bytes_remaining = part_settings.img_bytes;
1121 part_settings.file_bytes_remaining = part_settings.file_bytes;
Dees_Troy43d8b002012-09-17 16:00:01 -04001122
Ethan Yonker74db1572015-10-28 12:44:49 -05001123 gui_msg("backup_started=[BACKUP STARTED]");
bigbiff bigbiffcdd97c72019-03-29 19:12:33 -04001124
1125 int is_decrypted = 0;
1126 int is_encrypted = 0;
1127
1128 DataManager::GetValue(TW_IS_DECRYPTED, is_decrypted);
1129 DataManager::GetValue(TW_IS_ENCRYPTED, is_encrypted);
1130 if (!adbbackup || (!is_encrypted || (is_encrypted && is_decrypted))) {
1131 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
1132 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
1133 gui_err("fail_backup_folder=Failed to make backup folder.");
1134 return false;
1135 }
Dees_Troyd4b22b02013-01-18 17:17:58 +00001136 }
1137
Dees_Troy2673cec2013-04-02 20:22:16 +00001138 DataManager::SetProgress(0.0);
Dees_Troy093b7642012-09-21 15:59:38 -04001139
Dees_Troya13d74f2013-03-24 08:54:55 -05001140 start_pos = 0;
1141 end_pos = Backup_List.find(";", start_pos);
1142 while (end_pos != string::npos && start_pos < Backup_List.size()) {
bigbiff7abc5fe2015-01-17 16:53:12 -05001143 if (stop_backup.get_value() != 0)
1144 return -1;
Dees_Troya13d74f2013-03-24 08:54:55 -05001145 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001146 part_settings.Part = Find_Partition_By_Path(backup_path);
1147 if (part_settings.Part != NULL) {
1148 if (!Backup_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001149 return false;
1150 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001151 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 -05001152 }
1153 start_pos = end_pos + 1;
1154 end_pos = Backup_List.find(";", start_pos);
1155 }
Dees_Troy43d8b002012-09-17 16:00:01 -04001156
1157 // Average BPS
bigbiffce8f83c2015-12-12 18:30:21 -05001158 if (part_settings.img_time == 0)
1159 part_settings.img_time = 1;
1160 if (part_settings.file_time == 0)
1161 part_settings.file_time = 1;
1162 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
1163 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
Dees_Troy43d8b002012-09-17 16:00:01 -04001164
bigbiffce8f83c2015-12-12 18:30:21 -05001165 if (part_settings.file_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001166 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 -05001167 if (part_settings.img_bytes != 0)
Ethan Yonker472f5062016-02-25 13:47:30 -06001168 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 -04001169
1170 time(&total_stop);
1171 int total_time = (int) difftime(total_stop, total_start);
bigbiffce8f83c2015-12-12 18:30:21 -05001172
1173 uint64_t actual_backup_size;
Ethan Yonker3fdcda42016-11-30 12:29:37 -06001174 if (!adbbackup) {
1175 TWExclude twe;
1176 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
1177 } else
bigbiffce8f83c2015-12-12 18:30:21 -05001178 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001179 actual_backup_size /= (1024LLU * 1024LLU);
Dees_Troy43d8b002012-09-17 16:00:01 -04001180
bigbiffce8f83c2015-12-12 18:30:21 -05001181 int prev_img_bps = 0, use_compression = 0;
1182 unsigned long long prev_file_bps = 0;
Matt Mower173cdb92016-12-31 02:49:19 -06001183 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001184 img_bps += (prev_img_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001185 img_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001186
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001187 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
Dees_Troy093b7642012-09-21 15:59:38 -04001188 if (use_compression)
1189 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001190 else
Dees_Troy093b7642012-09-21 15:59:38 -04001191 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
1192 file_bps += (prev_file_bps * 4);
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001193 file_bps /= 5;
Dees_Troy093b7642012-09-21 15:59:38 -04001194
Matt Mowerfb1c4ff2014-04-16 13:43:36 -05001195 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
Dees_Troy093b7642012-09-21 15:59:38 -04001196 if (use_compression)
1197 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
1198 else
1199 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
1200
Ethan Yonker74db1572015-10-28 12:44:49 -05001201 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Dees_Troy43d8b002012-09-17 16:00:01 -04001202 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001203 UnMount_Main_Partitions();
Ethan Yonker56db1c42015-12-20 22:49:00 -06001204 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
Ethan Yonkere080c1f2016-09-19 13:50:25 -05001205 string backup_log = part_settings.Backup_Folder + "/recovery.log";
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001206 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -06001207 tw_set_default_metadata(backup_log.c_str());
bigbiffce8f83c2015-12-12 18:30:21 -05001208
1209 if (part_settings.adbbackup) {
1210 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
1211 return false;
1212 }
1213 }
1214 part_settings.adbbackup = false;
1215 DataManager::SetValue("tw_enable_adb_backup", 0);
1216
Dees_Troy3f5c4e82013-02-01 15:16:59 +00001217 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001218}
1219
bigbiffce8f83c2015-12-12 18:30:21 -05001220bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
Dees_Troy4a2a1262012-09-18 09:33:47 -04001221 time_t Start, Stop;
bigbiffce8f83c2015-12-12 18:30:21 -05001222
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001223 if (part_settings->adbbackup) {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001224 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
1225 LOGINFO("setting backup name: %s\n", partName.c_str());
bigbiff bigbiffb5ecaad2017-03-20 18:53:53 -04001226 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
1227 }
1228
Tom Hite5a926722014-09-15 01:31:03 +00001229 TWFunc::SetPerformanceMode(true);
bigbiffce8f83c2015-12-12 18:30:21 -05001230
Dees_Troy4a2a1262012-09-18 09:33:47 -04001231 time(&Start);
Ethan Yonker472f5062016-02-25 13:47:30 -06001232
bigbiffce8f83c2015-12-12 18:30:21 -05001233 if (!part_settings->Part->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001234 TWFunc::SetPerformanceMode(false);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001235 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001236 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001237 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
Dees_Troy8170a922012-09-18 15:40:25 -04001238 std::vector<TWPartition*>::iterator subpart;
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001239 TWPartition *parentPart = part_settings->Part;
Dees_Troy8170a922012-09-18 15:40:25 -04001240
1241 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001242 part_settings->Part = *subpart;
1243 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1244 part_settings->Part = (*subpart);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001245 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
bigbiffce8f83c2015-12-12 18:30:21 -05001246 if (!(*subpart)->Restore(part_settings)) {
Tom Hite5a926722014-09-15 01:31:03 +00001247 TWFunc::SetPerformanceMode(false);
Dees_Troy8170a922012-09-18 15:40:25 -04001248 return false;
Tom Hite5a926722014-09-15 01:31:03 +00001249 }
Dees_Troy8170a922012-09-18 15:40:25 -04001250 }
1251 }
1252 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001253 time(&Stop);
Tom Hite5a926722014-09-15 01:31:03 +00001254 TWFunc::SetPerformanceMode(false);
bigbiffce8f83c2015-12-12 18:30:21 -05001255 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1256
Dees_Troy4a2a1262012-09-18 09:33:47 -04001257 return true;
1258}
1259
Ethan Yonker472f5062016-02-25 13:47:30 -06001260int TWPartitionManager::Run_Restore(const string& Restore_Name) {
bigbiffce8f83c2015-12-12 18:30:21 -05001261 PartitionSettings part_settings;
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001262 int check_digest;
bigbiffce8f83c2015-12-12 18:30:21 -05001263
Dees_Troy4a2a1262012-09-18 09:33:47 -04001264 time_t rStart, rStop;
1265 time(&rStart);
Dees_Troya13d74f2013-03-24 08:54:55 -05001266 string Restore_List, restore_path;
1267 size_t start_pos = 0, end_pos;
bigbiffce8f83c2015-12-12 18:30:21 -05001268
Ethan Yonkerdcf2b672016-09-13 14:41:53 -05001269 part_settings.Backup_Folder = Restore_Name;
bigbiffce8f83c2015-12-12 18:30:21 -05001270 part_settings.Part = NULL;
1271 part_settings.partition_count = 0;
1272 part_settings.total_restore_size = 0;
1273 part_settings.adbbackup = false;
1274 part_settings.PM_Method = PM_RESTORE;
Dees_Troy43d8b002012-09-17 16:00:01 -04001275
Ethan Yonker74db1572015-10-28 12:44:49 -05001276 gui_msg("restore_started=[RESTORE STARTED]");
1277 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
Dees_Troy43d8b002012-09-17 16:00:01 -04001278
Dees_Troy4a2a1262012-09-18 09:33:47 -04001279 if (!Mount_Current_Storage(true))
1280 return false;
1281
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001282 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1283 if (check_digest > 0) {
1284 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1285 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1286 gui_msg("verifying_digest=Verifying Digest");
Dees_Troya13d74f2013-03-24 08:54:55 -05001287 } else {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001288 gui_msg("skip_digest=Skipping Digest check based on user setting.");
Dees_Troya13d74f2013-03-24 08:54:55 -05001289 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001290 gui_msg("calc_restore=Calculating restore details...");
Dees_Troya13d74f2013-03-24 08:54:55 -05001291 DataManager::GetValue("tw_restore_selected", Restore_List);
bigbiffce8f83c2015-12-12 18:30:21 -05001292
Dees_Troya13d74f2013-03-24 08:54:55 -05001293 if (!Restore_List.empty()) {
1294 end_pos = Restore_List.find(";", start_pos);
1295 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1296 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001297 part_settings.Part = Find_Partition_By_Path(restore_path);
1298 if (part_settings.Part != NULL) {
bigbiffce8f83c2015-12-12 18:30:21 -05001299 if (part_settings.Part->Mount_Read_Only) {
1300 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 -05001301 return false;
1302 }
bigbiffce8f83c2015-12-12 18:30:21 -05001303
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001304 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1305
bigbiff4a60bee2021-01-23 14:08:03 -05001306 if (tw_get_default_metadata(Get_Android_Root_Path().c_str()) != 0) {
1307 gui_msg(Msg(msg::kWarning, "restore_system_context=Unable to get default context for {1} -- Android may not boot.")(Get_Android_Root_Path()));
1308 }
1309
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001310 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001311 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001312 part_settings.partition_count++;
1313 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1314 if (part_settings.Part->Has_SubPartition) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001315 TWPartition *parentPart = part_settings.Part;
Dees_Troya13d74f2013-03-24 08:54:55 -05001316 std::vector<TWPartition*>::iterator subpart;
1317
1318 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
bigbiff bigbiff8fd4b092016-08-30 20:48:53 -04001319 part_settings.Part = *subpart;
1320 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
bigbiff bigbiff56cf5642016-08-19 17:43:45 -04001321 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
Dees_Troya13d74f2013-03-24 08:54:55 -05001322 return false;
bigbiffce8f83c2015-12-12 18:30:21 -05001323 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
Dees_Troya13d74f2013-03-24 08:54:55 -05001324 }
1325 }
1326 }
1327 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001328 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001329 }
1330 start_pos = end_pos + 1;
1331 end_pos = Restore_List.find(";", start_pos);
Dees_Troy4a2a1262012-09-18 09:33:47 -04001332 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001333 }
Dees_Troy4a2a1262012-09-18 09:33:47 -04001334
bigbiffce8f83c2015-12-12 18:30:21 -05001335 if (part_settings.partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001336 gui_err("no_part_restore=No partitions selected for restore.");
Dees_Troy4a2a1262012-09-18 09:33:47 -04001337 return false;
1338 }
1339
bigbiffce8f83c2015-12-12 18:30:21 -05001340 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1341 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 +00001342 DataManager::SetProgress(0.0);
bigbiffce8f83c2015-12-12 18:30:21 -05001343 ProgressTracking progress(part_settings.total_restore_size);
1344 part_settings.progress = &progress;
Ethan Yonker1b7a31b2014-07-03 15:09:22 -05001345
Dees_Troya13d74f2013-03-24 08:54:55 -05001346 start_pos = 0;
1347 if (!Restore_List.empty()) {
1348 end_pos = Restore_List.find(";", start_pos);
1349 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1350 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiffce8f83c2015-12-12 18:30:21 -05001351
1352 part_settings.Part = Find_Partition_By_Path(restore_path);
1353 if (part_settings.Part != NULL) {
1354 part_settings.partition_count++;
bigbiffce8f83c2015-12-12 18:30:21 -05001355 if (!Restore_Partition(&part_settings))
Dees_Troya13d74f2013-03-24 08:54:55 -05001356 return false;
1357 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001358 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05001359 }
1360 start_pos = end_pos + 1;
1361 end_pos = Restore_List.find(";", start_pos);
1362 }
1363 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001364 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
bigbiff4a60bee2021-01-23 14:08:03 -05001365 tw_set_default_metadata(Get_Android_Root_Path().c_str());
Captain Throwback9d6feb52018-07-27 10:05:24 -04001366 UnMount_By_Path(Get_Android_Root_Path(), false);
Dees_Troy43d8b002012-09-17 16:00:01 -04001367 Update_System_Details();
Dees_Troyd0384ef2012-10-12 12:15:42 -04001368 UnMount_Main_Partitions();
Dees_Troy4a2a1262012-09-18 09:33:47 -04001369 time(&rStop);
Matt Mower3c366972015-12-25 19:28:31 -06001370 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
bigbiff8f5fad32021-11-03 20:39:02 -04001371 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
1372 if (Decrypt_Data && Decrypt_Data->Is_Encrypted)
1373 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 -05001374 DataManager::SetValue("tw_file_progress", "");
bigbiffce8f83c2015-12-12 18:30:21 -05001375
Dees_Troy63c8df72012-09-10 14:02:05 -04001376 return true;
Dees_Troy51a0e822012-09-05 15:24:24 -04001377}
1378
1379void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001380 // Start with the default values
Dees_Troya13d74f2013-03-24 08:54:55 -05001381 string Restore_List;
Dees_Troy83bd4832013-05-04 12:39:56 +00001382 bool get_date = true, check_encryption = true;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001383 bool adbbackup = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001384
1385 DataManager::SetValue("tw_restore_encrypted", 0);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001386 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1387 vector<string> adb_files;
1388 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1389 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1390 string adb_restore_file = adb_files.at(i);
1391 std::size_t pos = adb_restore_file.find_first_of(".");
1392 std::string path = "/" + adb_restore_file.substr(0, pos);
1393 Restore_List = path + ";";
1394 TWPartition* Part = Find_Partition_By_Path(path);
1395 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1396 adbbackup = true;
1397 }
1398 DataManager::SetValue("tw_enable_adb_backup", 1);
Dees_Troy63c8df72012-09-10 14:02:05 -04001399 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001400 else {
1401 DIR* d;
1402 d = opendir(Restore_Name.c_str());
1403 if (d == NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001404 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001405 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1406 return;
Dees_Troy63c8df72012-09-10 14:02:05 -04001407 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001408
1409 struct dirent* de;
1410 while ((de = readdir(d)) != NULL)
Dees_Troy63c8df72012-09-10 14:02:05 -04001411 {
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001412 // Strip off three components
1413 char str[256];
1414 char* label;
1415 char* fstype = NULL;
1416 char* extn = NULL;
1417 char* ptr;
Dees_Troy63c8df72012-09-10 14:02:05 -04001418
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001419 strcpy(str, de->d_name);
1420 if (strlen(str) <= 2)
1421 continue;
Dees_Troy83bd4832013-05-04 12:39:56 +00001422
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001423 if (get_date) {
1424 char file_path[255];
1425 struct stat st;
1426
1427 strcpy(file_path, Restore_Name.c_str());
1428 strcat(file_path, "/");
1429 strcat(file_path, str);
1430 stat(file_path, &st);
1431 string backup_date = ctime((const time_t*)(&st.st_mtime));
1432 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1433 get_date = false;
Dees_Troy83bd4832013-05-04 12:39:56 +00001434 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001435
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001436 label = str;
1437 ptr = label;
1438 while (*ptr && *ptr != '.') ptr++;
1439 if (*ptr == '.')
1440 {
1441 *ptr = 0x00;
1442 ptr++;
1443 fstype = ptr;
1444 }
1445 while (*ptr && *ptr != '.') ptr++;
1446 if (*ptr == '.')
1447 {
1448 *ptr = 0x00;
1449 ptr++;
1450 extn = ptr;
1451 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001452
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001453 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1454 int extnlength = strlen(extn);
1455 if (extnlength != 3 && extnlength != 6) continue;
1456 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1457 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
Dees_Troy63c8df72012-09-10 14:02:05 -04001458
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001459 if (check_encryption) {
1460 string filename = Restore_Name + "/";
1461 filename += de->d_name;
1462 if (TWFunc::Get_File_Type(filename) == 2) {
1463 LOGINFO("'%s' is encrypted\n", filename.c_str());
1464 DataManager::SetValue("tw_restore_encrypted", 1);
1465 }
1466 }
1467 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1468
1469 TWPartition* Part = Find_Partition_By_Path(label);
1470 if (Part == NULL)
1471 {
1472 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1473 continue;
1474 }
1475
1476 Part->Backup_FileName = de->d_name;
1477 if (strlen(extn) > 3) {
1478 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1479 }
1480
dianlujitaob76a73a2020-04-30 20:33:20 +08001481 if (!Part->Is_SubPartition) {
1482 if (Part->Backup_Path == Get_Android_Root_Path())
1483 Restore_List += "/system;";
1484 else
1485 Restore_List += Part->Backup_Path + ";";
1486 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001487 }
1488 closedir(d);
Dees_Troy63c8df72012-09-10 14:02:05 -04001489 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001490
1491 if (adbbackup) {
1492 Restore_List = "ADB_Backup;";
1493 adbbackup = false;
1494 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001495
Dees_Troya13d74f2013-03-24 08:54:55 -05001496 // Set the final value
1497 DataManager::SetValue("tw_restore_list", Restore_List);
1498 DataManager::SetValue("tw_restore_selected", Restore_List);
Dees_Troy51a0e822012-09-05 15:24:24 -04001499 return;
1500}
1501
1502int TWPartitionManager::Wipe_By_Path(string Path) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001503 std::vector<TWPartition*>::iterator iter;
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301504 std::vector < TWPartition * >::iterator iter1;
Dees_Troy63c8df72012-09-10 14:02:05 -04001505 int ret = false;
1506 bool found = false;
Dees_Troy38bd7602012-09-14 13:33:53 -04001507 string Local_Path = TWFunc::Get_Root_Path(Path);
Dees_Troy63c8df72012-09-10 14:02:05 -04001508
dianlujitaob76a73a2020-04-30 20:33:20 +08001509 if (Local_Path == "/system")
1510 Local_Path = Get_Android_Root_Path();
bigbiffaed1bdf2021-08-03 18:21:39 -04001511 if (Path == "/cache") {
1512 TWPartition* cache = Find_Partition_By_Path("/cache");
1513 if (cache == nullptr) {
1514 TWPartition* dat = Find_Partition_By_Path("/data");
1515 if (dat) {
1516 dat->Wipe_Data_Cache();
1517 found = true;
1518 }
1519 }
1520 }
Dees_Troy63c8df72012-09-10 14:02:05 -04001521 // Iterate through all partitions
1522 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy657c3092012-09-10 20:32:10 -04001523 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
Mohd Farazfdd49bb2020-04-21 18:56:44 +05301524 // iterate through all partitions since some legacy devices uses other partitions as vendor causes issues while wiping
1525 (*iter)->Find_Actual_Block_Device();
1526 for (iter1 = Partitions.begin (); iter1 != Partitions.end (); iter1++)
1527 {
1528 (*iter1)->Find_Actual_Block_Device();
1529 if ((*iter)->Actual_Block_Device == (*iter1)->Actual_Block_Device && (*iter)->Mount_Point != (*iter1)->Mount_Point)
1530 (*iter1)->UnMount(false);
1531 }
Dees_Troye58d5262012-09-21 12:27:57 -04001532 if (Path == "/and-sec")
1533 ret = (*iter)->Wipe_AndSec();
1534 else
1535 ret = (*iter)->Wipe();
Dees_Troy63c8df72012-09-10 14:02:05 -04001536 found = true;
1537 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1538 (*iter)->Wipe();
1539 }
1540 }
1541 if (found) {
1542 return ret;
1543 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001544 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 -04001545 return false;
Dees_Troy51a0e822012-09-05 15:24:24 -04001546}
1547
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001548int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1549 std::vector<TWPartition*>::iterator iter;
1550 int ret = false;
1551 bool found = false;
1552 string Local_Path = TWFunc::Get_Root_Path(Path);
1553
1554 // Iterate through all partitions
1555 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1556 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1557 if (Path == "/and-sec")
1558 ret = (*iter)->Wipe_AndSec();
1559 else
1560 ret = (*iter)->Wipe(New_File_System);
1561 found = true;
1562 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1563 (*iter)->Wipe(New_File_System);
1564 }
1565 }
1566 if (found) {
1567 return ret;
1568 } else
Ethan Yonker74db1572015-10-28 12:44:49 -05001569 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 -05001570 return false;
1571}
1572
Dees_Troy51a0e822012-09-05 15:24:24 -04001573int TWPartitionManager::Factory_Reset(void) {
Dees_Troy63c8df72012-09-10 14:02:05 -04001574 std::vector<TWPartition*>::iterator iter;
1575 int ret = true;
1576
1577 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy38bd7602012-09-14 13:33:53 -04001578 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
Ethan Yonker89583ef2015-08-26 09:01:59 -05001579#ifdef TW_OEM_BUILD
1580 if ((*iter)->Mount_Point == "/data") {
1581 if (!(*iter)->Wipe_Encryption())
1582 ret = false;
1583 } else {
1584#endif
1585 if (!(*iter)->Wipe())
1586 ret = false;
1587#ifdef TW_OEM_BUILD
1588 }
1589#endif
Dees_Troy094207a2012-09-26 12:00:39 -04001590 } else if ((*iter)->Has_Android_Secure) {
1591 if (!(*iter)->Wipe_AndSec())
1592 ret = false;
Dees_Troy63c8df72012-09-10 14:02:05 -04001593 }
1594 }
bigbiffad58e1b2020-07-06 20:24:34 -04001595 TWFunc::check_and_run_script("/system/bin/factoryreset.sh", "Factory Reset Script");
Dees_Troy63c8df72012-09-10 14:02:05 -04001596 return ret;
Dees_Troy51a0e822012-09-05 15:24:24 -04001597}
1598
Dees_Troy38bd7602012-09-14 13:33:53 -04001599int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1600 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001601 vector <string> dir;
Dees_Troy38bd7602012-09-14 13:33:53 -04001602
1603 if (!Mount_By_Path("/data", true))
1604 return false;
1605
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001606 dir.push_back("/data/dalvik-cache");
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001607
bigbiff25d25b92020-06-19 16:07:38 -04001608 std::string cacheDir = TWFunc::get_log_dir();
1609 if (cacheDir == CACHE_LOGS_DIR) {
1610 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
1611 LOGINFO("Unable to mount %s for wiping cache.\n", CACHE_LOGS_DIR);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001612 }
1613 dir.push_back(cacheDir + "dalvik-cache");
1614 dir.push_back(cacheDir + "/dc");
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001615 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001616
Dees_Troy38bd7602012-09-14 13:33:53 -04001617 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001618 if (sdext && sdext->Is_Present && sdext->Mount(false))
1619 {
1620 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1621 {
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001622 dir.push_back("/sd-ext/dalvik-cache");
1623 }
1624 }
1625
bigbiff25d25b92020-06-19 16:07:38 -04001626 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001627 gui_msg("wiping_cache_dalvik=Wiping Dalvik Cache Directories...");
1628 } else {
1629 gui_msg("wiping_dalvik=Wiping Dalvik Directory...");
1630 }
Ethan Yonkerff2b7882016-12-10 09:04:41 -06001631 for (unsigned i = 0; i < dir.size(); ++i) {
1632 if (stat(dir.at(i).c_str(), &st) == 0) {
1633 TWFunc::removeDir(dir.at(i), false);
1634 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001635 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02001636 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001637
bigbiff25d25b92020-06-19 16:07:38 -04001638 if (cacheDir == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001639 gui_msg("cache_dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1640 } else {
1641 gui_msg("dalvik_done=-- Dalvik Directory Wipe Complete!");
1642 }
1643
Dees_Troy38bd7602012-09-14 13:33:53 -04001644 return true;
1645}
1646
1647int TWPartitionManager::Wipe_Rotate_Data(void) {
1648 if (!Mount_By_Path("/data", true))
1649 return false;
1650
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001651 unlink("/data/misc/akmd*");
1652 unlink("/data/misc/rild*");
Dees_Troy2673cec2013-04-02 20:22:16 +00001653 gui_print("Rotation data wiped.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001654 return true;
1655}
1656
1657int TWPartitionManager::Wipe_Battery_Stats(void) {
1658 struct stat st;
1659
1660 if (!Mount_By_Path("/data", true))
1661 return false;
1662
1663 if (0 != stat("/data/system/batterystats.bin", &st)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001664 gui_print("No Battery Stats Found. No Need To Wipe.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001665 } else {
1666 remove("/data/system/batterystats.bin");
Dees_Troy2673cec2013-04-02 20:22:16 +00001667 gui_print("Cleared battery stats.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001668 }
1669 return true;
1670}
1671
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001672int TWPartitionManager::Wipe_Android_Secure(void) {
1673 std::vector<TWPartition*>::iterator iter;
1674 int ret = false;
1675 bool found = false;
1676
1677 // Iterate through all partitions
1678 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1679 if ((*iter)->Has_Android_Secure) {
1680 ret = (*iter)->Wipe_AndSec();
1681 found = true;
1682 }
1683 }
1684 if (found) {
1685 return ret;
1686 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05001687 gui_err("no_andsec=No android secure partitions found.");
Dees_Troy2ff5a8d2012-09-26 14:53:02 -04001688 }
1689 return false;
1690}
1691
Dees_Troy38bd7602012-09-14 13:33:53 -04001692int TWPartitionManager::Format_Data(void) {
1693 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffcfa875c2021-06-20 16:20:27 -04001694 TWPartition* metadata = Find_Partition_By_Path("/metadata");
1695 if (metadata != NULL)
1696 metadata->UnMount(false);
Dees_Troy38bd7602012-09-14 13:33:53 -04001697
1698 if (dat != NULL) {
bigbiffab76bd72021-10-11 10:17:48 -04001699 if (android::base::GetBoolProperty("ro.virtual_ab.enabled", false)) {
bigbiffcfa875c2021-06-20 16:20:27 -04001700#ifndef TW_EXCLUDE_APEX
1701 twrpApex apex;
1702 apex.Unmount();
1703#endif
1704 if (metadata != NULL)
1705 metadata->Mount(true);
bigbiffd21252f2021-09-18 15:56:32 -04001706 if (!Check_Pending_Merges())
bigbiffcfa875c2021-06-20 16:20:27 -04001707 return false;
1708 }
Dees_Troy38bd7602012-09-14 13:33:53 -04001709 return dat->Wipe_Encryption();
1710 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001711 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001712 return false;
1713 }
1714 return false;
1715}
1716
1717int TWPartitionManager::Wipe_Media_From_Data(void) {
1718 TWPartition* dat = Find_Partition_By_Path("/data");
1719
1720 if (dat != NULL) {
1721 if (!dat->Has_Data_Media) {
Dees_Troy2673cec2013-04-02 20:22:16 +00001722 LOGERR("This device does not have /data/media\n");
Dees_Troy38bd7602012-09-14 13:33:53 -04001723 return false;
1724 }
1725 if (!dat->Mount(true))
1726 return false;
1727
Ethan Yonker74db1572015-10-28 12:44:49 -05001728 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
Ethan Yonker726a0202014-12-16 20:01:38 -06001729 Remove_MTP_Storage(dat->MTP_Storage_ID);
bigbiff bigbiff9c754052013-01-09 09:09:08 -05001730 TWFunc::removeDir("/data/media", false);
xiaolu9416f4f2015-06-04 08:22:23 +08001731 dat->Recreate_Media_Folder();
Ethan Yonker726a0202014-12-16 20:01:38 -06001732 Add_MTP_Storage(dat->MTP_Storage_ID);
Dees_Troy38bd7602012-09-14 13:33:53 -04001733 return true;
1734 } else {
Matt Mower3c366972015-12-25 19:28:31 -06001735 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
Dees_Troy38bd7602012-09-14 13:33:53 -04001736 return false;
1737 }
1738 return false;
1739}
1740
Ethan Yonker87c7bac2014-05-25 21:41:08 -05001741int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1742 std::vector<TWPartition*>::iterator iter;
1743 int ret = false;
1744 bool found = false;
1745 string Local_Path = TWFunc::Get_Root_Path(Path);
1746
1747 if (Local_Path == "/tmp" || Local_Path == "/")
1748 return true;
1749
1750 // Iterate through all partitions
1751 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1752 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1753 ret = (*iter)->Repair();
1754 found = true;
1755 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1756 (*iter)->Repair();
1757 }
1758 }
1759 if (found) {
1760 return ret;
1761 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001762 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 -05001763 } else {
1764 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1765 }
1766 return false;
1767}
1768
Ethan Yonkera2719152015-05-28 09:44:41 -05001769int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1770 std::vector<TWPartition*>::iterator iter;
1771 int ret = false;
1772 bool found = false;
1773 string Local_Path = TWFunc::Get_Root_Path(Path);
1774
1775 if (Local_Path == "/tmp" || Local_Path == "/")
1776 return true;
1777
1778 // Iterate through all partitions
1779 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1780 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1781 ret = (*iter)->Resize();
1782 found = true;
1783 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1784 (*iter)->Resize();
1785 }
1786 }
1787 if (found) {
1788 return ret;
1789 } else if (Display_Error) {
Ethan Yonker74db1572015-10-28 12:44:49 -05001790 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 -05001791 } else {
1792 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1793 }
1794 return false;
1795}
1796
Dees_Troy51a0e822012-09-05 15:24:24 -04001797void TWPartitionManager::Update_System_Details(void) {
Dees_Troy5bf43922012-09-07 16:07:55 -04001798 std::vector<TWPartition*>::iterator iter;
Dees_Troy51127312012-09-08 13:08:49 -04001799 int data_size = 0;
Dees_Troy5bf43922012-09-07 16:07:55 -04001800
Ethan Yonker74db1572015-10-28 12:44:49 -05001801 gui_msg("update_part_details=Updating partition details...");
Dees_Troy5bf43922012-09-07 16:07:55 -04001802 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker1b190162016-12-05 15:25:19 -06001803 (*iter)->Update_Size(true);
Dees_Troy51127312012-09-08 13:08:49 -04001804 if ((*iter)->Can_Be_Mounted) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001805 if ((*iter)->Mount_Point == Get_Android_Root_Path()) {
Dees_Troy51127312012-09-08 13:08:49 -04001806 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1807 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001808 TWFunc::Is_TWRP_App_In_System();
Dees_Troy51127312012-09-08 13:08:49 -04001809 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1810 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1811 } else if ((*iter)->Mount_Point == "/cache") {
1812 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1813 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1814 } else if ((*iter)->Mount_Point == "/sd-ext") {
1815 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1816 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1817 if ((*iter)->Backup_Size == 0) {
1818 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1819 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1820 } else
1821 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
Dees_Troye58d5262012-09-21 12:27:57 -04001822 } else if ((*iter)->Has_Android_Secure) {
Dees_Troy8170a922012-09-18 15:40:25 -04001823 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troye58d5262012-09-21 12:27:57 -04001824 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
Dees_Troy8170a922012-09-18 15:40:25 -04001825 if ((*iter)->Backup_Size == 0) {
1826 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1827 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1828 } else
1829 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
Dees_Troy2c50e182012-09-26 20:05:28 -04001830 } else if ((*iter)->Mount_Point == "/boot") {
1831 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1832 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1833 if ((*iter)->Backup_Size == 0) {
1834 DataManager::SetValue("tw_has_boot_partition", 0);
1835 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1836 } else
1837 DataManager::SetValue("tw_has_boot_partition", 1);
Dees_Troy51127312012-09-08 13:08:49 -04001838 }
Dees_Troyaa9cc402012-10-13 12:14:05 -04001839 } else {
1840 // Handle unmountable partitions in case we reset defaults
1841 if ((*iter)->Mount_Point == "/boot") {
1842 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1843 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1844 if ((*iter)->Backup_Size == 0) {
1845 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1846 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1847 } else
1848 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1849 } else if ((*iter)->Mount_Point == "/recovery") {
1850 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1851 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1852 if ((*iter)->Backup_Size == 0) {
1853 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1854 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1855 } else
1856 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
Gary Peck82599a82012-11-21 16:23:12 -08001857 } else if ((*iter)->Mount_Point == "/data") {
1858 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
Dees_Troyaa9cc402012-10-13 12:14:05 -04001859 }
Dees_Troy51127312012-09-08 13:08:49 -04001860 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001861 }
Ethan Yonker74db1572015-10-28 12:44:49 -05001862 gui_msg("update_part_details_done=...done");
Dees_Troy51127312012-09-08 13:08:49 -04001863 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1864 string current_storage_path = DataManager::GetCurrentStoragePath();
1865 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
Dees_Troy8170a922012-09-18 15:40:25 -04001866 if (FreeStorage != NULL) {
1867 // Attempt to mount storage
bigbiff25d25b92020-06-19 16:07:38 -04001868 if (!FreeStorage->Mount(false)) {
1869 gui_msg(Msg(msg::kWarning, "unable_to_mount_storage=Unable to mount storage"));
1870 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
1871 } else {
1872 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
Dees_Troy8170a922012-09-18 15:40:25 -04001873 }
1874 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00001875 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
Dees_Troy8170a922012-09-18 15:40:25 -04001876 }
Dees_Troy5bf43922012-09-07 16:07:55 -04001877 if (!Write_Fstab())
Dees_Troy2673cec2013-04-02 20:22:16 +00001878 LOGERR("Error creating fstab\n");
Dees_Troy51a0e822012-09-05 15:24:24 -04001879 return;
1880}
1881
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001882void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1883 TWPartition* dat = Find_Partition_By_Path("/data");
bigbiffc2cb3852020-09-11 14:03:31 -04001884
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001885 if (dat != NULL) {
bigbiffaed1bdf2021-08-03 18:21:39 -04001886 // reparse for /cache/recovery/command
1887 static constexpr const char* COMMAND_FILE = "/data/cache/command";
1888 if (TWFunc::Path_Exists(COMMAND_FILE)) {
1889 startupArgs startup;
1890 std::string content;
1891 TWFunc::read_file(COMMAND_FILE, content);
1892 std::vector<std::string> args = {content};
1893 startup.processRecoveryArgs(args, 0);
1894 }
1895
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001896 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1897 dat->Is_Decrypted = true;
1898 if (!Block_Device.empty()) {
1899 dat->Decrypted_Block_Device = Block_Device;
1900 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1901 } else {
1902 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1903 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001904 property_set("twrp.decrypt.done", "true");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001905 dat->Setup_File_System(false);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001906 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 -06001907
Noah Jacobson81d638d2019-04-28 00:10:07 -04001908 sleep(1); // Sleep for a bit so that the device will be ready
me-cafebabe09649612022-06-10 21:53:31 +08001909
1910 // Mount only /data
1911 dat->Symlink_Path = ""; // Not to let it to bind mount /data/media again
1912 if (!dat->Mount(false)) {
1913 LOGERR("Unable to mount /data after decryption");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001914 }
me-cafebabe09649612022-06-10 21:53:31 +08001915
1916 if (dat->Has_Data_Media && TWFunc::Path_Exists("/data/media/0")) {
1917 dat->Storage_Path = "/data/media/0";
1918 } else {
1919 dat->Storage_Path = "/data/media";
1920 }
1921 dat->Symlink_Path = dat->Storage_Path;
1922 DataManager::SetValue("tw_storage_path", dat->Symlink_Path);
Mohd Farazf9231102022-06-18 22:51:55 +02001923 DataManager::SetValue("tw_settings_path", TW_STORAGE_PATH);
me-cafebabe09649612022-06-10 21:53:31 +08001924 LOGINFO("New storage path after decryption: %s\n", dat->Storage_Path.c_str());
1925
epicXa721f952021-01-04 13:01:31 +05301926 DataManager::LoadTWRPFolderInfo();
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001927 Update_System_Details();
nkk71ffb02bd2017-06-04 23:12:16 +03001928 Output_Partition(dat);
bigbiff4fa02b52021-12-30 17:01:44 -05001929 if (!android::base::StartsWith(dat->Actual_Block_Device, "/dev/block/mmcblk")) {
1930 if (!dat->Bind_Mount(false))
1931 LOGERR("Unable to bind mount /sdcard to %s\n", dat->Storage_Path.c_str());
1932 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001933 } else
1934 LOGERR("Unable to locate data partition.\n");
1935}
1936
Noah Jacobson81d638d2019-04-28 00:10:07 -04001937void TWPartitionManager::Parse_Users() {
1938#ifdef TW_INCLUDE_FBE
1939 char user_check_result[PROPERTY_VALUE_MAX];
1940 for (int userId = 0; userId <= 9999; userId++) {
1941 string prop = "twrp.user." + to_string(userId) + ".decrypt";
1942 property_get(prop.c_str(), user_check_result, "-1");
1943 if (strcmp(user_check_result, "-1") != 0) {
1944 if (userId < 0 || userId > 9999) {
1945 LOGINFO("Incorrect user id %d\n", userId);
1946 continue;
1947 }
1948 struct users_struct user;
1949 user.userId = to_string(userId);
1950
1951 // Attempt to get name of user. Fallback to user ID if this fails.
Darth98f775972022-08-05 09:39:03 +01001952 std::string path = "/data/system/users/" + to_string(userId) + ".xml";
1953 if (!TWFunc::Check_Xml_Format(path)) {
1954 string oldpath = path;
1955 if (TWFunc::abx_to_xml(oldpath, path)) {
1956 LOGINFO("Android 12+: '%s' has been converted into plain text xml (for user %s).\n", oldpath.c_str(), user.userId.c_str());
1957 }
1958 }
1959 char* userFile = PageManager::LoadFileToBuffer(path, NULL);
me-cafebabec46981d2022-07-29 01:54:43 +08001960 if (userFile == NULL) {
1961 user.userName = to_string(userId);
bigbiffa957f072021-03-07 18:20:29 -05001962 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001963 else {
me-cafebabec46981d2022-07-29 01:54:43 +08001964 xml_document<> *userXml = new xml_document<>();
1965 userXml->parse<0>(userFile);
1966 xml_node<>* userNode = userXml->first_node("user");
1967 if (userNode == nullptr) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04001968 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08001969 } else {
1970 xml_node<>* nameNode = userNode->first_node("name");
1971 if (nameNode == nullptr)
Noah Jacobson81d638d2019-04-28 00:10:07 -04001972 user.userName = to_string(userId);
me-cafebabec46981d2022-07-29 01:54:43 +08001973 else {
1974 string userName = nameNode->value();
1975 user.userName = userName + " (" + to_string(userId) + ")";
Noah Jacobson81d638d2019-04-28 00:10:07 -04001976 }
1977 }
1978 }
1979
1980 string filename;
bigbiffdf53b6c2022-01-17 19:31:52 -05001981 user.type = android::keystore::Get_Password_Type(userId, filename);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001982
1983 user.isDecrypted = false;
1984 if (strcmp(user_check_result, "1") == 0)
1985 user.isDecrypted = true;
1986 Users_List.push_back(user);
1987 }
1988 }
1989 Check_Users_Decryption_Status();
1990#endif
1991}
1992
1993std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
1994 return &Users_List;
1995}
1996
1997void TWPartitionManager::Mark_User_Decrypted(int userID) {
1998#ifdef TW_INCLUDE_FBE
1999 std::vector<users_struct>::iterator iter;
2000 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2001 if (atoi((*iter).userId.c_str()) == userID) {
2002 (*iter).isDecrypted = true;
2003 string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
2004 property_set(user_prop_decrypted.c_str(), "1");
2005 break;
2006 }
2007 }
2008 Check_Users_Decryption_Status();
2009#endif
2010}
2011
2012void TWPartitionManager::Check_Users_Decryption_Status() {
2013#ifdef TW_INCLUDE_FBE
2014 int all_is_decrypted = 1;
2015 std::vector<users_struct>::iterator iter;
2016 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2017 if (!(*iter).isDecrypted) {
2018 LOGINFO("User %s is not decrypted.\n", (*iter).userId.c_str());
2019 all_is_decrypted = 0;
2020 break;
2021 }
2022 }
2023 if (all_is_decrypted == 1) {
2024 LOGINFO("All found users are decrypted.\n");
2025 DataManager::SetValue("tw_all_users_decrypted", "1");
2026 property_set("twrp.all.users.decrypted", "true");
2027 } else
2028 DataManager::SetValue("tw_all_users_decrypted", "0");
2029#endif
2030}
2031
2032int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
Dees_Troy5bf43922012-09-07 16:07:55 -04002033#ifdef TW_INCLUDE_CRYPTO
Captain Throwback37c3aef2021-10-06 11:38:18 -04002034 char crypto_blkdev[PROPERTY_VALUE_MAX];
Ethan Yonker253368a2014-11-25 15:00:52 -06002035 std::vector<TWPartition*>::iterator iter;
Dees_Troy5bf43922012-09-07 16:07:55 -04002036
Ethan Yonker253368a2014-11-25 15:00:52 -06002037 // Mount any partitions that need to be mounted for decrypt
2038 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2039 if ((*iter)->Mount_To_Decrypt) {
2040 (*iter)->Mount(true);
2041 }
a39552696ff55ce2013-01-08 16:14:56 +00002042 }
oshmouna82a7542018-04-10 17:45:55 +02002043 property_set("twrp.mount_to_decrypt", "1");
a39552696ff55ce2013-01-08 16:14:56 +00002044
Captain Throwback37c3aef2021-10-06 11:38:18 -04002045 Set_Crypto_State();
2046 Set_Crypto_Type("block");
Ethan Yonkera1de1492015-11-04 11:58:27 -06002047
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002048 if (DataManager::GetIntValue(TW_IS_FBE)) {
2049#ifdef TW_INCLUDE_FBE
2050 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
2051 return -1;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002052
2053 bool user_need_decrypt = false;
2054 std::vector<users_struct>::iterator iter;
2055 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2056 if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
2057 user_need_decrypt = true;
2058 }
2059 }
2060 if (!user_need_decrypt) {
2061 LOGINFO("User %d does not require decryption\n", user_id);
2062 return 0;
2063 }
2064
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002065 int retry_count = 10;
2066 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
Noah Jacobson81d638d2019-04-28 00:10:07 -04002067 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
2068 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002069 if (android::keystore::Decrypt_User(user_id, Password)) {
Noah Jacobson81d638d2019-04-28 00:10:07 -04002070 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
2071 Mark_User_Decrypted(user_id);
2072 if (user_id == 0) {
2073 // When decrypting user 0 also try all other users
2074 std::vector<users_struct>::iterator iter;
2075 for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
2076 if ((*iter).userId == "0" || (*iter).isDecrypted)
2077 continue;
2078
2079 int tmp_user_id = atoi((*iter).userId.c_str());
2080 gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
bigbiffdf53b6c2022-01-17 19:31:52 -05002081 if (android::keystore::Decrypt_User(tmp_user_id, Password) ||
2082 (Password != "!" && android::keystore::Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
Noah Jacobson81d638d2019-04-28 00:10:07 -04002083 gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
2084 Mark_User_Decrypted(tmp_user_id);
2085 } else {
2086 gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
2087 }
2088 }
2089 Post_Decrypt("");
2090 }
2091
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002092 return 0;
Noah Jacobson81d638d2019-04-28 00:10:07 -04002093 } else {
2094 gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002095 }
2096#else
2097 LOGERR("FBE support is not present\n");
2098#endif
2099 return -1;
2100 }
2101
Noah Jacobson81d638d2019-04-28 00:10:07 -04002102 char isdecrypteddata[PROPERTY_VALUE_MAX];
2103 property_get("twrp.decrypt.done", isdecrypteddata, "");
2104 if (strcmp(isdecrypteddata, "true") == 0) {
2105 LOGINFO("Data has no decryption required\n");
2106 return 0;
2107 }
2108
Ethan Yonkerddb63e22017-01-19 14:01:57 -06002109 int pwret = -1;
2110 pid_t pid = fork();
2111 if (pid < 0) {
2112 LOGERR("fork failed\n");
2113 return -1;
2114 } else if (pid == 0) {
2115 // Child process
2116 char cPassword[255];
2117 strcpy(cPassword, Password.c_str());
2118 int ret = cryptfs_check_passwd(cPassword);
2119 exit(ret);
2120 } else {
2121 // Parent
2122 int status;
2123 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
2124 pwret = -1;
2125 else
2126 pwret = WEXITSTATUS(status) ? -1 : 0;
2127 }
a39552696ff55ce2013-01-08 16:14:56 +00002128
Ethan Yonker253368a2014-11-25 15:00:52 -06002129 // Unmount any partitions that were needed for decrypt
2130 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2131 if ((*iter)->Mount_To_Decrypt) {
2132 (*iter)->UnMount(false);
2133 }
2134 }
oshmouna82a7542018-04-10 17:45:55 +02002135 property_set("twrp.mount_to_decrypt", "0");
Ethan Yonker253368a2014-11-25 15:00:52 -06002136
a39552696ff55ce2013-01-08 16:14:56 +00002137 if (pwret != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002138 gui_err("fail_decrypt=Failed to decrypt data.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002139 return -1;
2140 }
a39552696ff55ce2013-01-08 16:14:56 +00002141
Dees_Troy5bf43922012-09-07 16:07:55 -04002142 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
2143 if (strcmp(crypto_blkdev, "error") == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002144 LOGERR("Error retrieving decrypted data block device.\n");
Dees_Troy5bf43922012-09-07 16:07:55 -04002145 } else {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06002146 Post_Decrypt(crypto_blkdev);
Dees_Troy5bf43922012-09-07 16:07:55 -04002147 }
2148 return 0;
2149#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002150 gui_err("no_crypto_support=No crypto support was compiled into this build.");
Dees_Troy5bf43922012-09-07 16:07:55 -04002151 return -1;
2152#endif
Dees_Troy51a0e822012-09-05 15:24:24 -04002153 return 1;
Dees_Troy51127312012-09-08 13:08:49 -04002154}
2155
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002156int TWPartitionManager::Fix_Contexts(void) {
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002157 std::vector<TWPartition*>::iterator iter;
2158 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2159 if ((*iter)->Has_Data_Media) {
2160 if ((*iter)->Mount(true)) {
2161 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
2162 return -1;
2163 }
2164 }
2165 }
Dees_Troy1a650e62012-10-19 20:54:32 -04002166 UnMount_Main_Partitions();
Ethan Yonker74db1572015-10-28 12:44:49 -05002167 gui_msg("done=Done.");
Ethan Yonkerb5fab762016-01-28 14:03:33 -06002168 return 0;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002169}
2170
Ethan Yonker66a19492015-12-10 10:19:45 -06002171TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002172 std::vector<TWPartition*>::iterator iter = Partitions.begin();
2173
2174 if (!Path.empty()) {
2175 string Search_Path = TWFunc::Get_Root_Path(Path);
2176 for (; iter != Partitions.end(); iter++) {
Matt Mower9a561dd2016-02-22 21:25:51 -06002177 if ((*iter)->Mount_Point == Search_Path) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002178 iter++;
2179 break;
2180 }
2181 }
2182 }
2183
2184 for (; iter != Partitions.end(); iter++) {
Ethan Yonker66a19492015-12-10 10:19:45 -06002185 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
2186 // do nothing, do not return this type of partition
2187 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
Ethan Yonker47360be2014-04-01 10:34:34 -05002188 return (*iter);
2189 }
2190 }
2191
2192 return NULL;
2193}
2194
Dees_Troyd21618c2012-10-14 18:48:49 -04002195int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
Dees_Troyd21618c2012-10-14 18:48:49 -04002196 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
2197
2198 if (Part == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002199 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
2200 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 -04002201 return false;
2202 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002203 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
2204 if (!Part->UnMount(true) || !Part->Is_Present)
Dees_Troyd21618c2012-10-14 18:48:49 -04002205 return false;
2206
bigbiff22851b92021-09-01 16:46:57 -04002207 if (!TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002208 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
Dees_Troyd21618c2012-10-14 18:48:49 -04002209 return false;
2210 }
Dees_Troyd21618c2012-10-14 18:48:49 -04002211 return true;
2212}
2213
Dees_Troy8170a922012-09-18 15:40:25 -04002214int TWPartitionManager::usb_storage_enable(void) {
Dees_Troy8170a922012-09-18 15:40:25 -04002215 char lun_file[255];
Dees_Troyd21618c2012-10-14 18:48:49 -04002216 bool has_multiple_lun = false;
Dees_Troy8170a922012-09-18 15:40:25 -04002217
Ethan Yonker47360be2014-04-01 10:34:34 -05002218 string Lun_File_str = CUSTOM_LUN_FILE;
2219 size_t found = Lun_File_str.find("%");
2220 if (found != string::npos) {
2221 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
2222 if (TWFunc::Path_Exists(lun_file))
2223 has_multiple_lun = true;
2224 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002225 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
Ethan Yonker47360be2014-04-01 10:34:34 -05002226 if (!has_multiple_lun) {
2227 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
2228 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
2229 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
Ethan Yonker66a19492015-12-10 10:19:45 -06002230 TWPartition* Mount = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002231 if (Mount) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002232 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
2233 goto error_handle;
2234 }
Ethan Yonker47360be2014-04-01 10:34:34 -05002235 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002236 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002237 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002238 }
2239 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002240 goto error_handle;
Dees_Troy8170a922012-09-18 15:40:25 -04002241 }
Dees_Troy8170a922012-09-18 15:40:25 -04002242 } else {
Ethan Yonker47360be2014-04-01 10:34:34 -05002243 LOGINFO("Device has multiple lun files\n");
2244 TWPartition* Mount1;
2245 TWPartition* Mount2;
Dees_Troy8170a922012-09-18 15:40:25 -04002246 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
Ethan Yonker66a19492015-12-10 10:19:45 -06002247 Mount1 = Find_Next_Storage("", true);
Ethan Yonker47360be2014-04-01 10:34:34 -05002248 if (Mount1) {
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002249 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
2250 goto error_handle;
2251 }
Matt Moweree717062014-04-26 01:46:46 -05002252 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
Ethan Yonker66a19492015-12-10 10:19:45 -06002253 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
Matt Mower1fdcdb72016-01-25 20:53:47 -06002254 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
Matt Moweree717062014-04-26 01:46:46 -05002255 Open_Lun_File(Mount2->Mount_Point, lun_file);
nkk717aa6fc62017-03-24 18:28:03 +02002256 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2257 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data") {
2258 Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file);
Ethan Yonker47360be2014-04-01 10:34:34 -05002259 }
nkk717aa6fc62017-03-24 18:28:03 +02002260 // Mimic single lun code: Mount CurrentStoragePath if it's not /data
2261 } else if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) != "/data" && !Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002262 gui_err("unable_locate_storage=Unable to locate storage device.");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002263 goto error_handle;
Ethan Yonker47360be2014-04-01 10:34:34 -05002264 }
Dees_Troy8170a922012-09-18 15:40:25 -04002265 }
Matt Mowerb6ef4782014-11-06 02:24:36 -06002266 property_set("sys.storage.ums_enabled", "1");
HandyMenny37d42992014-10-26 22:15:59 +01002267 property_set("sys.usb.config", "mass_storage,adb");
Dees_Troy8170a922012-09-18 15:40:25 -04002268 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002269error_handle:
2270 if (mtp_was_enabled)
2271 if (!Enable_MTP())
2272 Disable_MTP();
2273 return false;
Dees_Troy8170a922012-09-18 15:40:25 -04002274}
2275
2276int TWPartitionManager::usb_storage_disable(void) {
bigbiff22851b92021-09-01 16:46:57 -04002277 int index, ret = 0;
Dees_Troy2673cec2013-04-02 20:22:16 +00002278 char lun_file[255], ch[2] = {0, 0};
2279 string str = ch;
Dees_Troy8170a922012-09-18 15:40:25 -04002280
2281 for (index=0; index<2; index++) {
2282 sprintf(lun_file, CUSTOM_LUN_FILE, index);
bigbiff22851b92021-09-01 16:46:57 -04002283 if (!TWFunc::write_to_file(lun_file, str)) {
Dees_Troy2673cec2013-04-02 20:22:16 +00002284 break;
bigbiff22851b92021-09-01 16:46:57 -04002285 ret = -1;
Dees_Troy8170a922012-09-18 15:40:25 -04002286 }
Dees_Troy8170a922012-09-18 15:40:25 -04002287 }
Dees_Troye58d5262012-09-21 12:27:57 -04002288 Mount_All_Storage();
2289 Update_System_Details();
Dees_Troycfd73ef2012-10-12 16:52:00 -04002290 UnMount_Main_Partitions();
Matt Mowerd9cb9062013-12-14 20:34:45 -06002291 property_set("sys.storage.ums_enabled", "0");
HandyMenny37d42992014-10-26 22:15:59 +01002292 property_set("sys.usb.config", "adb");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002293 if (mtp_was_enabled)
2294 if (!Enable_MTP())
2295 Disable_MTP();
Dees_Troy2673cec2013-04-02 20:22:16 +00002296 if (ret < 0 && index == 0) {
2297 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
2298 return false;
2299 } else {
2300 return true;
2301 }
Dees_Troy8170a922012-09-18 15:40:25 -04002302 return true;
Dees_Troy812660f2012-09-20 09:55:17 -04002303}
2304
2305void TWPartitionManager::Mount_All_Storage(void) {
2306 std::vector<TWPartition*>::iterator iter;
2307
2308 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2309 if ((*iter)->Is_Storage)
2310 (*iter)->Mount(false);
2311 }
Dees_Troy2c50e182012-09-26 20:05:28 -04002312}
Dees_Troy9350b8d2012-09-27 12:38:38 -04002313
Dees_Troyd0384ef2012-10-12 12:15:42 -04002314void TWPartitionManager::UnMount_Main_Partitions(void) {
2315 // Unmounts system and data if data is not data/media
2316 // Also unmounts boot if boot is mountable
Dees_Troy2673cec2013-04-02 20:22:16 +00002317 LOGINFO("Unmounting main partitions...\n");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002318
Mohd Faraze3948ec2020-08-14 01:40:59 +00002319 TWPartition *Partition = Find_Partition_By_Path ("/vendor");
Dees_Troyd0384ef2012-10-12 12:15:42 -04002320
Mohd Faraze3948ec2020-08-14 01:40:59 +00002321 if (Partition != NULL) UnMount_By_Path("/vendor", false);
2322 UnMount_By_Path (Get_Android_Root_Path(), true);
2323 Partition = Find_Partition_By_Path ("/product");
2324 if (Partition != NULL) UnMount_By_Path("/product", false);
Ethan Yonker6277c792014-09-15 14:54:30 -05002325 if (!datamedia)
2326 UnMount_By_Path("/data", true);
2327
Mohd Faraze3948ec2020-08-14 01:40:59 +00002328 Partition = Find_Partition_By_Path ("/boot");
2329 if (Partition != NULL && Partition->Can_Be_Mounted)
2330 Partition->UnMount(true);
Dees_Troyd0384ef2012-10-12 12:15:42 -04002331}
2332
Dees_Troy9350b8d2012-09-27 12:38:38 -04002333int TWPartitionManager::Partition_SDCard(void) {
Matt Mower23d8aae2017-01-06 14:30:33 -06002334 char temp[255];
Ethan Yonker483e9f42016-01-11 22:21:18 -06002335 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 -04002336 int ext, swap, total_size = 0, fat_size;
Dees_Troy9350b8d2012-09-27 12:38:38 -04002337
Ethan Yonker74db1572015-10-28 12:44:49 -05002338 gui_msg("start_partition_sd=Partitioning SD Card...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002339
2340 // Locate and validate device to partition
2341 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
2342
Ethan Yonker66a19492015-12-10 10:19:45 -06002343 if (SDCard->Is_Adopted_Storage)
2344 SDCard->Revert_Adopted();
2345
Ethan Yonker1eff6cd2014-09-15 13:30:42 -05002346 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002347 gui_err("partition_sd_locate=Unable to locate device to partition.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002348 return false;
2349 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002350
2351 // Unmount everything
Dees_Troy9350b8d2012-09-27 12:38:38 -04002352 if (!SDCard->UnMount(true))
2353 return false;
2354 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
2355 if (SDext != NULL) {
2356 if (!SDext->UnMount(true))
2357 return false;
2358 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002359 char* swappath = getenv("SWAPPATH");
2360 if (swappath != NULL) {
2361 LOGINFO("Unmounting swap at '%s'\n", swappath);
2362 umount(swappath);
2363 }
Vojtech Bocek05534202013-09-11 08:11:56 +02002364
Ethan Yonker483e9f42016-01-11 22:21:18 -06002365 // Determine block device
2366 if (SDCard->Alternate_Block_Device.empty()) {
2367 SDCard->Find_Actual_Block_Device();
2368 Device = SDCard->Actual_Block_Device;
2369 // Just use the root block device
2370 Device.resize(strlen("/dev/block/mmcblkX"));
2371 } else {
2372 Device = SDCard->Alternate_Block_Device;
2373 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002374
2375 // Find the size of the block device:
Ethan Yonker483e9f42016-01-11 22:21:18 -06002376 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002377
2378 DataManager::GetValue("tw_sdext_size", ext);
2379 DataManager::GetValue("tw_swap_size", swap);
2380 DataManager::GetValue("tw_sdpart_file_system", ext_format);
2381 fat_size = total_size - ext - swap;
Ethan Yonker483e9f42016-01-11 22:21:18 -06002382 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);
2383
2384 // Determine partition sizes
2385 if (swap == 0 && ext == 0) {
2386 fat_str = "-0";
2387 } else {
2388 memset(temp, 0, sizeof(temp));
2389 sprintf(temp, "%i", fat_size);
2390 fat_str = temp;
2391 fat_str += "MB";
2392 }
2393 if (swap == 0) {
2394 ext_str = "-0";
2395 } else {
2396 memset(temp, 0, sizeof(temp));
2397 sprintf(temp, "%i", ext);
2398 ext_str = "+";
2399 ext_str += temp;
2400 ext_str += "MB";
2401 }
2402
Dees_Troy9350b8d2012-09-27 12:38:38 -04002403 if (ext + swap > total_size) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002404 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002405 return false;
2406 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002407
Ethan Yonker74db1572015-10-28 12:44:49 -05002408 gui_msg("remove_part_table=Removing partition table...");
Ethan Yonker483e9f42016-01-11 22:21:18 -06002409 Command = "sgdisk --zap-all " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002410 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002411 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002412 gui_err("unable_rm_part=Unable to remove partition table.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002413 Update_System_Details();
2414 return false;
2415 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002416 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
Captain Throwback9643a802016-05-27 11:44:51 -04002417 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 +00002418 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002419 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002420 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002421 return false;
2422 }
2423 if (ext > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002424 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002425 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
Dees_Troy2673cec2013-04-02 20:22:16 +00002426 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002427 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002428 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002429 Update_System_Details();
2430 return false;
2431 }
2432 }
2433 if (swap > 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002434 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
Ethan Yonker483e9f42016-01-11 22:21:18 -06002435 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 +00002436 LOGINFO("Command is: '%s'\n", Command.c_str());
Vojtech Bocek05534202013-09-11 08:11:56 +02002437 if (TWFunc::Exec_Cmd(Command) != 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002438 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
Dees_Troy9350b8d2012-09-27 12:38:38 -04002439 Update_System_Details();
2440 return false;
2441 }
2442 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002443
2444 // Convert GPT to MBR
2445 Command = "sgdisk --gpttombr " + Device;
2446 if (TWFunc::Exec_Cmd(Command) != 0)
2447 LOGINFO("Failed to covert partition GPT to MBR\n");
2448
2449 // Tell the kernel to rescan the partition table
2450 int fd = open(Device.c_str(), O_RDONLY);
2451 ioctl(fd, BLKRRPART, 0);
2452 close(fd);
2453
2454 string format_device = Device;
2455 if (Device.substr(0, 17) == "/dev/block/mmcblk")
2456 format_device += "p";
2457
2458 // Format new partitions to proper file system
2459 if (fat_size > 0) {
2460 Command = "mkfs.fat " + format_device + "1";
2461 TWFunc::Exec_Cmd(Command);
2462 }
Dees_Troy9350b8d2012-09-27 12:38:38 -04002463 if (ext > 0) {
2464 if (SDext == NULL) {
Ethan Yonker483e9f42016-01-11 22:21:18 -06002465 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2466 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2467 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2468 TWFunc::Exec_Cmd(Command);
2469 } else {
2470 SDext->Wipe(ext_format);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002471 }
Ethan Yonker483e9f42016-01-11 22:21:18 -06002472 }
2473 if (swap > 0) {
2474 Command = "mkswap " + format_device;
2475 if (ext > 0)
2476 Command += "3";
2477 else
2478 Command += "2";
Vojtech Bocek05534202013-09-11 08:11:56 +02002479 TWFunc::Exec_Cmd(Command);
Dees_Troy9350b8d2012-09-27 12:38:38 -04002480 }
2481
Ethan Yonker483e9f42016-01-11 22:21:18 -06002482 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2483 if (SDCard->Mount(true)) {
2484 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2485 mkdir(TWRP_Folder.c_str(), 0777);
2486 DataManager::Flush();
2487 }
2488
Dees_Troy9350b8d2012-09-27 12:38:38 -04002489 Update_System_Details();
Ethan Yonker74db1572015-10-28 12:44:49 -05002490 gui_msg("part_complete=Partitioning complete.");
Dees_Troy9350b8d2012-09-27 12:38:38 -04002491 return true;
bigbiff bigbiffa0f8a592012-10-09 21:01:03 -04002492}
Dees_Troya13d74f2013-03-24 08:54:55 -05002493
2494void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2495 std::vector<TWPartition*>::iterator iter;
2496 if (ListType == "mount") {
2497 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002498 if ((*iter)->Can_Be_Mounted) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002499 struct PartitionList part;
2500 part.Display_Name = (*iter)->Display_Name;
2501 part.Mount_Point = (*iter)->Mount_Point;
2502 part.selected = (*iter)->Is_Mounted();
2503 Partition_List->push_back(part);
2504 }
2505 }
2506 } else if (ListType == "storage") {
2507 char free_space[255];
2508 string Current_Storage = DataManager::GetCurrentStoragePath();
2509 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2510 if ((*iter)->Is_Storage) {
2511 struct PartitionList part;
2512 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2513 part.Display_Name = (*iter)->Storage_Name + " (";
2514 part.Display_Name += free_space;
2515 part.Display_Name += "MB)";
2516 part.Mount_Point = (*iter)->Storage_Path;
2517 if ((*iter)->Storage_Path == Current_Storage)
2518 part.selected = 1;
2519 else
2520 part.selected = 0;
2521 Partition_List->push_back(part);
2522 }
2523 }
2524 } else if (ListType == "backup") {
2525 char backup_size[255];
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002526 unsigned long long Backup_Size;
Dees_Troya13d74f2013-03-24 08:54:55 -05002527 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002528 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002529 struct PartitionList part;
Dees_Troy9e0b71c2013-04-08 13:35:37 +00002530 Backup_Size = (*iter)->Backup_Size;
2531 if ((*iter)->Has_SubPartition) {
2532 std::vector<TWPartition*>::iterator subpart;
2533
2534 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2535 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2536 Backup_Size += (*subpart)->Backup_Size;
2537 }
2538 }
2539 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
Dees_Troya13d74f2013-03-24 08:54:55 -05002540 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2541 part.Display_Name += backup_size;
2542 part.Display_Name += "MB)";
2543 part.Mount_Point = (*iter)->Backup_Path;
2544 part.selected = 0;
2545 Partition_List->push_back(part);
2546 }
2547 }
2548 } else if (ListType == "restore") {
2549 string Restore_List, restore_path;
2550 TWPartition* restore_part = NULL;
2551
2552 DataManager::GetValue("tw_restore_list", Restore_List);
2553 if (!Restore_List.empty()) {
2554 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2555 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2556 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04002557 struct PartitionList part;
2558 if (restore_path.compare("ADB_Backup") == 0) {
2559 part.Display_Name = "ADB Backup";
2560 part.Mount_Point = "ADB Backup";
2561 part.selected = 1;
2562 Partition_List->push_back(part);
2563 break;
2564 }
Dees_Troy59df9262013-06-19 14:53:57 -05002565 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
Dees Troy4159aed2014-02-28 17:24:43 +00002566 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
Dees_Troya13d74f2013-03-24 08:54:55 -05002567 // Don't allow restore of recovery (causes problems on some devices)
Dees_Troy59df9262013-06-19 14:53:57 -05002568 // Don't add subpartitions to the list of items
Dees_Troya13d74f2013-03-24 08:54:55 -05002569 } else {
Dees_Troya13d74f2013-03-24 08:54:55 -05002570 part.Display_Name = restore_part->Backup_Display_Name;
2571 part.Mount_Point = restore_part->Backup_Path;
2572 part.selected = 1;
2573 Partition_List->push_back(part);
2574 }
2575 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002576 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
Dees_Troya13d74f2013-03-24 08:54:55 -05002577 }
2578 start_pos = end_pos + 1;
2579 end_pos = Restore_List.find(";", start_pos);
2580 }
2581 }
2582 } else if (ListType == "wipe") {
2583 struct PartitionList dalvik;
Ethan Yonker74db1572015-10-28 12:44:49 -05002584 dalvik.Display_Name = gui_parse_text("{@dalvik}");
Dees_Troya13d74f2013-03-24 08:54:55 -05002585 dalvik.Mount_Point = "DALVIK";
2586 dalvik.selected = 0;
2587 Partition_List->push_back(dalvik);
2588 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2589 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2590 struct PartitionList part;
2591 part.Display_Name = (*iter)->Display_Name;
2592 part.Mount_Point = (*iter)->Mount_Point;
2593 part.selected = 0;
2594 Partition_List->push_back(part);
2595 }
2596 if ((*iter)->Has_Android_Secure) {
2597 struct PartitionList part;
2598 part.Display_Name = (*iter)->Backup_Display_Name;
2599 part.Mount_Point = (*iter)->Backup_Path;
2600 part.selected = 0;
2601 Partition_List->push_back(part);
2602 }
Dees_Troy74fb2e92013-04-15 14:35:47 +00002603 if ((*iter)->Has_Data_Media) {
2604 struct PartitionList datamedia;
2605 datamedia.Display_Name = (*iter)->Storage_Name;
2606 datamedia.Mount_Point = "INTERNAL";
2607 datamedia.selected = 0;
2608 Partition_List->push_back(datamedia);
2609 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002610 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002611 } else if (ListType == "flashimg") {
2612 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2613 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2614 struct PartitionList part;
2615 part.Display_Name = (*iter)->Backup_Display_Name;
2616 part.Mount_Point = (*iter)->Backup_Path;
2617 part.selected = 0;
2618 Partition_List->push_back(part);
2619 }
2620 }
Ethan Yonker53796e72019-01-11 22:49:52 -06002621 if (DataManager::GetIntValue("tw_has_repack_tools") != 0 && DataManager::GetIntValue("tw_has_boot_slots") != 0) {
2622 TWPartition* boot = Find_Partition_By_Path("/boot");
2623 if (boot) {
2624 // Allow flashing kernels and ramdisks
2625 struct PartitionList repack_ramdisk;
2626 repack_ramdisk.Display_Name = gui_lookup("install_twrp_ramdisk", "Install Recovery Ramdisk");
2627 repack_ramdisk.Mount_Point = "/repack_ramdisk";
2628 repack_ramdisk.selected = 0;
2629 Partition_List->push_back(repack_ramdisk);
2630 /*struct PartitionList repack_kernel; For now let's leave repacking kernels under advanced only
2631 repack_kernel.Display_Name = gui_lookup("install_kernel", "Install Kernel");
2632 repack_kernel.Mount_Point = "/repack_kernel";
2633 repack_kernel.selected = 0;
2634 Partition_List->push_back(repack_kernel);*/
2635 }
2636 }
Dees_Troya13d74f2013-03-24 08:54:55 -05002637 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +00002638 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
Dees_Troya13d74f2013-03-24 08:54:55 -05002639 }
2640}
2641
2642int TWPartitionManager::Fstab_Processed(void) {
2643 return Partitions.size();
2644}
Dees_Troyd93bda52013-07-03 19:55:19 +00002645
2646void TWPartitionManager::Output_Storage_Fstab(void) {
2647 std::vector<TWPartition*>::iterator iter;
2648 char storage_partition[255];
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002649 std::string Temp;
bigbiff25d25b92020-06-19 16:07:38 -04002650 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04002651
2652 if (cacheDir.empty()) {
2653 LOGINFO("Unable to find cache directory\n");
2654 return;
2655 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002656
bigbiff25d25b92020-06-19 16:07:38 -04002657 std::string storageFstab = TWFunc::get_log_dir() + "recovery/storage.fstab";
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002658 FILE *fp = fopen(storageFstab.c_str(), "w");
Dees_Troyd93bda52013-07-03 19:55:19 +00002659
2660 if (fp == NULL) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05002661 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")(storageFstab));
Dees_Troyd93bda52013-07-03 19:55:19 +00002662 return;
2663 }
2664
2665 // Iterate through all partitions
2666 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2667 if ((*iter)->Is_Storage) {
2668 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2669 strcpy(storage_partition, Temp.c_str());
2670 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2671 }
2672 }
2673 fclose(fp);
Vojtech Bocekfafb0c52013-07-25 22:53:02 +02002674}
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002675
2676TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2677{
2678 TWPartition *res = NULL;
2679 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
Matt Mowera8a89d12016-12-30 18:10:37 -06002680 if (!(*iter)->Is_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002681 continue;
2682
Matt Mowera8a89d12016-12-30 18:10:37 -06002683 if ((*iter)->Is_Settings_Storage)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002684 return *iter;
2685
Matt Mowera8a89d12016-12-30 18:10:37 -06002686 if (!res)
Vojtech Bocek93cb1ef2014-05-12 15:41:52 +02002687 res = *iter;
2688 }
2689 return res;
2690}
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002691
2692bool TWPartitionManager::Enable_MTP(void) {
2693#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002694 if (mtppid) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002695 gui_err("mtp_already_enabled=MTP already enabled");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002696 return true;
2697 }
Ethan Yonker726a0202014-12-16 20:01:38 -06002698
2699 int mtppipe[2];
2700
2701 if (pipe(mtppipe) < 0) {
2702 LOGERR("Error creating MTP pipe\n");
2703 return false;
2704 }
2705
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002706 char old_value[PROPERTY_VALUE_MAX];
Matt Mowere07f0102017-02-23 17:40:00 -06002707 property_get("sys.usb.config", old_value, "");
2708 if (strcmp(old_value, "mtp,adb") != 0) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002709 char vendor[PROPERTY_VALUE_MAX];
2710 char product[PROPERTY_VALUE_MAX];
2711 property_set("sys.usb.config", "none");
2712 property_get("usb.vendor", vendor, "18D1");
2713 property_get("usb.product.mtpadb", product, "4EE2");
2714 string vendorstr = vendor;
2715 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002716 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2717 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002718 property_set("sys.usb.config", "mtp,adb");
2719 }
Matt Mower653a1702017-02-16 10:38:52 -06002720 /* To enable MTP debug, use the twrp command line feature:
Ethan Yonker6d154c42014-09-03 14:19:43 -05002721 * twrp set tw_mtp_debug 1
2722 */
2723 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
Ethan Yonker1b039202015-01-30 10:08:48 -06002724 mtppid = mtp->forkserver(mtppipe);
2725 if (mtppid) {
2726 close(mtppipe[0]); // Host closes read side
2727 mtp_write_fd = mtppipe[1];
2728 DataManager::SetValue("tw_mtp_enabled", 1);
2729 Add_All_MTP_Storage();
2730 return true;
Ethan Yonker726a0202014-12-16 20:01:38 -06002731 } else {
2732 close(mtppipe[0]);
2733 close(mtppipe[1]);
Ethan Yonker74db1572015-10-28 12:44:49 -05002734 gui_err("mtp_fail=Failed to enable MTP");
Ethan Yonker1b039202015-01-30 10:08:48 -06002735 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002736 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002737#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002738 gui_err("no_mtp=MTP support not included");
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002739#endif
2740 DataManager::SetValue("tw_mtp_enabled", 0);
2741 return false;
2742}
2743
Ethan Yonker1b039202015-01-30 10:08:48 -06002744void TWPartitionManager::Add_All_MTP_Storage(void) {
2745#ifdef TW_HAS_MTP
2746 std::vector<TWPartition*>::iterator iter;
2747
2748 if (!mtppid)
2749 return; // MTP is not enabled
2750
2751 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2752 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2753 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2754 }
2755#else
2756 return;
2757#endif
2758}
2759
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002760bool TWPartitionManager::Disable_MTP(void) {
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002761 char old_value[PROPERTY_VALUE_MAX];
bigbiff bigbiffaf32bb92018-12-18 18:39:53 -05002762 property_set("sys.usb.ffs.mtp.ready", "0");
Matt Mowere07f0102017-02-23 17:40:00 -06002763 property_get("sys.usb.config", old_value, "");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002764 if (strcmp(old_value, "adb") != 0) {
2765 char vendor[PROPERTY_VALUE_MAX];
2766 char product[PROPERTY_VALUE_MAX];
2767 property_set("sys.usb.config", "none");
2768 property_get("usb.vendor", vendor, "18D1");
Matt Mowere07f0102017-02-23 17:40:00 -06002769 property_get("usb.product.adb", product, "D001");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002770 string vendorstr = vendor;
2771 string productstr = product;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002772 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2773 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002774 usleep(2000);
2775 }
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002776#ifdef TW_HAS_MTP
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002777 if (mtppid) {
Ethan Yonker8613dc02014-09-11 09:28:20 -05002778 LOGINFO("Disabling MTP\n");
2779 int status;
2780 kill(mtppid, SIGKILL);
Ethan Yonker8dfa7772014-09-04 21:48:41 -05002781 mtppid = 0;
Ethan Yonker8613dc02014-09-11 09:28:20 -05002782 // We don't care about the exit value, but this prevents a zombie process
2783 waitpid(mtppid, &status, 0);
Ethan Yonker726a0202014-12-16 20:01:38 -06002784 close(mtp_write_fd);
2785 mtp_write_fd = -1;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002786 }
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002787#endif
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002788 property_set("sys.usb.config", "adb");
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002789#ifdef TW_HAS_MTP
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002790 DataManager::SetValue("tw_mtp_enabled", 0);
2791 return true;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002792#endif
Ethan Yonkerdf7abac2014-12-29 10:48:17 -06002793 return false;
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04002794}
Ethan Yonker726a0202014-12-16 20:01:38 -06002795
2796TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2797 std::vector<TWPartition*>::iterator iter;
2798
2799 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2800 if ((*iter)->MTP_Storage_ID == Storage_ID)
2801 return (*iter);
2802 }
2803 return NULL;
2804}
2805
2806bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2807#ifdef TW_HAS_MTP
2808 struct mtpmsg mtp_message;
2809
2810 if (!mtppid)
2811 return false; // MTP is disabled
2812
2813 if (mtp_write_fd < 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002814 LOGINFO("MTP: mtp_write_fd is not set\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002815 return false;
2816 }
2817
2818 if (Part) {
Ethan Yonker4bfabab2014-12-29 09:15:37 -06002819 if (Part->MTP_Storage_ID == 0)
2820 return false;
Ethan Yonker726a0202014-12-16 20:01:38 -06002821 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2822 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2823 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2824 mtp_message.storage_id = Part->MTP_Storage_ID;
2825 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002826 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002827 return false;
2828 } else {
2829 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2830 return true;
2831 }
2832 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2833 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2834 mtp_message.storage_id = Part->MTP_Storage_ID;
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002835 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2836 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2837 return false;
2838 }
2839 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2840 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2841 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2842 return false;
2843 }
2844 strcpy(mtp_message.display, Part->Storage_Name.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002845 mtp_message.maxFileSize = Part->Get_Max_FileSize();
Ethan Yonker1b039202015-01-30 10:08:48 -06002846 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 -06002847 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002848 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002849 return false;
2850 } else {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06002851 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
Ethan Yonker726a0202014-12-16 20:01:38 -06002852 return true;
2853 }
2854 } else {
2855 LOGERR("Unknown MTP message type: %i\n", message_type);
2856 }
2857 } else {
2858 // This hopefully never happens as the error handling should
2859 // occur in the calling function.
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002860 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
Ethan Yonker726a0202014-12-16 20:01:38 -06002861 }
2862 return true;
2863#else
Ethan Yonker74db1572015-10-28 12:44:49 -05002864 gui_err("no_mtp=MTP support not included");
Ethan Yonker726a0202014-12-16 20:01:38 -06002865 DataManager::SetValue("tw_mtp_enabled", 0);
2866 return false;
2867#endif
2868}
2869
2870bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2871#ifdef TW_HAS_MTP
2872 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2873 if (Part) {
2874 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2875 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002876 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002877 }
2878#endif
2879 return false;
2880}
2881
2882bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2883#ifdef TW_HAS_MTP
2884 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2885 if (Part) {
2886 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2887 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002888 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002889 }
2890#endif
2891 return false;
2892}
2893
2894bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2895#ifdef TW_HAS_MTP
2896 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2897 if (Part) {
2898 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2899 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002900 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
Ethan Yonker726a0202014-12-16 20:01:38 -06002901 }
2902#endif
2903 return false;
2904}
2905
2906bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2907#ifdef TW_HAS_MTP
2908 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2909 if (Part) {
2910 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2911 } else {
Ethan Yonkerd9ff3c52015-01-21 21:51:20 -06002912 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
Ethan Yonker726a0202014-12-16 20:01:38 -06002913 }
2914#endif
2915 return false;
2916}
Ethan Yonker96af84a2015-01-05 14:58:36 -06002917
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002918bool TWPartitionManager::Flash_Image(string& path, string& filename) {
bigbiffad58e1b2020-07-06 20:24:34 -04002919 twrpRepacker repacker;
Matt Mower23d8aae2017-01-06 14:30:33 -06002920 int partition_count = 0;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002921 TWPartition* flash_part = NULL;
bigbiffce8f83c2015-12-12 18:30:21 -05002922 string Flash_List, flash_path, full_filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002923 size_t start_pos = 0, end_pos = 0;
2924
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002925 full_filename = path + "/" + filename;
Ethan Yonker96af84a2015-01-05 14:58:36 -06002926
bigbiffce8f83c2015-12-12 18:30:21 -05002927 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
2928 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
2929
2930 if (!TWFunc::Path_Exists(full_filename)) {
2931 if (!Mount_By_Path(full_filename, true)) {
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002932 return false;
2933 }
bigbiffce8f83c2015-12-12 18:30:21 -05002934 if (!TWFunc::Path_Exists(full_filename)) {
2935 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
Ethan Yonkerb78fbdf2016-01-15 16:46:35 -06002936 return false;
2937 }
2938 }
Ethan Yonker96af84a2015-01-05 14:58:36 -06002939
Ethan Yonker53796e72019-01-11 22:49:52 -06002940 DataManager::GetValue("tw_flash_partition", Flash_List);
2941 Repack_Type repack = REPLACE_NONE;
2942 if (Flash_List == "/repack_ramdisk;") {
2943 repack = REPLACE_RAMDISK;
2944 } else if (Flash_List == "/repack_kernel;") {
2945 repack = REPLACE_KERNEL;
2946 }
2947 if (repack != REPLACE_NONE) {
2948 Repack_Options_struct Repack_Options;
2949 Repack_Options.Type = repack;
2950 Repack_Options.Disable_Verity = false;
2951 Repack_Options.Disable_Force_Encrypt = false;
2952 Repack_Options.Backup_First = DataManager::GetIntValue("tw_repack_backup_first") != 0;
bigbiffad58e1b2020-07-06 20:24:34 -04002953 return repacker.Repack_Image_And_Flash(full_filename, Repack_Options);
Ethan Yonker53796e72019-01-11 22:49:52 -06002954 }
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002955 PartitionSettings part_settings;
2956 part_settings.Backup_Folder = path;
2957 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
2958 ProgressTracking progress(total_bytes);
2959 part_settings.progress = &progress;
2960 part_settings.adbbackup = false;
2961 part_settings.PM_Method = PM_RESTORE;
Ethan Yonker74db1572015-10-28 12:44:49 -05002962 gui_msg("calc_restore=Calculating restore details...");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002963 if (!Flash_List.empty()) {
2964 end_pos = Flash_List.find(";", start_pos);
2965 while (end_pos != string::npos && start_pos < Flash_List.size()) {
2966 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
2967 flash_part = Find_Partition_By_Path(flash_path);
2968 if (flash_part != NULL) {
2969 partition_count++;
2970 if (partition_count > 1) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002971 gui_err("too_many_flash=Too many partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002972 return false;
2973 }
2974 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002975 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
Ethan Yonker96af84a2015-01-05 14:58:36 -06002976 return false;
2977 }
2978 start_pos = end_pos + 1;
2979 end_pos = Flash_List.find(";", start_pos);
2980 }
2981 }
2982
2983 if (partition_count == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -05002984 gui_err("no_part_flash=No partitions selected for flashing.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002985 return false;
2986 }
2987
2988 DataManager::SetProgress(0.0);
2989 if (flash_part) {
Ethan Yonkere080c1f2016-09-19 13:50:25 -05002990 flash_part->Backup_FileName = filename;
2991 if (!flash_part->Flash_Image(&part_settings))
Ethan Yonker96af84a2015-01-05 14:58:36 -06002992 return false;
2993 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -05002994 gui_err("invalid_flash=Invalid flash partition specified.");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002995 return false;
2996 }
Ethan Yonker74db1572015-10-28 12:44:49 -05002997 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
Ethan Yonker96af84a2015-01-05 14:58:36 -06002998 return true;
2999}
Ethan Yonker74db1572015-10-28 12:44:49 -05003000
3001void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
3002 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3003 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003004 if (part->Is_Adopted_Storage) {
3005 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3006 part->Backup_Display_Name = part->Display_Name;
3007 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3008 } else {
3009 part->Display_Name = gui_lookup(resource_name, default_value);
3010 part->Backup_Display_Name = part->Display_Name;
3011 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003012 }
3013}
3014
3015void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
3016 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3017 if (part) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003018 if (part->Is_Adopted_Storage) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003019 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
Ethan Yonker66a19492015-12-10 10:19:45 -06003020 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
Ethan Yonker66a19492015-12-10 10:19:45 -06003021 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3022 } else {
3023 part->Display_Name = gui_lookup(resource_name, default_value);
3024 part->Backup_Display_Name = part->Display_Name;
3025 if (part->Is_Storage)
3026 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3027 }
Ethan Yonker74db1572015-10-28 12:44:49 -05003028 }
3029}
3030
Ethan Yonker01f4e032017-02-03 15:30:52 -06003031void 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) {
3032 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
3033 if (part) {
3034 if (part->Is_Adopted_Storage) {
3035 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
3036 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
3037 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
3038 } else {
3039 part->Display_Name = gui_lookup(resource_name, default_value);
3040 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
3041 if (part->Is_Storage)
3042 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
3043 }
3044 }
3045}
3046
Ethan Yonker74db1572015-10-28 12:44:49 -05003047void TWPartitionManager::Translate_Partition_Display_Names() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003048 LOGINFO("Translating partition display names\n");
Ethan Yonker74db1572015-10-28 12:44:49 -05003049 Translate_Partition("/system", "system", "System");
3050 Translate_Partition("/system_image", "system_image", "System Image");
3051 Translate_Partition("/vendor", "vendor", "Vendor");
3052 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
3053 Translate_Partition("/cache", "cache", "Cache");
Ethan Yonker74db1572015-10-28 12:44:49 -05003054 Translate_Partition("/boot", "boot", "Boot");
3055 Translate_Partition("/recovery", "recovery", "Recovery");
3056 if (!datamedia) {
Ethan Yonker01f4e032017-02-03 15:30:52 -06003057 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
Ethan Yonker74db1572015-10-28 12:44:49 -05003058 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3059 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
3060 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
3061 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
Ethan Yonker01f4e032017-02-03 15:30:52 -06003062 } else {
3063 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003064 }
Ethan Yonker01f4e032017-02-03 15:30:52 -06003065 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
3066 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
Ethan Yonker74db1572015-10-28 12:44:49 -05003067 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
3068 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
3069
3070 // Android secure is a special case
3071 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
3072 if (part)
3073 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
3074
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003075 std::vector<TWPartition*>::iterator sysfs;
3076 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
3077 if (!(*sysfs)->Sysfs_Entry.empty()) {
3078 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
3079 }
3080 }
3081
Ethan Yonker74db1572015-10-28 12:44:49 -05003082 // This updates the text on all of the storage selection buttons in the GUI
3083 DataManager::SetBackupFolder();
3084}
Ethan Yonker66a19492015-12-10 10:19:45 -06003085
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003086bool TWPartitionManager::Decrypt_Adopted() {
Ethan Yonker66a19492015-12-10 10:19:45 -06003087#ifdef TW_INCLUDE_CRYPTO
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003088 bool ret = false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003089 if (!Mount_By_Path("/data", false)) {
3090 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003091 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003092 }
Darth98f775972022-08-05 09:39:03 +01003093
3094 std::string path = "/data/system/storage.xml";
3095 if (!TWFunc::Check_Xml_Format(path)) {
3096 std::string oldpath = path;
3097 if (TWFunc::abx_to_xml(oldpath, path)) {
3098 LOGINFO("Android 12+: '%s' has been converted into plain text xml (%s).\n", oldpath.c_str(), path.c_str());
3099 }
3100 }
3101
Ethan Yonker66a19492015-12-10 10:19:45 -06003102 LOGINFO("Decrypt adopted storage starting\n");
Darth98f775972022-08-05 09:39:03 +01003103 char* xmlFile = PageManager::LoadFileToBuffer(path, NULL);
Ethan Yonker66a19492015-12-10 10:19:45 -06003104 xml_document<> *doc = NULL;
3105 xml_node<>* volumes = NULL;
Ethan Yonker66a19492015-12-10 10:19:45 -06003106 string Primary_Storage_UUID = "";
3107 if (xmlFile != NULL) {
3108 LOGINFO("successfully loaded storage.xml\n");
3109 doc = new xml_document<>();
3110 doc->parse<0>(xmlFile);
3111 volumes = doc->first_node("volumes");
3112 if (volumes) {
3113 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
3114 if (psuuid) {
3115 Primary_Storage_UUID = psuuid->value();
3116 }
3117 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003118 } else {
3119 LOGINFO("No /data/system/storage.xml for adopted storage\n");
3120 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003121 }
3122 std::vector<TWPartition*>::iterator adopt;
3123 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
Peter Cai439d60c2019-10-17 08:49:10 +08003124 if ((*adopt)->Removable && !(*adopt)->Is_Present && (*adopt)->Adopted_Mount_Delay > 0) {
3125 // On some devices, the external mmc driver takes some time
3126 // to recognize the card, in which case the "actual block device"
3127 // would not have been found yet. We wait the specified delay
3128 // and then try again.
3129 LOGINFO("Sleeping %d seconds for adopted storage.\n", (*adopt)->Adopted_Mount_Delay);
3130 sleep((*adopt)->Adopted_Mount_Delay);
3131 (*adopt)->Find_Actual_Block_Device();
3132 }
3133
Ethan Yonker66a19492015-12-10 10:19:45 -06003134 if ((*adopt)->Removable && (*adopt)->Is_Present) {
3135 if ((*adopt)->Decrypt_Adopted() == 0) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003136 ret = true;
Ethan Yonker66a19492015-12-10 10:19:45 -06003137 if (volumes) {
3138 xml_node<>* volume = volumes->first_node("volume");
3139 while (volume) {
3140 xml_attribute<>* guid = volume->first_attribute("partGuid");
3141 if (guid) {
3142 string GUID = (*adopt)->Adopted_GUID.c_str();
3143 GUID.insert(8, "-");
3144 GUID.insert(13, "-");
3145 GUID.insert(18, "-");
3146 GUID.insert(23, "-");
3147
3148 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
3149 xml_attribute<>* attr = volume->first_attribute("nickname");
nkk71ffb02bd2017-06-04 23:12:16 +03003150 if (attr && attr->value() && strlen(attr->value()) > 0) {
Ethan Yonker66a19492015-12-10 10:19:45 -06003151 (*adopt)->Storage_Name = attr->value();
3152 (*adopt)->Display_Name = (*adopt)->Storage_Name;
3153 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
3154 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
3155 }
3156 attr = volume->first_attribute("fsUuid");
3157 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
3158 TWPartition* Dat = Find_Partition_By_Path("/data");
3159 if (Dat) {
3160 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
3161 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
3162 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
3163 Dat->Symlink_Mount_Point = "";
3164 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
3165 Dat->UnMount(false);
3166 Dat->Mount(false);
3167 (*adopt)->UnMount(false);
3168 (*adopt)->Mount(false);
Ethan Yonker66a19492015-12-10 10:19:45 -06003169 }
3170 }
3171 break;
3172 }
3173 }
3174 volume = volume->next_sibling("volume");
3175 }
3176 }
nkk71ffb02bd2017-06-04 23:12:16 +03003177 Update_System_Details();
3178 Output_Partition((*adopt));
Ethan Yonker66a19492015-12-10 10:19:45 -06003179 }
3180 }
3181 }
3182 if (xmlFile) {
3183 doc->clear();
3184 delete doc;
3185 free(xmlFile);
3186 }
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003187 return ret;
Ethan Yonker66a19492015-12-10 10:19:45 -06003188#else
3189 LOGINFO("Decrypt_Adopted: no crypto support\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003190 return false;
Ethan Yonker66a19492015-12-10 10:19:45 -06003191#endif
3192}
Ethan Yonkerfcf3f242016-02-16 12:30:26 -06003193
3194void TWPartitionManager::Remove_Partition_By_Path(string Path) {
3195 std::vector<TWPartition*>::iterator iter;
3196 string Local_Path = TWFunc::Get_Root_Path(Path);
3197
3198 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3199 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
3200 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
3201 Partitions.erase(iter);
3202 return;
3203 }
3204 }
3205}
Ethan Yonker1b190162016-12-05 15:25:19 -06003206
bigbiff74a46272021-07-31 19:02:26 -04003207void TWPartitionManager::Override_Active_Slot(const string& Slot) {
3208 LOGINFO("Overriding slot to '%s'\n", Slot.c_str());
3209 Active_Slot_Display = Slot;
3210 DataManager::SetValue("tw_active_slot", Slot);
nebrassy07c4b902021-11-21 03:32:47 +01003211 PartitionManager.Update_System_Details();
bigbiff74a46272021-07-31 19:02:26 -04003212}
3213
Ethan Yonker1b190162016-12-05 15:25:19 -06003214void TWPartitionManager::Set_Active_Slot(const string& Slot) {
3215 if (Slot != "A" && Slot != "B") {
3216 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
3217 return;
3218 }
3219 if (Active_Slot_Display == Slot)
3220 return;
3221 LOGINFO("Setting active slot %s\n", Slot.c_str());
3222#ifdef AB_OTA_UPDATER
3223 if (!Active_Slot_Display.empty()) {
dianlujitaoa90dc462021-12-16 16:56:26 +08003224 android::sp<IBootControl> module = IBootControl::getService();
3225 if (module == nullptr) {
Ethan Yonker1b190162016-12-05 15:25:19 -06003226 LOGERR("Error getting bootctrl module.\n");
3227 } else {
dianlujitaoa90dc462021-12-16 16:56:26 +08003228 uint32_t slot_number = 0;
Ethan Yonker1b190162016-12-05 15:25:19 -06003229 if (Slot == "B")
3230 slot_number = 1;
dianlujitaoa90dc462021-12-16 16:56:26 +08003231 CommandResult result;
3232 auto ret = module->setActiveBootSlot(slot_number, [&result]
3233 (const CommandResult &cb_result) { result = cb_result; });
3234 if (!ret.isOk() || !result.success)
Ethan Yonker1b190162016-12-05 15:25:19 -06003235 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
3236 }
3237 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
3238 }
3239#else
3240 LOGERR("Boot slot feature not present\n");
3241#endif
3242 Active_Slot_Display = Slot;
3243 if (Fstab_Processed())
3244 Update_System_Details();
3245}
3246string TWPartitionManager::Get_Active_Slot_Suffix() {
3247 if (Active_Slot_Display == "A")
3248 return "_a";
3249 return "_b";
3250}
3251string TWPartitionManager::Get_Active_Slot_Display() {
3252 return Active_Slot_Display;
3253}
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003254
Captain Throwback9d6feb52018-07-27 10:05:24 -04003255string TWPartitionManager::Get_Android_Root_Path() {
bigbiff8da46fa2020-09-08 16:42:34 -04003256 return "/system_root";
Captain Throwback9d6feb52018-07-27 10:05:24 -04003257}
3258
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003259void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
3260 std::vector<TWPartition*>::iterator iter;
3261
3262 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
3263 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
3264 TWPartition *part = *iter;
3265 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
3266 (*iter)->UnMount(false);
3267 rmdir((*iter)->Mount_Point.c_str());
3268 iter = Partitions.erase(iter);
3269 delete part;
3270 } else {
3271 iter++;
3272 }
3273 }
3274}
3275
3276void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
3277 std::vector<TWPartition*>::iterator iter;
3278
3279 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3280 if (!(*iter)->Sysfs_Entry.empty()) {
3281 string device;
3282 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
3283 if (wildcard != string::npos) {
3284 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
3285 } else {
3286 device = (*iter)->Sysfs_Entry;
3287 }
3288 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
3289 // Found a match
3290 if (uevent_data.action == "add") {
3291 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
3292 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
3293 (*iter)->Is_Present = true;
3294 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
3295 if (!Decrypt_Adopted()) {
3296 LOGINFO("No adopted storage so finding actual block device\n");
3297 (*iter)->Find_Actual_Block_Device();
3298 }
3299 return;
3300 } else if (uevent_data.action == "remove") {
3301 (*iter)->Is_Present = false;
3302 (*iter)->Primary_Block_Device = "";
3303 (*iter)->Actual_Block_Device = "";
3304 Remove_Uevent_Devices((*iter)->Mount_Point);
3305 return;
3306 }
3307 }
3308 }
3309 }
bigbiffee7b7ff2020-03-23 15:08:27 -04003310
3311 if (!PartitionManager.Get_Super_Status())
3312 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 -06003313}
3314
3315void TWPartitionManager::setup_uevent() {
3316 struct sockaddr_nl nls;
3317
3318 if (uevent_pfd.fd >= 0) {
3319 LOGINFO("uevent already set up\n");
3320 return;
3321 }
3322
3323 // Open hotplug event netlink socket
3324 memset(&nls,0,sizeof(struct sockaddr_nl));
3325 nls.nl_family = AF_NETLINK;
3326 nls.nl_pid = getpid();
3327 nls.nl_groups = -1;
3328 uevent_pfd.events = POLLIN;
3329 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
3330 if (uevent_pfd.fd==-1) {
3331 LOGERR("uevent not root\n");
3332 return;
3333 }
3334
3335 // Listen to netlink socket
3336 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
3337 LOGERR("Bind failed\n");
3338 return;
3339 }
3340 set_select_fd();
3341 Coldboot();
3342}
3343
3344Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
3345 Uevent_Block_Data ret;
3346 ret.subsystem = "";
3347 char *ptr = buf;
3348 const char *end = buf + len;
3349
3350 buf[len - 1] = '\0';
3351 while (ptr < end) {
3352 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
3353 ptr += strlen("ACTION=");
3354 ret.action = ptr;
3355 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
3356 ptr += strlen("SUBSYSTEM=");
3357 ret.subsystem = ptr;
3358 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
3359 ptr += strlen("DEVTYPE=");
3360 ret.type = ptr;
3361 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
3362 ptr += strlen("DEVPATH=");
3363 ret.sysfs_path += ptr;
3364 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
3365 ptr += strlen("DEVNAME=");
3366 ret.block_device += ptr;
3367 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
3368 ptr += strlen("MAJOR=");
3369 ret.major = atoi(ptr);
3370 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
3371 ptr += strlen("MINOR=");
3372 ret.minor = atoi(ptr);
3373 }
3374 ptr += strlen(ptr) + 1;
3375 }
3376 return ret;
3377}
3378
3379void TWPartitionManager::read_uevent() {
3380 char buf[1024];
3381
3382 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
3383 if (len == -1) {
Mauronofrio Matarresec1bb76e2019-08-04 17:02:41 +01003384 LOGINFO("recv error on uevent\n");
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06003385 return;
3386 }
3387 /*int i = 0; // Print all uevent output for test /debug
3388 while (i<len) {
3389 printf("%s\n", buf+i);
3390 i += strlen(buf+i)+1;
3391 }*/
3392 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
3393 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
3394 PartitionManager.Handle_Uevent(uevent_data);
3395 }
3396}
3397
3398void TWPartitionManager::close_uevent() {
3399 if (uevent_pfd.fd > 0)
3400 close(uevent_pfd.fd);
3401 uevent_pfd.fd = -1;
3402}
3403
3404void TWPartitionManager::Add_Partition(TWPartition* Part) {
3405 Partitions.push_back(Part);
3406}
3407
3408void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
3409 string Real_Path = Path;
3410 char real_path[PATH_MAX];
3411 if (realpath(Path.c_str(), &real_path[0])) {
3412 string Real_Path = real_path;
3413 std::vector<string>::iterator iter;
3414 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
3415 if (Real_Path.find((*iter)) != string::npos) {
3416 string Write_Path = Real_Path + "/uevent";
3417 if (TWFunc::Path_Exists(Write_Path)) {
3418 const char* write_val = "add\n";
3419 TWFunc::write_to_file(Write_Path, write_val);
3420 break;
3421 }
3422 }
3423 }
3424 }
3425
3426 DIR* d = opendir(Path.c_str());
3427 if (d != NULL) {
3428 struct dirent* de;
3429 while ((de = readdir(d)) != NULL) {
3430 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
3431 continue;
3432 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
3433 continue;
3434
3435 string item = Path + "/";
3436 item.append(de->d_name);
3437 Coldboot_Scan(sysfs_entries, item, depth + 1);
3438 }
3439 closedir(d);
3440 }
3441}
3442
3443void TWPartitionManager::Coldboot() {
3444 std::vector<TWPartition*>::iterator iter;
3445 std::vector<string> sysfs_entries;
3446
3447 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3448 if (!(*iter)->Sysfs_Entry.empty()) {
3449 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
3450 if (wildcard_pos == string::npos)
3451 wildcard_pos = (*iter)->Sysfs_Entry.size();
3452 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
3453 }
3454 }
3455
3456 if (sysfs_entries.size() > 0)
3457 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
3458}
Ethan Yonker53796e72019-01-11 22:49:52 -06003459
3460bool TWPartitionManager::Prepare_Empty_Folder(const std::string& Folder) {
3461 if (TWFunc::Path_Exists(Folder))
3462 TWFunc::removeDir(Folder, false);
3463 return TWFunc::Recursive_Mkdir(Folder);
3464}
3465
bigbiffcfa875c2021-06-20 16:20:27 -04003466std::string TWPartitionManager::Get_Bare_Partition_Name(std::string Mount_Point) {
3467 if (Mount_Point == "/system_root")
3468 return "system";
3469 else
3470 return TWFunc::Remove_Beginning_Slash(Mount_Point);
3471}
3472
bigbiffee7b7ff2020-03-23 15:08:27 -04003473bool TWPartitionManager::Prepare_Super_Volume(TWPartition* twrpPart) {
3474 Fstab fstab;
bigbiffcfa875c2021-06-20 16:20:27 -04003475 std::string bare_partition_name = Get_Bare_Partition_Name(twrpPart->Get_Mount_Point());
bigbiffee7b7ff2020-03-23 15:08:27 -04003476
bigbiff998f8392021-08-06 19:19:33 -04003477 Super_Partition_List.push_back(bare_partition_name);
bigbiffee7b7ff2020-03-23 15:08:27 -04003478 LOGINFO("Trying to prepare %s from super partition\n", bare_partition_name.c_str());
3479
3480 std::string blk_device_partition;
3481#ifdef AB_OTA_UPDATER
3482 blk_device_partition = bare_partition_name + PartitionManager.Get_Active_Slot_Suffix();
3483#else
3484 blk_device_partition = bare_partition_name;
3485#endif
3486
3487 FstabEntry fstabEntry = {
3488 .blk_device = blk_device_partition,
3489 .mount_point = twrpPart->Get_Mount_Point(),
3490 .fs_type = twrpPart->Current_File_System,
3491 .fs_mgr_flags.logical = twrpPart->Is_Super,
3492 };
3493
3494 fstab.emplace_back(fstabEntry);
3495 if (!fs_mgr_update_logical_partition(&fstabEntry)) {
Captain Throwbackc6939102021-04-06 12:57:30 -04003496 LOGINFO("unable to update logical partition: %s\n", twrpPart->Get_Mount_Point().c_str());
bigbiffee7b7ff2020-03-23 15:08:27 -04003497 return false;
3498 }
3499
bigbiff32cbabe2020-04-12 19:16:19 -04003500 while (access(fstabEntry.blk_device.c_str(), F_OK) != 0) {
3501 usleep(100);
3502 }
3503
bigbiffee7b7ff2020-03-23 15:08:27 -04003504 twrpPart->Set_Block_Device(fstabEntry.blk_device);
3505 twrpPart->Update_Size(true);
bigbiffee7b7ff2020-03-23 15:08:27 -04003506 twrpPart->Set_Can_Be_Backed_Up(false);
3507 twrpPart->Set_Can_Be_Wiped(false);
me-cafebabe928234b2022-07-28 04:07:04 +08003508 if (access(("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str(), F_OK) == -1) {
3509 LOGINFO("Symlinking %s => /dev/block/bootdevice/by-name/%s \n", fstabEntry.blk_device.c_str(), bare_partition_name.c_str());
3510 symlink(fstabEntry.blk_device.c_str(), ("/dev/block/bootdevice/by-name/" + bare_partition_name).c_str());
Captain Throwback88c6e652023-01-16 15:32:26 -05003511 property_set("twrp.super.symlinks_created", "true");
me-cafebabe928234b2022-07-28 04:07:04 +08003512 }
Mohd Faraz7fc70502021-04-22 20:44:11 +02003513
bigbiffee7b7ff2020-03-23 15:08:27 -04003514 return true;
3515}
3516
3517bool TWPartitionManager::Prepare_All_Super_Volumes() {
3518 bool status = true;
3519 std::vector<TWPartition*>::iterator iter;
3520
3521 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
3522 if ((*iter)->Is_Super) {
3523 if (!Prepare_Super_Volume(*iter)) {
3524 status = false;
Mohd Faraz787cc612023-01-02 22:47:51 +01003525 Partitions.erase(iter--);
bigbiffee7b7ff2020-03-23 15:08:27 -04003526 }
3527 PartitionManager.Output_Partition(*iter);
3528 }
3529 }
3530 Update_System_Details();
3531 return status;
3532}
3533
bigbiffee7b7ff2020-03-23 15:08:27 -04003534std::string TWPartitionManager::Get_Super_Partition() {
3535 int slot_number = Get_Active_Slot_Display() == "A" ? 0 : 1;
bigbiff998f8392021-08-06 19:19:33 -04003536 std::string super_device = fs_mgr_get_super_partition_name(slot_number);
bigbiffee7b7ff2020-03-23 15:08:27 -04003537 return "/dev/block/by-name/" + super_device;
3538}
3539
3540void TWPartitionManager::Setup_Super_Devices() {
3541 std::string superPart = Get_Super_Partition();
3542 android::fs_mgr::CreateLogicalPartitions(superPart);
bigbiff7ba75002020-04-11 20:47:09 -04003543}
3544
3545void TWPartitionManager::Setup_Super_Partition() {
bigbiffee7b7ff2020-03-23 15:08:27 -04003546 TWPartition* superPartition = new TWPartition();
bigbiff7ba75002020-04-11 20:47:09 -04003547 std::string superPart = Get_Super_Partition();
3548
3549 superPartition->Backup_Path = "/super";
3550 superPartition->Mount_Point = "/super";
bigbiffee7b7ff2020-03-23 15:08:27 -04003551 superPartition->Actual_Block_Device = superPart;
3552 superPartition->Alternate_Block_Device = superPart;
bigbiff998f8392021-08-06 19:19:33 -04003553 superPartition->Backup_Display_Name = "Super (";
3554 // Add first 4 items to fstab as logical that you would like to display in Backup_Display_Name
3555 // for the Super partition
3556 int list_size = Super_Partition_List.size();
3557 int orig_list_size = list_size;
3558 int max_display_size = 3; // total of 4 items since we start at 0
3559
3560 for (auto partition: Super_Partition_List) {
3561 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + partition;
3562 if ((orig_list_size - list_size) == max_display_size) {
3563 break;
3564 }
3565 if (list_size != 1)
3566 superPartition->Backup_Display_Name = superPartition->Backup_Display_Name + " ";
3567 list_size--;
3568 }
3569 superPartition->Backup_Display_Name += ")";
bigbiffee7b7ff2020-03-23 15:08:27 -04003570 superPartition->Can_Flash_Img = true;
bigbiffee7b7ff2020-03-23 15:08:27 -04003571 superPartition->Current_File_System = "emmc";
3572 superPartition->Can_Be_Backed_Up = true;
3573 superPartition->Is_Present = true;
3574 superPartition->Is_SubPartition = false;
bigbiff7ba75002020-04-11 20:47:09 -04003575 superPartition->Setup_Image();
bigbiffee7b7ff2020-03-23 15:08:27 -04003576 Add_Partition(superPartition);
3577 PartitionManager.Output_Partition(superPartition);
bigbiffee7b7ff2020-03-23 15:08:27 -04003578}
3579
3580bool TWPartitionManager::Get_Super_Status() {
bigbiffdf8436b2020-08-30 16:22:34 -04003581 std::string fastboot_mode = android::base::GetProperty("sys.usb.config", "");
3582 if (fastboot_mode == "fastboot") {
3583 return false;
3584 }
3585 else
3586 return access(Get_Super_Partition().c_str(), F_OK) == 0;
bigbiffee7b7ff2020-03-23 15:08:27 -04003587}
bigbiff25d25b92020-06-19 16:07:38 -04003588
3589bool TWPartitionManager::Recreate_Logs_Dir() {
3590#ifdef TW_INCLUDE_FBE
3591 struct passwd pd;
3592 struct passwd *pwdptr = &pd;
3593 struct passwd *tempPd;
3594 char pwdBuf[512];
3595 int uid = 0, gid = 0;
3596
3597 if ((getpwnam_r("system", pwdptr, pwdBuf, sizeof(pwdBuf), &tempPd)) != 0) {
3598 LOGERR("unable to get system user id\n");
3599 return false;
3600 } else {
3601 struct group grp;
3602 struct group *grpptr = &grp;
3603 struct group *tempGrp;
3604 char grpBuf[512];
3605
3606 if ((getgrnam_r("cache", grpptr, grpBuf, sizeof(grpBuf), &tempGrp)) != 0) {
3607 LOGERR("unable to get cache group id\n");
3608 return false;
3609 } else {
3610 uid = pd.pw_uid;
3611 gid = grp.gr_gid;
3612 std::string abLogsRecoveryDir(DATA_LOGS_DIR);
3613 abLogsRecoveryDir += "/recovery/";
3614
3615 if (!TWFunc::Create_Dir_Recursive(abLogsRecoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, uid, gid)) {
3616 LOGERR("Unable to recreate %s\n", abLogsRecoveryDir.c_str());
3617 return false;
3618 }
3619 if (setfilecon(abLogsRecoveryDir.c_str(), "u:object_r:cache_file:s0") != 0) {
3620 LOGERR("Unable to set contexts for %s\n", abLogsRecoveryDir.c_str());
3621 return false;
3622 }
3623 }
3624 }
3625#endif
3626 return true;
3627}
bigbiff1f9e4842020-10-31 11:33:15 -04003628
3629void TWPartitionManager::Unlock_Block_Partitions() {
3630 int fd, OFF = 0;
3631
3632 const std::string block_path = "/dev/block/";
3633 DIR* d = opendir(block_path.c_str());
3634 if (d != NULL) {
3635 struct dirent* de;
3636 while ((de = readdir(d)) != NULL) {
3637 if (de->d_type == DT_BLK) {
3638 std::string block_device = block_path + de->d_name;
bigbiff1f9e4842020-10-31 11:33:15 -04003639 if ((fd = open(block_device.c_str(), O_RDONLY | O_CLOEXEC)) < 0) {
3640 LOGERR("unable to open block device %s: %s\n", block_device.c_str(), strerror(errno));
3641 continue;
3642 }
3643 if (ioctl(fd, BLKROSET, &OFF) == -1) {
me-cafebabed63fcaa2022-07-28 03:19:20 +08003644 LOGERR("Unable to unlock %s: %s\n", block_device.c_str());
bigbiff1f9e4842020-10-31 11:33:15 -04003645 continue;
3646 }
3647 close(fd);
3648 }
3649 }
3650 closedir(d);
3651 }
bigbiffaf253cd2020-12-06 16:50:55 -05003652}
bigbiffcfa875c2021-06-20 16:20:27 -04003653
3654bool TWPartitionManager::Unmap_Super_Devices() {
3655 bool destroyed = false;
3656#ifndef TW_EXCLUDE_APEX
3657 twrpApex apex;
3658 apex.Unmount();
3659#endif
3660 for (auto iter = Partitions.begin(); iter != Partitions.end();) {
3661 LOGINFO("Checking partition: %s\n", (*iter)->Get_Mount_Point().c_str());
3662 if ((*iter)->Is_Super) {
3663 TWPartition *part = *iter;
3664 std::string bare_partition_name = Get_Bare_Partition_Name((*iter)->Get_Mount_Point());
me-cafebabe2136fc52022-07-20 06:42:18 +08003665 std::string blk_device_partition = bare_partition_name;
3666 if (DataManager::GetStrValue(TW_VIRTUAL_AB_ENABLED) == "1")
3667 blk_device_partition.append(PartitionManager.Get_Active_Slot_Suffix());
bigbiffcfa875c2021-06-20 16:20:27 -04003668 (*iter)->UnMount(false);
3669 LOGINFO("removing dynamic partition: %s\n", blk_device_partition.c_str());
3670 destroyed = DestroyLogicalPartition(blk_device_partition);
3671 std::string cow_partition = blk_device_partition + "-cow";
3672 std::string cow_partition_path = "/dev/block/mapper/" + cow_partition;
3673 struct stat st;
3674 if (lstat(cow_partition_path.c_str(), &st) == 0) {
3675 LOGINFO("removing cow partition: %s\n", cow_partition.c_str());
3676 destroyed = DestroyLogicalPartition(cow_partition);
3677 }
bigbiffcfa875c2021-06-20 16:20:27 -04003678 iter = Partitions.erase(iter);
3679 delete part;
3680 if (!destroyed) {
3681 return false;
3682 }
3683 } else {
3684 ++iter;
3685 }
3686 }
3687 return true;
3688}
bigbiffd21252f2021-09-18 15:56:32 -04003689
3690
3691bool TWPartitionManager::Check_Pending_Merges() {
3692 auto sm = android::snapshot::SnapshotManager::NewForFirstStageMount();
3693 if (!sm) {
3694 LOGERR("Unable to call snapshot manager\n");
3695 return false;
3696 }
3697
3698 if (!Unmap_Super_Devices()) {
3699 LOGERR("Unable to unmap dynamic partitions.\n");
3700 return false;
3701 }
3702
3703 auto callback = [&]() -> void {
3704 double progress;
3705 sm->GetUpdateState(&progress);
3706 LOGINFO("waiting for merge to complete: %.2f\n", progress);
3707 };
3708
3709 LOGINFO("checking for merges\n");
3710 if (!sm->HandleImminentDataWipe(callback)) {
3711 LOGERR("Unable to check merge status\n");
3712 return false;
3713 }
3714 return true;
Darth98f775972022-08-05 09:39:03 +01003715}