blob: a2970b0074b72cdf32dd547b441d62914596fdd4 [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
Ethan Yonkerd7f20922014-11-07 10:33:08 -060053#include "cutils/android_reboot.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040054
Dees_Troyb05ddee2013-01-28 20:24:50 +000055extern "C" {
56 #include "libcrecovery/common.h"
57}
58
bigbiff bigbiff9c754052013-01-09 09:09:08 -050059/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020060int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000061 FILE* exec;
62 char buffer[130];
63 int ret = 0;
64 exec = __popen(cmd.c_str(), "r");
65 if (!exec) return -1;
66 while(!feof(exec)) {
67 memset(&buffer, 0, sizeof(buffer));
68 if (fgets(buffer, 128, exec) != NULL) {
69 buffer[128] = '\n';
thatd43bf2d2014-09-21 23:13:02 +020070 buffer[129] = 0;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050071 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000072 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050073 }
Dees_Troy29a06352013-08-24 12:06:47 +000074 ret = __pclose(exec);
75 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050076}
77
Vojtech Bocek05534202013-09-11 08:11:56 +020078int TWFunc::Exec_Cmd(const string& cmd) {
79 pid_t pid;
80 int status;
81 switch(pid = fork())
82 {
83 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050084 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020085 return -1;
86 case 0: // child
87 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
88 _exit(127);
89 break;
90 default:
91 {
92 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
93 return -1;
94 else
95 return 0;
96 }
97 }
98}
99
Dees_Troy38bd7602012-09-14 13:33:53 -0400100// Returns "file.name" from a full /path/to/file.name
101string TWFunc::Get_Filename(string Path) {
102 size_t pos = Path.find_last_of("/");
103 if (pos != string::npos) {
104 string Filename;
105 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
106 return Filename;
107 } else
108 return Path;
109}
110
111// Returns "/path/to/" from a full /path/to/file.name
112string TWFunc::Get_Path(string Path) {
113 size_t pos = Path.find_last_of("/");
114 if (pos != string::npos) {
115 string Pathonly;
116 Pathonly = Path.substr(0, pos + 1);
117 return Pathonly;
118 } else
119 return Path;
120}
121
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600122int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
123 pid_t rc_pid;
124
125 rc_pid = waitpid(pid, status, 0);
126 if (rc_pid > 0) {
127 if (WEXITSTATUS(*status) == 0)
128 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
129 else if (WIFSIGNALED(*status)) {
130 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
131 return -1;
132 } else if (WEXITSTATUS(*status) != 0) {
133 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
134 return -1;
135 }
136 } else { // no PID returned
137 if (errno == ECHILD)
138 LOGINFO("%s no child process exist\n", Child_Name.c_str());
139 else {
140 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
141 return -1;
142 }
143 }
144 return 0;
145}
146
147bool TWFunc::Path_Exists(string Path) {
148 // Check to see if the Path exists
149 struct stat st;
150 if (stat(Path.c_str(), &st) != 0)
151 return false;
152 else
153 return true;
154}
155
156int TWFunc::Get_File_Type(string fn) {
157 string::size_type i = 0;
158 int firstbyte = 0, secondbyte = 0;
159 char header[3];
160
161 ifstream f;
162 f.open(fn.c_str(), ios::in | ios::binary);
163 f.get(header, 3);
164 f.close();
165 firstbyte = header[i] & 0xff;
166 secondbyte = header[++i] & 0xff;
167
168 if (firstbyte == 0x1f && secondbyte == 0x8b)
169 return 1; // Compressed
170 else if (firstbyte == 0x4f && secondbyte == 0x41)
171 return 2; // Encrypted
172 else
173 return 0; // Unknown
174
175 return 0;
176}
177
178int TWFunc::Try_Decrypting_File(string fn, string password) {
179#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
180 OAES_CTX * ctx = NULL;
181 uint8_t _key_data[32] = "";
182 FILE *f;
183 uint8_t buffer[4096];
184 uint8_t *buffer_out = NULL;
185 uint8_t *ptr = NULL;
186 size_t read_len = 0, out_len = 0;
187 int firstbyte = 0, secondbyte = 0, key_len;
188 size_t _j = 0;
189 size_t _key_data_len = 0;
190
191 // mostly kanged from OpenAES oaes.c
192 for( _j = 0; _j < 32; _j++ )
193 _key_data[_j] = _j + 1;
194 _key_data_len = password.size();
195 if( 16 >= _key_data_len )
196 _key_data_len = 16;
197 else if( 24 >= _key_data_len )
198 _key_data_len = 24;
199 else
200 _key_data_len = 32;
201 memcpy(_key_data, password.c_str(), password.size());
202
203 ctx = oaes_alloc();
204 if (ctx == NULL) {
205 LOGERR("Failed to allocate OAES\n");
206 return -1;
207 }
208
209 oaes_key_import_data(ctx, _key_data, _key_data_len);
210
211 f = fopen(fn.c_str(), "rb");
212 if (f == NULL) {
213 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
214 return -1;
215 }
216 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
217 if (read_len <= 0) {
218 LOGERR("Read size during try decrypt failed\n");
219 fclose(f);
220 return -1;
221 }
222 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
223 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
224 fclose(f);
225 return -1;
226 }
227 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
228 if (buffer_out == NULL) {
229 LOGERR("Failed to allocate output buffer for try decrypt.\n");
230 fclose(f);
231 return -1;
232 }
233 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
234 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
235 fclose(f);
236 free(buffer_out);
237 return 0;
238 }
239 fclose(f);
240 if (out_len < 2) {
241 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
242 free(buffer_out);
243 return 1; // Decrypted successfully
244 }
245 ptr = buffer_out;
246 firstbyte = *ptr & 0xff;
247 ptr++;
248 secondbyte = *ptr & 0xff;
249 if (firstbyte == 0x1f && secondbyte == 0x8b) {
250 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
251 free(buffer_out);
252 return 3; // Compressed
253 }
254 if (out_len >= 262) {
255 ptr = buffer_out + 257;
256 if (strncmp((char*)ptr, "ustar", 5) == 0) {
257 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
258 free(buffer_out);
259 return 2; // Tar
260 }
261 }
262 free(buffer_out);
263 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
264 return 1; // Decrypted successfully
265#else
266 LOGERR("Encrypted backup support not included.\n");
267 return -1;
268#endif
269}
270
271unsigned long TWFunc::Get_File_Size(string Path) {
272 struct stat st;
273
274 if (stat(Path.c_str(), &st) != 0)
275 return 0;
276 return st.st_size;
277}
278
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100279std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
280{
281 std::string res;
282 size_t last_idx = 0, idx = 0;
283
284 while(last_idx != std::string::npos)
285 {
286 if(last_idx != 0)
287 res += '/';
288
289 idx = path.find_first_of('/', last_idx);
290 if(idx == std::string::npos) {
291 res += path.substr(last_idx, idx);
292 break;
293 }
294
295 res += path.substr(last_idx, idx-last_idx);
296 last_idx = path.find_first_not_of('/', idx);
297 }
298
299 if(leaveLast)
300 res += '/';
301 return res;
302}
303
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500304vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
305 vector<string> res;
306
307 if (in.empty() || del == '\0')
308 return res;
309
310 string field;
311 istringstream f(in);
312 if (del == '\n') {
313 while(getline(f, field)) {
314 if (field.empty() && skip_empty)
315 continue;
316 res.push_back(field);
317 }
318 } else {
319 while(getline(f, field, del)) {
320 if (field.empty() && skip_empty)
321 continue;
322 res.push_back(field);
323 }
324 }
325 return res;
326}
327
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600328#ifndef BUILD_TWRPTAR_MAIN
329
Dees_Troy38bd7602012-09-14 13:33:53 -0400330// Returns "/path" from a full /path/to/file.name
331string TWFunc::Get_Root_Path(string Path) {
332 string Local_Path = Path;
333
334 // Make sure that we have a leading slash
335 if (Local_Path.substr(0, 1) != "/")
336 Local_Path = "/" + Local_Path;
337
338 // Trim the path to get the root path only
339 size_t position = Local_Path.find("/", 2);
340 if (position != string::npos) {
341 Local_Path.resize(position);
342 }
343 return Local_Path;
344}
345
346void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400347 int need_libs = 0;
348
349 if (!PartitionManager.Mount_By_Path("/system", true))
350 return;
351
352 if (!PartitionManager.Mount_By_Path("/data", true))
353 return;
354
Dees_Troy2673cec2013-04-02 20:22:16 +0000355 gui_print("Installing HTC Dumlock to system...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500356 copy_file("/res/htcd/htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400357 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000358 gui_print("Installing flash_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500359 copy_file("/res/htcd/flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400360 need_libs = 1;
361 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000362 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400363 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000364 gui_print("Installing dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500365 copy_file("/res/htcd/dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400366 need_libs = 1;
367 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000368 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400369 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000370 gui_print("Installing libs needed for flash_image and dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500371 copy_file("/res/htcd/libbmlutils.so", "/system/lib/libbmlutils.so", 0755);
372 copy_file("/res/htcd/libflashutils.so", "/system/lib/libflashutils.so", 0755);
373 copy_file("/res/htcd/libmmcutils.so", "/system/lib/libmmcutils.so", 0755);
374 copy_file("/res/htcd/libmtdutils.so", "/system/lib/libmtdutils.so", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400375 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000376 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400377 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500378 unlink("/data/app/com.teamwin.htcdumlock*");
379 copy_file("/res/htcd/HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400380 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000381 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400382}
383
384void TWFunc::htc_dumlock_restore_original_boot(void) {
385 if (!PartitionManager.Mount_By_Path("/sdcard", true))
386 return;
387
Dees_Troy2673cec2013-04-02 20:22:16 +0000388 gui_print("Restoring original boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200389 Exec_Cmd("htcdumlock restore");
Dees_Troy2673cec2013-04-02 20:22:16 +0000390 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400391}
392
393void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
394 if (!PartitionManager.Mount_By_Path("/sdcard", true))
395 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000396 gui_print("Reflashing recovery to boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200397 Exec_Cmd("htcdumlock recovery noreboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000398 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400399}
Dees_Troy43d8b002012-09-17 16:00:01 -0400400
401int TWFunc::Recursive_Mkdir(string Path) {
402 string pathCpy = Path;
403 string wholePath;
404 size_t pos = pathCpy.find("/", 2);
405
406 while (pos != string::npos)
407 {
408 wholePath = pathCpy.substr(0, pos);
409 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000410 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
Dees_Troy43d8b002012-09-17 16:00:01 -0400411 return false;
412 }
413
414 pos = pathCpy.find("/", pos + 1);
415 }
416 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
417 return false;
418 return true;
419}
420
Dees_Troyb46a6842012-09-25 11:06:46 -0400421void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
422 string Display_Text;
423
424 DataManager::GetValue(Read_Value, Display_Text);
425 if (Display_Text.empty())
426 Display_Text = Default_Text;
427
428 DataManager::SetValue("tw_operation", Display_Text);
429 DataManager::SetValue("tw_partition", "");
430}
431
432void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
433 string Display_Text;
434
435 DataManager::GetValue(Read_Value, Display_Text);
436 if (Display_Text.empty())
437 Display_Text = Default_Text;
438
439 DataManager::SetValue("tw_operation", Display_Text);
440 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400441}
442
Dees_Troy2673cec2013-04-02 20:22:16 +0000443void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000444 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000445 FILE *destination_log = fopen(Destination.c_str(), "a");
446 if (destination_log == NULL) {
447 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600448 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000449 FILE *source_log = fopen(Source.c_str(), "r");
450 if (source_log != NULL) {
451 fseek(source_log, Log_Offset, SEEK_SET);
452 char buffer[4096];
453 while (fgets(buffer, sizeof(buffer), source_log))
454 fputs(buffer, destination_log); // Buffered write of log file
455 Log_Offset = ftell(source_log);
456 fflush(source_log);
457 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600458 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000459 fflush(destination_log);
460 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600461 }
Dees_Troya58bead2012-09-27 09:49:29 -0400462}
463
Dees_Troy2673cec2013-04-02 20:22:16 +0000464void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500465 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000466 if (PartitionManager.Mount_By_Path("/cache", false)) {
467 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
468 LOGINFO("Recreating /cache/recovery folder.\n");
469 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
470 LOGINFO("Unable to create /cache/recovery folder.\n");
471 }
472 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
473 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
474 chown("/cache/recovery/log", 1000, 1000);
475 chmod("/cache/recovery/log", 0600);
476 chmod("/cache/recovery/last_log", 0640);
477 } else {
478 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
479 }
Dees_Troya58bead2012-09-27 09:49:29 -0400480
Dees_Troy2673cec2013-04-02 20:22:16 +0000481 // Reset bootloader message
482 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
483 if (Part != NULL) {
484 struct bootloader_message boot;
485 memset(&boot, 0, sizeof(boot));
486 if (Part->Current_File_System == "mtd") {
487 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
488 LOGERR("Unable to set MTD bootloader message.\n");
489 } else if (Part->Current_File_System == "emmc") {
490 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
491 LOGERR("Unable to set emmc bootloader message.\n");
492 } else {
493 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
494 }
495 }
Dees_Troya58bead2012-09-27 09:49:29 -0400496
Dees Troy9d7fdf52013-09-19 20:49:25 +0000497 if (PartitionManager.Mount_By_Path("/cache", true)) {
498 if (unlink("/cache/recovery/command") && errno != ENOENT) {
499 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
500 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500501 }
Dees_Troya58bead2012-09-27 09:49:29 -0400502
Dees_Troy2673cec2013-04-02 20:22:16 +0000503 sync();
504}
505
506void TWFunc::Update_Intent_File(string Intent) {
507 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
508 TWFunc::write_file("/cache/recovery/intent", Intent);
509 }
Dees_Troya58bead2012-09-27 09:49:29 -0400510}
511
512// reboot: Reboot the system. Return -1 on error, no return on success
513int TWFunc::tw_reboot(RebootCommand command)
514{
515 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600516 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400517
Dees_Troy2673cec2013-04-02 20:22:16 +0000518 switch (command) {
519 case rb_current:
520 case rb_system:
521 Update_Log_File();
522 Update_Intent_File("s");
523 sync();
524 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
525 return reboot(RB_AUTOBOOT);
526 case rb_recovery:
527 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600528 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
529 sleep(5);
530 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000531 case rb_bootloader:
532 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600533 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
534 sleep(5);
535 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000536 case rb_poweroff:
537 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000538#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000539 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000540#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000541 return reboot(RB_POWER_OFF);
542 case rb_download:
543 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600544 property_set(ANDROID_RB_PROPERTY, "reboot,download");
545 sleep(5);
546 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000547 default:
548 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600549 }
550 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400551}
552
553void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
554{
555 // Check for and run startup script if script exists
556 struct stat st;
557 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000558 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500559 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200560 TWFunc::Exec_Cmd(script_file);
Dees_Troy2673cec2013-04-02 20:22:16 +0000561 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400562 }
Dees_Troy3477d712012-09-27 15:44:01 -0400563}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500564
565int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000566 DIR *d = opendir(path.c_str());
567 int r = 0;
568 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500569
Dees_Troyce675462013-01-09 19:48:21 +0000570 if (d == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000571 LOGERR("Error opening '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000572 return -1;
573 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500574
Dees_Troyce675462013-01-09 19:48:21 +0000575 if (d) {
576 struct dirent *p;
577 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000578 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
579 continue;
580 new_path = path + "/";
581 new_path.append(p->d_name);
582 if (p->d_type == DT_DIR) {
583 r = removeDir(new_path, true);
584 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500585 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500586 r = rmdir(new_path.c_str());
587 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000588 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500589 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500590 } 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 +0000591 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000592 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000593 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000594 }
Dees_Troyce675462013-01-09 19:48:21 +0000595 }
596 }
597 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500598
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500599 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500600 if (skipParent)
601 return 0;
602 else
603 r = rmdir(path.c_str());
604 }
Dees_Troyce675462013-01-09 19:48:21 +0000605 }
606 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500607}
608
609int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000610 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500611 ifstream srcfile(src.c_str(), ios::binary);
612 ofstream dstfile(dst.c_str(), ios::binary);
613 dstfile << srcfile.rdbuf();
614 srcfile.close();
615 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500616 if (chmod(dst.c_str(), mode) != 0)
617 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500618 return 0;
619}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000620
621unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
622 struct stat st;
623
624 stat(Path.c_str(), &st);
625 if (st.st_mode & S_IFDIR)
626 return DT_DIR;
627 else if (st.st_mode & S_IFBLK)
628 return DT_BLK;
629 else if (st.st_mode & S_IFCHR)
630 return DT_CHR;
631 else if (st.st_mode & S_IFIFO)
632 return DT_FIFO;
633 else if (st.st_mode & S_IFLNK)
634 return DT_LNK;
635 else if (st.st_mode & S_IFREG)
636 return DT_REG;
637 else if (st.st_mode & S_IFSOCK)
638 return DT_SOCK;
639 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000640}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500641
642int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200643 ifstream file;
644 file.open(fn.c_str(), ios::in);
645
646 if (file.is_open()) {
647 file >> results;
648 file.close();
649 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500650 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200651
652 LOGINFO("Cannot find file %s\n", fn.c_str());
653 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500654}
655
656int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500657 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500658 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500659 file.open(fn.c_str(), ios::in);
660 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500661 while (getline(file, line))
662 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500663 file.close();
664 return 0;
665 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000666 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500667 return -1;
668}
669
xNUTxe85f02d2014-07-18 01:30:58 +0200670int TWFunc::read_file(string fn, uint64_t& results) {
671 ifstream file;
672 file.open(fn.c_str(), ios::in);
673
674 if (file.is_open()) {
675 file >> results;
676 file.close();
677 return 0;
678 }
679
680 LOGINFO("Cannot find file %s\n", fn.c_str());
681 return -1;
682}
683
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500684int TWFunc::write_file(string fn, string& line) {
685 FILE *file;
686 file = fopen(fn.c_str(), "w");
687 if (file != NULL) {
688 fwrite(line.c_str(), line.size(), 1, file);
689 fclose(file);
690 return 0;
691 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000692 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500693 return -1;
694}
695
696timespec TWFunc::timespec_diff(timespec& start, timespec& end)
697{
Dees_Troy6ef66352013-02-21 08:26:57 -0600698 timespec temp;
699 if ((end.tv_nsec-start.tv_nsec)<0) {
700 temp.tv_sec = end.tv_sec-start.tv_sec-1;
701 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
702 } else {
703 temp.tv_sec = end.tv_sec-start.tv_sec;
704 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
705 }
706 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500707}
708
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100709int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
710{
711 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
712 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
713}
714
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200715int TWFunc::drop_caches(void) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600716 string file = "/proc/sys/vm/drop_caches";
717 string value = "3";
718 if (write_file(file, value) != 0)
719 return -1;
720 return 0;
721}
722
723int TWFunc::Check_su_Perms(void) {
724 struct stat st;
725 int ret = 0;
726
727 if (!PartitionManager.Mount_By_Path("/system", false))
728 return 0;
729
730 // Check to ensure that perms are 6755 for all 3 file locations
731 if (stat("/system/bin/su", &st) == 0) {
732 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) {
733 ret = 1;
734 }
735 }
736 if (stat("/system/xbin/su", &st) == 0) {
737 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) {
738 ret += 2;
739 }
740 }
741 if (stat("/system/bin/.ext/.su", &st) == 0) {
742 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) {
743 ret += 4;
744 }
745 }
746 return ret;
747}
748
749bool TWFunc::Fix_su_Perms(void) {
750 if (!PartitionManager.Mount_By_Path("/system", true))
751 return false;
752
Ethan Yonker0385f512014-02-06 14:33:02 -0600753 string propvalue = System_Property_Get("ro.build.version.sdk");
754 string su_perms = "6755";
755 if (!propvalue.empty()) {
756 int sdk_version = atoi(propvalue.c_str());
757 if (sdk_version >= 18)
758 su_perms = "0755";
759 }
760
Dees_Troy6ef66352013-02-21 08:26:57 -0600761 string file = "/system/bin/su";
762 if (TWFunc::Path_Exists(file)) {
763 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000764 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600765 return false;
766 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600767 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000768 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600769 return false;
770 }
771 }
772 file = "/system/xbin/su";
773 if (TWFunc::Path_Exists(file)) {
774 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000775 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600776 return false;
777 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600778 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000779 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600780 return false;
781 }
782 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000783 file = "/system/xbin/daemonsu";
784 if (TWFunc::Path_Exists(file)) {
785 if (chown(file.c_str(), 0, 0) != 0) {
786 LOGERR("Failed to chown '%s'\n", file.c_str());
787 return false;
788 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600789 if (tw_chmod(file, "0755") != 0) {
Dees_Troya7939bb2013-08-29 20:21:12 +0000790 LOGERR("Failed to chmod '%s'\n", file.c_str());
791 return false;
792 }
793 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600794 file = "/system/bin/.ext/.su";
795 if (TWFunc::Path_Exists(file)) {
796 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000797 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600798 return false;
799 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600800 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000801 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600802 return false;
803 }
804 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000805 file = "/system/etc/install-recovery.sh";
806 if (TWFunc::Path_Exists(file)) {
807 if (chown(file.c_str(), 0, 0) != 0) {
808 LOGERR("Failed to chown '%s'\n", file.c_str());
809 return false;
810 }
811 if (tw_chmod(file, "0755") != 0) {
812 LOGERR("Failed to chmod '%s'\n", file.c_str());
813 return false;
814 }
815 }
816 file = "/system/etc/init.d/99SuperSUDaemon";
817 if (TWFunc::Path_Exists(file)) {
818 if (chown(file.c_str(), 0, 0) != 0) {
819 LOGERR("Failed to chown '%s'\n", file.c_str());
820 return false;
821 }
822 if (tw_chmod(file, "0755") != 0) {
823 LOGERR("Failed to chmod '%s'\n", file.c_str());
824 return false;
825 }
826 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600827 file = "/system/app/Superuser.apk";
828 if (TWFunc::Path_Exists(file)) {
829 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000830 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600831 return false;
832 }
833 if (tw_chmod(file, "0644") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000834 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600835 return false;
836 }
837 }
838 sync();
839 if (!PartitionManager.UnMount_By_Path("/system", true))
840 return false;
841 return true;
842}
843
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200844int TWFunc::tw_chmod(const string& fn, const string& mode) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600845 long mask = 0;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200846 std::string::size_type n = mode.length();
847 int cls = 0;
Dees_Troy6ef66352013-02-21 08:26:57 -0600848
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200849 if(n == 3)
850 ++cls;
851 else if(n != 4)
852 {
853 LOGERR("TWFunc::tw_chmod used with %u long mode string (should be 3 or 4)!\n", mode.length());
854 return -1;
855 }
856
857 for (n = 0; n < mode.length(); ++n, ++cls) {
858 if (cls == 0) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600859 if (mode[n] == '0')
860 continue;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200861 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600862 mask |= S_ISVTX;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200863 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600864 mask |= S_ISGID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200865 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600866 mask |= S_ISUID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200867 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600868 mask |= S_ISVTX;
869 mask |= S_ISUID;
870 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200871 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600872 mask |= S_ISGID;
873 mask |= S_ISUID;
874 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200875 else if (mode[n] == '7') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600876 mask |= S_ISVTX;
877 mask |= S_ISGID;
878 mask |= S_ISUID;
879 }
880 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200881 else if (cls == 1) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600882 if (mode[n] == '7') {
883 mask |= S_IRWXU;
884 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200885 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600886 mask |= S_IRUSR;
887 mask |= S_IWUSR;
888 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200889 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600890 mask |= S_IRUSR;
891 mask |= S_IXUSR;
892 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200893 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600894 mask |= S_IRUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200895 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600896 mask |= S_IWUSR;
897 mask |= S_IRUSR;
898 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200899 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600900 mask |= S_IWUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200901 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600902 mask |= S_IXUSR;
903 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200904 else if (cls == 2) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600905 if (mode[n] == '7') {
906 mask |= S_IRWXG;
907 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200908 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600909 mask |= S_IRGRP;
910 mask |= S_IWGRP;
911 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200912 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600913 mask |= S_IRGRP;
914 mask |= S_IXGRP;
915 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200916 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600917 mask |= S_IRGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200918 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600919 mask |= S_IWGRP;
920 mask |= S_IXGRP;
921 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200922 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600923 mask |= S_IWGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200924 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600925 mask |= S_IXGRP;
926 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200927 else if (cls == 3) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600928 if (mode[n] == '7') {
929 mask |= S_IRWXO;
930 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200931 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600932 mask |= S_IROTH;
933 mask |= S_IWOTH;
934 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200935 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600936 mask |= S_IROTH;
937 mask |= S_IXOTH;
938 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200939 else if (mode[n] == '4')
940 mask |= S_IROTH;
941 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600942 mask |= S_IWOTH;
943 mask |= S_IXOTH;
944 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200945 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600946 mask |= S_IWOTH;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200947 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600948 mask |= S_IXOTH;
949 }
950 }
951
952 if (chmod(fn.c_str(), mask) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000953 LOGERR("Unable to chmod '%s' %l\n", fn.c_str(), mask);
Dees_Troy6ef66352013-02-21 08:26:57 -0600954 return -1;
955 }
956
957 return 0;
958}
959
960bool TWFunc::Install_SuperSU(void) {
961 if (!PartitionManager.Mount_By_Path("/system", true))
962 return false;
963
Vojtech Bocek05534202013-09-11 08:11:56 +0200964 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/su");
jt1134113ee732013-02-22 23:26:10 -0600965 if (copy_file("/supersu/su", "/system/xbin/su", 0755) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000966 LOGERR("Failed to copy su binary to /system/bin\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600967 return false;
968 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000969 if (!Path_Exists("/system/bin/.ext")) {
970 mkdir("/system/bin/.ext", 0777);
971 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200972 TWFunc::Exec_Cmd("/sbin/chattr -i /system/bin/.ext/su");
Dees_Troya7939bb2013-08-29 20:21:12 +0000973 if (copy_file("/supersu/su", "/system/bin/.ext/su", 0755) != 0) {
974 LOGERR("Failed to copy su binary to /system/bin/.ext/su\n");
975 return false;
976 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200977 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/daemonsu");
Dees_Troya7939bb2013-08-29 20:21:12 +0000978 if (copy_file("/supersu/su", "/system/xbin/daemonsu", 0755) != 0) {
979 LOGERR("Failed to copy su binary to /system/xbin/daemonsu\n");
980 return false;
981 }
982 if (Path_Exists("/system/etc/init.d")) {
Vojtech Bocek05534202013-09-11 08:11:56 +0200983 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/init.d/99SuperSUDaemon");
Dees_Troya7939bb2013-08-29 20:21:12 +0000984 if (copy_file("/supersu/99SuperSUDaemon", "/system/etc/init.d/99SuperSUDaemon", 0755) != 0) {
985 LOGERR("Failed to copy 99SuperSUDaemon to /system/etc/init.d/99SuperSUDaemon\n");
986 return false;
987 }
988 } else {
Vojtech Bocek05534202013-09-11 08:11:56 +0200989 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/install-recovery.sh");
Dees_Troya7939bb2013-08-29 20:21:12 +0000990 if (copy_file("/supersu/install-recovery.sh", "/system/etc/install-recovery.sh", 0755) != 0) {
991 LOGERR("Failed to copy install-recovery.sh to /system/etc/install-recovery.sh\n");
992 return false;
993 }
994 }
jt1134113ee732013-02-22 23:26:10 -0600995 if (copy_file("/supersu/Superuser.apk", "/system/app/Superuser.apk", 0644) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000996 LOGERR("Failed to copy Superuser app to /system/app\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600997 return false;
998 }
999 if (!Fix_su_Perms())
1000 return false;
1001 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -05001002}
Dees_Troy83bd4832013-05-04 12:39:56 +00001003
Dees_Troy83bd4832013-05-04 12:39:56 +00001004bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
1005 DIR* d;
1006
1007 string Filename;
1008 Restore_Path += "/";
1009 d = opendir(Restore_Path.c_str());
1010 if (d == NULL) {
1011 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
1012 return false;
1013 }
1014
1015 struct dirent* de;
1016 while ((de = readdir(d)) != NULL) {
1017 Filename = Restore_Path;
1018 Filename += de->d_name;
1019 if (TWFunc::Get_File_Type(Filename) == 2) {
1020 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
1021 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
1022 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
1023 closedir(d);
1024 return false;
1025 }
1026 }
1027 }
1028 closedir(d);
1029 return true;
1030}
1031
Dees Troyb21cc642013-09-10 17:36:41 +00001032string TWFunc::Get_Current_Date() {
1033 string Current_Date;
1034 time_t seconds = time(0);
1035 struct tm *t = localtime(&seconds);
1036 char timestamp[255];
1037 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);
1038 Current_Date = timestamp;
1039 return Current_Date;
1040}
1041
Ethan Yonkerb5557892014-02-07 21:43:20 -06001042string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001043 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
1044 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001045 string propvalue;
1046 if (!PartitionManager.Mount_By_Path("/system", true))
1047 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001048 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -06001049 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +02001050 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +00001051 if (!mount_state)
1052 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001053 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001054 }
1055 int line_count = buildprop.size();
1056 int index;
1057 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001058 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +00001059 for (index = 0; index < line_count; index++) {
1060 end_pos = buildprop.at(index).find("=", start_pos);
1061 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001062 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001063 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -06001064 if (!mount_state)
1065 PartitionManager.UnMount_By_Path("/system", false);
1066 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001067 }
1068 }
Dees Troyb21cc642013-09-10 17:36:41 +00001069 if (!mount_state)
1070 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001071 return propvalue;
1072}
1073
1074void TWFunc::Auto_Generate_Backup_Name() {
1075 string propvalue = System_Property_Get("ro.build.display.id");
1076 if (propvalue.empty()) {
1077 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1078 return;
1079 }
1080 string Backup_Name = Get_Current_Date();
1081 Backup_Name += " " + propvalue;
1082 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
1083 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
1084 // Trailing spaces cause problems on some file systems, so remove them
1085 string space_check, space = " ";
1086 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1087 while (space_check == space) {
1088 Backup_Name.resize(Backup_Name.size() - 1);
1089 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1090 }
1091 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -06001092 if (PartitionManager.Check_Backup_Name(false) != 0) {
1093 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
1094 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1095 }
Vojtech Bocek05534202013-09-11 08:11:56 +02001096}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001097
1098void TWFunc::Fixup_Time_On_Boot()
1099{
1100#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +02001101
1102 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
1103
1104 struct timeval tv;
1105 uint64_t offset = 0;
1106 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
1107
1108 if (TWFunc::read_file(sepoch, offset) == 0) {
1109
1110 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
1111
1112 tv.tv_sec = offset;
1113 tv.tv_usec = 0;
1114 settimeofday(&tv, NULL);
1115
1116 gettimeofday(&tv, NULL);
1117
1118 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
1119
1120 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1121 return;
1122
1123 }
1124
1125 } else {
1126
1127 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
1128
1129 }
1130
1131 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n", sepoch.c_str());
1132
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001133 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
1134 // They never set it, it just ticks forward from 1970-01-01 00:00,
1135 // and then they have files /data/system/time/ats_* with 64bit offset
1136 // in miliseconds which, when added to the RTC, gives the correct time.
1137 // So, the time is: (offset_from_ats + value_from_RTC)
1138 // There are multiple ats files, they are for different systems? Bases?
1139 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1140 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1141
1142 static const char *paths[] = { "/data/system/time/", "/data/time/" };
1143
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001144 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001145 DIR *d;
1146 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001147 struct dirent *dt;
1148 std::string ats_path;
1149
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001150 if(!PartitionManager.Mount_By_Path("/data", false))
1151 return;
1152
1153 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1154 // - it is the one for ATS_TOD (time of day?).
1155 // However, I never saw a device where the offset differs between ats files.
1156 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
1157 {
1158 DIR *d = opendir(paths[i]);
1159 if(!d)
1160 continue;
1161
1162 while((dt = readdir(d)))
1163 {
1164 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
1165 continue;
1166
1167 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
1168 ats_path = std::string(paths[i]).append(dt->d_name);
1169 }
1170
1171 closedir(d);
1172 }
1173
1174 if(ats_path.empty())
1175 {
xNUTxe85f02d2014-07-18 01:30:58 +02001176 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001177 return;
1178 }
1179
1180 f = fopen(ats_path.c_str(), "r");
1181 if(!f)
1182 {
Dees Troy3e254b92014-03-06 20:24:54 +00001183 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001184 return;
1185 }
1186
1187 if(fread(&offset, sizeof(offset), 1, f) != 1)
1188 {
Dees Troy3e254b92014-03-06 20:24:54 +00001189 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001190 fclose(f);
1191 return;
1192 }
1193 fclose(f);
1194
1195 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
1196
1197 gettimeofday(&tv, NULL);
1198
1199 tv.tv_sec += offset/1000;
1200 tv.tv_usec += (offset%1000)*1000;
1201
1202 while(tv.tv_usec >= 1000000)
1203 {
1204 ++tv.tv_sec;
1205 tv.tv_usec -= 1000000;
1206 }
1207
1208 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001209
1210 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1211
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001212#endif
1213}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001214
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001215std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1216{
1217 std::vector<std::string> res;
1218 size_t idx = 0, idx_last = 0;
1219
1220 while(idx < str.size())
1221 {
1222 idx = str.find_first_of(delimiter, idx_last);
1223 if(idx == std::string::npos)
1224 idx = str.size();
1225
1226 if(idx-idx_last != 0 || !removeEmpty)
1227 res.push_back(str.substr(idx_last, idx-idx_last));
1228
1229 idx_last = idx + delimiter.size();
1230 }
1231
1232 return res;
1233}
1234
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001235bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1236{
1237 std::vector<std::string> parts = Split_String(path, "/");
1238 std::string cur_path;
1239 struct stat info;
1240 for(size_t i = 0; i < parts.size(); ++i)
1241 {
1242 cur_path += "/" + parts[i];
1243 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
1244 {
1245 if(mkdir(cur_path.c_str(), mode) < 0)
1246 return false;
1247 chown(cur_path.c_str(), uid, gid);
1248 }
1249 }
1250 return true;
1251}
1252
xNUTxe85f02d2014-07-18 01:30:58 +02001253int TWFunc::Set_Brightness(std::string brightness_value)
1254{
1255
1256 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
1257
1258 if (brightness_file.compare("/nobrightness") != 0) {
1259 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
1260 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
1261 int result = TWFunc::write_file(brightness_file, brightness_value);
1262 if (secondary_brightness_file != "") {
1263 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
1264 TWFunc::write_file(secondary_brightness_file, brightness_value);
1265 }
1266 return result;
1267 }
1268 return -1;
1269}
1270
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001271bool TWFunc::Toggle_MTP(bool enable) {
1272#ifdef TW_HAS_MTP
1273 static int was_enabled = false;
1274
1275 if (enable && was_enabled) {
1276 if (!PartitionManager.Enable_MTP())
1277 PartitionManager.Disable_MTP();
1278 } else {
1279 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1280 PartitionManager.Disable_MTP();
1281 usleep(500);
1282 }
1283 return was_enabled;
1284#else
1285 return false;
1286#endif
1287}
1288
Tom Hite5a926722014-09-15 01:31:03 +00001289void TWFunc::SetPerformanceMode(bool mode) {
1290 if (mode) {
1291 property_set("recovery.perf.mode", "1");
1292 } else {
1293 property_set("recovery.perf.mode", "0");
1294 }
1295 // Some time for events to catch up to init handlers
1296 usleep(500000);
1297}
1298
Jenkins1710bf22014-10-02 20:22:21 -04001299std::string TWFunc::to_string(unsigned long value) {
1300 std::ostringstream os;
1301 os << value;
1302 return os.str();
1303}
1304
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001305#endif // ndef BUILD_TWRPTAR_MAIN