blob: 72674ae6914e67e1fdee28848e64fd262fab479b [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
Ethan Yonkerf1179622016-08-25 15:32:21 -050054#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040055
Dees_Troyb05ddee2013-01-28 20:24:50 +000056extern "C" {
57 #include "libcrecovery/common.h"
58}
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
bigbiffce8f83c2015-12-12 18:30:21 -0500154Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600155 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)
bigbiffce8f83c2015-12-12 18:30:21 -0500167 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600168 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500169 return ENCRYPTED;
170 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600171}
172
173int TWFunc::Try_Decrypting_File(string fn, string password) {
174#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
175 OAES_CTX * ctx = NULL;
176 uint8_t _key_data[32] = "";
177 FILE *f;
178 uint8_t buffer[4096];
179 uint8_t *buffer_out = NULL;
180 uint8_t *ptr = NULL;
181 size_t read_len = 0, out_len = 0;
182 int firstbyte = 0, secondbyte = 0, key_len;
183 size_t _j = 0;
184 size_t _key_data_len = 0;
185
186 // mostly kanged from OpenAES oaes.c
187 for( _j = 0; _j < 32; _j++ )
188 _key_data[_j] = _j + 1;
189 _key_data_len = password.size();
190 if( 16 >= _key_data_len )
191 _key_data_len = 16;
192 else if( 24 >= _key_data_len )
193 _key_data_len = 24;
194 else
195 _key_data_len = 32;
196 memcpy(_key_data, password.c_str(), password.size());
197
198 ctx = oaes_alloc();
199 if (ctx == NULL) {
200 LOGERR("Failed to allocate OAES\n");
201 return -1;
202 }
203
204 oaes_key_import_data(ctx, _key_data, _key_data_len);
205
206 f = fopen(fn.c_str(), "rb");
207 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500208 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500209 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600210 return -1;
211 }
212 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
213 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500214 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600215 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500216 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600217 return -1;
218 }
219 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
220 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
221 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500222 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600223 return -1;
224 }
225 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
226 if (buffer_out == NULL) {
227 LOGERR("Failed to allocate output buffer for try decrypt.\n");
228 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500229 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600230 return -1;
231 }
232 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
233 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
234 fclose(f);
235 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500236 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600237 return 0;
238 }
239 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500240 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600241 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500242 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600243 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
Ethan Yonker472f5062016-02-25 13:47:30 -0600272unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600273 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
Matt Mower2416a502016-04-12 19:54:46 -0500305void TWFunc::Strip_Quotes(char* &str) {
306 if (strlen(str) > 0 && str[0] == '\"')
307 str++;
308 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
309 str[strlen(str)-1] = 0;
310}
311
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500312vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
313 vector<string> res;
314
315 if (in.empty() || del == '\0')
316 return res;
317
318 string field;
319 istringstream f(in);
320 if (del == '\n') {
321 while(getline(f, field)) {
322 if (field.empty() && skip_empty)
323 continue;
324 res.push_back(field);
325 }
326 } else {
327 while(getline(f, field, del)) {
328 if (field.empty() && skip_empty)
329 continue;
330 res.push_back(field);
331 }
332 }
333 return res;
334}
335
Ethan Yonker472f5062016-02-25 13:47:30 -0600336timespec TWFunc::timespec_diff(timespec& start, timespec& end)
337{
338 timespec temp;
339 if ((end.tv_nsec-start.tv_nsec)<0) {
340 temp.tv_sec = end.tv_sec-start.tv_sec-1;
341 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
342 } else {
343 temp.tv_sec = end.tv_sec-start.tv_sec;
344 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
345 }
346 return temp;
347}
348
349int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
350{
351 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
352 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
353}
354
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600355#ifndef BUILD_TWRPTAR_MAIN
356
Dees_Troy38bd7602012-09-14 13:33:53 -0400357// Returns "/path" from a full /path/to/file.name
358string TWFunc::Get_Root_Path(string Path) {
359 string Local_Path = Path;
360
361 // Make sure that we have a leading slash
362 if (Local_Path.substr(0, 1) != "/")
363 Local_Path = "/" + Local_Path;
364
365 // Trim the path to get the root path only
366 size_t position = Local_Path.find("/", 2);
367 if (position != string::npos) {
368 Local_Path.resize(position);
369 }
370 return Local_Path;
371}
372
373void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400374 int need_libs = 0;
375
376 if (!PartitionManager.Mount_By_Path("/system", true))
377 return;
378
379 if (!PartitionManager.Mount_By_Path("/data", true))
380 return;
381
Ethan Yonker74db1572015-10-28 12:44:49 -0500382 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000383 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400384 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500385 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000386 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400387 need_libs = 1;
388 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500389 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400390 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500391 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000392 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400393 need_libs = 1;
394 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500395 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400396 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500397 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000398 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
399 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
400 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
401 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400402 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500403 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400404 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500405 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000406 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400407 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500408 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400409}
410
411void TWFunc::htc_dumlock_restore_original_boot(void) {
412 if (!PartitionManager.Mount_By_Path("/sdcard", true))
413 return;
414
Ethan Yonker74db1572015-10-28 12:44:49 -0500415 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200416 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500417 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400418}
419
420void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
421 if (!PartitionManager.Mount_By_Path("/sdcard", true))
422 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500423 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200424 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500425 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400426}
Dees_Troy43d8b002012-09-17 16:00:01 -0400427
428int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100429 std::vector<std::string> parts = Split_String(Path, "/", true);
430 std::string cur_path;
431 for (size_t i = 0; i < parts.size(); ++i) {
432 cur_path += "/" + parts[i];
433 if (!TWFunc::Path_Exists(cur_path)) {
434 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600435 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 -0600436 return false;
437 } else {
thatf1408b32016-01-03 11:09:15 +0100438 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600439 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400440 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400441 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400442 return true;
443}
444
Dees_Troyb46a6842012-09-25 11:06:46 -0400445void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
446 string Display_Text;
447
448 DataManager::GetValue(Read_Value, Display_Text);
449 if (Display_Text.empty())
450 Display_Text = Default_Text;
451
452 DataManager::SetValue("tw_operation", Display_Text);
453 DataManager::SetValue("tw_partition", "");
454}
455
456void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
457 string Display_Text;
458
459 DataManager::GetValue(Read_Value, Display_Text);
460 if (Display_Text.empty())
461 Display_Text = Default_Text;
462
463 DataManager::SetValue("tw_operation", Display_Text);
464 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400465}
466
Dees_Troy2673cec2013-04-02 20:22:16 +0000467void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000468 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000469 FILE *destination_log = fopen(Destination.c_str(), "a");
470 if (destination_log == NULL) {
471 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600472 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000473 FILE *source_log = fopen(Source.c_str(), "r");
474 if (source_log != NULL) {
475 fseek(source_log, Log_Offset, SEEK_SET);
476 char buffer[4096];
477 while (fgets(buffer, sizeof(buffer), source_log))
478 fputs(buffer, destination_log); // Buffered write of log file
479 Log_Offset = ftell(source_log);
480 fflush(source_log);
481 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600482 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000483 fflush(destination_log);
484 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600485 }
Dees_Troya58bead2012-09-27 09:49:29 -0400486}
487
Dees_Troy2673cec2013-04-02 20:22:16 +0000488void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500489 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000490 if (PartitionManager.Mount_By_Path("/cache", false)) {
491 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
492 LOGINFO("Recreating /cache/recovery folder.\n");
493 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
494 LOGINFO("Unable to create /cache/recovery folder.\n");
495 }
496 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
497 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
498 chown("/cache/recovery/log", 1000, 1000);
499 chmod("/cache/recovery/log", 0600);
500 chmod("/cache/recovery/last_log", 0640);
501 } else {
502 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
503 }
Dees_Troya58bead2012-09-27 09:49:29 -0400504
Dees_Troy2673cec2013-04-02 20:22:16 +0000505 // Reset bootloader message
506 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
507 if (Part != NULL) {
Ethan Yonkerb5236502016-11-19 22:24:59 -0600508 string err;
509 if (!clear_bootloader_message(&err)) {
510 if (err == "no misc device set") {
511 LOGINFO("%s\n", err.c_str());
512 } else {
513 LOGERR("%s\n", err.c_str());
514 }
515 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000516 }
Dees_Troya58bead2012-09-27 09:49:29 -0400517
Dees Troy9d7fdf52013-09-19 20:49:25 +0000518 if (PartitionManager.Mount_By_Path("/cache", true)) {
519 if (unlink("/cache/recovery/command") && errno != ENOENT) {
520 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
521 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500522 }
Dees_Troya58bead2012-09-27 09:49:29 -0400523
Dees_Troy2673cec2013-04-02 20:22:16 +0000524 sync();
525}
526
527void TWFunc::Update_Intent_File(string Intent) {
528 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
529 TWFunc::write_file("/cache/recovery/intent", Intent);
530 }
Dees_Troya58bead2012-09-27 09:49:29 -0400531}
532
533// reboot: Reboot the system. Return -1 on error, no return on success
534int TWFunc::tw_reboot(RebootCommand command)
535{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500536 DataManager::Flush();
537 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400538 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600539 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400540
Dees_Troy2673cec2013-04-02 20:22:16 +0000541 switch (command) {
542 case rb_current:
543 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000544 Update_Intent_File("s");
545 sync();
546 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500547#ifdef ANDROID_RB_PROPERTY
548 return property_set(ANDROID_RB_PROPERTY, "reboot,");
549#elif defined(ANDROID_RB_RESTART)
550 return android_reboot(ANDROID_RB_RESTART, 0, 0);
551#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000552 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500553#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000554 case rb_recovery:
555 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600556#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500557 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600558#else
559 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
560#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000561 case rb_bootloader:
562 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600563#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500564 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600565#else
566 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
567#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000568 case rb_poweroff:
569 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500570#ifdef ANDROID_RB_PROPERTY
571 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
572#elif defined(ANDROID_RB_POWEROFF)
573 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
574#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000575 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500576#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000577 case rb_download:
578 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600579#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500580 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600581#else
582 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
583#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000584 default:
585 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600586 }
587 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400588}
589
590void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
591{
592 // Check for and run startup script if script exists
593 struct stat st;
594 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500595 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500596 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200597 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500598 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400599 }
Dees_Troy3477d712012-09-27 15:44:01 -0400600}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500601
602int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000603 DIR *d = opendir(path.c_str());
604 int r = 0;
605 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500606
Dees_Troyce675462013-01-09 19:48:21 +0000607 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500608 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000609 return -1;
610 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500611
Dees_Troyce675462013-01-09 19:48:21 +0000612 if (d) {
613 struct dirent *p;
614 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000615 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
616 continue;
617 new_path = path + "/";
618 new_path.append(p->d_name);
619 if (p->d_type == DT_DIR) {
620 r = removeDir(new_path, true);
621 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500622 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500623 r = rmdir(new_path.c_str());
624 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000625 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500626 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500627 } 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 +0000628 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000629 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000630 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000631 }
Dees_Troyce675462013-01-09 19:48:21 +0000632 }
633 }
634 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500635
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500636 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500637 if (skipParent)
638 return 0;
639 else
640 r = rmdir(path.c_str());
641 }
Dees_Troyce675462013-01-09 19:48:21 +0000642 }
643 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500644}
645
646int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000647 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500648 ifstream srcfile(src.c_str(), ios::binary);
649 ofstream dstfile(dst.c_str(), ios::binary);
650 dstfile << srcfile.rdbuf();
651 srcfile.close();
652 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500653 if (chmod(dst.c_str(), mode) != 0)
654 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500655 return 0;
656}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000657
658unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
659 struct stat st;
660
661 stat(Path.c_str(), &st);
662 if (st.st_mode & S_IFDIR)
663 return DT_DIR;
664 else if (st.st_mode & S_IFBLK)
665 return DT_BLK;
666 else if (st.st_mode & S_IFCHR)
667 return DT_CHR;
668 else if (st.st_mode & S_IFIFO)
669 return DT_FIFO;
670 else if (st.st_mode & S_IFLNK)
671 return DT_LNK;
672 else if (st.st_mode & S_IFREG)
673 return DT_REG;
674 else if (st.st_mode & S_IFSOCK)
675 return DT_SOCK;
676 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000677}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500678
679int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200680 ifstream file;
681 file.open(fn.c_str(), ios::in);
682
683 if (file.is_open()) {
684 file >> results;
685 file.close();
686 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500687 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200688
689 LOGINFO("Cannot find file %s\n", fn.c_str());
690 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500691}
692
693int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500694 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500695 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500696 file.open(fn.c_str(), ios::in);
697 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500698 while (getline(file, line))
699 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500700 file.close();
701 return 0;
702 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000703 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500704 return -1;
705}
706
xNUTxe85f02d2014-07-18 01:30:58 +0200707int TWFunc::read_file(string fn, uint64_t& results) {
708 ifstream file;
709 file.open(fn.c_str(), ios::in);
710
711 if (file.is_open()) {
712 file >> results;
713 file.close();
714 return 0;
715 }
716
717 LOGINFO("Cannot find file %s\n", fn.c_str());
718 return -1;
719}
720
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500721int TWFunc::write_file(string fn, string& line) {
722 FILE *file;
723 file = fopen(fn.c_str(), "w");
724 if (file != NULL) {
725 fwrite(line.c_str(), line.size(), 1, file);
726 fclose(file);
727 return 0;
728 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000729 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500730 return -1;
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) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500748 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000749 return false;
750 }
751
752 struct dirent* de;
753 while ((de = readdir(d)) != NULL) {
754 Filename = Restore_Path;
755 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500756 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000757 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{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900993 int result = -1;
994 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +0200995
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900996 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +0200997 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +0900998 result = TWFunc::write_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
999 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1000 if (!secondary_brightness_file.empty()) {
1001 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
xNUTxe85f02d2014-07-18 01:30:58 +02001002 TWFunc::write_file(secondary_brightness_file, brightness_value);
1003 }
xNUTxe85f02d2014-07-18 01:30:58 +02001004 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001005 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001006}
1007
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001008bool TWFunc::Toggle_MTP(bool enable) {
1009#ifdef TW_HAS_MTP
1010 static int was_enabled = false;
1011
1012 if (enable && was_enabled) {
1013 if (!PartitionManager.Enable_MTP())
1014 PartitionManager.Disable_MTP();
1015 } else {
1016 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1017 PartitionManager.Disable_MTP();
1018 usleep(500);
1019 }
1020 return was_enabled;
1021#else
1022 return false;
1023#endif
1024}
1025
Tom Hite5a926722014-09-15 01:31:03 +00001026void TWFunc::SetPerformanceMode(bool mode) {
1027 if (mode) {
1028 property_set("recovery.perf.mode", "1");
1029 } else {
1030 property_set("recovery.perf.mode", "0");
1031 }
1032 // Some time for events to catch up to init handlers
1033 usleep(500000);
1034}
1035
Jenkins1710bf22014-10-02 20:22:21 -04001036std::string TWFunc::to_string(unsigned long value) {
1037 std::ostringstream os;
1038 os << value;
1039 return os.str();
1040}
1041
Ethan Yonker9132d912015-02-02 10:32:49 -06001042void TWFunc::Disable_Stock_Recovery_Replace(void) {
1043 if (PartitionManager.Mount_By_Path("/system", false)) {
1044 // Disable flashing of stock recovery
1045 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1046 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001047 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 -06001048 sync();
1049 }
1050 PartitionManager.UnMount_By_Path("/system", false);
1051 }
1052}
1053
Ethan Yonker483e9f42016-01-11 22:21:18 -06001054unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1055 unsigned long block_device_size;
1056 int ret = 0;
1057
1058 int fd = open(block_device, O_RDONLY);
1059 if (fd < 0) {
1060 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1061 } else {
1062 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1063 close(fd);
1064 if (ret) {
1065 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1066 } else {
1067 return (unsigned long long)(block_device_size) * 512LLU;
1068 }
1069 }
1070 return 0;
1071}
1072
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001073void TWFunc::copy_kernel_log(string curr_storage) {
1074 std::string dmesgDst = curr_storage + "/dmesg.log";
1075 std::string dmesgCmd = "/sbin/dmesg";
1076
1077 std::string result;
1078 Exec_Cmd(dmesgCmd, result);
1079 write_file(dmesgDst, result);
1080 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1081 tw_set_default_metadata(dmesgDst.c_str());
1082}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001083#endif // ndef BUILD_TWRPTAR_MAIN