blob: 46352266466a71af886d40e892c97970fb836b76 [file] [log] [blame]
Dees_Troy38bd7602012-09-14 13:33:53 -04001#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
Dees_Troy38bd7602012-09-14 13:33:53 -04004#include <unistd.h>
5#include <vector>
6#include <dirent.h>
7#include <time.h>
Dees_Troy43d8b002012-09-17 16:00:01 -04008#include <errno.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -05009#include <fcntl.h>
10#include <sys/mount.h>
Dees_Troya58bead2012-09-27 09:49:29 -040011#include <sys/reboot.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050012#include <sys/sendfile.h>
13#include <sys/stat.h>
14#include <sys/vfs.h>
Dees_Troy83bd4832013-05-04 12:39:56 +000015#include <sys/types.h>
16#include <sys/wait.h>
Dees_Troya4438782013-02-22 18:44:00 +000017#ifdef ANDROID_RB_POWEROFF
18 #include "cutils/android_reboot.h"
19#endif
bigbiff bigbiff9c754052013-01-09 09:09:08 -050020#include <iostream>
21#include <fstream>
Dees_Troy83bd4832013-05-04 12:39:56 +000022#include <sstream>
Dees_Troy38bd7602012-09-14 13:33:53 -040023#include "twrp-functions.hpp"
24#include "partitions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000025#include "twcommon.h"
Dees_Troyb46a6842012-09-25 11:06:46 -040026#include "data.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040027#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000028#include "bootloader.h"
Dees_Troy83bd4832013-05-04 12:39:56 +000029#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
30 #include "openaes/inc/oaes_lib.h"
31#endif
Dees_Troy38bd7602012-09-14 13:33:53 -040032
Dees_Troyb05ddee2013-01-28 20:24:50 +000033extern "C" {
34 #include "libcrecovery/common.h"
35}
36
bigbiff bigbiff9c754052013-01-09 09:09:08 -050037/* Execute a command */
bigbiff bigbiff9c754052013-01-09 09:09:08 -050038int TWFunc::Exec_Cmd(string cmd, string &result) {
Vojtech Bocekc5754cf2013-06-18 15:56:59 +020039 int fd[2];
40 int ret = -1;
41 if(pipe(fd) < 0)
42 return -1;
43
44 pid_t pid = fork();
45 if (pid < 0)
46 {
47 close(fd[0]);
48 close(fd[1]);
49 return -1;
50 }
51
52 if(pid == 0) // child
53 {
54 close(fd[0]);
55 dup2(fd[1], 1); // send stdout to the pipe
56 dup2(fd[1], 2); // send stderr to the pipe
57 close(fd[1]);
58
59 ret = system(cmd.c_str());
60 if(ret != -1)
61 ret = WEXITSTATUS(ret);
62 else
63 LOGERR("Exec_Cmd: system() failed with -1 (%d)!\n", errno);
64 exit(ret);
65 }
66 else
67 {
68 close(fd[1]);
69
70 int len;
71 char buffer[128];
72 buffer[sizeof(buffer)-1] = 0;
73 while ((len = read(fd[0], buffer, sizeof(buffer)-1)) > 0)
74 {
75 buffer[len] = 0;
76 buffer[sizeof(buffer)-2] = '\n';
77 LOGINFO("%s", buffer);
bigbiff bigbiff9c754052013-01-09 09:09:08 -050078 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000079 }
Vojtech Bocekc5754cf2013-06-18 15:56:59 +020080
81 waitpid(pid, &ret, 0);
82 return WEXITSTATUS(ret);
bigbiff bigbiff9c754052013-01-09 09:09:08 -050083 }
Vojtech Bocekc5754cf2013-06-18 15:56:59 +020084 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050085}
86
Dees_Troy38bd7602012-09-14 13:33:53 -040087// Returns "file.name" from a full /path/to/file.name
88string TWFunc::Get_Filename(string Path) {
89 size_t pos = Path.find_last_of("/");
90 if (pos != string::npos) {
91 string Filename;
92 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
93 return Filename;
94 } else
95 return Path;
96}
97
98// Returns "/path/to/" from a full /path/to/file.name
99string TWFunc::Get_Path(string Path) {
100 size_t pos = Path.find_last_of("/");
101 if (pos != string::npos) {
102 string Pathonly;
103 Pathonly = Path.substr(0, pos + 1);
104 return Pathonly;
105 } else
106 return Path;
107}
108
109// Returns "/path" from a full /path/to/file.name
110string TWFunc::Get_Root_Path(string Path) {
111 string Local_Path = Path;
112
113 // Make sure that we have a leading slash
114 if (Local_Path.substr(0, 1) != "/")
115 Local_Path = "/" + Local_Path;
116
117 // Trim the path to get the root path only
118 size_t position = Local_Path.find("/", 2);
119 if (position != string::npos) {
120 Local_Path.resize(position);
121 }
122 return Local_Path;
123}
124
125void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400126 int need_libs = 0;
127
128 if (!PartitionManager.Mount_By_Path("/system", true))
129 return;
130
131 if (!PartitionManager.Mount_By_Path("/data", true))
132 return;
133
Dees_Troy2673cec2013-04-02 20:22:16 +0000134 gui_print("Installing HTC Dumlock to system...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500135 copy_file("/res/htcd/htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400136 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000137 gui_print("Installing flash_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500138 copy_file("/res/htcd/flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400139 need_libs = 1;
140 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000141 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400142 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000143 gui_print("Installing dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500144 copy_file("/res/htcd/dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400145 need_libs = 1;
146 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000147 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400148 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000149 gui_print("Installing libs needed for flash_image and dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500150 copy_file("/res/htcd/libbmlutils.so", "/system/lib/libbmlutils.so", 0755);
151 copy_file("/res/htcd/libflashutils.so", "/system/lib/libflashutils.so", 0755);
152 copy_file("/res/htcd/libmmcutils.so", "/system/lib/libmmcutils.so", 0755);
153 copy_file("/res/htcd/libmtdutils.so", "/system/lib/libmtdutils.so", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400154 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000155 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400156 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500157 unlink("/data/app/com.teamwin.htcdumlock*");
158 copy_file("/res/htcd/HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400159 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000160 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400161}
162
163void TWFunc::htc_dumlock_restore_original_boot(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500164 string status;
Dees_Troy38bd7602012-09-14 13:33:53 -0400165 if (!PartitionManager.Mount_By_Path("/sdcard", true))
166 return;
167
Dees_Troy2673cec2013-04-02 20:22:16 +0000168 gui_print("Restoring original boot...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500169 Exec_Cmd("htcdumlock restore", status);
Dees_Troy2673cec2013-04-02 20:22:16 +0000170 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400171}
172
173void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500174 string status;
Dees_Troy38bd7602012-09-14 13:33:53 -0400175 if (!PartitionManager.Mount_By_Path("/sdcard", true))
176 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000177 gui_print("Reflashing recovery to boot...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500178 Exec_Cmd("htcdumlock recovery noreboot", status);
Dees_Troy2673cec2013-04-02 20:22:16 +0000179 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400180}
Dees_Troy43d8b002012-09-17 16:00:01 -0400181
182int TWFunc::Recursive_Mkdir(string Path) {
183 string pathCpy = Path;
184 string wholePath;
185 size_t pos = pathCpy.find("/", 2);
186
187 while (pos != string::npos)
188 {
189 wholePath = pathCpy.substr(0, pos);
190 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000191 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
Dees_Troy43d8b002012-09-17 16:00:01 -0400192 return false;
193 }
194
195 pos = pathCpy.find("/", pos + 1);
196 }
197 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
198 return false;
199 return true;
200}
201
Vojtech Bocek2e97ec52013-02-02 13:22:42 +0100202unsigned long long TWFunc::Get_Folder_Size(const string& Path, bool Display_Error) {
Dees_Troy43d8b002012-09-17 16:00:01 -0400203 DIR* d;
204 struct dirent* de;
205 struct stat st;
Dees_Troy43d8b002012-09-17 16:00:01 -0400206 unsigned long long dusize = 0;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500207 unsigned long long dutemp = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400208
Vojtech Bocek2e97ec52013-02-02 13:22:42 +0100209 d = opendir(Path.c_str());
Dees_Troy43d8b002012-09-17 16:00:01 -0400210 if (d == NULL)
211 {
Dees_Troy2673cec2013-04-02 20:22:16 +0000212 LOGERR("error opening '%s'\n", Path.c_str());
213 LOGERR("error: %s\n", strerror(errno));
Dees_Troy43d8b002012-09-17 16:00:01 -0400214 return 0;
215 }
216
217 while ((de = readdir(d)) != NULL)
218 {
219 if (de->d_type == DT_DIR && strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
220 {
Vojtech Bocek2e97ec52013-02-02 13:22:42 +0100221 dutemp = Get_Folder_Size((Path + "/" + de->d_name), Display_Error);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500222 dusize += dutemp;
223 dutemp = 0;
Dees_Troy43d8b002012-09-17 16:00:01 -0400224 }
225 else if (de->d_type == DT_REG)
226 {
Vojtech Bocek2e97ec52013-02-02 13:22:42 +0100227 stat((Path + "/" + de->d_name).c_str(), &st);
Dees_Troy43d8b002012-09-17 16:00:01 -0400228 dusize += (unsigned long long)(st.st_size);
229 }
230 }
231 closedir(d);
Dees_Troy43d8b002012-09-17 16:00:01 -0400232 return dusize;
233}
234
235bool TWFunc::Path_Exists(string Path) {
236 // Check to see if the Path exists
Dees_Troy7c2dec82012-09-26 09:49:14 -0400237 struct stat st;
Dees_Troy7c2dec82012-09-26 09:49:14 -0400238 if (stat(Path.c_str(), &st) != 0)
Dees_Troy43d8b002012-09-17 16:00:01 -0400239 return false;
240 else
241 return true;
Dees_Troyb46a6842012-09-25 11:06:46 -0400242}
243
244void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
245 string Display_Text;
246
247 DataManager::GetValue(Read_Value, Display_Text);
248 if (Display_Text.empty())
249 Display_Text = Default_Text;
250
251 DataManager::SetValue("tw_operation", Display_Text);
252 DataManager::SetValue("tw_partition", "");
253}
254
255void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
256 string Display_Text;
257
258 DataManager::GetValue(Read_Value, Display_Text);
259 if (Display_Text.empty())
260 Display_Text = Default_Text;
261
262 DataManager::SetValue("tw_operation", Display_Text);
263 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400264}
265
266unsigned long TWFunc::Get_File_Size(string Path) {
267 struct stat st;
268
269 if (stat(Path.c_str(), &st) != 0)
270 return 0;
271 return st.st_size;
Dees_Troya58bead2012-09-27 09:49:29 -0400272}
273
Dees_Troy2673cec2013-04-02 20:22:16 +0000274void TWFunc::Copy_Log(string Source, string Destination) {
275 FILE *destination_log = fopen(Destination.c_str(), "a");
276 if (destination_log == NULL) {
277 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600278 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000279 FILE *source_log = fopen(Source.c_str(), "r");
280 if (source_log != NULL) {
281 fseek(source_log, Log_Offset, SEEK_SET);
282 char buffer[4096];
283 while (fgets(buffer, sizeof(buffer), source_log))
284 fputs(buffer, destination_log); // Buffered write of log file
285 Log_Offset = ftell(source_log);
286 fflush(source_log);
287 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600288 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000289 fflush(destination_log);
290 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600291 }
Dees_Troya58bead2012-09-27 09:49:29 -0400292}
293
Dees_Troy2673cec2013-04-02 20:22:16 +0000294void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500295 // Copy logs to cache so the system can find out what happened.
Dees_Troy2673cec2013-04-02 20:22:16 +0000296 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
297 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
298 chown("/cache/recovery/log", 1000, 1000);
299 chmod("/cache/recovery/log", 0600);
300 chmod("/cache/recovery/last_log", 0640);
Dees_Troya58bead2012-09-27 09:49:29 -0400301
Dees_Troy2673cec2013-04-02 20:22:16 +0000302 // Reset bootloader message
303 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
304 if (Part != NULL) {
305 struct bootloader_message boot;
306 memset(&boot, 0, sizeof(boot));
307 if (Part->Current_File_System == "mtd") {
308 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
309 LOGERR("Unable to set MTD bootloader message.\n");
310 } else if (Part->Current_File_System == "emmc") {
311 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
312 LOGERR("Unable to set emmc bootloader message.\n");
313 } else {
314 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
315 }
316 }
Dees_Troya58bead2012-09-27 09:49:29 -0400317
Dees_Troy2673cec2013-04-02 20:22:16 +0000318 if (!PartitionManager.Mount_By_Path("/cache", true) || (unlink("/cache/recovery/command") && errno != ENOENT)) {
319 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500320 }
Dees_Troya58bead2012-09-27 09:49:29 -0400321
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500322 PartitionManager.UnMount_By_Path("/cache", true);
Dees_Troy2673cec2013-04-02 20:22:16 +0000323 sync();
324}
325
326void TWFunc::Update_Intent_File(string Intent) {
327 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
328 TWFunc::write_file("/cache/recovery/intent", Intent);
329 }
Dees_Troya58bead2012-09-27 09:49:29 -0400330}
331
332// reboot: Reboot the system. Return -1 on error, no return on success
333int TWFunc::tw_reboot(RebootCommand command)
334{
335 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600336 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400337
Dees_Troy2673cec2013-04-02 20:22:16 +0000338 switch (command) {
339 case rb_current:
340 case rb_system:
341 Update_Log_File();
342 Update_Intent_File("s");
343 sync();
344 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
345 return reboot(RB_AUTOBOOT);
346 case rb_recovery:
347 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
348 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
349 case rb_bootloader:
350 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
351 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
352 case rb_poweroff:
353 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000354#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000355 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000356#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000357 return reboot(RB_POWER_OFF);
358 case rb_download:
359 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
360 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
361 default:
362 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600363 }
364 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400365}
366
367void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
368{
369 // Check for and run startup script if script exists
370 struct stat st;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500371 string result;
Dees_Troya58bead2012-09-27 09:49:29 -0400372 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000373 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500374 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
375 TWFunc::Exec_Cmd(script_file, result);
Dees_Troy2673cec2013-04-02 20:22:16 +0000376 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400377 }
Dees_Troy3477d712012-09-27 15:44:01 -0400378}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500379
380int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000381 DIR *d = opendir(path.c_str());
382 int r = 0;
383 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500384
Dees_Troyce675462013-01-09 19:48:21 +0000385 if (d == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000386 LOGERR("Error opening '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000387 return -1;
388 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500389
Dees_Troyce675462013-01-09 19:48:21 +0000390 if (d) {
391 struct dirent *p;
392 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000393 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
394 continue;
395 new_path = path + "/";
396 new_path.append(p->d_name);
397 if (p->d_type == DT_DIR) {
398 r = removeDir(new_path, true);
399 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500400 if (p->d_type == DT_DIR)
401 r = rmdir(new_path.c_str());
402 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000403 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500404 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500405 } else if (p->d_type == DT_REG || p->d_type == DT_LNK || p->d_type == DT_FIFO || p->d_type == DT_SOCK) {
Dees_Troyce675462013-01-09 19:48:21 +0000406 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000407 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000408 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000409 }
Dees_Troyce675462013-01-09 19:48:21 +0000410 }
411 }
412 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500413
414 if (!r) {
415 if (skipParent)
416 return 0;
417 else
418 r = rmdir(path.c_str());
419 }
Dees_Troyce675462013-01-09 19:48:21 +0000420 }
421 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500422}
423
424int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000425 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500426 ifstream srcfile(src.c_str(), ios::binary);
427 ofstream dstfile(dst.c_str(), ios::binary);
428 dstfile << srcfile.rdbuf();
429 srcfile.close();
430 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500431 if (chmod(dst.c_str(), mode) != 0)
432 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500433 return 0;
434}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000435
436unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
437 struct stat st;
438
439 stat(Path.c_str(), &st);
440 if (st.st_mode & S_IFDIR)
441 return DT_DIR;
442 else if (st.st_mode & S_IFBLK)
443 return DT_BLK;
444 else if (st.st_mode & S_IFCHR)
445 return DT_CHR;
446 else if (st.st_mode & S_IFIFO)
447 return DT_FIFO;
448 else if (st.st_mode & S_IFLNK)
449 return DT_LNK;
450 else if (st.st_mode & S_IFREG)
451 return DT_REG;
452 else if (st.st_mode & S_IFSOCK)
453 return DT_SOCK;
454 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000455}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500456
457int TWFunc::read_file(string fn, string& results) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500458 ifstream file;
459 file.open(fn.c_str(), ios::in);
460 if (file.is_open()) {
461 file >> results;
462 file.close();
463 return 0;
464 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000465 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500466 return -1;
467}
468
469int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500470 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500471 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500472 file.open(fn.c_str(), ios::in);
473 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500474 while (getline(file, line))
475 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500476 file.close();
477 return 0;
478 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000479 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500480 return -1;
481}
482
483int TWFunc::write_file(string fn, string& line) {
484 FILE *file;
485 file = fopen(fn.c_str(), "w");
486 if (file != NULL) {
487 fwrite(line.c_str(), line.size(), 1, file);
488 fclose(file);
489 return 0;
490 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000491 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500492 return -1;
493}
494
Dees_Troy83bd4832013-05-04 12:39:56 +0000495vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
496 vector<string> res;
497
498 if (in.empty() || del == '\0')
499 return res;
500
501 string field;
502 istringstream f(in);
503 if (del == '\n') {
504 while(getline(f, field)) {
505 if (field.empty() && skip_empty)
506 continue;
507 res.push_back(field);
508 }
509 } else {
510 while(getline(f, field, del)) {
511 if (field.empty() && skip_empty)
512 continue;
513 res.push_back(field);
514 }
515 }
516 return res;
517}
518
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500519timespec TWFunc::timespec_diff(timespec& start, timespec& end)
520{
Dees_Troy6ef66352013-02-21 08:26:57 -0600521 timespec temp;
522 if ((end.tv_nsec-start.tv_nsec)<0) {
523 temp.tv_sec = end.tv_sec-start.tv_sec-1;
524 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
525 } else {
526 temp.tv_sec = end.tv_sec-start.tv_sec;
527 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
528 }
529 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500530}
531
532 int TWFunc::drop_caches(void) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600533 string file = "/proc/sys/vm/drop_caches";
534 string value = "3";
535 if (write_file(file, value) != 0)
536 return -1;
537 return 0;
538}
539
540int TWFunc::Check_su_Perms(void) {
541 struct stat st;
542 int ret = 0;
543
544 if (!PartitionManager.Mount_By_Path("/system", false))
545 return 0;
546
547 // Check to ensure that perms are 6755 for all 3 file locations
548 if (stat("/system/bin/su", &st) == 0) {
549 if ((st.st_mode & (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) != (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) || st.st_uid != 0 || st.st_gid != 0) {
550 ret = 1;
551 }
552 }
553 if (stat("/system/xbin/su", &st) == 0) {
554 if ((st.st_mode & (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) != (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) || st.st_uid != 0 || st.st_gid != 0) {
555 ret += 2;
556 }
557 }
558 if (stat("/system/bin/.ext/.su", &st) == 0) {
559 if ((st.st_mode & (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) != (S_ISUID | S_ISGID | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) || st.st_uid != 0 || st.st_gid != 0) {
560 ret += 4;
561 }
562 }
563 return ret;
564}
565
566bool TWFunc::Fix_su_Perms(void) {
567 if (!PartitionManager.Mount_By_Path("/system", true))
568 return false;
569
570 string file = "/system/bin/su";
571 if (TWFunc::Path_Exists(file)) {
572 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000573 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600574 return false;
575 }
576 if (tw_chmod(file, "6755") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000577 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600578 return false;
579 }
580 }
581 file = "/system/xbin/su";
582 if (TWFunc::Path_Exists(file)) {
583 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000584 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600585 return false;
586 }
587 if (tw_chmod(file, "6755") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000588 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600589 return false;
590 }
591 }
592 file = "/system/bin/.ext/.su";
593 if (TWFunc::Path_Exists(file)) {
594 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000595 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600596 return false;
597 }
598 if (tw_chmod(file, "6755") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000599 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600600 return false;
601 }
602 }
603 file = "/system/app/Superuser.apk";
604 if (TWFunc::Path_Exists(file)) {
605 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000606 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600607 return false;
608 }
609 if (tw_chmod(file, "0644") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000610 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600611 return false;
612 }
613 }
614 sync();
615 if (!PartitionManager.UnMount_By_Path("/system", true))
616 return false;
617 return true;
618}
619
620int TWFunc::tw_chmod(string fn, string mode) {
621 long mask = 0;
622
623 for ( std::string::size_type n = 0; n < mode.length(); ++n) {
624 if (n == 0) {
625 if (mode[n] == '0')
626 continue;
627 if (mode[n] == '1')
628 mask |= S_ISVTX;
629 if (mode[n] == '2')
630 mask |= S_ISGID;
631 if (mode[n] == '4')
632 mask |= S_ISUID;
633 if (mode[n] == '5') {
634 mask |= S_ISVTX;
635 mask |= S_ISUID;
636 }
637 if (mode[n] == '6') {
638 mask |= S_ISGID;
639 mask |= S_ISUID;
640 }
641 if (mode[n] == '7') {
642 mask |= S_ISVTX;
643 mask |= S_ISGID;
644 mask |= S_ISUID;
645 }
646 }
647 else if (n == 1) {
648 if (mode[n] == '7') {
649 mask |= S_IRWXU;
650 }
651 if (mode[n] == '6') {
652 mask |= S_IRUSR;
653 mask |= S_IWUSR;
654 }
655 if (mode[n] == '5') {
656 mask |= S_IRUSR;
657 mask |= S_IXUSR;
658 }
659 if (mode[n] == '4')
660 mask |= S_IRUSR;
661 if (mode[n] == '3') {
662 mask |= S_IWUSR;
663 mask |= S_IRUSR;
664 }
665 if (mode[n] == '2')
666 mask |= S_IWUSR;
667 if (mode[n] == '1')
668 mask |= S_IXUSR;
669 }
670 else if (n == 2) {
671 if (mode[n] == '7') {
672 mask |= S_IRWXG;
673 }
674 if (mode[n] == '6') {
675 mask |= S_IRGRP;
676 mask |= S_IWGRP;
677 }
678 if (mode[n] == '5') {
679 mask |= S_IRGRP;
680 mask |= S_IXGRP;
681 }
682 if (mode[n] == '4')
683 mask |= S_IRGRP;
684 if (mode[n] == '3') {
685 mask |= S_IWGRP;
686 mask |= S_IXGRP;
687 }
688 if (mode[n] == '2')
689 mask |= S_IWGRP;
690 if (mode[n] == '1')
691 mask |= S_IXGRP;
692 }
693 else if (n == 3) {
694 if (mode[n] == '7') {
695 mask |= S_IRWXO;
696 }
697 if (mode[n] == '6') {
698 mask |= S_IROTH;
699 mask |= S_IWOTH;
700 }
701 if (mode[n] == '5') {
702 mask |= S_IROTH;
703 mask |= S_IXOTH;
704 }
705 if (mode[n] == '4')
706 mask |= S_IROTH;
707 if (mode[n] == '3') {
708 mask |= S_IWOTH;
709 mask |= S_IXOTH;
710 }
711 if (mode[n] == '2')
712 mask |= S_IWOTH;
713 if (mode[n] == '1')
714 mask |= S_IXOTH;
715 }
716 }
717
718 if (chmod(fn.c_str(), mask) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000719 LOGERR("Unable to chmod '%s' %l\n", fn.c_str(), mask);
Dees_Troy6ef66352013-02-21 08:26:57 -0600720 return -1;
721 }
722
723 return 0;
724}
725
726bool TWFunc::Install_SuperSU(void) {
727 if (!PartitionManager.Mount_By_Path("/system", true))
728 return false;
729
jt1134113ee732013-02-22 23:26:10 -0600730 if (copy_file("/supersu/su", "/system/xbin/su", 0755) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000731 LOGERR("Failed to copy su binary to /system/bin\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600732 return false;
733 }
jt1134113ee732013-02-22 23:26:10 -0600734 if (copy_file("/supersu/Superuser.apk", "/system/app/Superuser.apk", 0644) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000735 LOGERR("Failed to copy Superuser app to /system/app\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600736 return false;
737 }
738 if (!Fix_su_Perms())
739 return false;
740 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500741}
Dees_Troy83bd4832013-05-04 12:39:56 +0000742
743int TWFunc::Get_File_Type(string fn) {
744 string::size_type i = 0;
745 int firstbyte = 0, secondbyte = 0;
746 char header[3];
747
748 ifstream f;
749 f.open(fn.c_str(), ios::in | ios::binary);
750 f.get(header, 3);
751 f.close();
752 firstbyte = header[i] & 0xff;
753 secondbyte = header[++i] & 0xff;
754
755 if (firstbyte == 0x1f && secondbyte == 0x8b) {
756 return 1; // Compressed
757 } else if (firstbyte == 0x4f && secondbyte == 0x41) {
758 return 2; // Encrypted
759 } else {
760 return 0; // Unknown
761 }
762
763 return 0;
764}
765
766int TWFunc::Try_Decrypting_File(string fn, string password) {
767#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
768 OAES_CTX * ctx = NULL;
769 uint8_t _key_data[32] = "";
770 FILE *f;
771 uint8_t buffer[4096];
772 uint8_t *buffer_out = NULL;
773 uint8_t *ptr = NULL;
774 size_t read_len = 0, out_len = 0;
775 int firstbyte = 0, secondbyte = 0, key_len;
776 size_t _j = 0;
777 size_t _key_data_len = 0;
778
779 // mostly kanged from OpenAES oaes.c
780 for( _j = 0; _j < 32; _j++ )
781 _key_data[_j] = _j + 1;
782 _key_data_len = password.size();
783 if( 16 >= _key_data_len )
784 _key_data_len = 16;
785 else if( 24 >= _key_data_len )
786 _key_data_len = 24;
787 else
788 _key_data_len = 32;
789 memcpy(_key_data, password.c_str(), password.size());
790
791 ctx = oaes_alloc();
792 if (ctx == NULL) {
793 LOGERR("Failed to allocate OAES\n");
794 return -1;
795 }
796
797 oaes_key_import_data(ctx, _key_data, _key_data_len);
798
799 f = fopen(fn.c_str(), "rb");
800 if (f == NULL) {
801 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
802 return -1;
803 }
804 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
805 if (read_len <= 0) {
806 LOGERR("Read size during try decrypt failed\n");
807 fclose(f);
808 return -1;
809 }
810 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
811 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
812 fclose(f);
813 return -1;
814 }
815 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
816 if (buffer_out == NULL) {
817 LOGERR("Failed to allocate output buffer for try decrypt.\n");
818 fclose(f);
819 return -1;
820 }
821 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
822 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
823 fclose(f);
824 free(buffer_out);
825 return 0;
826 }
827 fclose(f);
828 if (out_len < 2) {
829 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
830 free(buffer_out);
831 return 1; // Decrypted successfully
832 }
833 ptr = buffer_out;
834 firstbyte = *ptr & 0xff;
835 ptr++;
836 secondbyte = *ptr & 0xff;
837 if (firstbyte == 0x1f && secondbyte == 0x8b) {
838 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
839 free(buffer_out);
840 return 3; // Compressed
841 }
842 if (out_len >= 262) {
843 ptr = buffer_out + 257;
844 if (strncmp((char*)ptr, "ustar", 5) == 0) {
845 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
846 free(buffer_out);
847 return 2; // Tar
848 }
849 }
850 free(buffer_out);
851 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
852 return 1; // Decrypted successfully
853#else
854 LOGERR("Encrypted backup support not included.\n");
855 return -1;
856#endif
857}
858
859bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
860 DIR* d;
861
862 string Filename;
863 Restore_Path += "/";
864 d = opendir(Restore_Path.c_str());
865 if (d == NULL) {
866 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
867 return false;
868 }
869
870 struct dirent* de;
871 while ((de = readdir(d)) != NULL) {
872 Filename = Restore_Path;
873 Filename += de->d_name;
874 if (TWFunc::Get_File_Type(Filename) == 2) {
875 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
876 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
877 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
878 closedir(d);
879 return false;
880 }
881 }
882 }
883 closedir(d);
884 return true;
885}
886
887int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
888 pid_t rc_pid;
889
890 rc_pid = waitpid(pid, status, 0);
891 if (rc_pid > 0) {
892 if (WEXITSTATUS(*status) == 0)
893 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
894 else if (WIFSIGNALED(*status)) {
895 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
896 return -1;
897 } else if (WEXITSTATUS(*status) != 0) {
898 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
899 return -1;
900 }
901 } else { // no PID returned
902 if (errno == ECHILD)
903 LOGINFO("%s no child process exist\n", Child_Name.c_str());
904 else {
905 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
906 return -1;
907 }
908 }
909 return 0;
910}