blob: 10a27f52255aa8b23c8b35a4ba9cf5f8aa9cd716 [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>
Mohd Faraz446ccbf2023-01-24 19:58:24 +010028#include <fstab/fstab.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050029#include <sys/mount.h>
Dees_Troya58bead2012-09-27 09:49:29 -040030#include <sys/reboot.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050031#include <sys/sendfile.h>
32#include <sys/stat.h>
33#include <sys/vfs.h>
Dees_Troy83bd4832013-05-04 12:39:56 +000034#include <sys/types.h>
35#include <sys/wait.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050036#include <iostream>
37#include <fstream>
Dees_Troy83bd4832013-05-04 12:39:56 +000038#include <sstream>
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -040039#include <cctype>
bigbiff74a6d0d2015-02-14 20:49:44 -050040#include <algorithm>
bigbiff bigbiff19874f12019-01-08 20:06:57 -050041#include <selinux/label.h>
Adithya Ra327aa72021-12-19 00:49:54 +053042#include <thread>
bigbiff22851b92021-09-01 16:46:57 -040043
44#include <android-base/strings.h>
Adithya Ra327aa72021-12-19 00:49:54 +053045#include <android-base/chrono_utils.h>
bigbiff22851b92021-09-01 16:46:57 -040046
Dees_Troy38bd7602012-09-14 13:33:53 -040047#include "twrp-functions.hpp"
Darth98f775972022-08-05 09:39:03 +010048#include "abx-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000049#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060050#include "gui/gui.hpp"
Mohd Faraz446ccbf2023-01-24 19:58:24 +010051#include <fs_mgr_priv_boot_config.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060052#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040053#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060054#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040055#include "variables.h"
bigbiffdf8436b2020-08-30 16:22:34 -040056#include "bootloader_message/include/bootloader_message/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000057#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050058#include "cutils/android_reboot.h"
59#include <sys/reboot.h>
Mohd Faraza57874b2023-09-30 00:57:58 +053060#include "gui/rapidxml.hpp"
61#include "gui/pages.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060062#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000063#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
64 #include "openaes/inc/oaes_lib.h"
65#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050066#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040067
Dees_Troyb05ddee2013-01-28 20:24:50 +000068extern "C" {
69 #include "libcrecovery/common.h"
70}
71
Chaosmaster461e39f2020-02-07 01:48:13 +010072#ifdef TW_INCLUDE_LIBRESETPROP
bigbiffa05d32c2021-12-25 15:43:34 -050073 #include <resetprop.hpp>
Chaosmaster461e39f2020-02-07 01:48:13 +010074#endif
75
bigbiff bigbiff19874f12019-01-08 20:06:57 -050076struct selabel_handle *selinux_handle;
77
bigbiff bigbiff9c754052013-01-09 09:09:08 -050078/* Execute a command */
bigbiffad58e1b2020-07-06 20:24:34 -040079int TWFunc::Exec_Cmd(const string& cmd, string &result, bool combine_stderr) {
Dees_Troy29a06352013-08-24 12:06:47 +000080 FILE* exec;
81 char buffer[130];
82 int ret = 0;
bigbiffad58e1b2020-07-06 20:24:34 -040083 std::string popen_cmd = cmd;
84 if (combine_stderr)
85 popen_cmd = cmd + " 2>&1";
86 exec = __popen(popen_cmd.c_str(), "r");
87
Matt Mowera8a89d12016-12-30 18:10:37 -060088 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000089 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050090 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000091 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050092 }
Dees_Troy29a06352013-08-24 12:06:47 +000093 ret = __pclose(exec);
94 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050095}
96
Ethan Yonker7e941582019-03-22 08:18:21 -050097int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020098 pid_t pid;
99 int status;
100 switch(pid = fork())
101 {
102 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -0500103 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +0200104 return -1;
105 case 0: // child
bigbiffad58e1b2020-07-06 20:24:34 -0400106 execl("/system/bin/sh", "sh", "-c", cmd.c_str(), NULL);
Vojtech Bocek05534202013-09-11 08:11:56 +0200107 _exit(127);
108 break;
109 default:
110 {
Ethan Yonker7e941582019-03-22 08:18:21 -0500111 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +0200112 return -1;
113 else
114 return 0;
115 }
116 }
117}
118
Dees_Troy38bd7602012-09-14 13:33:53 -0400119// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600120string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400121 size_t pos = Path.find_last_of("/");
122 if (pos != string::npos) {
123 string Filename;
124 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
125 return Filename;
126 } else
127 return Path;
128}
129
130// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600131string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400132 size_t pos = Path.find_last_of("/");
133 if (pos != string::npos) {
134 string Pathonly;
135 Pathonly = Path.substr(0, pos + 1);
136 return Pathonly;
137 } else
138 return Path;
139}
140
Ethan Yonker7e941582019-03-22 08:18:21 -0500141int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600142 pid_t rc_pid;
143
144 rc_pid = waitpid(pid, status, 0);
145 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100146 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500147 if (Show_Errors)
148 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 -0600149 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100150 } else if (WEXITSTATUS(*status) == 0) {
151 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
152 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500153 if (Show_Errors)
154 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 -0600155 return -1;
156 }
157 } else { // no PID returned
158 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200159 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600160 else {
that2252d242015-04-03 22:33:04 +0200161 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600162 return -1;
163 }
164 }
165 return 0;
166}
167
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600168int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
169 pid_t retpid = waitpid(pid, status, WNOHANG);
170 for (; retpid == 0 && timeout; --timeout) {
171 sleep(1);
172 retpid = waitpid(pid, status, WNOHANG);
173 }
174 if (retpid == 0 && timeout == 0) {
175 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
176 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600177 for (timeout = 5; retpid == 0 && timeout; --timeout) {
178 sleep(1);
179 retpid = waitpid(pid, status, WNOHANG);
180 }
181 if (retpid)
182 LOGINFO("Child process killed successfully\n");
183 else
184 LOGINFO("Child process took too long to kill, may be a zombie process\n");
185 return -1;
186 } else if (retpid > 0) {
187 if (WIFSIGNALED(*status)) {
188 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
189 return -1;
190 }
191 } else if (retpid < 0) { // no PID returned
192 if (errno == ECHILD)
193 LOGERR("%s no child process exist\n", Child_Name.c_str());
194 else {
195 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
196 return -1;
197 }
198 }
199 return 0;
200}
201
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600202bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600203 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400204 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600205}
206
bigbiffce8f83c2015-12-12 18:30:21 -0500207Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600208 string::size_type i = 0;
209 int firstbyte = 0, secondbyte = 0;
210 char header[3];
211
212 ifstream f;
213 f.open(fn.c_str(), ios::in | ios::binary);
214 f.get(header, 3);
215 f.close();
216 firstbyte = header[i] & 0xff;
217 secondbyte = header[++i] & 0xff;
218
219 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500220 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600221 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500222 return ENCRYPTED;
223 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600224}
225
226int TWFunc::Try_Decrypting_File(string fn, string password) {
227#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
228 OAES_CTX * ctx = NULL;
229 uint8_t _key_data[32] = "";
230 FILE *f;
231 uint8_t buffer[4096];
232 uint8_t *buffer_out = NULL;
233 uint8_t *ptr = NULL;
234 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600235 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600236 size_t _j = 0;
237 size_t _key_data_len = 0;
238
239 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600240 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600241 _key_data[_j] = _j + 1;
242 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600243 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600244 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600245 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600246 _key_data_len = 24;
247 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600248 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600249 memcpy(_key_data, password.c_str(), password.size());
250
251 ctx = oaes_alloc();
252 if (ctx == NULL) {
253 LOGERR("Failed to allocate OAES\n");
254 return -1;
255 }
256
257 oaes_key_import_data(ctx, _key_data, _key_data_len);
258
259 f = fopen(fn.c_str(), "rb");
260 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500261 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500262 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600263 return -1;
264 }
265 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
266 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500267 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600268 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500269 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600270 return -1;
271 }
272 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
273 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\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 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
279 if (buffer_out == NULL) {
280 LOGERR("Failed to allocate output buffer for try decrypt.\n");
281 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500282 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600283 return -1;
284 }
285 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
286 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
287 fclose(f);
288 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500289 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600290 return 0;
291 }
292 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500293 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600294 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500295 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600296 free(buffer_out);
297 return 1; // Decrypted successfully
298 }
299 ptr = buffer_out;
300 firstbyte = *ptr & 0xff;
301 ptr++;
302 secondbyte = *ptr & 0xff;
303 if (firstbyte == 0x1f && secondbyte == 0x8b) {
304 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
305 free(buffer_out);
306 return 3; // Compressed
307 }
308 if (out_len >= 262) {
309 ptr = buffer_out + 257;
310 if (strncmp((char*)ptr, "ustar", 5) == 0) {
311 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
312 free(buffer_out);
313 return 2; // Tar
314 }
315 }
316 free(buffer_out);
317 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
318 return 1; // Decrypted successfully
319#else
320 LOGERR("Encrypted backup support not included.\n");
321 return -1;
322#endif
323}
324
Ethan Yonker472f5062016-02-25 13:47:30 -0600325unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600326 struct stat st;
327
328 if (stat(Path.c_str(), &st) != 0)
329 return 0;
330 return st.st_size;
331}
332
bigbiffee7b7ff2020-03-23 15:08:27 -0400333std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
334 std::string res;
335 size_t pos = path.find_first_of("/");
336 if (pos != std::string::npos) {
337 res = path.substr(pos+1);
338 }
339 return res;
340}
341
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100342std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
343{
344 std::string res;
345 size_t last_idx = 0, idx = 0;
346
Matt Mowera8a89d12016-12-30 18:10:37 -0600347 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100348 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600349 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100350 res += '/';
351
352 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600353 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100354 res += path.substr(last_idx, idx);
355 break;
356 }
357
358 res += path.substr(last_idx, idx-last_idx);
359 last_idx = path.find_first_not_of('/', idx);
360 }
361
Matt Mowera8a89d12016-12-30 18:10:37 -0600362 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100363 res += '/';
364 return res;
365}
366
Matt Mower2416a502016-04-12 19:54:46 -0500367void TWFunc::Strip_Quotes(char* &str) {
368 if (strlen(str) > 0 && str[0] == '\"')
369 str++;
370 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
371 str[strlen(str)-1] = 0;
372}
373
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500374vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
375 vector<string> res;
376
377 if (in.empty() || del == '\0')
378 return res;
379
380 string field;
381 istringstream f(in);
382 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600383 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500384 if (field.empty() && skip_empty)
385 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600386 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500387 }
388 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600389 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500390 if (field.empty() && skip_empty)
391 continue;
392 res.push_back(field);
393 }
394 }
395 return res;
396}
397
Ethan Yonker472f5062016-02-25 13:47:30 -0600398timespec TWFunc::timespec_diff(timespec& start, timespec& end)
399{
400 timespec temp;
401 if ((end.tv_nsec-start.tv_nsec)<0) {
402 temp.tv_sec = end.tv_sec-start.tv_sec-1;
403 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
404 } else {
405 temp.tv_sec = end.tv_sec-start.tv_sec;
406 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
407 }
408 return temp;
409}
410
411int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
412{
413 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
414 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
415}
416
Adithya Ra327aa72021-12-19 00:49:54 +0530417bool TWFunc::Wait_For_File(const string& path, std::chrono::nanoseconds timeout) {
418 android::base::Timer t;
419 while (t.duration() < timeout) {
420 struct stat sb;
421 if (stat(path.c_str(), &sb) != -1) {
422 return true;
423 }
424 std::this_thread::sleep_for(10ms);
425 }
426 return false;
427}
428
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600429#ifndef BUILD_TWRPTAR_MAIN
430
Dees_Troy38bd7602012-09-14 13:33:53 -0400431// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600432string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400433 string Local_Path = Path;
434
435 // Make sure that we have a leading slash
436 if (Local_Path.substr(0, 1) != "/")
437 Local_Path = "/" + Local_Path;
438
439 // Trim the path to get the root path only
440 size_t position = Local_Path.find("/", 2);
441 if (position != string::npos) {
442 Local_Path.resize(position);
443 }
444 return Local_Path;
445}
446
Dees_Troy43d8b002012-09-17 16:00:01 -0400447int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100448 std::vector<std::string> parts = Split_String(Path, "/", true);
449 std::string cur_path;
450 for (size_t i = 0; i < parts.size(); ++i) {
451 cur_path += "/" + parts[i];
452 if (!TWFunc::Path_Exists(cur_path)) {
453 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600454 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 -0600455 return false;
456 } else {
thatf1408b32016-01-03 11:09:15 +0100457 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600458 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400459 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400460 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400461 return true;
462}
463
Dees_Troyb46a6842012-09-25 11:06:46 -0400464void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
465 string Display_Text;
466
467 DataManager::GetValue(Read_Value, Display_Text);
468 if (Display_Text.empty())
469 Display_Text = Default_Text;
470
471 DataManager::SetValue("tw_operation", Display_Text);
472 DataManager::SetValue("tw_partition", "");
473}
474
475void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
476 string Display_Text;
477
478 DataManager::GetValue(Read_Value, Display_Text);
479 if (Display_Text.empty())
480 Display_Text = Default_Text;
481
482 DataManager::SetValue("tw_operation", Display_Text);
483 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400484}
485
Dees_Troy2673cec2013-04-02 20:22:16 +0000486void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400487 int logPipe[2];
488 int pigz_pid;
489 int destination_fd;
490 std::string destLogBuffer;
491
Dees Troy9d7fdf52013-09-19 20:49:25 +0000492 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400493
494 size_t extPos = Destination.find(".gz");
495 std::string uncompressedLog(Destination);
496 uncompressedLog.replace(extPos, Destination.length(), "");
497
498 if (Path_Exists(Destination)) {
499 Archive_Type type = Get_File_Type(Destination);
500 if (type == COMPRESSED) {
501 std::string destFileBuffer;
502 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400503 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400504 LOGINFO("Unable to get destination logfile contents.\n");
505 return;
506 }
507 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600508 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400509 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500510 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400511 std::stringstream uncompressedSS;
512 uncompressedSS << uncompressedIfs.rdbuf();
513 uncompressedIfs.close();
514 std::string uncompressedLogBuffer(uncompressedSS.str());
515 destLogBuffer.append(uncompressedLogBuffer);
516 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600517 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400518
bigbiffd3317052019-12-22 16:05:12 -0500519 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400520 std::stringstream ss;
521 ss << ifs.rdbuf();
522 std::string srcLogBuffer(ss.str());
523 ifs.close();
524
525 if (pipe(logPipe) < 0) {
526 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
527 }
528
529 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
530
531 pigz_pid = fork();
532 if (pigz_pid < 0) {
533 LOGINFO("fork() failed\n");
534 close(destination_fd);
535 close(logPipe[0]);
536 close(logPipe[1]);
537 } else if (pigz_pid == 0) {
538 close(logPipe[1]);
539 dup2(logPipe[0], fileno(stdin));
540 dup2(destination_fd, fileno(stdout));
541 if (execlp("pigz", "pigz", "-", NULL) < 0) {
542 close(destination_fd);
543 close(logPipe[0]);
544 _exit(-1);
545 }
546 } else {
547 close(logPipe[0]);
548 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
549 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
550 close(logPipe[1]);
551 close(destination_fd);
552 return;
553 }
554 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
555 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
556 close(logPipe[1]);
557 close(destination_fd);
558 return;
559 }
560 close(logPipe[1]);
561 }
562 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400563}
564
Dees_Troy2673cec2013-04-02 20:22:16 +0000565void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400566 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500567
bigbiff25d25b92020-06-19 16:07:38 -0400568 if (get_log_dir() == CACHE_LOGS_DIR) {
569 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
570 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000571 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000572 }
Dees_Troya58bead2012-09-27 09:49:29 -0400573
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500574 if (!TWFunc::Path_Exists(recoveryDir)) {
575 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400576 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500577 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
578 }
579 }
580
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400581 std::string logCopy = recoveryDir + "log.gz";
582 std::string lastLogCopy = recoveryDir + "last_log.gz";
Ethan Yonker5f3b8f02021-08-16 15:10:10 -0500583 copy_file(logCopy, lastLogCopy, 0600);
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500584 Copy_Log(TMP_LOG_FILE, logCopy);
585 chown(logCopy.c_str(), 1000, 1000);
586 chmod(logCopy.c_str(), 0600);
587 chmod(lastLogCopy.c_str(), 0640);
588
bigbiff25d25b92020-06-19 16:07:38 -0400589 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500590 if (PartitionManager.Mount_By_Path("/cache", false)) {
591 if (unlink("/cache/recovery/command") && errno != ENOENT) {
592 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
593 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000594 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500595 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000596 sync();
597}
598
bigbiffdf8436b2020-08-30 16:22:34 -0400599void TWFunc::Clear_Bootloader_Message() {
600 std::string err;
601 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100602 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400603 }
604}
605
Dees_Troy2673cec2013-04-02 20:22:16 +0000606void TWFunc::Update_Intent_File(string Intent) {
607 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600608 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000609 }
Dees_Troya58bead2012-09-27 09:49:29 -0400610}
611
612// reboot: Reboot the system. Return -1 on error, no return on success
613int TWFunc::tw_reboot(RebootCommand command)
614{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500615 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400616 Update_Log_File();
617
Dees_Troya58bead2012-09-27 09:49:29 -0400618 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600619 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400620
Dees_Troy2673cec2013-04-02 20:22:16 +0000621 switch (command) {
622 case rb_current:
623 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000624 Update_Intent_File("s");
625 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400626 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500627#ifdef ANDROID_RB_PROPERTY
628 return property_set(ANDROID_RB_PROPERTY, "reboot,");
629#elif defined(ANDROID_RB_RESTART)
630 return android_reboot(ANDROID_RB_RESTART, 0, 0);
631#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000632 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500633#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000634 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400635 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500636 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000637 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400638 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500639 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000640 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400641 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500642#ifdef ANDROID_RB_PROPERTY
643 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
644#elif defined(ANDROID_RB_POWEROFF)
645 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
646#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000647 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500648#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000649 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400650 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500651 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200652 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400653 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200654 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400655 case rb_fastboot:
656 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000657 default:
658 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600659 }
660 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400661}
662
663void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
664{
665 // Check for and run startup script if script exists
666 struct stat st;
667 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500668 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500669 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200670 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500671 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400672 }
Dees_Troy3477d712012-09-27 15:44:01 -0400673}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500674
675int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000676 DIR *d = opendir(path.c_str());
677 int r = 0;
678 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500679
Dees_Troyce675462013-01-09 19:48:21 +0000680 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500681 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000682 return -1;
683 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500684
Dees_Troyce675462013-01-09 19:48:21 +0000685 if (d) {
686 struct dirent *p;
687 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000688 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
689 continue;
690 new_path = path + "/";
691 new_path.append(p->d_name);
692 if (p->d_type == DT_DIR) {
693 r = removeDir(new_path, true);
694 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500695 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500696 r = rmdir(new_path.c_str());
697 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000698 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500699 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500700 } 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 +0000701 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000702 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000703 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000704 }
Dees_Troyce675462013-01-09 19:48:21 +0000705 }
706 }
707 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500708
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500709 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500710 if (skipParent)
711 return 0;
712 else
713 r = rmdir(path.c_str());
714 }
Dees_Troyce675462013-01-09 19:48:21 +0000715 }
716 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500717}
718
bigbiff22851b92021-09-01 16:46:57 -0400719int TWFunc::copy_file(string src, string dst, int mode, bool mount_paths) {
720 if (mount_paths) {
721 PartitionManager.Mount_By_Path(src, false);
722 PartitionManager.Mount_By_Path(dst, false);
723 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400724 if (!Path_Exists(src)) {
bigbiff22851b92021-09-01 16:46:57 -0400725 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 -0400726 return -1;
727 }
bigbiffd3317052019-12-22 16:05:12 -0500728 std::ifstream srcfile(src.c_str(), ios::binary);
729 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500730 dstfile << srcfile.rdbuf();
bigbiff850fa282021-10-09 12:37:29 -0400731 if (dstfile.bad()) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400732 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
733 return -1;
734 }
735
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500736 srcfile.close();
737 dstfile.close();
bigbiff22851b92021-09-01 16:46:57 -0400738 if (chmod(dst.c_str(), mode) != 0) {
739 LOGERR("Unable to chmod file: %s. Error: %s\n", dst.c_str(), strerror(errno));
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500740 return -1;
bigbiff22851b92021-09-01 16:46:57 -0400741 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500742 return 0;
743}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000744
745unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
746 struct stat st;
747
748 stat(Path.c_str(), &st);
749 if (st.st_mode & S_IFDIR)
750 return DT_DIR;
751 else if (st.st_mode & S_IFBLK)
752 return DT_BLK;
753 else if (st.st_mode & S_IFCHR)
754 return DT_CHR;
755 else if (st.st_mode & S_IFIFO)
756 return DT_FIFO;
757 else if (st.st_mode & S_IFLNK)
758 return DT_LNK;
759 else if (st.st_mode & S_IFREG)
760 return DT_REG;
761 else if (st.st_mode & S_IFSOCK)
762 return DT_SOCK;
763 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000764}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500765
766int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200767 ifstream file;
768 file.open(fn.c_str(), ios::in);
769
770 if (file.is_open()) {
bigbiff22851b92021-09-01 16:46:57 -0400771 std::string line;
772 while (std::getline(file, line)) {
773 results += line;
774 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200775 file.close();
776 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500777 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200778
779 LOGINFO("Cannot find file %s\n", fn.c_str());
780 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500781}
782
783int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500784 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500785 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500786 file.open(fn.c_str(), ios::in);
787 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500788 while (getline(file, line))
789 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500790 file.close();
791 return 0;
792 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000793 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500794 return -1;
795}
796
xNUTxe85f02d2014-07-18 01:30:58 +0200797int TWFunc::read_file(string fn, uint64_t& results) {
798 ifstream file;
799 file.open(fn.c_str(), ios::in);
800
801 if (file.is_open()) {
802 file >> results;
803 file.close();
804 return 0;
805 }
806
807 LOGINFO("Cannot find file %s\n", fn.c_str());
808 return -1;
809}
810
bigbiff22851b92021-09-01 16:46:57 -0400811bool TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500812 FILE *file;
813 file = fopen(fn.c_str(), "w");
814 if (file != NULL) {
815 fwrite(line.c_str(), line.size(), 1, file);
816 fclose(file);
bigbiff22851b92021-09-01 16:46:57 -0400817 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500818 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000819 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff22851b92021-09-01 16:46:57 -0400820 return false;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500821}
822
bigbiff22851b92021-09-01 16:46:57 -0400823bool TWFunc::write_to_file(const string& fn, const std::vector<string> lines) {
824 FILE *file;
825 file = fopen(fn.c_str(), "a+");
826 if (file != NULL) {
827 for (auto&& line: lines) {
828 fwrite(line.c_str(), line.size(), 1, file);
829 fwrite("\n", sizeof(char), 1, file);
830 }
831 fclose(file);
832 return true;
833 }
834 return false;
835}
836
837
Dees_Troy83bd4832013-05-04 12:39:56 +0000838bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
839 DIR* d;
840
841 string Filename;
842 Restore_Path += "/";
843 d = opendir(Restore_Path.c_str());
844 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500845 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000846 return false;
847 }
848
849 struct dirent* de;
850 while ((de = readdir(d)) != NULL) {
851 Filename = Restore_Path;
852 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500853 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000854 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
855 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
856 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
857 closedir(d);
858 return false;
859 }
860 }
861 }
862 closedir(d);
863 return true;
864}
865
Dees Troyb21cc642013-09-10 17:36:41 +0000866string TWFunc::Get_Current_Date() {
867 string Current_Date;
868 time_t seconds = time(0);
869 struct tm *t = localtime(&seconds);
870 char timestamp[255];
871 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);
872 Current_Date = timestamp;
873 return Current_Date;
874}
875
Ethan Yonkerb5557892014-02-07 21:43:20 -0600876string TWFunc::System_Property_Get(string Prop_Name) {
Captain Throwback1483a8e2022-01-03 09:52:06 -0500877 return Partition_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path(), "build.prop");
Chaosmaster65633a42020-02-05 15:24:09 +0100878}
879
Captain Throwback1483a8e2022-01-03 09:52:06 -0500880string TWFunc::Partition_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point, string prop_file_name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100881 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000882 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600883 string propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500884 string prop_file;
Chaosmaster65633a42020-02-05 15:24:09 +0100885 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600886 return propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500887 if (Mount_Point == PartitionManager.Get_Android_Root_Path()) {
888 prop_file = Mount_Point + "/system/" + prop_file_name;
889 } else {
890 prop_file = Mount_Point + "/" + prop_file_name;
891 }
Captain Throwback2b9ea722021-12-31 21:35:52 -0500892 if (!TWFunc::Path_Exists(prop_file)) {
893 LOGINFO("Unable to locate file: %s\n", prop_file.c_str());
894 return propvalue;
895 }
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600896 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback2b9ea722021-12-31 21:35:52 -0500897 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 +0200898 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000899 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100900 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600901 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000902 }
903 int line_count = buildprop.size();
904 int index;
905 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600906 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000907 for (index = 0; index < line_count; index++) {
908 end_pos = buildprop.at(index).find("=", start_pos);
909 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600910 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000911 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600912 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100913 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600914 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000915 }
916 }
Dees Troyb21cc642013-09-10 17:36:41 +0000917 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100918 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600919 return propvalue;
920}
921
922void TWFunc::Auto_Generate_Backup_Name() {
923 string propvalue = System_Property_Get("ro.build.display.id");
924 if (propvalue.empty()) {
925 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
926 return;
927 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400928 else {
929 //remove periods from build display so it doesn't confuse the extension code
930 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
931 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600932 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500933 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600934 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
935 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
936 // Trailing spaces cause problems on some file systems, so remove them
937 string space_check, space = " ";
938 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
939 while (space_check == space) {
940 Backup_Name.resize(Backup_Name.size() - 1);
941 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
942 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500943 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600944 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
945 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600946 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600947 } else {
948 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600949 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200950}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100951
nkk7198fc3992017-12-16 16:26:42 +0200952void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100953{
954#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200955 static bool fixed = false;
956 if (fixed)
957 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200958
959 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
960
961 struct timeval tv;
962 uint64_t offset = 0;
963 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
964
965 if (TWFunc::read_file(sepoch, offset) == 0) {
966
967 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
968
969 tv.tv_sec = offset;
970 tv.tv_usec = 0;
971 settimeofday(&tv, NULL);
972
973 gettimeofday(&tv, NULL);
974
Phoenix59146b05f22018-02-03 06:41:08 +0000975 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 +0200976
977 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200978 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200979 return;
980
981 }
982
983 } else {
984
985 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
986
987 }
988
Ethan Yonker9132d912015-02-02 10:32:49 -0600989 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200990
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100991 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
992 // They never set it, it just ticks forward from 1970-01-01 00:00,
993 // and then they have files /data/system/time/ats_* with 64bit offset
994 // in miliseconds which, when added to the RTC, gives the correct time.
995 // So, the time is: (offset_from_ats + value_from_RTC)
996 // There are multiple ats files, they are for different systems? Bases?
997 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
998 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
999
nkk7198fc3992017-12-16 16:26:42 +02001000 std::vector<std::string> paths; // space separated list of paths
1001 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +01001002 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +02001003 if (!PartitionManager.Mount_By_Path("/data", false))
1004 return;
1005 } else {
1006 // When specific path(s) are used, Fixup_Time needs those
1007 // partitions to already be mounted!
1008 paths = Split_String(time_paths, " ");
1009 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001010
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001011 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001012 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001013 struct dirent *dt;
1014 std::string ats_path;
1015
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001016 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1017 // - it is the one for ATS_TOD (time of day?).
1018 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001019 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001020 {
nkk7198fc3992017-12-16 16:26:42 +02001021 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001022 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001023 continue;
1024
Matt Mowera8a89d12016-12-30 18:10:37 -06001025 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001026 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001027 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001028 continue;
1029
Matt Mowera8a89d12016-12-30 18:10:37 -06001030 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001031 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001032 }
1033
1034 closedir(d);
1035 }
1036
nkk7198fc3992017-12-16 16:26:42 +02001037 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001038 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001039 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001040 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001041 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001042 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001043 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001044 } else {
1045 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001046
nkk7198fc3992017-12-16 16:26:42 +02001047 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1048 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1049 fixed = true;
1050 }
1051
1052 if (!fixed) {
Captain Throwbackf74fc052022-01-19 13:25:54 -05001053#ifdef TW_QCOM_ATS_OFFSET
1054 // Offset is the difference between the current time and the time since_epoch
1055 // To calculate the offset in Android, the following expression (from a root shell) can be used:
1056 // echo "$(( ($(date +%s) - $(cat /sys/class/rtc/rtc0/since_epoch)) ))"
1057 // Add 3 zeros to the output and use that in the TW_QCOM_ATS_OFFSET flag in your BoardConfig.mk
1058 // For example, if the result of the calculation is 1642433544, use 1642433544000 as the offset
1059 offset = (uint64_t) TW_QCOM_ATS_OFFSET;
1060 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1061 LOGINFO("TWFunc::Fixup_Time: Setting time offset from TW_QCOM_ATS_OFFSET, offset %llu\n", (unsigned long long) offset);
1062#else
nkk7198fc3992017-12-16 16:26:42 +02001063 // Failed to get offset from ats file, check twrp settings
1064 unsigned long long value;
1065 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1066 return;
1067 } else {
1068 offset = (uint64_t) value;
1069 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1070 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1071 }
Captain Throwbackf74fc052022-01-19 13:25:54 -05001072#endif
nkk7198fc3992017-12-16 16:26:42 +02001073 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001074
1075 gettimeofday(&tv, NULL);
1076
1077 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001078#ifdef TW_CLOCK_OFFSET
1079// Some devices are even quirkier and have ats files that are offset from the actual time
1080 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1081#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001082 tv.tv_usec += (offset%1000)*1000;
1083
Matt Mowera8a89d12016-12-30 18:10:37 -06001084 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001085 {
1086 ++tv.tv_sec;
1087 tv.tv_usec -= 1000000;
1088 }
1089
1090 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001091
1092 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001093#endif
1094}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001095
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001096std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1097{
1098 std::vector<std::string> res;
1099 size_t idx = 0, idx_last = 0;
1100
Matt Mowera8a89d12016-12-30 18:10:37 -06001101 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001102 {
1103 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001104 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001105 idx = str.size();
1106
Matt Mowera8a89d12016-12-30 18:10:37 -06001107 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001108 res.push_back(str.substr(idx_last, idx-idx_last));
1109
1110 idx_last = idx + delimiter.size();
1111 }
1112
1113 return res;
1114}
1115
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001116bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1117{
1118 std::vector<std::string> parts = Split_String(path, "/");
1119 std::string cur_path;
1120 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001121 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001122 {
1123 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001124 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001125 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001126 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001127 return false;
1128 chown(cur_path.c_str(), uid, gid);
1129 }
1130 }
1131 return true;
1132}
1133
xNUTxe85f02d2014-07-18 01:30:58 +02001134int TWFunc::Set_Brightness(std::string brightness_value)
1135{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001136 int result = -1;
1137 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001138
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001139 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001140 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001141 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001142 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1143 if (!secondary_brightness_file.empty()) {
1144 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001145 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001146 }
xNUTxe85f02d2014-07-18 01:30:58 +02001147 }
bigbiff22851b92021-09-01 16:46:57 -04001148 return result ? 0 : -1;
xNUTxe85f02d2014-07-18 01:30:58 +02001149}
1150
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001151bool TWFunc::Toggle_MTP(bool enable) {
1152#ifdef TW_HAS_MTP
1153 static int was_enabled = false;
1154
1155 if (enable && was_enabled) {
1156 if (!PartitionManager.Enable_MTP())
1157 PartitionManager.Disable_MTP();
1158 } else {
1159 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1160 PartitionManager.Disable_MTP();
1161 usleep(500);
1162 }
1163 return was_enabled;
1164#else
1165 return false;
1166#endif
1167}
1168
Tom Hite5a926722014-09-15 01:31:03 +00001169void TWFunc::SetPerformanceMode(bool mode) {
1170 if (mode) {
1171 property_set("recovery.perf.mode", "1");
1172 } else {
1173 property_set("recovery.perf.mode", "0");
1174 }
1175 // Some time for events to catch up to init handlers
1176 usleep(500000);
1177}
1178
Jenkins1710bf22014-10-02 20:22:21 -04001179std::string TWFunc::to_string(unsigned long value) {
1180 std::ostringstream os;
1181 os << value;
1182 return os.str();
1183}
1184
Ethan Yonker9132d912015-02-02 10:32:49 -06001185void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001186 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001187 // Disable flashing of stock recovery
1188 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1189 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001190 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 -06001191 sync();
1192 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001193 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001194 }
1195}
1196
Ethan Yonker483e9f42016-01-11 22:21:18 -06001197unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1198 unsigned long block_device_size;
1199 int ret = 0;
1200
1201 int fd = open(block_device, O_RDONLY);
1202 if (fd < 0) {
1203 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1204 } else {
1205 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1206 close(fd);
1207 if (ret) {
1208 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1209 } else {
1210 return (unsigned long long)(block_device_size) * 512LLU;
1211 }
1212 }
1213 return 0;
1214}
1215
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001216void TWFunc::copy_kernel_log(string curr_storage) {
1217 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001218 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001219
1220 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001221 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001222 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001223 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1224 tw_set_default_metadata(dmesgDst.c_str());
1225}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001226
Captain Throwback52978932021-09-05 15:11:07 -04001227void TWFunc::copy_logcat(string curr_storage) {
1228 std::string logcatDst = curr_storage + "/logcat.txt";
1229 std::string logcatCmd = "logcat -d";
1230
1231 std::string result;
1232 Exec_Cmd(logcatCmd, result, false);
1233 write_to_file(logcatDst, result);
1234 gui_msg(Msg("copy_logcat=Copied logcat to {1}")(logcatDst));
1235 tw_set_default_metadata(logcatDst.c_str());
1236}
1237
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001238bool TWFunc::isNumber(string strtocheck) {
1239 int num = 0;
1240 std::istringstream iss(strtocheck);
1241
1242 if (!(iss >> num).fail())
1243 return true;
1244 else
1245 return false;
1246}
1247
1248int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001249 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001250 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1251 int ret = TWFunc::Exec_Cmd(cmd);
1252 if (ret != 0)
1253 return -1;
1254 return ret;
1255}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001256
bigbiff25d25b92020-06-19 16:07:38 -04001257std::string TWFunc::get_log_dir() {
1258 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1259 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001260 LOGINFO("Unable to find a directory to store TWRP logs.");
1261 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001262 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001263 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001264 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001265 }
1266 else {
bigbiff25d25b92020-06-19 16:07:38 -04001267 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001268 }
1269}
1270
1271void TWFunc::check_selinux_support() {
1272 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1273 if (TWFunc::Path_Exists("/file_contexts")) {
1274 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1275 rename("/file_contexts", "/file_contexts.bak");
1276 }
1277 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1278 rename("/prebuilt_file_contexts", "/file_contexts");
1279 }
1280 struct selinux_opt selinux_options[] = {
1281 { SELABEL_OPT_PATH, "/file_contexts" }
1282 };
1283 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1284 if (!selinux_handle)
1285 printf("No file contexts for SELinux\n");
1286 else
1287 printf("SELinux contexts loaded from /file_contexts\n");
1288 { // Check to ensure SELinux can be supported by the kernel
1289 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001290 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001291 std::string se_context_check = cacheDir + "recovery/";
1292 int ret = 0;
1293
bigbiff25d25b92020-06-19 16:07:38 -04001294 if (cacheDir == CACHE_LOGS_DIR) {
1295 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001296 }
1297 if (TWFunc::Path_Exists(se_context_check)) {
1298 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001299 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001300 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1301 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001302 }
1303 }
1304 if (ret < 0) {
1305 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1306 } else {
1307 free(contexts);
1308 gui_msg("full_selinux=Full SELinux support is present.");
1309 }
1310 }
1311}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001312
1313bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001314 LOGINFO("checking for twrp app\n");
1315 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1316 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001317 bool is_system_mounted = true;
1318 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1319 is_system_mounted = false;
1320 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001321 }
Captain Throwback31c14922020-12-21 11:28:34 -05001322 string base_path = PartitionManager.Get_Android_Root_Path();
1323 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1324 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1325 string install_path = base_path + "/priv-app";
1326 if (!TWFunc::Path_Exists(install_path))
1327 install_path = base_path + "/app";
1328 install_path += "/twrpapp";
1329 if (TWFunc::Path_Exists(install_path)) {
1330 LOGINFO("App found at '%s'\n", install_path.c_str());
1331 DataManager::SetValue("tw_app_installed_in_system", 1);
1332 return true;
1333 }
1334 if (!is_system_mounted)
1335 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001336 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001337 }
1338 DataManager::SetValue("tw_app_installed_in_system", 0);
1339 return false;
1340}
Chaosmaster461e39f2020-02-07 01:48:13 +01001341
epicX271bb3a2020-12-30 01:03:18 +05301342void TWFunc::checkforapp(){
1343
1344 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1345 int sdkver = 0;
1346 if (!sdkverstr.empty()) {
1347 sdkver = atoi(sdkverstr.c_str());
1348 }
1349 if (sdkver <= 13) {
1350 if (sdkver == 0)
1351 LOGINFO("Unable to read sdk version from build prop\n");
1352 else
1353 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1354 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1355 goto exit;
1356 }
1357 if (Is_TWRP_App_In_System()) {
1358 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1359 goto exit;
1360 }
1361 if (PartitionManager.Mount_By_Path("/data", false)) {
1362 const char parent_path[] = "/data/app";
1363 const char app_prefix[] = "me.twrp.twrpapp-";
1364 DIR *d = opendir(parent_path);
1365 if (d) {
1366 struct dirent *p;
1367 while ((p = readdir(d))) {
1368 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1369 continue;
1370 closedir(d);
1371 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1372 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1373 goto exit;
1374 }
1375 closedir(d);
1376 }
1377 } else {
1378 LOGINFO("Data partition cannot be mounted during app check\n");
1379 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1380 }
1381
1382 LOGINFO("App not installed\n");
1383 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1384exit:
1385 return;
1386
1387}
1388
Chaosmaster461e39f2020-02-07 01:48:13 +01001389int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1390#ifdef TW_INCLUDE_LIBRESETPROP
1391 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1392#else
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001393 return NOT_AVAILABLE;
1394#endif
1395}
1396
1397int TWFunc::Delete_Property(string Prop_Name) {
1398#ifdef TW_INCLUDE_LIBRESETPROP
1399 return delprop(Prop_Name.c_str(), false);
1400#else
1401 return NOT_AVAILABLE;
Chaosmaster461e39f2020-02-07 01:48:13 +01001402#endif
1403}
1404
bigbiffee7b7ff2020-03-23 15:08:27 -04001405void TWFunc::List_Mounts() {
1406 std::vector<std::string> mounts;
1407 read_file("/proc/mounts", mounts);
1408 LOGINFO("Mounts:\n");
1409 for (auto&& mount: mounts) {
1410 LOGINFO("%s\n", mount.c_str());
1411 }
1412}
1413
epicXa721f952021-01-04 13:01:31 +05301414string TWFunc::Check_For_TwrpFolder() {
1415 string oldFolder = "";
1416 vector<string> customTWRPFolders;
1417 string mainPath = DataManager::GetCurrentStoragePath();
1418 DIR* d;
1419 struct dirent* de;
1420
Fernando Oliveira073c4302022-10-19 13:33:47 -03001421 if (DataManager::GetIntValue(TW_IS_ENCRYPTED) && DataManager::GetIntValue(TW_CRYPTO_PWTYPE)) {
epicXa721f952021-01-04 13:01:31 +05301422 goto exit;
1423 }
1424
1425
1426 d = opendir(mainPath.c_str());
1427 if (d == NULL) {
1428 goto exit;
1429 }
1430
1431 while ((de = readdir(d)) != NULL) {
1432 string name = de->d_name;
1433 string fullPath = mainPath + '/' + name;
1434 unsigned char type = de->d_type;
1435
epicX11e90832021-03-01 00:02:57 +05301436 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301437
epicX11e90832021-03-01 00:02:57 +05301438 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301439 type = Get_D_Type_From_Stat(fullPath);
1440 }
1441
Fernando Oliveira25062d72023-02-01 12:52:32 -03001442 if (type == DT_DIR && Path_Exists(fullPath + "/.twrpcf")) {
epicX11e90832021-03-01 00:02:57 +05301443 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301444 oldFolder = name;
1445 } else {
1446 customTWRPFolders.push_back(name);
1447 }
1448 }
1449 }
1450
1451 closedir(d);
1452
epicX11e90832021-03-01 00:02:57 +05301453 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301454 LOGINFO("No recovery folder found. Using default folder.\n");
Fernando Oliveiraff555662023-10-22 12:09:06 -03001455 TWPartition* SDCard = PartitionManager.Find_Partition_By_Path(DataManager::GetCurrentStoragePath());
1456 if (SDCard->Mount(true)) {
1457 mainPath += TW_DEFAULT_RECOVERY_FOLDER;
1458 mkdir(mainPath.c_str(), 0777);
1459 }
epicXa721f952021-01-04 13:01:31 +05301460 goto exit;
epicX11e90832021-03-01 00:02:57 +05301461 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301462 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1463 goto exit;
1464 } else {
epicX11e90832021-03-01 00:02:57 +05301465 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301466 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1467 } else {
1468 LOGINFO("One custom recovery folder found.\n");
1469 }
1470 string customPath = '/' + customTWRPFolders.at(0);
1471
epicX11e90832021-03-01 00:02:57 +05301472 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301473 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1474 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1475
epicX11e90832021-03-01 00:02:57 +05301476 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301477 vector<string> backups;
1478 d = opendir(oldBackupFolder.c_str());
1479
1480 if (d != NULL) {
1481 while ((de = readdir(d)) != NULL) {
1482 string name = de->d_name;
1483 unsigned char type = de->d_type;
1484
epicX11e90832021-03-01 00:02:57 +05301485 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301486
epicX11e90832021-03-01 00:02:57 +05301487 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301488 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1489 }
1490
epicX11e90832021-03-01 00:02:57 +05301491 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301492 backups.push_back(name);
1493 }
1494 }
1495 closedir(d);
1496 }
1497
epicX11e90832021-03-01 00:02:57 +05301498 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301499 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1500 }
1501 }
1502 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1503 }
1504
1505 return customPath;
1506 }
1507
1508exit:
1509 return TW_DEFAULT_RECOVERY_FOLDER;
1510}
Darth98f775972022-08-05 09:39:03 +01001511
1512bool TWFunc::Check_Xml_Format(const std::string filename) {
1513 std::string buffer(' ', 4);
1514 std::string abx_hdr("ABX\x00", 4);
1515 std::ifstream File;
1516 File.open(filename);
1517 if (File.is_open()) {
1518 File.get(&buffer[0], buffer.size());
1519 File.close();
1520 // Android Binary Xml start from these bytes
1521 if(!buffer.compare(0, abx_hdr.size(), abx_hdr))
1522 return false; // ABX format - requires conversion
1523 }
1524 return true; // good format, possible to parse
1525}
1526
1527// return true=successful conversion (return the name of the converted file in "result");
1528// return false=an error happened (leave "result" alone)
1529bool TWFunc::abx_to_xml(const std::string path, std::string &result) {
1530 bool res = false;
1531 if (!TWFunc::Path_Exists(path))
1532 return res;
1533
1534 std::ifstream infile(path);
1535 if (!infile.is_open())
1536 return res;
1537
1538 std::string fname = TWFunc::Get_Filename(path);
1539 std::string tmp = "/tmp/converted_xml";
1540 if (!TWFunc::Path_Exists(tmp)) {
1541 if (mkdir(tmp.c_str(), 0777) != 0)
1542 tmp = "/tmp";
1543 }
1544
1545 std::string tmp_path = tmp + "/" + fname;
1546 std::ofstream outfile(tmp_path);
1547 if (!outfile.is_open()) {
1548 LOGINFO("Error. The abx conversion of %s has failed.\n", path.c_str());
1549 infile.close();
1550 return res;
1551 }
1552
1553 AbxToXml r(infile, outfile);
1554 if (r.run() && TWFunc::Path_Exists(tmp_path)) {
1555 res = true;
1556 result = tmp_path;
1557 }
1558
1559 infile.close();
1560 outfile.close();
1561
1562 return res;
1563}
1564
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001565std::string GetFstabPath() {
1566 for (const char* prop : {"fstab_suffix", "hardware", "hardware.platform"}) {
1567 std::string suffix;
1568
1569 if (!fs_mgr_get_boot_config(prop, &suffix)) continue;
1570
1571 for (const char* prefix : {// late-boot/post-boot locations
1572 "/odm/etc/fstab.", "/vendor/etc/fstab.",
1573 // early boot locations
1574 "/system/etc/fstab.", "/first_stage_ramdisk/system/etc/fstab.",
1575 "/fstab.", "/first_stage_ramdisk/fstab."}) {
1576 std::string fstab_path = prefix + suffix;
1577 LOGINFO("%s: %s\n", __func__, fstab_path.c_str());
1578 if (access(fstab_path.c_str(), F_OK) == 0) return fstab_path;
1579 }
1580 }
1581
1582 return "";
1583}
1584
1585bool TWFunc::Find_Fstab(string &fstab) {
1586 fstab = GetFstabPath();
1587 if (fstab == "") return false;
1588 return true;
1589}
1590
Mohd Faraza57874b2023-09-30 00:57:58 +05301591static inline std::string Get_Version_From_FQ(std::string name) {
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001592 int start, end;
1593 start = name.find('@') + 1;
Mohd Faraza57874b2023-09-30 00:57:58 +05301594 end = name.find(":") - start;
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001595 return name.substr(start, end);
1596}
1597
Mohd Faraza57874b2023-09-30 00:57:58 +05301598bool TWFunc::Get_Service_From_Manifest(std::string basepath, std::string service, std::string &res) {
1599 std::string manifestpath, filename, platform;
1600 manifestpath = basepath + "/etc/vintf/";
1601 bool ret = false;
1602
1603 // Prefer using ro.boot.product.vendor.sku property, following AOSP VintfObject::fetchVendorHalManifest
1604 // If not set, also try ro.board.platform.
1605 platform = android::base::GetProperty("ro.boot.product.vendor.sku", "");
1606 if (platform.empty()) {
1607 LOGINFO("Property ro.boot.product.vendor.sku not found, trying to get vintf manifest file name from ro.board.platform\n");
1608 platform = android::base::GetProperty("ro.board.platform", "");
1609 }
1610
1611 // Let's find the service xml if exists
1612 Exec_Cmd("find " + manifestpath + "manifest/ -type f -name *" + service + "*", filename, false);
1613 if (filename.empty()) {
1614 LOGINFO("Separate manifest doesn't exist for '%s'\n", service.c_str());
1615 // Look for manifest_PLATFORM.xml
1616 filename = manifestpath + "manifest_" + platform + ".xml";
1617 if (!Path_Exists(filename)) {
1618 // Use legacy manifest path if platform manifest is not found.
1619 LOGINFO("%s not found. Using default path for manifest.xml\n", filename.c_str());
1620 filename = manifestpath + "manifest.xml";
1621 }
1622 }
1623 if (Path_Exists(filename)) {
1624 char* manifest = PageManager::LoadFileToBuffer(filename, NULL);
1625 LOGINFO("Looking for '%s' service in manifest\n", service.c_str());
1626 xml_document<>* vintfManifest = new xml_document<>();
1627 vintfManifest->parse<0>(manifest);
1628 xml_node<>* manifestNode = vintfManifest->first_node("manifest");
1629 std::string version;
1630 if (manifestNode) {
1631 for (xml_node<>* child = manifestNode->first_node(); child; child = child->next_sibling()) {
1632 std::string type = child->name();
1633 if (type == "hal") {
1634 xml_node<>* nameNode = child->first_node("name");
1635 type = nameNode->value();
1636 if (type == service) {
1637 xml_node<> *versionNode = child->first_node("version");
1638 if (versionNode != nullptr) {
1639 LOGINFO("Found version in manifest: %s\n", versionNode->value());
1640 } else {
1641 versionNode = child->first_node("fqname");
1642 if (versionNode == nullptr) return ret;
1643 LOGINFO("Found fqname in manifest: %s\n", versionNode->value());
1644 }
1645 version = versionNode->value();
1646 if (version.find('@') == std::string::npos) {
1647 res = version;
1648 } else {
1649 res = Get_Version_From_FQ(version);
1650 }
1651 ret = true;
1652 }
1653 }
1654 }
1655 }
1656 }
1657 return ret;
1658}
1659
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001660#endif // ndef BUILD_TWRPTAR_MAIN