blob: 89714dd7d7e0bddbe9aa8e8b8b1b63b8d9d5b7df [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
2 Copyright 2012 bigbiff/Dees_Troy 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
Dees_Troy38bd7602012-09-14 13:33:53 -040019#include <stdio.h>
20#include <stdlib.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060021#include <string>
Dees_Troy38bd7602012-09-14 13:33:53 -040022#include <unistd.h>
23#include <vector>
24#include <dirent.h>
25#include <time.h>
Dees_Troy43d8b002012-09-17 16:00:01 -040026#include <errno.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050027#include <fcntl.h>
28#include <sys/mount.h>
Dees_Troya58bead2012-09-27 09:49:29 -040029#include <sys/reboot.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050030#include <sys/sendfile.h>
31#include <sys/stat.h>
32#include <sys/vfs.h>
Dees_Troy83bd4832013-05-04 12:39:56 +000033#include <sys/types.h>
34#include <sys/wait.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050035#include <iostream>
36#include <fstream>
Dees_Troy83bd4832013-05-04 12:39:56 +000037#include <sstream>
Dees_Troy38bd7602012-09-14 13:33:53 -040038#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000039#include "twcommon.h"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060040#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040041#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060042#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040043#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000044#include "bootloader.h"
Tom Hite5a926722014-09-15 01:31:03 +000045#include "cutils/properties.h"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060046#ifdef ANDROID_RB_POWEROFF
47 #include "cutils/android_reboot.h"
48#endif
49#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000050#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
51 #include "openaes/inc/oaes_lib.h"
52#endif
Dees_Troy38bd7602012-09-14 13:33:53 -040053
Dees_Troyb05ddee2013-01-28 20:24:50 +000054extern "C" {
55 #include "libcrecovery/common.h"
56}
57
bigbiff bigbiff9c754052013-01-09 09:09:08 -050058/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020059int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000060 FILE* exec;
61 char buffer[130];
62 int ret = 0;
63 exec = __popen(cmd.c_str(), "r");
64 if (!exec) return -1;
65 while(!feof(exec)) {
66 memset(&buffer, 0, sizeof(buffer));
67 if (fgets(buffer, 128, exec) != NULL) {
68 buffer[128] = '\n';
69 buffer[129] = NULL;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050070 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000071 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050072 }
Dees_Troy29a06352013-08-24 12:06:47 +000073 ret = __pclose(exec);
74 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050075}
76
Vojtech Bocek05534202013-09-11 08:11:56 +020077int TWFunc::Exec_Cmd(const string& cmd) {
78 pid_t pid;
79 int status;
80 switch(pid = fork())
81 {
82 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050083 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020084 return -1;
85 case 0: // child
86 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
87 _exit(127);
88 break;
89 default:
90 {
91 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
92 return -1;
93 else
94 return 0;
95 }
96 }
97}
98
Dees_Troy38bd7602012-09-14 13:33:53 -040099// Returns "file.name" from a full /path/to/file.name
100string TWFunc::Get_Filename(string Path) {
101 size_t pos = Path.find_last_of("/");
102 if (pos != string::npos) {
103 string Filename;
104 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
105 return Filename;
106 } else
107 return Path;
108}
109
110// Returns "/path/to/" from a full /path/to/file.name
111string TWFunc::Get_Path(string Path) {
112 size_t pos = Path.find_last_of("/");
113 if (pos != string::npos) {
114 string Pathonly;
115 Pathonly = Path.substr(0, pos + 1);
116 return Pathonly;
117 } else
118 return Path;
119}
120
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600121int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
122 pid_t rc_pid;
123
124 rc_pid = waitpid(pid, status, 0);
125 if (rc_pid > 0) {
126 if (WEXITSTATUS(*status) == 0)
127 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
128 else if (WIFSIGNALED(*status)) {
129 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
130 return -1;
131 } else if (WEXITSTATUS(*status) != 0) {
132 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
133 return -1;
134 }
135 } else { // no PID returned
136 if (errno == ECHILD)
137 LOGINFO("%s no child process exist\n", Child_Name.c_str());
138 else {
139 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
140 return -1;
141 }
142 }
143 return 0;
144}
145
146bool TWFunc::Path_Exists(string Path) {
147 // Check to see if the Path exists
148 struct stat st;
149 if (stat(Path.c_str(), &st) != 0)
150 return false;
151 else
152 return true;
153}
154
155int TWFunc::Get_File_Type(string fn) {
156 string::size_type i = 0;
157 int firstbyte = 0, secondbyte = 0;
158 char header[3];
159
160 ifstream f;
161 f.open(fn.c_str(), ios::in | ios::binary);
162 f.get(header, 3);
163 f.close();
164 firstbyte = header[i] & 0xff;
165 secondbyte = header[++i] & 0xff;
166
167 if (firstbyte == 0x1f && secondbyte == 0x8b)
168 return 1; // Compressed
169 else if (firstbyte == 0x4f && secondbyte == 0x41)
170 return 2; // Encrypted
171 else
172 return 0; // Unknown
173
174 return 0;
175}
176
177int TWFunc::Try_Decrypting_File(string fn, string password) {
178#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
179 OAES_CTX * ctx = NULL;
180 uint8_t _key_data[32] = "";
181 FILE *f;
182 uint8_t buffer[4096];
183 uint8_t *buffer_out = NULL;
184 uint8_t *ptr = NULL;
185 size_t read_len = 0, out_len = 0;
186 int firstbyte = 0, secondbyte = 0, key_len;
187 size_t _j = 0;
188 size_t _key_data_len = 0;
189
190 // mostly kanged from OpenAES oaes.c
191 for( _j = 0; _j < 32; _j++ )
192 _key_data[_j] = _j + 1;
193 _key_data_len = password.size();
194 if( 16 >= _key_data_len )
195 _key_data_len = 16;
196 else if( 24 >= _key_data_len )
197 _key_data_len = 24;
198 else
199 _key_data_len = 32;
200 memcpy(_key_data, password.c_str(), password.size());
201
202 ctx = oaes_alloc();
203 if (ctx == NULL) {
204 LOGERR("Failed to allocate OAES\n");
205 return -1;
206 }
207
208 oaes_key_import_data(ctx, _key_data, _key_data_len);
209
210 f = fopen(fn.c_str(), "rb");
211 if (f == NULL) {
212 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
213 return -1;
214 }
215 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
216 if (read_len <= 0) {
217 LOGERR("Read size during try decrypt failed\n");
218 fclose(f);
219 return -1;
220 }
221 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
222 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
223 fclose(f);
224 return -1;
225 }
226 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
227 if (buffer_out == NULL) {
228 LOGERR("Failed to allocate output buffer for try decrypt.\n");
229 fclose(f);
230 return -1;
231 }
232 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
233 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
234 fclose(f);
235 free(buffer_out);
236 return 0;
237 }
238 fclose(f);
239 if (out_len < 2) {
240 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
241 free(buffer_out);
242 return 1; // Decrypted successfully
243 }
244 ptr = buffer_out;
245 firstbyte = *ptr & 0xff;
246 ptr++;
247 secondbyte = *ptr & 0xff;
248 if (firstbyte == 0x1f && secondbyte == 0x8b) {
249 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
250 free(buffer_out);
251 return 3; // Compressed
252 }
253 if (out_len >= 262) {
254 ptr = buffer_out + 257;
255 if (strncmp((char*)ptr, "ustar", 5) == 0) {
256 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
257 free(buffer_out);
258 return 2; // Tar
259 }
260 }
261 free(buffer_out);
262 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
263 return 1; // Decrypted successfully
264#else
265 LOGERR("Encrypted backup support not included.\n");
266 return -1;
267#endif
268}
269
270unsigned long TWFunc::Get_File_Size(string Path) {
271 struct stat st;
272
273 if (stat(Path.c_str(), &st) != 0)
274 return 0;
275 return st.st_size;
276}
277
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100278std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
279{
280 std::string res;
281 size_t last_idx = 0, idx = 0;
282
283 while(last_idx != std::string::npos)
284 {
285 if(last_idx != 0)
286 res += '/';
287
288 idx = path.find_first_of('/', last_idx);
289 if(idx == std::string::npos) {
290 res += path.substr(last_idx, idx);
291 break;
292 }
293
294 res += path.substr(last_idx, idx-last_idx);
295 last_idx = path.find_first_not_of('/', idx);
296 }
297
298 if(leaveLast)
299 res += '/';
300 return res;
301}
302
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500303vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
304 vector<string> res;
305
306 if (in.empty() || del == '\0')
307 return res;
308
309 string field;
310 istringstream f(in);
311 if (del == '\n') {
312 while(getline(f, field)) {
313 if (field.empty() && skip_empty)
314 continue;
315 res.push_back(field);
316 }
317 } else {
318 while(getline(f, field, del)) {
319 if (field.empty() && skip_empty)
320 continue;
321 res.push_back(field);
322 }
323 }
324 return res;
325}
326
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600327#ifndef BUILD_TWRPTAR_MAIN
328
Dees_Troy38bd7602012-09-14 13:33:53 -0400329// Returns "/path" from a full /path/to/file.name
330string TWFunc::Get_Root_Path(string Path) {
331 string Local_Path = Path;
332
333 // Make sure that we have a leading slash
334 if (Local_Path.substr(0, 1) != "/")
335 Local_Path = "/" + Local_Path;
336
337 // Trim the path to get the root path only
338 size_t position = Local_Path.find("/", 2);
339 if (position != string::npos) {
340 Local_Path.resize(position);
341 }
342 return Local_Path;
343}
344
345void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400346 int need_libs = 0;
347
348 if (!PartitionManager.Mount_By_Path("/system", true))
349 return;
350
351 if (!PartitionManager.Mount_By_Path("/data", true))
352 return;
353
Dees_Troy2673cec2013-04-02 20:22:16 +0000354 gui_print("Installing HTC Dumlock to system...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500355 copy_file("/res/htcd/htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400356 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000357 gui_print("Installing flash_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500358 copy_file("/res/htcd/flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400359 need_libs = 1;
360 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000361 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400362 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000363 gui_print("Installing dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500364 copy_file("/res/htcd/dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400365 need_libs = 1;
366 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000367 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400368 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000369 gui_print("Installing libs needed for flash_image and dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500370 copy_file("/res/htcd/libbmlutils.so", "/system/lib/libbmlutils.so", 0755);
371 copy_file("/res/htcd/libflashutils.so", "/system/lib/libflashutils.so", 0755);
372 copy_file("/res/htcd/libmmcutils.so", "/system/lib/libmmcutils.so", 0755);
373 copy_file("/res/htcd/libmtdutils.so", "/system/lib/libmtdutils.so", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400374 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000375 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400376 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500377 unlink("/data/app/com.teamwin.htcdumlock*");
378 copy_file("/res/htcd/HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400379 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000380 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400381}
382
383void TWFunc::htc_dumlock_restore_original_boot(void) {
384 if (!PartitionManager.Mount_By_Path("/sdcard", true))
385 return;
386
Dees_Troy2673cec2013-04-02 20:22:16 +0000387 gui_print("Restoring original boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200388 Exec_Cmd("htcdumlock restore");
Dees_Troy2673cec2013-04-02 20:22:16 +0000389 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400390}
391
392void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
393 if (!PartitionManager.Mount_By_Path("/sdcard", true))
394 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000395 gui_print("Reflashing recovery to boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200396 Exec_Cmd("htcdumlock recovery noreboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000397 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400398}
Dees_Troy43d8b002012-09-17 16:00:01 -0400399
400int TWFunc::Recursive_Mkdir(string Path) {
401 string pathCpy = Path;
402 string wholePath;
403 size_t pos = pathCpy.find("/", 2);
404
405 while (pos != string::npos)
406 {
407 wholePath = pathCpy.substr(0, pos);
408 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000409 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
Dees_Troy43d8b002012-09-17 16:00:01 -0400410 return false;
411 }
412
413 pos = pathCpy.find("/", pos + 1);
414 }
415 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
416 return false;
417 return true;
418}
419
Dees_Troyb46a6842012-09-25 11:06:46 -0400420void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
421 string Display_Text;
422
423 DataManager::GetValue(Read_Value, Display_Text);
424 if (Display_Text.empty())
425 Display_Text = Default_Text;
426
427 DataManager::SetValue("tw_operation", Display_Text);
428 DataManager::SetValue("tw_partition", "");
429}
430
431void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
432 string Display_Text;
433
434 DataManager::GetValue(Read_Value, Display_Text);
435 if (Display_Text.empty())
436 Display_Text = Default_Text;
437
438 DataManager::SetValue("tw_operation", Display_Text);
439 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400440}
441
Dees_Troy2673cec2013-04-02 20:22:16 +0000442void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000443 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000444 FILE *destination_log = fopen(Destination.c_str(), "a");
445 if (destination_log == NULL) {
446 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600447 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000448 FILE *source_log = fopen(Source.c_str(), "r");
449 if (source_log != NULL) {
450 fseek(source_log, Log_Offset, SEEK_SET);
451 char buffer[4096];
452 while (fgets(buffer, sizeof(buffer), source_log))
453 fputs(buffer, destination_log); // Buffered write of log file
454 Log_Offset = ftell(source_log);
455 fflush(source_log);
456 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600457 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000458 fflush(destination_log);
459 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600460 }
Dees_Troya58bead2012-09-27 09:49:29 -0400461}
462
Dees_Troy2673cec2013-04-02 20:22:16 +0000463void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500464 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000465 if (PartitionManager.Mount_By_Path("/cache", false)) {
466 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
467 LOGINFO("Recreating /cache/recovery folder.\n");
468 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
469 LOGINFO("Unable to create /cache/recovery folder.\n");
470 }
471 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
472 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
473 chown("/cache/recovery/log", 1000, 1000);
474 chmod("/cache/recovery/log", 0600);
475 chmod("/cache/recovery/last_log", 0640);
476 } else {
477 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
478 }
Dees_Troya58bead2012-09-27 09:49:29 -0400479
Dees_Troy2673cec2013-04-02 20:22:16 +0000480 // Reset bootloader message
481 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
482 if (Part != NULL) {
483 struct bootloader_message boot;
484 memset(&boot, 0, sizeof(boot));
485 if (Part->Current_File_System == "mtd") {
486 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
487 LOGERR("Unable to set MTD bootloader message.\n");
488 } else if (Part->Current_File_System == "emmc") {
489 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
490 LOGERR("Unable to set emmc bootloader message.\n");
491 } else {
492 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
493 }
494 }
Dees_Troya58bead2012-09-27 09:49:29 -0400495
Dees Troy9d7fdf52013-09-19 20:49:25 +0000496 if (PartitionManager.Mount_By_Path("/cache", true)) {
497 if (unlink("/cache/recovery/command") && errno != ENOENT) {
498 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
499 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500500 }
Dees_Troya58bead2012-09-27 09:49:29 -0400501
Dees_Troy2673cec2013-04-02 20:22:16 +0000502 sync();
503}
504
505void TWFunc::Update_Intent_File(string Intent) {
506 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
507 TWFunc::write_file("/cache/recovery/intent", Intent);
508 }
Dees_Troya58bead2012-09-27 09:49:29 -0400509}
510
511// reboot: Reboot the system. Return -1 on error, no return on success
512int TWFunc::tw_reboot(RebootCommand command)
513{
514 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600515 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400516
Dees_Troy2673cec2013-04-02 20:22:16 +0000517 switch (command) {
518 case rb_current:
519 case rb_system:
520 Update_Log_File();
521 Update_Intent_File("s");
522 sync();
523 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
524 return reboot(RB_AUTOBOOT);
525 case rb_recovery:
526 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
527 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
528 case rb_bootloader:
529 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
530 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
531 case rb_poweroff:
532 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000533#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000534 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000535#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000536 return reboot(RB_POWER_OFF);
537 case rb_download:
538 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
539 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
540 default:
541 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600542 }
543 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400544}
545
546void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
547{
548 // Check for and run startup script if script exists
549 struct stat st;
550 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000551 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500552 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200553 TWFunc::Exec_Cmd(script_file);
Dees_Troy2673cec2013-04-02 20:22:16 +0000554 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400555 }
Dees_Troy3477d712012-09-27 15:44:01 -0400556}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500557
558int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000559 DIR *d = opendir(path.c_str());
560 int r = 0;
561 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500562
Dees_Troyce675462013-01-09 19:48:21 +0000563 if (d == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000564 LOGERR("Error opening '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000565 return -1;
566 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500567
Dees_Troyce675462013-01-09 19:48:21 +0000568 if (d) {
569 struct dirent *p;
570 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000571 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
572 continue;
573 new_path = path + "/";
574 new_path.append(p->d_name);
575 if (p->d_type == DT_DIR) {
576 r = removeDir(new_path, true);
577 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500578 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500579 r = rmdir(new_path.c_str());
580 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000581 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500582 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500583 } 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 +0000584 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000585 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000586 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000587 }
Dees_Troyce675462013-01-09 19:48:21 +0000588 }
589 }
590 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500591
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500592 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500593 if (skipParent)
594 return 0;
595 else
596 r = rmdir(path.c_str());
597 }
Dees_Troyce675462013-01-09 19:48:21 +0000598 }
599 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500600}
601
602int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000603 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500604 ifstream srcfile(src.c_str(), ios::binary);
605 ofstream dstfile(dst.c_str(), ios::binary);
606 dstfile << srcfile.rdbuf();
607 srcfile.close();
608 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500609 if (chmod(dst.c_str(), mode) != 0)
610 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500611 return 0;
612}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000613
614unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
615 struct stat st;
616
617 stat(Path.c_str(), &st);
618 if (st.st_mode & S_IFDIR)
619 return DT_DIR;
620 else if (st.st_mode & S_IFBLK)
621 return DT_BLK;
622 else if (st.st_mode & S_IFCHR)
623 return DT_CHR;
624 else if (st.st_mode & S_IFIFO)
625 return DT_FIFO;
626 else if (st.st_mode & S_IFLNK)
627 return DT_LNK;
628 else if (st.st_mode & S_IFREG)
629 return DT_REG;
630 else if (st.st_mode & S_IFSOCK)
631 return DT_SOCK;
632 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000633}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500634
635int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200636 ifstream file;
637 file.open(fn.c_str(), ios::in);
638
639 if (file.is_open()) {
640 file >> results;
641 file.close();
642 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500643 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200644
645 LOGINFO("Cannot find file %s\n", fn.c_str());
646 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500647}
648
649int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500650 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500651 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500652 file.open(fn.c_str(), ios::in);
653 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500654 while (getline(file, line))
655 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500656 file.close();
657 return 0;
658 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000659 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500660 return -1;
661}
662
xNUTxe85f02d2014-07-18 01:30:58 +0200663int TWFunc::read_file(string fn, uint64_t& results) {
664 ifstream file;
665 file.open(fn.c_str(), ios::in);
666
667 if (file.is_open()) {
668 file >> results;
669 file.close();
670 return 0;
671 }
672
673 LOGINFO("Cannot find file %s\n", fn.c_str());
674 return -1;
675}
676
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500677int TWFunc::write_file(string fn, string& line) {
678 FILE *file;
679 file = fopen(fn.c_str(), "w");
680 if (file != NULL) {
681 fwrite(line.c_str(), line.size(), 1, file);
682 fclose(file);
683 return 0;
684 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000685 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500686 return -1;
687}
688
689timespec TWFunc::timespec_diff(timespec& start, timespec& end)
690{
Dees_Troy6ef66352013-02-21 08:26:57 -0600691 timespec temp;
692 if ((end.tv_nsec-start.tv_nsec)<0) {
693 temp.tv_sec = end.tv_sec-start.tv_sec-1;
694 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
695 } else {
696 temp.tv_sec = end.tv_sec-start.tv_sec;
697 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
698 }
699 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500700}
701
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100702int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
703{
704 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
705 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
706}
707
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200708int TWFunc::drop_caches(void) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600709 string file = "/proc/sys/vm/drop_caches";
710 string value = "3";
711 if (write_file(file, value) != 0)
712 return -1;
713 return 0;
714}
715
716int TWFunc::Check_su_Perms(void) {
717 struct stat st;
718 int ret = 0;
719
720 if (!PartitionManager.Mount_By_Path("/system", false))
721 return 0;
722
723 // Check to ensure that perms are 6755 for all 3 file locations
724 if (stat("/system/bin/su", &st) == 0) {
725 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) {
726 ret = 1;
727 }
728 }
729 if (stat("/system/xbin/su", &st) == 0) {
730 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) {
731 ret += 2;
732 }
733 }
734 if (stat("/system/bin/.ext/.su", &st) == 0) {
735 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) {
736 ret += 4;
737 }
738 }
739 return ret;
740}
741
742bool TWFunc::Fix_su_Perms(void) {
743 if (!PartitionManager.Mount_By_Path("/system", true))
744 return false;
745
Ethan Yonker0385f512014-02-06 14:33:02 -0600746 string propvalue = System_Property_Get("ro.build.version.sdk");
747 string su_perms = "6755";
748 if (!propvalue.empty()) {
749 int sdk_version = atoi(propvalue.c_str());
750 if (sdk_version >= 18)
751 su_perms = "0755";
752 }
753
Dees_Troy6ef66352013-02-21 08:26:57 -0600754 string file = "/system/bin/su";
755 if (TWFunc::Path_Exists(file)) {
756 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000757 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600758 return false;
759 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600760 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000761 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600762 return false;
763 }
764 }
765 file = "/system/xbin/su";
766 if (TWFunc::Path_Exists(file)) {
767 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000768 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600769 return false;
770 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600771 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000772 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600773 return false;
774 }
775 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000776 file = "/system/xbin/daemonsu";
777 if (TWFunc::Path_Exists(file)) {
778 if (chown(file.c_str(), 0, 0) != 0) {
779 LOGERR("Failed to chown '%s'\n", file.c_str());
780 return false;
781 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600782 if (tw_chmod(file, "0755") != 0) {
Dees_Troya7939bb2013-08-29 20:21:12 +0000783 LOGERR("Failed to chmod '%s'\n", file.c_str());
784 return false;
785 }
786 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600787 file = "/system/bin/.ext/.su";
788 if (TWFunc::Path_Exists(file)) {
789 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000790 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600791 return false;
792 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600793 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000794 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600795 return false;
796 }
797 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000798 file = "/system/etc/install-recovery.sh";
799 if (TWFunc::Path_Exists(file)) {
800 if (chown(file.c_str(), 0, 0) != 0) {
801 LOGERR("Failed to chown '%s'\n", file.c_str());
802 return false;
803 }
804 if (tw_chmod(file, "0755") != 0) {
805 LOGERR("Failed to chmod '%s'\n", file.c_str());
806 return false;
807 }
808 }
809 file = "/system/etc/init.d/99SuperSUDaemon";
810 if (TWFunc::Path_Exists(file)) {
811 if (chown(file.c_str(), 0, 0) != 0) {
812 LOGERR("Failed to chown '%s'\n", file.c_str());
813 return false;
814 }
815 if (tw_chmod(file, "0755") != 0) {
816 LOGERR("Failed to chmod '%s'\n", file.c_str());
817 return false;
818 }
819 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600820 file = "/system/app/Superuser.apk";
821 if (TWFunc::Path_Exists(file)) {
822 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000823 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600824 return false;
825 }
826 if (tw_chmod(file, "0644") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000827 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600828 return false;
829 }
830 }
831 sync();
832 if (!PartitionManager.UnMount_By_Path("/system", true))
833 return false;
834 return true;
835}
836
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200837int TWFunc::tw_chmod(const string& fn, const string& mode) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600838 long mask = 0;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200839 std::string::size_type n = mode.length();
840 int cls = 0;
Dees_Troy6ef66352013-02-21 08:26:57 -0600841
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200842 if(n == 3)
843 ++cls;
844 else if(n != 4)
845 {
846 LOGERR("TWFunc::tw_chmod used with %u long mode string (should be 3 or 4)!\n", mode.length());
847 return -1;
848 }
849
850 for (n = 0; n < mode.length(); ++n, ++cls) {
851 if (cls == 0) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600852 if (mode[n] == '0')
853 continue;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200854 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600855 mask |= S_ISVTX;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200856 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600857 mask |= S_ISGID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200858 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600859 mask |= S_ISUID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200860 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600861 mask |= S_ISVTX;
862 mask |= S_ISUID;
863 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200864 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600865 mask |= S_ISGID;
866 mask |= S_ISUID;
867 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200868 else if (mode[n] == '7') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600869 mask |= S_ISVTX;
870 mask |= S_ISGID;
871 mask |= S_ISUID;
872 }
873 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200874 else if (cls == 1) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600875 if (mode[n] == '7') {
876 mask |= S_IRWXU;
877 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200878 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600879 mask |= S_IRUSR;
880 mask |= S_IWUSR;
881 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200882 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600883 mask |= S_IRUSR;
884 mask |= S_IXUSR;
885 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200886 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600887 mask |= S_IRUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200888 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600889 mask |= S_IWUSR;
890 mask |= S_IRUSR;
891 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200892 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600893 mask |= S_IWUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200894 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600895 mask |= S_IXUSR;
896 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200897 else if (cls == 2) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600898 if (mode[n] == '7') {
899 mask |= S_IRWXG;
900 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200901 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600902 mask |= S_IRGRP;
903 mask |= S_IWGRP;
904 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200905 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600906 mask |= S_IRGRP;
907 mask |= S_IXGRP;
908 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200909 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600910 mask |= S_IRGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200911 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600912 mask |= S_IWGRP;
913 mask |= S_IXGRP;
914 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200915 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600916 mask |= S_IWGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200917 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600918 mask |= S_IXGRP;
919 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200920 else if (cls == 3) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600921 if (mode[n] == '7') {
922 mask |= S_IRWXO;
923 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200924 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600925 mask |= S_IROTH;
926 mask |= S_IWOTH;
927 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200928 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600929 mask |= S_IROTH;
930 mask |= S_IXOTH;
931 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200932 else if (mode[n] == '4')
933 mask |= S_IROTH;
934 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600935 mask |= S_IWOTH;
936 mask |= S_IXOTH;
937 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200938 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600939 mask |= S_IWOTH;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200940 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600941 mask |= S_IXOTH;
942 }
943 }
944
945 if (chmod(fn.c_str(), mask) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000946 LOGERR("Unable to chmod '%s' %l\n", fn.c_str(), mask);
Dees_Troy6ef66352013-02-21 08:26:57 -0600947 return -1;
948 }
949
950 return 0;
951}
952
953bool TWFunc::Install_SuperSU(void) {
954 if (!PartitionManager.Mount_By_Path("/system", true))
955 return false;
956
Vojtech Bocek05534202013-09-11 08:11:56 +0200957 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/su");
jt1134113ee732013-02-22 23:26:10 -0600958 if (copy_file("/supersu/su", "/system/xbin/su", 0755) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000959 LOGERR("Failed to copy su binary to /system/bin\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600960 return false;
961 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000962 if (!Path_Exists("/system/bin/.ext")) {
963 mkdir("/system/bin/.ext", 0777);
964 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200965 TWFunc::Exec_Cmd("/sbin/chattr -i /system/bin/.ext/su");
Dees_Troya7939bb2013-08-29 20:21:12 +0000966 if (copy_file("/supersu/su", "/system/bin/.ext/su", 0755) != 0) {
967 LOGERR("Failed to copy su binary to /system/bin/.ext/su\n");
968 return false;
969 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200970 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/daemonsu");
Dees_Troya7939bb2013-08-29 20:21:12 +0000971 if (copy_file("/supersu/su", "/system/xbin/daemonsu", 0755) != 0) {
972 LOGERR("Failed to copy su binary to /system/xbin/daemonsu\n");
973 return false;
974 }
975 if (Path_Exists("/system/etc/init.d")) {
Vojtech Bocek05534202013-09-11 08:11:56 +0200976 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/init.d/99SuperSUDaemon");
Dees_Troya7939bb2013-08-29 20:21:12 +0000977 if (copy_file("/supersu/99SuperSUDaemon", "/system/etc/init.d/99SuperSUDaemon", 0755) != 0) {
978 LOGERR("Failed to copy 99SuperSUDaemon to /system/etc/init.d/99SuperSUDaemon\n");
979 return false;
980 }
981 } else {
Vojtech Bocek05534202013-09-11 08:11:56 +0200982 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/install-recovery.sh");
Dees_Troya7939bb2013-08-29 20:21:12 +0000983 if (copy_file("/supersu/install-recovery.sh", "/system/etc/install-recovery.sh", 0755) != 0) {
984 LOGERR("Failed to copy install-recovery.sh to /system/etc/install-recovery.sh\n");
985 return false;
986 }
987 }
jt1134113ee732013-02-22 23:26:10 -0600988 if (copy_file("/supersu/Superuser.apk", "/system/app/Superuser.apk", 0644) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000989 LOGERR("Failed to copy Superuser app to /system/app\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600990 return false;
991 }
992 if (!Fix_su_Perms())
993 return false;
994 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500995}
Dees_Troy83bd4832013-05-04 12:39:56 +0000996
Dees_Troy83bd4832013-05-04 12:39:56 +0000997bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
998 DIR* d;
999
1000 string Filename;
1001 Restore_Path += "/";
1002 d = opendir(Restore_Path.c_str());
1003 if (d == NULL) {
1004 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
1005 return false;
1006 }
1007
1008 struct dirent* de;
1009 while ((de = readdir(d)) != NULL) {
1010 Filename = Restore_Path;
1011 Filename += de->d_name;
1012 if (TWFunc::Get_File_Type(Filename) == 2) {
1013 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
1014 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
1015 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
1016 closedir(d);
1017 return false;
1018 }
1019 }
1020 }
1021 closedir(d);
1022 return true;
1023}
1024
Dees Troyb21cc642013-09-10 17:36:41 +00001025string TWFunc::Get_Current_Date() {
1026 string Current_Date;
1027 time_t seconds = time(0);
1028 struct tm *t = localtime(&seconds);
1029 char timestamp[255];
1030 sprintf(timestamp,"%04d-%02d-%02d--%02d-%02d-%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
1031 Current_Date = timestamp;
1032 return Current_Date;
1033}
1034
Ethan Yonkerb5557892014-02-07 21:43:20 -06001035string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001036 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
1037 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001038 string propvalue;
1039 if (!PartitionManager.Mount_By_Path("/system", true))
1040 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001041 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -06001042 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +02001043 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +00001044 if (!mount_state)
1045 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001046 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001047 }
1048 int line_count = buildprop.size();
1049 int index;
1050 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001051 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +00001052 for (index = 0; index < line_count; index++) {
1053 end_pos = buildprop.at(index).find("=", start_pos);
1054 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001055 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001056 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -06001057 if (!mount_state)
1058 PartitionManager.UnMount_By_Path("/system", false);
1059 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001060 }
1061 }
Dees Troyb21cc642013-09-10 17:36:41 +00001062 if (!mount_state)
1063 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001064 return propvalue;
1065}
1066
1067void TWFunc::Auto_Generate_Backup_Name() {
1068 string propvalue = System_Property_Get("ro.build.display.id");
1069 if (propvalue.empty()) {
1070 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1071 return;
1072 }
1073 string Backup_Name = Get_Current_Date();
1074 Backup_Name += " " + propvalue;
1075 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
1076 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
1077 // Trailing spaces cause problems on some file systems, so remove them
1078 string space_check, space = " ";
1079 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1080 while (space_check == space) {
1081 Backup_Name.resize(Backup_Name.size() - 1);
1082 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1083 }
1084 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -06001085 if (PartitionManager.Check_Backup_Name(false) != 0) {
1086 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
1087 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1088 }
Vojtech Bocek05534202013-09-11 08:11:56 +02001089}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001090
1091void TWFunc::Fixup_Time_On_Boot()
1092{
1093#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +02001094
1095 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
1096
1097 struct timeval tv;
1098 uint64_t offset = 0;
1099 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
1100
1101 if (TWFunc::read_file(sepoch, offset) == 0) {
1102
1103 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
1104
1105 tv.tv_sec = offset;
1106 tv.tv_usec = 0;
1107 settimeofday(&tv, NULL);
1108
1109 gettimeofday(&tv, NULL);
1110
1111 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
1112
1113 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1114 return;
1115
1116 }
1117
1118 } else {
1119
1120 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
1121
1122 }
1123
1124 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n", sepoch.c_str());
1125
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001126 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
1127 // They never set it, it just ticks forward from 1970-01-01 00:00,
1128 // and then they have files /data/system/time/ats_* with 64bit offset
1129 // in miliseconds which, when added to the RTC, gives the correct time.
1130 // So, the time is: (offset_from_ats + value_from_RTC)
1131 // There are multiple ats files, they are for different systems? Bases?
1132 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1133 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1134
1135 static const char *paths[] = { "/data/system/time/", "/data/time/" };
1136
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001137 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001138 DIR *d;
1139 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001140 struct dirent *dt;
1141 std::string ats_path;
1142
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001143 if(!PartitionManager.Mount_By_Path("/data", false))
1144 return;
1145
1146 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1147 // - it is the one for ATS_TOD (time of day?).
1148 // However, I never saw a device where the offset differs between ats files.
1149 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
1150 {
1151 DIR *d = opendir(paths[i]);
1152 if(!d)
1153 continue;
1154
1155 while((dt = readdir(d)))
1156 {
1157 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
1158 continue;
1159
1160 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
1161 ats_path = std::string(paths[i]).append(dt->d_name);
1162 }
1163
1164 closedir(d);
1165 }
1166
1167 if(ats_path.empty())
1168 {
xNUTxe85f02d2014-07-18 01:30:58 +02001169 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001170 return;
1171 }
1172
1173 f = fopen(ats_path.c_str(), "r");
1174 if(!f)
1175 {
Dees Troy3e254b92014-03-06 20:24:54 +00001176 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001177 return;
1178 }
1179
1180 if(fread(&offset, sizeof(offset), 1, f) != 1)
1181 {
Dees Troy3e254b92014-03-06 20:24:54 +00001182 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001183 fclose(f);
1184 return;
1185 }
1186 fclose(f);
1187
1188 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
1189
1190 gettimeofday(&tv, NULL);
1191
1192 tv.tv_sec += offset/1000;
1193 tv.tv_usec += (offset%1000)*1000;
1194
1195 while(tv.tv_usec >= 1000000)
1196 {
1197 ++tv.tv_sec;
1198 tv.tv_usec -= 1000000;
1199 }
1200
1201 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001202
1203 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1204
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001205#endif
1206}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001207
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001208std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1209{
1210 std::vector<std::string> res;
1211 size_t idx = 0, idx_last = 0;
1212
1213 while(idx < str.size())
1214 {
1215 idx = str.find_first_of(delimiter, idx_last);
1216 if(idx == std::string::npos)
1217 idx = str.size();
1218
1219 if(idx-idx_last != 0 || !removeEmpty)
1220 res.push_back(str.substr(idx_last, idx-idx_last));
1221
1222 idx_last = idx + delimiter.size();
1223 }
1224
1225 return res;
1226}
1227
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001228bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1229{
1230 std::vector<std::string> parts = Split_String(path, "/");
1231 std::string cur_path;
1232 struct stat info;
1233 for(size_t i = 0; i < parts.size(); ++i)
1234 {
1235 cur_path += "/" + parts[i];
1236 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
1237 {
1238 if(mkdir(cur_path.c_str(), mode) < 0)
1239 return false;
1240 chown(cur_path.c_str(), uid, gid);
1241 }
1242 }
1243 return true;
1244}
1245
xNUTxe85f02d2014-07-18 01:30:58 +02001246int TWFunc::Set_Brightness(std::string brightness_value)
1247{
1248
1249 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
1250
1251 if (brightness_file.compare("/nobrightness") != 0) {
1252 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
1253 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
1254 int result = TWFunc::write_file(brightness_file, brightness_value);
1255 if (secondary_brightness_file != "") {
1256 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
1257 TWFunc::write_file(secondary_brightness_file, brightness_value);
1258 }
1259 return result;
1260 }
1261 return -1;
1262}
1263
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001264bool TWFunc::Toggle_MTP(bool enable) {
1265#ifdef TW_HAS_MTP
1266 static int was_enabled = false;
1267
1268 if (enable && was_enabled) {
1269 if (!PartitionManager.Enable_MTP())
1270 PartitionManager.Disable_MTP();
1271 } else {
1272 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1273 PartitionManager.Disable_MTP();
1274 usleep(500);
1275 }
1276 return was_enabled;
1277#else
1278 return false;
1279#endif
1280}
1281
Tom Hite5a926722014-09-15 01:31:03 +00001282void TWFunc::SetPerformanceMode(bool mode) {
1283 if (mode) {
1284 property_set("recovery.perf.mode", "1");
1285 } else {
1286 property_set("recovery.perf.mode", "0");
1287 }
1288 // Some time for events to catch up to init handlers
1289 usleep(500000);
1290}
1291
Jenkins1710bf22014-10-02 20:22:21 -04001292std::string TWFunc::to_string(unsigned long value) {
1293 std::ostringstream os;
1294 os << value;
1295 return os.str();
1296}
1297
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001298#endif // ndef BUILD_TWRPTAR_MAIN