-
Notifications
You must be signed in to change notification settings - Fork 9
/
partitionmanager.cpp
executable file
·3807 lines (3436 loc) · 125 KB
/
partitionmanager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 to 2021 TeamWin
This file is part of TWRP/TeamWin Recovery Project.
TWRP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TWRP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with TWRP. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <map>
#include <vector>
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <zlib.h>
#include <iostream>
#include <iomanip>
#include <sys/wait.h>
#include <linux/fs.h>
#include <sys/mount.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/types.h>
#include <linux/netlink.h>
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/strings.h>
#include <fstab/fstab.h>
#include <fs_avb/fs_avb.h>
#include <fs_mgr.h>
#include <fs_mgr_dm_linear.h>
#include <fs_mgr_overlayfs.h>
#include <fs_mgr/roots.h>
#include <libgsi/libgsi.h>
#include <liblp/liblp.h>
#include <libgsi/libgsi.h>
#include <liblp/builder.h>
#include <libsnapshot/snapshot.h>
#include "variables.h"
#include "twcommon.h"
#include "partitions.hpp"
#include "data.hpp"
#include "startupArgs.hpp"
#include "twrp-functions.hpp"
#include "fixContexts.hpp"
#include "exclude.hpp"
#include "set_metadata.h"
#include "tw_atomic.hpp"
#include "gui/gui.hpp"
#include "progresstracking.hpp"
#include "twrpDigestDriver.hpp"
#include "twrpRepacker.hpp"
#include "adbbu/libtwadbbu.hpp"
#ifdef TW_HAS_MTP
#ifdef TW_HAS_LEGACY_MTP
#include "mtp/legacy/mtp_MtpServer.hpp"
#include "mtp/legacy/twrpMtp.hpp"
#include "mtp/legacy/MtpMessage.hpp"
#else
#include "mtp/ffs/mtp_MtpServer.hpp"
#include "mtp/ffs/twrpMtp.hpp"
#include "mtp/ffs/MtpMessage.hpp"
#endif
#endif
extern "C" {
#include "cutils/properties.h"
#include "gui/gui.h"
}
#ifdef TW_INCLUDE_CRYPTO
// #include "crypto/fde/cryptfs.h"
#include "gui/rapidxml.hpp"
#include "gui/pages.hpp"
#ifdef TW_INCLUDE_FBE
#include "Decrypt.h"
#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
#ifdef USE_FSCRYPT
#include "cryptfs.h"
#include "fscrypt-common.h"
#include "MetadataCrypt.h"
#endif
#endif
#endif
#endif
#ifdef AB_OTA_UPDATER
#include <android/hardware/boot/1.0/IBootControl.h>
using android::hardware::boot::V1_0::CommandResult;
using android::hardware::boot::V1_0::IBootControl;
#endif
using android::fs_mgr::DestroyLogicalPartition;
using android::fs_mgr::Fstab;
using android::fs_mgr::FstabEntry;
using android::fs_mgr::MetadataBuilder;
extern bool datamedia;
std::vector<users_struct> Users_List;
std::string additional_fstab = "/etc/additional.fstab";
TWPartitionManager::TWPartitionManager(void) {
mtp_was_enabled = false;
mtp_write_fd = -1;
uevent_pfd.fd = -1;
stop_backup.set_value(0);
#ifdef AB_OTA_UPDATER
char slot_suffix[PROPERTY_VALUE_MAX];
property_get("ro.boot.slot_suffix", slot_suffix, "error");
if (strcmp(slot_suffix, "error") == 0)
property_get("ro.boot.slot", slot_suffix, "error");
Active_Slot_Display = "";
if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
Set_Active_Slot("A");
else
Set_Active_Slot("B");
#endif
}
void TWPartitionManager::Set_Crypto_State() {
char crypto_state[PROPERTY_VALUE_MAX];
property_get("ro.crypto.state", crypto_state, "error");
if (strcmp(crypto_state, "error") == 0)
property_set("ro.crypto.state", "encrypted");
}
int TWPartitionManager::Set_Crypto_Type(const char* crypto_type) {
char type_prop[PROPERTY_VALUE_MAX];
property_get("ro.crypto.type", type_prop, "error");
if (strcmp(type_prop, "error") == 0)
property_set("ro.crypto.type", crypto_type);
// Sleep for a bit so that services can start if needed
sleep(1);
return 0;
}
void inline Reset_Prop_From_Partition(std::string prop, std::string def, TWPartition *ven, TWPartition *odm) {
bool prop_on_odm = false, prop_on_vendor = false;
string prop_value;
if (odm) {
string odm_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/odm", "etc/build.prop");
if (!odm_prop.empty()) {
prop_on_odm = true;
if (TWFunc::Property_Override(prop, odm_prop) == NOT_AVAILABLE) {
LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
} else {
prop_value = android::base::GetProperty(prop, "");
LOGINFO("Setting '%s' to '%s' from /odm/etc/build.prop\n", prop.c_str(), prop_value.c_str());
}
}
}
if (ven) {
string vendor_prop = TWFunc::Partition_Property_Get(prop, PartitionManager, "/vendor", "build.prop");
if (!vendor_prop.empty()) {
prop_on_vendor = true;
if (TWFunc::Property_Override(prop, vendor_prop) == NOT_AVAILABLE) {
LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
} else {
prop_value = android::base::GetProperty(prop, "");
LOGINFO("Setting '%s' to '%s' from /vendor/build.prop\n", prop.c_str(), prop_value.c_str());
}
}
}
if (!prop_on_odm && !prop_on_vendor && !def.empty()) {
if (TWFunc::Property_Override(prop, def) == NOT_AVAILABLE) {
LOGERR("Unable to override '%s' due to missing libresetprop\n", prop.c_str());
} else {
prop_value = android::base::GetProperty(prop, "");
LOGINFO("Setting '%s' to default value (%s)\n", prop.c_str(), prop_value.c_str());
}
}
prop_value = android::base::GetProperty(prop, "");
if (!prop_on_odm && !prop_on_vendor && !prop_value.empty() && def.empty()) {
if(TWFunc::Delete_Property(prop) == NOT_AVAILABLE) {
LOGERR("Unable to delete '%s' due to missing libresetprop\n", prop.c_str());
} else {
LOGINFO("Deleting property '%s'\n", prop.c_str());
}
}
}
static constexpr const char* __unused BOOT_DEV_PATH = "/dev/block/bootdevice/by-name/boot";
bool TWPartitionManager::Prevent_Install_Stock_Rec(bool Display_Info) {
#ifdef AB_OTA_UPDATER
return true;
#else
int BUFFSIZE = 4;
char sk[5] = {0x53, 0x4B, 0x4B, 0x4B, 0x0};
char buf[BUFFSIZE];
int _ret;
bool ret = false;
FILE *bootFile = fopen(BOOT_DEV_PATH, "rb+");
if (bootFile) {
bzero(buf, BUFFSIZE);
fseek(bootFile, -4L, SEEK_END);
_ret = fread(buf, sizeof(char), BUFFSIZE, bootFile);
if(!_ret) goto exit;
if(strncmp(sk, buf, BUFFSIZE) != 0) {
fseek(bootFile, -4L, SEEK_END);
_ret = fwrite(sk, sizeof(char), BUFFSIZE, bootFile);
if(!_ret) goto exit;
if(Display_Info) gui_highlight("prevent_auto_install_stock_rec_success_msg=Prevent automatic installation of stock Recovery success.");
} else {
if(Display_Info) gui_highlight("prevented_auto_install_stock_rec_msg=Prevented automatic installation of stock Recovery.");
}
ret = true;
}
exit:
if (bootFile) {
fclose(bootFile);
bootFile = nullptr;
}
return ret;
#endif
}
#define AVB_MAGIC "AVB0"
#define AVB_MAGIC_LEN 4
#define AVB_VBMETA_FLAGS_OFFSET 123
bool Do_Disable_AVB2(string File_Name, char Disable_Flags, bool Display_Info) {
char AVB_MAGIC_BUF[AVB_MAGIC_LEN + 1] = {0}, flags_buf[1] = {0};
int _ret;
bool ret = false;
string dev = "/dev/block/bootdevice/by-name/";
FILE *vbmetaFile = fopen((dev + File_Name).c_str(), "rb+");
if (vbmetaFile != NULL) {
fread(&AVB_MAGIC_BUF, AVB_MAGIC_LEN, 1, vbmetaFile);
if(strncmp(AVB_MAGIC, AVB_MAGIC_BUF, AVB_MAGIC_LEN) != 0) goto exit;
fseek(vbmetaFile, AVB_VBMETA_FLAGS_OFFSET, SEEK_SET);
_ret = fread(&flags_buf, 1, 1, vbmetaFile);
if(!_ret) goto exit;
if (flags_buf[0] != Disable_Flags) {
fseek(vbmetaFile, AVB_VBMETA_FLAGS_OFFSET, SEEK_SET);
_ret = fwrite(&Disable_Flags, 1, 1, vbmetaFile);
if(!_ret) goto exit;
}
ret = true;
}
exit:
if (vbmetaFile) {
fclose(vbmetaFile);
vbmetaFile = nullptr;
}
if (Display_Info) {
auto msg = ret ? Msg(msg::kHighlight, "disable_avb2_success_msg=Disable AVB2.0: processing '{1}' successfully.")(File_Name)
: Msg(msg::kError, "disable_avb2_fail_msg=Disable AVB2.0: processing '{1}' failed!")(File_Name);
gui_msg(msg);
}
return ret;
}
bool TWPartitionManager::Disable_AVB2(bool Display_Info) {
char disable_flags = AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED;
#ifdef AB_OTA_UPDATER
return Do_Disable_AVB2("vbmeta_a", disable_flags, Display_Info)
& Do_Disable_AVB2("vbmeta_system_a", disable_flags, Display_Info)
& Do_Disable_AVB2("vbmeta_b", disable_flags, Display_Info)
& Do_Disable_AVB2("vbmeta_system_b", disable_flags, Display_Info);
#else
return Do_Disable_AVB2("vbmeta", disable_flags, Display_Info)
& Do_Disable_AVB2("vbmeta_system", disable_flags, Display_Info);
#endif
}
int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error, bool recovery_mode) {
FILE *fstabFile;
char fstab_line[MAX_FSTAB_LINE_LENGTH];
bool parse_userdata = false;
std::map<string, Flags_Map> twrp_flags;
fstabFile = fopen("/etc/twrp.flags", "rt");
if (Get_Super_Status()) {
Setup_Super_Devices();
}
if (fstabFile != NULL) {
LOGINFO("Reading /etc/twrp.flags\n");
while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
size_t line_size = strlen(fstab_line);
if (fstab_line[line_size - 1] != '\n')
fstab_line[line_size] = '\n';
Flags_Map line_flags;
line_flags.Primary_Block_Device = "";
line_flags.Alternate_Block_Device = "";
line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
if (!line_flags.fstab_line) {
LOGERR("malloc error on line_flags.fstab_line\n");
return false;
}
memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
bool found_separator = false;
char *fs_loc = NULL;
char *block_loc = NULL;
char *flags_loc = NULL;
size_t index, item_index = 0;
for (index = 0; index < line_size; index++) {
if (fstab_line[index] <= 32) {
fstab_line[index] = '\0';
found_separator = true;
} else if (found_separator) {
if (item_index == 0) {
fs_loc = fstab_line + index;
} else if (item_index == 1) {
block_loc = fstab_line + index;
} else if (item_index > 1) {
char *ptr = fstab_line + index;
if (*ptr == '/') {
line_flags.Alternate_Block_Device = ptr;
} else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
flags_loc = ptr;
// Once we find the flags=, we're done scanning the line
break;
}
}
found_separator = false;
item_index++;
}
}
if (block_loc)
line_flags.Primary_Block_Device = block_loc;
if (fs_loc)
line_flags.File_System = fs_loc;
if (flags_loc)
line_flags.Flags = flags_loc;
string Mount_Point = fstab_line;
twrp_flags[Mount_Point] = line_flags;
memset(fstab_line, 0, sizeof(fstab_line));
}
fclose(fstabFile);
}
TWPartition *data = NULL;
TWPartition *meta = NULL;
parse:
fstabFile = fopen(Fstab_Filename.c_str(), "rt");
if (!parse_userdata && fstabFile == NULL) {
LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
return false;
} else
LOGINFO("Reading %s\n", Fstab_Filename.c_str());
while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
if (strstr(fstab_line, "swap"))
continue; // Skip swap in recovery
if (fstab_line[0] == '#')
continue;
if (parse_userdata) {
if (strstr(fstab_line, "/metadata") && !strstr(fstab_line, "/data")) {
if (meta) {
Partitions.erase(std::find(Partitions.begin(), Partitions.end(), meta));
delete meta;
meta = NULL;
}
} else if (strstr(fstab_line, "/data")) {
if (data) {
Partitions.erase(std::find(Partitions.begin(), Partitions.end(), data));
delete data;
data = NULL;
}
} else {
continue;
}
}
size_t line_size = strlen(fstab_line);
if (fstab_line[line_size - 1] != '\n')
fstab_line[line_size] = '\n';
TWPartition* partition = new TWPartition();
if (partition->Process_Fstab_Line(fstab_line, Display_Error, parse_userdata ? NULL : &twrp_flags)) {
if (partition->Mount_Point == "/data") data = partition;
if (partition->Mount_Point == "/metadata") meta = partition;
if (partition->Is_Super && !Prepare_Super_Volume(partition)) {
goto clear;
}
Partitions.push_back(partition);
}
else
clear:
delete partition;
memset(fstab_line, 0, sizeof(fstab_line));
}
fclose(fstabFile);
if (!parse_userdata && twrp_flags.size() > 0) {
LOGINFO("Processing remaining twrp.flags\n");
// Add any items from twrp.flags that did not exist in the recovery.fstab
for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
if (Find_Partition_By_Path(mapit->first) == NULL) {
TWPartition* partition = new TWPartition();
if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
Partitions.push_back(partition);
else
delete partition;
}
if (mapit->second.fstab_line)
free(mapit->second.fstab_line);
mapit->second.fstab_line = NULL;
}
}
TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
TWPartition* odm = PartitionManager.Find_Partition_By_Path("/odm");
if (!parse_userdata) {
if (ven) ven->Mount(Display_Error);
if (odm) odm->Mount(Display_Error);
if (TWFunc::Find_Fstab(Fstab_Filename)) {
string service;
LOGINFO("Fstab: %s\n", Fstab_Filename.c_str());
TWFunc::copy_file(Fstab_Filename, additional_fstab, 0600, false);
Fstab_Filename = additional_fstab;
property_set("fstab.additional", "1");
TWFunc::Get_Service_From(ven, "keymaster", service);
LOGINFO("Keymaster version: '%s'\n", TWFunc::Get_Version_From_Service(service).c_str());
property_set("keymaster_ver", TWFunc::Get_Version_From_Service(service).c_str());
parse_userdata = true;
Reset_Prop_From_Partition("ro.crypto.dm_default_key.options_format.version", "", ven, odm);
Reset_Prop_From_Partition("ro.crypto.volume.metadata.method", "", ven, odm);
Reset_Prop_From_Partition("ro.crypto.volume.options", "", ven, odm);
Reset_Prop_From_Partition("external_storage.projid.enabled", "", ven, odm);
Reset_Prop_From_Partition("external_storage.casefold.enabled", "", ven, odm);
Reset_Prop_From_Partition("external_storage.sdcardfs.enabled", "", ven, odm);
goto parse;
} else {
LOGINFO("Unable to parse vendor fstab\n");
}
}
if (ven) ven->UnMount(Display_Error);
if (odm) odm->UnMount(Display_Error);
LOGINFO("Done processing fstab files\n");
return true;
}
void TWPartitionManager::Setup_Fstab_Partitions(bool Display_Error) {
TWPartition* settings_partition = NULL;
TWPartition* andsec_partition = NULL;
std::vector<TWPartition*>::iterator iter;
unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
(*iter)->Partition_Post_Processing(Display_Error);
if ((*iter)->Is_Storage) {
++storageid;
(*iter)->MTP_Storage_ID = storageid;
}
if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
settings_partition = (*iter);
else
(*iter)->Is_Settings_Storage = false;
if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
andsec_partition = (*iter);
else
(*iter)->Has_Android_Secure = false;
}
Unlock_Block_Partitions();
//Setup Apex before decryption
TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
if (sys) {
if (sys->Get_Super_Status()) {
sys->Mount(Display_Error);
if (ven) {
ven->Mount(Display_Error);
}
#ifdef TW_EXCLUDE_APEX
LOGINFO("Apex is disabled in this build\n");
#else
twrpApex apex;
if (!apex.loadApexImages()) {
LOGERR("Unable to load apex images from %s\n", APEX_DIR);
property_set("twrp.apex.loaded", "false");
} else {
property_set("twrp.apex.loaded", "true");
}
TWFunc::check_and_run_script("/sbin/resyncapex.sh", "apex");
#endif
}
}
#ifndef USE_VENDOR_LIBS
if (ven)
ven->UnMount(Display_Error);
if (sys)
sys->UnMount(Display_Error);
#endif
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) {
// Attempt to automatically identify /data/media emulated storage devices
TWPartition* Dat = Find_Partition_By_Path("/data");
if (Dat) {
LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
datamedia = true;
Dat->Setup_Data_Media();
settings_partition = Dat;
// Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
++storageid;
Dat->MTP_Storage_ID = storageid;
}
}
if (!settings_partition) {
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Is_Storage) {
settings_partition = (*iter);
break;
}
}
if (!settings_partition)
LOGERR("Unable to locate storage partition for storing settings file.\n");
}
if (!Write_Fstab()) {
if (Display_Error)
LOGERR("Error creating fstab\n");
else
LOGINFO("Error creating fstab\n");
}
if (andsec_partition) {
Setup_Android_Secure_Location(andsec_partition);
} else if (settings_partition) {
Setup_Android_Secure_Location(settings_partition);
}
if (settings_partition) {
Setup_Settings_Storage_Partition(settings_partition);
}
#ifdef TW_INCLUDE_CRYPTO
DataManager::SetValue(TW_IS_ENCRYPTED, 1);
Decrypt_Data();
#endif
Update_System_Details();
if (Get_Super_Status())
Setup_Super_Partition();
UnMount_Main_Partitions();
#ifdef AB_OTA_UPDATER
DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
#endif
setup_uevent();
}
int TWPartitionManager::Write_Fstab(void) {
FILE *fp;
std::vector<TWPartition*>::iterator iter;
string Line;
fp = fopen("/etc/fstab", "w");
if (fp == NULL) {
LOGINFO("Can not open /etc/fstab.\n");
return false;
}
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Can_Be_Mounted) {
Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System +
((*iter)->Mount_Read_Only ? " ro " : " rw ") + "0 0\n";
fputs(Line.c_str(), fp);
}
// Handle subpartition tracking
if ((*iter)->Is_SubPartition) {
TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
if (ParentPartition)
ParentPartition->Has_SubPartition = true;
else
LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
}
}
fclose(fp);
return true;
}
void TWPartitionManager::Decrypt_Data() {
#ifdef TW_INCLUDE_CRYPTO
TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
Set_Crypto_State();
TWPartition* Key_Directory_Partition = Find_Partition_By_Path(Decrypt_Data->Key_Directory);
if (Key_Directory_Partition != nullptr)
if (!Key_Directory_Partition->Is_Mounted())
Mount_By_Path(Decrypt_Data->Key_Directory, false);
if (!Decrypt_Data->Key_Directory.empty()) {
Set_Crypto_Type("file");
#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
#ifdef USE_FSCRYPT
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 : "")) {
std::string crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "error");
Decrypt_Data->Decrypted_Block_Device = crypto_blkdev;
LOGINFO("Successfully decrypted metadata encrypted data partition with new block device: '%s'\n", crypto_blkdev.c_str());
#endif
Decrypt_Data->Is_Decrypted = true; // Needed to make the mount function work correctly
int retry_count = 10;
while (!Decrypt_Data->Mount(false) && --retry_count)
usleep(500);
if (Decrypt_Data->Mount(false)) {
if (!Decrypt_Data->Decrypt_FBE_DE()) {
gui_err("unable_to_decrypt_fbe_device_mgs=Unable to decrypt FBE device.");
gui_warn("unable_to_decrypt_fbe_device_msg2=If your device is not encrypted, decrypting the FEB device will fail.");
//LOGERR("Unable to decrypt FBE device\n");
}
} else {
LOGINFO("Failed to mount data after metadata decrypt\n");
}
} else {
LOGINFO("Unable to decrypt metadata encryption\n");
}
#else
LOGERR("Metadata FBE decrypt support not present in this TWRP\n");
#endif
}
if (Decrypt_Data->Is_FBE) {
if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
if (Decrypt_Device("!") == 0) {
gui_msg("decrypt_success=Successfully decrypted with default password.");
DataManager::SetValue(TW_IS_ENCRYPTED, 0);
} else {
gui_err("unable_to_decrypt=Unable to decrypt with default password.");
}
}
} else {
LOGINFO("FBE setup failed. Trying FDE...\n");
Set_Crypto_State();
Set_Crypto_Type("block");
int password_type = cryptfs_get_password_type();
if (password_type == CRYPT_TYPE_DEFAULT) {
LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
if (Decrypt_Device("default_password") == 0) {
gui_msg("decrypt_success=Successfully decrypted with default password.");
DataManager::SetValue(TW_IS_ENCRYPTED, 0);
} else {
gui_err("unable_to_decrypt=Unable to decrypt with default password.");
}
} else {
DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
DataManager::SetValue("tw_crypto_pwtype_0", password_type);
}
}
}
if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted)) {
Decrypt_Adopted();
}
#endif
}
void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
DataManager::SetValue("tw_storage_path", Part->Storage_Path);
}
void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
if (Part->Has_Android_Secure)
Part->Setup_AndSec();
else if (!datamedia)
Part->Setup_AndSec();
}
void TWPartitionManager::Output_Partition_Logging(void) {
std::vector<TWPartition*>::iterator iter;
printf("\n\nPartition Logs:\n");
for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
Output_Partition((*iter));
}
void TWPartitionManager::Output_Partition(TWPartition* Part) {
unsigned long long mb = 1048576;
printf("%s | %s | Size: %iMB", Part->Mount_Point.c_str(), Part->Actual_Block_Device.c_str(), (int)(Part->Size / mb));
if (Part->Can_Be_Mounted) {
printf(" Used: %iMB Free: %iMB Backup Size: %iMB", (int)(Part->Used / mb), (int)(Part->Free / mb), (int)(Part->Backup_Size / mb));
}
printf("\n Flags: ");
if (Part->Can_Be_Mounted)
printf("Can_Be_Mounted ");
if (Part->Can_Be_Wiped)
printf("Can_Be_Wiped ");
if (Part->Use_Rm_Rf)
printf("Use_Rm_Rf ");
if (Part->Can_Be_Backed_Up)
printf("Can_Be_Backed_Up ");
if (Part->Wipe_During_Factory_Reset)
printf("Wipe_During_Factory_Reset ");
if (Part->Wipe_Available_in_GUI)
printf("Wipe_Available_in_GUI ");
if (Part->Is_SubPartition)
printf("Is_SubPartition ");
if (Part->Has_SubPartition)
printf("Has_SubPartition ");
if (Part->Removable)
printf("Removable ");
if (Part->Is_Present)
printf("IsPresent ");
if (Part->Can_Be_Encrypted)
printf("Can_Be_Encrypted ");
if (Part->Is_Encrypted)
printf("Is_Encrypted ");
if (Part->Is_Decrypted)
printf("Is_Decrypted ");
if (Part->Has_Data_Media)
printf("Has_Data_Media ");
if (Part->Can_Encrypt_Backup)
printf("Can_Encrypt_Backup ");
if (Part->Use_Userdata_Encryption)
printf("Use_Userdata_Encryption ");
if (Part->Has_Android_Secure)
printf("Has_Android_Secure ");
if (Part->Is_Storage)
printf("Is_Storage ");
if (Part->Is_Settings_Storage)
printf("Is_Settings_Storage ");
if (Part->Ignore_Blkid)
printf("Ignore_Blkid ");
if (Part->Mount_To_Decrypt)
printf("Mount_To_Decrypt ");
if (Part->Can_Flash_Img)
printf("Can_Flash_Img ");
if (Part->Is_Adopted_Storage)
printf("Is_Adopted_Storage ");
if (Part->SlotSelect)
printf("SlotSelect ");
if (Part->Mount_Read_Only)
printf("Mount_Read_Only ");
if (Part->Is_Super)
printf("Is_Super ");
printf("\n");
if (!Part->SubPartition_Of.empty())
printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
if (!Part->Symlink_Path.empty())
printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
if (!Part->Symlink_Mount_Point.empty())
printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
if (!Part->Primary_Block_Device.empty())
printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
if (!Part->Alternate_Block_Device.empty())
printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
if (!Part->Decrypted_Block_Device.empty())
printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
if (!Part->Crypto_Key_Location.empty())
printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
if (Part->Length != 0)
printf(" Length: %i\n", Part->Length);
if (!Part->Display_Name.empty())
printf(" Display_Name: %s\n", Part->Display_Name.c_str());
if (!Part->Storage_Name.empty())
printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
if (!Part->Backup_Path.empty())
printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
if (!Part->Backup_Name.empty())
printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
if (!Part->Backup_Display_Name.empty())
printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
if (!Part->Backup_FileName.empty())
printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
if (!Part->Storage_Path.empty())
printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
if (!Part->Current_File_System.empty())
printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
if (!Part->Fstab_File_System.empty())
printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
if (Part->Format_Block_Size != 0)
printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
if (!Part->MTD_Name.empty())
printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
if (Part->Mount_Flags || !Part->Mount_Options.empty())
printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
if (Part->MTP_Storage_ID)
printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
if (!Part->Key_Directory.empty())
printf(" Metadata Key Directory: %s\n", Part->Key_Directory.c_str());
printf("\n");
}
int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
std::vector<TWPartition*>::iterator iter;
int ret = false;
bool found = false;
string Local_Path = TWFunc::Get_Root_Path(Path);
if (Local_Path == "/tmp" || Local_Path == "/")
return true;
// Iterate through all partitions
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
ret = (*iter)->Mount(Display_Error);
found = true;
} else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
(*iter)->Mount(Display_Error);
}
}
if (found) {
return ret;
} else if (Display_Error) {
gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
}
return false;
}
int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
std::vector<TWPartition*>::iterator iter;
int ret = false;
bool found = false;
string Local_Path = TWFunc::Get_Root_Path(Path);
// Iterate through all partitions
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
ret = (*iter)->UnMount(Display_Error);
found = true;
} else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
(*iter)->UnMount(Display_Error);
}
}
if (found) {
return ret;
} else if (Display_Error) {
gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
} else {
LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
}
return false;
}
int TWPartitionManager::Is_Mounted_By_Path(string Path) {
TWPartition* Part = Find_Partition_By_Path(Path);
if (Part)
return Part->Is_Mounted();
else
LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
return false;
}
int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
string current_storage_path = DataManager::GetCurrentStoragePath();
if (Mount_By_Path(current_storage_path, Display_Error)) {
TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
if (FreeStorage)
DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
return true;
}
return false;
}
int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
}
TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
std::vector<TWPartition*>::iterator iter;
string Local_Path = TWFunc::Get_Root_Path(Path);
if (Local_Path == "/system")
Local_Path = Get_Android_Root_Path();
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
return (*iter);
}
return NULL;
}
TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
std::vector<TWPartition*>::iterator iter;
for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
return (*iter);
}
return NULL;
}
int TWPartitionManager::Check_Backup_Name(const std::string& Backup_Name, bool Display_Error, bool Must_Be_Unique) {
// Check the backup name to ensure that it is the correct size and contains only valid characters
// and that a backup with that name doesn't already exist
char backup_name[MAX_BACKUP_NAME_LEN];
char backup_loc[255], tw_image_dir[255];
int copy_size;
int index, cur_char;
string Backup_Loc;
copy_size = Backup_Name.size();
// Check size
if (copy_size > MAX_BACKUP_NAME_LEN) {
if (Display_Error)
gui_err("backup_name_len=Backup name is too long.");
return -2;
}
// Check each character
strncpy(backup_name, Backup_Name.c_str(), copy_size);
if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
return 0; // A "0" (zero) means to use the current timestamp for the backup name
for (index=0; index<copy_size; index++) {
cur_char = (int)backup_name[index];
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) {
// These are valid characters
// Numbers
// Upper case letters
// Lower case letters
// Space
// and -_.{}[]
} else {
if (Display_Error)
gui_msg(Msg(msg::kError, "backup_name_invalid=Backup name '{1}' contains invalid character: '{1}'")(Backup_Name)((char)cur_char));
return -3;
}
}
if (Must_Be_Unique) {
// Check to make sure that a backup with this name doesn't already exist
DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
strcpy(backup_loc, Backup_Loc.c_str());
sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
if (TWFunc::Path_Exists(tw_image_dir)) {
if (Display_Error)
gui_err("backup_name_exists=A backup with that name already exists!");
return -4;
}
// Backup is unique
}
// No problems found
return 0;
}
bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
time_t start, stop;
int use_compression;
string backup_log = part_settings->Backup_Folder + "/recovery.log";
if (part_settings->Part == NULL)
return true;
DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
TWFunc::SetPerformanceMode(true);
time(&start);
if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
sync();
sync();
string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
if (!part_settings->adbbackup && part_settings->generate_digest) {
if (!twrpDigestDriver::Make_Digest(Full_Filename))
goto backup_error;
}
if (part_settings->Part->Has_SubPartition) {
std::vector<TWPartition*>::iterator subpart;
TWPartition *parentPart = part_settings->Part;
for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
part_settings->Part = *subpart;
if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
goto backup_error;
}
sync();
sync();
string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
if (!part_settings->adbbackup && part_settings->generate_digest) {
if (!twrpDigestDriver::Make_Digest(Full_Filename)) {