blob: 1798c49b7b4c3a531048e90c0e225ff6acefd107 [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"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060045#ifdef ANDROID_RB_POWEROFF
46 #include "cutils/android_reboot.h"
47#endif
48#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000049#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
50 #include "openaes/inc/oaes_lib.h"
51#endif
Dees_Troy38bd7602012-09-14 13:33:53 -040052
Dees_Troyb05ddee2013-01-28 20:24:50 +000053extern "C" {
54 #include "libcrecovery/common.h"
55}
56
bigbiff bigbiff9c754052013-01-09 09:09:08 -050057/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020058int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000059 FILE* exec;
60 char buffer[130];
61 int ret = 0;
62 exec = __popen(cmd.c_str(), "r");
63 if (!exec) return -1;
64 while(!feof(exec)) {
65 memset(&buffer, 0, sizeof(buffer));
66 if (fgets(buffer, 128, exec) != NULL) {
67 buffer[128] = '\n';
68 buffer[129] = NULL;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050069 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000070 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050071 }
Dees_Troy29a06352013-08-24 12:06:47 +000072 ret = __pclose(exec);
73 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050074}
75
Vojtech Bocek05534202013-09-11 08:11:56 +020076int TWFunc::Exec_Cmd(const string& cmd) {
77 pid_t pid;
78 int status;
79 switch(pid = fork())
80 {
81 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050082 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020083 return -1;
84 case 0: // child
85 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
86 _exit(127);
87 break;
88 default:
89 {
90 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
91 return -1;
92 else
93 return 0;
94 }
95 }
96}
97
Dees_Troy38bd7602012-09-14 13:33:53 -040098// Returns "file.name" from a full /path/to/file.name
99string TWFunc::Get_Filename(string Path) {
100 size_t pos = Path.find_last_of("/");
101 if (pos != string::npos) {
102 string Filename;
103 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
104 return Filename;
105 } else
106 return Path;
107}
108
109// Returns "/path/to/" from a full /path/to/file.name
110string TWFunc::Get_Path(string Path) {
111 size_t pos = Path.find_last_of("/");
112 if (pos != string::npos) {
113 string Pathonly;
114 Pathonly = Path.substr(0, pos + 1);
115 return Pathonly;
116 } else
117 return Path;
118}
119
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600120int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
121 pid_t rc_pid;
122
123 rc_pid = waitpid(pid, status, 0);
124 if (rc_pid > 0) {
125 if (WEXITSTATUS(*status) == 0)
126 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
127 else if (WIFSIGNALED(*status)) {
128 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
129 return -1;
130 } else if (WEXITSTATUS(*status) != 0) {
131 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
132 return -1;
133 }
134 } else { // no PID returned
135 if (errno == ECHILD)
136 LOGINFO("%s no child process exist\n", Child_Name.c_str());
137 else {
138 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
139 return -1;
140 }
141 }
142 return 0;
143}
144
145bool TWFunc::Path_Exists(string Path) {
146 // Check to see if the Path exists
147 struct stat st;
148 if (stat(Path.c_str(), &st) != 0)
149 return false;
150 else
151 return true;
152}
153
154int TWFunc::Get_File_Type(string fn) {
155 string::size_type i = 0;
156 int firstbyte = 0, secondbyte = 0;
157 char header[3];
158
159 ifstream f;
160 f.open(fn.c_str(), ios::in | ios::binary);
161 f.get(header, 3);
162 f.close();
163 firstbyte = header[i] & 0xff;
164 secondbyte = header[++i] & 0xff;
165
166 if (firstbyte == 0x1f && secondbyte == 0x8b)
167 return 1; // Compressed
168 else if (firstbyte == 0x4f && secondbyte == 0x41)
169 return 2; // Encrypted
170 else
171 return 0; // Unknown
172
173 return 0;
174}
175
176int TWFunc::Try_Decrypting_File(string fn, string password) {
177#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
178 OAES_CTX * ctx = NULL;
179 uint8_t _key_data[32] = "";
180 FILE *f;
181 uint8_t buffer[4096];
182 uint8_t *buffer_out = NULL;
183 uint8_t *ptr = NULL;
184 size_t read_len = 0, out_len = 0;
185 int firstbyte = 0, secondbyte = 0, key_len;
186 size_t _j = 0;
187 size_t _key_data_len = 0;
188
189 // mostly kanged from OpenAES oaes.c
190 for( _j = 0; _j < 32; _j++ )
191 _key_data[_j] = _j + 1;
192 _key_data_len = password.size();
193 if( 16 >= _key_data_len )
194 _key_data_len = 16;
195 else if( 24 >= _key_data_len )
196 _key_data_len = 24;
197 else
198 _key_data_len = 32;
199 memcpy(_key_data, password.c_str(), password.size());
200
201 ctx = oaes_alloc();
202 if (ctx == NULL) {
203 LOGERR("Failed to allocate OAES\n");
204 return -1;
205 }
206
207 oaes_key_import_data(ctx, _key_data, _key_data_len);
208
209 f = fopen(fn.c_str(), "rb");
210 if (f == NULL) {
211 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
212 return -1;
213 }
214 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
215 if (read_len <= 0) {
216 LOGERR("Read size during try decrypt failed\n");
217 fclose(f);
218 return -1;
219 }
220 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
221 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
222 fclose(f);
223 return -1;
224 }
225 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
226 if (buffer_out == NULL) {
227 LOGERR("Failed to allocate output buffer for try decrypt.\n");
228 fclose(f);
229 return -1;
230 }
231 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
232 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
233 fclose(f);
234 free(buffer_out);
235 return 0;
236 }
237 fclose(f);
238 if (out_len < 2) {
239 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
240 free(buffer_out);
241 return 1; // Decrypted successfully
242 }
243 ptr = buffer_out;
244 firstbyte = *ptr & 0xff;
245 ptr++;
246 secondbyte = *ptr & 0xff;
247 if (firstbyte == 0x1f && secondbyte == 0x8b) {
248 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
249 free(buffer_out);
250 return 3; // Compressed
251 }
252 if (out_len >= 262) {
253 ptr = buffer_out + 257;
254 if (strncmp((char*)ptr, "ustar", 5) == 0) {
255 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
256 free(buffer_out);
257 return 2; // Tar
258 }
259 }
260 free(buffer_out);
261 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
262 return 1; // Decrypted successfully
263#else
264 LOGERR("Encrypted backup support not included.\n");
265 return -1;
266#endif
267}
268
269unsigned long TWFunc::Get_File_Size(string Path) {
270 struct stat st;
271
272 if (stat(Path.c_str(), &st) != 0)
273 return 0;
274 return st.st_size;
275}
276
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100277std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
278{
279 std::string res;
280 size_t last_idx = 0, idx = 0;
281
282 while(last_idx != std::string::npos)
283 {
284 if(last_idx != 0)
285 res += '/';
286
287 idx = path.find_first_of('/', last_idx);
288 if(idx == std::string::npos) {
289 res += path.substr(last_idx, idx);
290 break;
291 }
292
293 res += path.substr(last_idx, idx-last_idx);
294 last_idx = path.find_first_not_of('/', idx);
295 }
296
297 if(leaveLast)
298 res += '/';
299 return res;
300}
301
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500302vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
303 vector<string> res;
304
305 if (in.empty() || del == '\0')
306 return res;
307
308 string field;
309 istringstream f(in);
310 if (del == '\n') {
311 while(getline(f, field)) {
312 if (field.empty() && skip_empty)
313 continue;
314 res.push_back(field);
315 }
316 } else {
317 while(getline(f, field, del)) {
318 if (field.empty() && skip_empty)
319 continue;
320 res.push_back(field);
321 }
322 }
323 return res;
324}
325
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600326#ifndef BUILD_TWRPTAR_MAIN
327
Dees_Troy38bd7602012-09-14 13:33:53 -0400328// Returns "/path" from a full /path/to/file.name
329string TWFunc::Get_Root_Path(string Path) {
330 string Local_Path = Path;
331
332 // Make sure that we have a leading slash
333 if (Local_Path.substr(0, 1) != "/")
334 Local_Path = "/" + Local_Path;
335
336 // Trim the path to get the root path only
337 size_t position = Local_Path.find("/", 2);
338 if (position != string::npos) {
339 Local_Path.resize(position);
340 }
341 return Local_Path;
342}
343
344void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400345 int need_libs = 0;
346
347 if (!PartitionManager.Mount_By_Path("/system", true))
348 return;
349
350 if (!PartitionManager.Mount_By_Path("/data", true))
351 return;
352
Dees_Troy2673cec2013-04-02 20:22:16 +0000353 gui_print("Installing HTC Dumlock to system...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500354 copy_file("/res/htcd/htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400355 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000356 gui_print("Installing flash_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500357 copy_file("/res/htcd/flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400358 need_libs = 1;
359 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000360 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400361 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000362 gui_print("Installing dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500363 copy_file("/res/htcd/dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400364 need_libs = 1;
365 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000366 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400367 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000368 gui_print("Installing libs needed for flash_image and dump_image...\n");
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500369 copy_file("/res/htcd/libbmlutils.so", "/system/lib/libbmlutils.so", 0755);
370 copy_file("/res/htcd/libflashutils.so", "/system/lib/libflashutils.so", 0755);
371 copy_file("/res/htcd/libmmcutils.so", "/system/lib/libmmcutils.so", 0755);
372 copy_file("/res/htcd/libmtdutils.so", "/system/lib/libmtdutils.so", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400373 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000374 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400375 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500376 unlink("/data/app/com.teamwin.htcdumlock*");
377 copy_file("/res/htcd/HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400378 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000379 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400380}
381
382void TWFunc::htc_dumlock_restore_original_boot(void) {
383 if (!PartitionManager.Mount_By_Path("/sdcard", true))
384 return;
385
Dees_Troy2673cec2013-04-02 20:22:16 +0000386 gui_print("Restoring original boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200387 Exec_Cmd("htcdumlock restore");
Dees_Troy2673cec2013-04-02 20:22:16 +0000388 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400389}
390
391void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
392 if (!PartitionManager.Mount_By_Path("/sdcard", true))
393 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000394 gui_print("Reflashing recovery to boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200395 Exec_Cmd("htcdumlock recovery noreboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000396 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400397}
Dees_Troy43d8b002012-09-17 16:00:01 -0400398
399int TWFunc::Recursive_Mkdir(string Path) {
400 string pathCpy = Path;
401 string wholePath;
402 size_t pos = pathCpy.find("/", 2);
403
404 while (pos != string::npos)
405 {
406 wholePath = pathCpy.substr(0, pos);
407 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000408 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
Dees_Troy43d8b002012-09-17 16:00:01 -0400409 return false;
410 }
411
412 pos = pathCpy.find("/", pos + 1);
413 }
414 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
415 return false;
416 return true;
417}
418
Dees_Troyb46a6842012-09-25 11:06:46 -0400419void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
420 string Display_Text;
421
422 DataManager::GetValue(Read_Value, Display_Text);
423 if (Display_Text.empty())
424 Display_Text = Default_Text;
425
426 DataManager::SetValue("tw_operation", Display_Text);
427 DataManager::SetValue("tw_partition", "");
428}
429
430void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
431 string Display_Text;
432
433 DataManager::GetValue(Read_Value, Display_Text);
434 if (Display_Text.empty())
435 Display_Text = Default_Text;
436
437 DataManager::SetValue("tw_operation", Display_Text);
438 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400439}
440
Dees_Troy2673cec2013-04-02 20:22:16 +0000441void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000442 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000443 FILE *destination_log = fopen(Destination.c_str(), "a");
444 if (destination_log == NULL) {
445 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600446 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000447 FILE *source_log = fopen(Source.c_str(), "r");
448 if (source_log != NULL) {
449 fseek(source_log, Log_Offset, SEEK_SET);
450 char buffer[4096];
451 while (fgets(buffer, sizeof(buffer), source_log))
452 fputs(buffer, destination_log); // Buffered write of log file
453 Log_Offset = ftell(source_log);
454 fflush(source_log);
455 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600456 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000457 fflush(destination_log);
458 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600459 }
Dees_Troya58bead2012-09-27 09:49:29 -0400460}
461
Dees_Troy2673cec2013-04-02 20:22:16 +0000462void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500463 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000464 if (PartitionManager.Mount_By_Path("/cache", false)) {
465 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
466 LOGINFO("Recreating /cache/recovery folder.\n");
467 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
468 LOGINFO("Unable to create /cache/recovery folder.\n");
469 }
470 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
471 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
472 chown("/cache/recovery/log", 1000, 1000);
473 chmod("/cache/recovery/log", 0600);
474 chmod("/cache/recovery/last_log", 0640);
475 } else {
476 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
477 }
Dees_Troya58bead2012-09-27 09:49:29 -0400478
Dees_Troy2673cec2013-04-02 20:22:16 +0000479 // Reset bootloader message
480 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
481 if (Part != NULL) {
482 struct bootloader_message boot;
483 memset(&boot, 0, sizeof(boot));
484 if (Part->Current_File_System == "mtd") {
485 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
486 LOGERR("Unable to set MTD bootloader message.\n");
487 } else if (Part->Current_File_System == "emmc") {
488 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
489 LOGERR("Unable to set emmc bootloader message.\n");
490 } else {
491 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
492 }
493 }
Dees_Troya58bead2012-09-27 09:49:29 -0400494
Dees Troy9d7fdf52013-09-19 20:49:25 +0000495 if (PartitionManager.Mount_By_Path("/cache", true)) {
496 if (unlink("/cache/recovery/command") && errno != ENOENT) {
497 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
498 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500499 }
Dees_Troya58bead2012-09-27 09:49:29 -0400500
Dees_Troy2673cec2013-04-02 20:22:16 +0000501 sync();
502}
503
504void TWFunc::Update_Intent_File(string Intent) {
505 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
506 TWFunc::write_file("/cache/recovery/intent", Intent);
507 }
Dees_Troya58bead2012-09-27 09:49:29 -0400508}
509
510// reboot: Reboot the system. Return -1 on error, no return on success
511int TWFunc::tw_reboot(RebootCommand command)
512{
513 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600514 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400515
Dees_Troy2673cec2013-04-02 20:22:16 +0000516 switch (command) {
517 case rb_current:
518 case rb_system:
519 Update_Log_File();
520 Update_Intent_File("s");
521 sync();
522 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
523 return reboot(RB_AUTOBOOT);
524 case rb_recovery:
525 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
526 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
527 case rb_bootloader:
528 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
529 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
530 case rb_poweroff:
531 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000532#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000533 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000534#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000535 return reboot(RB_POWER_OFF);
536 case rb_download:
537 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
538 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
539 default:
540 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600541 }
542 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400543}
544
545void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
546{
547 // Check for and run startup script if script exists
548 struct stat st;
549 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000550 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500551 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200552 TWFunc::Exec_Cmd(script_file);
Dees_Troy2673cec2013-04-02 20:22:16 +0000553 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400554 }
Dees_Troy3477d712012-09-27 15:44:01 -0400555}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500556
557int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000558 DIR *d = opendir(path.c_str());
559 int r = 0;
560 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500561
Dees_Troyce675462013-01-09 19:48:21 +0000562 if (d == NULL) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000563 LOGERR("Error opening '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000564 return -1;
565 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500566
Dees_Troyce675462013-01-09 19:48:21 +0000567 if (d) {
568 struct dirent *p;
569 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000570 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
571 continue;
572 new_path = path + "/";
573 new_path.append(p->d_name);
574 if (p->d_type == DT_DIR) {
575 r = removeDir(new_path, true);
576 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500577 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500578 r = rmdir(new_path.c_str());
579 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000580 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500581 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500582 } 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 +0000583 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000584 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000585 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000586 }
Dees_Troyce675462013-01-09 19:48:21 +0000587 }
588 }
589 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500590
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500591 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500592 if (skipParent)
593 return 0;
594 else
595 r = rmdir(path.c_str());
596 }
Dees_Troyce675462013-01-09 19:48:21 +0000597 }
598 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500599}
600
601int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000602 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500603 ifstream srcfile(src.c_str(), ios::binary);
604 ofstream dstfile(dst.c_str(), ios::binary);
605 dstfile << srcfile.rdbuf();
606 srcfile.close();
607 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500608 if (chmod(dst.c_str(), mode) != 0)
609 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500610 return 0;
611}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000612
613unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
614 struct stat st;
615
616 stat(Path.c_str(), &st);
617 if (st.st_mode & S_IFDIR)
618 return DT_DIR;
619 else if (st.st_mode & S_IFBLK)
620 return DT_BLK;
621 else if (st.st_mode & S_IFCHR)
622 return DT_CHR;
623 else if (st.st_mode & S_IFIFO)
624 return DT_FIFO;
625 else if (st.st_mode & S_IFLNK)
626 return DT_LNK;
627 else if (st.st_mode & S_IFREG)
628 return DT_REG;
629 else if (st.st_mode & S_IFSOCK)
630 return DT_SOCK;
631 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000632}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500633
634int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200635 ifstream file;
636 file.open(fn.c_str(), ios::in);
637
638 if (file.is_open()) {
639 file >> results;
640 file.close();
641 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500642 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200643
644 LOGINFO("Cannot find file %s\n", fn.c_str());
645 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500646}
647
648int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500649 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500650 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500651 file.open(fn.c_str(), ios::in);
652 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500653 while (getline(file, line))
654 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500655 file.close();
656 return 0;
657 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000658 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500659 return -1;
660}
661
xNUTxe85f02d2014-07-18 01:30:58 +0200662int TWFunc::read_file(string fn, uint64_t& results) {
663 ifstream file;
664 file.open(fn.c_str(), ios::in);
665
666 if (file.is_open()) {
667 file >> results;
668 file.close();
669 return 0;
670 }
671
672 LOGINFO("Cannot find file %s\n", fn.c_str());
673 return -1;
674}
675
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500676int TWFunc::write_file(string fn, string& line) {
677 FILE *file;
678 file = fopen(fn.c_str(), "w");
679 if (file != NULL) {
680 fwrite(line.c_str(), line.size(), 1, file);
681 fclose(file);
682 return 0;
683 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000684 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500685 return -1;
686}
687
688timespec TWFunc::timespec_diff(timespec& start, timespec& end)
689{
Dees_Troy6ef66352013-02-21 08:26:57 -0600690 timespec temp;
691 if ((end.tv_nsec-start.tv_nsec)<0) {
692 temp.tv_sec = end.tv_sec-start.tv_sec-1;
693 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
694 } else {
695 temp.tv_sec = end.tv_sec-start.tv_sec;
696 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
697 }
698 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500699}
700
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100701int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
702{
703 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
704 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
705}
706
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200707int TWFunc::drop_caches(void) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600708 string file = "/proc/sys/vm/drop_caches";
709 string value = "3";
710 if (write_file(file, value) != 0)
711 return -1;
712 return 0;
713}
714
715int TWFunc::Check_su_Perms(void) {
716 struct stat st;
717 int ret = 0;
718
719 if (!PartitionManager.Mount_By_Path("/system", false))
720 return 0;
721
722 // Check to ensure that perms are 6755 for all 3 file locations
723 if (stat("/system/bin/su", &st) == 0) {
724 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) {
725 ret = 1;
726 }
727 }
728 if (stat("/system/xbin/su", &st) == 0) {
729 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) {
730 ret += 2;
731 }
732 }
733 if (stat("/system/bin/.ext/.su", &st) == 0) {
734 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) {
735 ret += 4;
736 }
737 }
738 return ret;
739}
740
741bool TWFunc::Fix_su_Perms(void) {
742 if (!PartitionManager.Mount_By_Path("/system", true))
743 return false;
744
Ethan Yonker0385f512014-02-06 14:33:02 -0600745 string propvalue = System_Property_Get("ro.build.version.sdk");
746 string su_perms = "6755";
747 if (!propvalue.empty()) {
748 int sdk_version = atoi(propvalue.c_str());
749 if (sdk_version >= 18)
750 su_perms = "0755";
751 }
752
Dees_Troy6ef66352013-02-21 08:26:57 -0600753 string file = "/system/bin/su";
754 if (TWFunc::Path_Exists(file)) {
755 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000756 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600757 return false;
758 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600759 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000760 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600761 return false;
762 }
763 }
764 file = "/system/xbin/su";
765 if (TWFunc::Path_Exists(file)) {
766 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000767 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600768 return false;
769 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600770 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000771 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600772 return false;
773 }
774 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000775 file = "/system/xbin/daemonsu";
776 if (TWFunc::Path_Exists(file)) {
777 if (chown(file.c_str(), 0, 0) != 0) {
778 LOGERR("Failed to chown '%s'\n", file.c_str());
779 return false;
780 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600781 if (tw_chmod(file, "0755") != 0) {
Dees_Troya7939bb2013-08-29 20:21:12 +0000782 LOGERR("Failed to chmod '%s'\n", file.c_str());
783 return false;
784 }
785 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600786 file = "/system/bin/.ext/.su";
787 if (TWFunc::Path_Exists(file)) {
788 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000789 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600790 return false;
791 }
Ethan Yonker0385f512014-02-06 14:33:02 -0600792 if (tw_chmod(file, su_perms) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000793 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600794 return false;
795 }
796 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000797 file = "/system/etc/install-recovery.sh";
798 if (TWFunc::Path_Exists(file)) {
799 if (chown(file.c_str(), 0, 0) != 0) {
800 LOGERR("Failed to chown '%s'\n", file.c_str());
801 return false;
802 }
803 if (tw_chmod(file, "0755") != 0) {
804 LOGERR("Failed to chmod '%s'\n", file.c_str());
805 return false;
806 }
807 }
808 file = "/system/etc/init.d/99SuperSUDaemon";
809 if (TWFunc::Path_Exists(file)) {
810 if (chown(file.c_str(), 0, 0) != 0) {
811 LOGERR("Failed to chown '%s'\n", file.c_str());
812 return false;
813 }
814 if (tw_chmod(file, "0755") != 0) {
815 LOGERR("Failed to chmod '%s'\n", file.c_str());
816 return false;
817 }
818 }
Dees_Troy6ef66352013-02-21 08:26:57 -0600819 file = "/system/app/Superuser.apk";
820 if (TWFunc::Path_Exists(file)) {
821 if (chown(file.c_str(), 0, 0) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000822 LOGERR("Failed to chown '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600823 return false;
824 }
825 if (tw_chmod(file, "0644") != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000826 LOGERR("Failed to chmod '%s'\n", file.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600827 return false;
828 }
829 }
830 sync();
831 if (!PartitionManager.UnMount_By_Path("/system", true))
832 return false;
833 return true;
834}
835
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200836int TWFunc::tw_chmod(const string& fn, const string& mode) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600837 long mask = 0;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200838 std::string::size_type n = mode.length();
839 int cls = 0;
Dees_Troy6ef66352013-02-21 08:26:57 -0600840
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200841 if(n == 3)
842 ++cls;
843 else if(n != 4)
844 {
845 LOGERR("TWFunc::tw_chmod used with %u long mode string (should be 3 or 4)!\n", mode.length());
846 return -1;
847 }
848
849 for (n = 0; n < mode.length(); ++n, ++cls) {
850 if (cls == 0) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600851 if (mode[n] == '0')
852 continue;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200853 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600854 mask |= S_ISVTX;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200855 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600856 mask |= S_ISGID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200857 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600858 mask |= S_ISUID;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200859 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600860 mask |= S_ISVTX;
861 mask |= S_ISUID;
862 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200863 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600864 mask |= S_ISGID;
865 mask |= S_ISUID;
866 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200867 else if (mode[n] == '7') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600868 mask |= S_ISVTX;
869 mask |= S_ISGID;
870 mask |= S_ISUID;
871 }
872 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200873 else if (cls == 1) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600874 if (mode[n] == '7') {
875 mask |= S_IRWXU;
876 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200877 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600878 mask |= S_IRUSR;
879 mask |= S_IWUSR;
880 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200881 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600882 mask |= S_IRUSR;
883 mask |= S_IXUSR;
884 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200885 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600886 mask |= S_IRUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200887 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600888 mask |= S_IWUSR;
889 mask |= S_IRUSR;
890 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200891 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600892 mask |= S_IWUSR;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200893 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600894 mask |= S_IXUSR;
895 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200896 else if (cls == 2) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600897 if (mode[n] == '7') {
898 mask |= S_IRWXG;
899 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200900 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600901 mask |= S_IRGRP;
902 mask |= S_IWGRP;
903 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200904 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600905 mask |= S_IRGRP;
906 mask |= S_IXGRP;
907 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200908 else if (mode[n] == '4')
Dees_Troy6ef66352013-02-21 08:26:57 -0600909 mask |= S_IRGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200910 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600911 mask |= S_IWGRP;
912 mask |= S_IXGRP;
913 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200914 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600915 mask |= S_IWGRP;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200916 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600917 mask |= S_IXGRP;
918 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200919 else if (cls == 3) {
Dees_Troy6ef66352013-02-21 08:26:57 -0600920 if (mode[n] == '7') {
921 mask |= S_IRWXO;
922 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200923 else if (mode[n] == '6') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600924 mask |= S_IROTH;
925 mask |= S_IWOTH;
926 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200927 else if (mode[n] == '5') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600928 mask |= S_IROTH;
929 mask |= S_IXOTH;
930 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200931 else if (mode[n] == '4')
932 mask |= S_IROTH;
933 else if (mode[n] == '3') {
Dees_Troy6ef66352013-02-21 08:26:57 -0600934 mask |= S_IWOTH;
935 mask |= S_IXOTH;
936 }
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200937 else if (mode[n] == '2')
Dees_Troy6ef66352013-02-21 08:26:57 -0600938 mask |= S_IWOTH;
Vojtech Bocek37aeb8d2013-08-29 22:38:20 +0200939 else if (mode[n] == '1')
Dees_Troy6ef66352013-02-21 08:26:57 -0600940 mask |= S_IXOTH;
941 }
942 }
943
944 if (chmod(fn.c_str(), mask) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000945 LOGERR("Unable to chmod '%s' %l\n", fn.c_str(), mask);
Dees_Troy6ef66352013-02-21 08:26:57 -0600946 return -1;
947 }
948
949 return 0;
950}
951
952bool TWFunc::Install_SuperSU(void) {
953 if (!PartitionManager.Mount_By_Path("/system", true))
954 return false;
955
Vojtech Bocek05534202013-09-11 08:11:56 +0200956 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/su");
jt1134113ee732013-02-22 23:26:10 -0600957 if (copy_file("/supersu/su", "/system/xbin/su", 0755) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000958 LOGERR("Failed to copy su binary to /system/bin\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600959 return false;
960 }
Dees_Troya7939bb2013-08-29 20:21:12 +0000961 if (!Path_Exists("/system/bin/.ext")) {
962 mkdir("/system/bin/.ext", 0777);
963 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200964 TWFunc::Exec_Cmd("/sbin/chattr -i /system/bin/.ext/su");
Dees_Troya7939bb2013-08-29 20:21:12 +0000965 if (copy_file("/supersu/su", "/system/bin/.ext/su", 0755) != 0) {
966 LOGERR("Failed to copy su binary to /system/bin/.ext/su\n");
967 return false;
968 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200969 TWFunc::Exec_Cmd("/sbin/chattr -i /system/xbin/daemonsu");
Dees_Troya7939bb2013-08-29 20:21:12 +0000970 if (copy_file("/supersu/su", "/system/xbin/daemonsu", 0755) != 0) {
971 LOGERR("Failed to copy su binary to /system/xbin/daemonsu\n");
972 return false;
973 }
974 if (Path_Exists("/system/etc/init.d")) {
Vojtech Bocek05534202013-09-11 08:11:56 +0200975 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/init.d/99SuperSUDaemon");
Dees_Troya7939bb2013-08-29 20:21:12 +0000976 if (copy_file("/supersu/99SuperSUDaemon", "/system/etc/init.d/99SuperSUDaemon", 0755) != 0) {
977 LOGERR("Failed to copy 99SuperSUDaemon to /system/etc/init.d/99SuperSUDaemon\n");
978 return false;
979 }
980 } else {
Vojtech Bocek05534202013-09-11 08:11:56 +0200981 TWFunc::Exec_Cmd("/sbin/chattr -i /system/etc/install-recovery.sh");
Dees_Troya7939bb2013-08-29 20:21:12 +0000982 if (copy_file("/supersu/install-recovery.sh", "/system/etc/install-recovery.sh", 0755) != 0) {
983 LOGERR("Failed to copy install-recovery.sh to /system/etc/install-recovery.sh\n");
984 return false;
985 }
986 }
jt1134113ee732013-02-22 23:26:10 -0600987 if (copy_file("/supersu/Superuser.apk", "/system/app/Superuser.apk", 0644) != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000988 LOGERR("Failed to copy Superuser app to /system/app\n");
Dees_Troy6ef66352013-02-21 08:26:57 -0600989 return false;
990 }
991 if (!Fix_su_Perms())
992 return false;
993 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500994}
Dees_Troy83bd4832013-05-04 12:39:56 +0000995
Dees_Troy83bd4832013-05-04 12:39:56 +0000996bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
997 DIR* d;
998
999 string Filename;
1000 Restore_Path += "/";
1001 d = opendir(Restore_Path.c_str());
1002 if (d == NULL) {
1003 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
1004 return false;
1005 }
1006
1007 struct dirent* de;
1008 while ((de = readdir(d)) != NULL) {
1009 Filename = Restore_Path;
1010 Filename += de->d_name;
1011 if (TWFunc::Get_File_Type(Filename) == 2) {
1012 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
1013 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
1014 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
1015 closedir(d);
1016 return false;
1017 }
1018 }
1019 }
1020 closedir(d);
1021 return true;
1022}
1023
Dees Troyb21cc642013-09-10 17:36:41 +00001024string TWFunc::Get_Current_Date() {
1025 string Current_Date;
1026 time_t seconds = time(0);
1027 struct tm *t = localtime(&seconds);
1028 char timestamp[255];
1029 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);
1030 Current_Date = timestamp;
1031 return Current_Date;
1032}
1033
Ethan Yonkerb5557892014-02-07 21:43:20 -06001034string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001035 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
1036 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001037 string propvalue;
1038 if (!PartitionManager.Mount_By_Path("/system", true))
1039 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001040 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -06001041 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +02001042 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +00001043 if (!mount_state)
1044 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001045 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001046 }
1047 int line_count = buildprop.size();
1048 int index;
1049 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -06001050 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +00001051 for (index = 0; index < line_count; index++) {
1052 end_pos = buildprop.at(index).find("=", start_pos);
1053 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001054 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +00001055 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -06001056 if (!mount_state)
1057 PartitionManager.UnMount_By_Path("/system", false);
1058 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +00001059 }
1060 }
Dees Troyb21cc642013-09-10 17:36:41 +00001061 if (!mount_state)
1062 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -06001063 return propvalue;
1064}
1065
1066void TWFunc::Auto_Generate_Backup_Name() {
1067 string propvalue = System_Property_Get("ro.build.display.id");
1068 if (propvalue.empty()) {
1069 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1070 return;
1071 }
1072 string Backup_Name = Get_Current_Date();
1073 Backup_Name += " " + propvalue;
1074 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
1075 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
1076 // Trailing spaces cause problems on some file systems, so remove them
1077 string space_check, space = " ";
1078 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1079 while (space_check == space) {
1080 Backup_Name.resize(Backup_Name.size() - 1);
1081 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
1082 }
1083 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -06001084 if (PartitionManager.Check_Backup_Name(false) != 0) {
1085 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
1086 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
1087 }
Vojtech Bocek05534202013-09-11 08:11:56 +02001088}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001089
1090void TWFunc::Fixup_Time_On_Boot()
1091{
1092#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +02001093
1094 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
1095
1096 struct timeval tv;
1097 uint64_t offset = 0;
1098 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
1099
1100 if (TWFunc::read_file(sepoch, offset) == 0) {
1101
1102 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
1103
1104 tv.tv_sec = offset;
1105 tv.tv_usec = 0;
1106 settimeofday(&tv, NULL);
1107
1108 gettimeofday(&tv, NULL);
1109
1110 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
1111
1112 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1113 return;
1114
1115 }
1116
1117 } else {
1118
1119 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
1120
1121 }
1122
1123 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n", sepoch.c_str());
1124
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001125 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
1126 // They never set it, it just ticks forward from 1970-01-01 00:00,
1127 // and then they have files /data/system/time/ats_* with 64bit offset
1128 // in miliseconds which, when added to the RTC, gives the correct time.
1129 // So, the time is: (offset_from_ats + value_from_RTC)
1130 // There are multiple ats files, they are for different systems? Bases?
1131 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1132 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1133
1134 static const char *paths[] = { "/data/system/time/", "/data/time/" };
1135
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001136 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001137 DIR *d;
1138 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001139 struct dirent *dt;
1140 std::string ats_path;
1141
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001142 if(!PartitionManager.Mount_By_Path("/data", false))
1143 return;
1144
1145 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1146 // - it is the one for ATS_TOD (time of day?).
1147 // However, I never saw a device where the offset differs between ats files.
1148 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
1149 {
1150 DIR *d = opendir(paths[i]);
1151 if(!d)
1152 continue;
1153
1154 while((dt = readdir(d)))
1155 {
1156 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
1157 continue;
1158
1159 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
1160 ats_path = std::string(paths[i]).append(dt->d_name);
1161 }
1162
1163 closedir(d);
1164 }
1165
1166 if(ats_path.empty())
1167 {
xNUTxe85f02d2014-07-18 01:30:58 +02001168 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001169 return;
1170 }
1171
1172 f = fopen(ats_path.c_str(), "r");
1173 if(!f)
1174 {
Dees Troy3e254b92014-03-06 20:24:54 +00001175 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001176 return;
1177 }
1178
1179 if(fread(&offset, sizeof(offset), 1, f) != 1)
1180 {
Dees Troy3e254b92014-03-06 20:24:54 +00001181 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001182 fclose(f);
1183 return;
1184 }
1185 fclose(f);
1186
1187 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
1188
1189 gettimeofday(&tv, NULL);
1190
1191 tv.tv_sec += offset/1000;
1192 tv.tv_usec += (offset%1000)*1000;
1193
1194 while(tv.tv_usec >= 1000000)
1195 {
1196 ++tv.tv_sec;
1197 tv.tv_usec -= 1000000;
1198 }
1199
1200 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001201
1202 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
1203
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001204#endif
1205}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001206
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001207std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1208{
1209 std::vector<std::string> res;
1210 size_t idx = 0, idx_last = 0;
1211
1212 while(idx < str.size())
1213 {
1214 idx = str.find_first_of(delimiter, idx_last);
1215 if(idx == std::string::npos)
1216 idx = str.size();
1217
1218 if(idx-idx_last != 0 || !removeEmpty)
1219 res.push_back(str.substr(idx_last, idx-idx_last));
1220
1221 idx_last = idx + delimiter.size();
1222 }
1223
1224 return res;
1225}
1226
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001227bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1228{
1229 std::vector<std::string> parts = Split_String(path, "/");
1230 std::string cur_path;
1231 struct stat info;
1232 for(size_t i = 0; i < parts.size(); ++i)
1233 {
1234 cur_path += "/" + parts[i];
1235 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
1236 {
1237 if(mkdir(cur_path.c_str(), mode) < 0)
1238 return false;
1239 chown(cur_path.c_str(), uid, gid);
1240 }
1241 }
1242 return true;
1243}
1244
xNUTxe85f02d2014-07-18 01:30:58 +02001245int TWFunc::Set_Brightness(std::string brightness_value)
1246{
1247
1248 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
1249
1250 if (brightness_file.compare("/nobrightness") != 0) {
1251 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
1252 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
1253 int result = TWFunc::write_file(brightness_file, brightness_value);
1254 if (secondary_brightness_file != "") {
1255 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
1256 TWFunc::write_file(secondary_brightness_file, brightness_value);
1257 }
1258 return result;
1259 }
1260 return -1;
1261}
1262
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001263bool TWFunc::Toggle_MTP(bool enable) {
1264#ifdef TW_HAS_MTP
1265 static int was_enabled = false;
1266
1267 if (enable && was_enabled) {
1268 if (!PartitionManager.Enable_MTP())
1269 PartitionManager.Disable_MTP();
1270 } else {
1271 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1272 PartitionManager.Disable_MTP();
1273 usleep(500);
1274 }
1275 return was_enabled;
1276#else
1277 return false;
1278#endif
1279}
1280
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001281#endif // ndef BUILD_TWRPTAR_MAIN