blob: 30d7b560bad4b7335c47b8b170e93e65f8e9970c [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>
Adithya Ra327aa72021-12-19 00:49:54 +053041#include <thread>
bigbiff22851b92021-09-01 16:46:57 -040042
43#include <android-base/strings.h>
Adithya Ra327aa72021-12-19 00:49:54 +053044#include <android-base/chrono_utils.h>
bigbiff22851b92021-09-01 16:46:57 -040045
Dees_Troy38bd7602012-09-14 13:33:53 -040046#include "twrp-functions.hpp"
Darth98f775972022-08-05 09:39:03 +010047#include "abx-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000048#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060049#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060050#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040051#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060052#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040053#include "variables.h"
bigbiffdf8436b2020-08-30 16:22:34 -040054#include "bootloader_message/include/bootloader_message/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000055#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050056#include "cutils/android_reboot.h"
57#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060058#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000059#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
60 #include "openaes/inc/oaes_lib.h"
61#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050062#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040063
Dees_Troyb05ddee2013-01-28 20:24:50 +000064extern "C" {
65 #include "libcrecovery/common.h"
66}
67
Chaosmaster461e39f2020-02-07 01:48:13 +010068#ifdef TW_INCLUDE_LIBRESETPROP
bigbiffa05d32c2021-12-25 15:43:34 -050069 #include <resetprop.hpp>
Chaosmaster461e39f2020-02-07 01:48:13 +010070#endif
71
bigbiff bigbiff19874f12019-01-08 20:06:57 -050072struct selabel_handle *selinux_handle;
73
bigbiff bigbiff9c754052013-01-09 09:09:08 -050074/* Execute a command */
bigbiffad58e1b2020-07-06 20:24:34 -040075int TWFunc::Exec_Cmd(const string& cmd, string &result, bool combine_stderr) {
Dees_Troy29a06352013-08-24 12:06:47 +000076 FILE* exec;
77 char buffer[130];
78 int ret = 0;
bigbiffad58e1b2020-07-06 20:24:34 -040079 std::string popen_cmd = cmd;
80 if (combine_stderr)
81 popen_cmd = cmd + " 2>&1";
82 exec = __popen(popen_cmd.c_str(), "r");
83
Matt Mowera8a89d12016-12-30 18:10:37 -060084 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000085 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050086 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000087 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050088 }
Dees_Troy29a06352013-08-24 12:06:47 +000089 ret = __pclose(exec);
90 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050091}
92
Ethan Yonker7e941582019-03-22 08:18:21 -050093int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020094 pid_t pid;
95 int status;
96 switch(pid = fork())
97 {
98 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050099 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +0200100 return -1;
101 case 0: // child
bigbiffad58e1b2020-07-06 20:24:34 -0400102 execl("/system/bin/sh", "sh", "-c", cmd.c_str(), NULL);
Vojtech Bocek05534202013-09-11 08:11:56 +0200103 _exit(127);
104 break;
105 default:
106 {
Ethan Yonker7e941582019-03-22 08:18:21 -0500107 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +0200108 return -1;
109 else
110 return 0;
111 }
112 }
113}
114
Dees_Troy38bd7602012-09-14 13:33:53 -0400115// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600116string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400117 size_t pos = Path.find_last_of("/");
118 if (pos != string::npos) {
119 string Filename;
120 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
121 return Filename;
122 } else
123 return Path;
124}
125
126// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600127string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400128 size_t pos = Path.find_last_of("/");
129 if (pos != string::npos) {
130 string Pathonly;
131 Pathonly = Path.substr(0, pos + 1);
132 return Pathonly;
133 } else
134 return Path;
135}
136
Ethan Yonker7e941582019-03-22 08:18:21 -0500137int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600138 pid_t rc_pid;
139
140 rc_pid = waitpid(pid, status, 0);
141 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100142 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500143 if (Show_Errors)
144 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 -0600145 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100146 } else if (WEXITSTATUS(*status) == 0) {
147 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
148 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500149 if (Show_Errors)
150 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 -0600151 return -1;
152 }
153 } else { // no PID returned
154 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200155 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600156 else {
that2252d242015-04-03 22:33:04 +0200157 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600158 return -1;
159 }
160 }
161 return 0;
162}
163
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600164int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
165 pid_t retpid = waitpid(pid, status, WNOHANG);
166 for (; retpid == 0 && timeout; --timeout) {
167 sleep(1);
168 retpid = waitpid(pid, status, WNOHANG);
169 }
170 if (retpid == 0 && timeout == 0) {
171 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
172 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600173 for (timeout = 5; retpid == 0 && timeout; --timeout) {
174 sleep(1);
175 retpid = waitpid(pid, status, WNOHANG);
176 }
177 if (retpid)
178 LOGINFO("Child process killed successfully\n");
179 else
180 LOGINFO("Child process took too long to kill, may be a zombie process\n");
181 return -1;
182 } else if (retpid > 0) {
183 if (WIFSIGNALED(*status)) {
184 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
185 return -1;
186 }
187 } else if (retpid < 0) { // no PID returned
188 if (errno == ECHILD)
189 LOGERR("%s no child process exist\n", Child_Name.c_str());
190 else {
191 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
192 return -1;
193 }
194 }
195 return 0;
196}
197
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600198bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600199 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400200 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600201}
202
bigbiffce8f83c2015-12-12 18:30:21 -0500203Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600204 string::size_type i = 0;
205 int firstbyte = 0, secondbyte = 0;
206 char header[3];
207
208 ifstream f;
209 f.open(fn.c_str(), ios::in | ios::binary);
210 f.get(header, 3);
211 f.close();
212 firstbyte = header[i] & 0xff;
213 secondbyte = header[++i] & 0xff;
214
215 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500216 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600217 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500218 return ENCRYPTED;
219 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600220}
221
222int TWFunc::Try_Decrypting_File(string fn, string password) {
223#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
224 OAES_CTX * ctx = NULL;
225 uint8_t _key_data[32] = "";
226 FILE *f;
227 uint8_t buffer[4096];
228 uint8_t *buffer_out = NULL;
229 uint8_t *ptr = NULL;
230 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600231 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600232 size_t _j = 0;
233 size_t _key_data_len = 0;
234
235 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600236 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600237 _key_data[_j] = _j + 1;
238 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600239 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600240 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600241 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600242 _key_data_len = 24;
243 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600244 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600245 memcpy(_key_data, password.c_str(), password.size());
246
247 ctx = oaes_alloc();
248 if (ctx == NULL) {
249 LOGERR("Failed to allocate OAES\n");
250 return -1;
251 }
252
253 oaes_key_import_data(ctx, _key_data, _key_data_len);
254
255 f = fopen(fn.c_str(), "rb");
256 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500257 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500258 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600259 return -1;
260 }
261 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
262 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500263 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600264 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 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
269 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
270 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500271 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600272 return -1;
273 }
274 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
275 if (buffer_out == NULL) {
276 LOGERR("Failed to allocate output buffer for try decrypt.\n");
277 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500278 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600279 return -1;
280 }
281 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
282 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
283 fclose(f);
284 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500285 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600286 return 0;
287 }
288 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500289 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600290 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500291 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600292 free(buffer_out);
293 return 1; // Decrypted successfully
294 }
295 ptr = buffer_out;
296 firstbyte = *ptr & 0xff;
297 ptr++;
298 secondbyte = *ptr & 0xff;
299 if (firstbyte == 0x1f && secondbyte == 0x8b) {
300 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
301 free(buffer_out);
302 return 3; // Compressed
303 }
304 if (out_len >= 262) {
305 ptr = buffer_out + 257;
306 if (strncmp((char*)ptr, "ustar", 5) == 0) {
307 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
308 free(buffer_out);
309 return 2; // Tar
310 }
311 }
312 free(buffer_out);
313 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
314 return 1; // Decrypted successfully
315#else
316 LOGERR("Encrypted backup support not included.\n");
317 return -1;
318#endif
319}
320
Ethan Yonker472f5062016-02-25 13:47:30 -0600321unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600322 struct stat st;
323
324 if (stat(Path.c_str(), &st) != 0)
325 return 0;
326 return st.st_size;
327}
328
bigbiffee7b7ff2020-03-23 15:08:27 -0400329std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
330 std::string res;
331 size_t pos = path.find_first_of("/");
332 if (pos != std::string::npos) {
333 res = path.substr(pos+1);
334 }
335 return res;
336}
337
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100338std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
339{
340 std::string res;
341 size_t last_idx = 0, idx = 0;
342
Matt Mowera8a89d12016-12-30 18:10:37 -0600343 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100344 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600345 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100346 res += '/';
347
348 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600349 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100350 res += path.substr(last_idx, idx);
351 break;
352 }
353
354 res += path.substr(last_idx, idx-last_idx);
355 last_idx = path.find_first_not_of('/', idx);
356 }
357
Matt Mowera8a89d12016-12-30 18:10:37 -0600358 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100359 res += '/';
360 return res;
361}
362
Matt Mower2416a502016-04-12 19:54:46 -0500363void TWFunc::Strip_Quotes(char* &str) {
364 if (strlen(str) > 0 && str[0] == '\"')
365 str++;
366 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
367 str[strlen(str)-1] = 0;
368}
369
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500370vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
371 vector<string> res;
372
373 if (in.empty() || del == '\0')
374 return res;
375
376 string field;
377 istringstream f(in);
378 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600379 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500380 if (field.empty() && skip_empty)
381 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600382 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500383 }
384 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600385 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500386 if (field.empty() && skip_empty)
387 continue;
388 res.push_back(field);
389 }
390 }
391 return res;
392}
393
Ethan Yonker472f5062016-02-25 13:47:30 -0600394timespec TWFunc::timespec_diff(timespec& start, timespec& end)
395{
396 timespec temp;
397 if ((end.tv_nsec-start.tv_nsec)<0) {
398 temp.tv_sec = end.tv_sec-start.tv_sec-1;
399 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
400 } else {
401 temp.tv_sec = end.tv_sec-start.tv_sec;
402 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
403 }
404 return temp;
405}
406
407int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
408{
409 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
410 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
411}
412
Adithya Ra327aa72021-12-19 00:49:54 +0530413bool TWFunc::Wait_For_File(const string& path, std::chrono::nanoseconds timeout) {
414 android::base::Timer t;
415 while (t.duration() < timeout) {
416 struct stat sb;
417 if (stat(path.c_str(), &sb) != -1) {
418 return true;
419 }
420 std::this_thread::sleep_for(10ms);
421 }
422 return false;
423}
424
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600425#ifndef BUILD_TWRPTAR_MAIN
426
Dees_Troy38bd7602012-09-14 13:33:53 -0400427// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600428string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400429 string Local_Path = Path;
430
431 // Make sure that we have a leading slash
432 if (Local_Path.substr(0, 1) != "/")
433 Local_Path = "/" + Local_Path;
434
435 // Trim the path to get the root path only
436 size_t position = Local_Path.find("/", 2);
437 if (position != string::npos) {
438 Local_Path.resize(position);
439 }
440 return Local_Path;
441}
442
Dees_Troy43d8b002012-09-17 16:00:01 -0400443int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100444 std::vector<std::string> parts = Split_String(Path, "/", true);
445 std::string cur_path;
446 for (size_t i = 0; i < parts.size(); ++i) {
447 cur_path += "/" + parts[i];
448 if (!TWFunc::Path_Exists(cur_path)) {
449 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600450 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 -0600451 return false;
452 } else {
thatf1408b32016-01-03 11:09:15 +0100453 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600454 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400455 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400456 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400457 return true;
458}
459
Dees_Troyb46a6842012-09-25 11:06:46 -0400460void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
461 string Display_Text;
462
463 DataManager::GetValue(Read_Value, Display_Text);
464 if (Display_Text.empty())
465 Display_Text = Default_Text;
466
467 DataManager::SetValue("tw_operation", Display_Text);
468 DataManager::SetValue("tw_partition", "");
469}
470
471void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
472 string Display_Text;
473
474 DataManager::GetValue(Read_Value, Display_Text);
475 if (Display_Text.empty())
476 Display_Text = Default_Text;
477
478 DataManager::SetValue("tw_operation", Display_Text);
479 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400480}
481
Dees_Troy2673cec2013-04-02 20:22:16 +0000482void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400483 int logPipe[2];
484 int pigz_pid;
485 int destination_fd;
486 std::string destLogBuffer;
487
Dees Troy9d7fdf52013-09-19 20:49:25 +0000488 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400489
490 size_t extPos = Destination.find(".gz");
491 std::string uncompressedLog(Destination);
492 uncompressedLog.replace(extPos, Destination.length(), "");
493
494 if (Path_Exists(Destination)) {
495 Archive_Type type = Get_File_Type(Destination);
496 if (type == COMPRESSED) {
497 std::string destFileBuffer;
498 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400499 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400500 LOGINFO("Unable to get destination logfile contents.\n");
501 return;
502 }
503 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600504 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400505 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500506 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400507 std::stringstream uncompressedSS;
508 uncompressedSS << uncompressedIfs.rdbuf();
509 uncompressedIfs.close();
510 std::string uncompressedLogBuffer(uncompressedSS.str());
511 destLogBuffer.append(uncompressedLogBuffer);
512 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600513 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400514
bigbiffd3317052019-12-22 16:05:12 -0500515 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400516 std::stringstream ss;
517 ss << ifs.rdbuf();
518 std::string srcLogBuffer(ss.str());
519 ifs.close();
520
521 if (pipe(logPipe) < 0) {
522 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
523 }
524
525 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
526
527 pigz_pid = fork();
528 if (pigz_pid < 0) {
529 LOGINFO("fork() failed\n");
530 close(destination_fd);
531 close(logPipe[0]);
532 close(logPipe[1]);
533 } else if (pigz_pid == 0) {
534 close(logPipe[1]);
535 dup2(logPipe[0], fileno(stdin));
536 dup2(destination_fd, fileno(stdout));
537 if (execlp("pigz", "pigz", "-", NULL) < 0) {
538 close(destination_fd);
539 close(logPipe[0]);
540 _exit(-1);
541 }
542 } else {
543 close(logPipe[0]);
544 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
545 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
546 close(logPipe[1]);
547 close(destination_fd);
548 return;
549 }
550 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
551 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
552 close(logPipe[1]);
553 close(destination_fd);
554 return;
555 }
556 close(logPipe[1]);
557 }
558 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400559}
560
Dees_Troy2673cec2013-04-02 20:22:16 +0000561void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400562 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500563
bigbiff25d25b92020-06-19 16:07:38 -0400564 if (get_log_dir() == CACHE_LOGS_DIR) {
565 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
566 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000567 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000568 }
Dees_Troya58bead2012-09-27 09:49:29 -0400569
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500570 if (!TWFunc::Path_Exists(recoveryDir)) {
571 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400572 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500573 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
574 }
575 }
576
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400577 std::string logCopy = recoveryDir + "log.gz";
578 std::string lastLogCopy = recoveryDir + "last_log.gz";
Ethan Yonker5f3b8f02021-08-16 15:10:10 -0500579 copy_file(logCopy, lastLogCopy, 0600);
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500580 Copy_Log(TMP_LOG_FILE, logCopy);
581 chown(logCopy.c_str(), 1000, 1000);
582 chmod(logCopy.c_str(), 0600);
583 chmod(lastLogCopy.c_str(), 0640);
584
bigbiff25d25b92020-06-19 16:07:38 -0400585 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500586 if (PartitionManager.Mount_By_Path("/cache", false)) {
587 if (unlink("/cache/recovery/command") && errno != ENOENT) {
588 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
589 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000590 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500591 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000592 sync();
593}
594
bigbiffdf8436b2020-08-30 16:22:34 -0400595void TWFunc::Clear_Bootloader_Message() {
596 std::string err;
597 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100598 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400599 }
600}
601
Dees_Troy2673cec2013-04-02 20:22:16 +0000602void TWFunc::Update_Intent_File(string Intent) {
603 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600604 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000605 }
Dees_Troya58bead2012-09-27 09:49:29 -0400606}
607
608// reboot: Reboot the system. Return -1 on error, no return on success
609int TWFunc::tw_reboot(RebootCommand command)
610{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500611 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400612 Update_Log_File();
613
Dees_Troya58bead2012-09-27 09:49:29 -0400614 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600615 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400616
Dees_Troy2673cec2013-04-02 20:22:16 +0000617 switch (command) {
618 case rb_current:
619 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000620 Update_Intent_File("s");
621 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400622 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500623#ifdef ANDROID_RB_PROPERTY
624 return property_set(ANDROID_RB_PROPERTY, "reboot,");
625#elif defined(ANDROID_RB_RESTART)
626 return android_reboot(ANDROID_RB_RESTART, 0, 0);
627#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000628 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500629#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000630 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400631 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500632 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000633 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400634 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500635 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000636 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400637 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500638#ifdef ANDROID_RB_PROPERTY
639 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
640#elif defined(ANDROID_RB_POWEROFF)
641 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
642#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000643 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500644#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000645 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400646 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500647 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200648 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400649 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200650 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400651 case rb_fastboot:
652 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000653 default:
654 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600655 }
656 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400657}
658
659void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
660{
661 // Check for and run startup script if script exists
662 struct stat st;
663 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500664 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500665 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200666 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500667 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400668 }
Dees_Troy3477d712012-09-27 15:44:01 -0400669}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500670
671int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000672 DIR *d = opendir(path.c_str());
673 int r = 0;
674 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500675
Dees_Troyce675462013-01-09 19:48:21 +0000676 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500677 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000678 return -1;
679 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500680
Dees_Troyce675462013-01-09 19:48:21 +0000681 if (d) {
682 struct dirent *p;
683 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000684 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
685 continue;
686 new_path = path + "/";
687 new_path.append(p->d_name);
688 if (p->d_type == DT_DIR) {
689 r = removeDir(new_path, true);
690 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500691 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500692 r = rmdir(new_path.c_str());
693 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000694 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500695 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500696 } 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 +0000697 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000698 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000699 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000700 }
Dees_Troyce675462013-01-09 19:48:21 +0000701 }
702 }
703 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500704
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500705 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500706 if (skipParent)
707 return 0;
708 else
709 r = rmdir(path.c_str());
710 }
Dees_Troyce675462013-01-09 19:48:21 +0000711 }
712 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500713}
714
bigbiff22851b92021-09-01 16:46:57 -0400715int TWFunc::copy_file(string src, string dst, int mode, bool mount_paths) {
716 if (mount_paths) {
717 PartitionManager.Mount_By_Path(src, false);
718 PartitionManager.Mount_By_Path(dst, false);
719 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400720 if (!Path_Exists(src)) {
bigbiff22851b92021-09-01 16:46:57 -0400721 LOGINFO("Path %s does not exist. Unable to copy file to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400722 return -1;
723 }
bigbiffd3317052019-12-22 16:05:12 -0500724 std::ifstream srcfile(src.c_str(), ios::binary);
725 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500726 dstfile << srcfile.rdbuf();
bigbiff850fa282021-10-09 12:37:29 -0400727 if (dstfile.bad()) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400728 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
729 return -1;
730 }
731
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500732 srcfile.close();
733 dstfile.close();
bigbiff22851b92021-09-01 16:46:57 -0400734 if (chmod(dst.c_str(), mode) != 0) {
735 LOGERR("Unable to chmod file: %s. Error: %s\n", dst.c_str(), strerror(errno));
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500736 return -1;
bigbiff22851b92021-09-01 16:46:57 -0400737 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500738 return 0;
739}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000740
741unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
742 struct stat st;
743
744 stat(Path.c_str(), &st);
745 if (st.st_mode & S_IFDIR)
746 return DT_DIR;
747 else if (st.st_mode & S_IFBLK)
748 return DT_BLK;
749 else if (st.st_mode & S_IFCHR)
750 return DT_CHR;
751 else if (st.st_mode & S_IFIFO)
752 return DT_FIFO;
753 else if (st.st_mode & S_IFLNK)
754 return DT_LNK;
755 else if (st.st_mode & S_IFREG)
756 return DT_REG;
757 else if (st.st_mode & S_IFSOCK)
758 return DT_SOCK;
759 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000760}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500761
762int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200763 ifstream file;
764 file.open(fn.c_str(), ios::in);
765
766 if (file.is_open()) {
bigbiff22851b92021-09-01 16:46:57 -0400767 std::string line;
768 while (std::getline(file, line)) {
769 results += line;
770 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200771 file.close();
772 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500773 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200774
775 LOGINFO("Cannot find file %s\n", fn.c_str());
776 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500777}
778
779int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500780 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500781 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500782 file.open(fn.c_str(), ios::in);
783 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500784 while (getline(file, line))
785 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500786 file.close();
787 return 0;
788 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000789 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500790 return -1;
791}
792
xNUTxe85f02d2014-07-18 01:30:58 +0200793int TWFunc::read_file(string fn, uint64_t& results) {
794 ifstream file;
795 file.open(fn.c_str(), ios::in);
796
797 if (file.is_open()) {
798 file >> results;
799 file.close();
800 return 0;
801 }
802
803 LOGINFO("Cannot find file %s\n", fn.c_str());
804 return -1;
805}
806
bigbiff22851b92021-09-01 16:46:57 -0400807bool TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500808 FILE *file;
809 file = fopen(fn.c_str(), "w");
810 if (file != NULL) {
811 fwrite(line.c_str(), line.size(), 1, file);
812 fclose(file);
bigbiff22851b92021-09-01 16:46:57 -0400813 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500814 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000815 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff22851b92021-09-01 16:46:57 -0400816 return false;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500817}
818
bigbiff22851b92021-09-01 16:46:57 -0400819bool TWFunc::write_to_file(const string& fn, const std::vector<string> lines) {
820 FILE *file;
821 file = fopen(fn.c_str(), "a+");
822 if (file != NULL) {
823 for (auto&& line: lines) {
824 fwrite(line.c_str(), line.size(), 1, file);
825 fwrite("\n", sizeof(char), 1, file);
826 }
827 fclose(file);
828 return true;
829 }
830 return false;
831}
832
833
Dees_Troy83bd4832013-05-04 12:39:56 +0000834bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
835 DIR* d;
836
837 string Filename;
838 Restore_Path += "/";
839 d = opendir(Restore_Path.c_str());
840 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500841 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000842 return false;
843 }
844
845 struct dirent* de;
846 while ((de = readdir(d)) != NULL) {
847 Filename = Restore_Path;
848 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500849 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000850 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
851 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
852 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
853 closedir(d);
854 return false;
855 }
856 }
857 }
858 closedir(d);
859 return true;
860}
861
Dees Troyb21cc642013-09-10 17:36:41 +0000862string TWFunc::Get_Current_Date() {
863 string Current_Date;
864 time_t seconds = time(0);
865 struct tm *t = localtime(&seconds);
866 char timestamp[255];
867 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);
868 Current_Date = timestamp;
869 return Current_Date;
870}
871
Ethan Yonkerb5557892014-02-07 21:43:20 -0600872string TWFunc::System_Property_Get(string Prop_Name) {
Captain Throwback1483a8e2022-01-03 09:52:06 -0500873 return Partition_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path(), "build.prop");
Chaosmaster65633a42020-02-05 15:24:09 +0100874}
875
Captain Throwback1483a8e2022-01-03 09:52:06 -0500876string TWFunc::Partition_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point, string prop_file_name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100877 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000878 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600879 string propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500880 string prop_file;
Chaosmaster65633a42020-02-05 15:24:09 +0100881 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600882 return propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500883 if (Mount_Point == PartitionManager.Get_Android_Root_Path()) {
884 prop_file = Mount_Point + "/system/" + prop_file_name;
885 } else {
886 prop_file = Mount_Point + "/" + prop_file_name;
887 }
Captain Throwback2b9ea722021-12-31 21:35:52 -0500888 if (!TWFunc::Path_Exists(prop_file)) {
889 LOGINFO("Unable to locate file: %s\n", prop_file.c_str());
890 return propvalue;
891 }
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600892 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback2b9ea722021-12-31 21:35:52 -0500893 LOGINFO("Unable to open %s for getting '%s'.\n", prop_file_name.c_str(), Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200894 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000895 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100896 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600897 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000898 }
899 int line_count = buildprop.size();
900 int index;
901 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600902 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000903 for (index = 0; index < line_count; index++) {
904 end_pos = buildprop.at(index).find("=", start_pos);
905 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600906 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000907 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600908 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100909 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600910 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000911 }
912 }
Dees Troyb21cc642013-09-10 17:36:41 +0000913 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100914 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600915 return propvalue;
916}
917
918void TWFunc::Auto_Generate_Backup_Name() {
919 string propvalue = System_Property_Get("ro.build.display.id");
920 if (propvalue.empty()) {
921 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
922 return;
923 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400924 else {
925 //remove periods from build display so it doesn't confuse the extension code
926 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
927 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600928 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500929 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600930 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
931 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
932 // Trailing spaces cause problems on some file systems, so remove them
933 string space_check, space = " ";
934 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
935 while (space_check == space) {
936 Backup_Name.resize(Backup_Name.size() - 1);
937 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
938 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500939 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600940 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
941 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600942 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600943 } else {
944 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600945 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200946}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100947
nkk7198fc3992017-12-16 16:26:42 +0200948void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100949{
950#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200951 static bool fixed = false;
952 if (fixed)
953 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200954
955 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
956
957 struct timeval tv;
958 uint64_t offset = 0;
959 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
960
961 if (TWFunc::read_file(sepoch, offset) == 0) {
962
963 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
964
965 tv.tv_sec = offset;
966 tv.tv_usec = 0;
967 settimeofday(&tv, NULL);
968
969 gettimeofday(&tv, NULL);
970
Phoenix59146b05f22018-02-03 06:41:08 +0000971 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 +0200972
973 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200974 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200975 return;
976
977 }
978
979 } else {
980
981 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
982
983 }
984
Ethan Yonker9132d912015-02-02 10:32:49 -0600985 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200986
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100987 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
988 // They never set it, it just ticks forward from 1970-01-01 00:00,
989 // and then they have files /data/system/time/ats_* with 64bit offset
990 // in miliseconds which, when added to the RTC, gives the correct time.
991 // So, the time is: (offset_from_ats + value_from_RTC)
992 // There are multiple ats files, they are for different systems? Bases?
993 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
994 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
995
nkk7198fc3992017-12-16 16:26:42 +0200996 std::vector<std::string> paths; // space separated list of paths
997 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +0100998 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +0200999 if (!PartitionManager.Mount_By_Path("/data", false))
1000 return;
1001 } else {
1002 // When specific path(s) are used, Fixup_Time needs those
1003 // partitions to already be mounted!
1004 paths = Split_String(time_paths, " ");
1005 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001006
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001007 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001008 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001009 struct dirent *dt;
1010 std::string ats_path;
1011
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001012 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1013 // - it is the one for ATS_TOD (time of day?).
1014 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001015 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001016 {
nkk7198fc3992017-12-16 16:26:42 +02001017 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001018 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001019 continue;
1020
Matt Mowera8a89d12016-12-30 18:10:37 -06001021 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001022 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001023 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001024 continue;
1025
Matt Mowera8a89d12016-12-30 18:10:37 -06001026 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001027 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001028 }
1029
1030 closedir(d);
1031 }
1032
nkk7198fc3992017-12-16 16:26:42 +02001033 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001034 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001035 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001036 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001037 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001038 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001039 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001040 } else {
1041 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001042
nkk7198fc3992017-12-16 16:26:42 +02001043 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1044 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1045 fixed = true;
1046 }
1047
1048 if (!fixed) {
Captain Throwbackf74fc052022-01-19 13:25:54 -05001049#ifdef TW_QCOM_ATS_OFFSET
1050 // Offset is the difference between the current time and the time since_epoch
1051 // To calculate the offset in Android, the following expression (from a root shell) can be used:
1052 // echo "$(( ($(date +%s) - $(cat /sys/class/rtc/rtc0/since_epoch)) ))"
1053 // Add 3 zeros to the output and use that in the TW_QCOM_ATS_OFFSET flag in your BoardConfig.mk
1054 // For example, if the result of the calculation is 1642433544, use 1642433544000 as the offset
1055 offset = (uint64_t) TW_QCOM_ATS_OFFSET;
1056 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1057 LOGINFO("TWFunc::Fixup_Time: Setting time offset from TW_QCOM_ATS_OFFSET, offset %llu\n", (unsigned long long) offset);
1058#else
nkk7198fc3992017-12-16 16:26:42 +02001059 // Failed to get offset from ats file, check twrp settings
1060 unsigned long long value;
1061 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1062 return;
1063 } else {
1064 offset = (uint64_t) value;
1065 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1066 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1067 }
Captain Throwbackf74fc052022-01-19 13:25:54 -05001068#endif
nkk7198fc3992017-12-16 16:26:42 +02001069 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001070
1071 gettimeofday(&tv, NULL);
1072
1073 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001074#ifdef TW_CLOCK_OFFSET
1075// Some devices are even quirkier and have ats files that are offset from the actual time
1076 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1077#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001078 tv.tv_usec += (offset%1000)*1000;
1079
Matt Mowera8a89d12016-12-30 18:10:37 -06001080 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001081 {
1082 ++tv.tv_sec;
1083 tv.tv_usec -= 1000000;
1084 }
1085
1086 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001087
1088 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001089#endif
1090}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001091
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001092std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1093{
1094 std::vector<std::string> res;
1095 size_t idx = 0, idx_last = 0;
1096
Matt Mowera8a89d12016-12-30 18:10:37 -06001097 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001098 {
1099 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001100 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001101 idx = str.size();
1102
Matt Mowera8a89d12016-12-30 18:10:37 -06001103 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001104 res.push_back(str.substr(idx_last, idx-idx_last));
1105
1106 idx_last = idx + delimiter.size();
1107 }
1108
1109 return res;
1110}
1111
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001112bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1113{
1114 std::vector<std::string> parts = Split_String(path, "/");
1115 std::string cur_path;
1116 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001117 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001118 {
1119 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001120 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001121 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001122 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001123 return false;
1124 chown(cur_path.c_str(), uid, gid);
1125 }
1126 }
1127 return true;
1128}
1129
xNUTxe85f02d2014-07-18 01:30:58 +02001130int TWFunc::Set_Brightness(std::string brightness_value)
1131{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001132 int result = -1;
1133 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001134
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001135 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001136 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001137 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001138 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1139 if (!secondary_brightness_file.empty()) {
1140 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001141 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001142 }
xNUTxe85f02d2014-07-18 01:30:58 +02001143 }
bigbiff22851b92021-09-01 16:46:57 -04001144 return result ? 0 : -1;
xNUTxe85f02d2014-07-18 01:30:58 +02001145}
1146
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001147bool TWFunc::Toggle_MTP(bool enable) {
1148#ifdef TW_HAS_MTP
1149 static int was_enabled = false;
1150
1151 if (enable && was_enabled) {
1152 if (!PartitionManager.Enable_MTP())
1153 PartitionManager.Disable_MTP();
1154 } else {
1155 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1156 PartitionManager.Disable_MTP();
1157 usleep(500);
1158 }
1159 return was_enabled;
1160#else
1161 return false;
1162#endif
1163}
1164
Tom Hite5a926722014-09-15 01:31:03 +00001165void TWFunc::SetPerformanceMode(bool mode) {
1166 if (mode) {
1167 property_set("recovery.perf.mode", "1");
1168 } else {
1169 property_set("recovery.perf.mode", "0");
1170 }
1171 // Some time for events to catch up to init handlers
1172 usleep(500000);
1173}
1174
Jenkins1710bf22014-10-02 20:22:21 -04001175std::string TWFunc::to_string(unsigned long value) {
1176 std::ostringstream os;
1177 os << value;
1178 return os.str();
1179}
1180
Ethan Yonker9132d912015-02-02 10:32:49 -06001181void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001182 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001183 // Disable flashing of stock recovery
1184 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1185 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001186 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 -06001187 sync();
1188 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001189 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001190 }
1191}
1192
Ethan Yonker483e9f42016-01-11 22:21:18 -06001193unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1194 unsigned long block_device_size;
1195 int ret = 0;
1196
1197 int fd = open(block_device, O_RDONLY);
1198 if (fd < 0) {
1199 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1200 } else {
1201 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1202 close(fd);
1203 if (ret) {
1204 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1205 } else {
1206 return (unsigned long long)(block_device_size) * 512LLU;
1207 }
1208 }
1209 return 0;
1210}
1211
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001212void TWFunc::copy_kernel_log(string curr_storage) {
1213 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001214 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001215
1216 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001217 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001218 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001219 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1220 tw_set_default_metadata(dmesgDst.c_str());
1221}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001222
Captain Throwback52978932021-09-05 15:11:07 -04001223void TWFunc::copy_logcat(string curr_storage) {
1224 std::string logcatDst = curr_storage + "/logcat.txt";
1225 std::string logcatCmd = "logcat -d";
1226
1227 std::string result;
1228 Exec_Cmd(logcatCmd, result, false);
1229 write_to_file(logcatDst, result);
1230 gui_msg(Msg("copy_logcat=Copied logcat to {1}")(logcatDst));
1231 tw_set_default_metadata(logcatDst.c_str());
1232}
1233
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001234bool TWFunc::isNumber(string strtocheck) {
1235 int num = 0;
1236 std::istringstream iss(strtocheck);
1237
1238 if (!(iss >> num).fail())
1239 return true;
1240 else
1241 return false;
1242}
1243
1244int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001245 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001246 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1247 int ret = TWFunc::Exec_Cmd(cmd);
1248 if (ret != 0)
1249 return -1;
1250 return ret;
1251}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001252
bigbiff25d25b92020-06-19 16:07:38 -04001253std::string TWFunc::get_log_dir() {
1254 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1255 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001256 LOGINFO("Unable to find a directory to store TWRP logs.");
1257 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001258 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001259 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001260 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001261 }
1262 else {
bigbiff25d25b92020-06-19 16:07:38 -04001263 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001264 }
1265}
1266
1267void TWFunc::check_selinux_support() {
1268 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1269 if (TWFunc::Path_Exists("/file_contexts")) {
1270 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1271 rename("/file_contexts", "/file_contexts.bak");
1272 }
1273 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1274 rename("/prebuilt_file_contexts", "/file_contexts");
1275 }
1276 struct selinux_opt selinux_options[] = {
1277 { SELABEL_OPT_PATH, "/file_contexts" }
1278 };
1279 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1280 if (!selinux_handle)
1281 printf("No file contexts for SELinux\n");
1282 else
1283 printf("SELinux contexts loaded from /file_contexts\n");
1284 { // Check to ensure SELinux can be supported by the kernel
1285 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001286 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001287 std::string se_context_check = cacheDir + "recovery/";
1288 int ret = 0;
1289
bigbiff25d25b92020-06-19 16:07:38 -04001290 if (cacheDir == CACHE_LOGS_DIR) {
1291 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001292 }
1293 if (TWFunc::Path_Exists(se_context_check)) {
1294 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001295 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001296 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1297 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001298 }
1299 }
1300 if (ret < 0) {
1301 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1302 } else {
1303 free(contexts);
1304 gui_msg("full_selinux=Full SELinux support is present.");
1305 }
1306 }
1307}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001308
1309bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001310 LOGINFO("checking for twrp app\n");
1311 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1312 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001313 bool is_system_mounted = true;
1314 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1315 is_system_mounted = false;
1316 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001317 }
Captain Throwback31c14922020-12-21 11:28:34 -05001318 string base_path = PartitionManager.Get_Android_Root_Path();
1319 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1320 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1321 string install_path = base_path + "/priv-app";
1322 if (!TWFunc::Path_Exists(install_path))
1323 install_path = base_path + "/app";
1324 install_path += "/twrpapp";
1325 if (TWFunc::Path_Exists(install_path)) {
1326 LOGINFO("App found at '%s'\n", install_path.c_str());
1327 DataManager::SetValue("tw_app_installed_in_system", 1);
1328 return true;
1329 }
1330 if (!is_system_mounted)
1331 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001332 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001333 }
1334 DataManager::SetValue("tw_app_installed_in_system", 0);
1335 return false;
1336}
Chaosmaster461e39f2020-02-07 01:48:13 +01001337
epicX271bb3a2020-12-30 01:03:18 +05301338void TWFunc::checkforapp(){
1339
1340 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1341 int sdkver = 0;
1342 if (!sdkverstr.empty()) {
1343 sdkver = atoi(sdkverstr.c_str());
1344 }
1345 if (sdkver <= 13) {
1346 if (sdkver == 0)
1347 LOGINFO("Unable to read sdk version from build prop\n");
1348 else
1349 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1350 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1351 goto exit;
1352 }
1353 if (Is_TWRP_App_In_System()) {
1354 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1355 goto exit;
1356 }
1357 if (PartitionManager.Mount_By_Path("/data", false)) {
1358 const char parent_path[] = "/data/app";
1359 const char app_prefix[] = "me.twrp.twrpapp-";
1360 DIR *d = opendir(parent_path);
1361 if (d) {
1362 struct dirent *p;
1363 while ((p = readdir(d))) {
1364 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1365 continue;
1366 closedir(d);
1367 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1368 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1369 goto exit;
1370 }
1371 closedir(d);
1372 }
1373 } else {
1374 LOGINFO("Data partition cannot be mounted during app check\n");
1375 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1376 }
1377
1378 LOGINFO("App not installed\n");
1379 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1380exit:
1381 return;
1382
1383}
1384
Chaosmaster461e39f2020-02-07 01:48:13 +01001385int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1386#ifdef TW_INCLUDE_LIBRESETPROP
1387 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1388#else
1389 return -2;
1390#endif
1391}
1392
bigbiffee7b7ff2020-03-23 15:08:27 -04001393void TWFunc::List_Mounts() {
1394 std::vector<std::string> mounts;
1395 read_file("/proc/mounts", mounts);
1396 LOGINFO("Mounts:\n");
1397 for (auto&& mount: mounts) {
1398 LOGINFO("%s\n", mount.c_str());
1399 }
1400}
1401
epicXa721f952021-01-04 13:01:31 +05301402string TWFunc::Check_For_TwrpFolder() {
1403 string oldFolder = "";
1404 vector<string> customTWRPFolders;
1405 string mainPath = DataManager::GetCurrentStoragePath();
1406 DIR* d;
1407 struct dirent* de;
1408
Fernando Oliveira4ef24232022-10-19 13:33:47 -03001409 if (DataManager::GetIntValue(TW_IS_ENCRYPTED) && DataManager::GetIntValue(TW_CRYPTO_PWTYPE)) {
epicXa721f952021-01-04 13:01:31 +05301410 goto exit;
1411 }
1412
1413
1414 d = opendir(mainPath.c_str());
1415 if (d == NULL) {
1416 goto exit;
1417 }
1418
1419 while ((de = readdir(d)) != NULL) {
1420 string name = de->d_name;
1421 string fullPath = mainPath + '/' + name;
1422 unsigned char type = de->d_type;
1423
epicX11e90832021-03-01 00:02:57 +05301424 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301425
epicX11e90832021-03-01 00:02:57 +05301426 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301427 type = Get_D_Type_From_Stat(fullPath);
1428 }
1429
Fernando Oliveira80c34602023-02-01 12:52:32 -03001430 if (type == DT_DIR && Path_Exists(fullPath + "/.twrpcf")) {
epicX11e90832021-03-01 00:02:57 +05301431 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301432 oldFolder = name;
1433 } else {
1434 customTWRPFolders.push_back(name);
1435 }
1436 }
1437 }
1438
1439 closedir(d);
1440
epicX11e90832021-03-01 00:02:57 +05301441 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301442 LOGINFO("No recovery folder found. Using default folder.\n");
Fernando Oliveira80c34602023-02-01 12:52:32 -03001443 //Creates the TWRP folder if it does not exist on the device and if the folder has not been changed to a new name
1444 mainPath += TW_DEFAULT_RECOVERY_FOLDER;
1445 mkdir(mainPath.c_str(), 0777);
epicXa721f952021-01-04 13:01:31 +05301446 goto exit;
epicX11e90832021-03-01 00:02:57 +05301447 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301448 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1449 goto exit;
1450 } else {
epicX11e90832021-03-01 00:02:57 +05301451 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301452 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1453 } else {
1454 LOGINFO("One custom recovery folder found.\n");
1455 }
1456 string customPath = '/' + customTWRPFolders.at(0);
1457
epicX11e90832021-03-01 00:02:57 +05301458 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301459 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1460 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1461
epicX11e90832021-03-01 00:02:57 +05301462 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301463 vector<string> backups;
1464 d = opendir(oldBackupFolder.c_str());
1465
1466 if (d != NULL) {
1467 while ((de = readdir(d)) != NULL) {
1468 string name = de->d_name;
1469 unsigned char type = de->d_type;
1470
epicX11e90832021-03-01 00:02:57 +05301471 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301472
epicX11e90832021-03-01 00:02:57 +05301473 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301474 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1475 }
1476
epicX11e90832021-03-01 00:02:57 +05301477 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301478 backups.push_back(name);
1479 }
1480 }
1481 closedir(d);
1482 }
1483
epicX11e90832021-03-01 00:02:57 +05301484 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301485 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1486 }
1487 }
1488 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1489 }
1490
1491 return customPath;
1492 }
1493
1494exit:
1495 return TW_DEFAULT_RECOVERY_FOLDER;
1496}
Darth98f775972022-08-05 09:39:03 +01001497
1498bool TWFunc::Check_Xml_Format(const std::string filename) {
1499 std::string buffer(' ', 4);
1500 std::string abx_hdr("ABX\x00", 4);
1501 std::ifstream File;
1502 File.open(filename);
1503 if (File.is_open()) {
1504 File.get(&buffer[0], buffer.size());
1505 File.close();
1506 // Android Binary Xml start from these bytes
1507 if(!buffer.compare(0, abx_hdr.size(), abx_hdr))
1508 return false; // ABX format - requires conversion
1509 }
1510 return true; // good format, possible to parse
1511}
1512
1513// return true=successful conversion (return the name of the converted file in "result");
1514// return false=an error happened (leave "result" alone)
1515bool TWFunc::abx_to_xml(const std::string path, std::string &result) {
1516 bool res = false;
1517 if (!TWFunc::Path_Exists(path))
1518 return res;
1519
1520 std::ifstream infile(path);
1521 if (!infile.is_open())
1522 return res;
1523
1524 std::string fname = TWFunc::Get_Filename(path);
1525 std::string tmp = "/tmp/converted_xml";
1526 if (!TWFunc::Path_Exists(tmp)) {
1527 if (mkdir(tmp.c_str(), 0777) != 0)
1528 tmp = "/tmp";
1529 }
1530
1531 std::string tmp_path = tmp + "/" + fname;
1532 std::ofstream outfile(tmp_path);
1533 if (!outfile.is_open()) {
1534 LOGINFO("Error. The abx conversion of %s has failed.\n", path.c_str());
1535 infile.close();
1536 return res;
1537 }
1538
1539 AbxToXml r(infile, outfile);
1540 if (r.run() && TWFunc::Path_Exists(tmp_path)) {
1541 res = true;
1542 result = tmp_path;
1543 }
1544
1545 infile.close();
1546 outfile.close();
1547
1548 return res;
1549}
1550
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001551#endif // ndef BUILD_TWRPTAR_MAIN