blob: 40205c94390268226354e3435d6d70e2d47cc9b3 [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>
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -040038#include <cctype>
bigbiff74a6d0d2015-02-14 20:49:44 -050039#include <algorithm>
Dees_Troy38bd7602012-09-14 13:33:53 -040040#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000041#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060042#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060043#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040044#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060045#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040046#include "variables.h"
Ethan Yonker8373cfe2017-09-08 06:50:54 -050047#include "bootloader_message_twrp/include/bootloader_message_twrp/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000048#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050049#include "cutils/android_reboot.h"
50#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060051#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000052#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
53 #include "openaes/inc/oaes_lib.h"
54#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050055#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040056
Dees_Troyb05ddee2013-01-28 20:24:50 +000057extern "C" {
58 #include "libcrecovery/common.h"
59}
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;
Matt Mowera8a89d12016-12-30 18:10:37 -060068 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000069 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050070 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000071 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050072 }
Dees_Troy29a06352013-08-24 12:06:47 +000073 ret = __pclose(exec);
74 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050075}
76
Vojtech Bocek05534202013-09-11 08:11:56 +020077int TWFunc::Exec_Cmd(const string& cmd) {
78 pid_t pid;
79 int status;
80 switch(pid = fork())
81 {
82 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050083 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020084 return -1;
85 case 0: // child
86 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
87 _exit(127);
88 break;
89 default:
90 {
91 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
92 return -1;
93 else
94 return 0;
95 }
96 }
97}
98
Dees_Troy38bd7602012-09-14 13:33:53 -040099// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600100string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400101 size_t pos = Path.find_last_of("/");
102 if (pos != string::npos) {
103 string Filename;
104 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
105 return Filename;
106 } else
107 return Path;
108}
109
110// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600111string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400112 size_t pos = Path.find_last_of("/");
113 if (pos != string::npos) {
114 string Pathonly;
115 Pathonly = Path.substr(0, pos + 1);
116 return Pathonly;
117 } else
118 return Path;
119}
120
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600121int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
122 pid_t rc_pid;
123
124 rc_pid = waitpid(pid, status, 0);
125 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100126 if (WIFSIGNALED(*status)) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500127 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 -0600128 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100129 } else if (WEXITSTATUS(*status) == 0) {
130 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
131 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500132 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 -0600133 return -1;
134 }
135 } else { // no PID returned
136 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200137 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600138 else {
that2252d242015-04-03 22:33:04 +0200139 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600140 return -1;
141 }
142 }
143 return 0;
144}
145
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600146int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
147 pid_t retpid = waitpid(pid, status, WNOHANG);
148 for (; retpid == 0 && timeout; --timeout) {
149 sleep(1);
150 retpid = waitpid(pid, status, WNOHANG);
151 }
152 if (retpid == 0 && timeout == 0) {
153 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
154 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600155 for (timeout = 5; retpid == 0 && timeout; --timeout) {
156 sleep(1);
157 retpid = waitpid(pid, status, WNOHANG);
158 }
159 if (retpid)
160 LOGINFO("Child process killed successfully\n");
161 else
162 LOGINFO("Child process took too long to kill, may be a zombie process\n");
163 return -1;
164 } else if (retpid > 0) {
165 if (WIFSIGNALED(*status)) {
166 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
167 return -1;
168 }
169 } else if (retpid < 0) { // no PID returned
170 if (errno == ECHILD)
171 LOGERR("%s no child process exist\n", Child_Name.c_str());
172 else {
173 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
174 return -1;
175 }
176 }
177 return 0;
178}
179
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600180bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600181 struct stat st;
182 if (stat(Path.c_str(), &st) != 0)
183 return false;
184 else
185 return true;
186}
187
bigbiffce8f83c2015-12-12 18:30:21 -0500188Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600189 string::size_type i = 0;
190 int firstbyte = 0, secondbyte = 0;
191 char header[3];
192
193 ifstream f;
194 f.open(fn.c_str(), ios::in | ios::binary);
195 f.get(header, 3);
196 f.close();
197 firstbyte = header[i] & 0xff;
198 secondbyte = header[++i] & 0xff;
199
200 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500201 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600202 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500203 return ENCRYPTED;
204 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600205}
206
207int TWFunc::Try_Decrypting_File(string fn, string password) {
208#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
209 OAES_CTX * ctx = NULL;
210 uint8_t _key_data[32] = "";
211 FILE *f;
212 uint8_t buffer[4096];
213 uint8_t *buffer_out = NULL;
214 uint8_t *ptr = NULL;
215 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600216 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600217 size_t _j = 0;
218 size_t _key_data_len = 0;
219
220 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600221 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600222 _key_data[_j] = _j + 1;
223 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600224 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600225 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600226 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600227 _key_data_len = 24;
228 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600229 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600230 memcpy(_key_data, password.c_str(), password.size());
231
232 ctx = oaes_alloc();
233 if (ctx == NULL) {
234 LOGERR("Failed to allocate OAES\n");
235 return -1;
236 }
237
238 oaes_key_import_data(ctx, _key_data, _key_data_len);
239
240 f = fopen(fn.c_str(), "rb");
241 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500242 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500243 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600244 return -1;
245 }
246 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
247 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500248 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600249 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500250 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600251 return -1;
252 }
253 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
254 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
255 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500256 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600257 return -1;
258 }
259 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
260 if (buffer_out == NULL) {
261 LOGERR("Failed to allocate output buffer for try decrypt.\n");
262 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500263 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600264 return -1;
265 }
266 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
267 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
268 fclose(f);
269 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500270 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600271 return 0;
272 }
273 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500274 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600275 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500276 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600277 free(buffer_out);
278 return 1; // Decrypted successfully
279 }
280 ptr = buffer_out;
281 firstbyte = *ptr & 0xff;
282 ptr++;
283 secondbyte = *ptr & 0xff;
284 if (firstbyte == 0x1f && secondbyte == 0x8b) {
285 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
286 free(buffer_out);
287 return 3; // Compressed
288 }
289 if (out_len >= 262) {
290 ptr = buffer_out + 257;
291 if (strncmp((char*)ptr, "ustar", 5) == 0) {
292 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
293 free(buffer_out);
294 return 2; // Tar
295 }
296 }
297 free(buffer_out);
298 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
299 return 1; // Decrypted successfully
300#else
301 LOGERR("Encrypted backup support not included.\n");
302 return -1;
303#endif
304}
305
Ethan Yonker472f5062016-02-25 13:47:30 -0600306unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600307 struct stat st;
308
309 if (stat(Path.c_str(), &st) != 0)
310 return 0;
311 return st.st_size;
312}
313
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100314std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
315{
316 std::string res;
317 size_t last_idx = 0, idx = 0;
318
Matt Mowera8a89d12016-12-30 18:10:37 -0600319 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100320 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600321 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100322 res += '/';
323
324 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600325 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100326 res += path.substr(last_idx, idx);
327 break;
328 }
329
330 res += path.substr(last_idx, idx-last_idx);
331 last_idx = path.find_first_not_of('/', idx);
332 }
333
Matt Mowera8a89d12016-12-30 18:10:37 -0600334 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100335 res += '/';
336 return res;
337}
338
Matt Mower2416a502016-04-12 19:54:46 -0500339void TWFunc::Strip_Quotes(char* &str) {
340 if (strlen(str) > 0 && str[0] == '\"')
341 str++;
342 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
343 str[strlen(str)-1] = 0;
344}
345
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500346vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
347 vector<string> res;
348
349 if (in.empty() || del == '\0')
350 return res;
351
352 string field;
353 istringstream f(in);
354 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600355 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500356 if (field.empty() && skip_empty)
357 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600358 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500359 }
360 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600361 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500362 if (field.empty() && skip_empty)
363 continue;
364 res.push_back(field);
365 }
366 }
367 return res;
368}
369
Ethan Yonker472f5062016-02-25 13:47:30 -0600370timespec TWFunc::timespec_diff(timespec& start, timespec& end)
371{
372 timespec temp;
373 if ((end.tv_nsec-start.tv_nsec)<0) {
374 temp.tv_sec = end.tv_sec-start.tv_sec-1;
375 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
376 } else {
377 temp.tv_sec = end.tv_sec-start.tv_sec;
378 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
379 }
380 return temp;
381}
382
383int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
384{
385 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
386 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
387}
388
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600389#ifndef BUILD_TWRPTAR_MAIN
390
Dees_Troy38bd7602012-09-14 13:33:53 -0400391// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600392string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400393 string Local_Path = Path;
394
395 // Make sure that we have a leading slash
396 if (Local_Path.substr(0, 1) != "/")
397 Local_Path = "/" + Local_Path;
398
399 // Trim the path to get the root path only
400 size_t position = Local_Path.find("/", 2);
401 if (position != string::npos) {
402 Local_Path.resize(position);
403 }
404 return Local_Path;
405}
406
407void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400408 int need_libs = 0;
409
410 if (!PartitionManager.Mount_By_Path("/system", true))
411 return;
412
413 if (!PartitionManager.Mount_By_Path("/data", true))
414 return;
415
Ethan Yonker74db1572015-10-28 12:44:49 -0500416 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000417 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400418 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500419 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000420 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400421 need_libs = 1;
422 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500423 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400424 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500425 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000426 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400427 need_libs = 1;
428 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500429 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400430 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500431 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000432 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
433 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
434 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
435 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400436 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500437 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400438 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500439 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000440 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400441 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500442 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400443}
444
445void TWFunc::htc_dumlock_restore_original_boot(void) {
446 if (!PartitionManager.Mount_By_Path("/sdcard", true))
447 return;
448
Ethan Yonker74db1572015-10-28 12:44:49 -0500449 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200450 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500451 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400452}
453
454void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
455 if (!PartitionManager.Mount_By_Path("/sdcard", true))
456 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500457 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200458 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500459 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400460}
Dees_Troy43d8b002012-09-17 16:00:01 -0400461
462int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100463 std::vector<std::string> parts = Split_String(Path, "/", true);
464 std::string cur_path;
465 for (size_t i = 0; i < parts.size(); ++i) {
466 cur_path += "/" + parts[i];
467 if (!TWFunc::Path_Exists(cur_path)) {
468 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600469 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 -0600470 return false;
471 } else {
thatf1408b32016-01-03 11:09:15 +0100472 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600473 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400474 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400475 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400476 return true;
477}
478
Dees_Troyb46a6842012-09-25 11:06:46 -0400479void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
480 string Display_Text;
481
482 DataManager::GetValue(Read_Value, Display_Text);
483 if (Display_Text.empty())
484 Display_Text = Default_Text;
485
486 DataManager::SetValue("tw_operation", Display_Text);
487 DataManager::SetValue("tw_partition", "");
488}
489
490void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
491 string Display_Text;
492
493 DataManager::GetValue(Read_Value, Display_Text);
494 if (Display_Text.empty())
495 Display_Text = Default_Text;
496
497 DataManager::SetValue("tw_operation", Display_Text);
498 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400499}
500
Dees_Troy2673cec2013-04-02 20:22:16 +0000501void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000502 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000503 FILE *destination_log = fopen(Destination.c_str(), "a");
504 if (destination_log == NULL) {
505 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600506 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000507 FILE *source_log = fopen(Source.c_str(), "r");
508 if (source_log != NULL) {
509 fseek(source_log, Log_Offset, SEEK_SET);
510 char buffer[4096];
511 while (fgets(buffer, sizeof(buffer), source_log))
512 fputs(buffer, destination_log); // Buffered write of log file
513 Log_Offset = ftell(source_log);
514 fflush(source_log);
515 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600516 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000517 fflush(destination_log);
518 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600519 }
Dees_Troya58bead2012-09-27 09:49:29 -0400520}
521
Dees_Troy2673cec2013-04-02 20:22:16 +0000522void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500523 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000524 if (PartitionManager.Mount_By_Path("/cache", false)) {
525 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
526 LOGINFO("Recreating /cache/recovery folder.\n");
527 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
528 LOGINFO("Unable to create /cache/recovery folder.\n");
529 }
530 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
531 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
532 chown("/cache/recovery/log", 1000, 1000);
533 chmod("/cache/recovery/log", 0600);
534 chmod("/cache/recovery/last_log", 0640);
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600535 } else if (PartitionManager.Mount_By_Path("/data", false) && TWFunc::Path_Exists("/data/cache/recovery/.")) {
536 Copy_Log(TMP_LOG_FILE, "/data/cache/recovery/log");
537 copy_file("/data/cache/recovery/log", "/data/cache/recovery/last_log", 600);
538 chown("/data/cache/recovery/log", 1000, 1000);
539 chmod("/data/cache/recovery/log", 0600);
540 chmod("/data/cache/recovery/last_log", 0640);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000541 } else {
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600542 LOGINFO("Failed to mount /cache or find /data/cache for TWFunc::Update_Log_File\n");
Dees Troy9d7fdf52013-09-19 20:49:25 +0000543 }
Dees_Troya58bead2012-09-27 09:49:29 -0400544
Dees_Troy2673cec2013-04-02 20:22:16 +0000545 // Reset bootloader message
546 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
547 if (Part != NULL) {
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500548 std::string err;
549 if (!clear_bootloader_message((void*)&err)) {
Ethan Yonkerb5236502016-11-19 22:24:59 -0600550 if (err == "no misc device set") {
551 LOGINFO("%s\n", err.c_str());
552 } else {
553 LOGERR("%s\n", err.c_str());
554 }
555 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000556 }
Dees_Troya58bead2012-09-27 09:49:29 -0400557
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600558 if (PartitionManager.Mount_By_Path("/cache", false)) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000559 if (unlink("/cache/recovery/command") && errno != ENOENT) {
560 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
561 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500562 }
Dees_Troya58bead2012-09-27 09:49:29 -0400563
Dees_Troy2673cec2013-04-02 20:22:16 +0000564 sync();
565}
566
567void TWFunc::Update_Intent_File(string Intent) {
568 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600569 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000570 }
Dees_Troya58bead2012-09-27 09:49:29 -0400571}
572
573// reboot: Reboot the system. Return -1 on error, no return on success
574int TWFunc::tw_reboot(RebootCommand command)
575{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500576 DataManager::Flush();
577 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400578 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600579 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400580
Dees_Troy2673cec2013-04-02 20:22:16 +0000581 switch (command) {
582 case rb_current:
583 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000584 Update_Intent_File("s");
585 sync();
586 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500587#ifdef ANDROID_RB_PROPERTY
588 return property_set(ANDROID_RB_PROPERTY, "reboot,");
589#elif defined(ANDROID_RB_RESTART)
590 return android_reboot(ANDROID_RB_RESTART, 0, 0);
591#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000592 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500593#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000594 case rb_recovery:
595 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600596#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500597 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600598#else
599 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
600#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000601 case rb_bootloader:
602 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600603#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500604 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600605#else
606 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
607#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000608 case rb_poweroff:
609 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500610#ifdef ANDROID_RB_PROPERTY
611 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
612#elif defined(ANDROID_RB_POWEROFF)
613 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
614#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000615 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500616#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000617 case rb_download:
618 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600619#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500620 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600621#else
622 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
623#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000624 default:
625 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600626 }
627 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400628}
629
630void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
631{
632 // Check for and run startup script if script exists
633 struct stat st;
634 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500635 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500636 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200637 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500638 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400639 }
Dees_Troy3477d712012-09-27 15:44:01 -0400640}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500641
642int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000643 DIR *d = opendir(path.c_str());
644 int r = 0;
645 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500646
Dees_Troyce675462013-01-09 19:48:21 +0000647 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500648 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000649 return -1;
650 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500651
Dees_Troyce675462013-01-09 19:48:21 +0000652 if (d) {
653 struct dirent *p;
654 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000655 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
656 continue;
657 new_path = path + "/";
658 new_path.append(p->d_name);
659 if (p->d_type == DT_DIR) {
660 r = removeDir(new_path, true);
661 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500662 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500663 r = rmdir(new_path.c_str());
664 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000665 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500666 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500667 } 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 +0000668 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000669 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000670 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000671 }
Dees_Troyce675462013-01-09 19:48:21 +0000672 }
673 }
674 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500675
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500676 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500677 if (skipParent)
678 return 0;
679 else
680 r = rmdir(path.c_str());
681 }
Dees_Troyce675462013-01-09 19:48:21 +0000682 }
683 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500684}
685
686int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000687 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500688 ifstream srcfile(src.c_str(), ios::binary);
689 ofstream dstfile(dst.c_str(), ios::binary);
690 dstfile << srcfile.rdbuf();
691 srcfile.close();
692 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500693 if (chmod(dst.c_str(), mode) != 0)
694 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500695 return 0;
696}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000697
698unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
699 struct stat st;
700
701 stat(Path.c_str(), &st);
702 if (st.st_mode & S_IFDIR)
703 return DT_DIR;
704 else if (st.st_mode & S_IFBLK)
705 return DT_BLK;
706 else if (st.st_mode & S_IFCHR)
707 return DT_CHR;
708 else if (st.st_mode & S_IFIFO)
709 return DT_FIFO;
710 else if (st.st_mode & S_IFLNK)
711 return DT_LNK;
712 else if (st.st_mode & S_IFREG)
713 return DT_REG;
714 else if (st.st_mode & S_IFSOCK)
715 return DT_SOCK;
716 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000717}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500718
719int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200720 ifstream file;
721 file.open(fn.c_str(), ios::in);
722
723 if (file.is_open()) {
724 file >> results;
725 file.close();
726 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500727 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200728
729 LOGINFO("Cannot find file %s\n", fn.c_str());
730 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500731}
732
733int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500734 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500735 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500736 file.open(fn.c_str(), ios::in);
737 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500738 while (getline(file, line))
739 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500740 file.close();
741 return 0;
742 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000743 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500744 return -1;
745}
746
xNUTxe85f02d2014-07-18 01:30:58 +0200747int TWFunc::read_file(string fn, uint64_t& results) {
748 ifstream file;
749 file.open(fn.c_str(), ios::in);
750
751 if (file.is_open()) {
752 file >> results;
753 file.close();
754 return 0;
755 }
756
757 LOGINFO("Cannot find file %s\n", fn.c_str());
758 return -1;
759}
760
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600761int TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500762 FILE *file;
763 file = fopen(fn.c_str(), "w");
764 if (file != NULL) {
765 fwrite(line.c_str(), line.size(), 1, file);
766 fclose(file);
767 return 0;
768 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000769 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500770 return -1;
771}
772
Dees_Troy83bd4832013-05-04 12:39:56 +0000773bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
774 DIR* d;
775
776 string Filename;
777 Restore_Path += "/";
778 d = opendir(Restore_Path.c_str());
779 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500780 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000781 return false;
782 }
783
784 struct dirent* de;
785 while ((de = readdir(d)) != NULL) {
786 Filename = Restore_Path;
787 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500788 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000789 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
790 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
791 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
792 closedir(d);
793 return false;
794 }
795 }
796 }
797 closedir(d);
798 return true;
799}
800
Dees Troyb21cc642013-09-10 17:36:41 +0000801string TWFunc::Get_Current_Date() {
802 string Current_Date;
803 time_t seconds = time(0);
804 struct tm *t = localtime(&seconds);
805 char timestamp[255];
806 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);
807 Current_Date = timestamp;
808 return Current_Date;
809}
810
Ethan Yonkerb5557892014-02-07 21:43:20 -0600811string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000812 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
813 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600814 string propvalue;
815 if (!PartitionManager.Mount_By_Path("/system", true))
816 return propvalue;
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600817 string prop_file = "/system/build.prop";
818 if (!TWFunc::Path_Exists(prop_file))
819 prop_file = "/system/system/build.prop"; // for devices with system as a root file system (e.g. Pixel)
820 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -0600821 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200822 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000823 if (!mount_state)
824 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600825 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000826 }
827 int line_count = buildprop.size();
828 int index;
829 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600830 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000831 for (index = 0; index < line_count; index++) {
832 end_pos = buildprop.at(index).find("=", start_pos);
833 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600834 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000835 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600836 if (!mount_state)
837 PartitionManager.UnMount_By_Path("/system", false);
838 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000839 }
840 }
Dees Troyb21cc642013-09-10 17:36:41 +0000841 if (!mount_state)
842 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600843 return propvalue;
844}
845
846void TWFunc::Auto_Generate_Backup_Name() {
847 string propvalue = System_Property_Get("ro.build.display.id");
848 if (propvalue.empty()) {
849 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
850 return;
851 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400852 else {
853 //remove periods from build display so it doesn't confuse the extension code
854 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
855 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600856 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500857 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600858 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
859 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
860 // Trailing spaces cause problems on some file systems, so remove them
861 string space_check, space = " ";
862 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
863 while (space_check == space) {
864 Backup_Name.resize(Backup_Name.size() - 1);
865 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
866 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500867 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonkerb5557892014-02-07 21:43:20 -0600868 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600869 if (PartitionManager.Check_Backup_Name(false) != 0) {
870 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
871 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
872 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200873}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100874
nkk7198fc3992017-12-16 16:26:42 +0200875void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100876{
877#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200878 static bool fixed = false;
879 if (fixed)
880 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200881
882 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
883
884 struct timeval tv;
885 uint64_t offset = 0;
886 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
887
888 if (TWFunc::read_file(sepoch, offset) == 0) {
889
890 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
891
892 tv.tv_sec = offset;
893 tv.tv_usec = 0;
894 settimeofday(&tv, NULL);
895
896 gettimeofday(&tv, NULL);
897
Phoenix59146b05f22018-02-03 06:41:08 +0000898 if (tv.tv_sec > 1517600000) { // Anything older then 2 Feb 2018 19:33:20 GMT will do nicely thank you ;)
xNUTxe85f02d2014-07-18 01:30:58 +0200899
900 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200901 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200902 return;
903
904 }
905
906 } else {
907
908 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
909
910 }
911
Ethan Yonker9132d912015-02-02 10:32:49 -0600912 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200913
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100914 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
915 // They never set it, it just ticks forward from 1970-01-01 00:00,
916 // and then they have files /data/system/time/ats_* with 64bit offset
917 // in miliseconds which, when added to the RTC, gives the correct time.
918 // So, the time is: (offset_from_ats + value_from_RTC)
919 // There are multiple ats files, they are for different systems? Bases?
920 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
921 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
922
nkk7198fc3992017-12-16 16:26:42 +0200923 std::vector<std::string> paths; // space separated list of paths
924 if (time_paths.empty()) {
925 paths = Split_String("/data/system/time/ /data/time/", " ");
926 if (!PartitionManager.Mount_By_Path("/data", false))
927 return;
928 } else {
929 // When specific path(s) are used, Fixup_Time needs those
930 // partitions to already be mounted!
931 paths = Split_String(time_paths, " ");
932 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100933
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100934 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200935 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100936 struct dirent *dt;
937 std::string ats_path;
938
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100939 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
940 // - it is the one for ATS_TOD (time of day?).
941 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +0200942 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100943 {
nkk7198fc3992017-12-16 16:26:42 +0200944 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -0600945 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100946 continue;
947
Matt Mowera8a89d12016-12-30 18:10:37 -0600948 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100949 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600950 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100951 continue;
952
Matt Mowera8a89d12016-12-30 18:10:37 -0600953 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +0200954 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100955 }
956
957 closedir(d);
958 }
959
nkk7198fc3992017-12-16 16:26:42 +0200960 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +0200961 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +0200962 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +0000963 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +0200964 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +0000965 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100966 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +0200967 } else {
968 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100969
nkk7198fc3992017-12-16 16:26:42 +0200970 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
971 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
972 fixed = true;
973 }
974
975 if (!fixed) {
976 // Failed to get offset from ats file, check twrp settings
977 unsigned long long value;
978 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
979 return;
980 } else {
981 offset = (uint64_t) value;
982 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
983 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
984 }
985 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100986
987 gettimeofday(&tv, NULL);
988
989 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +0000990#ifdef TW_CLOCK_OFFSET
991// Some devices are even quirkier and have ats files that are offset from the actual time
992 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
993#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100994 tv.tv_usec += (offset%1000)*1000;
995
Matt Mowera8a89d12016-12-30 18:10:37 -0600996 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100997 {
998 ++tv.tv_sec;
999 tv.tv_usec -= 1000000;
1000 }
1001
1002 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001003
1004 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001005#endif
1006}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001007
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001008std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1009{
1010 std::vector<std::string> res;
1011 size_t idx = 0, idx_last = 0;
1012
Matt Mowera8a89d12016-12-30 18:10:37 -06001013 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001014 {
1015 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001016 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001017 idx = str.size();
1018
Matt Mowera8a89d12016-12-30 18:10:37 -06001019 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001020 res.push_back(str.substr(idx_last, idx-idx_last));
1021
1022 idx_last = idx + delimiter.size();
1023 }
1024
1025 return res;
1026}
1027
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001028bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1029{
1030 std::vector<std::string> parts = Split_String(path, "/");
1031 std::string cur_path;
1032 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001033 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001034 {
1035 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001036 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001037 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001038 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001039 return false;
1040 chown(cur_path.c_str(), uid, gid);
1041 }
1042 }
1043 return true;
1044}
1045
xNUTxe85f02d2014-07-18 01:30:58 +02001046int TWFunc::Set_Brightness(std::string brightness_value)
1047{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001048 int result = -1;
1049 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001050
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001051 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001052 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001053 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001054 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1055 if (!secondary_brightness_file.empty()) {
1056 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001057 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001058 }
xNUTxe85f02d2014-07-18 01:30:58 +02001059 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001060 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001061}
1062
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001063bool TWFunc::Toggle_MTP(bool enable) {
1064#ifdef TW_HAS_MTP
1065 static int was_enabled = false;
1066
1067 if (enable && was_enabled) {
1068 if (!PartitionManager.Enable_MTP())
1069 PartitionManager.Disable_MTP();
1070 } else {
1071 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1072 PartitionManager.Disable_MTP();
1073 usleep(500);
1074 }
1075 return was_enabled;
1076#else
1077 return false;
1078#endif
1079}
1080
Tom Hite5a926722014-09-15 01:31:03 +00001081void TWFunc::SetPerformanceMode(bool mode) {
1082 if (mode) {
1083 property_set("recovery.perf.mode", "1");
1084 } else {
1085 property_set("recovery.perf.mode", "0");
1086 }
1087 // Some time for events to catch up to init handlers
1088 usleep(500000);
1089}
1090
Jenkins1710bf22014-10-02 20:22:21 -04001091std::string TWFunc::to_string(unsigned long value) {
1092 std::ostringstream os;
1093 os << value;
1094 return os.str();
1095}
1096
Ethan Yonker9132d912015-02-02 10:32:49 -06001097void TWFunc::Disable_Stock_Recovery_Replace(void) {
1098 if (PartitionManager.Mount_By_Path("/system", false)) {
1099 // Disable flashing of stock recovery
1100 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1101 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001102 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 -06001103 sync();
1104 }
1105 PartitionManager.UnMount_By_Path("/system", false);
1106 }
1107}
1108
Ethan Yonker483e9f42016-01-11 22:21:18 -06001109unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1110 unsigned long block_device_size;
1111 int ret = 0;
1112
1113 int fd = open(block_device, O_RDONLY);
1114 if (fd < 0) {
1115 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1116 } else {
1117 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1118 close(fd);
1119 if (ret) {
1120 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1121 } else {
1122 return (unsigned long long)(block_device_size) * 512LLU;
1123 }
1124 }
1125 return 0;
1126}
1127
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001128void TWFunc::copy_kernel_log(string curr_storage) {
1129 std::string dmesgDst = curr_storage + "/dmesg.log";
1130 std::string dmesgCmd = "/sbin/dmesg";
1131
1132 std::string result;
1133 Exec_Cmd(dmesgCmd, result);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001134 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001135 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1136 tw_set_default_metadata(dmesgDst.c_str());
1137}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001138
1139bool TWFunc::isNumber(string strtocheck) {
1140 int num = 0;
1141 std::istringstream iss(strtocheck);
1142
1143 if (!(iss >> num).fail())
1144 return true;
1145 else
1146 return false;
1147}
1148
1149int TWFunc::stream_adb_backup(string &Restore_Name) {
1150 string cmd = "/sbin/bu --twrp stream " + Restore_Name;
1151 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1152 int ret = TWFunc::Exec_Cmd(cmd);
1153 if (ret != 0)
1154 return -1;
1155 return ret;
1156}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001157#endif // ndef BUILD_TWRPTAR_MAIN