forked from omnirom/android_bootable_recovery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
partitionmanager.cpp
2385 lines (2154 loc) · 77.5 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 2016 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 <vector>
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <iomanip>
#include <sys/wait.h>
#include <linux/fs.h>
#include <sys/mount.h>
#include "variables.h"
#include "twcommon.h"
#include "partitions.hpp"
#include "data.hpp"
#include "twrp-functions.hpp"
#include "fixContexts.hpp"
#include "twrpDigest.hpp"
#include "twrpDU.hpp"
#include "set_metadata.h"
#include "tw_atomic.hpp"
#include "gui/gui.hpp"
#include "progresstracking.hpp"
#ifdef TW_HAS_MTP
#include "mtp/mtp_MtpServer.hpp"
#include "mtp/twrpMtp.hpp"
#include "mtp/MtpMessage.hpp"
#endif
extern "C" {
#include "cutils/properties.h"
#include "gui/gui.h"
}
#ifdef TW_INCLUDE_CRYPTO
#include "crypto/lollipop/cryptfs.h"
#include "gui/rapidxml.hpp"
#include "gui/pages.hpp"
#endif
extern bool datamedia;
TWPartitionManager::TWPartitionManager(void) {
mtp_was_enabled = false;
mtp_write_fd = -1;
stop_backup.set_value(0);
tar_fork_pid = 0;
}
int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error) {
FILE *fstabFile;
char fstab_line[MAX_FSTAB_LINE_LENGTH];
TWPartition* settings_partition = NULL;
TWPartition* andsec_partition = NULL;
unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
fstabFile = fopen(Fstab_Filename.c_str(), "rt");
if (fstabFile == NULL) {
LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
return false;
}
while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
if (fstab_line[0] != '/')
continue;
if (fstab_line[strlen(fstab_line) - 1] != '\n')
fstab_line[strlen(fstab_line)] = '\n';
TWPartition* partition = new TWPartition();
if (partition->Process_Fstab_Line(fstab_line, Display_Error))
Partitions.push_back(partition);
else
delete partition;
memset(fstab_line, 0, sizeof(fstab_line));
}
fclose(fstabFile);
std::vector<TWPartition*>::iterator iter;
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;
}
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
TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
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);
}
}
if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) && Decrypt_Data->Mount(false)) {
Decrypt_Adopted();
}
#endif
Update_System_Details();
UnMount_Main_Partitions();
return true;
}
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 + " 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::Setup_Settings_Storage_Partition(TWPartition* Part) {
DataManager::SetValue("tw_settings_path", Part->Storage_Path);
DataManager::SetValue("tw_storage_path", Part->Storage_Path);
LOGINFO("Settings storage is '%s'\n", Part->Storage_Path.c_str());
}
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->Retain_Layout_Version)
printf("Retain_Layout_Version ");
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 ");
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() && Part->Crypto_Key_Location != "footer")
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());
string back_meth = Part->Backup_Method_By_Name();
printf(" Backup_Method: %s\n", back_meth.c_str());
if (Part->Mount_Flags || !Part->Mount_Options.empty())
printf(" Mount_Options: %s\n", Part->Mount_Options.c_str());
if (Part->MTP_Storage_ID)
printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
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));
} else {
LOGINFO("Mount: Unable to find partition for path '%s'\n", Local_Path.c_str());
}
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(string Path) {
std::vector<TWPartition*>::iterator iter;
string Local_Path = TWFunc::Get_Root_Path(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;
}
int TWPartitionManager::Check_Backup_Name(bool Display_Error) {
// 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_Name, Backup_Loc;
DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
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;
}
}
// 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;
}
// No problems found, return 0
return 0;
}
bool TWPartitionManager::Make_MD5(bool generate_md5, string Backup_Folder, string Backup_Filename)
{
string command;
string Full_File = Backup_Folder + Backup_Filename;
string result;
twrpDigest md5sum;
if (!generate_md5)
return true;
TWFunc::GUI_Operation_Text(TW_GENERATE_MD5_TEXT, gui_parse_text("{@generating_md51}"));
gui_msg("generating_md52= * Generating md5...");
if (TWFunc::Path_Exists(Full_File)) {
md5sum.setfn(Backup_Folder + Backup_Filename);
if (md5sum.computeMD5() == 0)
if (md5sum.write_md5digest() == 0)
gui_msg("md5_created= * MD5 Created.");
else
return -1;
else
gui_err("md5_error= * MD5 Error!");
} else {
char filename[512];
int index = 0;
string strfn;
sprintf(filename, "%s%03i", Full_File.c_str(), index);
strfn = filename;
while (index < 1000) {
md5sum.setfn(filename);
if (TWFunc::Path_Exists(filename)) {
if (md5sum.computeMD5() == 0) {
if (md5sum.write_md5digest() != 0)
{
gui_err("md5_error= * MD5 Error!");
return false;
}
} else {
gui_err("md5_compute_error= * Error computing MD5.");
return false;
}
}
index++;
sprintf(filename, "%s%03i", Full_File.c_str(), index);
strfn = filename;
}
if (index == 0) {
LOGERR("Backup file: '%s' not found!\n", filename);
return false;
}
gui_msg("md5_created= * MD5 Created.");
}
return true;
}
bool TWPartitionManager::Backup_Partition(TWPartition* Part, const string& Backup_Folder, bool generate_md5, unsigned long *img_time, unsigned long *file_time, ProgressTracking *progress) {
time_t start, stop;
int use_compression;
string backup_log = Backup_Folder + "recovery.log";
if (Part == NULL)
return true;
DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
TWFunc::SetPerformanceMode(true);
time(&start);
if (Part->Backup(Backup_Folder, tar_fork_pid, progress)) {
bool md5Success = false;
if (Part->Has_SubPartition) {
std::vector<TWPartition*>::iterator subpart;
for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == Part->Mount_Point) {
if (!(*subpart)->Backup(Backup_Folder, tar_fork_pid, progress)) {
TWFunc::SetPerformanceMode(false);
Clean_Backup_Folder(Backup_Folder);
TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
tw_set_default_metadata(backup_log.c_str());
return false;
}
sync();
sync();
if (!Make_MD5(generate_md5, Backup_Folder, (*subpart)->Backup_FileName)) {
TWFunc::SetPerformanceMode(false);
return false;
}
}
}
}
time(&stop);
int backup_time = (int) difftime(stop, start);
LOGINFO("Partition Backup time: %d\n", backup_time);
if (Part->Backup_Method == 1) {
*file_time += backup_time;
} else {
*img_time += backup_time;
}
md5Success = Make_MD5(generate_md5, Backup_Folder, Part->Backup_FileName);
TWFunc::SetPerformanceMode(false);
return md5Success;
} else {
Clean_Backup_Folder(Backup_Folder);
TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
tw_set_default_metadata(backup_log.c_str());
TWFunc::SetPerformanceMode(false);
return false;
}
return 0;
}
void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
DIR *d = opendir(Backup_Folder.c_str());
struct dirent *p;
int r;
gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
if (d == NULL) {
gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
return;
}
while ((p = readdir(d))) {
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
string path = Backup_Folder + p->d_name;
size_t dot = path.find_last_of(".") + 1;
if (path.substr(dot) == "win" || path.substr(dot) == "md5" || path.substr(dot) == "info") {
r = unlink(path.c_str());
if (r != 0) {
LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
}
}
}
closedir(d);
}
int TWPartitionManager::Check_Backup_Cancel() {
return stop_backup.get_value();
}
int TWPartitionManager::Cancel_Backup() {
string Backup_Folder, Backup_Name, Full_Backup_Path;
stop_backup.set_value(1);
if (tar_fork_pid != 0) {
DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
Full_Backup_Path = Backup_Folder + "/" + Backup_Name + "/";
LOGINFO("Killing pid: %d\n", tar_fork_pid);
kill(tar_fork_pid, SIGUSR2);
while (kill(tar_fork_pid, 0) == 0) {
usleep(1000);
}
LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
TWFunc::removeDir(Full_Backup_Path, false);
tar_fork_pid = 0;
}
return 0;
}
int TWPartitionManager::Run_Backup(void) {
int check, do_md5, partition_count = 0, disable_free_space_check = 0;
string Backup_Folder, Backup_Name, Full_Backup_Path, Backup_List, backup_path;
unsigned long long total_bytes = 0, file_bytes = 0, img_bytes = 0, free_space = 0, img_bytes_remaining, file_bytes_remaining, subpart_size;
unsigned long img_time = 0, file_time = 0;
TWPartition* backup_part = NULL;
TWPartition* storage = NULL;
std::vector<TWPartition*>::iterator subpart;
struct tm *t;
time_t start, stop, seconds, total_start, total_stop;
size_t start_pos = 0, end_pos = 0;
stop_backup.set_value(0);
seconds = time(0);
t = localtime(&seconds);
time(&total_start);
Update_System_Details();
if (!Mount_Current_Storage(true))
return false;
DataManager::GetValue(TW_SKIP_MD5_GENERATE_VAR, do_md5);
if (do_md5 == 0)
do_md5 = true;
else
do_md5 = false;
DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
Backup_Name = TWFunc::Get_Current_Date();
} else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
TWFunc::Auto_Generate_Backup_Name();
DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
}
LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
Full_Backup_Path = Backup_Folder + "/" + Backup_Name + "/";
LOGINFO("Full_Backup_Path is: '%s'\n", Full_Backup_Path.c_str());
LOGINFO("Calculating backup details...\n");
DataManager::GetValue("tw_backup_list", Backup_List);
if (!Backup_List.empty()) {
end_pos = Backup_List.find(";", start_pos);
while (end_pos != string::npos && start_pos < Backup_List.size()) {
backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
backup_part = Find_Partition_By_Path(backup_path);
if (backup_part != NULL) {
partition_count++;
if (backup_part->Backup_Method == 1)
file_bytes += backup_part->Backup_Size;
else
img_bytes += backup_part->Backup_Size;
if (backup_part->Has_SubPartition) {
std::vector<TWPartition*>::iterator subpart;
for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == backup_part->Mount_Point) {
partition_count++;
if ((*subpart)->Backup_Method == 1)
file_bytes += (*subpart)->Backup_Size;
else
img_bytes += (*subpart)->Backup_Size;
}
}
}
} else {
gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
}
start_pos = end_pos + 1;
end_pos = Backup_List.find(";", start_pos);
}
}
if (partition_count == 0) {
gui_msg("no_partition_selected=No partitions selected for backup.");
return false;
}
total_bytes = file_bytes + img_bytes;
ProgressTracking progress(total_bytes);
gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
if (storage != NULL) {
free_space = storage->Free;
gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
} else {
gui_err("unable_locate_storage=Unable to locate storage device.");
return false;
}
DataManager::GetValue("tw_disable_free_space", disable_free_space_check);
if (!disable_free_space_check) {
if (free_space - (32 * 1024 * 1024) < total_bytes) {
// We require an extra 32MB just in case
gui_err("no_space=Not enough free space on storage.");
return false;
}
}
img_bytes_remaining = img_bytes;
file_bytes_remaining = file_bytes;
gui_msg("backup_started=[BACKUP STARTED]");
gui_msg(Msg("backup_folder= * Backup Folder: {1}")(Full_Backup_Path));
if (!TWFunc::Recursive_Mkdir(Full_Backup_Path)) {
gui_err("fail_backup_folder=Failed to make backup folder.");
return false;
}
DataManager::SetProgress(0.0);
start_pos = 0;
end_pos = Backup_List.find(";", start_pos);
while (end_pos != string::npos && start_pos < Backup_List.size()) {
if (stop_backup.get_value() != 0)
return -1;
backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
backup_part = Find_Partition_By_Path(backup_path);
if (backup_part != NULL) {
if (!Backup_Partition(backup_part, Full_Backup_Path, do_md5, &img_time, &file_time, &progress))
return false;
} else {
gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
}
start_pos = end_pos + 1;
end_pos = Backup_List.find(";", start_pos);
}
// Average BPS
if (img_time == 0)
img_time = 1;
if (file_time == 0)
file_time = 1;
int img_bps = (int)img_bytes / (int)img_time;
unsigned long long file_bps = file_bytes / (int)file_time;
if (file_bytes != 0)
gui_msg(Msg("avg_backup_fs=Average backup rate for file systems: {1} MB/sec")(file_bps / (1024 * 1024)));
if (img_bytes != 0)
gui_msg(Msg("avg_backup_img=Average backup rate for imaged drives: {1} MB/sec")(img_bps / (1024 * 1024)));
time(&total_stop);
int total_time = (int) difftime(total_stop, total_start);
uint64_t actual_backup_size = du.Get_Folder_Size(Full_Backup_Path);
actual_backup_size /= (1024LLU * 1024LLU);
int prev_img_bps, use_compression;
unsigned long long prev_file_bps;
DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
img_bps += (prev_img_bps * 4);
img_bps /= 5;
DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
if (use_compression)
DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
else
DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
file_bps += (prev_file_bps * 4);
file_bps /= 5;
DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
if (use_compression)
DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
else
DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
Update_System_Details();
UnMount_Main_Partitions();
gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
string backup_log = Full_Backup_Path + "recovery.log";
TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
tw_set_default_metadata(backup_log.c_str());
return true;
}
bool TWPartitionManager::Restore_Partition(TWPartition* Part, const string& Restore_Name, ProgressTracking *progress) {
time_t Start, Stop;
TWFunc::SetPerformanceMode(true);
time(&Start);
if (!Part->Restore(Restore_Name, progress)) {
TWFunc::SetPerformanceMode(false);
return false;
}
if (Part->Has_SubPartition) {
std::vector<TWPartition*>::iterator subpart;
for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == Part->Mount_Point) {
if (!(*subpart)->Restore(Restore_Name, progress)) {
TWFunc::SetPerformanceMode(false);
return false;
}
}
}
}
time(&Stop);
TWFunc::SetPerformanceMode(false);
gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(Part->Backup_Display_Name)((int)difftime(Stop, Start)));
return true;
}
int TWPartitionManager::Run_Restore(const string& Restore_Name) {
int check_md5, check, partition_count = 0;
TWPartition* restore_part = NULL;
time_t rStart, rStop;
time(&rStart);
string Restore_List, restore_path;
size_t start_pos = 0, end_pos;
unsigned long long total_restore_size = 0, already_restored_size = 0;
gui_msg("restore_started=[RESTORE STARTED]");
gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
if (!Mount_Current_Storage(true))
return false;
DataManager::GetValue(TW_SKIP_MD5_CHECK_VAR, check_md5);
if (check_md5 > 0) {
// Check MD5 files first before restoring to ensure that all of them match before starting a restore
TWFunc::GUI_Operation_Text(TW_VERIFY_MD5_TEXT, gui_parse_text("{@verifying_md5}"));
gui_msg("verifying_md5=Verifying MD5");
} else {
gui_msg("skip_md5=Skipping MD5 check based on user setting.");
}
gui_msg("calc_restore=Calculating restore details...");
DataManager::GetValue("tw_restore_selected", Restore_List);
if (!Restore_List.empty()) {
end_pos = Restore_List.find(";", start_pos);
while (end_pos != string::npos && start_pos < Restore_List.size()) {
restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
restore_part = Find_Partition_By_Path(restore_path);
if (restore_part != NULL) {
if (restore_part->Mount_Read_Only) {
gui_msg(Msg(msg::kError, "restore_read_only=Cannot restore {1} -- mounted read only.")(restore_part->Backup_Display_Name));
return false;
}
if (check_md5 > 0 && !restore_part->Check_MD5(Restore_Name))
return false;
partition_count++;
total_restore_size += restore_part->Get_Restore_Size(Restore_Name);
if (restore_part->Has_SubPartition) {
std::vector<TWPartition*>::iterator subpart;
for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == restore_part->Mount_Point) {
if (check_md5 > 0 && !(*subpart)->Check_MD5(Restore_Name))
return false;
total_restore_size += (*subpart)->Get_Restore_Size(Restore_Name);
}
}
}
} else {
gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
}
start_pos = end_pos + 1;
end_pos = Restore_List.find(";", start_pos);
}
}
if (partition_count == 0) {
gui_err("no_part_restore=No partitions selected for restore.");
return false;
}
gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(partition_count));
gui_msg(Msg("total_restore_size=Total restore size is {1}MB")(total_restore_size / 1048576));
DataManager::SetProgress(0.0);
ProgressTracking progress(total_restore_size);
start_pos = 0;
if (!Restore_List.empty()) {
end_pos = Restore_List.find(";", start_pos);
while (end_pos != string::npos && start_pos < Restore_List.size()) {
restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
restore_part = Find_Partition_By_Path(restore_path);
if (restore_part != NULL) {
partition_count++;
if (!Restore_Partition(restore_part, Restore_Name, &progress))
return false;
} else {
gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
}
start_pos = end_pos + 1;
end_pos = Restore_List.find(";", start_pos);
}
}
TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
Update_System_Details();
UnMount_Main_Partitions();
time(&rStop);
gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
DataManager::SetValue("tw_file_progress", "");
return true;
}
void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
// Start with the default values
string Restore_List;
bool get_date = true, check_encryption = true;
DataManager::SetValue("tw_restore_encrypted", 0);
DIR* d;
d = opendir(Restore_Name.c_str());
if (d == NULL)
{
gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
return;
}
struct dirent* de;
while ((de = readdir(d)) != NULL)
{
// Strip off three components
char str[256];
char* label;
char* fstype = NULL;
char* extn = NULL;
char* ptr;
strcpy(str, de->d_name);
if (strlen(str) <= 2)
continue;
if (get_date) {
char file_path[255];
struct stat st;
strcpy(file_path, Restore_Name.c_str());
strcat(file_path, "/");
strcat(file_path, str);
stat(file_path, &st);
string backup_date = ctime((const time_t*)(&st.st_mtime));
DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
get_date = false;
}
label = str;
ptr = label;
while (*ptr && *ptr != '.') ptr++;
if (*ptr == '.')
{
*ptr = 0x00;
ptr++;
fstype = ptr;
}
while (*ptr && *ptr != '.') ptr++;
if (*ptr == '.')