· 8 years ago · May 12, 2018, 02:58 PM
1/*
2 Copyright 2014 to 2017 TeamWin
3 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*/
18
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>
25#include <map>
26#include <vector>
27#include <dirent.h>
28#include <time.h>
29#include <errno.h>
30#include <fcntl.h>
31#include <zlib.h>
32#include <iostream>
33#include <iomanip>
34#include <sys/wait.h>
35#include <linux/fs.h>
36#include <sys/mount.h>
37
38#include <sys/poll.h>
39#include <sys/socket.h>
40#include <linux/types.h>
41#include <linux/netlink.h>
42
43#include "variables.h"
44#include "twcommon.h"
45#include "partitions.hpp"
46#include "data.hpp"
47#include "twrp-functions.hpp"
48#include "fixContexts.hpp"
49#include "exclude.hpp"
50#include "set_metadata.h"
51#include "tw_atomic.hpp"
52#include "gui/gui.hpp"
53#include "progresstracking.hpp"
54#include "twrpDigestDriver.hpp"
55#include "adbbu/libtwadbbu.hpp"
56
57#ifdef TW_HAS_MTP
58#include "mtp/mtp_MtpServer.hpp"
59#include "mtp/twrpMtp.hpp"
60#include "mtp/MtpMessage.hpp"
61#endif
62
63extern "C" {
64 #include "cutils/properties.h"
65 #include "gui/gui.h"
66}
67
68#ifdef TW_INCLUDE_CRYPTO
69 #include "crypto/lollipop/cryptfs.h"
70 #include "gui/rapidxml.hpp"
71 #include "gui/pages.hpp"
72 #ifdef TW_INCLUDE_FBE
73 #include "crypto/ext4crypt/Decrypt.h"
74 #endif
75 #ifdef TW_CRYPTO_USE_SYSTEM_VOLD
76 #include "crypto/vold_decrypt/vold_decrypt.h"
77 #endif
78#endif
79
80#ifdef AB_OTA_UPDATER
81#include <hardware/hardware.h>
82#include <hardware/boot_control.h>
83#endif
84
85extern bool datamedia;
86
87TWPartitionManager::TWPartitionManager(void) {
88 mtp_was_enabled = false;
89 mtp_write_fd = -1;
90 uevent_pfd.fd = -1;
91 stop_backup.set_value(0);
92#ifdef AB_OTA_UPDATER
93 char slot_suffix[PROPERTY_VALUE_MAX];
94 property_get("ro.boot.slot_suffix", slot_suffix, "error");
95 if (strcmp(slot_suffix, "error") == 0)
96 property_get("ro.boot.slot", slot_suffix, "error");
97 Active_Slot_Display = "";
98 if (strcmp(slot_suffix, "_a") == 0 || strcmp(slot_suffix, "a") == 0)
99 Set_Active_Slot("A");
100 else
101 Set_Active_Slot("B");
102#endif
103}
104
105int TWPartitionManager::Process_Fstab(string Fstab_Filename, bool Display_Error) {
106 FILE *fstabFile;
107 char fstab_line[MAX_FSTAB_LINE_LENGTH];
108 TWPartition* settings_partition = NULL;
109 TWPartition* andsec_partition = NULL;
110 unsigned int storageid = 1 << 16; // upper 16 bits are for physical storage device, we pretend to have only one
111 std::map<string, Flags_Map> twrp_flags;
112
113 fstabFile = fopen("/etc/twrp.flags", "rt");
114 if (fstabFile != NULL) {
115 LOGINFO("reading /etc/twrp.flags\n");
116 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
117 if (fstab_line[0] != '/')
118 continue;
119
120 size_t line_size = strlen(fstab_line);
121 if (fstab_line[line_size - 1] != '\n')
122 fstab_line[line_size] = '\n';
123 Flags_Map line_flags;
124 line_flags.Primary_Block_Device = "";
125 line_flags.Alternate_Block_Device = "";
126 line_flags.fstab_line = (char*)malloc(MAX_FSTAB_LINE_LENGTH);
127 if (!line_flags.fstab_line) {
128 LOGERR("malloc error on line_flags.fstab_line\n");
129 return false;
130 }
131 memcpy(line_flags.fstab_line, fstab_line, MAX_FSTAB_LINE_LENGTH);
132 bool found_separator = false;
133 char *fs_loc = NULL;
134 char *block_loc = NULL;
135 char *flags_loc = NULL;
136 size_t index, item_index = 0;
137 for (index = 0; index < line_size; index++) {
138 if (fstab_line[index] <= 32) {
139 fstab_line[index] = '\0';
140 found_separator = true;
141 } else if (found_separator) {
142 if (item_index == 0) {
143 fs_loc = fstab_line + index;
144 } else if (item_index == 1) {
145 block_loc = fstab_line + index;
146 } else if (item_index > 1) {
147 char *ptr = fstab_line + index;
148 if (*ptr == '/') {
149 line_flags.Alternate_Block_Device = ptr;
150 } else if (strlen(ptr) > strlen("flags=") && strncmp(ptr, "flags=", strlen("flags=")) == 0) {
151 flags_loc = ptr;
152 // Once we find the flags=, we're done scanning the line
153 break;
154 }
155 }
156 found_separator = false;
157 item_index++;
158 }
159 }
160 if (block_loc)
161 line_flags.Primary_Block_Device = block_loc;
162 if (fs_loc)
163 line_flags.File_System = fs_loc;
164 if (flags_loc)
165 line_flags.Flags = flags_loc;
166 string Mount_Point = fstab_line;
167 twrp_flags[Mount_Point] = line_flags;
168 memset(fstab_line, 0, sizeof(fstab_line));
169 }
170 fclose(fstabFile);
171 }
172
173 fstabFile = fopen(Fstab_Filename.c_str(), "rt");
174 if (fstabFile == NULL) {
175 LOGERR("Critical Error: Unable to open fstab at '%s'.\n", Fstab_Filename.c_str());
176 return false;
177 } else
178 LOGINFO("Reading %s\n", Fstab_Filename.c_str());
179
180 while (fgets(fstab_line, sizeof(fstab_line), fstabFile) != NULL) {
181 if (fstab_line[0] != '/')
182 continue;
183
184 if (strstr(fstab_line, "swap"))
185 continue; // Skip swap in recovery
186
187 size_t line_size = strlen(fstab_line);
188 if (fstab_line[line_size - 1] != '\n')
189 fstab_line[line_size] = '\n';
190
191 TWPartition* partition = new TWPartition();
192 if (partition->Process_Fstab_Line(fstab_line, Display_Error, &twrp_flags))
193 Partitions.push_back(partition);
194 else
195 delete partition;
196
197 memset(fstab_line, 0, sizeof(fstab_line));
198 }
199 fclose(fstabFile);
200
201 if (twrp_flags.size() > 0) {
202 LOGINFO("Processing remaining twrp.flags\n");
203 // Add any items from twrp.flags that did not exist in the recovery.fstab
204 for (std::map<string, Flags_Map>::iterator mapit=twrp_flags.begin(); mapit!=twrp_flags.end(); mapit++) {
205 if (Find_Partition_By_Path(mapit->first) == NULL) {
206 TWPartition* partition = new TWPartition();
207 if (partition->Process_Fstab_Line(mapit->second.fstab_line, Display_Error, NULL))
208 Partitions.push_back(partition);
209 else
210 delete partition;
211 }
212 if (mapit->second.fstab_line)
213 free(mapit->second.fstab_line);
214 mapit->second.fstab_line = NULL;
215 }
216 }
217 LOGINFO("Done processing fstab files\n");
218
219 std::vector<TWPartition*>::iterator iter;
220 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
221 (*iter)->Partition_Post_Processing(Display_Error);
222
223 if ((*iter)->Is_Storage) {
224 ++storageid;
225 (*iter)->MTP_Storage_ID = storageid;
226 }
227
228 if (!settings_partition && (*iter)->Is_Settings_Storage && (*iter)->Is_Present)
229 settings_partition = (*iter);
230 else
231 (*iter)->Is_Settings_Storage = false;
232
233 if (!andsec_partition && (*iter)->Has_Android_Secure && (*iter)->Is_Present)
234 andsec_partition = (*iter);
235 else
236 (*iter)->Has_Android_Secure = false;
237 }
238
239 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) {
240 // Attempt to automatically identify /data/media emulated storage devices
241 TWPartition* Dat = Find_Partition_By_Path("/data");
242 if (Dat) {
243 LOGINFO("Using automatic handling for /data/media emulated storage device.\n");
244 datamedia = true;
245 Dat->Setup_Data_Media();
246 settings_partition = Dat;
247 // Since /data was not considered a storage partition earlier, we still need to assign an MTP ID
248 ++storageid;
249 Dat->MTP_Storage_ID = storageid;
250 }
251 }
252 if (!settings_partition) {
253 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
254 if ((*iter)->Is_Storage) {
255 settings_partition = (*iter);
256 break;
257 }
258 }
259 if (!settings_partition)
260 LOGERR("Unable to locate storage partition for storing settings file.\n");
261 }
262 if (!Write_Fstab()) {
263 if (Display_Error)
264 LOGERR("Error creating fstab\n");
265 else
266 LOGINFO("Error creating fstab\n");
267 }
268
269 if (andsec_partition) {
270 Setup_Android_Secure_Location(andsec_partition);
271 } else if (settings_partition) {
272 Setup_Android_Secure_Location(settings_partition);
273 }
274 if (settings_partition) {
275 Setup_Settings_Storage_Partition(settings_partition);
276 }
277#ifdef TW_INCLUDE_CRYPTO
278 TWPartition* Decrypt_Data = Find_Partition_By_Path("/data");
279 if (Decrypt_Data && Decrypt_Data->Is_Encrypted && !Decrypt_Data->Is_Decrypted) {
280 if (Decrypt_Data->Is_FBE) {
281 if (DataManager::GetIntValue(TW_CRYPTO_PWTYPE) == 0) {
282 if (Decrypt_Device("!") == 0) {
283 gui_msg("decrypt_success=Successfully decrypted with default password.");
284 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
285 } else {
286 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
287 }
288 }
289 } else {
290 int password_type = cryptfs_get_password_type();
291 if (password_type == CRYPT_TYPE_DEFAULT) {
292 LOGINFO("Device is encrypted with the default password, attempting to decrypt.\n");
293 if (Decrypt_Device("default_password") == 0) {
294 gui_msg("decrypt_success=Successfully decrypted with default password.");
295 DataManager::SetValue(TW_IS_ENCRYPTED, 0);
296 } else {
297 gui_err("unable_to_decrypt=Unable to decrypt with default password.");
298 }
299 } else {
300 DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
301 }
302 }
303 }
304 if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) && Decrypt_Data->Mount(false)) {
305 Decrypt_Adopted();
306 }
307#endif
308 Update_System_Details();
309 UnMount_Main_Partitions();
310#ifdef AB_OTA_UPDATER
311 DataManager::SetValue("tw_active_slot", Get_Active_Slot_Display());
312#endif
313 setup_uevent();
314 return true;
315}
316
317int TWPartitionManager::Write_Fstab(void) {
318 FILE *fp;
319 std::vector<TWPartition*>::iterator iter;
320 string Line;
321
322 fp = fopen("/etc/fstab", "w");
323 if (fp == NULL) {
324 LOGINFO("Can not open /etc/fstab.\n");
325 return false;
326 }
327 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
328 if ((*iter)->Can_Be_Mounted) {
329 Line = (*iter)->Actual_Block_Device + " " + (*iter)->Mount_Point + " " + (*iter)->Current_File_System + " rw 0 0\n";
330 fputs(Line.c_str(), fp);
331 }
332 // Handle subpartition tracking
333 if ((*iter)->Is_SubPartition) {
334 TWPartition* ParentPartition = Find_Partition_By_Path((*iter)->SubPartition_Of);
335 if (ParentPartition)
336 ParentPartition->Has_SubPartition = true;
337 else
338 LOGERR("Unable to locate parent partition '%s' of '%s'\n", (*iter)->SubPartition_Of.c_str(), (*iter)->Mount_Point.c_str());
339 }
340 }
341 fclose(fp);
342 return true;
343}
344
345void TWPartitionManager::Setup_Settings_Storage_Partition(TWPartition* Part) {
346 DataManager::SetValue("tw_settings_path", Part->Storage_Path);
347 DataManager::SetValue("tw_storage_path", Part->Storage_Path);
348 LOGINFO("Settings storage is '%s'\n", Part->Storage_Path.c_str());
349}
350
351void TWPartitionManager::Setup_Android_Secure_Location(TWPartition* Part) {
352 if (Part->Has_Android_Secure)
353 Part->Setup_AndSec();
354 else if (!datamedia)
355 Part->Setup_AndSec();
356}
357
358void TWPartitionManager::Output_Partition_Logging(void) {
359 std::vector<TWPartition*>::iterator iter;
360
361 printf("\n\nPartition Logs:\n");
362 for (iter = Partitions.begin(); iter != Partitions.end(); iter++)
363 Output_Partition((*iter));
364}
365
366void TWPartitionManager::Output_Partition(TWPartition* Part) {
367 unsigned long long mb = 1048576;
368
369 printf("%s | %s | Size: %iMB", Part->Mount_Point.c_str(), Part->Actual_Block_Device.c_str(), (int)(Part->Size / mb));
370 if (Part->Can_Be_Mounted) {
371 printf(" Used: %iMB Free: %iMB Backup Size: %iMB", (int)(Part->Used / mb), (int)(Part->Free / mb), (int)(Part->Backup_Size / mb));
372 }
373 printf("\n Flags: ");
374 if (Part->Can_Be_Mounted)
375 printf("Can_Be_Mounted ");
376 if (Part->Can_Be_Wiped)
377 printf("Can_Be_Wiped ");
378 if (Part->Use_Rm_Rf)
379 printf("Use_Rm_Rf ");
380 if (Part->Can_Be_Backed_Up)
381 printf("Can_Be_Backed_Up ");
382 if (Part->Wipe_During_Factory_Reset)
383 printf("Wipe_During_Factory_Reset ");
384 if (Part->Wipe_Available_in_GUI)
385 printf("Wipe_Available_in_GUI ");
386 if (Part->Is_SubPartition)
387 printf("Is_SubPartition ");
388 if (Part->Has_SubPartition)
389 printf("Has_SubPartition ");
390 if (Part->Removable)
391 printf("Removable ");
392 if (Part->Is_Present)
393 printf("IsPresent ");
394 if (Part->Can_Be_Encrypted)
395 printf("Can_Be_Encrypted ");
396 if (Part->Is_Encrypted)
397 printf("Is_Encrypted ");
398 if (Part->Is_Decrypted)
399 printf("Is_Decrypted ");
400 if (Part->Has_Data_Media)
401 printf("Has_Data_Media ");
402 if (Part->Can_Encrypt_Backup)
403 printf("Can_Encrypt_Backup ");
404 if (Part->Use_Userdata_Encryption)
405 printf("Use_Userdata_Encryption ");
406 if (Part->Has_Android_Secure)
407 printf("Has_Android_Secure ");
408 if (Part->Is_Storage)
409 printf("Is_Storage ");
410 if (Part->Is_Settings_Storage)
411 printf("Is_Settings_Storage ");
412 if (Part->Ignore_Blkid)
413 printf("Ignore_Blkid ");
414 if (Part->Retain_Layout_Version)
415 printf("Retain_Layout_Version ");
416 if (Part->Mount_To_Decrypt)
417 printf("Mount_To_Decrypt ");
418 if (Part->Can_Flash_Img)
419 printf("Can_Flash_Img ");
420 if (Part->Is_Adopted_Storage)
421 printf("Is_Adopted_Storage ");
422 if (Part->SlotSelect)
423 printf("SlotSelect ");
424 if (Part->Mount_Read_Only)
425 printf("Mount_Read_Only ");
426 printf("\n");
427 if (!Part->SubPartition_Of.empty())
428 printf(" SubPartition_Of: %s\n", Part->SubPartition_Of.c_str());
429 if (!Part->Symlink_Path.empty())
430 printf(" Symlink_Path: %s\n", Part->Symlink_Path.c_str());
431 if (!Part->Symlink_Mount_Point.empty())
432 printf(" Symlink_Mount_Point: %s\n", Part->Symlink_Mount_Point.c_str());
433 if (!Part->Primary_Block_Device.empty())
434 printf(" Primary_Block_Device: %s\n", Part->Primary_Block_Device.c_str());
435 if (!Part->Alternate_Block_Device.empty())
436 printf(" Alternate_Block_Device: %s\n", Part->Alternate_Block_Device.c_str());
437 if (!Part->Decrypted_Block_Device.empty())
438 printf(" Decrypted_Block_Device: %s\n", Part->Decrypted_Block_Device.c_str());
439 if (!Part->Crypto_Key_Location.empty() && Part->Crypto_Key_Location != "footer")
440 printf(" Crypto_Key_Location: %s\n", Part->Crypto_Key_Location.c_str());
441 if (Part->Length != 0)
442 printf(" Length: %i\n", Part->Length);
443 if (!Part->Display_Name.empty())
444 printf(" Display_Name: %s\n", Part->Display_Name.c_str());
445 if (!Part->Storage_Name.empty())
446 printf(" Storage_Name: %s\n", Part->Storage_Name.c_str());
447 if (!Part->Backup_Path.empty())
448 printf(" Backup_Path: %s\n", Part->Backup_Path.c_str());
449 if (!Part->Backup_Name.empty())
450 printf(" Backup_Name: %s\n", Part->Backup_Name.c_str());
451 if (!Part->Backup_Display_Name.empty())
452 printf(" Backup_Display_Name: %s\n", Part->Backup_Display_Name.c_str());
453 if (!Part->Backup_FileName.empty())
454 printf(" Backup_FileName: %s\n", Part->Backup_FileName.c_str());
455 if (!Part->Storage_Path.empty())
456 printf(" Storage_Path: %s\n", Part->Storage_Path.c_str());
457 if (!Part->Current_File_System.empty())
458 printf(" Current_File_System: %s\n", Part->Current_File_System.c_str());
459 if (!Part->Fstab_File_System.empty())
460 printf(" Fstab_File_System: %s\n", Part->Fstab_File_System.c_str());
461 if (Part->Format_Block_Size != 0)
462 printf(" Format_Block_Size: %lu\n", Part->Format_Block_Size);
463 if (!Part->MTD_Name.empty())
464 printf(" MTD_Name: %s\n", Part->MTD_Name.c_str());
465 printf(" Backup_Method: %s\n", Part->Backup_Method_By_Name().c_str());
466 if (Part->Mount_Flags || !Part->Mount_Options.empty())
467 printf(" Mount_Flags: %i, Mount_Options: %s\n", Part->Mount_Flags, Part->Mount_Options.c_str());
468 if (Part->MTP_Storage_ID)
469 printf(" MTP_Storage_ID: %i\n", Part->MTP_Storage_ID);
470 printf("\n");
471}
472
473int TWPartitionManager::Mount_By_Path(string Path, bool Display_Error) {
474 std::vector<TWPartition*>::iterator iter;
475 int ret = false;
476 bool found = false;
477 string Local_Path = TWFunc::Get_Root_Path(Path);
478
479 if (Local_Path == "/tmp" || Local_Path == "/")
480 return true;
481
482 // Iterate through all partitions
483 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
484 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
485 ret = (*iter)->Mount(Display_Error);
486 found = true;
487 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
488 (*iter)->Mount(Display_Error);
489 }
490 }
491 if (found) {
492 return ret;
493 } else if (Display_Error) {
494 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
495 } else {
496 LOGINFO("Mount: Unable to find partition for path '%s'\n", Local_Path.c_str());
497 }
498 return false;
499}
500
501int TWPartitionManager::UnMount_By_Path(string Path, bool Display_Error) {
502 std::vector<TWPartition*>::iterator iter;
503 int ret = false;
504 bool found = false;
505 string Local_Path = TWFunc::Get_Root_Path(Path);
506
507 // Iterate through all partitions
508 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
509 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
510 ret = (*iter)->UnMount(Display_Error);
511 found = true;
512 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
513 (*iter)->UnMount(Display_Error);
514 }
515 }
516 if (found) {
517 return ret;
518 } else if (Display_Error) {
519 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
520 } else {
521 LOGINFO("UnMount: Unable to find partition for path '%s'\n", Local_Path.c_str());
522 }
523 return false;
524}
525
526int TWPartitionManager::Is_Mounted_By_Path(string Path) {
527 TWPartition* Part = Find_Partition_By_Path(Path);
528
529 if (Part)
530 return Part->Is_Mounted();
531 else
532 LOGINFO("Is_Mounted: Unable to find partition for path '%s'\n", Path.c_str());
533 return false;
534}
535
536int TWPartitionManager::Mount_Current_Storage(bool Display_Error) {
537 string current_storage_path = DataManager::GetCurrentStoragePath();
538
539 if (Mount_By_Path(current_storage_path, Display_Error)) {
540 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
541 if (FreeStorage)
542 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
543 return true;
544 }
545 return false;
546}
547
548int TWPartitionManager::Mount_Settings_Storage(bool Display_Error) {
549 return Mount_By_Path(DataManager::GetSettingsStoragePath(), Display_Error);
550}
551
552TWPartition* TWPartitionManager::Find_Partition_By_Path(const string& Path) {
553 std::vector<TWPartition*>::iterator iter;
554 string Local_Path = TWFunc::Get_Root_Path(Path);
555
556 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
557 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path))
558 return (*iter);
559 }
560 return NULL;
561}
562
563TWPartition* TWPartitionManager::Find_Partition_By_Block_Device(const string& Block_Device) {
564 std::vector<TWPartition*>::iterator iter;
565
566 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
567 if ((*iter)->Primary_Block_Device == Block_Device || (!(*iter)->Actual_Block_Device.empty() && (*iter)->Actual_Block_Device == Block_Device))
568 return (*iter);
569 }
570 return NULL;
571}
572
573int TWPartitionManager::Check_Backup_Name(bool Display_Error) {
574 // Check the backup name to ensure that it is the correct size and contains only valid characters
575 // and that a backup with that name doesn't already exist
576 char backup_name[MAX_BACKUP_NAME_LEN];
577 char backup_loc[255], tw_image_dir[255];
578 int copy_size;
579 int index, cur_char;
580 string Backup_Name, Backup_Loc;
581
582 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
583 copy_size = Backup_Name.size();
584 // Check size
585 if (copy_size > MAX_BACKUP_NAME_LEN) {
586 if (Display_Error)
587 gui_err("backup_name_len=Backup name is too long.");
588 return -2;
589 }
590
591 // Check each character
592 strncpy(backup_name, Backup_Name.c_str(), copy_size);
593 if (copy_size == 1 && strncmp(backup_name, "0", 1) == 0)
594 return 0; // A "0" (zero) means to use the current timestamp for the backup name
595 for (index=0; index<copy_size; index++) {
596 cur_char = (int)backup_name[index];
597 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) {
598 // These are valid characters
599 // Numbers
600 // Upper case letters
601 // Lower case letters
602 // Space
603 // and -_.{}[]
604 } else {
605 if (Display_Error)
606 gui_msg(Msg(msg::kError, "backup_name_invalid=Backup name '{1}' contains invalid character: '{1}'")(Backup_Name)((char)cur_char));
607 return -3;
608 }
609 }
610
611 // Check to make sure that a backup with this name doesn't already exist
612 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Loc);
613 strcpy(backup_loc, Backup_Loc.c_str());
614 sprintf(tw_image_dir,"%s/%s", backup_loc, Backup_Name.c_str());
615 if (TWFunc::Path_Exists(tw_image_dir)) {
616 if (Display_Error)
617 gui_err("backup_name_exists=A backup with that name already exists!");
618
619 return -4;
620 }
621 // No problems found, return 0
622 return 0;
623}
624
625bool TWPartitionManager::Backup_Partition(PartitionSettings *part_settings) {
626 time_t start, stop;
627 int use_compression;
628 string backup_log = part_settings->Backup_Folder + "/recovery.log";
629
630 if (part_settings->Part == NULL)
631 return true;
632
633 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
634
635 TWFunc::SetPerformanceMode(true);
636 time(&start);
637
638 if (part_settings->Part->Backup(part_settings, &tar_fork_pid)) {
639 sync();
640 sync();
641 string Full_Filename = part_settings->Backup_Folder + "/" + part_settings->Part->Backup_FileName;
642 if (!part_settings->adbbackup && part_settings->generate_digest) {
643 if (!twrpDigestDriver::Make_Digest(Full_Filename))
644 goto backup_error;
645 }
646
647 if (part_settings->Part->Has_SubPartition) {
648 std::vector<TWPartition*>::iterator subpart;
649 TWPartition *parentPart = part_settings->Part;
650
651 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
652 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
653 part_settings->Part = *subpart;
654 if (!(*subpart)->Backup(part_settings, &tar_fork_pid)) {
655 goto backup_error;
656 }
657 sync();
658 sync();
659 if (!part_settings->adbbackup && part_settings->generate_digest) {
660 if (!twrpDigestDriver::Make_Digest(Full_Filename)) {
661 goto backup_error;
662 }
663 }
664 }
665 }
666 }
667
668 time(&stop);
669 int backup_time = (int) difftime(stop, start);
670 LOGINFO("Partition Backup time: %d\n", backup_time);
671
672 if (part_settings->Part->Backup_Method == BM_FILES) {
673 part_settings->file_time += backup_time;
674 } else {
675 part_settings->img_time += backup_time;
676
677 }
678
679 TWFunc::SetPerformanceMode(false);
680 return true;
681 }
682backup_error:
683 Clean_Backup_Folder(part_settings->Backup_Folder);
684 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
685 tw_set_default_metadata(backup_log.c_str());
686 TWFunc::SetPerformanceMode(false);
687 return false;
688}
689
690void TWPartitionManager::Clean_Backup_Folder(string Backup_Folder) {
691 DIR *d = opendir(Backup_Folder.c_str());
692 struct dirent *p;
693 int r;
694 vector<string> ext;
695
696 //extensions we should delete when cleaning
697 ext.push_back("win");
698 ext.push_back("md5");
699 ext.push_back("sha2");
700 ext.push_back("info");
701
702 gui_msg("backup_clean=Backup Failed. Cleaning Backup Folder.");
703
704 if (d == NULL) {
705 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Backup_Folder)(strerror(errno)));
706 return;
707 }
708
709 while ((p = readdir(d))) {
710 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
711 continue;
712
713 string path = Backup_Folder + "/" + p->d_name;
714
715 size_t dot = path.find_last_of(".") + 1;
716 for (vector<string>::const_iterator i = ext.begin(); i != ext.end(); ++i) {
717 if (path.substr(dot) == *i) {
718 r = unlink(path.c_str());
719 if (r != 0)
720 LOGINFO("Unable to unlink '%s: %s'\n", path.c_str(), strerror(errno));
721 }
722 }
723 }
724 closedir(d);
725}
726
727int TWPartitionManager::Check_Backup_Cancel() {
728 return stop_backup.get_value();
729}
730
731int TWPartitionManager::Cancel_Backup() {
732 string Backup_Folder, Backup_Name, Full_Backup_Path;
733
734 stop_backup.set_value(1);
735
736 if (tar_fork_pid != 0) {
737 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
738 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, Backup_Folder);
739 Full_Backup_Path = Backup_Folder + "/" + Backup_Name;
740 LOGINFO("Killing pid: %d\n", tar_fork_pid);
741 kill(tar_fork_pid, SIGUSR2);
742 while (kill(tar_fork_pid, 0) == 0) {
743 usleep(1000);
744 }
745 LOGINFO("Backup_Run stopped and returning false, backup cancelled.\n");
746 LOGINFO("Removing directory %s\n", Full_Backup_Path.c_str());
747 TWFunc::removeDir(Full_Backup_Path, false);
748 tar_fork_pid = 0;
749 }
750
751 return 0;
752}
753
754int TWPartitionManager::Run_Backup(bool adbbackup) {
755 PartitionSettings part_settings;
756 int partition_count = 0, disable_free_space_check = 0, skip_digest = 0;
757 int gui_adb_backup;
758 string Backup_Name, Backup_List, backup_path;
759 unsigned long long total_bytes = 0, free_space = 0;
760 TWPartition* storage = NULL;
761 std::vector<TWPartition*>::iterator subpart;
762 struct tm *t;
763 time_t seconds, total_start, total_stop;
764 size_t start_pos = 0, end_pos = 0;
765 stop_backup.set_value(0);
766 seconds = time(0);
767 t = localtime(&seconds);
768
769 part_settings.img_bytes_remaining = 0;
770 part_settings.file_bytes_remaining = 0;
771 part_settings.img_time = 0;
772 part_settings.file_time = 0;
773 part_settings.img_bytes = 0;
774 part_settings.file_bytes = 0;
775 part_settings.PM_Method = PM_BACKUP;
776
777 part_settings.adbbackup = adbbackup;
778 time(&total_start);
779
780 Update_System_Details();
781
782 if (!Mount_Current_Storage(true))
783 return false;
784
785 DataManager::GetValue(TW_SKIP_DIGEST_GENERATE_VAR, skip_digest);
786 if (skip_digest == 0)
787 part_settings.generate_digest = true;
788 else
789 part_settings.generate_digest = false;
790
791 DataManager::GetValue(TW_BACKUPS_FOLDER_VAR, part_settings.Backup_Folder);
792 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
793 if (Backup_Name == gui_lookup("curr_date", "(Current Date)")) {
794 Backup_Name = TWFunc::Get_Current_Date();
795 } else if (Backup_Name == gui_lookup("auto_generate", "(Auto Generate)") || Backup_Name == "0" || Backup_Name.empty()) {
796 TWFunc::Auto_Generate_Backup_Name();
797 DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
798 }
799
800 LOGINFO("Backup Name is: '%s'\n", Backup_Name.c_str());
801 part_settings.Backup_Folder = part_settings.Backup_Folder + "/" + Backup_Name;
802
803 LOGINFO("Backup_Folder is: '%s'\n", part_settings.Backup_Folder.c_str());
804
805 LOGINFO("Calculating backup details...\n");
806 DataManager::GetValue("tw_backup_list", Backup_List);
807 if (!Backup_List.empty()) {
808 end_pos = Backup_List.find(";", start_pos);
809 while (end_pos != string::npos && start_pos < Backup_List.size()) {
810 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
811 part_settings.Part = Find_Partition_By_Path(backup_path);
812 if (part_settings.Part != NULL) {
813 partition_count++;
814 if (part_settings.Part->Backup_Method == BM_FILES)
815 part_settings.file_bytes += part_settings.Part->Backup_Size;
816 else
817 part_settings.img_bytes += part_settings.Part->Backup_Size;
818 if (part_settings.Part->Has_SubPartition) {
819 std::vector<TWPartition*>::iterator subpart;
820
821 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
822 if ((*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == part_settings.Part->Mount_Point) {
823 partition_count++;
824 if ((*subpart)->Backup_Method == BM_FILES)
825 part_settings.file_bytes += (*subpart)->Backup_Size;
826 else
827 part_settings.img_bytes += (*subpart)->Backup_Size;
828 }
829 }
830 }
831 } else {
832 gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
833 }
834 start_pos = end_pos + 1;
835 end_pos = Backup_List.find(";", start_pos);
836 }
837 }
838
839 if (partition_count == 0) {
840 gui_msg("no_partition_selected=No partitions selected for backup.");
841 return false;
842 }
843 if (adbbackup) {
844 if (twadbbu::Write_ADB_Stream_Header(partition_count) == false) {
845 return false;
846 }
847 }
848 total_bytes = part_settings.file_bytes + part_settings.img_bytes;
849 ProgressTracking progress(total_bytes);
850 part_settings.progress = &progress;
851
852 gui_msg(Msg("total_partitions_backup= * Total number of partitions to back up: {1}")(partition_count));
853 gui_msg(Msg("total_backup_size= * Total size of all data: {1}MB")(total_bytes / 1024 / 1024));
854 storage = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
855 if (storage != NULL) {
856 free_space = storage->Free;
857 gui_msg(Msg("available_space= * Available space: {1}MB")(free_space / 1024 / 1024));
858 } else {
859 gui_err("unable_locate_storage=Unable to locate storage device.");
860 return false;
861 }
862
863 DataManager::GetValue(TW_DISABLE_FREE_SPACE_VAR, disable_free_space_check);
864
865 if (adbbackup)
866 disable_free_space_check = true;
867
868 if (!disable_free_space_check) {
869 if (free_space - (32 * 1024 * 1024) < total_bytes) {
870 // We require an extra 32MB just in case
871 gui_err("no_space=Not enough free space on storage.");
872 return false;
873 }
874 }
875 part_settings.img_bytes_remaining = part_settings.img_bytes;
876 part_settings.file_bytes_remaining = part_settings.file_bytes;
877
878 gui_msg("backup_started=[BACKUP STARTED]");
879 gui_msg(Msg("backup_folder= * Backup Folder: {1}")(part_settings.Backup_Folder));
880 if (!TWFunc::Recursive_Mkdir(part_settings.Backup_Folder)) {
881 gui_err("fail_backup_folder=Failed to make backup folder.");
882 return false;
883 }
884
885 DataManager::SetProgress(0.0);
886
887 start_pos = 0;
888 end_pos = Backup_List.find(";", start_pos);
889 while (end_pos != string::npos && start_pos < Backup_List.size()) {
890 if (stop_backup.get_value() != 0)
891 return -1;
892 backup_path = Backup_List.substr(start_pos, end_pos - start_pos);
893 part_settings.Part = Find_Partition_By_Path(backup_path);
894 if (part_settings.Part != NULL) {
895 if (!Backup_Partition(&part_settings))
896 return false;
897 } else {
898 gui_msg(Msg(msg::kError, "unable_to_locate_partition=Unable to locate '{1}' partition for backup calculations.")(backup_path));
899 }
900 start_pos = end_pos + 1;
901 end_pos = Backup_List.find(";", start_pos);
902 }
903
904 // Average BPS
905 if (part_settings.img_time == 0)
906 part_settings.img_time = 1;
907 if (part_settings.file_time == 0)
908 part_settings.file_time = 1;
909 int img_bps = (int)part_settings.img_bytes / (int)part_settings.img_time;
910 unsigned long long file_bps = part_settings.file_bytes / (int)part_settings.file_time;
911
912 if (part_settings.file_bytes != 0)
913 gui_msg(Msg("avg_backup_fs=Average backup rate for file systems: {1} MB/sec")(file_bps / (1024 * 1024)));
914 if (part_settings.img_bytes != 0)
915 gui_msg(Msg("avg_backup_img=Average backup rate for imaged drives: {1} MB/sec")(img_bps / (1024 * 1024)));
916
917 time(&total_stop);
918 int total_time = (int) difftime(total_stop, total_start);
919
920 uint64_t actual_backup_size;
921 if (!adbbackup) {
922 TWExclude twe;
923 actual_backup_size = twe.Get_Folder_Size(part_settings.Backup_Folder);
924 } else
925 actual_backup_size = part_settings.file_bytes + part_settings.img_bytes;
926 actual_backup_size /= (1024LLU * 1024LLU);
927
928 int prev_img_bps = 0, use_compression = 0;
929 unsigned long long prev_file_bps = 0;
930 DataManager::GetValue(TW_BACKUP_AVG_IMG_RATE, prev_img_bps);
931 img_bps += (prev_img_bps * 4);
932 img_bps /= 5;
933
934 DataManager::GetValue(TW_USE_COMPRESSION_VAR, use_compression);
935 if (use_compression)
936 DataManager::GetValue(TW_BACKUP_AVG_FILE_COMP_RATE, prev_file_bps);
937 else
938 DataManager::GetValue(TW_BACKUP_AVG_FILE_RATE, prev_file_bps);
939 file_bps += (prev_file_bps * 4);
940 file_bps /= 5;
941
942 DataManager::SetValue(TW_BACKUP_AVG_IMG_RATE, img_bps);
943 if (use_compression)
944 DataManager::SetValue(TW_BACKUP_AVG_FILE_COMP_RATE, file_bps);
945 else
946 DataManager::SetValue(TW_BACKUP_AVG_FILE_RATE, file_bps);
947
948 gui_msg(Msg("total_backed_size=[{1} MB TOTAL BACKED UP]")(actual_backup_size));
949 Update_System_Details();
950 UnMount_Main_Partitions();
951 gui_msg(Msg(msg::kHighlight, "backup_completed=[BACKUP COMPLETED IN {1} SECONDS]")(total_time)); // the end
952 string backup_log = part_settings.Backup_Folder + "/recovery.log";
953 TWFunc::copy_file("/tmp/recovery.log", backup_log, 0644);
954 tw_set_default_metadata(backup_log.c_str());
955
956 if (part_settings.adbbackup) {
957 if (twadbbu::Write_ADB_Stream_Trailer() == false) {
958 return false;
959 }
960 }
961 part_settings.adbbackup = false;
962 DataManager::SetValue("tw_enable_adb_backup", 0);
963
964 return true;
965}
966
967bool TWPartitionManager::Restore_Partition(PartitionSettings *part_settings) {
968 time_t Start, Stop;
969
970 if (part_settings->adbbackup) {
971 std::string partName = part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win";
972 LOGINFO("setting backup name: %s\n", partName.c_str());
973 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
974 }
975
976 TWFunc::SetPerformanceMode(true);
977
978 time(&Start);
979
980 if (!part_settings->Part->Restore(part_settings)) {
981 TWFunc::SetPerformanceMode(false);
982 return false;
983 }
984 if (part_settings->Part->Has_SubPartition && !part_settings->adbbackup) {
985 std::vector<TWPartition*>::iterator subpart;
986 TWPartition *parentPart = part_settings->Part;
987
988 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
989 part_settings->Part = *subpart;
990 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
991 part_settings->Part = (*subpart);
992 part_settings->Part->Set_Backup_FileName(part_settings->Part->Backup_Name + "." + part_settings->Part->Current_File_System + ".win");
993 if (!(*subpart)->Restore(part_settings)) {
994 TWFunc::SetPerformanceMode(false);
995 return false;
996 }
997 }
998 }
999 }
1000 time(&Stop);
1001 TWFunc::SetPerformanceMode(false);
1002 gui_msg(Msg("restore_part_done=[{1} done ({2} seconds)]")(part_settings->Part->Backup_Display_Name)((int)difftime(Stop, Start)));
1003
1004 return true;
1005}
1006
1007int TWPartitionManager::Run_Restore(const string& Restore_Name) {
1008 PartitionSettings part_settings;
1009 int check_digest;
1010
1011 time_t rStart, rStop;
1012 time(&rStart);
1013 string Restore_List, restore_path;
1014 size_t start_pos = 0, end_pos;
1015
1016 part_settings.Backup_Folder = Restore_Name;
1017 part_settings.Part = NULL;
1018 part_settings.partition_count = 0;
1019 part_settings.total_restore_size = 0;
1020 part_settings.adbbackup = false;
1021 part_settings.PM_Method = PM_RESTORE;
1022
1023 gui_msg("restore_started=[RESTORE STARTED]");
1024 gui_msg(Msg("restore_folder=Restore folder: '{1}'")(Restore_Name));
1025
1026 if (!Mount_Current_Storage(true))
1027 return false;
1028
1029 DataManager::GetValue(TW_SKIP_DIGEST_CHECK_VAR, check_digest);
1030 if (check_digest > 0) {
1031 // Check Digest files first before restoring to ensure that all of them match before starting a restore
1032 TWFunc::GUI_Operation_Text(TW_VERIFY_DIGEST_TEXT, gui_parse_text("{@verifying_digest}"));
1033 gui_msg("verifying_digest=Verifying Digest");
1034 } else {
1035 gui_msg("skip_digest=Skipping Digest check based on user setting.");
1036 }
1037 gui_msg("calc_restore=Calculating restore details...");
1038 DataManager::GetValue("tw_restore_selected", Restore_List);
1039
1040 if (!Restore_List.empty()) {
1041 end_pos = Restore_List.find(";", start_pos);
1042 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1043 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
1044 part_settings.Part = Find_Partition_By_Path(restore_path);
1045 if (part_settings.Part != NULL) {
1046 if (part_settings.Part->Mount_Read_Only) {
1047 gui_msg(Msg(msg::kError, "restore_read_only=Cannot restore {1} -- mounted read only.")(part_settings.Part->Backup_Display_Name));
1048 return false;
1049 }
1050
1051 string Full_Filename = part_settings.Backup_Folder + "/" + part_settings.Part->Backup_FileName;
1052
1053 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
1054 return false;
1055 part_settings.partition_count++;
1056 part_settings.total_restore_size += part_settings.Part->Get_Restore_Size(&part_settings);
1057 if (part_settings.Part->Has_SubPartition) {
1058 TWPartition *parentPart = part_settings.Part;
1059 std::vector<TWPartition*>::iterator subpart;
1060
1061 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
1062 part_settings.Part = *subpart;
1063 if ((*subpart)->Is_SubPartition && (*subpart)->SubPartition_Of == parentPart->Mount_Point) {
1064 if (check_digest > 0 && !twrpDigestDriver::Check_Digest(Full_Filename))
1065 return false;
1066 part_settings.total_restore_size += (*subpart)->Get_Restore_Size(&part_settings);
1067 }
1068 }
1069 }
1070 } else {
1071 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
1072 }
1073 start_pos = end_pos + 1;
1074 end_pos = Restore_List.find(";", start_pos);
1075 }
1076 }
1077
1078 if (part_settings.partition_count == 0) {
1079 gui_err("no_part_restore=No partitions selected for restore.");
1080 return false;
1081 }
1082
1083 gui_msg(Msg("restore_part_count=Restoring {1} partitions...")(part_settings.partition_count));
1084 gui_msg(Msg("total_restore_size=Total restore size is {1}MB")(part_settings.total_restore_size / 1048576));
1085 DataManager::SetProgress(0.0);
1086 ProgressTracking progress(part_settings.total_restore_size);
1087 part_settings.progress = &progress;
1088
1089 start_pos = 0;
1090 if (!Restore_List.empty()) {
1091 end_pos = Restore_List.find(";", start_pos);
1092 while (end_pos != string::npos && start_pos < Restore_List.size()) {
1093 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
1094
1095 part_settings.Part = Find_Partition_By_Path(restore_path);
1096 if (part_settings.Part != NULL) {
1097 part_settings.partition_count++;
1098 if (!Restore_Partition(&part_settings))
1099 return false;
1100 } else {
1101 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
1102 }
1103 start_pos = end_pos + 1;
1104 end_pos = Restore_List.find(";", start_pos);
1105 }
1106 }
1107 TWFunc::GUI_Operation_Text(TW_UPDATE_SYSTEM_DETAILS_TEXT, gui_parse_text("{@updating_system_details}"));
1108 UnMount_By_Path("/system", false);
1109 Update_System_Details();
1110 UnMount_Main_Partitions();
1111 time(&rStop);
1112 gui_msg(Msg(msg::kHighlight, "restore_completed=[RESTORE COMPLETED IN {1} SECONDS]")((int)difftime(rStop,rStart)));
1113 DataManager::SetValue("tw_file_progress", "");
1114
1115 return true;
1116}
1117
1118void TWPartitionManager::Set_Restore_Files(string Restore_Name) {
1119 // Start with the default values
1120 string Restore_List;
1121 bool get_date = true, check_encryption = true;
1122 bool adbbackup = false;
1123
1124 DataManager::SetValue("tw_restore_encrypted", 0);
1125 if (twadbbu::Check_ADB_Backup_File(Restore_Name)) {
1126 vector<string> adb_files;
1127 adb_files = twadbbu::Get_ADB_Backup_Files(Restore_Name);
1128 for (unsigned int i = 0; i < adb_files.size(); ++i) {
1129 string adb_restore_file = adb_files.at(i);
1130 std::size_t pos = adb_restore_file.find_first_of(".");
1131 std::string path = "/" + adb_restore_file.substr(0, pos);
1132 Restore_List = path + ";";
1133 TWPartition* Part = Find_Partition_By_Path(path);
1134 Part->Backup_FileName = TWFunc::Get_Filename(adb_restore_file);
1135 adbbackup = true;
1136 }
1137 DataManager::SetValue("tw_enable_adb_backup", 1);
1138 }
1139 else {
1140 DIR* d;
1141 d = opendir(Restore_Name.c_str());
1142 if (d == NULL)
1143 {
1144 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Name)(strerror(errno)));
1145 return;
1146 }
1147
1148 struct dirent* de;
1149 while ((de = readdir(d)) != NULL)
1150 {
1151 // Strip off three components
1152 char str[256];
1153 char* label;
1154 char* fstype = NULL;
1155 char* extn = NULL;
1156 char* ptr;
1157
1158 strcpy(str, de->d_name);
1159 if (strlen(str) <= 2)
1160 continue;
1161
1162 if (get_date) {
1163 char file_path[255];
1164 struct stat st;
1165
1166 strcpy(file_path, Restore_Name.c_str());
1167 strcat(file_path, "/");
1168 strcat(file_path, str);
1169 stat(file_path, &st);
1170 string backup_date = ctime((const time_t*)(&st.st_mtime));
1171 DataManager::SetValue(TW_RESTORE_FILE_DATE, backup_date);
1172 get_date = false;
1173 }
1174
1175 label = str;
1176 ptr = label;
1177 while (*ptr && *ptr != '.') ptr++;
1178 if (*ptr == '.')
1179 {
1180 *ptr = 0x00;
1181 ptr++;
1182 fstype = ptr;
1183 }
1184 while (*ptr && *ptr != '.') ptr++;
1185 if (*ptr == '.')
1186 {
1187 *ptr = 0x00;
1188 ptr++;
1189 extn = ptr;
1190 }
1191
1192 if (fstype == NULL || extn == NULL || strcmp(fstype, "log") == 0) continue;
1193 int extnlength = strlen(extn);
1194 if (extnlength != 3 && extnlength != 6) continue;
1195 if (extnlength >= 3 && strncmp(extn, "win", 3) != 0) continue;
1196 //if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1197
1198 if (check_encryption) {
1199 string filename = Restore_Name + "/";
1200 filename += de->d_name;
1201 if (TWFunc::Get_File_Type(filename) == 2) {
1202 LOGINFO("'%s' is encrypted\n", filename.c_str());
1203 DataManager::SetValue("tw_restore_encrypted", 1);
1204 }
1205 }
1206 if (extnlength == 6 && strncmp(extn, "win000", 6) != 0) continue;
1207
1208 TWPartition* Part = Find_Partition_By_Path(label);
1209 if (Part == NULL)
1210 {
1211 gui_msg(Msg(msg::kError, "unable_locate_part_backup_name=Unable to locate partition by backup name: '{1}'")(label));
1212 continue;
1213 }
1214
1215 Part->Backup_FileName = de->d_name;
1216 if (strlen(extn) > 3) {
1217 Part->Backup_FileName.resize(Part->Backup_FileName.size() - strlen(extn) + 3);
1218 }
1219
1220 if (!Part->Is_SubPartition)
1221 Restore_List += Part->Backup_Path + ";";
1222 }
1223 closedir(d);
1224 }
1225
1226 if (adbbackup) {
1227 Restore_List = "ADB_Backup;";
1228 adbbackup = false;
1229 }
1230
1231 // Set the final value
1232 DataManager::SetValue("tw_restore_list", Restore_List);
1233 DataManager::SetValue("tw_restore_selected", Restore_List);
1234 return;
1235}
1236
1237int TWPartitionManager::Wipe_By_Path(string Path) {
1238 std::vector<TWPartition*>::iterator iter;
1239 int ret = false;
1240 bool found = false;
1241 string Local_Path = TWFunc::Get_Root_Path(Path);
1242
1243 // Iterate through all partitions
1244 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1245 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1246 if (Path == "/and-sec")
1247 ret = (*iter)->Wipe_AndSec();
1248 else
1249 ret = (*iter)->Wipe();
1250 found = true;
1251 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1252 (*iter)->Wipe();
1253 }
1254 }
1255 if (found) {
1256 return ret;
1257 } else
1258 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
1259 return false;
1260}
1261
1262int TWPartitionManager::Wipe_By_Path(string Path, string New_File_System) {
1263 std::vector<TWPartition*>::iterator iter;
1264 int ret = false;
1265 bool found = false;
1266 string Local_Path = TWFunc::Get_Root_Path(Path);
1267
1268 // Iterate through all partitions
1269 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1270 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1271 if (Path == "/and-sec")
1272 ret = (*iter)->Wipe_AndSec();
1273 else
1274 ret = (*iter)->Wipe(New_File_System);
1275 found = true;
1276 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1277 (*iter)->Wipe(New_File_System);
1278 }
1279 }
1280 if (found) {
1281 return ret;
1282 } else
1283 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
1284 return false;
1285}
1286
1287int TWPartitionManager::Factory_Reset(void) {
1288 std::vector<TWPartition*>::iterator iter;
1289 int ret = true;
1290
1291 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1292 if ((*iter)->Wipe_During_Factory_Reset && (*iter)->Is_Present) {
1293#ifdef TW_OEM_BUILD
1294 if ((*iter)->Mount_Point == "/data") {
1295 if (!(*iter)->Wipe_Encryption())
1296 ret = false;
1297 } else {
1298#endif
1299 if (!(*iter)->Wipe())
1300 ret = false;
1301#ifdef TW_OEM_BUILD
1302 }
1303#endif
1304 } else if ((*iter)->Has_Android_Secure) {
1305 if (!(*iter)->Wipe_AndSec())
1306 ret = false;
1307 }
1308 }
1309 TWFunc::check_and_run_script("/sbin/factoryreset.sh", "Factory Reset Script");
1310 return ret;
1311}
1312
1313int TWPartitionManager::Wipe_Dalvik_Cache(void) {
1314 struct stat st;
1315 vector <string> dir;
1316
1317 if (!Mount_By_Path("/data", true))
1318 return false;
1319
1320 dir.push_back("/data/dalvik-cache");
1321 if (Mount_By_Path("/cache", false)) {
1322 dir.push_back("/cache/dalvik-cache");
1323 dir.push_back("/cache/dc");
1324 }
1325
1326 TWPartition* sdext = Find_Partition_By_Path("/sd-ext");
1327 if (sdext && sdext->Is_Present && sdext->Mount(false))
1328 {
1329 if (stat("/sd-ext/dalvik-cache", &st) == 0)
1330 {
1331 dir.push_back("/sd-ext/dalvik-cache");
1332 }
1333 }
1334
1335 gui_msg("wiping_dalvik=Wiping Dalvik Cache Directories...");
1336 for (unsigned i = 0; i < dir.size(); ++i) {
1337 if (stat(dir.at(i).c_str(), &st) == 0) {
1338 TWFunc::removeDir(dir.at(i), false);
1339 gui_msg(Msg("cleaned=Cleaned: {1}...")(dir.at(i)));
1340 }
1341 }
1342 gui_msg("dalvik_done=-- Dalvik Cache Directories Wipe Complete!");
1343 return true;
1344}
1345
1346int TWPartitionManager::Wipe_Rotate_Data(void) {
1347 if (!Mount_By_Path("/data", true))
1348 return false;
1349
1350 unlink("/data/misc/akmd*");
1351 unlink("/data/misc/rild*");
1352 gui_print("Rotation data wiped.\n");
1353 return true;
1354}
1355
1356int TWPartitionManager::Wipe_Battery_Stats(void) {
1357 struct stat st;
1358
1359 if (!Mount_By_Path("/data", true))
1360 return false;
1361
1362 if (0 != stat("/data/system/batterystats.bin", &st)) {
1363 gui_print("No Battery Stats Found. No Need To Wipe.\n");
1364 } else {
1365 remove("/data/system/batterystats.bin");
1366 gui_print("Cleared battery stats.\n");
1367 }
1368 return true;
1369}
1370
1371int TWPartitionManager::Wipe_Android_Secure(void) {
1372 std::vector<TWPartition*>::iterator iter;
1373 int ret = false;
1374 bool found = false;
1375
1376 // Iterate through all partitions
1377 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1378 if ((*iter)->Has_Android_Secure) {
1379 ret = (*iter)->Wipe_AndSec();
1380 found = true;
1381 }
1382 }
1383 if (found) {
1384 return ret;
1385 } else {
1386 gui_err("no_andsec=No android secure partitions found.");
1387 }
1388 return false;
1389}
1390
1391int TWPartitionManager::Format_Data(void) {
1392 TWPartition* dat = Find_Partition_By_Path("/data");
1393
1394 if (dat != NULL) {
1395 if (!dat->UnMount(true))
1396 return false;
1397
1398 return dat->Wipe_Encryption();
1399 } else {
1400 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
1401 return false;
1402 }
1403 return false;
1404}
1405
1406int TWPartitionManager::Wipe_Media_From_Data(void) {
1407 TWPartition* dat = Find_Partition_By_Path("/data");
1408
1409 if (dat != NULL) {
1410 if (!dat->Has_Data_Media) {
1411 LOGERR("This device does not have /data/media\n");
1412 return false;
1413 }
1414 if (!dat->Mount(true))
1415 return false;
1416
1417 gui_msg("wiping_datamedia=Wiping internal storage -- /data/media...");
1418 Remove_MTP_Storage(dat->MTP_Storage_ID);
1419 TWFunc::removeDir("/data/media", false);
1420 dat->Recreate_Media_Folder();
1421 Add_MTP_Storage(dat->MTP_Storage_ID);
1422 return true;
1423 } else {
1424 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")("/data"));
1425 return false;
1426 }
1427 return false;
1428}
1429
1430int TWPartitionManager::Repair_By_Path(string Path, bool Display_Error) {
1431 std::vector<TWPartition*>::iterator iter;
1432 int ret = false;
1433 bool found = false;
1434 string Local_Path = TWFunc::Get_Root_Path(Path);
1435
1436 if (Local_Path == "/tmp" || Local_Path == "/")
1437 return true;
1438
1439 // Iterate through all partitions
1440 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1441 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1442 ret = (*iter)->Repair();
1443 found = true;
1444 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1445 (*iter)->Repair();
1446 }
1447 }
1448 if (found) {
1449 return ret;
1450 } else if (Display_Error) {
1451 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
1452 } else {
1453 LOGINFO("Repair: Unable to find partition for path '%s'\n", Local_Path.c_str());
1454 }
1455 return false;
1456}
1457
1458int TWPartitionManager::Resize_By_Path(string Path, bool Display_Error) {
1459 std::vector<TWPartition*>::iterator iter;
1460 int ret = false;
1461 bool found = false;
1462 string Local_Path = TWFunc::Get_Root_Path(Path);
1463
1464 if (Local_Path == "/tmp" || Local_Path == "/")
1465 return true;
1466
1467 // Iterate through all partitions
1468 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1469 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
1470 ret = (*iter)->Resize();
1471 found = true;
1472 } else if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Local_Path) {
1473 (*iter)->Resize();
1474 }
1475 }
1476 if (found) {
1477 return ret;
1478 } else if (Display_Error) {
1479 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Local_Path));
1480 } else {
1481 LOGINFO("Resize: Unable to find partition for path '%s'\n", Local_Path.c_str());
1482 }
1483 return false;
1484}
1485
1486void TWPartitionManager::Update_System_Details(void) {
1487 std::vector<TWPartition*>::iterator iter;
1488 int data_size = 0;
1489
1490 gui_msg("update_part_details=Updating partition details...");
1491 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1492 (*iter)->Update_Size(true);
1493 if ((*iter)->Can_Be_Mounted) {
1494 if ((*iter)->Mount_Point == "/system") {
1495 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1496 DataManager::SetValue(TW_BACKUP_SYSTEM_SIZE, backup_display_size);
1497 } else if ((*iter)->Mount_Point == "/data" || (*iter)->Mount_Point == "/datadata") {
1498 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1499 } else if ((*iter)->Mount_Point == "/cache") {
1500 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1501 DataManager::SetValue(TW_BACKUP_CACHE_SIZE, backup_display_size);
1502 } else if ((*iter)->Mount_Point == "/sd-ext") {
1503 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1504 DataManager::SetValue(TW_BACKUP_SDEXT_SIZE, backup_display_size);
1505 if ((*iter)->Backup_Size == 0) {
1506 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 0);
1507 DataManager::SetValue(TW_BACKUP_SDEXT_VAR, 0);
1508 } else
1509 DataManager::SetValue(TW_HAS_SDEXT_PARTITION, 1);
1510 } else if ((*iter)->Has_Android_Secure) {
1511 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1512 DataManager::SetValue(TW_BACKUP_ANDSEC_SIZE, backup_display_size);
1513 if ((*iter)->Backup_Size == 0) {
1514 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 0);
1515 DataManager::SetValue(TW_BACKUP_ANDSEC_VAR, 0);
1516 } else
1517 DataManager::SetValue(TW_HAS_ANDROID_SECURE, 1);
1518 } else if ((*iter)->Mount_Point == "/boot") {
1519 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1520 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1521 if ((*iter)->Backup_Size == 0) {
1522 DataManager::SetValue("tw_has_boot_partition", 0);
1523 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1524 } else
1525 DataManager::SetValue("tw_has_boot_partition", 1);
1526 }
1527 } else {
1528 // Handle unmountable partitions in case we reset defaults
1529 if ((*iter)->Mount_Point == "/boot") {
1530 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1531 DataManager::SetValue(TW_BACKUP_BOOT_SIZE, backup_display_size);
1532 if ((*iter)->Backup_Size == 0) {
1533 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 0);
1534 DataManager::SetValue(TW_BACKUP_BOOT_VAR, 0);
1535 } else
1536 DataManager::SetValue(TW_HAS_BOOT_PARTITION, 1);
1537 } else if ((*iter)->Mount_Point == "/recovery") {
1538 int backup_display_size = (int)((*iter)->Backup_Size / 1048576LLU);
1539 DataManager::SetValue(TW_BACKUP_RECOVERY_SIZE, backup_display_size);
1540 if ((*iter)->Backup_Size == 0) {
1541 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 0);
1542 DataManager::SetValue(TW_BACKUP_RECOVERY_VAR, 0);
1543 } else
1544 DataManager::SetValue(TW_HAS_RECOVERY_PARTITION, 1);
1545 } else if ((*iter)->Mount_Point == "/data") {
1546 data_size += (int)((*iter)->Backup_Size / 1048576LLU);
1547 }
1548 }
1549 }
1550 gui_msg("update_part_details_done=...done");
1551 DataManager::SetValue(TW_BACKUP_DATA_SIZE, data_size);
1552 string current_storage_path = DataManager::GetCurrentStoragePath();
1553 TWPartition* FreeStorage = Find_Partition_By_Path(current_storage_path);
1554 if (FreeStorage != NULL) {
1555 // Attempt to mount storage
1556 if (!FreeStorage->Mount(false)) {
1557 gui_msg(Msg(msg::kError, "unable_to_mount_storage=Unable to mount storage"));
1558 DataManager::SetValue(TW_STORAGE_FREE_SIZE, 0);
1559 } else {
1560 DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)(FreeStorage->Free / 1048576LLU));
1561 }
1562 } else {
1563 LOGINFO("Unable to find storage partition '%s'.\n", current_storage_path.c_str());
1564 }
1565 if (!Write_Fstab())
1566 LOGERR("Error creating fstab\n");
1567 return;
1568}
1569
1570void TWPartitionManager::Post_Decrypt(const string& Block_Device) {
1571 TWPartition* dat = Find_Partition_By_Path("/data");
1572 if (dat != NULL) {
1573 DataManager::SetValue(TW_IS_DECRYPTED, 1);
1574 dat->Is_Decrypted = true;
1575 if (!Block_Device.empty()) {
1576 dat->Decrypted_Block_Device = Block_Device;
1577 gui_msg(Msg("decrypt_success_dev=Data successfully decrypted, new block device: '{1}'")(Block_Device));
1578 } else {
1579 gui_msg("decrypt_success_nodev=Data successfully decrypted");
1580 }
1581 dat->Setup_File_System(false);
1582 dat->Current_File_System = dat->Fstab_File_System; // Needed if we're ignoring blkid because encrypted devices start out as emmc
1583
1584 // Sleep for a bit so that the device will be ready
1585 sleep(1);
1586 if (dat->Has_Data_Media && dat->Mount(false) && TWFunc::Path_Exists("/data/media/0")) {
1587 dat->Storage_Path = "/data/media/0";
1588 dat->Symlink_Path = dat->Storage_Path;
1589 DataManager::SetValue("tw_storage_path", "/data/media/0");
1590 DataManager::SetValue("tw_settings_path", "/data/media/0");
1591 dat->UnMount(false);
1592 }
1593 Update_System_Details();
1594 Output_Partition(dat);
1595 UnMount_Main_Partitions();
1596 } else
1597 LOGERR("Unable to locate data partition.\n");
1598}
1599
1600int TWPartitionManager::Decrypt_Device(string Password) {
1601#ifdef TW_INCLUDE_CRYPTO
1602 char crypto_state[PROPERTY_VALUE_MAX], crypto_blkdev[PROPERTY_VALUE_MAX];
1603 std::vector<TWPartition*>::iterator iter;
1604
1605 // Mount any partitions that need to be mounted for decrypt
1606 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1607 if ((*iter)->Mount_To_Decrypt) {
1608 (*iter)->Mount(true);
1609 }
1610 }
1611
1612 property_get("ro.crypto.state", crypto_state, "error");
1613 if (strcmp(crypto_state, "error") == 0) {
1614 property_set("ro.crypto.state", "encrypted");
1615 // Sleep for a bit so that services can start if needed
1616 sleep(1);
1617 }
1618
1619 if (DataManager::GetIntValue(TW_IS_FBE)) {
1620#ifdef TW_INCLUDE_FBE
1621 if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
1622 return -1;
1623 int retry_count = 10;
1624 while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
1625 usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt... maybe because of DE?
1626 int user_id = DataManager::GetIntValue("tw_decrypt_user_id");
1627 LOGINFO("Decrypting FBE for user %i\n", user_id);
1628 if (Decrypt_User(user_id, Password)) {
1629 Post_Decrypt("");
1630 return 0;
1631 }
1632#else
1633 LOGERR("FBE support is not present\n");
1634#endif
1635 return -1;
1636 }
1637
1638 int pwret = -1;
1639 pid_t pid = fork();
1640 if (pid < 0) {
1641 LOGERR("fork failed\n");
1642 return -1;
1643 } else if (pid == 0) {
1644 // Child process
1645 char cPassword[255];
1646 strcpy(cPassword, Password.c_str());
1647 int ret = cryptfs_check_passwd(cPassword);
1648 exit(ret);
1649 } else {
1650 // Parent
1651 int status;
1652 if (TWFunc::Wait_For_Child_Timeout(pid, &status, "Decrypt", 30))
1653 pwret = -1;
1654 else
1655 pwret = WEXITSTATUS(status) ? -1 : 0;
1656 }
1657
1658#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
1659 if (pwret != 0) {
1660 pwret = vold_decrypt(Password);
1661 switch (pwret) {
1662 case VD_SUCCESS:
1663 break;
1664 case VD_ERR_MISSING_VDC:
1665 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vdc"));
1666 break;
1667 case VD_ERR_MISSING_VOLD:
1668 gui_msg(Msg(msg::kError, "decrypt_data_vold_os_missing=Missing files needed for vold decrypt: {1}")("/system/bin/vold"));
1669 break;
1670 }
1671 }
1672#endif // TW_CRYPTO_USE_SYSTEM_VOLD
1673
1674 // Unmount any partitions that were needed for decrypt
1675 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1676 if ((*iter)->Mount_To_Decrypt) {
1677 (*iter)->UnMount(false);
1678 }
1679 }
1680
1681 if (pwret != 0) {
1682 gui_err("fail_decrypt=Failed to decrypt data.");
1683 return -1;
1684 }
1685
1686 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "error");
1687 if (strcmp(crypto_blkdev, "error") == 0) {
1688 LOGERR("Error retrieving decrypted data block device.\n");
1689 } else {
1690 Post_Decrypt(crypto_blkdev);
1691 }
1692 return 0;
1693#else
1694 gui_err("no_crypto_support=No crypto support was compiled into this build.");
1695 return -1;
1696#endif
1697 return 1;
1698}
1699
1700int TWPartitionManager::Fix_Contexts(void) {
1701 std::vector<TWPartition*>::iterator iter;
1702 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1703 if ((*iter)->Has_Data_Media) {
1704 if ((*iter)->Mount(true)) {
1705 if (fixContexts::fixDataMediaContexts((*iter)->Mount_Point) != 0)
1706 return -1;
1707 }
1708 }
1709 }
1710 UnMount_Main_Partitions();
1711 gui_msg("done=Done.");
1712 return 0;
1713}
1714
1715TWPartition* TWPartitionManager::Find_Next_Storage(string Path, bool Exclude_Data_Media) {
1716 std::vector<TWPartition*>::iterator iter = Partitions.begin();
1717
1718 if (!Path.empty()) {
1719 string Search_Path = TWFunc::Get_Root_Path(Path);
1720 for (; iter != Partitions.end(); iter++) {
1721 if ((*iter)->Mount_Point == Search_Path) {
1722 iter++;
1723 break;
1724 }
1725 }
1726 }
1727
1728 for (; iter != Partitions.end(); iter++) {
1729 if (Exclude_Data_Media && (*iter)->Has_Data_Media) {
1730 // do nothing, do not return this type of partition
1731 } else if ((*iter)->Is_Storage && (*iter)->Is_Present) {
1732 return (*iter);
1733 }
1734 }
1735
1736 return NULL;
1737}
1738
1739int TWPartitionManager::Open_Lun_File(string Partition_Path, string Lun_File) {
1740 TWPartition* Part = Find_Partition_By_Path(Partition_Path);
1741
1742 if (Part == NULL) {
1743 LOGINFO("Unable to locate '%s' for USB storage mode.", Partition_Path.c_str());
1744 gui_msg(Msg(msg::kError, "unable_find_part_path=Unable to find partition for path '{1}'")(Partition_Path));
1745 return false;
1746 }
1747 LOGINFO("USB mount '%s', '%s' > '%s'\n", Partition_Path.c_str(), Part->Actual_Block_Device.c_str(), Lun_File.c_str());
1748 if (!Part->UnMount(true) || !Part->Is_Present)
1749 return false;
1750
1751 if (TWFunc::write_to_file(Lun_File, Part->Actual_Block_Device)) {
1752 LOGERR("Unable to write to ums lunfile '%s': (%s)\n", Lun_File.c_str(), strerror(errno));
1753 return false;
1754 }
1755 return true;
1756}
1757
1758int TWPartitionManager::usb_storage_enable(void) {
1759 char lun_file[255];
1760 bool has_multiple_lun = false;
1761
1762 string Lun_File_str = CUSTOM_LUN_FILE;
1763 size_t found = Lun_File_str.find("%");
1764 if (found != string::npos) {
1765 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
1766 if (TWFunc::Path_Exists(lun_file))
1767 has_multiple_lun = true;
1768 }
1769 mtp_was_enabled = TWFunc::Toggle_MTP(false); // Must disable MTP for USB Storage
1770 if (!has_multiple_lun) {
1771 LOGINFO("Device doesn't have multiple lun files, mount current storage\n");
1772 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
1773 if (TWFunc::Get_Root_Path(DataManager::GetCurrentStoragePath()) == "/data") {
1774 TWPartition* Mount = Find_Next_Storage("", true);
1775 if (Mount) {
1776 if (!Open_Lun_File(Mount->Mount_Point, lun_file)) {
1777 goto error_handle;
1778 }
1779 } else {
1780 gui_err("unable_locate_storage=Unable to locate storage device.");
1781 goto error_handle;
1782 }
1783 } else if (!Open_Lun_File(DataManager::GetCurrentStoragePath(), lun_file)) {
1784 goto error_handle;
1785 }
1786 } else {
1787 LOGINFO("Device has multiple lun files\n");
1788 TWPartition* Mount1;
1789 TWPartition* Mount2;
1790 sprintf(lun_file, CUSTOM_LUN_FILE, 0);
1791 Mount1 = Find_Next_Storage("", true);
1792 if (Mount1) {
1793 if (!Open_Lun_File(Mount1->Mount_Point, lun_file)) {
1794 goto error_handle;
1795 }
1796 sprintf(lun_file, CUSTOM_LUN_FILE, 1);
1797 Mount2 = Find_Next_Storage(Mount1->Mount_Point, true);
1798 if (Mount2 && Mount2->Mount_Point != Mount1->Mount_Point) {
1799 Open_Lun_File(Mount2->Mount_Point, lun_file);
1800 }
1801 } else {
1802 gui_err("unable_locate_storage=Unable to locate storage device.");
1803 goto error_handle;
1804 }
1805 }
1806 property_set("sys.storage.ums_enabled", "1");
1807 property_set("sys.usb.config", "mass_storage,adb");
1808 return true;
1809error_handle:
1810 if (mtp_was_enabled)
1811 if (!Enable_MTP())
1812 Disable_MTP();
1813 return false;
1814}
1815
1816int TWPartitionManager::usb_storage_disable(void) {
1817 int index, ret;
1818 char lun_file[255], ch[2] = {0, 0};
1819 string str = ch;
1820
1821 for (index=0; index<2; index++) {
1822 sprintf(lun_file, CUSTOM_LUN_FILE, index);
1823 ret = TWFunc::write_to_file(lun_file, str);
1824 if (ret < 0) {
1825 break;
1826 }
1827 }
1828 Mount_All_Storage();
1829 Update_System_Details();
1830 UnMount_Main_Partitions();
1831 property_set("sys.storage.ums_enabled", "0");
1832 property_set("sys.usb.config", "adb");
1833 if (mtp_was_enabled)
1834 if (!Enable_MTP())
1835 Disable_MTP();
1836 if (ret < 0 && index == 0) {
1837 LOGERR("Unable to write to ums lunfile '%s'.", lun_file);
1838 return false;
1839 } else {
1840 return true;
1841 }
1842 return true;
1843}
1844
1845void TWPartitionManager::Mount_All_Storage(void) {
1846 std::vector<TWPartition*>::iterator iter;
1847
1848 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
1849 if ((*iter)->Is_Storage)
1850 (*iter)->Mount(false);
1851 }
1852}
1853
1854void TWPartitionManager::UnMount_Main_Partitions(void) {
1855 // Unmounts system and data if data is not data/media
1856 // Also unmounts boot if boot is mountable
1857 LOGINFO("Unmounting main partitions...\n");
1858
1859 TWPartition* Boot_Partition = Find_Partition_By_Path("/boot");
1860
1861 UnMount_By_Path("/system", true);
1862 if (!datamedia)
1863 UnMount_By_Path("/data", true);
1864
1865 if (Boot_Partition != NULL && Boot_Partition->Can_Be_Mounted)
1866 Boot_Partition->UnMount(true);
1867}
1868
1869int TWPartitionManager::Partition_SDCard(void) {
1870 char temp[255];
1871 string Storage_Path, Command, Device, fat_str, ext_str, start_loc, end_loc, ext_format, sd_path, tmpdevice;
1872 int ext, swap, total_size = 0, fat_size;
1873
1874 gui_msg("start_partition_sd=Partitioning SD Card...");
1875
1876 // Locate and validate device to partition
1877 TWPartition* SDCard = Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1878
1879 if (SDCard->Is_Adopted_Storage)
1880 SDCard->Revert_Adopted();
1881
1882 if (SDCard == NULL || !SDCard->Removable || SDCard->Has_Data_Media) {
1883 gui_err("partition_sd_locate=Unable to locate device to partition.");
1884 return false;
1885 }
1886
1887 // Unmount everything
1888 if (!SDCard->UnMount(true))
1889 return false;
1890 TWPartition* SDext = Find_Partition_By_Path("/sd-ext");
1891 if (SDext != NULL) {
1892 if (!SDext->UnMount(true))
1893 return false;
1894 }
1895 char* swappath = getenv("SWAPPATH");
1896 if (swappath != NULL) {
1897 LOGINFO("Unmounting swap at '%s'\n", swappath);
1898 umount(swappath);
1899 }
1900
1901 // Determine block device
1902 if (SDCard->Alternate_Block_Device.empty()) {
1903 SDCard->Find_Actual_Block_Device();
1904 Device = SDCard->Actual_Block_Device;
1905 // Just use the root block device
1906 Device.resize(strlen("/dev/block/mmcblkX"));
1907 } else {
1908 Device = SDCard->Alternate_Block_Device;
1909 }
1910
1911 // Find the size of the block device:
1912 total_size = (int)(TWFunc::IOCTL_Get_Block_Size(Device.c_str()) / (1048576));
1913
1914 DataManager::GetValue("tw_sdext_size", ext);
1915 DataManager::GetValue("tw_swap_size", swap);
1916 DataManager::GetValue("tw_sdpart_file_system", ext_format);
1917 fat_size = total_size - ext - swap;
1918 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);
1919
1920 // Determine partition sizes
1921 if (swap == 0 && ext == 0) {
1922 fat_str = "-0";
1923 } else {
1924 memset(temp, 0, sizeof(temp));
1925 sprintf(temp, "%i", fat_size);
1926 fat_str = temp;
1927 fat_str += "MB";
1928 }
1929 if (swap == 0) {
1930 ext_str = "-0";
1931 } else {
1932 memset(temp, 0, sizeof(temp));
1933 sprintf(temp, "%i", ext);
1934 ext_str = "+";
1935 ext_str += temp;
1936 ext_str += "MB";
1937 }
1938
1939 if (ext + swap > total_size) {
1940 gui_err("ext_swap_size=EXT + Swap size is larger than sdcard size.");
1941 return false;
1942 }
1943
1944 gui_msg("remove_part_table=Removing partition table...");
1945 Command = "sgdisk --zap-all " + Device;
1946 LOGINFO("Command is: '%s'\n", Command.c_str());
1947 if (TWFunc::Exec_Cmd(Command) != 0) {
1948 gui_err("unable_rm_part=Unable to remove partition table.");
1949 Update_System_Details();
1950 return false;
1951 }
1952 gui_msg(Msg("create_part=Creating {1} partition...")("FAT32"));
1953 Command = "sgdisk --new=0:0:" + fat_str + " --change-name=0:\"Microsoft basic data\" --typecode=0:EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 " + Device;
1954 LOGINFO("Command is: '%s'\n", Command.c_str());
1955 if (TWFunc::Exec_Cmd(Command) != 0) {
1956 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("FAT32"));
1957 return false;
1958 }
1959 if (ext > 0) {
1960 gui_msg(Msg("create_part=Creating {1} partition...")("EXT"));
1961 Command = "sgdisk --new=0:0:" + ext_str + " --change-name=0:\"Linux filesystem\" " + Device;
1962 LOGINFO("Command is: '%s'\n", Command.c_str());
1963 if (TWFunc::Exec_Cmd(Command) != 0) {
1964 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("EXT"));
1965 Update_System_Details();
1966 return false;
1967 }
1968 }
1969 if (swap > 0) {
1970 gui_msg(Msg("create_part=Creating {1} partition...")("swap"));
1971 Command = "sgdisk --new=0:0:-0 --change-name=0:\"Linux swap\" --typecode=0:0657FD6D-A4AB-43C4-84E5-0933C84B4F4F " + Device;
1972 LOGINFO("Command is: '%s'\n", Command.c_str());
1973 if (TWFunc::Exec_Cmd(Command) != 0) {
1974 gui_msg(Msg(msg::kError, "unable_to_create_part=Unable to create {1} partition.")("swap"));
1975 Update_System_Details();
1976 return false;
1977 }
1978 }
1979
1980 // Convert GPT to MBR
1981 Command = "sgdisk --gpttombr " + Device;
1982 if (TWFunc::Exec_Cmd(Command) != 0)
1983 LOGINFO("Failed to covert partition GPT to MBR\n");
1984
1985 // Tell the kernel to rescan the partition table
1986 int fd = open(Device.c_str(), O_RDONLY);
1987 ioctl(fd, BLKRRPART, 0);
1988 close(fd);
1989
1990 string format_device = Device;
1991 if (Device.substr(0, 17) == "/dev/block/mmcblk")
1992 format_device += "p";
1993
1994 // Format new partitions to proper file system
1995 if (fat_size > 0) {
1996 Command = "mkfs.fat " + format_device + "1";
1997 TWFunc::Exec_Cmd(Command);
1998 }
1999 if (ext > 0) {
2000 if (SDext == NULL) {
2001 Command = "mke2fs -t " + ext_format + " -m 0 " + format_device + "2";
2002 gui_msg(Msg("format_sdext_as=Formatting sd-ext as {1}...")(ext_format));
2003 LOGINFO("Formatting sd-ext after partitioning, command: '%s'\n", Command.c_str());
2004 TWFunc::Exec_Cmd(Command);
2005 } else {
2006 SDext->Wipe(ext_format);
2007 }
2008 }
2009 if (swap > 0) {
2010 Command = "mkswap " + format_device;
2011 if (ext > 0)
2012 Command += "3";
2013 else
2014 Command += "2";
2015 TWFunc::Exec_Cmd(Command);
2016 }
2017
2018 // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned
2019 if (SDCard->Mount(true)) {
2020 string TWRP_Folder = SDCard->Mount_Point + "/TWRP";
2021 mkdir(TWRP_Folder.c_str(), 0777);
2022 DataManager::Flush();
2023 }
2024
2025 Update_System_Details();
2026 gui_msg("part_complete=Partitioning complete.");
2027 return true;
2028}
2029
2030void TWPartitionManager::Get_Partition_List(string ListType, std::vector<PartitionList> *Partition_List) {
2031 std::vector<TWPartition*>::iterator iter;
2032 if (ListType == "mount") {
2033 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2034 if ((*iter)->Can_Be_Mounted) {
2035 struct PartitionList part;
2036 part.Display_Name = (*iter)->Display_Name;
2037 part.Mount_Point = (*iter)->Mount_Point;
2038 part.selected = (*iter)->Is_Mounted();
2039 Partition_List->push_back(part);
2040 }
2041 }
2042 } else if (ListType == "storage") {
2043 char free_space[255];
2044 string Current_Storage = DataManager::GetCurrentStoragePath();
2045 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2046 if ((*iter)->Is_Storage) {
2047 struct PartitionList part;
2048 sprintf(free_space, "%llu", (*iter)->Free / 1024 / 1024);
2049 part.Display_Name = (*iter)->Storage_Name + " (";
2050 part.Display_Name += free_space;
2051 part.Display_Name += "MB)";
2052 part.Mount_Point = (*iter)->Storage_Path;
2053 if ((*iter)->Storage_Path == Current_Storage)
2054 part.selected = 1;
2055 else
2056 part.selected = 0;
2057 Partition_List->push_back(part);
2058 }
2059 }
2060 } else if (ListType == "backup") {
2061 char backup_size[255];
2062 unsigned long long Backup_Size;
2063 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2064 if ((*iter)->Can_Be_Backed_Up && !(*iter)->Is_SubPartition && (*iter)->Is_Present) {
2065 struct PartitionList part;
2066 Backup_Size = (*iter)->Backup_Size;
2067 if ((*iter)->Has_SubPartition) {
2068 std::vector<TWPartition*>::iterator subpart;
2069
2070 for (subpart = Partitions.begin(); subpart != Partitions.end(); subpart++) {
2071 if ((*subpart)->Is_SubPartition && (*subpart)->Can_Be_Backed_Up && (*subpart)->Is_Present && (*subpart)->SubPartition_Of == (*iter)->Mount_Point)
2072 Backup_Size += (*subpart)->Backup_Size;
2073 }
2074 }
2075 sprintf(backup_size, "%llu", Backup_Size / 1024 / 1024);
2076 part.Display_Name = (*iter)->Backup_Display_Name + " (";
2077 part.Display_Name += backup_size;
2078 part.Display_Name += "MB)";
2079 part.Mount_Point = (*iter)->Backup_Path;
2080 part.selected = 0;
2081 Partition_List->push_back(part);
2082 }
2083 }
2084 } else if (ListType == "restore") {
2085 string Restore_List, restore_path;
2086 TWPartition* restore_part = NULL;
2087
2088 DataManager::GetValue("tw_restore_list", Restore_List);
2089 if (!Restore_List.empty()) {
2090 size_t start_pos = 0, end_pos = Restore_List.find(";", start_pos);
2091 while (end_pos != string::npos && start_pos < Restore_List.size()) {
2092 restore_path = Restore_List.substr(start_pos, end_pos - start_pos);
2093 struct PartitionList part;
2094 if (restore_path.compare("ADB_Backup") == 0) {
2095 part.Display_Name = "ADB Backup";
2096 part.Mount_Point = "ADB Backup";
2097 part.selected = 1;
2098 Partition_List->push_back(part);
2099 break;
2100 }
2101 if ((restore_part = Find_Partition_By_Path(restore_path)) != NULL) {
2102 if ((restore_part->Backup_Name == "recovery" && !restore_part->Can_Be_Backed_Up) || restore_part->Is_SubPartition) {
2103 // Don't allow restore of recovery (causes problems on some devices)
2104 // Don't add subpartitions to the list of items
2105 } else {
2106 part.Display_Name = restore_part->Backup_Display_Name;
2107 part.Mount_Point = restore_part->Backup_Path;
2108 part.selected = 1;
2109 Partition_List->push_back(part);
2110 }
2111 } else {
2112 gui_msg(Msg(msg::kError, "restore_unable_locate=Unable to locate '{1}' partition for restoring.")(restore_path));
2113 }
2114 start_pos = end_pos + 1;
2115 end_pos = Restore_List.find(";", start_pos);
2116 }
2117 }
2118 } else if (ListType == "wipe") {
2119 struct PartitionList dalvik;
2120 dalvik.Display_Name = gui_parse_text("{@dalvik}");
2121 dalvik.Mount_Point = "DALVIK";
2122 dalvik.selected = 0;
2123 Partition_List->push_back(dalvik);
2124 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2125 if ((*iter)->Wipe_Available_in_GUI && !(*iter)->Is_SubPartition) {
2126 struct PartitionList part;
2127 part.Display_Name = (*iter)->Display_Name;
2128 part.Mount_Point = (*iter)->Mount_Point;
2129 part.selected = 0;
2130 Partition_List->push_back(part);
2131 }
2132 if ((*iter)->Has_Android_Secure) {
2133 struct PartitionList part;
2134 part.Display_Name = (*iter)->Backup_Display_Name;
2135 part.Mount_Point = (*iter)->Backup_Path;
2136 part.selected = 0;
2137 Partition_List->push_back(part);
2138 }
2139 if ((*iter)->Has_Data_Media) {
2140 struct PartitionList datamedia;
2141 datamedia.Display_Name = (*iter)->Storage_Name;
2142 datamedia.Mount_Point = "INTERNAL";
2143 datamedia.selected = 0;
2144 Partition_List->push_back(datamedia);
2145 }
2146 }
2147 } else if (ListType == "flashimg") {
2148 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2149 if ((*iter)->Can_Flash_Img && (*iter)->Is_Present) {
2150 struct PartitionList part;
2151 part.Display_Name = (*iter)->Backup_Display_Name;
2152 part.Mount_Point = (*iter)->Backup_Path;
2153 part.selected = 0;
2154 Partition_List->push_back(part);
2155 }
2156 }
2157 } else {
2158 LOGERR("Unknown list type '%s' requested for TWPartitionManager::Get_Partition_List\n", ListType.c_str());
2159 }
2160}
2161
2162int TWPartitionManager::Fstab_Processed(void) {
2163 return Partitions.size();
2164}
2165
2166void TWPartitionManager::Output_Storage_Fstab(void) {
2167 std::vector<TWPartition*>::iterator iter;
2168 char storage_partition[255];
2169 string Temp;
2170 FILE *fp = fopen("/cache/recovery/storage.fstab", "w");
2171
2172 if (fp == NULL) {
2173 gui_msg(Msg(msg::kError, "unable_to_open=Unable to open '{1}'.")("/cache/recovery/storage.fstab"));
2174 return;
2175 }
2176
2177 // Iterate through all partitions
2178 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2179 if ((*iter)->Is_Storage) {
2180 Temp = (*iter)->Storage_Path + ";" + (*iter)->Storage_Name + ";\n";
2181 strcpy(storage_partition, Temp.c_str());
2182 fwrite(storage_partition, sizeof(storage_partition[0]), strlen(storage_partition) / sizeof(storage_partition[0]), fp);
2183 }
2184 }
2185 fclose(fp);
2186}
2187
2188TWPartition *TWPartitionManager::Get_Default_Storage_Partition()
2189{
2190 TWPartition *res = NULL;
2191 for (std::vector<TWPartition*>::iterator iter = Partitions.begin(); iter != Partitions.end(); ++iter) {
2192 if (!(*iter)->Is_Storage)
2193 continue;
2194
2195 if ((*iter)->Is_Settings_Storage)
2196 return *iter;
2197
2198 if (!res)
2199 res = *iter;
2200 }
2201 return res;
2202}
2203
2204bool TWPartitionManager::Enable_MTP(void) {
2205#ifdef TW_HAS_MTP
2206 if (mtppid) {
2207 gui_err("mtp_already_enabled=MTP already enabled");
2208 return true;
2209 }
2210
2211 int mtppipe[2];
2212
2213 if (pipe(mtppipe) < 0) {
2214 LOGERR("Error creating MTP pipe\n");
2215 return false;
2216 }
2217
2218 char old_value[PROPERTY_VALUE_MAX];
2219 property_get("sys.usb.config", old_value, "");
2220 if (strcmp(old_value, "mtp,adb") != 0) {
2221 char vendor[PROPERTY_VALUE_MAX];
2222 char product[PROPERTY_VALUE_MAX];
2223 property_set("sys.usb.config", "none");
2224 property_get("usb.vendor", vendor, "18D1");
2225 property_get("usb.product.mtpadb", product, "4EE2");
2226 string vendorstr = vendor;
2227 string productstr = product;
2228 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2229 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
2230 property_set("sys.usb.config", "mtp,adb");
2231 }
2232 /* To enable MTP debug, use the twrp command line feature:
2233 * twrp set tw_mtp_debug 1
2234 */
2235 twrpMtp *mtp = new twrpMtp(DataManager::GetIntValue("tw_mtp_debug"));
2236 mtppid = mtp->forkserver(mtppipe);
2237 if (mtppid) {
2238 close(mtppipe[0]); // Host closes read side
2239 mtp_write_fd = mtppipe[1];
2240 DataManager::SetValue("tw_mtp_enabled", 1);
2241 Add_All_MTP_Storage();
2242 return true;
2243 } else {
2244 close(mtppipe[0]);
2245 close(mtppipe[1]);
2246 gui_err("mtp_fail=Failed to enable MTP");
2247 return false;
2248 }
2249#else
2250 gui_err("no_mtp=MTP support not included");
2251#endif
2252 DataManager::SetValue("tw_mtp_enabled", 0);
2253 return false;
2254}
2255
2256void TWPartitionManager::Add_All_MTP_Storage(void) {
2257#ifdef TW_HAS_MTP
2258 std::vector<TWPartition*>::iterator iter;
2259
2260 if (!mtppid)
2261 return; // MTP is not enabled
2262
2263 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2264 if ((*iter)->Is_Storage && (*iter)->Is_Present && (*iter)->Mount(false))
2265 Add_Remove_MTP_Storage((*iter), MTP_MESSAGE_ADD_STORAGE);
2266 }
2267#else
2268 return;
2269#endif
2270}
2271
2272bool TWPartitionManager::Disable_MTP(void) {
2273 char old_value[PROPERTY_VALUE_MAX];
2274 property_get("sys.usb.config", old_value, "");
2275 if (strcmp(old_value, "adb") != 0) {
2276 char vendor[PROPERTY_VALUE_MAX];
2277 char product[PROPERTY_VALUE_MAX];
2278 property_set("sys.usb.config", "none");
2279 property_get("usb.vendor", vendor, "18D1");
2280 property_get("usb.product.adb", product, "D001");
2281 string vendorstr = vendor;
2282 string productstr = product;
2283 TWFunc::write_to_file("/sys/class/android_usb/android0/idVendor", vendorstr);
2284 TWFunc::write_to_file("/sys/class/android_usb/android0/idProduct", productstr);
2285 usleep(2000);
2286 }
2287#ifdef TW_HAS_MTP
2288 if (mtppid) {
2289 LOGINFO("Disabling MTP\n");
2290 int status;
2291 kill(mtppid, SIGKILL);
2292 mtppid = 0;
2293 // We don't care about the exit value, but this prevents a zombie process
2294 waitpid(mtppid, &status, 0);
2295 close(mtp_write_fd);
2296 mtp_write_fd = -1;
2297 }
2298#endif
2299 property_set("sys.usb.config", "adb");
2300#ifdef TW_HAS_MTP
2301 DataManager::SetValue("tw_mtp_enabled", 0);
2302 return true;
2303#endif
2304 return false;
2305}
2306
2307TWPartition* TWPartitionManager::Find_Partition_By_MTP_Storage_ID(unsigned int Storage_ID) {
2308 std::vector<TWPartition*>::iterator iter;
2309
2310 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2311 if ((*iter)->MTP_Storage_ID == Storage_ID)
2312 return (*iter);
2313 }
2314 return NULL;
2315}
2316
2317bool TWPartitionManager::Add_Remove_MTP_Storage(TWPartition* Part, int message_type) {
2318#ifdef TW_HAS_MTP
2319 struct mtpmsg mtp_message;
2320
2321 if (!mtppid)
2322 return false; // MTP is disabled
2323
2324 if (mtp_write_fd < 0) {
2325 LOGINFO("MTP: mtp_write_fd is not set\n");
2326 return false;
2327 }
2328
2329 if (Part) {
2330 if (Part->MTP_Storage_ID == 0)
2331 return false;
2332 if (message_type == MTP_MESSAGE_REMOVE_STORAGE) {
2333 mtp_message.message_type = MTP_MESSAGE_REMOVE_STORAGE; // Remove
2334 LOGINFO("sending message to remove %i\n", Part->MTP_Storage_ID);
2335 mtp_message.storage_id = Part->MTP_Storage_ID;
2336 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
2337 LOGINFO("error sending message to remove storage %i\n", Part->MTP_Storage_ID);
2338 return false;
2339 } else {
2340 LOGINFO("Message sent, remove storage ID: %i\n", Part->MTP_Storage_ID);
2341 return true;
2342 }
2343 } else if (message_type == MTP_MESSAGE_ADD_STORAGE && Part->Is_Mounted()) {
2344 mtp_message.message_type = MTP_MESSAGE_ADD_STORAGE; // Add
2345 mtp_message.storage_id = Part->MTP_Storage_ID;
2346 if (Part->Storage_Path.size() >= sizeof(mtp_message.path)) {
2347 LOGERR("Storage path '%s' too large for mtpmsg\n", Part->Storage_Path.c_str());
2348 return false;
2349 }
2350 strcpy(mtp_message.path, Part->Storage_Path.c_str());
2351 if (Part->Storage_Name.size() >= sizeof(mtp_message.display)) {
2352 LOGERR("Storage name '%s' too large for mtpmsg\n", Part->Storage_Name.c_str());
2353 return false;
2354 }
2355 strcpy(mtp_message.display, Part->Storage_Name.c_str());
2356 mtp_message.maxFileSize = Part->Get_Max_FileSize();
2357 LOGINFO("sending message to add %i '%s' '%s'\n", mtp_message.storage_id, mtp_message.path, mtp_message.display);
2358 if (write(mtp_write_fd, &mtp_message, sizeof(mtp_message)) <= 0) {
2359 LOGINFO("error sending message to add storage %i\n", Part->MTP_Storage_ID);
2360 return false;
2361 } else {
2362 LOGINFO("Message sent, add storage ID: %i '%s'\n", Part->MTP_Storage_ID, mtp_message.path);
2363 return true;
2364 }
2365 } else {
2366 LOGERR("Unknown MTP message type: %i\n", message_type);
2367 }
2368 } else {
2369 // This hopefully never happens as the error handling should
2370 // occur in the calling function.
2371 LOGINFO("TWPartitionManager::Add_Remove_MTP_Storage NULL partition given\n");
2372 }
2373 return true;
2374#else
2375 gui_err("no_mtp=MTP support not included");
2376 DataManager::SetValue("tw_mtp_enabled", 0);
2377 return false;
2378#endif
2379}
2380
2381bool TWPartitionManager::Add_MTP_Storage(string Mount_Point) {
2382#ifdef TW_HAS_MTP
2383 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2384 if (Part) {
2385 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2386 } else {
2387 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
2388 }
2389#endif
2390 return false;
2391}
2392
2393bool TWPartitionManager::Add_MTP_Storage(unsigned int Storage_ID) {
2394#ifdef TW_HAS_MTP
2395 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2396 if (Part) {
2397 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_ADD_STORAGE);
2398 } else {
2399 LOGINFO("TWFunc::Add_MTP_Storage unable to locate partition for %i\n", Storage_ID);
2400 }
2401#endif
2402 return false;
2403}
2404
2405bool TWPartitionManager::Remove_MTP_Storage(string Mount_Point) {
2406#ifdef TW_HAS_MTP
2407 TWPartition* Part = PartitionManager.Find_Partition_By_Path(Mount_Point);
2408 if (Part) {
2409 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2410 } else {
2411 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for '%s'\n", Mount_Point.c_str());
2412 }
2413#endif
2414 return false;
2415}
2416
2417bool TWPartitionManager::Remove_MTP_Storage(unsigned int Storage_ID) {
2418#ifdef TW_HAS_MTP
2419 TWPartition* Part = PartitionManager.Find_Partition_By_MTP_Storage_ID(Storage_ID);
2420 if (Part) {
2421 return PartitionManager.Add_Remove_MTP_Storage(Part, MTP_MESSAGE_REMOVE_STORAGE);
2422 } else {
2423 LOGINFO("TWFunc::Remove_MTP_Storage unable to locate partition for %i\n", Storage_ID);
2424 }
2425#endif
2426 return false;
2427}
2428
2429bool TWPartitionManager::Flash_Image(string& path, string& filename) {
2430 int partition_count = 0;
2431 TWPartition* flash_part = NULL;
2432 string Flash_List, flash_path, full_filename;
2433 size_t start_pos = 0, end_pos = 0;
2434
2435 full_filename = path + "/" + filename;
2436
2437 gui_msg("image_flash_start=[IMAGE FLASH STARTED]");
2438 gui_msg(Msg("img_to_flash=Image to flash: '{1}'")(full_filename));
2439
2440 if (!TWFunc::Path_Exists(full_filename)) {
2441 if (!Mount_By_Path(full_filename, true)) {
2442 return false;
2443 }
2444 if (!TWFunc::Path_Exists(full_filename)) {
2445 gui_msg(Msg(msg::kError, "unable_to_locate=Unable to locate {1}.")(full_filename));
2446 return false;
2447 }
2448 }
2449
2450 PartitionSettings part_settings;
2451 part_settings.Backup_Folder = path;
2452 unsigned long long total_bytes = TWFunc::Get_File_Size(full_filename);
2453 ProgressTracking progress(total_bytes);
2454 part_settings.progress = &progress;
2455 part_settings.adbbackup = false;
2456 part_settings.PM_Method = PM_RESTORE;
2457
2458 gui_msg("calc_restore=Calculating restore details...");
2459 DataManager::GetValue("tw_flash_partition", Flash_List);
2460 if (!Flash_List.empty()) {
2461 end_pos = Flash_List.find(";", start_pos);
2462 while (end_pos != string::npos && start_pos < Flash_List.size()) {
2463 flash_path = Flash_List.substr(start_pos, end_pos - start_pos);
2464 flash_part = Find_Partition_By_Path(flash_path);
2465 if (flash_part != NULL) {
2466 partition_count++;
2467 if (partition_count > 1) {
2468 gui_err("too_many_flash=Too many partitions selected for flashing.");
2469 return false;
2470 }
2471 } else {
2472 gui_msg(Msg(msg::kError, "flash_unable_locate=Unable to locate '{1}' partition for flashing.")(flash_path));
2473 return false;
2474 }
2475 start_pos = end_pos + 1;
2476 end_pos = Flash_List.find(";", start_pos);
2477 }
2478 }
2479
2480 if (partition_count == 0) {
2481 gui_err("no_part_flash=No partitions selected for flashing.");
2482 return false;
2483 }
2484
2485 DataManager::SetProgress(0.0);
2486 if (flash_part) {
2487 flash_part->Backup_FileName = filename;
2488 if (!flash_part->Flash_Image(&part_settings))
2489 return false;
2490 } else {
2491 gui_err("invalid_flash=Invalid flash partition specified.");
2492 return false;
2493 }
2494 gui_highlight("flash_done=IMAGE FLASH COMPLETED]");
2495 return true;
2496}
2497
2498void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value) {
2499 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2500 if (part) {
2501 if (part->Is_Adopted_Storage) {
2502 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2503 part->Backup_Display_Name = part->Display_Name;
2504 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2505 } else {
2506 part->Display_Name = gui_lookup(resource_name, default_value);
2507 part->Backup_Display_Name = part->Display_Name;
2508 }
2509 }
2510}
2511
2512void TWPartitionManager::Translate_Partition(const char* path, const char* resource_name, const char* default_value, const char* storage_resource_name, const char* storage_default_value) {
2513 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2514 if (part) {
2515 if (part->Is_Adopted_Storage) {
2516 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup("data_backup", "Data (excl. storage)");
2517 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2518 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2519 } else {
2520 part->Display_Name = gui_lookup(resource_name, default_value);
2521 part->Backup_Display_Name = part->Display_Name;
2522 if (part->Is_Storage)
2523 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2524 }
2525 }
2526}
2527
2528void 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) {
2529 TWPartition* part = PartitionManager.Find_Partition_By_Path(path);
2530 if (part) {
2531 if (part->Is_Adopted_Storage) {
2532 part->Backup_Display_Name = part->Display_Name + " - " + gui_lookup(backup_name, backup_default);
2533 part->Display_Name = part->Display_Name + " - " + gui_lookup("data", "Data");
2534 part->Storage_Name = part->Storage_Name + " - " + gui_lookup("adopted_storage", "Adopted Storage");
2535 } else {
2536 part->Display_Name = gui_lookup(resource_name, default_value);
2537 part->Backup_Display_Name = gui_lookup(backup_name, backup_default);
2538 if (part->Is_Storage)
2539 part->Storage_Name = gui_lookup(storage_resource_name, storage_default_value);
2540 }
2541 }
2542}
2543
2544void TWPartitionManager::Translate_Partition_Display_Names() {
2545 LOGINFO("Translating partition display names\n");
2546 Translate_Partition("/system", "system", "System");
2547 Translate_Partition("/system_image", "system_image", "System Image");
2548 Translate_Partition("/vendor", "vendor", "Vendor");
2549 Translate_Partition("/vendor_image", "vendor_image", "Vendor Image");
2550 Translate_Partition("/cache", "cache", "Cache");
2551 Translate_Partition("/boot", "boot", "Boot");
2552 Translate_Partition("/recovery", "recovery", "Recovery");
2553 if (!datamedia) {
2554 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage");
2555 Translate_Partition("/sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2556 Translate_Partition("/internal_sd", "sdcard", "SDCard", "sdcard", "SDCard");
2557 Translate_Partition("/internal_sdcard", "sdcard", "SDCard", "sdcard", "SDCard");
2558 Translate_Partition("/emmc", "sdcard", "SDCard", "sdcard", "SDCard");
2559 } else {
2560 Translate_Partition("/data", "data", "Data", "internal", "Internal Storage", "data_backup", "Data (excl. storage)");
2561 }
2562 Translate_Partition("/external_sd", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
2563 Translate_Partition("/external_sdcard", "microsd", "Micro SDCard", "microsd", "Micro SDCard", "data_backup", "Data (excl. storage)");
2564 Translate_Partition("/usb-otg", "usbotg", "USB OTG", "usbotg", "USB OTG");
2565 Translate_Partition("/sd-ext", "sdext", "SD-EXT");
2566
2567 // Android secure is a special case
2568 TWPartition* part = PartitionManager.Find_Partition_By_Path("/and-sec");
2569 if (part)
2570 part->Backup_Display_Name = gui_lookup("android_secure", "Android Secure");
2571
2572 std::vector<TWPartition*>::iterator sysfs;
2573 for (sysfs = Partitions.begin(); sysfs != Partitions.end(); sysfs++) {
2574 if (!(*sysfs)->Sysfs_Entry.empty()) {
2575 Translate_Partition((*sysfs)->Mount_Point.c_str(), "autostorage", "Storage", "autostorage", "Storage");
2576 }
2577 }
2578
2579 // This updates the text on all of the storage selection buttons in the GUI
2580 DataManager::SetBackupFolder();
2581}
2582
2583bool TWPartitionManager::Decrypt_Adopted() {
2584#ifdef TW_INCLUDE_CRYPTO
2585 bool ret = false;
2586 if (!Mount_By_Path("/data", false)) {
2587 LOGERR("Cannot decrypt adopted storage because /data will not mount\n");
2588 return false;
2589 }
2590 LOGINFO("Decrypt adopted storage starting\n");
2591 char* xmlFile = PageManager::LoadFileToBuffer("/data/system/storage.xml", NULL);
2592 xml_document<> *doc = NULL;
2593 xml_node<>* volumes = NULL;
2594 string Primary_Storage_UUID = "";
2595 if (xmlFile != NULL) {
2596 LOGINFO("successfully loaded storage.xml\n");
2597 doc = new xml_document<>();
2598 doc->parse<0>(xmlFile);
2599 volumes = doc->first_node("volumes");
2600 if (volumes) {
2601 xml_attribute<>* psuuid = volumes->first_attribute("primaryStorageUuid");
2602 if (psuuid) {
2603 Primary_Storage_UUID = psuuid->value();
2604 }
2605 }
2606 } else {
2607 LOGINFO("No /data/system/storage.xml for adopted storage\n");
2608 return false;
2609 }
2610 std::vector<TWPartition*>::iterator adopt;
2611 for (adopt = Partitions.begin(); adopt != Partitions.end(); adopt++) {
2612 if ((*adopt)->Removable && (*adopt)->Is_Present) {
2613 if ((*adopt)->Decrypt_Adopted() == 0) {
2614 ret = true;
2615 if (volumes) {
2616 xml_node<>* volume = volumes->first_node("volume");
2617 while (volume) {
2618 xml_attribute<>* guid = volume->first_attribute("partGuid");
2619 if (guid) {
2620 string GUID = (*adopt)->Adopted_GUID.c_str();
2621 GUID.insert(8, "-");
2622 GUID.insert(13, "-");
2623 GUID.insert(18, "-");
2624 GUID.insert(23, "-");
2625
2626 if (strcasecmp(GUID.c_str(), guid->value()) == 0) {
2627 xml_attribute<>* attr = volume->first_attribute("nickname");
2628 if (attr && attr->value() && strlen(attr->value()) > 0) {
2629 (*adopt)->Storage_Name = attr->value();
2630 (*adopt)->Display_Name = (*adopt)->Storage_Name;
2631 (*adopt)->Backup_Display_Name = (*adopt)->Storage_Name;
2632 LOGINFO("storage name from storage.xml is '%s'\n", attr->value());
2633 }
2634 attr = volume->first_attribute("fsUuid");
2635 if (attr && !Primary_Storage_UUID.empty() && strcmp(Primary_Storage_UUID.c_str(), attr->value()) == 0) {
2636 TWPartition* Dat = Find_Partition_By_Path("/data");
2637 if (Dat) {
2638 LOGINFO("Internal storage is found on adopted storage '%s'\n", (*adopt)->Display_Name.c_str());
2639 LOGINFO("Changing '%s' to point to '%s'\n", Dat->Symlink_Mount_Point.c_str(), (*adopt)->Storage_Path.c_str());
2640 (*adopt)->Symlink_Mount_Point = Dat->Symlink_Mount_Point;
2641 Dat->Symlink_Mount_Point = "";
2642 // Toggle mounts to ensure that the symlink mount point (probably /sdcard) is mounted to the right location
2643 Dat->UnMount(false);
2644 Dat->Mount(false);
2645 (*adopt)->UnMount(false);
2646 (*adopt)->Mount(false);
2647 }
2648 }
2649 break;
2650 }
2651 }
2652 volume = volume->next_sibling("volume");
2653 }
2654 }
2655 Update_System_Details();
2656 Output_Partition((*adopt));
2657 }
2658 }
2659 }
2660 if (xmlFile) {
2661 doc->clear();
2662 delete doc;
2663 free(xmlFile);
2664 }
2665 return ret;
2666#else
2667 LOGINFO("Decrypt_Adopted: no crypto support\n");
2668 return false;
2669#endif
2670}
2671
2672void TWPartitionManager::Remove_Partition_By_Path(string Path) {
2673 std::vector<TWPartition*>::iterator iter;
2674 string Local_Path = TWFunc::Get_Root_Path(Path);
2675
2676 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2677 if ((*iter)->Mount_Point == Local_Path || (!(*iter)->Symlink_Mount_Point.empty() && (*iter)->Symlink_Mount_Point == Local_Path)) {
2678 LOGINFO("Found and erasing '%s' from partition list\n", Local_Path.c_str());
2679 Partitions.erase(iter);
2680 return;
2681 }
2682 }
2683}
2684
2685void TWPartitionManager::Set_Active_Slot(const string& Slot) {
2686 if (Slot != "A" && Slot != "B") {
2687 LOGERR("Set_Active_Slot invalid slot '%s'\n", Slot.c_str());
2688 return;
2689 }
2690 if (Active_Slot_Display == Slot)
2691 return;
2692 LOGINFO("Setting active slot %s\n", Slot.c_str());
2693#ifdef AB_OTA_UPDATER
2694 if (!Active_Slot_Display.empty()) {
2695 const hw_module_t *hw_module;
2696 boot_control_module_t *module;
2697 int ret;
2698 ret = hw_get_module("bootctrl", &hw_module);
2699 if (ret != 0) {
2700 LOGERR("Error getting bootctrl module.\n");
2701 } else {
2702 module = (boot_control_module_t*) hw_module;
2703 module->init(module);
2704 int slot_number = 0;
2705 if (Slot == "B")
2706 slot_number = 1;
2707 if (module->setActiveBootSlot(module, slot_number))
2708 gui_msg(Msg(msg::kError, "unable_set_boot_slot=Error changing bootloader boot slot to {1}")(Slot));
2709 }
2710 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
2711 }
2712#else
2713 LOGERR("Boot slot feature not present\n");
2714#endif
2715 Active_Slot_Display = Slot;
2716 if (Fstab_Processed())
2717 Update_System_Details();
2718}
2719string TWPartitionManager::Get_Active_Slot_Suffix() {
2720 if (Active_Slot_Display == "A")
2721 return "_a";
2722 return "_b";
2723}
2724string TWPartitionManager::Get_Active_Slot_Display() {
2725 return Active_Slot_Display;
2726}
2727
2728void TWPartitionManager::Remove_Uevent_Devices(const string& Mount_Point) {
2729 std::vector<TWPartition*>::iterator iter;
2730
2731 for (iter = Partitions.begin(); iter != Partitions.end(); ) {
2732 if ((*iter)->Is_SubPartition && (*iter)->SubPartition_Of == Mount_Point) {
2733 TWPartition *part = *iter;
2734 LOGINFO("%s was removed by uevent data\n", (*iter)->Mount_Point.c_str());
2735 (*iter)->UnMount(false);
2736 rmdir((*iter)->Mount_Point.c_str());
2737 iter = Partitions.erase(iter);
2738 delete part;
2739 } else {
2740 iter++;
2741 }
2742 }
2743}
2744
2745void TWPartitionManager::Handle_Uevent(const Uevent_Block_Data& uevent_data) {
2746 std::vector<TWPartition*>::iterator iter;
2747
2748 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2749 if (!(*iter)->Sysfs_Entry.empty()) {
2750 string device;
2751 size_t wildcard = (*iter)->Sysfs_Entry.find("*");
2752 if (wildcard != string::npos) {
2753 device = (*iter)->Sysfs_Entry.substr(0, wildcard);
2754 } else {
2755 device = (*iter)->Sysfs_Entry;
2756 }
2757 if (device == uevent_data.sysfs_path.substr(0, device.size())) {
2758 // Found a match
2759 if (uevent_data.action == "add") {
2760 (*iter)->Primary_Block_Device = "/dev/block/" + uevent_data.block_device;
2761 (*iter)->Alternate_Block_Device = (*iter)->Primary_Block_Device;
2762 (*iter)->Is_Present = true;
2763 LOGINFO("Found a match '%s' '%s'\n", uevent_data.block_device.c_str(), device.c_str());
2764 if (!Decrypt_Adopted()) {
2765 LOGINFO("No adopted storage so finding actual block device\n");
2766 (*iter)->Find_Actual_Block_Device();
2767 }
2768 return;
2769 } else if (uevent_data.action == "remove") {
2770 (*iter)->Is_Present = false;
2771 (*iter)->Primary_Block_Device = "";
2772 (*iter)->Actual_Block_Device = "";
2773 Remove_Uevent_Devices((*iter)->Mount_Point);
2774 return;
2775 }
2776 }
2777 }
2778 }
2779 LOGINFO("Found no matching fstab entry for uevent device '%s' - %s\n", uevent_data.sysfs_path.c_str(), uevent_data.action.c_str());
2780}
2781
2782void TWPartitionManager::setup_uevent() {
2783 struct sockaddr_nl nls;
2784
2785 if (uevent_pfd.fd >= 0) {
2786 LOGINFO("uevent already set up\n");
2787 return;
2788 }
2789
2790 // Open hotplug event netlink socket
2791 memset(&nls,0,sizeof(struct sockaddr_nl));
2792 nls.nl_family = AF_NETLINK;
2793 nls.nl_pid = getpid();
2794 nls.nl_groups = -1;
2795 uevent_pfd.events = POLLIN;
2796 uevent_pfd.fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
2797 if (uevent_pfd.fd==-1) {
2798 LOGERR("uevent not root\n");
2799 return;
2800 }
2801
2802 // Listen to netlink socket
2803 if (::bind(uevent_pfd.fd, (struct sockaddr *) &nls, sizeof(struct sockaddr_nl)) < 0) {
2804 LOGERR("Bind failed\n");
2805 return;
2806 }
2807 set_select_fd();
2808 Coldboot();
2809}
2810
2811Uevent_Block_Data TWPartitionManager::get_event_block_values(char *buf, int len) {
2812 Uevent_Block_Data ret;
2813 ret.subsystem = "";
2814 char *ptr = buf;
2815 const char *end = buf + len;
2816
2817 buf[len - 1] = '\0';
2818 while (ptr < end) {
2819 if (strncmp(ptr, "ACTION=", strlen("ACTION=")) == 0) {
2820 ptr += strlen("ACTION=");
2821 ret.action = ptr;
2822 } else if (strncmp(ptr, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
2823 ptr += strlen("SUBSYSTEM=");
2824 ret.subsystem = ptr;
2825 } else if (strncmp(ptr, "DEVTYPE=", strlen("DEVTYPE=")) == 0) {
2826 ptr += strlen("DEVTYPE=");
2827 ret.type = ptr;
2828 } else if (strncmp(ptr, "DEVPATH=", strlen("DEVPATH=")) == 0) {
2829 ptr += strlen("DEVPATH=");
2830 ret.sysfs_path += ptr;
2831 } else if (strncmp(ptr, "DEVNAME=", strlen("DEVNAME=")) == 0) {
2832 ptr += strlen("DEVNAME=");
2833 ret.block_device += ptr;
2834 } else if (strncmp(ptr, "MAJOR=", strlen("MAJOR=")) == 0) {
2835 ptr += strlen("MAJOR=");
2836 ret.major = atoi(ptr);
2837 } else if (strncmp(ptr, "MINOR=", strlen("MINOR=")) == 0) {
2838 ptr += strlen("MINOR=");
2839 ret.minor = atoi(ptr);
2840 }
2841 ptr += strlen(ptr) + 1;
2842 }
2843 return ret;
2844}
2845
2846void TWPartitionManager::read_uevent() {
2847 char buf[1024];
2848
2849 int len = recv(uevent_pfd.fd, buf, sizeof(buf), MSG_DONTWAIT);
2850 if (len == -1) {
2851 LOGERR("recv error on uevent\n");
2852 return;
2853 }
2854 /*int i = 0; // Print all uevent output for test /debug
2855 while (i<len) {
2856 printf("%s\n", buf+i);
2857 i += strlen(buf+i)+1;
2858 }*/
2859 Uevent_Block_Data uevent_data = get_event_block_values(buf, len);
2860 if (uevent_data.subsystem == "block" && uevent_data.type == "disk") {
2861 PartitionManager.Handle_Uevent(uevent_data);
2862 }
2863}
2864
2865void TWPartitionManager::close_uevent() {
2866 if (uevent_pfd.fd > 0)
2867 close(uevent_pfd.fd);
2868 uevent_pfd.fd = -1;
2869}
2870
2871void TWPartitionManager::Add_Partition(TWPartition* Part) {
2872 Partitions.push_back(Part);
2873}
2874
2875void TWPartitionManager::Coldboot_Scan(std::vector<string> *sysfs_entries, const string& Path, int depth) {
2876 string Real_Path = Path;
2877 char real_path[PATH_MAX];
2878 if (realpath(Path.c_str(), &real_path[0])) {
2879 string Real_Path = real_path;
2880 std::vector<string>::iterator iter;
2881 for (iter = sysfs_entries->begin(); iter != sysfs_entries->end(); iter++) {
2882 if (Real_Path.find((*iter)) != string::npos) {
2883 string Write_Path = Real_Path + "/uevent";
2884 if (TWFunc::Path_Exists(Write_Path)) {
2885 const char* write_val = "add\n";
2886 TWFunc::write_to_file(Write_Path, write_val);
2887 break;
2888 }
2889 }
2890 }
2891 }
2892
2893 DIR* d = opendir(Path.c_str());
2894 if (d != NULL) {
2895 struct dirent* de;
2896 while ((de = readdir(d)) != NULL) {
2897 if (de->d_name[0] == '.' || (de->d_type != DT_DIR && depth > 0))
2898 continue;
2899 if (strlen(de->d_name) >= 4 && (strncmp(de->d_name, "ram", 3) == 0 || strncmp(de->d_name, "loop", 4) == 0))
2900 continue;
2901
2902 string item = Path + "/";
2903 item.append(de->d_name);
2904 Coldboot_Scan(sysfs_entries, item, depth + 1);
2905 }
2906 closedir(d);
2907 }
2908}
2909
2910void TWPartitionManager::Coldboot() {
2911 std::vector<TWPartition*>::iterator iter;
2912 std::vector<string> sysfs_entries;
2913
2914 for (iter = Partitions.begin(); iter != Partitions.end(); iter++) {
2915 if (!(*iter)->Sysfs_Entry.empty()) {
2916 size_t wildcard_pos = (*iter)->Sysfs_Entry.find("*");
2917 if (wildcard_pos == string::npos)
2918 wildcard_pos = (*iter)->Sysfs_Entry.size();
2919 sysfs_entries.push_back((*iter)->Sysfs_Entry.substr(0, wildcard_pos));
2920 }
2921 }
2922
2923 if (sysfs_entries.size() > 0)
2924 Coldboot_Scan(&sysfs_entries, "/sys/block", 0);
2925}