blob: 069561183829f6b07ef5c2ff0605c36ba5f96676 [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>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060060#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000061#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
62 #include "openaes/inc/oaes_lib.h"
63#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050064#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040065
Dees_Troyb05ddee2013-01-28 20:24:50 +000066extern "C" {
67 #include "libcrecovery/common.h"
68}
69
Chaosmaster461e39f2020-02-07 01:48:13 +010070#ifdef TW_INCLUDE_LIBRESETPROP
bigbiffa05d32c2021-12-25 15:43:34 -050071 #include <resetprop.hpp>
Chaosmaster461e39f2020-02-07 01:48:13 +010072#endif
73
bigbiff bigbiff19874f12019-01-08 20:06:57 -050074struct selabel_handle *selinux_handle;
75
bigbiff bigbiff9c754052013-01-09 09:09:08 -050076/* Execute a command */
bigbiffad58e1b2020-07-06 20:24:34 -040077int TWFunc::Exec_Cmd(const string& cmd, string &result, bool combine_stderr) {
Dees_Troy29a06352013-08-24 12:06:47 +000078 FILE* exec;
79 char buffer[130];
80 int ret = 0;
bigbiffad58e1b2020-07-06 20:24:34 -040081 std::string popen_cmd = cmd;
82 if (combine_stderr)
83 popen_cmd = cmd + " 2>&1";
84 exec = __popen(popen_cmd.c_str(), "r");
85
Matt Mowera8a89d12016-12-30 18:10:37 -060086 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000087 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050088 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000089 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050090 }
Dees_Troy29a06352013-08-24 12:06:47 +000091 ret = __pclose(exec);
92 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050093}
94
Ethan Yonker7e941582019-03-22 08:18:21 -050095int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020096 pid_t pid;
97 int status;
98 switch(pid = fork())
99 {
100 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -0500101 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +0200102 return -1;
103 case 0: // child
bigbiffad58e1b2020-07-06 20:24:34 -0400104 execl("/system/bin/sh", "sh", "-c", cmd.c_str(), NULL);
Vojtech Bocek05534202013-09-11 08:11:56 +0200105 _exit(127);
106 break;
107 default:
108 {
Ethan Yonker7e941582019-03-22 08:18:21 -0500109 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +0200110 return -1;
111 else
112 return 0;
113 }
114 }
115}
116
Dees_Troy38bd7602012-09-14 13:33:53 -0400117// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600118string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400119 size_t pos = Path.find_last_of("/");
120 if (pos != string::npos) {
121 string Filename;
122 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
123 return Filename;
124 } else
125 return Path;
126}
127
128// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600129string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400130 size_t pos = Path.find_last_of("/");
131 if (pos != string::npos) {
132 string Pathonly;
133 Pathonly = Path.substr(0, pos + 1);
134 return Pathonly;
135 } else
136 return Path;
137}
138
Ethan Yonker7e941582019-03-22 08:18:21 -0500139int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600140 pid_t rc_pid;
141
142 rc_pid = waitpid(pid, status, 0);
143 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100144 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500145 if (Show_Errors)
146 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 -0600147 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100148 } else if (WEXITSTATUS(*status) == 0) {
149 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
150 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500151 if (Show_Errors)
152 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 -0600153 return -1;
154 }
155 } else { // no PID returned
156 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200157 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600158 else {
that2252d242015-04-03 22:33:04 +0200159 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600160 return -1;
161 }
162 }
163 return 0;
164}
165
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600166int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
167 pid_t retpid = waitpid(pid, status, WNOHANG);
168 for (; retpid == 0 && timeout; --timeout) {
169 sleep(1);
170 retpid = waitpid(pid, status, WNOHANG);
171 }
172 if (retpid == 0 && timeout == 0) {
173 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
174 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600175 for (timeout = 5; retpid == 0 && timeout; --timeout) {
176 sleep(1);
177 retpid = waitpid(pid, status, WNOHANG);
178 }
179 if (retpid)
180 LOGINFO("Child process killed successfully\n");
181 else
182 LOGINFO("Child process took too long to kill, may be a zombie process\n");
183 return -1;
184 } else if (retpid > 0) {
185 if (WIFSIGNALED(*status)) {
186 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
187 return -1;
188 }
189 } else if (retpid < 0) { // no PID returned
190 if (errno == ECHILD)
191 LOGERR("%s no child process exist\n", Child_Name.c_str());
192 else {
193 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
194 return -1;
195 }
196 }
197 return 0;
198}
199
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600200bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600201 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400202 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600203}
204
bigbiffce8f83c2015-12-12 18:30:21 -0500205Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600206 string::size_type i = 0;
207 int firstbyte = 0, secondbyte = 0;
208 char header[3];
209
210 ifstream f;
211 f.open(fn.c_str(), ios::in | ios::binary);
212 f.get(header, 3);
213 f.close();
214 firstbyte = header[i] & 0xff;
215 secondbyte = header[++i] & 0xff;
216
217 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500218 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600219 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500220 return ENCRYPTED;
221 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600222}
223
224int TWFunc::Try_Decrypting_File(string fn, string password) {
225#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
226 OAES_CTX * ctx = NULL;
227 uint8_t _key_data[32] = "";
228 FILE *f;
229 uint8_t buffer[4096];
230 uint8_t *buffer_out = NULL;
231 uint8_t *ptr = NULL;
232 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600233 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600234 size_t _j = 0;
235 size_t _key_data_len = 0;
236
237 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600238 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600239 _key_data[_j] = _j + 1;
240 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600241 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600242 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600243 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600244 _key_data_len = 24;
245 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600246 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600247 memcpy(_key_data, password.c_str(), password.size());
248
249 ctx = oaes_alloc();
250 if (ctx == NULL) {
251 LOGERR("Failed to allocate OAES\n");
252 return -1;
253 }
254
255 oaes_key_import_data(ctx, _key_data, _key_data_len);
256
257 f = fopen(fn.c_str(), "rb");
258 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500259 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500260 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600261 return -1;
262 }
263 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
264 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500265 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600266 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500267 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600268 return -1;
269 }
270 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
271 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
272 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500273 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600274 return -1;
275 }
276 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
277 if (buffer_out == NULL) {
278 LOGERR("Failed to allocate output buffer for try decrypt.\n");
279 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500280 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600281 return -1;
282 }
283 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
284 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
285 fclose(f);
286 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500287 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600288 return 0;
289 }
290 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500291 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600292 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500293 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600294 free(buffer_out);
295 return 1; // Decrypted successfully
296 }
297 ptr = buffer_out;
298 firstbyte = *ptr & 0xff;
299 ptr++;
300 secondbyte = *ptr & 0xff;
301 if (firstbyte == 0x1f && secondbyte == 0x8b) {
302 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
303 free(buffer_out);
304 return 3; // Compressed
305 }
306 if (out_len >= 262) {
307 ptr = buffer_out + 257;
308 if (strncmp((char*)ptr, "ustar", 5) == 0) {
309 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
310 free(buffer_out);
311 return 2; // Tar
312 }
313 }
314 free(buffer_out);
315 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
316 return 1; // Decrypted successfully
317#else
318 LOGERR("Encrypted backup support not included.\n");
319 return -1;
320#endif
321}
322
Ethan Yonker472f5062016-02-25 13:47:30 -0600323unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600324 struct stat st;
325
326 if (stat(Path.c_str(), &st) != 0)
327 return 0;
328 return st.st_size;
329}
330
bigbiffee7b7ff2020-03-23 15:08:27 -0400331std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
332 std::string res;
333 size_t pos = path.find_first_of("/");
334 if (pos != std::string::npos) {
335 res = path.substr(pos+1);
336 }
337 return res;
338}
339
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100340std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
341{
342 std::string res;
343 size_t last_idx = 0, idx = 0;
344
Matt Mowera8a89d12016-12-30 18:10:37 -0600345 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100346 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600347 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100348 res += '/';
349
350 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600351 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100352 res += path.substr(last_idx, idx);
353 break;
354 }
355
356 res += path.substr(last_idx, idx-last_idx);
357 last_idx = path.find_first_not_of('/', idx);
358 }
359
Matt Mowera8a89d12016-12-30 18:10:37 -0600360 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100361 res += '/';
362 return res;
363}
364
Matt Mower2416a502016-04-12 19:54:46 -0500365void TWFunc::Strip_Quotes(char* &str) {
366 if (strlen(str) > 0 && str[0] == '\"')
367 str++;
368 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
369 str[strlen(str)-1] = 0;
370}
371
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500372vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
373 vector<string> res;
374
375 if (in.empty() || del == '\0')
376 return res;
377
378 string field;
379 istringstream f(in);
380 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600381 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500382 if (field.empty() && skip_empty)
383 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600384 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500385 }
386 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600387 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500388 if (field.empty() && skip_empty)
389 continue;
390 res.push_back(field);
391 }
392 }
393 return res;
394}
395
Ethan Yonker472f5062016-02-25 13:47:30 -0600396timespec TWFunc::timespec_diff(timespec& start, timespec& end)
397{
398 timespec temp;
399 if ((end.tv_nsec-start.tv_nsec)<0) {
400 temp.tv_sec = end.tv_sec-start.tv_sec-1;
401 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
402 } else {
403 temp.tv_sec = end.tv_sec-start.tv_sec;
404 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
405 }
406 return temp;
407}
408
409int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
410{
411 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
412 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
413}
414
Adithya Ra327aa72021-12-19 00:49:54 +0530415bool TWFunc::Wait_For_File(const string& path, std::chrono::nanoseconds timeout) {
416 android::base::Timer t;
417 while (t.duration() < timeout) {
418 struct stat sb;
419 if (stat(path.c_str(), &sb) != -1) {
420 return true;
421 }
422 std::this_thread::sleep_for(10ms);
423 }
424 return false;
425}
426
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600427#ifndef BUILD_TWRPTAR_MAIN
428
Dees_Troy38bd7602012-09-14 13:33:53 -0400429// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600430string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400431 string Local_Path = Path;
432
433 // Make sure that we have a leading slash
434 if (Local_Path.substr(0, 1) != "/")
435 Local_Path = "/" + Local_Path;
436
437 // Trim the path to get the root path only
438 size_t position = Local_Path.find("/", 2);
439 if (position != string::npos) {
440 Local_Path.resize(position);
441 }
442 return Local_Path;
443}
444
Dees_Troy43d8b002012-09-17 16:00:01 -0400445int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100446 std::vector<std::string> parts = Split_String(Path, "/", true);
447 std::string cur_path;
448 for (size_t i = 0; i < parts.size(); ++i) {
449 cur_path += "/" + parts[i];
450 if (!TWFunc::Path_Exists(cur_path)) {
451 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600452 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 -0600453 return false;
454 } else {
thatf1408b32016-01-03 11:09:15 +0100455 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600456 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400457 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400458 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400459 return true;
460}
461
Dees_Troyb46a6842012-09-25 11:06:46 -0400462void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
463 string Display_Text;
464
465 DataManager::GetValue(Read_Value, Display_Text);
466 if (Display_Text.empty())
467 Display_Text = Default_Text;
468
469 DataManager::SetValue("tw_operation", Display_Text);
470 DataManager::SetValue("tw_partition", "");
471}
472
473void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
474 string Display_Text;
475
476 DataManager::GetValue(Read_Value, Display_Text);
477 if (Display_Text.empty())
478 Display_Text = Default_Text;
479
480 DataManager::SetValue("tw_operation", Display_Text);
481 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400482}
483
Dees_Troy2673cec2013-04-02 20:22:16 +0000484void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400485 int logPipe[2];
486 int pigz_pid;
487 int destination_fd;
488 std::string destLogBuffer;
489
Dees Troy9d7fdf52013-09-19 20:49:25 +0000490 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400491
492 size_t extPos = Destination.find(".gz");
493 std::string uncompressedLog(Destination);
494 uncompressedLog.replace(extPos, Destination.length(), "");
495
496 if (Path_Exists(Destination)) {
497 Archive_Type type = Get_File_Type(Destination);
498 if (type == COMPRESSED) {
499 std::string destFileBuffer;
500 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400501 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400502 LOGINFO("Unable to get destination logfile contents.\n");
503 return;
504 }
505 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600506 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400507 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500508 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400509 std::stringstream uncompressedSS;
510 uncompressedSS << uncompressedIfs.rdbuf();
511 uncompressedIfs.close();
512 std::string uncompressedLogBuffer(uncompressedSS.str());
513 destLogBuffer.append(uncompressedLogBuffer);
514 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600515 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400516
bigbiffd3317052019-12-22 16:05:12 -0500517 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400518 std::stringstream ss;
519 ss << ifs.rdbuf();
520 std::string srcLogBuffer(ss.str());
521 ifs.close();
522
523 if (pipe(logPipe) < 0) {
524 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
525 }
526
527 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
528
529 pigz_pid = fork();
530 if (pigz_pid < 0) {
531 LOGINFO("fork() failed\n");
532 close(destination_fd);
533 close(logPipe[0]);
534 close(logPipe[1]);
535 } else if (pigz_pid == 0) {
536 close(logPipe[1]);
537 dup2(logPipe[0], fileno(stdin));
538 dup2(destination_fd, fileno(stdout));
539 if (execlp("pigz", "pigz", "-", NULL) < 0) {
540 close(destination_fd);
541 close(logPipe[0]);
542 _exit(-1);
543 }
544 } else {
545 close(logPipe[0]);
546 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
547 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
548 close(logPipe[1]);
549 close(destination_fd);
550 return;
551 }
552 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
553 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
554 close(logPipe[1]);
555 close(destination_fd);
556 return;
557 }
558 close(logPipe[1]);
559 }
560 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400561}
562
Dees_Troy2673cec2013-04-02 20:22:16 +0000563void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400564 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500565
bigbiff25d25b92020-06-19 16:07:38 -0400566 if (get_log_dir() == CACHE_LOGS_DIR) {
567 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
568 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000569 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000570 }
Dees_Troya58bead2012-09-27 09:49:29 -0400571
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500572 if (!TWFunc::Path_Exists(recoveryDir)) {
573 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400574 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500575 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
576 }
577 }
578
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400579 std::string logCopy = recoveryDir + "log.gz";
580 std::string lastLogCopy = recoveryDir + "last_log.gz";
Ethan Yonker5f3b8f02021-08-16 15:10:10 -0500581 copy_file(logCopy, lastLogCopy, 0600);
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500582 Copy_Log(TMP_LOG_FILE, logCopy);
583 chown(logCopy.c_str(), 1000, 1000);
584 chmod(logCopy.c_str(), 0600);
585 chmod(lastLogCopy.c_str(), 0640);
586
bigbiff25d25b92020-06-19 16:07:38 -0400587 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500588 if (PartitionManager.Mount_By_Path("/cache", false)) {
589 if (unlink("/cache/recovery/command") && errno != ENOENT) {
590 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
591 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000592 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500593 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000594 sync();
595}
596
bigbiffdf8436b2020-08-30 16:22:34 -0400597void TWFunc::Clear_Bootloader_Message() {
598 std::string err;
599 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100600 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400601 }
602}
603
Dees_Troy2673cec2013-04-02 20:22:16 +0000604void TWFunc::Update_Intent_File(string Intent) {
605 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600606 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000607 }
Dees_Troya58bead2012-09-27 09:49:29 -0400608}
609
610// reboot: Reboot the system. Return -1 on error, no return on success
611int TWFunc::tw_reboot(RebootCommand command)
612{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500613 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400614 Update_Log_File();
615
Dees_Troya58bead2012-09-27 09:49:29 -0400616 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600617 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400618
Dees_Troy2673cec2013-04-02 20:22:16 +0000619 switch (command) {
620 case rb_current:
621 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000622 Update_Intent_File("s");
623 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400624 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500625#ifdef ANDROID_RB_PROPERTY
626 return property_set(ANDROID_RB_PROPERTY, "reboot,");
627#elif defined(ANDROID_RB_RESTART)
628 return android_reboot(ANDROID_RB_RESTART, 0, 0);
629#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000630 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500631#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000632 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400633 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500634 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000635 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400636 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500637 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000638 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400639 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500640#ifdef ANDROID_RB_PROPERTY
641 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
642#elif defined(ANDROID_RB_POWEROFF)
643 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
644#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000645 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500646#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000647 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400648 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500649 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200650 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400651 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200652 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400653 case rb_fastboot:
654 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000655 default:
656 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600657 }
658 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400659}
660
661void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
662{
663 // Check for and run startup script if script exists
664 struct stat st;
665 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500666 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500667 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200668 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500669 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400670 }
Dees_Troy3477d712012-09-27 15:44:01 -0400671}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500672
673int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000674 DIR *d = opendir(path.c_str());
675 int r = 0;
676 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500677
Dees_Troyce675462013-01-09 19:48:21 +0000678 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500679 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000680 return -1;
681 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500682
Dees_Troyce675462013-01-09 19:48:21 +0000683 if (d) {
684 struct dirent *p;
685 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000686 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
687 continue;
688 new_path = path + "/";
689 new_path.append(p->d_name);
690 if (p->d_type == DT_DIR) {
691 r = removeDir(new_path, true);
692 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500693 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500694 r = rmdir(new_path.c_str());
695 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000696 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500697 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500698 } 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 +0000699 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000700 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000701 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000702 }
Dees_Troyce675462013-01-09 19:48:21 +0000703 }
704 }
705 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500706
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500707 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500708 if (skipParent)
709 return 0;
710 else
711 r = rmdir(path.c_str());
712 }
Dees_Troyce675462013-01-09 19:48:21 +0000713 }
714 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500715}
716
bigbiff22851b92021-09-01 16:46:57 -0400717int TWFunc::copy_file(string src, string dst, int mode, bool mount_paths) {
718 if (mount_paths) {
719 PartitionManager.Mount_By_Path(src, false);
720 PartitionManager.Mount_By_Path(dst, false);
721 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400722 if (!Path_Exists(src)) {
bigbiff22851b92021-09-01 16:46:57 -0400723 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 -0400724 return -1;
725 }
bigbiffd3317052019-12-22 16:05:12 -0500726 std::ifstream srcfile(src.c_str(), ios::binary);
727 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500728 dstfile << srcfile.rdbuf();
bigbiff850fa282021-10-09 12:37:29 -0400729 if (dstfile.bad()) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400730 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
731 return -1;
732 }
733
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500734 srcfile.close();
735 dstfile.close();
bigbiff22851b92021-09-01 16:46:57 -0400736 if (chmod(dst.c_str(), mode) != 0) {
737 LOGERR("Unable to chmod file: %s. Error: %s\n", dst.c_str(), strerror(errno));
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500738 return -1;
bigbiff22851b92021-09-01 16:46:57 -0400739 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500740 return 0;
741}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000742
743unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
744 struct stat st;
745
746 stat(Path.c_str(), &st);
747 if (st.st_mode & S_IFDIR)
748 return DT_DIR;
749 else if (st.st_mode & S_IFBLK)
750 return DT_BLK;
751 else if (st.st_mode & S_IFCHR)
752 return DT_CHR;
753 else if (st.st_mode & S_IFIFO)
754 return DT_FIFO;
755 else if (st.st_mode & S_IFLNK)
756 return DT_LNK;
757 else if (st.st_mode & S_IFREG)
758 return DT_REG;
759 else if (st.st_mode & S_IFSOCK)
760 return DT_SOCK;
761 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000762}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500763
764int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200765 ifstream file;
766 file.open(fn.c_str(), ios::in);
767
768 if (file.is_open()) {
bigbiff22851b92021-09-01 16:46:57 -0400769 std::string line;
770 while (std::getline(file, line)) {
771 results += line;
772 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200773 file.close();
774 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500775 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200776
777 LOGINFO("Cannot find file %s\n", fn.c_str());
778 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500779}
780
781int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500782 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500783 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500784 file.open(fn.c_str(), ios::in);
785 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500786 while (getline(file, line))
787 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500788 file.close();
789 return 0;
790 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000791 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500792 return -1;
793}
794
xNUTxe85f02d2014-07-18 01:30:58 +0200795int TWFunc::read_file(string fn, uint64_t& results) {
796 ifstream file;
797 file.open(fn.c_str(), ios::in);
798
799 if (file.is_open()) {
800 file >> results;
801 file.close();
802 return 0;
803 }
804
805 LOGINFO("Cannot find file %s\n", fn.c_str());
806 return -1;
807}
808
bigbiff22851b92021-09-01 16:46:57 -0400809bool TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500810 FILE *file;
811 file = fopen(fn.c_str(), "w");
812 if (file != NULL) {
813 fwrite(line.c_str(), line.size(), 1, file);
814 fclose(file);
bigbiff22851b92021-09-01 16:46:57 -0400815 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500816 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000817 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff22851b92021-09-01 16:46:57 -0400818 return false;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500819}
820
bigbiff22851b92021-09-01 16:46:57 -0400821bool TWFunc::write_to_file(const string& fn, const std::vector<string> lines) {
822 FILE *file;
823 file = fopen(fn.c_str(), "a+");
824 if (file != NULL) {
825 for (auto&& line: lines) {
826 fwrite(line.c_str(), line.size(), 1, file);
827 fwrite("\n", sizeof(char), 1, file);
828 }
829 fclose(file);
830 return true;
831 }
832 return false;
833}
834
835
Dees_Troy83bd4832013-05-04 12:39:56 +0000836bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
837 DIR* d;
838
839 string Filename;
840 Restore_Path += "/";
841 d = opendir(Restore_Path.c_str());
842 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500843 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000844 return false;
845 }
846
847 struct dirent* de;
848 while ((de = readdir(d)) != NULL) {
849 Filename = Restore_Path;
850 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500851 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000852 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
853 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
854 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
855 closedir(d);
856 return false;
857 }
858 }
859 }
860 closedir(d);
861 return true;
862}
863
Dees Troyb21cc642013-09-10 17:36:41 +0000864string TWFunc::Get_Current_Date() {
865 string Current_Date;
866 time_t seconds = time(0);
867 struct tm *t = localtime(&seconds);
868 char timestamp[255];
869 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);
870 Current_Date = timestamp;
871 return Current_Date;
872}
873
Ethan Yonkerb5557892014-02-07 21:43:20 -0600874string TWFunc::System_Property_Get(string Prop_Name) {
Captain Throwback1483a8e2022-01-03 09:52:06 -0500875 return Partition_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path(), "build.prop");
Chaosmaster65633a42020-02-05 15:24:09 +0100876}
877
Captain Throwback1483a8e2022-01-03 09:52:06 -0500878string TWFunc::Partition_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point, string prop_file_name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100879 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000880 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600881 string propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500882 string prop_file;
Chaosmaster65633a42020-02-05 15:24:09 +0100883 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600884 return propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500885 if (Mount_Point == PartitionManager.Get_Android_Root_Path()) {
886 prop_file = Mount_Point + "/system/" + prop_file_name;
887 } else {
888 prop_file = Mount_Point + "/" + prop_file_name;
889 }
Captain Throwback2b9ea722021-12-31 21:35:52 -0500890 if (!TWFunc::Path_Exists(prop_file)) {
891 LOGINFO("Unable to locate file: %s\n", prop_file.c_str());
892 return propvalue;
893 }
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600894 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback2b9ea722021-12-31 21:35:52 -0500895 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 +0200896 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000897 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100898 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600899 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000900 }
901 int line_count = buildprop.size();
902 int index;
903 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600904 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000905 for (index = 0; index < line_count; index++) {
906 end_pos = buildprop.at(index).find("=", start_pos);
907 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600908 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000909 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600910 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100911 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600912 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000913 }
914 }
Dees Troyb21cc642013-09-10 17:36:41 +0000915 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100916 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600917 return propvalue;
918}
919
920void TWFunc::Auto_Generate_Backup_Name() {
921 string propvalue = System_Property_Get("ro.build.display.id");
922 if (propvalue.empty()) {
923 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
924 return;
925 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400926 else {
927 //remove periods from build display so it doesn't confuse the extension code
928 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
929 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600930 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500931 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600932 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
933 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
934 // Trailing spaces cause problems on some file systems, so remove them
935 string space_check, space = " ";
936 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
937 while (space_check == space) {
938 Backup_Name.resize(Backup_Name.size() - 1);
939 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
940 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500941 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600942 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
943 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600944 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600945 } else {
946 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600947 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200948}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100949
nkk7198fc3992017-12-16 16:26:42 +0200950void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100951{
952#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200953 static bool fixed = false;
954 if (fixed)
955 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200956
957 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
958
959 struct timeval tv;
960 uint64_t offset = 0;
961 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
962
963 if (TWFunc::read_file(sepoch, offset) == 0) {
964
965 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
966
967 tv.tv_sec = offset;
968 tv.tv_usec = 0;
969 settimeofday(&tv, NULL);
970
971 gettimeofday(&tv, NULL);
972
Phoenix59146b05f22018-02-03 06:41:08 +0000973 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 +0200974
975 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200976 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200977 return;
978
979 }
980
981 } else {
982
983 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
984
985 }
986
Ethan Yonker9132d912015-02-02 10:32:49 -0600987 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200988
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100989 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
990 // They never set it, it just ticks forward from 1970-01-01 00:00,
991 // and then they have files /data/system/time/ats_* with 64bit offset
992 // in miliseconds which, when added to the RTC, gives the correct time.
993 // So, the time is: (offset_from_ats + value_from_RTC)
994 // There are multiple ats files, they are for different systems? Bases?
995 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
996 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
997
nkk7198fc3992017-12-16 16:26:42 +0200998 std::vector<std::string> paths; // space separated list of paths
999 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +01001000 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +02001001 if (!PartitionManager.Mount_By_Path("/data", false))
1002 return;
1003 } else {
1004 // When specific path(s) are used, Fixup_Time needs those
1005 // partitions to already be mounted!
1006 paths = Split_String(time_paths, " ");
1007 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001008
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001009 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001010 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001011 struct dirent *dt;
1012 std::string ats_path;
1013
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001014 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1015 // - it is the one for ATS_TOD (time of day?).
1016 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001017 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001018 {
nkk7198fc3992017-12-16 16:26:42 +02001019 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001020 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001021 continue;
1022
Matt Mowera8a89d12016-12-30 18:10:37 -06001023 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001024 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001025 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001026 continue;
1027
Matt Mowera8a89d12016-12-30 18:10:37 -06001028 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001029 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001030 }
1031
1032 closedir(d);
1033 }
1034
nkk7198fc3992017-12-16 16:26:42 +02001035 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001036 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001037 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001038 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001039 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001040 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001041 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001042 } else {
1043 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001044
nkk7198fc3992017-12-16 16:26:42 +02001045 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1046 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1047 fixed = true;
1048 }
1049
1050 if (!fixed) {
Captain Throwbackf74fc052022-01-19 13:25:54 -05001051#ifdef TW_QCOM_ATS_OFFSET
1052 // Offset is the difference between the current time and the time since_epoch
1053 // To calculate the offset in Android, the following expression (from a root shell) can be used:
1054 // echo "$(( ($(date +%s) - $(cat /sys/class/rtc/rtc0/since_epoch)) ))"
1055 // Add 3 zeros to the output and use that in the TW_QCOM_ATS_OFFSET flag in your BoardConfig.mk
1056 // For example, if the result of the calculation is 1642433544, use 1642433544000 as the offset
1057 offset = (uint64_t) TW_QCOM_ATS_OFFSET;
1058 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1059 LOGINFO("TWFunc::Fixup_Time: Setting time offset from TW_QCOM_ATS_OFFSET, offset %llu\n", (unsigned long long) offset);
1060#else
nkk7198fc3992017-12-16 16:26:42 +02001061 // Failed to get offset from ats file, check twrp settings
1062 unsigned long long value;
1063 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1064 return;
1065 } else {
1066 offset = (uint64_t) value;
1067 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1068 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1069 }
Captain Throwbackf74fc052022-01-19 13:25:54 -05001070#endif
nkk7198fc3992017-12-16 16:26:42 +02001071 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001072
1073 gettimeofday(&tv, NULL);
1074
1075 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001076#ifdef TW_CLOCK_OFFSET
1077// Some devices are even quirkier and have ats files that are offset from the actual time
1078 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1079#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001080 tv.tv_usec += (offset%1000)*1000;
1081
Matt Mowera8a89d12016-12-30 18:10:37 -06001082 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001083 {
1084 ++tv.tv_sec;
1085 tv.tv_usec -= 1000000;
1086 }
1087
1088 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001089
1090 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001091#endif
1092}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001093
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001094std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1095{
1096 std::vector<std::string> res;
1097 size_t idx = 0, idx_last = 0;
1098
Matt Mowera8a89d12016-12-30 18:10:37 -06001099 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001100 {
1101 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001102 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001103 idx = str.size();
1104
Matt Mowera8a89d12016-12-30 18:10:37 -06001105 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001106 res.push_back(str.substr(idx_last, idx-idx_last));
1107
1108 idx_last = idx + delimiter.size();
1109 }
1110
1111 return res;
1112}
1113
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001114bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1115{
1116 std::vector<std::string> parts = Split_String(path, "/");
1117 std::string cur_path;
1118 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001119 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001120 {
1121 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001122 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001123 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001124 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001125 return false;
1126 chown(cur_path.c_str(), uid, gid);
1127 }
1128 }
1129 return true;
1130}
1131
xNUTxe85f02d2014-07-18 01:30:58 +02001132int TWFunc::Set_Brightness(std::string brightness_value)
1133{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001134 int result = -1;
1135 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001136
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001137 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001138 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001139 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001140 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1141 if (!secondary_brightness_file.empty()) {
1142 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001143 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001144 }
xNUTxe85f02d2014-07-18 01:30:58 +02001145 }
bigbiff22851b92021-09-01 16:46:57 -04001146 return result ? 0 : -1;
xNUTxe85f02d2014-07-18 01:30:58 +02001147}
1148
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001149bool TWFunc::Toggle_MTP(bool enable) {
1150#ifdef TW_HAS_MTP
1151 static int was_enabled = false;
1152
1153 if (enable && was_enabled) {
1154 if (!PartitionManager.Enable_MTP())
1155 PartitionManager.Disable_MTP();
1156 } else {
1157 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1158 PartitionManager.Disable_MTP();
1159 usleep(500);
1160 }
1161 return was_enabled;
1162#else
1163 return false;
1164#endif
1165}
1166
Tom Hite5a926722014-09-15 01:31:03 +00001167void TWFunc::SetPerformanceMode(bool mode) {
1168 if (mode) {
1169 property_set("recovery.perf.mode", "1");
1170 } else {
1171 property_set("recovery.perf.mode", "0");
1172 }
1173 // Some time for events to catch up to init handlers
1174 usleep(500000);
1175}
1176
Jenkins1710bf22014-10-02 20:22:21 -04001177std::string TWFunc::to_string(unsigned long value) {
1178 std::ostringstream os;
1179 os << value;
1180 return os.str();
1181}
1182
Ethan Yonker9132d912015-02-02 10:32:49 -06001183void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001184 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001185 // Disable flashing of stock recovery
1186 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1187 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001188 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 -06001189 sync();
1190 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001191 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001192 }
1193}
1194
Ethan Yonker483e9f42016-01-11 22:21:18 -06001195unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1196 unsigned long block_device_size;
1197 int ret = 0;
1198
1199 int fd = open(block_device, O_RDONLY);
1200 if (fd < 0) {
1201 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1202 } else {
1203 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1204 close(fd);
1205 if (ret) {
1206 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1207 } else {
1208 return (unsigned long long)(block_device_size) * 512LLU;
1209 }
1210 }
1211 return 0;
1212}
1213
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001214void TWFunc::copy_kernel_log(string curr_storage) {
1215 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001216 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001217
1218 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001219 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001220 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001221 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1222 tw_set_default_metadata(dmesgDst.c_str());
1223}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001224
Captain Throwback52978932021-09-05 15:11:07 -04001225void TWFunc::copy_logcat(string curr_storage) {
1226 std::string logcatDst = curr_storage + "/logcat.txt";
1227 std::string logcatCmd = "logcat -d";
1228
1229 std::string result;
1230 Exec_Cmd(logcatCmd, result, false);
1231 write_to_file(logcatDst, result);
1232 gui_msg(Msg("copy_logcat=Copied logcat to {1}")(logcatDst));
1233 tw_set_default_metadata(logcatDst.c_str());
1234}
1235
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001236bool TWFunc::isNumber(string strtocheck) {
1237 int num = 0;
1238 std::istringstream iss(strtocheck);
1239
1240 if (!(iss >> num).fail())
1241 return true;
1242 else
1243 return false;
1244}
1245
1246int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001247 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001248 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1249 int ret = TWFunc::Exec_Cmd(cmd);
1250 if (ret != 0)
1251 return -1;
1252 return ret;
1253}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001254
bigbiff25d25b92020-06-19 16:07:38 -04001255std::string TWFunc::get_log_dir() {
1256 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1257 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001258 LOGINFO("Unable to find a directory to store TWRP logs.");
1259 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001260 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001261 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001262 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001263 }
1264 else {
bigbiff25d25b92020-06-19 16:07:38 -04001265 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001266 }
1267}
1268
1269void TWFunc::check_selinux_support() {
1270 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1271 if (TWFunc::Path_Exists("/file_contexts")) {
1272 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1273 rename("/file_contexts", "/file_contexts.bak");
1274 }
1275 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1276 rename("/prebuilt_file_contexts", "/file_contexts");
1277 }
1278 struct selinux_opt selinux_options[] = {
1279 { SELABEL_OPT_PATH, "/file_contexts" }
1280 };
1281 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1282 if (!selinux_handle)
1283 printf("No file contexts for SELinux\n");
1284 else
1285 printf("SELinux contexts loaded from /file_contexts\n");
1286 { // Check to ensure SELinux can be supported by the kernel
1287 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001288 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001289 std::string se_context_check = cacheDir + "recovery/";
1290 int ret = 0;
1291
bigbiff25d25b92020-06-19 16:07:38 -04001292 if (cacheDir == CACHE_LOGS_DIR) {
1293 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001294 }
1295 if (TWFunc::Path_Exists(se_context_check)) {
1296 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001297 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001298 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1299 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001300 }
1301 }
1302 if (ret < 0) {
1303 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1304 } else {
1305 free(contexts);
1306 gui_msg("full_selinux=Full SELinux support is present.");
1307 }
1308 }
1309}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001310
1311bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001312 LOGINFO("checking for twrp app\n");
1313 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1314 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001315 bool is_system_mounted = true;
1316 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1317 is_system_mounted = false;
1318 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001319 }
Captain Throwback31c14922020-12-21 11:28:34 -05001320 string base_path = PartitionManager.Get_Android_Root_Path();
1321 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1322 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1323 string install_path = base_path + "/priv-app";
1324 if (!TWFunc::Path_Exists(install_path))
1325 install_path = base_path + "/app";
1326 install_path += "/twrpapp";
1327 if (TWFunc::Path_Exists(install_path)) {
1328 LOGINFO("App found at '%s'\n", install_path.c_str());
1329 DataManager::SetValue("tw_app_installed_in_system", 1);
1330 return true;
1331 }
1332 if (!is_system_mounted)
1333 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001334 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001335 }
1336 DataManager::SetValue("tw_app_installed_in_system", 0);
1337 return false;
1338}
Chaosmaster461e39f2020-02-07 01:48:13 +01001339
epicX271bb3a2020-12-30 01:03:18 +05301340void TWFunc::checkforapp(){
1341
1342 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1343 int sdkver = 0;
1344 if (!sdkverstr.empty()) {
1345 sdkver = atoi(sdkverstr.c_str());
1346 }
1347 if (sdkver <= 13) {
1348 if (sdkver == 0)
1349 LOGINFO("Unable to read sdk version from build prop\n");
1350 else
1351 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1352 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1353 goto exit;
1354 }
1355 if (Is_TWRP_App_In_System()) {
1356 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1357 goto exit;
1358 }
1359 if (PartitionManager.Mount_By_Path("/data", false)) {
1360 const char parent_path[] = "/data/app";
1361 const char app_prefix[] = "me.twrp.twrpapp-";
1362 DIR *d = opendir(parent_path);
1363 if (d) {
1364 struct dirent *p;
1365 while ((p = readdir(d))) {
1366 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1367 continue;
1368 closedir(d);
1369 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1370 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1371 goto exit;
1372 }
1373 closedir(d);
1374 }
1375 } else {
1376 LOGINFO("Data partition cannot be mounted during app check\n");
1377 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1378 }
1379
1380 LOGINFO("App not installed\n");
1381 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1382exit:
1383 return;
1384
1385}
1386
Chaosmaster461e39f2020-02-07 01:48:13 +01001387int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1388#ifdef TW_INCLUDE_LIBRESETPROP
1389 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1390#else
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001391 return NOT_AVAILABLE;
1392#endif
1393}
1394
1395int TWFunc::Delete_Property(string Prop_Name) {
1396#ifdef TW_INCLUDE_LIBRESETPROP
1397 return delprop(Prop_Name.c_str(), false);
1398#else
1399 return NOT_AVAILABLE;
Chaosmaster461e39f2020-02-07 01:48:13 +01001400#endif
1401}
1402
bigbiffee7b7ff2020-03-23 15:08:27 -04001403void TWFunc::List_Mounts() {
1404 std::vector<std::string> mounts;
1405 read_file("/proc/mounts", mounts);
1406 LOGINFO("Mounts:\n");
1407 for (auto&& mount: mounts) {
1408 LOGINFO("%s\n", mount.c_str());
1409 }
1410}
1411
epicXa721f952021-01-04 13:01:31 +05301412string TWFunc::Check_For_TwrpFolder() {
1413 string oldFolder = "";
1414 vector<string> customTWRPFolders;
1415 string mainPath = DataManager::GetCurrentStoragePath();
1416 DIR* d;
1417 struct dirent* de;
1418
Fernando Oliveira073c4302022-10-19 13:33:47 -03001419 if (DataManager::GetIntValue(TW_IS_ENCRYPTED) && DataManager::GetIntValue(TW_CRYPTO_PWTYPE)) {
epicXa721f952021-01-04 13:01:31 +05301420 goto exit;
1421 }
1422
1423
1424 d = opendir(mainPath.c_str());
1425 if (d == NULL) {
1426 goto exit;
1427 }
1428
1429 while ((de = readdir(d)) != NULL) {
1430 string name = de->d_name;
1431 string fullPath = mainPath + '/' + name;
1432 unsigned char type = de->d_type;
1433
epicX11e90832021-03-01 00:02:57 +05301434 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301435
epicX11e90832021-03-01 00:02:57 +05301436 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301437 type = Get_D_Type_From_Stat(fullPath);
1438 }
1439
Fernando Oliveira25062d72023-02-01 12:52:32 -03001440 if (type == DT_DIR && Path_Exists(fullPath + "/.twrpcf")) {
epicX11e90832021-03-01 00:02:57 +05301441 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301442 oldFolder = name;
1443 } else {
1444 customTWRPFolders.push_back(name);
1445 }
1446 }
1447 }
1448
1449 closedir(d);
1450
epicX11e90832021-03-01 00:02:57 +05301451 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301452 LOGINFO("No recovery folder found. Using default folder.\n");
Fernando Oliveira25062d72023-02-01 12:52:32 -03001453 //Creates the TWRP folder if it does not exist on the device and if the folder has not been changed to a new name
1454 mainPath += TW_DEFAULT_RECOVERY_FOLDER;
1455 mkdir(mainPath.c_str(), 0777);
epicXa721f952021-01-04 13:01:31 +05301456 goto exit;
epicX11e90832021-03-01 00:02:57 +05301457 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301458 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1459 goto exit;
1460 } else {
epicX11e90832021-03-01 00:02:57 +05301461 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301462 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1463 } else {
1464 LOGINFO("One custom recovery folder found.\n");
1465 }
1466 string customPath = '/' + customTWRPFolders.at(0);
1467
epicX11e90832021-03-01 00:02:57 +05301468 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301469 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1470 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1471
epicX11e90832021-03-01 00:02:57 +05301472 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301473 vector<string> backups;
1474 d = opendir(oldBackupFolder.c_str());
1475
1476 if (d != NULL) {
1477 while ((de = readdir(d)) != NULL) {
1478 string name = de->d_name;
1479 unsigned char type = de->d_type;
1480
epicX11e90832021-03-01 00:02:57 +05301481 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301482
epicX11e90832021-03-01 00:02:57 +05301483 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301484 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1485 }
1486
epicX11e90832021-03-01 00:02:57 +05301487 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301488 backups.push_back(name);
1489 }
1490 }
1491 closedir(d);
1492 }
1493
epicX11e90832021-03-01 00:02:57 +05301494 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301495 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1496 }
1497 }
1498 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1499 }
1500
1501 return customPath;
1502 }
1503
1504exit:
1505 return TW_DEFAULT_RECOVERY_FOLDER;
1506}
Darth98f775972022-08-05 09:39:03 +01001507
1508bool TWFunc::Check_Xml_Format(const std::string filename) {
1509 std::string buffer(' ', 4);
1510 std::string abx_hdr("ABX\x00", 4);
1511 std::ifstream File;
1512 File.open(filename);
1513 if (File.is_open()) {
1514 File.get(&buffer[0], buffer.size());
1515 File.close();
1516 // Android Binary Xml start from these bytes
1517 if(!buffer.compare(0, abx_hdr.size(), abx_hdr))
1518 return false; // ABX format - requires conversion
1519 }
1520 return true; // good format, possible to parse
1521}
1522
1523// return true=successful conversion (return the name of the converted file in "result");
1524// return false=an error happened (leave "result" alone)
1525bool TWFunc::abx_to_xml(const std::string path, std::string &result) {
1526 bool res = false;
1527 if (!TWFunc::Path_Exists(path))
1528 return res;
1529
1530 std::ifstream infile(path);
1531 if (!infile.is_open())
1532 return res;
1533
1534 std::string fname = TWFunc::Get_Filename(path);
1535 std::string tmp = "/tmp/converted_xml";
1536 if (!TWFunc::Path_Exists(tmp)) {
1537 if (mkdir(tmp.c_str(), 0777) != 0)
1538 tmp = "/tmp";
1539 }
1540
1541 std::string tmp_path = tmp + "/" + fname;
1542 std::ofstream outfile(tmp_path);
1543 if (!outfile.is_open()) {
1544 LOGINFO("Error. The abx conversion of %s has failed.\n", path.c_str());
1545 infile.close();
1546 return res;
1547 }
1548
1549 AbxToXml r(infile, outfile);
1550 if (r.run() && TWFunc::Path_Exists(tmp_path)) {
1551 res = true;
1552 result = tmp_path;
1553 }
1554
1555 infile.close();
1556 outfile.close();
1557
1558 return res;
1559}
1560
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001561std::string GetFstabPath() {
1562 for (const char* prop : {"fstab_suffix", "hardware", "hardware.platform"}) {
1563 std::string suffix;
1564
1565 if (!fs_mgr_get_boot_config(prop, &suffix)) continue;
1566
1567 for (const char* prefix : {// late-boot/post-boot locations
1568 "/odm/etc/fstab.", "/vendor/etc/fstab.",
1569 // early boot locations
1570 "/system/etc/fstab.", "/first_stage_ramdisk/system/etc/fstab.",
1571 "/fstab.", "/first_stage_ramdisk/fstab."}) {
1572 std::string fstab_path = prefix + suffix;
1573 LOGINFO("%s: %s\n", __func__, fstab_path.c_str());
1574 if (access(fstab_path.c_str(), F_OK) == 0) return fstab_path;
1575 }
1576 }
1577
1578 return "";
1579}
1580
1581bool TWFunc::Find_Fstab(string &fstab) {
1582 fstab = GetFstabPath();
1583 if (fstab == "") return false;
1584 return true;
1585}
1586
1587bool TWFunc::Get_Service_From(TWPartition *Partition, std::string Service, std::string &Res) {
1588 Partition->Mount(true);
1589 std::string Path = Partition->Get_Mount_Point() + "/etc/init/";
1590 std::string Name;
1591 std::vector<std::string> Data;
1592 bool Found = false, ret = false;
1593 DIR* dir;
1594 struct dirent* der;
1595 dir = opendir(Path.c_str());
1596 while ((der = readdir(dir)) != NULL)
1597 {
1598 Name = der->d_name;
1599 if (Name.find(Service) != string::npos) {
1600 Found = true;
1601 Path += Name;
1602 break;
1603 }
1604 }
1605 closedir(dir);
1606
1607 if (!Found) {
1608 LOGINFO("Unable to locate service RC\n");
1609 goto finish;
1610 }
1611
1612 if (read_file(Path, Data) != 0) {
1613 LOGINFO("Unable to read file '%s'\n", Path.c_str());
1614 goto finish;
1615 }
1616
1617 for (int index = 0; index < Data.size(); index++) {
1618 Name = Data.at(index);
1619 if (Name.find("service") != string::npos) {
1620 Res = Name.substr(Name.find_last_of('/')+1);
1621 ret = true;
1622 goto finish;
1623 }
1624 }
1625
1626finish:
1627 Partition->UnMount(true);
1628 return ret;
1629}
1630
1631std::string TWFunc::Get_Version_From_Service(std::string name) {
1632 int start, end;
1633 start = name.find('@') + 1;
1634 end = name.find("-") - start;
1635 return name.substr(start, end);
1636}
1637
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001638#endif // ndef BUILD_TWRPTAR_MAIN