blob: e6961e28848d8d146cdd22016c5820113aa8e8e5 [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>
bigbiff74a6d0d2015-02-14 20:49:44 -050038#include <algorithm>
Dees_Troy38bd7602012-09-14 13:33:53 -040039#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000040#include "twcommon.h"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060041#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040042#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060043#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040044#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000045#include "bootloader.h"
Tom Hite5a926722014-09-15 01:31:03 +000046#include "cutils/properties.h"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060047#ifdef ANDROID_RB_POWEROFF
48 #include "cutils/android_reboot.h"
49#endif
50#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000051#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
52 #include "openaes/inc/oaes_lib.h"
53#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -060054#include "cutils/android_reboot.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040055
Dees_Troyb05ddee2013-01-28 20:24:50 +000056extern "C" {
57 #include "libcrecovery/common.h"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060058 #include "set_metadata.h"
Dees_Troyb05ddee2013-01-28 20:24:50 +000059}
60
bigbiff bigbiff9c754052013-01-09 09:09:08 -050061/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020062int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000063 FILE* exec;
64 char buffer[130];
65 int ret = 0;
66 exec = __popen(cmd.c_str(), "r");
67 if (!exec) return -1;
68 while(!feof(exec)) {
69 memset(&buffer, 0, sizeof(buffer));
70 if (fgets(buffer, 128, exec) != NULL) {
71 buffer[128] = '\n';
thatd43bf2d2014-09-21 23:13:02 +020072 buffer[129] = 0;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050073 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000074 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050075 }
Dees_Troy29a06352013-08-24 12:06:47 +000076 ret = __pclose(exec);
77 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050078}
79
Vojtech Bocek05534202013-09-11 08:11:56 +020080int TWFunc::Exec_Cmd(const string& cmd) {
81 pid_t pid;
82 int status;
83 switch(pid = fork())
84 {
85 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050086 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020087 return -1;
88 case 0: // child
89 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
90 _exit(127);
91 break;
92 default:
93 {
94 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
95 return -1;
96 else
97 return 0;
98 }
99 }
100}
101
Dees_Troy38bd7602012-09-14 13:33:53 -0400102// Returns "file.name" from a full /path/to/file.name
103string TWFunc::Get_Filename(string Path) {
104 size_t pos = Path.find_last_of("/");
105 if (pos != string::npos) {
106 string Filename;
107 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
108 return Filename;
109 } else
110 return Path;
111}
112
113// Returns "/path/to/" from a full /path/to/file.name
114string TWFunc::Get_Path(string Path) {
115 size_t pos = Path.find_last_of("/");
116 if (pos != string::npos) {
117 string Pathonly;
118 Pathonly = Path.substr(0, pos + 1);
119 return Pathonly;
120 } else
121 return Path;
122}
123
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600124int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
125 pid_t rc_pid;
126
127 rc_pid = waitpid(pid, status, 0);
128 if (rc_pid > 0) {
129 if (WEXITSTATUS(*status) == 0)
130 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
131 else if (WIFSIGNALED(*status)) {
132 LOGINFO("%s process ended with signal: %d\n", Child_Name.c_str(), WTERMSIG(*status)); // Seg fault or some other non-graceful termination
133 return -1;
134 } else if (WEXITSTATUS(*status) != 0) {
135 LOGINFO("%s process ended with ERROR=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Graceful exit, but there was an error
136 return -1;
137 }
138 } else { // no PID returned
139 if (errno == ECHILD)
140 LOGINFO("%s no child process exist\n", Child_Name.c_str());
141 else {
142 LOGINFO("%s Unexpected error\n", Child_Name.c_str());
143 return -1;
144 }
145 }
146 return 0;
147}
148
149bool TWFunc::Path_Exists(string Path) {
150 // Check to see if the Path exists
151 struct stat st;
152 if (stat(Path.c_str(), &st) != 0)
153 return false;
154 else
155 return true;
156}
157
158int TWFunc::Get_File_Type(string fn) {
159 string::size_type i = 0;
160 int firstbyte = 0, secondbyte = 0;
161 char header[3];
162
163 ifstream f;
164 f.open(fn.c_str(), ios::in | ios::binary);
165 f.get(header, 3);
166 f.close();
167 firstbyte = header[i] & 0xff;
168 secondbyte = header[++i] & 0xff;
169
170 if (firstbyte == 0x1f && secondbyte == 0x8b)
171 return 1; // Compressed
172 else if (firstbyte == 0x4f && secondbyte == 0x41)
173 return 2; // Encrypted
174 else
175 return 0; // Unknown
176
177 return 0;
178}
179
180int TWFunc::Try_Decrypting_File(string fn, string password) {
181#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
182 OAES_CTX * ctx = NULL;
183 uint8_t _key_data[32] = "";
184 FILE *f;
185 uint8_t buffer[4096];
186 uint8_t *buffer_out = NULL;
187 uint8_t *ptr = NULL;
188 size_t read_len = 0, out_len = 0;
189 int firstbyte = 0, secondbyte = 0, key_len;
190 size_t _j = 0;
191 size_t _key_data_len = 0;
192
193 // mostly kanged from OpenAES oaes.c
194 for( _j = 0; _j < 32; _j++ )
195 _key_data[_j] = _j + 1;
196 _key_data_len = password.size();
197 if( 16 >= _key_data_len )
198 _key_data_len = 16;
199 else if( 24 >= _key_data_len )
200 _key_data_len = 24;
201 else
202 _key_data_len = 32;
203 memcpy(_key_data, password.c_str(), password.size());
204
205 ctx = oaes_alloc();
206 if (ctx == NULL) {
207 LOGERR("Failed to allocate OAES\n");
208 return -1;
209 }
210
211 oaes_key_import_data(ctx, _key_data, _key_data_len);
212
213 f = fopen(fn.c_str(), "rb");
214 if (f == NULL) {
215 LOGERR("Failed to open '%s' to try decrypt\n", fn.c_str());
216 return -1;
217 }
218 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
219 if (read_len <= 0) {
220 LOGERR("Read size during try decrypt failed\n");
221 fclose(f);
222 return -1;
223 }
224 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
225 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
226 fclose(f);
227 return -1;
228 }
229 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
230 if (buffer_out == NULL) {
231 LOGERR("Failed to allocate output buffer for try decrypt.\n");
232 fclose(f);
233 return -1;
234 }
235 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
236 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
237 fclose(f);
238 free(buffer_out);
239 return 0;
240 }
241 fclose(f);
242 if (out_len < 2) {
243 LOGINFO("Successfully decrypted '%s' but read length %i too small.\n", fn.c_str(), out_len);
244 free(buffer_out);
245 return 1; // Decrypted successfully
246 }
247 ptr = buffer_out;
248 firstbyte = *ptr & 0xff;
249 ptr++;
250 secondbyte = *ptr & 0xff;
251 if (firstbyte == 0x1f && secondbyte == 0x8b) {
252 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
253 free(buffer_out);
254 return 3; // Compressed
255 }
256 if (out_len >= 262) {
257 ptr = buffer_out + 257;
258 if (strncmp((char*)ptr, "ustar", 5) == 0) {
259 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
260 free(buffer_out);
261 return 2; // Tar
262 }
263 }
264 free(buffer_out);
265 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
266 return 1; // Decrypted successfully
267#else
268 LOGERR("Encrypted backup support not included.\n");
269 return -1;
270#endif
271}
272
273unsigned long TWFunc::Get_File_Size(string Path) {
274 struct stat st;
275
276 if (stat(Path.c_str(), &st) != 0)
277 return 0;
278 return st.st_size;
279}
280
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100281std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
282{
283 std::string res;
284 size_t last_idx = 0, idx = 0;
285
286 while(last_idx != std::string::npos)
287 {
288 if(last_idx != 0)
289 res += '/';
290
291 idx = path.find_first_of('/', last_idx);
292 if(idx == std::string::npos) {
293 res += path.substr(last_idx, idx);
294 break;
295 }
296
297 res += path.substr(last_idx, idx-last_idx);
298 last_idx = path.find_first_not_of('/', idx);
299 }
300
301 if(leaveLast)
302 res += '/';
303 return res;
304}
305
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500306vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
307 vector<string> res;
308
309 if (in.empty() || del == '\0')
310 return res;
311
312 string field;
313 istringstream f(in);
314 if (del == '\n') {
315 while(getline(f, field)) {
316 if (field.empty() && skip_empty)
317 continue;
318 res.push_back(field);
319 }
320 } else {
321 while(getline(f, field, del)) {
322 if (field.empty() && skip_empty)
323 continue;
324 res.push_back(field);
325 }
326 }
327 return res;
328}
329
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600330#ifndef BUILD_TWRPTAR_MAIN
331
Dees_Troy38bd7602012-09-14 13:33:53 -0400332// Returns "/path" from a full /path/to/file.name
333string TWFunc::Get_Root_Path(string Path) {
334 string Local_Path = Path;
335
336 // Make sure that we have a leading slash
337 if (Local_Path.substr(0, 1) != "/")
338 Local_Path = "/" + Local_Path;
339
340 // Trim the path to get the root path only
341 size_t position = Local_Path.find("/", 2);
342 if (position != string::npos) {
343 Local_Path.resize(position);
344 }
345 return Local_Path;
346}
347
348void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400349 int need_libs = 0;
350
351 if (!PartitionManager.Mount_By_Path("/system", true))
352 return;
353
354 if (!PartitionManager.Mount_By_Path("/data", true))
355 return;
356
Dees_Troy2673cec2013-04-02 20:22:16 +0000357 gui_print("Installing HTC Dumlock to system...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000358 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400359 if (!Path_Exists("/system/bin/flash_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000360 gui_print("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000361 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400362 need_libs = 1;
363 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000364 gui_print("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400365 if (!Path_Exists("/system/bin/dump_image")) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000366 gui_print("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000367 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400368 need_libs = 1;
369 } else
Dees_Troy2673cec2013-04-02 20:22:16 +0000370 gui_print("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400371 if (need_libs) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000372 gui_print("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000373 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
374 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
375 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
376 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400377 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000378 gui_print("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400379 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500380 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000381 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400382 sync();
Dees_Troy2673cec2013-04-02 20:22:16 +0000383 gui_print("HTC Dumlock is installed.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400384}
385
386void TWFunc::htc_dumlock_restore_original_boot(void) {
387 if (!PartitionManager.Mount_By_Path("/sdcard", true))
388 return;
389
Dees_Troy2673cec2013-04-02 20:22:16 +0000390 gui_print("Restoring original boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200391 Exec_Cmd("htcdumlock restore");
Dees_Troy2673cec2013-04-02 20:22:16 +0000392 gui_print("Original boot restored.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400393}
394
395void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
396 if (!PartitionManager.Mount_By_Path("/sdcard", true))
397 return;
Dees_Troy2673cec2013-04-02 20:22:16 +0000398 gui_print("Reflashing recovery to boot...\n");
Vojtech Bocek05534202013-09-11 08:11:56 +0200399 Exec_Cmd("htcdumlock recovery noreboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000400 gui_print("Recovery is flashed to boot.\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400401}
Dees_Troy43d8b002012-09-17 16:00:01 -0400402
403int TWFunc::Recursive_Mkdir(string Path) {
404 string pathCpy = Path;
405 string wholePath;
406 size_t pos = pathCpy.find("/", 2);
407
408 while (pos != string::npos)
409 {
410 wholePath = pathCpy.substr(0, pos);
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600411 if (!TWFunc::Path_Exists(wholePath)) {
412 if (mkdir(wholePath.c_str(), 0777)) {
413 LOGERR("Unable to create folder: %s (errno=%d)\n", wholePath.c_str(), errno);
414 return false;
415 } else {
416 tw_set_default_metadata(wholePath.c_str());
417 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400418 }
419
420 pos = pathCpy.find("/", pos + 1);
421 }
422 if (mkdir(wholePath.c_str(), 0777) && errno != EEXIST)
423 return false;
424 return true;
425}
426
Dees_Troyb46a6842012-09-25 11:06:46 -0400427void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
428 string Display_Text;
429
430 DataManager::GetValue(Read_Value, Display_Text);
431 if (Display_Text.empty())
432 Display_Text = Default_Text;
433
434 DataManager::SetValue("tw_operation", Display_Text);
435 DataManager::SetValue("tw_partition", "");
436}
437
438void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
439 string Display_Text;
440
441 DataManager::GetValue(Read_Value, Display_Text);
442 if (Display_Text.empty())
443 Display_Text = Default_Text;
444
445 DataManager::SetValue("tw_operation", Display_Text);
446 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400447}
448
Dees_Troy2673cec2013-04-02 20:22:16 +0000449void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000450 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000451 FILE *destination_log = fopen(Destination.c_str(), "a");
452 if (destination_log == NULL) {
453 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600454 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000455 FILE *source_log = fopen(Source.c_str(), "r");
456 if (source_log != NULL) {
457 fseek(source_log, Log_Offset, SEEK_SET);
458 char buffer[4096];
459 while (fgets(buffer, sizeof(buffer), source_log))
460 fputs(buffer, destination_log); // Buffered write of log file
461 Log_Offset = ftell(source_log);
462 fflush(source_log);
463 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600464 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000465 fflush(destination_log);
466 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600467 }
Dees_Troya58bead2012-09-27 09:49:29 -0400468}
469
Dees_Troy2673cec2013-04-02 20:22:16 +0000470void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500471 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000472 if (PartitionManager.Mount_By_Path("/cache", false)) {
473 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
474 LOGINFO("Recreating /cache/recovery folder.\n");
475 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
476 LOGINFO("Unable to create /cache/recovery folder.\n");
477 }
478 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
479 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
480 chown("/cache/recovery/log", 1000, 1000);
481 chmod("/cache/recovery/log", 0600);
482 chmod("/cache/recovery/last_log", 0640);
483 } else {
484 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
485 }
Dees_Troya58bead2012-09-27 09:49:29 -0400486
Dees_Troy2673cec2013-04-02 20:22:16 +0000487 // Reset bootloader message
488 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
489 if (Part != NULL) {
490 struct bootloader_message boot;
491 memset(&boot, 0, sizeof(boot));
492 if (Part->Current_File_System == "mtd") {
493 if (set_bootloader_message_mtd_name(&boot, Part->MTD_Name.c_str()) != 0)
494 LOGERR("Unable to set MTD bootloader message.\n");
495 } else if (Part->Current_File_System == "emmc") {
496 if (set_bootloader_message_block_name(&boot, Part->Actual_Block_Device.c_str()) != 0)
497 LOGERR("Unable to set emmc bootloader message.\n");
498 } else {
499 LOGERR("Unknown file system for /misc: '%s'\n", Part->Current_File_System.c_str());
500 }
501 }
Dees_Troya58bead2012-09-27 09:49:29 -0400502
Dees Troy9d7fdf52013-09-19 20:49:25 +0000503 if (PartitionManager.Mount_By_Path("/cache", true)) {
504 if (unlink("/cache/recovery/command") && errno != ENOENT) {
505 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
506 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500507 }
Dees_Troya58bead2012-09-27 09:49:29 -0400508
Dees_Troy2673cec2013-04-02 20:22:16 +0000509 sync();
510}
511
512void TWFunc::Update_Intent_File(string Intent) {
513 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
514 TWFunc::write_file("/cache/recovery/intent", Intent);
515 }
Dees_Troya58bead2012-09-27 09:49:29 -0400516}
517
518// reboot: Reboot the system. Return -1 on error, no return on success
519int TWFunc::tw_reboot(RebootCommand command)
520{
521 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600522 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400523
Dees_Troy2673cec2013-04-02 20:22:16 +0000524 switch (command) {
525 case rb_current:
526 case rb_system:
527 Update_Log_File();
528 Update_Intent_File("s");
529 sync();
530 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
531 return reboot(RB_AUTOBOOT);
532 case rb_recovery:
533 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600534#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600535 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600536#else
537 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
538#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600539 sleep(5);
540 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000541 case rb_bootloader:
542 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600543#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600544 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600545#else
546 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
547#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600548 sleep(5);
549 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000550 case rb_poweroff:
551 check_and_run_script("/sbin/poweroff.sh", "power off");
Dees_Troya4438782013-02-22 18:44:00 +0000552#ifdef ANDROID_RB_POWEROFF
Dees_Troy2673cec2013-04-02 20:22:16 +0000553 android_reboot(ANDROID_RB_POWEROFF, 0, 0);
Dees_Troya4438782013-02-22 18:44:00 +0000554#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000555 return reboot(RB_POWER_OFF);
556 case rb_download:
557 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600558#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600559 property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600560#else
561 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
562#endif
Ethan Yonkerd7f20922014-11-07 10:33:08 -0600563 sleep(5);
564 return 0;
Dees_Troy2673cec2013-04-02 20:22:16 +0000565 default:
566 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600567 }
568 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400569}
570
571void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
572{
573 // Check for and run startup script if script exists
574 struct stat st;
575 if (stat(script_file, &st) == 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000576 gui_print("Running %s script...\n", display_name);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500577 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200578 TWFunc::Exec_Cmd(script_file);
Dees_Troy2673cec2013-04-02 20:22:16 +0000579 gui_print("\nFinished running %s script.\n", display_name);
Dees_Troya58bead2012-09-27 09:49:29 -0400580 }
Dees_Troy3477d712012-09-27 15:44:01 -0400581}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500582
583int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000584 DIR *d = opendir(path.c_str());
585 int r = 0;
586 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500587
Dees_Troyce675462013-01-09 19:48:21 +0000588 if (d == NULL) {
bigbiff7abc5fe2015-01-17 16:53:12 -0500589 LOGERR("Error opening dir: '%s'\n", path.c_str());
Dees_Troyce675462013-01-09 19:48:21 +0000590 return -1;
591 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500592
Dees_Troyce675462013-01-09 19:48:21 +0000593 if (d) {
594 struct dirent *p;
595 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000596 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
597 continue;
598 new_path = path + "/";
599 new_path.append(p->d_name);
600 if (p->d_type == DT_DIR) {
601 r = removeDir(new_path, true);
602 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500603 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500604 r = rmdir(new_path.c_str());
605 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000606 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500607 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500608 } 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 +0000609 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000610 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000611 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000612 }
Dees_Troyce675462013-01-09 19:48:21 +0000613 }
614 }
615 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500616
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500617 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500618 if (skipParent)
619 return 0;
620 else
621 r = rmdir(path.c_str());
622 }
Dees_Troyce675462013-01-09 19:48:21 +0000623 }
624 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500625}
626
627int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000628 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500629 ifstream srcfile(src.c_str(), ios::binary);
630 ofstream dstfile(dst.c_str(), ios::binary);
631 dstfile << srcfile.rdbuf();
632 srcfile.close();
633 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500634 if (chmod(dst.c_str(), mode) != 0)
635 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500636 return 0;
637}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000638
639unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
640 struct stat st;
641
642 stat(Path.c_str(), &st);
643 if (st.st_mode & S_IFDIR)
644 return DT_DIR;
645 else if (st.st_mode & S_IFBLK)
646 return DT_BLK;
647 else if (st.st_mode & S_IFCHR)
648 return DT_CHR;
649 else if (st.st_mode & S_IFIFO)
650 return DT_FIFO;
651 else if (st.st_mode & S_IFLNK)
652 return DT_LNK;
653 else if (st.st_mode & S_IFREG)
654 return DT_REG;
655 else if (st.st_mode & S_IFSOCK)
656 return DT_SOCK;
657 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000658}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500659
660int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200661 ifstream file;
662 file.open(fn.c_str(), ios::in);
663
664 if (file.is_open()) {
665 file >> results;
666 file.close();
667 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500668 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200669
670 LOGINFO("Cannot find file %s\n", fn.c_str());
671 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500672}
673
674int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500675 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500676 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500677 file.open(fn.c_str(), ios::in);
678 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500679 while (getline(file, line))
680 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500681 file.close();
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
xNUTxe85f02d2014-07-18 01:30:58 +0200688int TWFunc::read_file(string fn, uint64_t& results) {
689 ifstream file;
690 file.open(fn.c_str(), ios::in);
691
692 if (file.is_open()) {
693 file >> results;
694 file.close();
695 return 0;
696 }
697
698 LOGINFO("Cannot find file %s\n", fn.c_str());
699 return -1;
700}
701
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500702int TWFunc::write_file(string fn, string& line) {
703 FILE *file;
704 file = fopen(fn.c_str(), "w");
705 if (file != NULL) {
706 fwrite(line.c_str(), line.size(), 1, file);
707 fclose(file);
708 return 0;
709 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000710 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500711 return -1;
712}
713
714timespec TWFunc::timespec_diff(timespec& start, timespec& end)
715{
Dees_Troy6ef66352013-02-21 08:26:57 -0600716 timespec temp;
717 if ((end.tv_nsec-start.tv_nsec)<0) {
718 temp.tv_sec = end.tv_sec-start.tv_sec-1;
719 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
720 } else {
721 temp.tv_sec = end.tv_sec-start.tv_sec;
722 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
723 }
724 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500725}
726
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100727int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
728{
729 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
730 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
731}
732
Dees_Troy6ef66352013-02-21 08:26:57 -0600733bool TWFunc::Install_SuperSU(void) {
734 if (!PartitionManager.Mount_By_Path("/system", true))
735 return false;
736
Ethan Yonkere3e88292014-12-10 16:17:55 -0600737 check_and_run_script("/supersu/install-supersu.sh", "SuperSU");
Dees_Troy6ef66352013-02-21 08:26:57 -0600738 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500739}
Dees_Troy83bd4832013-05-04 12:39:56 +0000740
Dees_Troy83bd4832013-05-04 12:39:56 +0000741bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
742 DIR* d;
743
744 string Filename;
745 Restore_Path += "/";
746 d = opendir(Restore_Path.c_str());
747 if (d == NULL) {
748 LOGERR("Error opening '%s'\n", Restore_Path.c_str());
749 return false;
750 }
751
752 struct dirent* de;
753 while ((de = readdir(d)) != NULL) {
754 Filename = Restore_Path;
755 Filename += de->d_name;
756 if (TWFunc::Get_File_Type(Filename) == 2) {
757 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
758 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
759 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
760 closedir(d);
761 return false;
762 }
763 }
764 }
765 closedir(d);
766 return true;
767}
768
Dees Troyb21cc642013-09-10 17:36:41 +0000769string TWFunc::Get_Current_Date() {
770 string Current_Date;
771 time_t seconds = time(0);
772 struct tm *t = localtime(&seconds);
773 char timestamp[255];
774 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);
775 Current_Date = timestamp;
776 return Current_Date;
777}
778
Ethan Yonkerb5557892014-02-07 21:43:20 -0600779string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000780 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
781 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600782 string propvalue;
783 if (!PartitionManager.Mount_By_Path("/system", true))
784 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000785 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -0600786 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200787 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000788 if (!mount_state)
789 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600790 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000791 }
792 int line_count = buildprop.size();
793 int index;
794 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600795 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000796 for (index = 0; index < line_count; index++) {
797 end_pos = buildprop.at(index).find("=", start_pos);
798 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600799 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000800 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600801 if (!mount_state)
802 PartitionManager.UnMount_By_Path("/system", false);
803 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000804 }
805 }
Dees Troyb21cc642013-09-10 17:36:41 +0000806 if (!mount_state)
807 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600808 return propvalue;
809}
810
811void TWFunc::Auto_Generate_Backup_Name() {
812 string propvalue = System_Property_Get("ro.build.display.id");
813 if (propvalue.empty()) {
814 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
815 return;
816 }
817 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500818 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600819 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
820 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
821 // Trailing spaces cause problems on some file systems, so remove them
822 string space_check, space = " ";
823 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
824 while (space_check == space) {
825 Backup_Name.resize(Backup_Name.size() - 1);
826 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
827 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500828 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonkerb5557892014-02-07 21:43:20 -0600829 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600830 if (PartitionManager.Check_Backup_Name(false) != 0) {
831 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
832 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
833 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200834}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100835
836void TWFunc::Fixup_Time_On_Boot()
837{
838#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +0200839
840 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
841
842 struct timeval tv;
843 uint64_t offset = 0;
844 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
845
846 if (TWFunc::read_file(sepoch, offset) == 0) {
847
848 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
849
850 tv.tv_sec = offset;
851 tv.tv_usec = 0;
852 settimeofday(&tv, NULL);
853
854 gettimeofday(&tv, NULL);
855
856 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
857
858 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
859 return;
860
861 }
862
863 } else {
864
865 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
866
867 }
868
Ethan Yonker9132d912015-02-02 10:32:49 -0600869 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200870
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100871 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
872 // They never set it, it just ticks forward from 1970-01-01 00:00,
873 // and then they have files /data/system/time/ats_* with 64bit offset
874 // in miliseconds which, when added to the RTC, gives the correct time.
875 // So, the time is: (offset_from_ats + value_from_RTC)
876 // There are multiple ats files, they are for different systems? Bases?
877 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
878 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
879
880 static const char *paths[] = { "/data/system/time/", "/data/time/" };
881
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100882 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200883 DIR *d;
884 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100885 struct dirent *dt;
886 std::string ats_path;
887
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100888 if(!PartitionManager.Mount_By_Path("/data", false))
889 return;
890
891 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
892 // - it is the one for ATS_TOD (time of day?).
893 // However, I never saw a device where the offset differs between ats files.
894 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
895 {
896 DIR *d = opendir(paths[i]);
897 if(!d)
898 continue;
899
900 while((dt = readdir(d)))
901 {
902 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
903 continue;
904
905 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
906 ats_path = std::string(paths[i]).append(dt->d_name);
907 }
908
909 closedir(d);
910 }
911
912 if(ats_path.empty())
913 {
xNUTxe85f02d2014-07-18 01:30:58 +0200914 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100915 return;
916 }
917
918 f = fopen(ats_path.c_str(), "r");
919 if(!f)
920 {
Dees Troy3e254b92014-03-06 20:24:54 +0000921 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100922 return;
923 }
924
925 if(fread(&offset, sizeof(offset), 1, f) != 1)
926 {
Dees Troy3e254b92014-03-06 20:24:54 +0000927 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100928 fclose(f);
929 return;
930 }
931 fclose(f);
932
933 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
934
935 gettimeofday(&tv, NULL);
936
937 tv.tv_sec += offset/1000;
938 tv.tv_usec += (offset%1000)*1000;
939
940 while(tv.tv_usec >= 1000000)
941 {
942 ++tv.tv_sec;
943 tv.tv_usec -= 1000000;
944 }
945
946 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +0200947
948 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
949
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100950#endif
951}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600952
Vojtech Bocek0b7fe502014-03-13 17:36:52 +0100953std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
954{
955 std::vector<std::string> res;
956 size_t idx = 0, idx_last = 0;
957
958 while(idx < str.size())
959 {
960 idx = str.find_first_of(delimiter, idx_last);
961 if(idx == std::string::npos)
962 idx = str.size();
963
964 if(idx-idx_last != 0 || !removeEmpty)
965 res.push_back(str.substr(idx_last, idx-idx_last));
966
967 idx_last = idx + delimiter.size();
968 }
969
970 return res;
971}
972
Vojtech Bocek03fd6c52014-03-13 18:46:34 +0100973bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
974{
975 std::vector<std::string> parts = Split_String(path, "/");
976 std::string cur_path;
977 struct stat info;
978 for(size_t i = 0; i < parts.size(); ++i)
979 {
980 cur_path += "/" + parts[i];
981 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
982 {
983 if(mkdir(cur_path.c_str(), mode) < 0)
984 return false;
985 chown(cur_path.c_str(), uid, gid);
986 }
987 }
988 return true;
989}
990
xNUTxe85f02d2014-07-18 01:30:58 +0200991int TWFunc::Set_Brightness(std::string brightness_value)
992{
993
994 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
995
996 if (brightness_file.compare("/nobrightness") != 0) {
997 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
998 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
999 int result = TWFunc::write_file(brightness_file, brightness_value);
1000 if (secondary_brightness_file != "") {
1001 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
1002 TWFunc::write_file(secondary_brightness_file, brightness_value);
1003 }
1004 return result;
1005 }
1006 return -1;
1007}
1008
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001009bool TWFunc::Toggle_MTP(bool enable) {
1010#ifdef TW_HAS_MTP
1011 static int was_enabled = false;
1012
1013 if (enable && was_enabled) {
1014 if (!PartitionManager.Enable_MTP())
1015 PartitionManager.Disable_MTP();
1016 } else {
1017 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1018 PartitionManager.Disable_MTP();
1019 usleep(500);
1020 }
1021 return was_enabled;
1022#else
1023 return false;
1024#endif
1025}
1026
Tom Hite5a926722014-09-15 01:31:03 +00001027void TWFunc::SetPerformanceMode(bool mode) {
1028 if (mode) {
1029 property_set("recovery.perf.mode", "1");
1030 } else {
1031 property_set("recovery.perf.mode", "0");
1032 }
1033 // Some time for events to catch up to init handlers
1034 usleep(500000);
1035}
1036
Jenkins1710bf22014-10-02 20:22:21 -04001037std::string TWFunc::to_string(unsigned long value) {
1038 std::ostringstream os;
1039 os << value;
1040 return os.str();
1041}
1042
Ethan Yonker9132d912015-02-02 10:32:49 -06001043void TWFunc::Disable_Stock_Recovery_Replace(void) {
1044 if (PartitionManager.Mount_By_Path("/system", false)) {
1045 // Disable flashing of stock recovery
1046 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1047 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
1048 gui_print("Renamed stock recovery file in /system to prevent\nthe stock ROM from replacing TWRP.\n");
1049 sync();
1050 }
1051 PartitionManager.UnMount_By_Path("/system", false);
1052 }
1053}
1054
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001055#endif // ndef BUILD_TWRPTAR_MAIN