blob: 1c633e7e493fed228ead143eea06849acb7a303b [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 Yonker472f5062016-02-25 13:47:30 -060041#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060042#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040043#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060044#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040045#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000046#include "bootloader.h"
Tom Hite5a926722014-09-15 01:31:03 +000047#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050048#include "cutils/android_reboot.h"
49#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060050#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
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)) {
Dees_Troy29a06352013-08-24 12:06:47 +000068 if (fgets(buffer, 128, exec) != 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) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100125 if (WIFSIGNALED(*status)) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500126 gui_msg(Msg(msg::kError, "pid_signal={1} process ended with signal: {2}")(Child_Name)(WTERMSIG(*status))); // Seg fault or some other non-graceful termination
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600127 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100128 } else if (WEXITSTATUS(*status) == 0) {
129 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
130 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500131 gui_msg(Msg(msg::kError, "pid_error={1} process ended with ERROR: {2}")(Child_Name)(WEXITSTATUS(*status))); // Graceful exit, but there was an error
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600132 return -1;
133 }
134 } else { // no PID returned
135 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200136 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600137 else {
that2252d242015-04-03 22:33:04 +0200138 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600139 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) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500211 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500212 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600213 return -1;
214 }
215 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
216 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500217 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600218 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500219 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600220 return -1;
221 }
222 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
223 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
224 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500225 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600226 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);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500232 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600233 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);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500239 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600240 return 0;
241 }
242 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500243 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600244 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500245 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600246 free(buffer_out);
247 return 1; // Decrypted successfully
248 }
249 ptr = buffer_out;
250 firstbyte = *ptr & 0xff;
251 ptr++;
252 secondbyte = *ptr & 0xff;
253 if (firstbyte == 0x1f && secondbyte == 0x8b) {
254 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
255 free(buffer_out);
256 return 3; // Compressed
257 }
258 if (out_len >= 262) {
259 ptr = buffer_out + 257;
260 if (strncmp((char*)ptr, "ustar", 5) == 0) {
261 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
262 free(buffer_out);
263 return 2; // Tar
264 }
265 }
266 free(buffer_out);
267 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
268 return 1; // Decrypted successfully
269#else
270 LOGERR("Encrypted backup support not included.\n");
271 return -1;
272#endif
273}
274
Ethan Yonker472f5062016-02-25 13:47:30 -0600275unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600276 struct stat st;
277
278 if (stat(Path.c_str(), &st) != 0)
279 return 0;
280 return st.st_size;
281}
282
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100283std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
284{
285 std::string res;
286 size_t last_idx = 0, idx = 0;
287
288 while(last_idx != std::string::npos)
289 {
290 if(last_idx != 0)
291 res += '/';
292
293 idx = path.find_first_of('/', last_idx);
294 if(idx == std::string::npos) {
295 res += path.substr(last_idx, idx);
296 break;
297 }
298
299 res += path.substr(last_idx, idx-last_idx);
300 last_idx = path.find_first_not_of('/', idx);
301 }
302
303 if(leaveLast)
304 res += '/';
305 return res;
306}
307
Matt Mower2416a502016-04-12 19:54:46 -0500308void TWFunc::Strip_Quotes(char* &str) {
309 if (strlen(str) > 0 && str[0] == '\"')
310 str++;
311 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
312 str[strlen(str)-1] = 0;
313}
314
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500315vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
316 vector<string> res;
317
318 if (in.empty() || del == '\0')
319 return res;
320
321 string field;
322 istringstream f(in);
323 if (del == '\n') {
324 while(getline(f, field)) {
325 if (field.empty() && skip_empty)
326 continue;
327 res.push_back(field);
328 }
329 } else {
330 while(getline(f, field, del)) {
331 if (field.empty() && skip_empty)
332 continue;
333 res.push_back(field);
334 }
335 }
336 return res;
337}
338
Ethan Yonker472f5062016-02-25 13:47:30 -0600339timespec TWFunc::timespec_diff(timespec& start, timespec& end)
340{
341 timespec temp;
342 if ((end.tv_nsec-start.tv_nsec)<0) {
343 temp.tv_sec = end.tv_sec-start.tv_sec-1;
344 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
345 } else {
346 temp.tv_sec = end.tv_sec-start.tv_sec;
347 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
348 }
349 return temp;
350}
351
352int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
353{
354 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
355 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
356}
357
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600358#ifndef BUILD_TWRPTAR_MAIN
359
Dees_Troy38bd7602012-09-14 13:33:53 -0400360// Returns "/path" from a full /path/to/file.name
361string TWFunc::Get_Root_Path(string Path) {
362 string Local_Path = Path;
363
364 // Make sure that we have a leading slash
365 if (Local_Path.substr(0, 1) != "/")
366 Local_Path = "/" + Local_Path;
367
368 // Trim the path to get the root path only
369 size_t position = Local_Path.find("/", 2);
370 if (position != string::npos) {
371 Local_Path.resize(position);
372 }
373 return Local_Path;
374}
375
376void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400377 int need_libs = 0;
378
379 if (!PartitionManager.Mount_By_Path("/system", true))
380 return;
381
382 if (!PartitionManager.Mount_By_Path("/data", true))
383 return;
384
Ethan Yonker74db1572015-10-28 12:44:49 -0500385 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000386 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400387 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500388 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000389 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400390 need_libs = 1;
391 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500392 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400393 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500394 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000395 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400396 need_libs = 1;
397 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500398 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400399 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500400 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000401 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
402 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
403 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
404 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400405 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500406 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400407 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500408 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000409 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400410 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500411 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400412}
413
414void TWFunc::htc_dumlock_restore_original_boot(void) {
415 if (!PartitionManager.Mount_By_Path("/sdcard", true))
416 return;
417
Ethan Yonker74db1572015-10-28 12:44:49 -0500418 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200419 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500420 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400421}
422
423void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
424 if (!PartitionManager.Mount_By_Path("/sdcard", true))
425 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500426 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200427 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500428 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400429}
Dees_Troy43d8b002012-09-17 16:00:01 -0400430
431int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100432 std::vector<std::string> parts = Split_String(Path, "/", true);
433 std::string cur_path;
434 for (size_t i = 0; i < parts.size(); ++i) {
435 cur_path += "/" + parts[i];
436 if (!TWFunc::Path_Exists(cur_path)) {
437 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600438 gui_msg(Msg(msg::kError, "create_folder_strerr=Can not create '{1}' folder ({2}).")(cur_path)(strerror(errno)));
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600439 return false;
440 } else {
thatf1408b32016-01-03 11:09:15 +0100441 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600442 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400443 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400444 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400445 return true;
446}
447
Dees_Troyb46a6842012-09-25 11:06:46 -0400448void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
449 string Display_Text;
450
451 DataManager::GetValue(Read_Value, Display_Text);
452 if (Display_Text.empty())
453 Display_Text = Default_Text;
454
455 DataManager::SetValue("tw_operation", Display_Text);
456 DataManager::SetValue("tw_partition", "");
457}
458
459void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
460 string Display_Text;
461
462 DataManager::GetValue(Read_Value, Display_Text);
463 if (Display_Text.empty())
464 Display_Text = Default_Text;
465
466 DataManager::SetValue("tw_operation", Display_Text);
467 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400468}
469
Dees_Troy2673cec2013-04-02 20:22:16 +0000470void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000471 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000472 FILE *destination_log = fopen(Destination.c_str(), "a");
473 if (destination_log == NULL) {
474 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600475 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000476 FILE *source_log = fopen(Source.c_str(), "r");
477 if (source_log != NULL) {
478 fseek(source_log, Log_Offset, SEEK_SET);
479 char buffer[4096];
480 while (fgets(buffer, sizeof(buffer), source_log))
481 fputs(buffer, destination_log); // Buffered write of log file
482 Log_Offset = ftell(source_log);
483 fflush(source_log);
484 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600485 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000486 fflush(destination_log);
487 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600488 }
Dees_Troya58bead2012-09-27 09:49:29 -0400489}
490
Dees_Troy2673cec2013-04-02 20:22:16 +0000491void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500492 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000493 if (PartitionManager.Mount_By_Path("/cache", false)) {
494 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
495 LOGINFO("Recreating /cache/recovery folder.\n");
496 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
497 LOGINFO("Unable to create /cache/recovery folder.\n");
498 }
499 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
500 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
501 chown("/cache/recovery/log", 1000, 1000);
502 chmod("/cache/recovery/log", 0600);
503 chmod("/cache/recovery/last_log", 0640);
504 } else {
505 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
506 }
Dees_Troya58bead2012-09-27 09:49:29 -0400507
Dees_Troy2673cec2013-04-02 20:22:16 +0000508 // Reset bootloader message
509 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
510 if (Part != NULL) {
511 struct bootloader_message boot;
512 memset(&boot, 0, sizeof(boot));
that4e0e3fc2015-04-13 19:52:49 +0200513 if (set_bootloader_message(&boot) != 0)
514 LOGERR("Unable to set bootloader message.\n");
Dees_Troy2673cec2013-04-02 20:22:16 +0000515 }
Dees_Troya58bead2012-09-27 09:49:29 -0400516
Dees Troy9d7fdf52013-09-19 20:49:25 +0000517 if (PartitionManager.Mount_By_Path("/cache", true)) {
518 if (unlink("/cache/recovery/command") && errno != ENOENT) {
519 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
520 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500521 }
Dees_Troya58bead2012-09-27 09:49:29 -0400522
Dees_Troy2673cec2013-04-02 20:22:16 +0000523 sync();
524}
525
526void TWFunc::Update_Intent_File(string Intent) {
527 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
528 TWFunc::write_file("/cache/recovery/intent", Intent);
529 }
Dees_Troya58bead2012-09-27 09:49:29 -0400530}
531
532// reboot: Reboot the system. Return -1 on error, no return on success
533int TWFunc::tw_reboot(RebootCommand command)
534{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500535 DataManager::Flush();
536 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400537 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600538 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400539
Dees_Troy2673cec2013-04-02 20:22:16 +0000540 switch (command) {
541 case rb_current:
542 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000543 Update_Intent_File("s");
544 sync();
545 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500546#ifdef ANDROID_RB_PROPERTY
547 return property_set(ANDROID_RB_PROPERTY, "reboot,");
548#elif defined(ANDROID_RB_RESTART)
549 return android_reboot(ANDROID_RB_RESTART, 0, 0);
550#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000551 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500552#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000553 case rb_recovery:
554 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600555#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500556 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600557#else
558 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
559#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000560 case rb_bootloader:
561 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600562#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500563 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600564#else
565 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
566#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000567 case rb_poweroff:
568 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500569#ifdef ANDROID_RB_PROPERTY
570 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
571#elif defined(ANDROID_RB_POWEROFF)
572 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
573#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000574 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500575#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000576 case rb_download:
577 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600578#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500579 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600580#else
581 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
582#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000583 default:
584 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600585 }
586 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400587}
588
589void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
590{
591 // Check for and run startup script if script exists
592 struct stat st;
593 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500594 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500595 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200596 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500597 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400598 }
Dees_Troy3477d712012-09-27 15:44:01 -0400599}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500600
601int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000602 DIR *d = opendir(path.c_str());
603 int r = 0;
604 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500605
Dees_Troyce675462013-01-09 19:48:21 +0000606 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500607 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000608 return -1;
609 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500610
Dees_Troyce675462013-01-09 19:48:21 +0000611 if (d) {
612 struct dirent *p;
613 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000614 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
615 continue;
616 new_path = path + "/";
617 new_path.append(p->d_name);
618 if (p->d_type == DT_DIR) {
619 r = removeDir(new_path, true);
620 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500621 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500622 r = rmdir(new_path.c_str());
623 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000624 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500625 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500626 } 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 +0000627 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000628 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000629 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000630 }
Dees_Troyce675462013-01-09 19:48:21 +0000631 }
632 }
633 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500634
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500635 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500636 if (skipParent)
637 return 0;
638 else
639 r = rmdir(path.c_str());
640 }
Dees_Troyce675462013-01-09 19:48:21 +0000641 }
642 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500643}
644
645int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000646 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500647 ifstream srcfile(src.c_str(), ios::binary);
648 ofstream dstfile(dst.c_str(), ios::binary);
649 dstfile << srcfile.rdbuf();
650 srcfile.close();
651 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500652 if (chmod(dst.c_str(), mode) != 0)
653 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500654 return 0;
655}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000656
657unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
658 struct stat st;
659
660 stat(Path.c_str(), &st);
661 if (st.st_mode & S_IFDIR)
662 return DT_DIR;
663 else if (st.st_mode & S_IFBLK)
664 return DT_BLK;
665 else if (st.st_mode & S_IFCHR)
666 return DT_CHR;
667 else if (st.st_mode & S_IFIFO)
668 return DT_FIFO;
669 else if (st.st_mode & S_IFLNK)
670 return DT_LNK;
671 else if (st.st_mode & S_IFREG)
672 return DT_REG;
673 else if (st.st_mode & S_IFSOCK)
674 return DT_SOCK;
675 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000676}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500677
678int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200679 ifstream file;
680 file.open(fn.c_str(), ios::in);
681
682 if (file.is_open()) {
683 file >> results;
684 file.close();
685 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500686 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200687
688 LOGINFO("Cannot find file %s\n", fn.c_str());
689 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500690}
691
692int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500693 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500694 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500695 file.open(fn.c_str(), ios::in);
696 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500697 while (getline(file, line))
698 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500699 file.close();
700 return 0;
701 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000702 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500703 return -1;
704}
705
xNUTxe85f02d2014-07-18 01:30:58 +0200706int TWFunc::read_file(string fn, uint64_t& results) {
707 ifstream file;
708 file.open(fn.c_str(), ios::in);
709
710 if (file.is_open()) {
711 file >> results;
712 file.close();
713 return 0;
714 }
715
716 LOGINFO("Cannot find file %s\n", fn.c_str());
717 return -1;
718}
719
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500720int TWFunc::write_file(string fn, string& line) {
721 FILE *file;
722 file = fopen(fn.c_str(), "w");
723 if (file != NULL) {
724 fwrite(line.c_str(), line.size(), 1, file);
725 fclose(file);
726 return 0;
727 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000728 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500729 return -1;
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) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500747 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000748 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();
bigbiff74a6d0d2015-02-14 20:49:44 -0500817 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600818 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 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500827 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonkerb5557892014-02-07 21:43:20 -0600828 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600829 if (PartitionManager.Check_Backup_Name(false) != 0) {
830 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
831 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
832 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200833}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100834
835void TWFunc::Fixup_Time_On_Boot()
836{
837#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +0200838
839 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
840
841 struct timeval tv;
842 uint64_t offset = 0;
843 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
844
845 if (TWFunc::read_file(sepoch, offset) == 0) {
846
847 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
848
849 tv.tv_sec = offset;
850 tv.tv_usec = 0;
851 settimeofday(&tv, NULL);
852
853 gettimeofday(&tv, NULL);
854
855 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
856
857 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
858 return;
859
860 }
861
862 } else {
863
864 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
865
866 }
867
Ethan Yonker9132d912015-02-02 10:32:49 -0600868 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200869
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100870 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
871 // They never set it, it just ticks forward from 1970-01-01 00:00,
872 // and then they have files /data/system/time/ats_* with 64bit offset
873 // in miliseconds which, when added to the RTC, gives the correct time.
874 // So, the time is: (offset_from_ats + value_from_RTC)
875 // There are multiple ats files, they are for different systems? Bases?
876 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
877 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
878
879 static const char *paths[] = { "/data/system/time/", "/data/time/" };
880
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100881 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200882 DIR *d;
883 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100884 struct dirent *dt;
885 std::string ats_path;
886
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100887 if(!PartitionManager.Mount_By_Path("/data", false))
888 return;
889
890 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
891 // - it is the one for ATS_TOD (time of day?).
892 // However, I never saw a device where the offset differs between ats files.
893 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
894 {
895 DIR *d = opendir(paths[i]);
896 if(!d)
897 continue;
898
899 while((dt = readdir(d)))
900 {
901 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
902 continue;
903
904 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
905 ats_path = std::string(paths[i]).append(dt->d_name);
906 }
907
908 closedir(d);
909 }
910
911 if(ats_path.empty())
912 {
xNUTxe85f02d2014-07-18 01:30:58 +0200913 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100914 return;
915 }
916
917 f = fopen(ats_path.c_str(), "r");
918 if(!f)
919 {
Dees Troy3e254b92014-03-06 20:24:54 +0000920 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100921 return;
922 }
923
924 if(fread(&offset, sizeof(offset), 1, f) != 1)
925 {
Dees Troy3e254b92014-03-06 20:24:54 +0000926 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100927 fclose(f);
928 return;
929 }
930 fclose(f);
931
932 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
933
934 gettimeofday(&tv, NULL);
935
936 tv.tv_sec += offset/1000;
937 tv.tv_usec += (offset%1000)*1000;
938
939 while(tv.tv_usec >= 1000000)
940 {
941 ++tv.tv_sec;
942 tv.tv_usec -= 1000000;
943 }
944
945 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +0200946
947 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
948
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100949#endif
950}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600951
Vojtech Bocek0b7fe502014-03-13 17:36:52 +0100952std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
953{
954 std::vector<std::string> res;
955 size_t idx = 0, idx_last = 0;
956
957 while(idx < str.size())
958 {
959 idx = str.find_first_of(delimiter, idx_last);
960 if(idx == std::string::npos)
961 idx = str.size();
962
963 if(idx-idx_last != 0 || !removeEmpty)
964 res.push_back(str.substr(idx_last, idx-idx_last));
965
966 idx_last = idx + delimiter.size();
967 }
968
969 return res;
970}
971
Vojtech Bocek03fd6c52014-03-13 18:46:34 +0100972bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
973{
974 std::vector<std::string> parts = Split_String(path, "/");
975 std::string cur_path;
976 struct stat info;
977 for(size_t i = 0; i < parts.size(); ++i)
978 {
979 cur_path += "/" + parts[i];
980 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
981 {
982 if(mkdir(cur_path.c_str(), mode) < 0)
983 return false;
984 chown(cur_path.c_str(), uid, gid);
985 }
986 }
987 return true;
988}
989
xNUTxe85f02d2014-07-18 01:30:58 +0200990int TWFunc::Set_Brightness(std::string brightness_value)
991{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900992 int result = -1;
993 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +0200994
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900995 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +0200996 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900997 result = TWFunc::write_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
998 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
999 if (!secondary_brightness_file.empty()) {
1000 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
xNUTxe85f02d2014-07-18 01:30:58 +02001001 TWFunc::write_file(secondary_brightness_file, brightness_value);
1002 }
xNUTxe85f02d2014-07-18 01:30:58 +02001003 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001004 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001005}
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");
Ethan Yonker74db1572015-10-28 12:44:49 -05001046 gui_msg("rename_stock=Renamed stock recovery file in /system to prevent the stock ROM from replacing TWRP.");
Ethan Yonker9132d912015-02-02 10:32:49 -06001047 sync();
1048 }
1049 PartitionManager.UnMount_By_Path("/system", false);
1050 }
1051}
1052
Ethan Yonker483e9f42016-01-11 22:21:18 -06001053unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1054 unsigned long block_device_size;
1055 int ret = 0;
1056
1057 int fd = open(block_device, O_RDONLY);
1058 if (fd < 0) {
1059 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1060 } else {
1061 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1062 close(fd);
1063 if (ret) {
1064 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1065 } else {
1066 return (unsigned long long)(block_device_size) * 512LLU;
1067 }
1068 }
1069 return 0;
1070}
1071
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001072#endif // ndef BUILD_TWRPTAR_MAIN