blob: 50511ce0ac9f0611c37253efa930e72fd9097f97 [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
bigbiffdf8436b2020-08-30 16:22:34 -04002 Copyright 2012-2020 TeamWin
Dees Troy3be70a82013-10-22 14:25:12 +00003 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>
bigbiff bigbiff19874f12019-01-08 20:06:57 -050040#include <selinux/label.h>
Dees_Troy38bd7602012-09-14 13:33:53 -040041#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000042#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060043#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060044#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040045#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060046#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040047#include "variables.h"
bigbiffdf8436b2020-08-30 16:22:34 -040048#include "bootloader_message/include/bootloader_message/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000049#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050050#include "cutils/android_reboot.h"
51#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060052#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000053#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
54 #include "openaes/inc/oaes_lib.h"
55#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050056#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040057
Dees_Troyb05ddee2013-01-28 20:24:50 +000058extern "C" {
59 #include "libcrecovery/common.h"
60}
61
Chaosmaster461e39f2020-02-07 01:48:13 +010062#ifdef TW_INCLUDE_LIBRESETPROP
63 #include <resetprop.h>
64#endif
65
bigbiff bigbiff19874f12019-01-08 20:06:57 -050066struct selabel_handle *selinux_handle;
67
bigbiff bigbiff9c754052013-01-09 09:09:08 -050068/* Execute a command */
bigbiffad58e1b2020-07-06 20:24:34 -040069int TWFunc::Exec_Cmd(const string& cmd, string &result, bool combine_stderr) {
Dees_Troy29a06352013-08-24 12:06:47 +000070 FILE* exec;
71 char buffer[130];
72 int ret = 0;
bigbiffad58e1b2020-07-06 20:24:34 -040073 std::string popen_cmd = cmd;
74 if (combine_stderr)
75 popen_cmd = cmd + " 2>&1";
76 exec = __popen(popen_cmd.c_str(), "r");
77
Matt Mowera8a89d12016-12-30 18:10:37 -060078 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000079 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050080 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000081 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050082 }
Dees_Troy29a06352013-08-24 12:06:47 +000083 ret = __pclose(exec);
84 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050085}
86
Ethan Yonker7e941582019-03-22 08:18:21 -050087int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020088 pid_t pid;
89 int status;
90 switch(pid = fork())
91 {
92 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050093 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020094 return -1;
95 case 0: // child
bigbiffad58e1b2020-07-06 20:24:34 -040096 execl("/system/bin/sh", "sh", "-c", cmd.c_str(), NULL);
Vojtech Bocek05534202013-09-11 08:11:56 +020097 _exit(127);
98 break;
99 default:
100 {
Ethan Yonker7e941582019-03-22 08:18:21 -0500101 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +0200102 return -1;
103 else
104 return 0;
105 }
106 }
107}
108
Dees_Troy38bd7602012-09-14 13:33:53 -0400109// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600110string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400111 size_t pos = Path.find_last_of("/");
112 if (pos != string::npos) {
113 string Filename;
114 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
115 return Filename;
116 } else
117 return Path;
118}
119
120// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600121string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400122 size_t pos = Path.find_last_of("/");
123 if (pos != string::npos) {
124 string Pathonly;
125 Pathonly = Path.substr(0, pos + 1);
126 return Pathonly;
127 } else
128 return Path;
129}
130
Ethan Yonker7e941582019-03-22 08:18:21 -0500131int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600132 pid_t rc_pid;
133
134 rc_pid = waitpid(pid, status, 0);
135 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100136 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500137 if (Show_Errors)
138 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 -0600139 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100140 } else if (WEXITSTATUS(*status) == 0) {
141 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
142 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500143 if (Show_Errors)
144 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 -0600145 return -1;
146 }
147 } else { // no PID returned
148 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200149 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600150 else {
that2252d242015-04-03 22:33:04 +0200151 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600152 return -1;
153 }
154 }
155 return 0;
156}
157
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600158int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
159 pid_t retpid = waitpid(pid, status, WNOHANG);
160 for (; retpid == 0 && timeout; --timeout) {
161 sleep(1);
162 retpid = waitpid(pid, status, WNOHANG);
163 }
164 if (retpid == 0 && timeout == 0) {
165 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
166 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600167 for (timeout = 5; retpid == 0 && timeout; --timeout) {
168 sleep(1);
169 retpid = waitpid(pid, status, WNOHANG);
170 }
171 if (retpid)
172 LOGINFO("Child process killed successfully\n");
173 else
174 LOGINFO("Child process took too long to kill, may be a zombie process\n");
175 return -1;
176 } else if (retpid > 0) {
177 if (WIFSIGNALED(*status)) {
178 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
179 return -1;
180 }
181 } else if (retpid < 0) { // no PID returned
182 if (errno == ECHILD)
183 LOGERR("%s no child process exist\n", Child_Name.c_str());
184 else {
185 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
186 return -1;
187 }
188 }
189 return 0;
190}
191
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600192bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600193 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400194 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600195}
196
bigbiffce8f83c2015-12-12 18:30:21 -0500197Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600198 string::size_type i = 0;
199 int firstbyte = 0, secondbyte = 0;
200 char header[3];
201
202 ifstream f;
203 f.open(fn.c_str(), ios::in | ios::binary);
204 f.get(header, 3);
205 f.close();
206 firstbyte = header[i] & 0xff;
207 secondbyte = header[++i] & 0xff;
208
209 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500210 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600211 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500212 return ENCRYPTED;
213 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600214}
215
216int TWFunc::Try_Decrypting_File(string fn, string password) {
217#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
218 OAES_CTX * ctx = NULL;
219 uint8_t _key_data[32] = "";
220 FILE *f;
221 uint8_t buffer[4096];
222 uint8_t *buffer_out = NULL;
223 uint8_t *ptr = NULL;
224 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600225 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600226 size_t _j = 0;
227 size_t _key_data_len = 0;
228
229 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600230 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600231 _key_data[_j] = _j + 1;
232 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600233 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600234 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600235 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600236 _key_data_len = 24;
237 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600238 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600239 memcpy(_key_data, password.c_str(), password.size());
240
241 ctx = oaes_alloc();
242 if (ctx == NULL) {
243 LOGERR("Failed to allocate OAES\n");
244 return -1;
245 }
246
247 oaes_key_import_data(ctx, _key_data, _key_data_len);
248
249 f = fopen(fn.c_str(), "rb");
250 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500251 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500252 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600253 return -1;
254 }
255 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
256 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500257 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600258 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500259 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600260 return -1;
261 }
262 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
263 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
264 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500265 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600266 return -1;
267 }
268 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
269 if (buffer_out == NULL) {
270 LOGERR("Failed to allocate output buffer for try decrypt.\n");
271 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500272 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600273 return -1;
274 }
275 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
276 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
277 fclose(f);
278 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500279 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600280 return 0;
281 }
282 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500283 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600284 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500285 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600286 free(buffer_out);
287 return 1; // Decrypted successfully
288 }
289 ptr = buffer_out;
290 firstbyte = *ptr & 0xff;
291 ptr++;
292 secondbyte = *ptr & 0xff;
293 if (firstbyte == 0x1f && secondbyte == 0x8b) {
294 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
295 free(buffer_out);
296 return 3; // Compressed
297 }
298 if (out_len >= 262) {
299 ptr = buffer_out + 257;
300 if (strncmp((char*)ptr, "ustar", 5) == 0) {
301 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
302 free(buffer_out);
303 return 2; // Tar
304 }
305 }
306 free(buffer_out);
307 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
308 return 1; // Decrypted successfully
309#else
310 LOGERR("Encrypted backup support not included.\n");
311 return -1;
312#endif
313}
314
Ethan Yonker472f5062016-02-25 13:47:30 -0600315unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600316 struct stat st;
317
318 if (stat(Path.c_str(), &st) != 0)
319 return 0;
320 return st.st_size;
321}
322
bigbiffee7b7ff2020-03-23 15:08:27 -0400323std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
324 std::string res;
325 size_t pos = path.find_first_of("/");
326 if (pos != std::string::npos) {
327 res = path.substr(pos+1);
328 }
329 return res;
330}
331
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100332std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
333{
334 std::string res;
335 size_t last_idx = 0, idx = 0;
336
Matt Mowera8a89d12016-12-30 18:10:37 -0600337 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100338 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600339 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100340 res += '/';
341
342 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600343 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100344 res += path.substr(last_idx, idx);
345 break;
346 }
347
348 res += path.substr(last_idx, idx-last_idx);
349 last_idx = path.find_first_not_of('/', idx);
350 }
351
Matt Mowera8a89d12016-12-30 18:10:37 -0600352 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100353 res += '/';
354 return res;
355}
356
Matt Mower2416a502016-04-12 19:54:46 -0500357void TWFunc::Strip_Quotes(char* &str) {
358 if (strlen(str) > 0 && str[0] == '\"')
359 str++;
360 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
361 str[strlen(str)-1] = 0;
362}
363
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500364vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
365 vector<string> res;
366
367 if (in.empty() || del == '\0')
368 return res;
369
370 string field;
371 istringstream f(in);
372 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600373 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500374 if (field.empty() && skip_empty)
375 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600376 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500377 }
378 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600379 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500380 if (field.empty() && skip_empty)
381 continue;
382 res.push_back(field);
383 }
384 }
385 return res;
386}
387
Ethan Yonker472f5062016-02-25 13:47:30 -0600388timespec TWFunc::timespec_diff(timespec& start, timespec& end)
389{
390 timespec temp;
391 if ((end.tv_nsec-start.tv_nsec)<0) {
392 temp.tv_sec = end.tv_sec-start.tv_sec-1;
393 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
394 } else {
395 temp.tv_sec = end.tv_sec-start.tv_sec;
396 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
397 }
398 return temp;
399}
400
401int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
402{
403 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
404 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
405}
406
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600407#ifndef BUILD_TWRPTAR_MAIN
408
Dees_Troy38bd7602012-09-14 13:33:53 -0400409// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600410string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400411 string Local_Path = Path;
412
413 // Make sure that we have a leading slash
414 if (Local_Path.substr(0, 1) != "/")
415 Local_Path = "/" + Local_Path;
416
417 // Trim the path to get the root path only
418 size_t position = Local_Path.find("/", 2);
419 if (position != string::npos) {
420 Local_Path.resize(position);
421 }
422 return Local_Path;
423}
424
Dees_Troy43d8b002012-09-17 16:00:01 -0400425int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100426 std::vector<std::string> parts = Split_String(Path, "/", true);
427 std::string cur_path;
428 for (size_t i = 0; i < parts.size(); ++i) {
429 cur_path += "/" + parts[i];
430 if (!TWFunc::Path_Exists(cur_path)) {
431 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600432 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 -0600433 return false;
434 } else {
thatf1408b32016-01-03 11:09:15 +0100435 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600436 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400437 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400438 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400439 return true;
440}
441
Dees_Troyb46a6842012-09-25 11:06:46 -0400442void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
443 string Display_Text;
444
445 DataManager::GetValue(Read_Value, Display_Text);
446 if (Display_Text.empty())
447 Display_Text = Default_Text;
448
449 DataManager::SetValue("tw_operation", Display_Text);
450 DataManager::SetValue("tw_partition", "");
451}
452
453void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
454 string Display_Text;
455
456 DataManager::GetValue(Read_Value, Display_Text);
457 if (Display_Text.empty())
458 Display_Text = Default_Text;
459
460 DataManager::SetValue("tw_operation", Display_Text);
461 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400462}
463
Dees_Troy2673cec2013-04-02 20:22:16 +0000464void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400465 int logPipe[2];
466 int pigz_pid;
467 int destination_fd;
468 std::string destLogBuffer;
469
Dees Troy9d7fdf52013-09-19 20:49:25 +0000470 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400471
472 size_t extPos = Destination.find(".gz");
473 std::string uncompressedLog(Destination);
474 uncompressedLog.replace(extPos, Destination.length(), "");
475
476 if (Path_Exists(Destination)) {
477 Archive_Type type = Get_File_Type(Destination);
478 if (type == COMPRESSED) {
479 std::string destFileBuffer;
480 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400481 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400482 LOGINFO("Unable to get destination logfile contents.\n");
483 return;
484 }
485 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600486 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400487 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500488 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400489 std::stringstream uncompressedSS;
490 uncompressedSS << uncompressedIfs.rdbuf();
491 uncompressedIfs.close();
492 std::string uncompressedLogBuffer(uncompressedSS.str());
493 destLogBuffer.append(uncompressedLogBuffer);
494 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600495 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400496
bigbiffd3317052019-12-22 16:05:12 -0500497 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400498 std::stringstream ss;
499 ss << ifs.rdbuf();
500 std::string srcLogBuffer(ss.str());
501 ifs.close();
502
503 if (pipe(logPipe) < 0) {
504 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
505 }
506
507 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
508
509 pigz_pid = fork();
510 if (pigz_pid < 0) {
511 LOGINFO("fork() failed\n");
512 close(destination_fd);
513 close(logPipe[0]);
514 close(logPipe[1]);
515 } else if (pigz_pid == 0) {
516 close(logPipe[1]);
517 dup2(logPipe[0], fileno(stdin));
518 dup2(destination_fd, fileno(stdout));
519 if (execlp("pigz", "pigz", "-", NULL) < 0) {
520 close(destination_fd);
521 close(logPipe[0]);
522 _exit(-1);
523 }
524 } else {
525 close(logPipe[0]);
526 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
527 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
528 close(logPipe[1]);
529 close(destination_fd);
530 return;
531 }
532 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
533 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
534 close(logPipe[1]);
535 close(destination_fd);
536 return;
537 }
538 close(logPipe[1]);
539 }
540 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400541}
542
Dees_Troy2673cec2013-04-02 20:22:16 +0000543void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400544 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500545
bigbiff25d25b92020-06-19 16:07:38 -0400546 if (get_log_dir() == CACHE_LOGS_DIR) {
547 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
548 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000549 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000550 }
Dees_Troya58bead2012-09-27 09:49:29 -0400551
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500552 if (!TWFunc::Path_Exists(recoveryDir)) {
553 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400554 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500555 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
556 }
557 }
558
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400559 std::string logCopy = recoveryDir + "log.gz";
560 std::string lastLogCopy = recoveryDir + "last_log.gz";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500561 copy_file(logCopy, lastLogCopy, 600);
562 Copy_Log(TMP_LOG_FILE, logCopy);
563 chown(logCopy.c_str(), 1000, 1000);
564 chmod(logCopy.c_str(), 0600);
565 chmod(lastLogCopy.c_str(), 0640);
566
bigbiff25d25b92020-06-19 16:07:38 -0400567 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500568 if (PartitionManager.Mount_By_Path("/cache", false)) {
569 if (unlink("/cache/recovery/command") && errno != ENOENT) {
570 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
571 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000572 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500573 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000574 sync();
575}
576
bigbiffdf8436b2020-08-30 16:22:34 -0400577void TWFunc::Clear_Bootloader_Message() {
578 std::string err;
579 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100580 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400581 }
582}
583
Dees_Troy2673cec2013-04-02 20:22:16 +0000584void TWFunc::Update_Intent_File(string Intent) {
585 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600586 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000587 }
Dees_Troya58bead2012-09-27 09:49:29 -0400588}
589
590// reboot: Reboot the system. Return -1 on error, no return on success
591int TWFunc::tw_reboot(RebootCommand command)
592{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500593 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400594 Update_Log_File();
595
Dees_Troya58bead2012-09-27 09:49:29 -0400596 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600597 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400598
Dees_Troy2673cec2013-04-02 20:22:16 +0000599 switch (command) {
600 case rb_current:
601 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000602 Update_Intent_File("s");
603 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400604 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500605#ifdef ANDROID_RB_PROPERTY
606 return property_set(ANDROID_RB_PROPERTY, "reboot,");
607#elif defined(ANDROID_RB_RESTART)
608 return android_reboot(ANDROID_RB_RESTART, 0, 0);
609#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000610 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500611#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000612 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400613 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500614 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000615 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400616 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500617 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000618 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400619 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500620#ifdef ANDROID_RB_PROPERTY
621 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
622#elif defined(ANDROID_RB_POWEROFF)
623 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
624#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000625 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500626#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000627 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400628 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500629 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200630 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400631 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200632 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400633 case rb_fastboot:
634 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000635 default:
636 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600637 }
638 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400639}
640
641void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
642{
643 // Check for and run startup script if script exists
644 struct stat st;
645 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500646 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500647 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200648 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500649 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400650 }
Dees_Troy3477d712012-09-27 15:44:01 -0400651}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500652
653int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000654 DIR *d = opendir(path.c_str());
655 int r = 0;
656 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500657
Dees_Troyce675462013-01-09 19:48:21 +0000658 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500659 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000660 return -1;
661 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500662
Dees_Troyce675462013-01-09 19:48:21 +0000663 if (d) {
664 struct dirent *p;
665 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000666 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
667 continue;
668 new_path = path + "/";
669 new_path.append(p->d_name);
670 if (p->d_type == DT_DIR) {
671 r = removeDir(new_path, true);
672 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500673 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500674 r = rmdir(new_path.c_str());
675 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000676 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500677 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500678 } 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 +0000679 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000680 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000681 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000682 }
Dees_Troyce675462013-01-09 19:48:21 +0000683 }
684 }
685 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500686
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500687 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500688 if (skipParent)
689 return 0;
690 else
691 r = rmdir(path.c_str());
692 }
Dees_Troyce675462013-01-09 19:48:21 +0000693 }
694 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500695}
696
697int TWFunc::copy_file(string src, string dst, int mode) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400698 PartitionManager.Mount_By_Path(src, false);
699 PartitionManager.Mount_By_Path(dst, false);
700 if (!Path_Exists(src)) {
bigbiffaac58612020-08-30 11:18:39 -0400701 LOGINFO("Path %s does not exist. Unable to copy %s\n", src.c_str(), dst.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400702 return -1;
703 }
bigbiffd3317052019-12-22 16:05:12 -0500704 std::ifstream srcfile(src.c_str(), ios::binary);
705 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500706 dstfile << srcfile.rdbuf();
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400707 if (!dstfile.bad()) {
708 LOGINFO("Copied file %s to %s\n", src.c_str(), dst.c_str());
709 }
710 else {
711 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
712 return -1;
713 }
714
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500715 srcfile.close();
716 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500717 if (chmod(dst.c_str(), mode) != 0)
718 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500719 return 0;
720}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000721
722unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
723 struct stat st;
724
725 stat(Path.c_str(), &st);
726 if (st.st_mode & S_IFDIR)
727 return DT_DIR;
728 else if (st.st_mode & S_IFBLK)
729 return DT_BLK;
730 else if (st.st_mode & S_IFCHR)
731 return DT_CHR;
732 else if (st.st_mode & S_IFIFO)
733 return DT_FIFO;
734 else if (st.st_mode & S_IFLNK)
735 return DT_LNK;
736 else if (st.st_mode & S_IFREG)
737 return DT_REG;
738 else if (st.st_mode & S_IFSOCK)
739 return DT_SOCK;
740 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000741}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500742
743int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200744 ifstream file;
745 file.open(fn.c_str(), ios::in);
746
747 if (file.is_open()) {
748 file >> results;
749 file.close();
750 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500751 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200752
753 LOGINFO("Cannot find file %s\n", fn.c_str());
754 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500755}
756
757int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500758 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500759 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500760 file.open(fn.c_str(), ios::in);
761 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500762 while (getline(file, line))
763 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500764 file.close();
765 return 0;
766 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000767 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500768 return -1;
769}
770
xNUTxe85f02d2014-07-18 01:30:58 +0200771int TWFunc::read_file(string fn, uint64_t& results) {
772 ifstream file;
773 file.open(fn.c_str(), ios::in);
774
775 if (file.is_open()) {
776 file >> results;
777 file.close();
778 return 0;
779 }
780
781 LOGINFO("Cannot find file %s\n", fn.c_str());
782 return -1;
783}
784
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600785int TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500786 FILE *file;
787 file = fopen(fn.c_str(), "w");
788 if (file != NULL) {
789 fwrite(line.c_str(), line.size(), 1, file);
790 fclose(file);
791 return 0;
792 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000793 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500794 return -1;
795}
796
Dees_Troy83bd4832013-05-04 12:39:56 +0000797bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
798 DIR* d;
799
800 string Filename;
801 Restore_Path += "/";
802 d = opendir(Restore_Path.c_str());
803 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500804 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000805 return false;
806 }
807
808 struct dirent* de;
809 while ((de = readdir(d)) != NULL) {
810 Filename = Restore_Path;
811 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500812 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000813 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
814 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
815 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
816 closedir(d);
817 return false;
818 }
819 }
820 }
821 closedir(d);
822 return true;
823}
824
Dees Troyb21cc642013-09-10 17:36:41 +0000825string TWFunc::Get_Current_Date() {
826 string Current_Date;
827 time_t seconds = time(0);
828 struct tm *t = localtime(&seconds);
829 char timestamp[255];
830 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);
831 Current_Date = timestamp;
832 return Current_Date;
833}
834
Ethan Yonkerb5557892014-02-07 21:43:20 -0600835string TWFunc::System_Property_Get(string Prop_Name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100836 return System_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path());
837}
838
839string TWFunc::System_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point) {
840 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000841 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600842 string propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100843 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600844 return propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100845 string prop_file = Mount_Point + "/build.prop";
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600846 if (!TWFunc::Path_Exists(prop_file))
Chaosmaster65633a42020-02-05 15:24:09 +0100847 prop_file = Mount_Point + "/system/build.prop"; // for devices with system as a root file system (e.g. Pixel)
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600848 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback9d6feb52018-07-27 10:05:24 -0400849 LOGINFO("Unable to open build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200850 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000851 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100852 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600853 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000854 }
855 int line_count = buildprop.size();
856 int index;
857 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600858 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000859 for (index = 0; index < line_count; index++) {
860 end_pos = buildprop.at(index).find("=", start_pos);
861 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600862 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000863 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600864 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100865 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600866 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000867 }
868 }
Dees Troyb21cc642013-09-10 17:36:41 +0000869 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100870 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600871 return propvalue;
872}
873
874void TWFunc::Auto_Generate_Backup_Name() {
875 string propvalue = System_Property_Get("ro.build.display.id");
876 if (propvalue.empty()) {
877 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
878 return;
879 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400880 else {
881 //remove periods from build display so it doesn't confuse the extension code
882 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
883 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600884 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500885 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600886 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
887 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
888 // Trailing spaces cause problems on some file systems, so remove them
889 string space_check, space = " ";
890 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
891 while (space_check == space) {
892 Backup_Name.resize(Backup_Name.size() - 1);
893 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
894 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500895 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600896 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
897 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600898 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600899 } else {
900 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600901 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200902}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100903
nkk7198fc3992017-12-16 16:26:42 +0200904void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100905{
906#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200907 static bool fixed = false;
908 if (fixed)
909 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200910
911 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
912
913 struct timeval tv;
914 uint64_t offset = 0;
915 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
916
917 if (TWFunc::read_file(sepoch, offset) == 0) {
918
919 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
920
921 tv.tv_sec = offset;
922 tv.tv_usec = 0;
923 settimeofday(&tv, NULL);
924
925 gettimeofday(&tv, NULL);
926
Phoenix59146b05f22018-02-03 06:41:08 +0000927 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 +0200928
929 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200930 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200931 return;
932
933 }
934
935 } else {
936
937 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
938
939 }
940
Ethan Yonker9132d912015-02-02 10:32:49 -0600941 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200942
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100943 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
944 // They never set it, it just ticks forward from 1970-01-01 00:00,
945 // and then they have files /data/system/time/ats_* with 64bit offset
946 // in miliseconds which, when added to the RTC, gives the correct time.
947 // So, the time is: (offset_from_ats + value_from_RTC)
948 // There are multiple ats files, they are for different systems? Bases?
949 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
950 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
951
nkk7198fc3992017-12-16 16:26:42 +0200952 std::vector<std::string> paths; // space separated list of paths
953 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +0100954 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +0200955 if (!PartitionManager.Mount_By_Path("/data", false))
956 return;
957 } else {
958 // When specific path(s) are used, Fixup_Time needs those
959 // partitions to already be mounted!
960 paths = Split_String(time_paths, " ");
961 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100962
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100963 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200964 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100965 struct dirent *dt;
966 std::string ats_path;
967
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100968 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
969 // - it is the one for ATS_TOD (time of day?).
970 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +0200971 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100972 {
nkk7198fc3992017-12-16 16:26:42 +0200973 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -0600974 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100975 continue;
976
Matt Mowera8a89d12016-12-30 18:10:37 -0600977 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100978 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600979 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100980 continue;
981
Matt Mowera8a89d12016-12-30 18:10:37 -0600982 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +0200983 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100984 }
985
986 closedir(d);
987 }
988
nkk7198fc3992017-12-16 16:26:42 +0200989 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +0200990 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +0200991 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +0000992 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +0200993 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +0000994 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100995 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +0200996 } else {
997 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100998
nkk7198fc3992017-12-16 16:26:42 +0200999 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1000 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1001 fixed = true;
1002 }
1003
1004 if (!fixed) {
1005 // Failed to get offset from ats file, check twrp settings
1006 unsigned long long value;
1007 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1008 return;
1009 } else {
1010 offset = (uint64_t) value;
1011 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1012 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1013 }
1014 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001015
1016 gettimeofday(&tv, NULL);
1017
1018 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001019#ifdef TW_CLOCK_OFFSET
1020// Some devices are even quirkier and have ats files that are offset from the actual time
1021 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1022#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001023 tv.tv_usec += (offset%1000)*1000;
1024
Matt Mowera8a89d12016-12-30 18:10:37 -06001025 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001026 {
1027 ++tv.tv_sec;
1028 tv.tv_usec -= 1000000;
1029 }
1030
1031 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001032
1033 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001034#endif
1035}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001036
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001037std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1038{
1039 std::vector<std::string> res;
1040 size_t idx = 0, idx_last = 0;
1041
Matt Mowera8a89d12016-12-30 18:10:37 -06001042 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001043 {
1044 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001045 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001046 idx = str.size();
1047
Matt Mowera8a89d12016-12-30 18:10:37 -06001048 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001049 res.push_back(str.substr(idx_last, idx-idx_last));
1050
1051 idx_last = idx + delimiter.size();
1052 }
1053
1054 return res;
1055}
1056
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001057bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1058{
1059 std::vector<std::string> parts = Split_String(path, "/");
1060 std::string cur_path;
1061 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001062 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001063 {
1064 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001065 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001066 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001067 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001068 return false;
1069 chown(cur_path.c_str(), uid, gid);
1070 }
1071 }
1072 return true;
1073}
1074
xNUTxe85f02d2014-07-18 01:30:58 +02001075int TWFunc::Set_Brightness(std::string brightness_value)
1076{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001077 int result = -1;
1078 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001079
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001080 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001081 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001082 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001083 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1084 if (!secondary_brightness_file.empty()) {
1085 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001086 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001087 }
xNUTxe85f02d2014-07-18 01:30:58 +02001088 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001089 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001090}
1091
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001092bool TWFunc::Toggle_MTP(bool enable) {
1093#ifdef TW_HAS_MTP
1094 static int was_enabled = false;
1095
1096 if (enable && was_enabled) {
1097 if (!PartitionManager.Enable_MTP())
1098 PartitionManager.Disable_MTP();
1099 } else {
1100 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1101 PartitionManager.Disable_MTP();
1102 usleep(500);
1103 }
1104 return was_enabled;
1105#else
1106 return false;
1107#endif
1108}
1109
Tom Hite5a926722014-09-15 01:31:03 +00001110void TWFunc::SetPerformanceMode(bool mode) {
1111 if (mode) {
1112 property_set("recovery.perf.mode", "1");
1113 } else {
1114 property_set("recovery.perf.mode", "0");
1115 }
1116 // Some time for events to catch up to init handlers
1117 usleep(500000);
1118}
1119
Jenkins1710bf22014-10-02 20:22:21 -04001120std::string TWFunc::to_string(unsigned long value) {
1121 std::ostringstream os;
1122 os << value;
1123 return os.str();
1124}
1125
Ethan Yonker9132d912015-02-02 10:32:49 -06001126void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001127 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001128 // Disable flashing of stock recovery
1129 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1130 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001131 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 -06001132 sync();
1133 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001134 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001135 }
1136}
1137
Ethan Yonker483e9f42016-01-11 22:21:18 -06001138unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1139 unsigned long block_device_size;
1140 int ret = 0;
1141
1142 int fd = open(block_device, O_RDONLY);
1143 if (fd < 0) {
1144 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1145 } else {
1146 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1147 close(fd);
1148 if (ret) {
1149 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1150 } else {
1151 return (unsigned long long)(block_device_size) * 512LLU;
1152 }
1153 }
1154 return 0;
1155}
1156
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001157void TWFunc::copy_kernel_log(string curr_storage) {
1158 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001159 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001160
1161 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001162 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001163 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001164 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1165 tw_set_default_metadata(dmesgDst.c_str());
1166}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001167
1168bool TWFunc::isNumber(string strtocheck) {
1169 int num = 0;
1170 std::istringstream iss(strtocheck);
1171
1172 if (!(iss >> num).fail())
1173 return true;
1174 else
1175 return false;
1176}
1177
1178int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001179 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001180 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1181 int ret = TWFunc::Exec_Cmd(cmd);
1182 if (ret != 0)
1183 return -1;
1184 return ret;
1185}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001186
bigbiff25d25b92020-06-19 16:07:38 -04001187std::string TWFunc::get_log_dir() {
1188 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1189 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001190 LOGINFO("Unable to find a directory to store TWRP logs.");
1191 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001192 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001193 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001194 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001195 }
1196 else {
bigbiff25d25b92020-06-19 16:07:38 -04001197 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001198 }
1199}
1200
1201void TWFunc::check_selinux_support() {
1202 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1203 if (TWFunc::Path_Exists("/file_contexts")) {
1204 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1205 rename("/file_contexts", "/file_contexts.bak");
1206 }
1207 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1208 rename("/prebuilt_file_contexts", "/file_contexts");
1209 }
1210 struct selinux_opt selinux_options[] = {
1211 { SELABEL_OPT_PATH, "/file_contexts" }
1212 };
1213 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1214 if (!selinux_handle)
1215 printf("No file contexts for SELinux\n");
1216 else
1217 printf("SELinux contexts loaded from /file_contexts\n");
1218 { // Check to ensure SELinux can be supported by the kernel
1219 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001220 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001221 std::string se_context_check = cacheDir + "recovery/";
1222 int ret = 0;
1223
bigbiff25d25b92020-06-19 16:07:38 -04001224 if (cacheDir == CACHE_LOGS_DIR) {
1225 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001226 }
1227 if (TWFunc::Path_Exists(se_context_check)) {
1228 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001229 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001230 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1231 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001232 }
1233 }
1234 if (ret < 0) {
1235 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1236 } else {
1237 free(contexts);
1238 gui_msg("full_selinux=Full SELinux support is present.");
1239 }
1240 }
1241}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001242
1243bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001244 LOGINFO("checking for twrp app\n");
1245 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1246 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001247 bool is_system_mounted = true;
1248 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1249 is_system_mounted = false;
1250 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001251 }
Captain Throwback31c14922020-12-21 11:28:34 -05001252 string base_path = PartitionManager.Get_Android_Root_Path();
1253 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1254 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1255 string install_path = base_path + "/priv-app";
1256 if (!TWFunc::Path_Exists(install_path))
1257 install_path = base_path + "/app";
1258 install_path += "/twrpapp";
1259 if (TWFunc::Path_Exists(install_path)) {
1260 LOGINFO("App found at '%s'\n", install_path.c_str());
1261 DataManager::SetValue("tw_app_installed_in_system", 1);
1262 return true;
1263 }
1264 if (!is_system_mounted)
1265 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001266 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001267 }
1268 DataManager::SetValue("tw_app_installed_in_system", 0);
1269 return false;
1270}
Chaosmaster461e39f2020-02-07 01:48:13 +01001271
epicX271bb3a2020-12-30 01:03:18 +05301272void TWFunc::checkforapp(){
1273
1274 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1275 int sdkver = 0;
1276 if (!sdkverstr.empty()) {
1277 sdkver = atoi(sdkverstr.c_str());
1278 }
1279 if (sdkver <= 13) {
1280 if (sdkver == 0)
1281 LOGINFO("Unable to read sdk version from build prop\n");
1282 else
1283 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1284 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1285 goto exit;
1286 }
1287 if (Is_TWRP_App_In_System()) {
1288 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1289 goto exit;
1290 }
1291 if (PartitionManager.Mount_By_Path("/data", false)) {
1292 const char parent_path[] = "/data/app";
1293 const char app_prefix[] = "me.twrp.twrpapp-";
1294 DIR *d = opendir(parent_path);
1295 if (d) {
1296 struct dirent *p;
1297 while ((p = readdir(d))) {
1298 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1299 continue;
1300 closedir(d);
1301 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1302 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1303 goto exit;
1304 }
1305 closedir(d);
1306 }
1307 } else {
1308 LOGINFO("Data partition cannot be mounted during app check\n");
1309 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1310 }
1311
1312 LOGINFO("App not installed\n");
1313 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1314exit:
1315 return;
1316
1317}
1318
Chaosmaster461e39f2020-02-07 01:48:13 +01001319int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1320#ifdef TW_INCLUDE_LIBRESETPROP
1321 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1322#else
1323 return -2;
1324#endif
1325}
1326
bigbiffee7b7ff2020-03-23 15:08:27 -04001327void TWFunc::List_Mounts() {
1328 std::vector<std::string> mounts;
1329 read_file("/proc/mounts", mounts);
1330 LOGINFO("Mounts:\n");
1331 for (auto&& mount: mounts) {
1332 LOGINFO("%s\n", mount.c_str());
1333 }
1334}
1335
bigbiffa957f072021-03-07 18:20:29 -05001336#ifdef TW_INCLUDE_CRYPTO
1337#ifdef USE_FSCRYPT_POLICY_V1
1338bool TWFunc::Get_Encryption_Policy(struct fscrypt_policy_v1 &policy, std::string path) {
1339#else
1340bool TWFunc::Get_Encryption_Policy(struct fscrypt_policy_v2 &policy, std::string path) {
1341#endif
bigbiff7ba75002020-04-11 20:47:09 -04001342 if (!TWFunc::Path_Exists(path)) {
1343 LOGERR("Unable to find %s to get policy\n", path.c_str());
1344 return false;
1345 }
1346 if (!fscrypt_policy_get_struct(path.c_str(), &policy)) {
1347 LOGERR("No policy set for path %s\n", path.c_str());
1348 return false;
1349 }
1350 return true;
1351}
1352
bigbiffa957f072021-03-07 18:20:29 -05001353#ifdef USE_FSCRYPT_POLICY_V1
1354bool TWFunc::Set_Encryption_Policy(std::string path, struct fscrypt_policy_v1 &policy) {
1355#else
1356bool TWFunc::Set_Encryption_Policy(std::string path, struct fscrypt_policy_v2 &policy) {
1357#endif
bigbiff7ba75002020-04-11 20:47:09 -04001358 if (!TWFunc::Path_Exists(path)) {
1359 LOGERR("unable to find %s to set policy\n", path.c_str());
1360 return false;
1361 }
1362 uint8_t binary_policy[FS_KEY_DESCRIPTOR_SIZE];
bigbiffa957f072021-03-07 18:20:29 -05001363 char policy_hex[FSCRYPT_KEY_IDENTIFIER_HEX_SIZE];
1364 bytes_to_hex(binary_policy, FS_KEY_DESCRIPTOR_SIZE, policy_hex);
bigbiff7ba75002020-04-11 20:47:09 -04001365 if (!fscrypt_policy_set_struct(path.c_str(), &policy)) {
1366 LOGERR("unable to set policy for path: %s\n", path.c_str());
1367 return false;
1368 }
1369 return true;
1370}
bigbiffa957f072021-03-07 18:20:29 -05001371#endif
epicXa721f952021-01-04 13:01:31 +05301372
1373string TWFunc::Check_For_TwrpFolder() {
1374 string oldFolder = "";
1375 vector<string> customTWRPFolders;
1376 string mainPath = DataManager::GetCurrentStoragePath();
1377 DIR* d;
1378 struct dirent* de;
1379
epicX11e90832021-03-01 00:02:57 +05301380 if (DataManager::GetIntValue(TW_IS_ENCRYPTED)) {
epicXa721f952021-01-04 13:01:31 +05301381 goto exit;
1382 }
1383
1384
1385 d = opendir(mainPath.c_str());
1386 if (d == NULL) {
1387 goto exit;
1388 }
1389
1390 while ((de = readdir(d)) != NULL) {
1391 string name = de->d_name;
1392 string fullPath = mainPath + '/' + name;
1393 unsigned char type = de->d_type;
1394
epicX11e90832021-03-01 00:02:57 +05301395 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301396
epicX11e90832021-03-01 00:02:57 +05301397 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301398 type = Get_D_Type_From_Stat(fullPath);
1399 }
1400
epicX11e90832021-03-01 00:02:57 +05301401 if (type == DT_DIR && Path_Exists(fullPath + '/' + TW_SETTINGS_FILE)) {
1402 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301403 oldFolder = name;
1404 } else {
1405 customTWRPFolders.push_back(name);
1406 }
1407 }
1408 }
1409
1410 closedir(d);
1411
epicX11e90832021-03-01 00:02:57 +05301412 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301413 LOGINFO("No recovery folder found. Using default folder.\n");
1414 goto exit;
epicX11e90832021-03-01 00:02:57 +05301415 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301416 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1417 goto exit;
1418 } else {
epicX11e90832021-03-01 00:02:57 +05301419 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301420 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1421 } else {
1422 LOGINFO("One custom recovery folder found.\n");
1423 }
1424 string customPath = '/' + customTWRPFolders.at(0);
1425
epicX11e90832021-03-01 00:02:57 +05301426 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301427 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1428 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1429
epicX11e90832021-03-01 00:02:57 +05301430 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301431 vector<string> backups;
1432 d = opendir(oldBackupFolder.c_str());
1433
1434 if (d != NULL) {
1435 while ((de = readdir(d)) != NULL) {
1436 string name = de->d_name;
1437 unsigned char type = de->d_type;
1438
epicX11e90832021-03-01 00:02:57 +05301439 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301440
epicX11e90832021-03-01 00:02:57 +05301441 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301442 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1443 }
1444
epicX11e90832021-03-01 00:02:57 +05301445 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301446 backups.push_back(name);
1447 }
1448 }
1449 closedir(d);
1450 }
1451
epicX11e90832021-03-01 00:02:57 +05301452 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301453 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1454 }
1455 }
1456 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1457 }
1458
1459 return customPath;
1460 }
1461
1462exit:
1463 return TW_DEFAULT_RECOVERY_FOLDER;
1464}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001465#endif // ndef BUILD_TWRPTAR_MAIN