blob: 0f7ebb39cc1d5cdd59166ec0fbe7c94a0bcf3a13 [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>
bigbiff22851b92021-09-01 16:46:57 -040041
42#include <android-base/strings.h>
43
Dees_Troy38bd7602012-09-14 13:33:53 -040044#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000045#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060046#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060047#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040048#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060049#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040050#include "variables.h"
bigbiffdf8436b2020-08-30 16:22:34 -040051#include "bootloader_message/include/bootloader_message/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000052#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050053#include "cutils/android_reboot.h"
54#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060055#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000056#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
57 #include "openaes/inc/oaes_lib.h"
58#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050059#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040060
Dees_Troyb05ddee2013-01-28 20:24:50 +000061extern "C" {
62 #include "libcrecovery/common.h"
63}
64
Chaosmaster461e39f2020-02-07 01:48:13 +010065#ifdef TW_INCLUDE_LIBRESETPROP
66 #include <resetprop.h>
67#endif
68
bigbiff bigbiff19874f12019-01-08 20:06:57 -050069struct selabel_handle *selinux_handle;
70
bigbiff bigbiff9c754052013-01-09 09:09:08 -050071/* Execute a command */
bigbiffad58e1b2020-07-06 20:24:34 -040072int TWFunc::Exec_Cmd(const string& cmd, string &result, bool combine_stderr) {
Dees_Troy29a06352013-08-24 12:06:47 +000073 FILE* exec;
74 char buffer[130];
75 int ret = 0;
bigbiffad58e1b2020-07-06 20:24:34 -040076 std::string popen_cmd = cmd;
77 if (combine_stderr)
78 popen_cmd = cmd + " 2>&1";
79 exec = __popen(popen_cmd.c_str(), "r");
80
Matt Mowera8a89d12016-12-30 18:10:37 -060081 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000082 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050083 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000084 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050085 }
Dees_Troy29a06352013-08-24 12:06:47 +000086 ret = __pclose(exec);
87 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050088}
89
Ethan Yonker7e941582019-03-22 08:18:21 -050090int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020091 pid_t pid;
92 int status;
93 switch(pid = fork())
94 {
95 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050096 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020097 return -1;
98 case 0: // child
bigbiffad58e1b2020-07-06 20:24:34 -040099 execl("/system/bin/sh", "sh", "-c", cmd.c_str(), NULL);
Vojtech Bocek05534202013-09-11 08:11:56 +0200100 _exit(127);
101 break;
102 default:
103 {
Ethan Yonker7e941582019-03-22 08:18:21 -0500104 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +0200105 return -1;
106 else
107 return 0;
108 }
109 }
110}
111
Dees_Troy38bd7602012-09-14 13:33:53 -0400112// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600113string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400114 size_t pos = Path.find_last_of("/");
115 if (pos != string::npos) {
116 string Filename;
117 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
118 return Filename;
119 } else
120 return Path;
121}
122
123// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600124string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400125 size_t pos = Path.find_last_of("/");
126 if (pos != string::npos) {
127 string Pathonly;
128 Pathonly = Path.substr(0, pos + 1);
129 return Pathonly;
130 } else
131 return Path;
132}
133
Ethan Yonker7e941582019-03-22 08:18:21 -0500134int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600135 pid_t rc_pid;
136
137 rc_pid = waitpid(pid, status, 0);
138 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100139 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500140 if (Show_Errors)
141 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 -0600142 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100143 } else if (WEXITSTATUS(*status) == 0) {
144 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
145 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500146 if (Show_Errors)
147 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 -0600148 return -1;
149 }
150 } else { // no PID returned
151 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200152 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600153 else {
that2252d242015-04-03 22:33:04 +0200154 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600155 return -1;
156 }
157 }
158 return 0;
159}
160
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600161int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
162 pid_t retpid = waitpid(pid, status, WNOHANG);
163 for (; retpid == 0 && timeout; --timeout) {
164 sleep(1);
165 retpid = waitpid(pid, status, WNOHANG);
166 }
167 if (retpid == 0 && timeout == 0) {
168 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
169 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600170 for (timeout = 5; retpid == 0 && timeout; --timeout) {
171 sleep(1);
172 retpid = waitpid(pid, status, WNOHANG);
173 }
174 if (retpid)
175 LOGINFO("Child process killed successfully\n");
176 else
177 LOGINFO("Child process took too long to kill, may be a zombie process\n");
178 return -1;
179 } else if (retpid > 0) {
180 if (WIFSIGNALED(*status)) {
181 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
182 return -1;
183 }
184 } else if (retpid < 0) { // no PID returned
185 if (errno == ECHILD)
186 LOGERR("%s no child process exist\n", Child_Name.c_str());
187 else {
188 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
189 return -1;
190 }
191 }
192 return 0;
193}
194
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600195bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600196 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400197 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600198}
199
bigbiffce8f83c2015-12-12 18:30:21 -0500200Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600201 string::size_type i = 0;
202 int firstbyte = 0, secondbyte = 0;
203 char header[3];
204
205 ifstream f;
206 f.open(fn.c_str(), ios::in | ios::binary);
207 f.get(header, 3);
208 f.close();
209 firstbyte = header[i] & 0xff;
210 secondbyte = header[++i] & 0xff;
211
212 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500213 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600214 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500215 return ENCRYPTED;
216 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600217}
218
219int TWFunc::Try_Decrypting_File(string fn, string password) {
220#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
221 OAES_CTX * ctx = NULL;
222 uint8_t _key_data[32] = "";
223 FILE *f;
224 uint8_t buffer[4096];
225 uint8_t *buffer_out = NULL;
226 uint8_t *ptr = NULL;
227 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600228 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600229 size_t _j = 0;
230 size_t _key_data_len = 0;
231
232 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600233 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600234 _key_data[_j] = _j + 1;
235 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600236 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600237 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600238 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600239 _key_data_len = 24;
240 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600241 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600242 memcpy(_key_data, password.c_str(), password.size());
243
244 ctx = oaes_alloc();
245 if (ctx == NULL) {
246 LOGERR("Failed to allocate OAES\n");
247 return -1;
248 }
249
250 oaes_key_import_data(ctx, _key_data, _key_data_len);
251
252 f = fopen(fn.c_str(), "rb");
253 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500254 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500255 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600256 return -1;
257 }
258 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
259 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500260 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600261 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500262 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600263 return -1;
264 }
265 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
266 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
267 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500268 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600269 return -1;
270 }
271 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
272 if (buffer_out == NULL) {
273 LOGERR("Failed to allocate output buffer for try decrypt.\n");
274 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500275 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600276 return -1;
277 }
278 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
279 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
280 fclose(f);
281 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500282 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600283 return 0;
284 }
285 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500286 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600287 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500288 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600289 free(buffer_out);
290 return 1; // Decrypted successfully
291 }
292 ptr = buffer_out;
293 firstbyte = *ptr & 0xff;
294 ptr++;
295 secondbyte = *ptr & 0xff;
296 if (firstbyte == 0x1f && secondbyte == 0x8b) {
297 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
298 free(buffer_out);
299 return 3; // Compressed
300 }
301 if (out_len >= 262) {
302 ptr = buffer_out + 257;
303 if (strncmp((char*)ptr, "ustar", 5) == 0) {
304 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
305 free(buffer_out);
306 return 2; // Tar
307 }
308 }
309 free(buffer_out);
310 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
311 return 1; // Decrypted successfully
312#else
313 LOGERR("Encrypted backup support not included.\n");
314 return -1;
315#endif
316}
317
Ethan Yonker472f5062016-02-25 13:47:30 -0600318unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600319 struct stat st;
320
321 if (stat(Path.c_str(), &st) != 0)
322 return 0;
323 return st.st_size;
324}
325
bigbiffee7b7ff2020-03-23 15:08:27 -0400326std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
327 std::string res;
328 size_t pos = path.find_first_of("/");
329 if (pos != std::string::npos) {
330 res = path.substr(pos+1);
331 }
332 return res;
333}
334
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100335std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
336{
337 std::string res;
338 size_t last_idx = 0, idx = 0;
339
Matt Mowera8a89d12016-12-30 18:10:37 -0600340 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100341 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600342 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100343 res += '/';
344
345 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600346 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100347 res += path.substr(last_idx, idx);
348 break;
349 }
350
351 res += path.substr(last_idx, idx-last_idx);
352 last_idx = path.find_first_not_of('/', idx);
353 }
354
Matt Mowera8a89d12016-12-30 18:10:37 -0600355 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100356 res += '/';
357 return res;
358}
359
Matt Mower2416a502016-04-12 19:54:46 -0500360void TWFunc::Strip_Quotes(char* &str) {
361 if (strlen(str) > 0 && str[0] == '\"')
362 str++;
363 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
364 str[strlen(str)-1] = 0;
365}
366
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500367vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
368 vector<string> res;
369
370 if (in.empty() || del == '\0')
371 return res;
372
373 string field;
374 istringstream f(in);
375 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600376 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500377 if (field.empty() && skip_empty)
378 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600379 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500380 }
381 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600382 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500383 if (field.empty() && skip_empty)
384 continue;
385 res.push_back(field);
386 }
387 }
388 return res;
389}
390
Ethan Yonker472f5062016-02-25 13:47:30 -0600391timespec TWFunc::timespec_diff(timespec& start, timespec& end)
392{
393 timespec temp;
394 if ((end.tv_nsec-start.tv_nsec)<0) {
395 temp.tv_sec = end.tv_sec-start.tv_sec-1;
396 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
397 } else {
398 temp.tv_sec = end.tv_sec-start.tv_sec;
399 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
400 }
401 return temp;
402}
403
404int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
405{
406 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
407 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
408}
409
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600410#ifndef BUILD_TWRPTAR_MAIN
411
Dees_Troy38bd7602012-09-14 13:33:53 -0400412// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600413string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400414 string Local_Path = Path;
415
416 // Make sure that we have a leading slash
417 if (Local_Path.substr(0, 1) != "/")
418 Local_Path = "/" + Local_Path;
419
420 // Trim the path to get the root path only
421 size_t position = Local_Path.find("/", 2);
422 if (position != string::npos) {
423 Local_Path.resize(position);
424 }
425 return Local_Path;
426}
427
Dees_Troy43d8b002012-09-17 16:00:01 -0400428int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100429 std::vector<std::string> parts = Split_String(Path, "/", true);
430 std::string cur_path;
431 for (size_t i = 0; i < parts.size(); ++i) {
432 cur_path += "/" + parts[i];
433 if (!TWFunc::Path_Exists(cur_path)) {
434 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600435 gui_msg(Msg(msg::kError, "create_folder_strerr=Can not create '{1}' folder ({2}).")(cur_path)(strerror(errno)));
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600436 return false;
437 } else {
thatf1408b32016-01-03 11:09:15 +0100438 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600439 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400440 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400441 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400442 return true;
443}
444
Dees_Troyb46a6842012-09-25 11:06:46 -0400445void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
446 string Display_Text;
447
448 DataManager::GetValue(Read_Value, Display_Text);
449 if (Display_Text.empty())
450 Display_Text = Default_Text;
451
452 DataManager::SetValue("tw_operation", Display_Text);
453 DataManager::SetValue("tw_partition", "");
454}
455
456void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
457 string Display_Text;
458
459 DataManager::GetValue(Read_Value, Display_Text);
460 if (Display_Text.empty())
461 Display_Text = Default_Text;
462
463 DataManager::SetValue("tw_operation", Display_Text);
464 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400465}
466
Dees_Troy2673cec2013-04-02 20:22:16 +0000467void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400468 int logPipe[2];
469 int pigz_pid;
470 int destination_fd;
471 std::string destLogBuffer;
472
Dees Troy9d7fdf52013-09-19 20:49:25 +0000473 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400474
475 size_t extPos = Destination.find(".gz");
476 std::string uncompressedLog(Destination);
477 uncompressedLog.replace(extPos, Destination.length(), "");
478
479 if (Path_Exists(Destination)) {
480 Archive_Type type = Get_File_Type(Destination);
481 if (type == COMPRESSED) {
482 std::string destFileBuffer;
483 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400484 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400485 LOGINFO("Unable to get destination logfile contents.\n");
486 return;
487 }
488 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600489 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400490 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500491 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400492 std::stringstream uncompressedSS;
493 uncompressedSS << uncompressedIfs.rdbuf();
494 uncompressedIfs.close();
495 std::string uncompressedLogBuffer(uncompressedSS.str());
496 destLogBuffer.append(uncompressedLogBuffer);
497 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600498 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400499
bigbiffd3317052019-12-22 16:05:12 -0500500 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400501 std::stringstream ss;
502 ss << ifs.rdbuf();
503 std::string srcLogBuffer(ss.str());
504 ifs.close();
505
506 if (pipe(logPipe) < 0) {
507 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
508 }
509
510 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
511
512 pigz_pid = fork();
513 if (pigz_pid < 0) {
514 LOGINFO("fork() failed\n");
515 close(destination_fd);
516 close(logPipe[0]);
517 close(logPipe[1]);
518 } else if (pigz_pid == 0) {
519 close(logPipe[1]);
520 dup2(logPipe[0], fileno(stdin));
521 dup2(destination_fd, fileno(stdout));
522 if (execlp("pigz", "pigz", "-", NULL) < 0) {
523 close(destination_fd);
524 close(logPipe[0]);
525 _exit(-1);
526 }
527 } else {
528 close(logPipe[0]);
529 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
530 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
531 close(logPipe[1]);
532 close(destination_fd);
533 return;
534 }
535 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
536 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
537 close(logPipe[1]);
538 close(destination_fd);
539 return;
540 }
541 close(logPipe[1]);
542 }
543 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400544}
545
Dees_Troy2673cec2013-04-02 20:22:16 +0000546void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400547 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500548
bigbiff25d25b92020-06-19 16:07:38 -0400549 if (get_log_dir() == CACHE_LOGS_DIR) {
550 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
551 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000552 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000553 }
Dees_Troya58bead2012-09-27 09:49:29 -0400554
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500555 if (!TWFunc::Path_Exists(recoveryDir)) {
556 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400557 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500558 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
559 }
560 }
561
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400562 std::string logCopy = recoveryDir + "log.gz";
563 std::string lastLogCopy = recoveryDir + "last_log.gz";
Ethan Yonker5f3b8f02021-08-16 15:10:10 -0500564 copy_file(logCopy, lastLogCopy, 0600);
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500565 Copy_Log(TMP_LOG_FILE, logCopy);
566 chown(logCopy.c_str(), 1000, 1000);
567 chmod(logCopy.c_str(), 0600);
568 chmod(lastLogCopy.c_str(), 0640);
569
bigbiff25d25b92020-06-19 16:07:38 -0400570 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500571 if (PartitionManager.Mount_By_Path("/cache", false)) {
572 if (unlink("/cache/recovery/command") && errno != ENOENT) {
573 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
574 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000575 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500576 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000577 sync();
578}
579
bigbiffdf8436b2020-08-30 16:22:34 -0400580void TWFunc::Clear_Bootloader_Message() {
581 std::string err;
582 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100583 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400584 }
585}
586
Dees_Troy2673cec2013-04-02 20:22:16 +0000587void TWFunc::Update_Intent_File(string Intent) {
588 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600589 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000590 }
Dees_Troya58bead2012-09-27 09:49:29 -0400591}
592
593// reboot: Reboot the system. Return -1 on error, no return on success
594int TWFunc::tw_reboot(RebootCommand command)
595{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500596 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400597 Update_Log_File();
598
Dees_Troya58bead2012-09-27 09:49:29 -0400599 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600600 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400601
Dees_Troy2673cec2013-04-02 20:22:16 +0000602 switch (command) {
603 case rb_current:
604 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000605 Update_Intent_File("s");
606 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400607 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500608#ifdef ANDROID_RB_PROPERTY
609 return property_set(ANDROID_RB_PROPERTY, "reboot,");
610#elif defined(ANDROID_RB_RESTART)
611 return android_reboot(ANDROID_RB_RESTART, 0, 0);
612#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000613 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500614#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000615 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400616 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500617 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000618 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400619 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500620 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000621 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400622 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500623#ifdef ANDROID_RB_PROPERTY
624 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
625#elif defined(ANDROID_RB_POWEROFF)
626 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
627#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000628 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500629#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000630 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400631 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500632 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200633 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400634 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200635 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400636 case rb_fastboot:
637 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000638 default:
639 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600640 }
641 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400642}
643
644void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
645{
646 // Check for and run startup script if script exists
647 struct stat st;
648 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500649 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500650 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200651 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500652 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400653 }
Dees_Troy3477d712012-09-27 15:44:01 -0400654}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500655
656int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000657 DIR *d = opendir(path.c_str());
658 int r = 0;
659 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500660
Dees_Troyce675462013-01-09 19:48:21 +0000661 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500662 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000663 return -1;
664 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500665
Dees_Troyce675462013-01-09 19:48:21 +0000666 if (d) {
667 struct dirent *p;
668 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000669 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
670 continue;
671 new_path = path + "/";
672 new_path.append(p->d_name);
673 if (p->d_type == DT_DIR) {
674 r = removeDir(new_path, true);
675 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500676 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500677 r = rmdir(new_path.c_str());
678 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000679 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500680 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500681 } 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 +0000682 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000683 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000684 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000685 }
Dees_Troyce675462013-01-09 19:48:21 +0000686 }
687 }
688 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500689
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500690 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500691 if (skipParent)
692 return 0;
693 else
694 r = rmdir(path.c_str());
695 }
Dees_Troyce675462013-01-09 19:48:21 +0000696 }
697 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500698}
699
bigbiff22851b92021-09-01 16:46:57 -0400700int TWFunc::copy_file(string src, string dst, int mode, bool mount_paths) {
701 if (mount_paths) {
702 PartitionManager.Mount_By_Path(src, false);
703 PartitionManager.Mount_By_Path(dst, false);
704 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400705 if (!Path_Exists(src)) {
bigbiff22851b92021-09-01 16:46:57 -0400706 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 -0400707 return -1;
708 }
bigbiffd3317052019-12-22 16:05:12 -0500709 std::ifstream srcfile(src.c_str(), ios::binary);
710 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500711 dstfile << srcfile.rdbuf();
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400712 if (!dstfile.bad()) {
713 LOGINFO("Copied file %s to %s\n", src.c_str(), dst.c_str());
714 }
715 else {
716 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
717 return -1;
718 }
719
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500720 srcfile.close();
721 dstfile.close();
bigbiff22851b92021-09-01 16:46:57 -0400722 if (chmod(dst.c_str(), mode) != 0) {
723 LOGERR("Unable to chmod file: %s. Error: %s\n", dst.c_str(), strerror(errno));
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500724 return -1;
bigbiff22851b92021-09-01 16:46:57 -0400725 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500726 return 0;
727}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000728
729unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
730 struct stat st;
731
732 stat(Path.c_str(), &st);
733 if (st.st_mode & S_IFDIR)
734 return DT_DIR;
735 else if (st.st_mode & S_IFBLK)
736 return DT_BLK;
737 else if (st.st_mode & S_IFCHR)
738 return DT_CHR;
739 else if (st.st_mode & S_IFIFO)
740 return DT_FIFO;
741 else if (st.st_mode & S_IFLNK)
742 return DT_LNK;
743 else if (st.st_mode & S_IFREG)
744 return DT_REG;
745 else if (st.st_mode & S_IFSOCK)
746 return DT_SOCK;
747 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000748}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500749
750int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200751 ifstream file;
752 file.open(fn.c_str(), ios::in);
753
754 if (file.is_open()) {
bigbiff22851b92021-09-01 16:46:57 -0400755 std::string line;
756 while (std::getline(file, line)) {
757 results += line;
758 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200759 file.close();
760 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500761 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200762
763 LOGINFO("Cannot find file %s\n", fn.c_str());
764 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500765}
766
767int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500768 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500769 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500770 file.open(fn.c_str(), ios::in);
771 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500772 while (getline(file, line))
773 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500774 file.close();
775 return 0;
776 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000777 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500778 return -1;
779}
780
xNUTxe85f02d2014-07-18 01:30:58 +0200781int TWFunc::read_file(string fn, uint64_t& results) {
782 ifstream file;
783 file.open(fn.c_str(), ios::in);
784
785 if (file.is_open()) {
786 file >> results;
787 file.close();
788 return 0;
789 }
790
791 LOGINFO("Cannot find file %s\n", fn.c_str());
792 return -1;
793}
794
bigbiff22851b92021-09-01 16:46:57 -0400795bool TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500796 FILE *file;
797 file = fopen(fn.c_str(), "w");
798 if (file != NULL) {
799 fwrite(line.c_str(), line.size(), 1, file);
800 fclose(file);
bigbiff22851b92021-09-01 16:46:57 -0400801 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500802 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000803 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff22851b92021-09-01 16:46:57 -0400804 return false;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500805}
806
bigbiff22851b92021-09-01 16:46:57 -0400807bool TWFunc::write_to_file(const string& fn, const std::vector<string> lines) {
808 FILE *file;
809 file = fopen(fn.c_str(), "a+");
810 if (file != NULL) {
811 for (auto&& line: lines) {
812 fwrite(line.c_str(), line.size(), 1, file);
813 fwrite("\n", sizeof(char), 1, file);
814 }
815 fclose(file);
816 return true;
817 }
818 return false;
819}
820
821
Dees_Troy83bd4832013-05-04 12:39:56 +0000822bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
823 DIR* d;
824
825 string Filename;
826 Restore_Path += "/";
827 d = opendir(Restore_Path.c_str());
828 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500829 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000830 return false;
831 }
832
833 struct dirent* de;
834 while ((de = readdir(d)) != NULL) {
835 Filename = Restore_Path;
836 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500837 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000838 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
839 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
840 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
841 closedir(d);
842 return false;
843 }
844 }
845 }
846 closedir(d);
847 return true;
848}
849
Dees Troyb21cc642013-09-10 17:36:41 +0000850string TWFunc::Get_Current_Date() {
851 string Current_Date;
852 time_t seconds = time(0);
853 struct tm *t = localtime(&seconds);
854 char timestamp[255];
855 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);
856 Current_Date = timestamp;
857 return Current_Date;
858}
859
Ethan Yonkerb5557892014-02-07 21:43:20 -0600860string TWFunc::System_Property_Get(string Prop_Name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100861 return System_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path());
862}
863
864string TWFunc::System_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point) {
865 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000866 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600867 string propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100868 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600869 return propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100870 string prop_file = Mount_Point + "/build.prop";
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600871 if (!TWFunc::Path_Exists(prop_file))
Chaosmaster65633a42020-02-05 15:24:09 +0100872 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 -0600873 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback9d6feb52018-07-27 10:05:24 -0400874 LOGINFO("Unable to open build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200875 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000876 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100877 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600878 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000879 }
880 int line_count = buildprop.size();
881 int index;
882 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600883 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000884 for (index = 0; index < line_count; index++) {
885 end_pos = buildprop.at(index).find("=", start_pos);
886 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600887 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000888 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600889 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100890 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600891 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000892 }
893 }
Dees Troyb21cc642013-09-10 17:36:41 +0000894 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100895 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600896 return propvalue;
897}
898
899void TWFunc::Auto_Generate_Backup_Name() {
900 string propvalue = System_Property_Get("ro.build.display.id");
901 if (propvalue.empty()) {
902 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
903 return;
904 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400905 else {
906 //remove periods from build display so it doesn't confuse the extension code
907 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
908 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600909 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500910 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600911 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
912 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
913 // Trailing spaces cause problems on some file systems, so remove them
914 string space_check, space = " ";
915 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
916 while (space_check == space) {
917 Backup_Name.resize(Backup_Name.size() - 1);
918 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
919 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500920 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600921 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
922 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600923 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600924 } else {
925 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600926 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200927}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100928
nkk7198fc3992017-12-16 16:26:42 +0200929void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100930{
931#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200932 static bool fixed = false;
933 if (fixed)
934 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200935
936 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
937
938 struct timeval tv;
939 uint64_t offset = 0;
940 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
941
942 if (TWFunc::read_file(sepoch, offset) == 0) {
943
944 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
945
946 tv.tv_sec = offset;
947 tv.tv_usec = 0;
948 settimeofday(&tv, NULL);
949
950 gettimeofday(&tv, NULL);
951
Phoenix59146b05f22018-02-03 06:41:08 +0000952 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 +0200953
954 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200955 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200956 return;
957
958 }
959
960 } else {
961
962 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
963
964 }
965
Ethan Yonker9132d912015-02-02 10:32:49 -0600966 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200967
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100968 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
969 // They never set it, it just ticks forward from 1970-01-01 00:00,
970 // and then they have files /data/system/time/ats_* with 64bit offset
971 // in miliseconds which, when added to the RTC, gives the correct time.
972 // So, the time is: (offset_from_ats + value_from_RTC)
973 // There are multiple ats files, they are for different systems? Bases?
974 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
975 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
976
nkk7198fc3992017-12-16 16:26:42 +0200977 std::vector<std::string> paths; // space separated list of paths
978 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +0100979 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +0200980 if (!PartitionManager.Mount_By_Path("/data", false))
981 return;
982 } else {
983 // When specific path(s) are used, Fixup_Time needs those
984 // partitions to already be mounted!
985 paths = Split_String(time_paths, " ");
986 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100987
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100988 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200989 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100990 struct dirent *dt;
991 std::string ats_path;
992
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100993 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
994 // - it is the one for ATS_TOD (time of day?).
995 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +0200996 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100997 {
nkk7198fc3992017-12-16 16:26:42 +0200998 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -0600999 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001000 continue;
1001
Matt Mowera8a89d12016-12-30 18:10:37 -06001002 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001003 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001004 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001005 continue;
1006
Matt Mowera8a89d12016-12-30 18:10:37 -06001007 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001008 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001009 }
1010
1011 closedir(d);
1012 }
1013
nkk7198fc3992017-12-16 16:26:42 +02001014 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001015 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001016 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001017 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001018 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001019 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001020 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001021 } else {
1022 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001023
nkk7198fc3992017-12-16 16:26:42 +02001024 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1025 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1026 fixed = true;
1027 }
1028
1029 if (!fixed) {
1030 // Failed to get offset from ats file, check twrp settings
1031 unsigned long long value;
1032 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1033 return;
1034 } else {
1035 offset = (uint64_t) value;
1036 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1037 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1038 }
1039 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001040
1041 gettimeofday(&tv, NULL);
1042
1043 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001044#ifdef TW_CLOCK_OFFSET
1045// Some devices are even quirkier and have ats files that are offset from the actual time
1046 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1047#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001048 tv.tv_usec += (offset%1000)*1000;
1049
Matt Mowera8a89d12016-12-30 18:10:37 -06001050 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001051 {
1052 ++tv.tv_sec;
1053 tv.tv_usec -= 1000000;
1054 }
1055
1056 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001057
1058 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001059#endif
1060}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001061
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001062std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1063{
1064 std::vector<std::string> res;
1065 size_t idx = 0, idx_last = 0;
1066
Matt Mowera8a89d12016-12-30 18:10:37 -06001067 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001068 {
1069 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001070 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001071 idx = str.size();
1072
Matt Mowera8a89d12016-12-30 18:10:37 -06001073 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001074 res.push_back(str.substr(idx_last, idx-idx_last));
1075
1076 idx_last = idx + delimiter.size();
1077 }
1078
1079 return res;
1080}
1081
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001082bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1083{
1084 std::vector<std::string> parts = Split_String(path, "/");
1085 std::string cur_path;
1086 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001087 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001088 {
1089 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001090 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001091 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001092 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001093 return false;
1094 chown(cur_path.c_str(), uid, gid);
1095 }
1096 }
1097 return true;
1098}
1099
xNUTxe85f02d2014-07-18 01:30:58 +02001100int TWFunc::Set_Brightness(std::string brightness_value)
1101{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001102 int result = -1;
1103 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001104
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001105 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001106 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001107 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001108 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1109 if (!secondary_brightness_file.empty()) {
1110 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001111 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001112 }
xNUTxe85f02d2014-07-18 01:30:58 +02001113 }
bigbiff22851b92021-09-01 16:46:57 -04001114 return result ? 0 : -1;
xNUTxe85f02d2014-07-18 01:30:58 +02001115}
1116
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001117bool TWFunc::Toggle_MTP(bool enable) {
1118#ifdef TW_HAS_MTP
1119 static int was_enabled = false;
1120
1121 if (enable && was_enabled) {
1122 if (!PartitionManager.Enable_MTP())
1123 PartitionManager.Disable_MTP();
1124 } else {
1125 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1126 PartitionManager.Disable_MTP();
1127 usleep(500);
1128 }
1129 return was_enabled;
1130#else
1131 return false;
1132#endif
1133}
1134
Tom Hite5a926722014-09-15 01:31:03 +00001135void TWFunc::SetPerformanceMode(bool mode) {
1136 if (mode) {
1137 property_set("recovery.perf.mode", "1");
1138 } else {
1139 property_set("recovery.perf.mode", "0");
1140 }
1141 // Some time for events to catch up to init handlers
1142 usleep(500000);
1143}
1144
Jenkins1710bf22014-10-02 20:22:21 -04001145std::string TWFunc::to_string(unsigned long value) {
1146 std::ostringstream os;
1147 os << value;
1148 return os.str();
1149}
1150
Ethan Yonker9132d912015-02-02 10:32:49 -06001151void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001152 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001153 // Disable flashing of stock recovery
1154 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1155 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001156 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 -06001157 sync();
1158 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001159 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001160 }
1161}
1162
Ethan Yonker483e9f42016-01-11 22:21:18 -06001163unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1164 unsigned long block_device_size;
1165 int ret = 0;
1166
1167 int fd = open(block_device, O_RDONLY);
1168 if (fd < 0) {
1169 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1170 } else {
1171 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1172 close(fd);
1173 if (ret) {
1174 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1175 } else {
1176 return (unsigned long long)(block_device_size) * 512LLU;
1177 }
1178 }
1179 return 0;
1180}
1181
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001182void TWFunc::copy_kernel_log(string curr_storage) {
1183 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001184 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001185
1186 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001187 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001188 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001189 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1190 tw_set_default_metadata(dmesgDst.c_str());
1191}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001192
Captain Throwback52978932021-09-05 15:11:07 -04001193void TWFunc::copy_logcat(string curr_storage) {
1194 std::string logcatDst = curr_storage + "/logcat.txt";
1195 std::string logcatCmd = "logcat -d";
1196
1197 std::string result;
1198 Exec_Cmd(logcatCmd, result, false);
1199 write_to_file(logcatDst, result);
1200 gui_msg(Msg("copy_logcat=Copied logcat to {1}")(logcatDst));
1201 tw_set_default_metadata(logcatDst.c_str());
1202}
1203
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001204bool TWFunc::isNumber(string strtocheck) {
1205 int num = 0;
1206 std::istringstream iss(strtocheck);
1207
1208 if (!(iss >> num).fail())
1209 return true;
1210 else
1211 return false;
1212}
1213
1214int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001215 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001216 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1217 int ret = TWFunc::Exec_Cmd(cmd);
1218 if (ret != 0)
1219 return -1;
1220 return ret;
1221}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001222
bigbiff25d25b92020-06-19 16:07:38 -04001223std::string TWFunc::get_log_dir() {
1224 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1225 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001226 LOGINFO("Unable to find a directory to store TWRP logs.");
1227 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001228 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001229 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001230 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001231 }
1232 else {
bigbiff25d25b92020-06-19 16:07:38 -04001233 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001234 }
1235}
1236
1237void TWFunc::check_selinux_support() {
1238 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1239 if (TWFunc::Path_Exists("/file_contexts")) {
1240 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1241 rename("/file_contexts", "/file_contexts.bak");
1242 }
1243 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1244 rename("/prebuilt_file_contexts", "/file_contexts");
1245 }
1246 struct selinux_opt selinux_options[] = {
1247 { SELABEL_OPT_PATH, "/file_contexts" }
1248 };
1249 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1250 if (!selinux_handle)
1251 printf("No file contexts for SELinux\n");
1252 else
1253 printf("SELinux contexts loaded from /file_contexts\n");
1254 { // Check to ensure SELinux can be supported by the kernel
1255 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001256 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001257 std::string se_context_check = cacheDir + "recovery/";
1258 int ret = 0;
1259
bigbiff25d25b92020-06-19 16:07:38 -04001260 if (cacheDir == CACHE_LOGS_DIR) {
1261 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001262 }
1263 if (TWFunc::Path_Exists(se_context_check)) {
1264 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001265 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001266 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1267 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001268 }
1269 }
1270 if (ret < 0) {
1271 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1272 } else {
1273 free(contexts);
1274 gui_msg("full_selinux=Full SELinux support is present.");
1275 }
1276 }
1277}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001278
1279bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001280 LOGINFO("checking for twrp app\n");
1281 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1282 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001283 bool is_system_mounted = true;
1284 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1285 is_system_mounted = false;
1286 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001287 }
Captain Throwback31c14922020-12-21 11:28:34 -05001288 string base_path = PartitionManager.Get_Android_Root_Path();
1289 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1290 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1291 string install_path = base_path + "/priv-app";
1292 if (!TWFunc::Path_Exists(install_path))
1293 install_path = base_path + "/app";
1294 install_path += "/twrpapp";
1295 if (TWFunc::Path_Exists(install_path)) {
1296 LOGINFO("App found at '%s'\n", install_path.c_str());
1297 DataManager::SetValue("tw_app_installed_in_system", 1);
1298 return true;
1299 }
1300 if (!is_system_mounted)
1301 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001302 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001303 }
1304 DataManager::SetValue("tw_app_installed_in_system", 0);
1305 return false;
1306}
Chaosmaster461e39f2020-02-07 01:48:13 +01001307
epicX271bb3a2020-12-30 01:03:18 +05301308void TWFunc::checkforapp(){
1309
1310 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1311 int sdkver = 0;
1312 if (!sdkverstr.empty()) {
1313 sdkver = atoi(sdkverstr.c_str());
1314 }
1315 if (sdkver <= 13) {
1316 if (sdkver == 0)
1317 LOGINFO("Unable to read sdk version from build prop\n");
1318 else
1319 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1320 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1321 goto exit;
1322 }
1323 if (Is_TWRP_App_In_System()) {
1324 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1325 goto exit;
1326 }
1327 if (PartitionManager.Mount_By_Path("/data", false)) {
1328 const char parent_path[] = "/data/app";
1329 const char app_prefix[] = "me.twrp.twrpapp-";
1330 DIR *d = opendir(parent_path);
1331 if (d) {
1332 struct dirent *p;
1333 while ((p = readdir(d))) {
1334 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1335 continue;
1336 closedir(d);
1337 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1338 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1339 goto exit;
1340 }
1341 closedir(d);
1342 }
1343 } else {
1344 LOGINFO("Data partition cannot be mounted during app check\n");
1345 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1346 }
1347
1348 LOGINFO("App not installed\n");
1349 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1350exit:
1351 return;
1352
1353}
1354
Chaosmaster461e39f2020-02-07 01:48:13 +01001355int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1356#ifdef TW_INCLUDE_LIBRESETPROP
1357 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1358#else
1359 return -2;
1360#endif
1361}
1362
bigbiffee7b7ff2020-03-23 15:08:27 -04001363void TWFunc::List_Mounts() {
1364 std::vector<std::string> mounts;
1365 read_file("/proc/mounts", mounts);
1366 LOGINFO("Mounts:\n");
1367 for (auto&& mount: mounts) {
1368 LOGINFO("%s\n", mount.c_str());
1369 }
1370}
1371
bigbiffa957f072021-03-07 18:20:29 -05001372#ifdef TW_INCLUDE_CRYPTO
1373#ifdef USE_FSCRYPT_POLICY_V1
1374bool TWFunc::Get_Encryption_Policy(struct fscrypt_policy_v1 &policy, std::string path) {
1375#else
1376bool TWFunc::Get_Encryption_Policy(struct fscrypt_policy_v2 &policy, std::string path) {
1377#endif
bigbiff7ba75002020-04-11 20:47:09 -04001378 if (!TWFunc::Path_Exists(path)) {
1379 LOGERR("Unable to find %s to get policy\n", path.c_str());
1380 return false;
1381 }
1382 if (!fscrypt_policy_get_struct(path.c_str(), &policy)) {
1383 LOGERR("No policy set for path %s\n", path.c_str());
1384 return false;
1385 }
1386 return true;
1387}
1388
bigbiffa957f072021-03-07 18:20:29 -05001389#ifdef USE_FSCRYPT_POLICY_V1
1390bool TWFunc::Set_Encryption_Policy(std::string path, struct fscrypt_policy_v1 &policy) {
1391#else
1392bool TWFunc::Set_Encryption_Policy(std::string path, struct fscrypt_policy_v2 &policy) {
1393#endif
bigbiff7ba75002020-04-11 20:47:09 -04001394 if (!TWFunc::Path_Exists(path)) {
1395 LOGERR("unable to find %s to set policy\n", path.c_str());
1396 return false;
1397 }
1398 uint8_t binary_policy[FS_KEY_DESCRIPTOR_SIZE];
bigbiffa957f072021-03-07 18:20:29 -05001399 char policy_hex[FSCRYPT_KEY_IDENTIFIER_HEX_SIZE];
1400 bytes_to_hex(binary_policy, FS_KEY_DESCRIPTOR_SIZE, policy_hex);
bigbiff7ba75002020-04-11 20:47:09 -04001401 if (!fscrypt_policy_set_struct(path.c_str(), &policy)) {
1402 LOGERR("unable to set policy for path: %s\n", path.c_str());
1403 return false;
1404 }
1405 return true;
1406}
bigbiffa957f072021-03-07 18:20:29 -05001407#endif
epicXa721f952021-01-04 13:01:31 +05301408
1409string TWFunc::Check_For_TwrpFolder() {
1410 string oldFolder = "";
1411 vector<string> customTWRPFolders;
1412 string mainPath = DataManager::GetCurrentStoragePath();
1413 DIR* d;
1414 struct dirent* de;
1415
epicX11e90832021-03-01 00:02:57 +05301416 if (DataManager::GetIntValue(TW_IS_ENCRYPTED)) {
epicXa721f952021-01-04 13:01:31 +05301417 goto exit;
1418 }
1419
1420
1421 d = opendir(mainPath.c_str());
1422 if (d == NULL) {
1423 goto exit;
1424 }
1425
1426 while ((de = readdir(d)) != NULL) {
1427 string name = de->d_name;
1428 string fullPath = mainPath + '/' + name;
1429 unsigned char type = de->d_type;
1430
epicX11e90832021-03-01 00:02:57 +05301431 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301432
epicX11e90832021-03-01 00:02:57 +05301433 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301434 type = Get_D_Type_From_Stat(fullPath);
1435 }
1436
epicX11e90832021-03-01 00:02:57 +05301437 if (type == DT_DIR && Path_Exists(fullPath + '/' + TW_SETTINGS_FILE)) {
1438 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301439 oldFolder = name;
1440 } else {
1441 customTWRPFolders.push_back(name);
1442 }
1443 }
1444 }
1445
1446 closedir(d);
1447
epicX11e90832021-03-01 00:02:57 +05301448 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301449 LOGINFO("No recovery folder found. Using default folder.\n");
1450 goto exit;
epicX11e90832021-03-01 00:02:57 +05301451 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301452 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1453 goto exit;
1454 } else {
epicX11e90832021-03-01 00:02:57 +05301455 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301456 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1457 } else {
1458 LOGINFO("One custom recovery folder found.\n");
1459 }
1460 string customPath = '/' + customTWRPFolders.at(0);
1461
epicX11e90832021-03-01 00:02:57 +05301462 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301463 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1464 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1465
epicX11e90832021-03-01 00:02:57 +05301466 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301467 vector<string> backups;
1468 d = opendir(oldBackupFolder.c_str());
1469
1470 if (d != NULL) {
1471 while ((de = readdir(d)) != NULL) {
1472 string name = de->d_name;
1473 unsigned char type = de->d_type;
1474
epicX11e90832021-03-01 00:02:57 +05301475 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301476
epicX11e90832021-03-01 00:02:57 +05301477 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301478 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1479 }
1480
epicX11e90832021-03-01 00:02:57 +05301481 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301482 backups.push_back(name);
1483 }
1484 }
1485 closedir(d);
1486 }
1487
epicX11e90832021-03-01 00:02:57 +05301488 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301489 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1490 }
1491 }
1492 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1493 }
1494
1495 return customPath;
1496 }
1497
1498exit:
1499 return TW_DEFAULT_RECOVERY_FOLDER;
1500}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001501#endif // ndef BUILD_TWRPTAR_MAIN