blob: 55f795c6f7e13d79909b539166132dc9d06ea761 [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"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060057 #include "set_metadata.h"
Dees_Troyb05ddee2013-01-28 20:24:50 +000058}
59
bigbiff bigbiff9c754052013-01-09 09:09:08 -050060/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020061int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000062 FILE* exec;
63 char buffer[130];
64 int ret = 0;
65 exec = __popen(cmd.c_str(), "r");
66 if (!exec) return -1;
67 while(!feof(exec)) {
68 memset(&buffer, 0, sizeof(buffer));
69 if (fgets(buffer, 128, exec) != NULL) {
70 buffer[128] = '\n';
thatd43bf2d2014-09-21 23:13:02 +020071 buffer[129] = 0;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050072 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000073 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050074 }
Dees_Troy29a06352013-08-24 12:06:47 +000075 ret = __pclose(exec);
76 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050077}
78
Vojtech Bocek05534202013-09-11 08:11:56 +020079int TWFunc::Exec_Cmd(const string& cmd) {
80 pid_t pid;
81 int status;
82 switch(pid = fork())
83 {
84 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050085 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020086 return -1;
87 case 0: // child
88 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
89 _exit(127);
90 break;
91 default:
92 {
93 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
94 return -1;
95 else
96 return 0;
97 }
98 }
99}
100
Dees_Troy38bd7602012-09-14 13:33:53 -0400101// Returns "file.name" from a full /path/to/file.name
102string TWFunc::Get_Filename(string Path) {
103 size_t pos = Path.find_last_of("/");
104 if (pos != string::npos) {
105 string Filename;
106 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
107 return Filename;
108 } else
109 return Path;
110}
111
112// Returns "/path/to/" from a full /path/to/file.name
113string TWFunc::Get_Path(string Path) {
114 size_t pos = Path.find_last_of("/");
115 if (pos != string::npos) {
116 string Pathonly;
117 Pathonly = Path.substr(0, pos + 1);
118 return Pathonly;
119 } else
120 return Path;
121}
122
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600123int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
124 pid_t rc_pid;
125
126 rc_pid = waitpid(pid, status, 0);
127 if (rc_pid > 0) {
128 if (WEXITSTATUS(*status) == 0)
129 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
130 else if (WIFSIGNALED(*status)) {
131 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
132 return -1;
133 } else if (WEXITSTATUS(*status) != 0) {
134 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
135 return -1;
136 }
137 } else { // no PID returned
138 if (errno == ECHILD)
139 LOGINFO("%s no child process exist\n", Child_Name.c_str());
140 else {
141 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
142 return -1;
143 }
144 }
145 return 0;
146}
147
148bool TWFunc::Path_Exists(string Path) {
149 // Check to see if the Path exists
150 struct stat st;
151 if (stat(Path.c_str(), &st) != 0)
152 return false;
153 else
154 return true;
155}
156
157int TWFunc::Get_File_Type(string fn) {
158 string::size_type i = 0;
159 int firstbyte = 0, secondbyte = 0;
160 char header[3];
161
162 ifstream f;
163 f.open(fn.c_str(), ios::in | ios::binary);
164 f.get(header, 3);
165 f.close();
166 firstbyte = header[i] & 0xff;
167 secondbyte = header[++i] & 0xff;
168
169 if (firstbyte == 0x1f && secondbyte == 0x8b)
170 return 1; // Compressed
171 else if (firstbyte == 0x4f && secondbyte == 0x41)
172 return 2; // Encrypted
173 else
174 return 0; // Unknown
175
176 return 0;
177}
178
179int TWFunc::Try_Decrypting_File(string fn, string password) {
180#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
181 OAES_CTX * ctx = NULL;
182 uint8_t _key_data[32] = "";
183 FILE *f;
184 uint8_t buffer[4096];
185 uint8_t *buffer_out = NULL;
186 uint8_t *ptr = NULL;
187 size_t read_len = 0, out_len = 0;
188 int firstbyte = 0, secondbyte = 0, key_len;
189 size_t _j = 0;
190 size_t _key_data_len = 0;
191
192 // mostly kanged from OpenAES oaes.c
193 for( _j = 0; _j < 32; _j++ )
194 _key_data[_j] = _j + 1;
195 _key_data_len = password.size();
196 if( 16 >= _key_data_len )
197 _key_data_len = 16;
198 else if( 24 >= _key_data_len )
199 _key_data_len = 24;
200 else
201 _key_data_len = 32;
202 memcpy(_key_data, password.c_str(), password.size());
203
204 ctx = oaes_alloc();
205 if (ctx == NULL) {
206 LOGERR("Failed to allocate OAES\n");
207 return -1;
208 }
209
210 oaes_key_import_data(ctx, _key_data, _key_data_len);
211
212 f = fopen(fn.c_str(), "rb");
213 if (f == NULL) {
214 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
215 return -1;
216 }
217 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
218 if (read_len <= 0) {
219 LOGERR("Read size during try decrypt failed\n");
220 fclose(f);
221 return -1;
222 }
223 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
224 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
225 fclose(f);
226 return -1;
227 }
228 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
229 if (buffer_out == NULL) {
230 LOGERR("Failed to allocate output buffer for try decrypt.\n");
231 fclose(f);
232 return -1;
233 }
234 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
235 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
236 fclose(f);
237 free(buffer_out);
238 return 0;
239 }
240 fclose(f);
241 if (out_len < 2) {
242 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
243 free(buffer_out);
244 return 1; // Decrypted successfully
245 }
246 ptr = buffer_out;
247 firstbyte = *ptr & 0xff;
248 ptr++;
249 secondbyte = *ptr & 0xff;
250 if (firstbyte == 0x1f && secondbyte == 0x8b) {
251 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
252 free(buffer_out);
253 return 3; // Compressed
254 }
255 if (out_len >= 262) {
256 ptr = buffer_out + 257;
257 if (strncmp((char*)ptr, "ustar", 5) == 0) {
258 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
259 free(buffer_out);
260 return 2; // Tar
261 }
262 }
263 free(buffer_out);
264 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
265 return 1; // Decrypted successfully
266#else
267 LOGERR("Encrypted backup support not included.\n");
268 return -1;
269#endif
270}
271
272unsigned long TWFunc::Get_File_Size(string Path) {
273 struct stat st;
274
275 if (stat(Path.c_str(), &st) != 0)
276 return 0;
277 return st.st_size;
278}
279
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100280std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
281{
282 std::string res;
283 size_t last_idx = 0, idx = 0;
284
285 while(last_idx != std::string::npos)
286 {
287 if(last_idx != 0)
288 res += '/';
289
290 idx = path.find_first_of('/', last_idx);
291 if(idx == std::string::npos) {
292 res += path.substr(last_idx, idx);
293 break;
294 }
295
296 res += path.substr(last_idx, idx-last_idx);
297 last_idx = path.find_first_not_of('/', idx);
298 }
299
300 if(leaveLast)
301 res += '/';
302 return res;
303}
304
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500305vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
306 vector<string> res;
307
308 if (in.empty() || del == '\0')
309 return res;
310
311 string field;
312 istringstream f(in);
313 if (del == '\n') {
314 while(getline(f, field)) {
315 if (field.empty() && skip_empty)
316 continue;
317 res.push_back(field);
318 }
319 } else {
320 while(getline(f, field, del)) {
321 if (field.empty() && skip_empty)
322 continue;
323 res.push_back(field);
324 }
325 }
326 return res;
327}
328
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600329#ifndef BUILD_TWRPTAR_MAIN
330
Dees_Troy38bd7602012-09-14 13:33:53 -0400331// Returns "/path" from a full /path/to/file.name
332string TWFunc::Get_Root_Path(string Path) {
333 string Local_Path = Path;
334
335 // Make sure that we have a leading slash
336 if (Local_Path.substr(0, 1) != "/")
337 Local_Path = "/" + Local_Path;
338
339 // Trim the path to get the root path only
340 size_t position = Local_Path.find("/", 2);
341 if (position != string::npos) {
342 Local_Path.resize(position);
343 }
344 return Local_Path;
345}
346
347void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400348 int need_libs = 0;
349
350 if (!PartitionManager.Mount_By_Path("/system", true))
351 return;
352
353 if (!PartitionManager.Mount_By_Path("/data", true))
354 return;
355
Dees_Troy2673cec2013-04-02 20:22:16 +0000356 gui_print("Installing HTC Dumlock to system...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000357 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400358 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000359 gui_print("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000360 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400361 need_libs = 1;
362 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000363 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400364 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000365 gui_print("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000366 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400367 need_libs = 1;
368 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000369 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400370 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000371 gui_print("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000372 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
373 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
374 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
375 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400376 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000377 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400378 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500379 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000380 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400381 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000382 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400383}
384
385void TWFunc::htc_dumlock_restore_original_boot(void) {
386 if (!PartitionManager.Mount_By_Path("/sdcard", true))
387 return;
388
Dees_Troy2673cec2013-04-02 20:22:16 +0000389 gui_print("Restoring original boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200390 Exec_Cmd("htcdumlock restore");
Dees_Troy2673cec2013-04-02 20:22:16 +0000391 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400392}
393
394void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
395 if (!PartitionManager.Mount_By_Path("/sdcard", true))
396 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000397 gui_print("Reflashing recovery to boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200398 Exec_Cmd("htcdumlock recovery noreboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000399 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400400}
Dees_Troy43d8b002012-09-17 16:00:01 -0400401
402int TWFunc::Recursive_Mkdir(string Path) {
403 string pathCpy = Path;
404 string wholePath;
405 size_t pos = pathCpy.find("/", 2);
406
407 while (pos != string::npos)
408 {
409 wholePath = pathCpy.substr(0, pos);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600410 if (!TWFunc::Path_Exists(wholePath)) {
411 if (mkdir(wholePath.c_str(), 0777)) {
412 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
413 return false;
414 } else {
415 tw_set_default_metadata(wholePath.c_str());
416 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400417 }
418
419 pos = pathCpy.find("/", pos + 1);
420 }
421 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
422 return false;
423 return true;
424}
425
Dees_Troyb46a6842012-09-25 11:06:46 -0400426void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
427 string Display_Text;
428
429 DataManager::GetValue(Read_Value, Display_Text);
430 if (Display_Text.empty())
431 Display_Text = Default_Text;
432
433 DataManager::SetValue("tw_operation", Display_Text);
434 DataManager::SetValue("tw_partition", "");
435}
436
437void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
438 string Display_Text;
439
440 DataManager::GetValue(Read_Value, Display_Text);
441 if (Display_Text.empty())
442 Display_Text = Default_Text;
443
444 DataManager::SetValue("tw_operation", Display_Text);
445 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400446}
447
Dees_Troy2673cec2013-04-02 20:22:16 +0000448void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000449 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000450 FILE *destination_log = fopen(Destination.c_str(), "a");
451 if (destination_log == NULL) {
452 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600453 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000454 FILE *source_log = fopen(Source.c_str(), "r");
455 if (source_log != NULL) {
456 fseek(source_log, Log_Offset, SEEK_SET);
457 char buffer[4096];
458 while (fgets(buffer, sizeof(buffer), source_log))
459 fputs(buffer, destination_log); // Buffered write of log file
460 Log_Offset = ftell(source_log);
461 fflush(source_log);
462 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600463 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000464 fflush(destination_log);
465 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600466 }
Dees_Troya58bead2012-09-27 09:49:29 -0400467}
468
Dees_Troy2673cec2013-04-02 20:22:16 +0000469void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500470 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000471 if (PartitionManager.Mount_By_Path("/cache", false)) {
472 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
473 LOGINFO("Recreating /cache/recovery folder.\n");
474 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
475 LOGINFO("Unable to create /cache/recovery folder.\n");
476 }
477 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
478 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
479 chown("/cache/recovery/log", 1000, 1000);
480 chmod("/cache/recovery/log", 0600);
481 chmod("/cache/recovery/last_log", 0640);
482 } else {
483 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
484 }
Dees_Troya58bead2012-09-27 09:49:29 -0400485
Dees_Troy2673cec2013-04-02 20:22:16 +0000486 // Reset bootloader message
487 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
488 if (Part != NULL) {
489 struct bootloader_message boot;
490 memset(&boot, 0, sizeof(boot));
491 if (Part->Current_File_System == "mtd") {
492 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
493 LOGERR("Unable to set MTD bootloader message.\n");
494 } else if (Part->Current_File_System == "emmc") {
495 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
496 LOGERR("Unable to set emmc bootloader message.\n");
497 } else {
498 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
499 }
500 }
Dees_Troya58bead2012-09-27 09:49:29 -0400501
Dees Troy9d7fdf52013-09-19 20:49:25 +0000502 if (PartitionManager.Mount_By_Path("/cache", true)) {
503 if (unlink("/cache/recovery/command") && errno != ENOENT) {
504 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
505 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500506 }
Dees_Troya58bead2012-09-27 09:49:29 -0400507
Dees_Troy2673cec2013-04-02 20:22:16 +0000508 sync();
509}
510
511void TWFunc::Update_Intent_File(string Intent) {
512 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
513 TWFunc::write_file("/cache/recovery/intent", Intent);
514 }
Dees_Troya58bead2012-09-27 09:49:29 -0400515}
516
517// reboot: Reboot the system. Return -1 on error, no return on success
518int TWFunc::tw_reboot(RebootCommand command)
519{
520 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600521 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400522
Dees_Troy2673cec2013-04-02 20:22:16 +0000523 switch (command) {
524 case rb_current:
525 case rb_system:
526 Update_Log_File();
527 Update_Intent_File("s");
528 sync();
529 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
530 return reboot(RB_AUTOBOOT);
531 case rb_recovery:
532 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600533#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600534 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600535#else
536 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
537#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600538 sleep(5);
539 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000540 case rb_bootloader:
541 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600542#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600543 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600544#else
545 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
546#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600547 sleep(5);
548 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000549 case rb_poweroff:
550 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000551#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000552 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000553#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000554 return reboot(RB_POWER_OFF);
555 case rb_download:
556 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600557#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600558 property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600559#else
560 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
561#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600562 sleep(5);
563 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000564 default:
565 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600566 }
567 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400568}
569
570void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
571{
572 // Check for and run startup script if script exists
573 struct stat st;
574 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000575 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500576 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200577 TWFunc::Exec_Cmd(script_file);
Dees_Troy2673cec2013-04-02 20:22:16 +0000578 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400579 }
Dees_Troy3477d712012-09-27 15:44:01 -0400580}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500581
582int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000583 DIR *d = opendir(path.c_str());
584 int r = 0;
585 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500586
Dees_Troyce675462013-01-09 19:48:21 +0000587 if (d == NULL) {
bigbiff7abc5fe2015-01-17 16:53:12 -0500588 LOGERR("Error opening dir: '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000589 return -1;
590 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500591
Dees_Troyce675462013-01-09 19:48:21 +0000592 if (d) {
593 struct dirent *p;
594 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000595 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
596 continue;
597 new_path = path + "/";
598 new_path.append(p->d_name);
599 if (p->d_type == DT_DIR) {
600 r = removeDir(new_path, true);
601 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500602 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500603 r = rmdir(new_path.c_str());
604 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000605 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500606 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500607 } 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 +0000608 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000609 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000610 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000611 }
Dees_Troyce675462013-01-09 19:48:21 +0000612 }
613 }
614 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500615
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500616 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500617 if (skipParent)
618 return 0;
619 else
620 r = rmdir(path.c_str());
621 }
Dees_Troyce675462013-01-09 19:48:21 +0000622 }
623 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500624}
625
626int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000627 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500628 ifstream srcfile(src.c_str(), ios::binary);
629 ofstream dstfile(dst.c_str(), ios::binary);
630 dstfile << srcfile.rdbuf();
631 srcfile.close();
632 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500633 if (chmod(dst.c_str(), mode) != 0)
634 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500635 return 0;
636}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000637
638unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
639 struct stat st;
640
641 stat(Path.c_str(), &st);
642 if (st.st_mode & S_IFDIR)
643 return DT_DIR;
644 else if (st.st_mode & S_IFBLK)
645 return DT_BLK;
646 else if (st.st_mode & S_IFCHR)
647 return DT_CHR;
648 else if (st.st_mode & S_IFIFO)
649 return DT_FIFO;
650 else if (st.st_mode & S_IFLNK)
651 return DT_LNK;
652 else if (st.st_mode & S_IFREG)
653 return DT_REG;
654 else if (st.st_mode & S_IFSOCK)
655 return DT_SOCK;
656 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000657}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500658
659int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200660 ifstream file;
661 file.open(fn.c_str(), ios::in);
662
663 if (file.is_open()) {
664 file >> results;
665 file.close();
666 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500667 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200668
669 LOGINFO("Cannot find file %s\n", fn.c_str());
670 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500671}
672
673int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500674 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500675 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500676 file.open(fn.c_str(), ios::in);
677 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500678 while (getline(file, line))
679 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500680 file.close();
681 return 0;
682 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000683 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500684 return -1;
685}
686
xNUTxe85f02d2014-07-18 01:30:58 +0200687int TWFunc::read_file(string fn, uint64_t& results) {
688 ifstream file;
689 file.open(fn.c_str(), ios::in);
690
691 if (file.is_open()) {
692 file >> results;
693 file.close();
694 return 0;
695 }
696
697 LOGINFO("Cannot find file %s\n", fn.c_str());
698 return -1;
699}
700
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500701int TWFunc::write_file(string fn, string& line) {
702 FILE *file;
703 file = fopen(fn.c_str(), "w");
704 if (file != NULL) {
705 fwrite(line.c_str(), line.size(), 1, file);
706 fclose(file);
707 return 0;
708 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000709 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500710 return -1;
711}
712
713timespec TWFunc::timespec_diff(timespec& start, timespec& end)
714{
Dees_Troy6ef66352013-02-21 08:26:57 -0600715 timespec temp;
716 if ((end.tv_nsec-start.tv_nsec)<0) {
717 temp.tv_sec = end.tv_sec-start.tv_sec-1;
718 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
719 } else {
720 temp.tv_sec = end.tv_sec-start.tv_sec;
721 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
722 }
723 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500724}
725
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100726int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
727{
728 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
729 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
730}
731
Dees_Troy6ef66352013-02-21 08:26:57 -0600732bool TWFunc::Install_SuperSU(void) {
733 if (!PartitionManager.Mount_By_Path("/system", true))
734 return false;
735
Ethan Yonkere3e88292014-12-10 16:17:55 -0600736 check_and_run_script("/supersu/install-supersu.sh", "SuperSU");
Dees_Troy6ef66352013-02-21 08:26:57 -0600737 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500738}
Dees_Troy83bd4832013-05-04 12:39:56 +0000739
Dees_Troy83bd4832013-05-04 12:39:56 +0000740bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
741 DIR* d;
742
743 string Filename;
744 Restore_Path += "/";
745 d = opendir(Restore_Path.c_str());
746 if (d == NULL) {
747 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
748 return false;
749 }
750
751 struct dirent* de;
752 while ((de = readdir(d)) != NULL) {
753 Filename = Restore_Path;
754 Filename += de->d_name;
755 if (TWFunc::Get_File_Type(Filename) == 2) {
756 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
757 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
758 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
759 closedir(d);
760 return false;
761 }
762 }
763 }
764 closedir(d);
765 return true;
766}
767
Dees Troyb21cc642013-09-10 17:36:41 +0000768string TWFunc::Get_Current_Date() {
769 string Current_Date;
770 time_t seconds = time(0);
771 struct tm *t = localtime(&seconds);
772 char timestamp[255];
773 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);
774 Current_Date = timestamp;
775 return Current_Date;
776}
777
Ethan Yonkerb5557892014-02-07 21:43:20 -0600778string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000779 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
780 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600781 string propvalue;
782 if (!PartitionManager.Mount_By_Path("/system", true))
783 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000784 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -0600785 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200786 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000787 if (!mount_state)
788 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600789 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000790 }
791 int line_count = buildprop.size();
792 int index;
793 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600794 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000795 for (index = 0; index < line_count; index++) {
796 end_pos = buildprop.at(index).find("=", start_pos);
797 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600798 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000799 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600800 if (!mount_state)
801 PartitionManager.UnMount_By_Path("/system", false);
802 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000803 }
804 }
Dees Troyb21cc642013-09-10 17:36:41 +0000805 if (!mount_state)
806 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600807 return propvalue;
808}
809
810void TWFunc::Auto_Generate_Backup_Name() {
811 string propvalue = System_Property_Get("ro.build.display.id");
812 if (propvalue.empty()) {
813 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
814 return;
815 }
816 string Backup_Name = Get_Current_Date();
817 Backup_Name += " " + propvalue;
818 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
819 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
820 // Trailing spaces cause problems on some file systems, so remove them
821 string space_check, space = " ";
822 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
823 while (space_check == space) {
824 Backup_Name.resize(Backup_Name.size() - 1);
825 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
826 }
827 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600828 if (PartitionManager.Check_Backup_Name(false) != 0) {
829 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
830 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
831 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200832}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100833
834void TWFunc::Fixup_Time_On_Boot()
835{
836#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +0200837
838 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
839
840 struct timeval tv;
841 uint64_t offset = 0;
842 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
843
844 if (TWFunc::read_file(sepoch, offset) == 0) {
845
846 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
847
848 tv.tv_sec = offset;
849 tv.tv_usec = 0;
850 settimeofday(&tv, NULL);
851
852 gettimeofday(&tv, NULL);
853
854 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
855
856 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
857 return;
858
859 }
860
861 } else {
862
863 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
864
865 }
866
Ethan Yonker9132d912015-02-02 10:32:49 -0600867 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200868
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100869 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
870 // They never set it, it just ticks forward from 1970-01-01 00:00,
871 // and then they have files /data/system/time/ats_* with 64bit offset
872 // in miliseconds which, when added to the RTC, gives the correct time.
873 // So, the time is: (offset_from_ats + value_from_RTC)
874 // There are multiple ats files, they are for different systems? Bases?
875 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
876 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
877
878 static const char *paths[] = { "/data/system/time/", "/data/time/" };
879
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100880 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200881 DIR *d;
882 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100883 struct dirent *dt;
884 std::string ats_path;
885
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100886 if(!PartitionManager.Mount_By_Path("/data", false))
887 return;
888
889 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
890 // - it is the one for ATS_TOD (time of day?).
891 // However, I never saw a device where the offset differs between ats files.
892 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
893 {
894 DIR *d = opendir(paths[i]);
895 if(!d)
896 continue;
897
898 while((dt = readdir(d)))
899 {
900 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
901 continue;
902
903 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
904 ats_path = std::string(paths[i]).append(dt->d_name);
905 }
906
907 closedir(d);
908 }
909
910 if(ats_path.empty())
911 {
xNUTxe85f02d2014-07-18 01:30:58 +0200912 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100913 return;
914 }
915
916 f = fopen(ats_path.c_str(), "r");
917 if(!f)
918 {
Dees Troy3e254b92014-03-06 20:24:54 +0000919 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100920 return;
921 }
922
923 if(fread(&offset, sizeof(offset), 1, f) != 1)
924 {
Dees Troy3e254b92014-03-06 20:24:54 +0000925 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100926 fclose(f);
927 return;
928 }
929 fclose(f);
930
931 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
932
933 gettimeofday(&tv, NULL);
934
935 tv.tv_sec += offset/1000;
936 tv.tv_usec += (offset%1000)*1000;
937
938 while(tv.tv_usec >= 1000000)
939 {
940 ++tv.tv_sec;
941 tv.tv_usec -= 1000000;
942 }
943
944 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +0200945
946 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
947
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100948#endif
949}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600950
Vojtech Bocek0b7fe502014-03-13 17:36:52 +0100951std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
952{
953 std::vector<std::string> res;
954 size_t idx = 0, idx_last = 0;
955
956 while(idx < str.size())
957 {
958 idx = str.find_first_of(delimiter, idx_last);
959 if(idx == std::string::npos)
960 idx = str.size();
961
962 if(idx-idx_last != 0 || !removeEmpty)
963 res.push_back(str.substr(idx_last, idx-idx_last));
964
965 idx_last = idx + delimiter.size();
966 }
967
968 return res;
969}
970
Vojtech Bocek03fd6c52014-03-13 18:46:34 +0100971bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
972{
973 std::vector<std::string> parts = Split_String(path, "/");
974 std::string cur_path;
975 struct stat info;
976 for(size_t i = 0; i < parts.size(); ++i)
977 {
978 cur_path += "/" + parts[i];
979 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
980 {
981 if(mkdir(cur_path.c_str(), mode) < 0)
982 return false;
983 chown(cur_path.c_str(), uid, gid);
984 }
985 }
986 return true;
987}
988
xNUTxe85f02d2014-07-18 01:30:58 +0200989int TWFunc::Set_Brightness(std::string brightness_value)
990{
991
992 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
993
994 if (brightness_file.compare("/nobrightness") != 0) {
995 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
996 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
997 int result = TWFunc::write_file(brightness_file, brightness_value);
998 if (secondary_brightness_file != "") {
999 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
1000 TWFunc::write_file(secondary_brightness_file, brightness_value);
1001 }
1002 return result;
1003 }
1004 return -1;
1005}
1006
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001007bool TWFunc::Toggle_MTP(bool enable) {
1008#ifdef TW_HAS_MTP
1009 static int was_enabled = false;
1010
1011 if (enable && was_enabled) {
1012 if (!PartitionManager.Enable_MTP())
1013 PartitionManager.Disable_MTP();
1014 } else {
1015 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1016 PartitionManager.Disable_MTP();
1017 usleep(500);
1018 }
1019 return was_enabled;
1020#else
1021 return false;
1022#endif
1023}
1024
Tom Hite5a926722014-09-15 01:31:03 +00001025void TWFunc::SetPerformanceMode(bool mode) {
1026 if (mode) {
1027 property_set("recovery.perf.mode", "1");
1028 } else {
1029 property_set("recovery.perf.mode", "0");
1030 }
1031 // Some time for events to catch up to init handlers
1032 usleep(500000);
1033}
1034
Jenkins1710bf22014-10-02 20:22:21 -04001035std::string TWFunc::to_string(unsigned long value) {
1036 std::ostringstream os;
1037 os << value;
1038 return os.str();
1039}
1040
Ethan Yonker9132d912015-02-02 10:32:49 -06001041void TWFunc::Disable_Stock_Recovery_Replace(void) {
1042 if (PartitionManager.Mount_By_Path("/system", false)) {
1043 // Disable flashing of stock recovery
1044 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1045 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
1046 gui_print("Renamed stock recovery file in /system to prevent\nthe stock ROM from replacing TWRP.\n");
1047 sync();
1048 }
1049 PartitionManager.UnMount_By_Path("/system", false);
1050 }
1051}
1052
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001053#endif // ndef BUILD_TWRPTAR_MAIN