blob: 51d252ac1904252fa8f60941e54f72a2c86d3a61 [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
427bool TWFunc::Wait_For_Battery(std::chrono::nanoseconds timeout) {
428 std::string battery_path;
429#ifdef TW_CUSTOM_BATTERY_PATH
430 battery_path = EXPAND(TW_CUSTOM_BATTERY_PATH);
431#else
432 battery_path = "/sys/class/power_supply/battery";
433#endif
434 if (!battery_path.empty()) return TWFunc::Wait_For_File(battery_path, timeout);
435
436 return false;
437}
438
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600439#ifndef BUILD_TWRPTAR_MAIN
440
Dees_Troy38bd7602012-09-14 13:33:53 -0400441// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600442string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400443 string Local_Path = Path;
444
445 // Make sure that we have a leading slash
446 if (Local_Path.substr(0, 1) != "/")
447 Local_Path = "/" + Local_Path;
448
449 // Trim the path to get the root path only
450 size_t position = Local_Path.find("/", 2);
451 if (position != string::npos) {
452 Local_Path.resize(position);
453 }
454 return Local_Path;
455}
456
Dees_Troy43d8b002012-09-17 16:00:01 -0400457int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100458 std::vector<std::string> parts = Split_String(Path, "/", true);
459 std::string cur_path;
460 for (size_t i = 0; i < parts.size(); ++i) {
461 cur_path += "/" + parts[i];
462 if (!TWFunc::Path_Exists(cur_path)) {
463 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600464 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 -0600465 return false;
466 } else {
thatf1408b32016-01-03 11:09:15 +0100467 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600468 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400469 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400470 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400471 return true;
472}
473
Dees_Troyb46a6842012-09-25 11:06:46 -0400474void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
475 string Display_Text;
476
477 DataManager::GetValue(Read_Value, Display_Text);
478 if (Display_Text.empty())
479 Display_Text = Default_Text;
480
481 DataManager::SetValue("tw_operation", Display_Text);
482 DataManager::SetValue("tw_partition", "");
483}
484
485void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
486 string Display_Text;
487
488 DataManager::GetValue(Read_Value, Display_Text);
489 if (Display_Text.empty())
490 Display_Text = Default_Text;
491
492 DataManager::SetValue("tw_operation", Display_Text);
493 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400494}
495
Dees_Troy2673cec2013-04-02 20:22:16 +0000496void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400497 int logPipe[2];
498 int pigz_pid;
499 int destination_fd;
500 std::string destLogBuffer;
501
Dees Troy9d7fdf52013-09-19 20:49:25 +0000502 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400503
504 size_t extPos = Destination.find(".gz");
505 std::string uncompressedLog(Destination);
506 uncompressedLog.replace(extPos, Destination.length(), "");
507
508 if (Path_Exists(Destination)) {
509 Archive_Type type = Get_File_Type(Destination);
510 if (type == COMPRESSED) {
511 std::string destFileBuffer;
512 std::string getCompressedContents = "pigz -c -d " + Destination;
bigbiffad58e1b2020-07-06 20:24:34 -0400513 if (Exec_Cmd(getCompressedContents, destFileBuffer, false) < 0) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400514 LOGINFO("Unable to get destination logfile contents.\n");
515 return;
516 }
517 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600518 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400519 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500520 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400521 std::stringstream uncompressedSS;
522 uncompressedSS << uncompressedIfs.rdbuf();
523 uncompressedIfs.close();
524 std::string uncompressedLogBuffer(uncompressedSS.str());
525 destLogBuffer.append(uncompressedLogBuffer);
526 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600527 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400528
bigbiffd3317052019-12-22 16:05:12 -0500529 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400530 std::stringstream ss;
531 ss << ifs.rdbuf();
532 std::string srcLogBuffer(ss.str());
533 ifs.close();
534
535 if (pipe(logPipe) < 0) {
536 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
537 }
538
539 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
540
541 pigz_pid = fork();
542 if (pigz_pid < 0) {
543 LOGINFO("fork() failed\n");
544 close(destination_fd);
545 close(logPipe[0]);
546 close(logPipe[1]);
547 } else if (pigz_pid == 0) {
548 close(logPipe[1]);
549 dup2(logPipe[0], fileno(stdin));
550 dup2(destination_fd, fileno(stdout));
551 if (execlp("pigz", "pigz", "-", NULL) < 0) {
552 close(destination_fd);
553 close(logPipe[0]);
554 _exit(-1);
555 }
556 } else {
557 close(logPipe[0]);
558 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
559 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
560 close(logPipe[1]);
561 close(destination_fd);
562 return;
563 }
564 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
565 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
566 close(logPipe[1]);
567 close(destination_fd);
568 return;
569 }
570 close(logPipe[1]);
571 }
572 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400573}
574
Dees_Troy2673cec2013-04-02 20:22:16 +0000575void TWFunc::Update_Log_File(void) {
bigbiff25d25b92020-06-19 16:07:38 -0400576 std::string recoveryDir = get_log_dir() + "recovery/";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500577
bigbiff25d25b92020-06-19 16:07:38 -0400578 if (get_log_dir() == CACHE_LOGS_DIR) {
579 if (!PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false)) {
580 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", CACHE_LOGS_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000581 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000582 }
Dees_Troya58bead2012-09-27 09:49:29 -0400583
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500584 if (!TWFunc::Path_Exists(recoveryDir)) {
585 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400586 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500587 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
588 }
589 }
590
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400591 std::string logCopy = recoveryDir + "log.gz";
592 std::string lastLogCopy = recoveryDir + "last_log.gz";
Ethan Yonker5f3b8f02021-08-16 15:10:10 -0500593 copy_file(logCopy, lastLogCopy, 0600);
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500594 Copy_Log(TMP_LOG_FILE, logCopy);
595 chown(logCopy.c_str(), 1000, 1000);
596 chmod(logCopy.c_str(), 0600);
597 chmod(lastLogCopy.c_str(), 0640);
598
bigbiff25d25b92020-06-19 16:07:38 -0400599 if (get_log_dir() == CACHE_LOGS_DIR) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500600 if (PartitionManager.Mount_By_Path("/cache", false)) {
601 if (unlink("/cache/recovery/command") && errno != ENOENT) {
602 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
603 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000604 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500605 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000606 sync();
607}
608
bigbiffdf8436b2020-08-30 16:22:34 -0400609void TWFunc::Clear_Bootloader_Message() {
610 std::string err;
611 if (!clear_bootloader_message(&err)) {
Ian Macdonaldd4851822020-11-02 08:52:32 +0100612 LOGINFO("%s\n", err.c_str());
bigbiffdf8436b2020-08-30 16:22:34 -0400613 }
614}
615
Dees_Troy2673cec2013-04-02 20:22:16 +0000616void TWFunc::Update_Intent_File(string Intent) {
617 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600618 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000619 }
Dees_Troya58bead2012-09-27 09:49:29 -0400620}
621
622// reboot: Reboot the system. Return -1 on error, no return on success
623int TWFunc::tw_reboot(RebootCommand command)
624{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500625 DataManager::Flush();
bigbiff25d25b92020-06-19 16:07:38 -0400626 Update_Log_File();
627
Dees_Troya58bead2012-09-27 09:49:29 -0400628 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600629 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400630
Dees_Troy2673cec2013-04-02 20:22:16 +0000631 switch (command) {
632 case rb_current:
633 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000634 Update_Intent_File("s");
635 sync();
bigbiffad58e1b2020-07-06 20:24:34 -0400636 check_and_run_script("/system/bin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500637#ifdef ANDROID_RB_PROPERTY
638 return property_set(ANDROID_RB_PROPERTY, "reboot,");
639#elif defined(ANDROID_RB_RESTART)
640 return android_reboot(ANDROID_RB_RESTART, 0, 0);
641#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000642 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500643#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000644 case rb_recovery:
bigbiffad58e1b2020-07-06 20:24:34 -0400645 check_and_run_script("/system/bin/rebootrecovery.sh", "reboot recovery");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500646 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Dees_Troy2673cec2013-04-02 20:22:16 +0000647 case rb_bootloader:
bigbiffad58e1b2020-07-06 20:24:34 -0400648 check_and_run_script("/system/bin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500649 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Dees_Troy2673cec2013-04-02 20:22:16 +0000650 case rb_poweroff:
bigbiffad58e1b2020-07-06 20:24:34 -0400651 check_and_run_script("/system/bin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500652#ifdef ANDROID_RB_PROPERTY
653 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
654#elif defined(ANDROID_RB_POWEROFF)
655 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
656#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000657 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500658#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000659 case rb_download:
bigbiffad58e1b2020-07-06 20:24:34 -0400660 check_and_run_script("/system/bin/rebootdownload.sh", "reboot download");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500661 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200662 case rb_edl:
bigbiffad58e1b2020-07-06 20:24:34 -0400663 check_and_run_script("/system/bin/rebootedl.sh", "reboot edl");
mauronofrioe9a49ef2018-10-03 13:38:16 +0200664 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
bigbiffdf8436b2020-08-30 16:22:34 -0400665 case rb_fastboot:
666 return property_set(ANDROID_RB_PROPERTY, "reboot,fastboot");
Dees_Troy2673cec2013-04-02 20:22:16 +0000667 default:
668 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600669 }
670 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400671}
672
673void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
674{
675 // Check for and run startup script if script exists
676 struct stat st;
677 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500678 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500679 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200680 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500681 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400682 }
Dees_Troy3477d712012-09-27 15:44:01 -0400683}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500684
685int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000686 DIR *d = opendir(path.c_str());
687 int r = 0;
688 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500689
Dees_Troyce675462013-01-09 19:48:21 +0000690 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500691 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000692 return -1;
693 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500694
Dees_Troyce675462013-01-09 19:48:21 +0000695 if (d) {
696 struct dirent *p;
697 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000698 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
699 continue;
700 new_path = path + "/";
701 new_path.append(p->d_name);
702 if (p->d_type == DT_DIR) {
703 r = removeDir(new_path, true);
704 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500705 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500706 r = rmdir(new_path.c_str());
707 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000708 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500709 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500710 } 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 +0000711 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000712 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000713 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000714 }
Dees_Troyce675462013-01-09 19:48:21 +0000715 }
716 }
717 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500718
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500719 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500720 if (skipParent)
721 return 0;
722 else
723 r = rmdir(path.c_str());
724 }
Dees_Troyce675462013-01-09 19:48:21 +0000725 }
726 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500727}
728
bigbiff22851b92021-09-01 16:46:57 -0400729int TWFunc::copy_file(string src, string dst, int mode, bool mount_paths) {
730 if (mount_paths) {
731 PartitionManager.Mount_By_Path(src, false);
732 PartitionManager.Mount_By_Path(dst, false);
733 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400734 if (!Path_Exists(src)) {
bigbiff22851b92021-09-01 16:46:57 -0400735 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 -0400736 return -1;
737 }
bigbiffd3317052019-12-22 16:05:12 -0500738 std::ifstream srcfile(src.c_str(), ios::binary);
739 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500740 dstfile << srcfile.rdbuf();
bigbiff850fa282021-10-09 12:37:29 -0400741 if (dstfile.bad()) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400742 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
743 return -1;
744 }
745
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500746 srcfile.close();
747 dstfile.close();
bigbiff22851b92021-09-01 16:46:57 -0400748 if (chmod(dst.c_str(), mode) != 0) {
749 LOGERR("Unable to chmod file: %s. Error: %s\n", dst.c_str(), strerror(errno));
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500750 return -1;
bigbiff22851b92021-09-01 16:46:57 -0400751 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500752 return 0;
753}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000754
755unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
756 struct stat st;
757
758 stat(Path.c_str(), &st);
759 if (st.st_mode & S_IFDIR)
760 return DT_DIR;
761 else if (st.st_mode & S_IFBLK)
762 return DT_BLK;
763 else if (st.st_mode & S_IFCHR)
764 return DT_CHR;
765 else if (st.st_mode & S_IFIFO)
766 return DT_FIFO;
767 else if (st.st_mode & S_IFLNK)
768 return DT_LNK;
769 else if (st.st_mode & S_IFREG)
770 return DT_REG;
771 else if (st.st_mode & S_IFSOCK)
772 return DT_SOCK;
773 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000774}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500775
776int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200777 ifstream file;
778 file.open(fn.c_str(), ios::in);
779
780 if (file.is_open()) {
bigbiff22851b92021-09-01 16:46:57 -0400781 std::string line;
782 while (std::getline(file, line)) {
783 results += line;
784 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200785 file.close();
786 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500787 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200788
789 LOGINFO("Cannot find file %s\n", fn.c_str());
790 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500791}
792
793int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500794 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500795 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500796 file.open(fn.c_str(), ios::in);
797 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500798 while (getline(file, line))
799 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500800 file.close();
801 return 0;
802 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000803 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500804 return -1;
805}
806
xNUTxe85f02d2014-07-18 01:30:58 +0200807int TWFunc::read_file(string fn, uint64_t& results) {
808 ifstream file;
809 file.open(fn.c_str(), ios::in);
810
811 if (file.is_open()) {
812 file >> results;
813 file.close();
814 return 0;
815 }
816
817 LOGINFO("Cannot find file %s\n", fn.c_str());
818 return -1;
819}
820
bigbiff22851b92021-09-01 16:46:57 -0400821bool TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500822 FILE *file;
823 file = fopen(fn.c_str(), "w");
824 if (file != NULL) {
825 fwrite(line.c_str(), line.size(), 1, file);
826 fclose(file);
bigbiff22851b92021-09-01 16:46:57 -0400827 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500828 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000829 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff22851b92021-09-01 16:46:57 -0400830 return false;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500831}
832
bigbiff22851b92021-09-01 16:46:57 -0400833bool TWFunc::write_to_file(const string& fn, const std::vector<string> lines) {
834 FILE *file;
835 file = fopen(fn.c_str(), "a+");
836 if (file != NULL) {
837 for (auto&& line: lines) {
838 fwrite(line.c_str(), line.size(), 1, file);
839 fwrite("\n", sizeof(char), 1, file);
840 }
841 fclose(file);
842 return true;
843 }
844 return false;
845}
846
847
Dees_Troy83bd4832013-05-04 12:39:56 +0000848bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
849 DIR* d;
850
851 string Filename;
852 Restore_Path += "/";
853 d = opendir(Restore_Path.c_str());
854 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500855 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000856 return false;
857 }
858
859 struct dirent* de;
860 while ((de = readdir(d)) != NULL) {
861 Filename = Restore_Path;
862 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500863 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000864 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
865 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
866 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
867 closedir(d);
868 return false;
869 }
870 }
871 }
872 closedir(d);
873 return true;
874}
875
Dees Troyb21cc642013-09-10 17:36:41 +0000876string TWFunc::Get_Current_Date() {
877 string Current_Date;
878 time_t seconds = time(0);
879 struct tm *t = localtime(&seconds);
880 char timestamp[255];
881 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);
882 Current_Date = timestamp;
883 return Current_Date;
884}
885
Ethan Yonkerb5557892014-02-07 21:43:20 -0600886string TWFunc::System_Property_Get(string Prop_Name) {
Captain Throwback1483a8e2022-01-03 09:52:06 -0500887 return Partition_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path(), "build.prop");
Chaosmaster65633a42020-02-05 15:24:09 +0100888}
889
Captain Throwback1483a8e2022-01-03 09:52:06 -0500890string TWFunc::Partition_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point, string prop_file_name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100891 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000892 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600893 string propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500894 string prop_file;
Chaosmaster65633a42020-02-05 15:24:09 +0100895 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600896 return propvalue;
Captain Throwback1483a8e2022-01-03 09:52:06 -0500897 if (Mount_Point == PartitionManager.Get_Android_Root_Path()) {
898 prop_file = Mount_Point + "/system/" + prop_file_name;
899 } else {
900 prop_file = Mount_Point + "/" + prop_file_name;
901 }
Captain Throwback2b9ea722021-12-31 21:35:52 -0500902 if (!TWFunc::Path_Exists(prop_file)) {
903 LOGINFO("Unable to locate file: %s\n", prop_file.c_str());
904 return propvalue;
905 }
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600906 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback2b9ea722021-12-31 21:35:52 -0500907 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 +0200908 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000909 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100910 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600911 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000912 }
913 int line_count = buildprop.size();
914 int index;
915 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600916 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000917 for (index = 0; index < line_count; index++) {
918 end_pos = buildprop.at(index).find("=", start_pos);
919 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600920 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000921 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600922 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100923 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600924 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000925 }
926 }
Dees Troyb21cc642013-09-10 17:36:41 +0000927 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100928 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600929 return propvalue;
930}
931
932void TWFunc::Auto_Generate_Backup_Name() {
933 string propvalue = System_Property_Get("ro.build.display.id");
934 if (propvalue.empty()) {
935 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
936 return;
937 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400938 else {
939 //remove periods from build display so it doesn't confuse the extension code
940 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
941 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600942 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500943 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600944 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
945 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
946 // Trailing spaces cause problems on some file systems, so remove them
947 string space_check, space = " ";
948 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
949 while (space_check == space) {
950 Backup_Name.resize(Backup_Name.size() - 1);
951 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
952 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500953 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600954 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
955 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600956 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600957 } else {
958 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600959 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200960}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100961
nkk7198fc3992017-12-16 16:26:42 +0200962void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100963{
964#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200965 static bool fixed = false;
966 if (fixed)
967 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200968
969 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
970
971 struct timeval tv;
972 uint64_t offset = 0;
973 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
974
975 if (TWFunc::read_file(sepoch, offset) == 0) {
976
977 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
978
979 tv.tv_sec = offset;
980 tv.tv_usec = 0;
981 settimeofday(&tv, NULL);
982
983 gettimeofday(&tv, NULL);
984
Phoenix59146b05f22018-02-03 06:41:08 +0000985 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 +0200986
987 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200988 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200989 return;
990
991 }
992
993 } else {
994
995 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
996
997 }
998
Ethan Yonker9132d912015-02-02 10:32:49 -0600999 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +02001000
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001001 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
1002 // They never set it, it just ticks forward from 1970-01-01 00:00,
1003 // and then they have files /data/system/time/ats_* with 64bit offset
1004 // in miliseconds which, when added to the RTC, gives the correct time.
1005 // So, the time is: (offset_from_ats + value_from_RTC)
1006 // There are multiple ats files, they are for different systems? Bases?
1007 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1008 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1009
nkk7198fc3992017-12-16 16:26:42 +02001010 std::vector<std::string> paths; // space separated list of paths
1011 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +01001012 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +02001013 if (!PartitionManager.Mount_By_Path("/data", false))
1014 return;
1015 } else {
1016 // When specific path(s) are used, Fixup_Time needs those
1017 // partitions to already be mounted!
1018 paths = Split_String(time_paths, " ");
1019 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001020
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001021 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001022 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001023 struct dirent *dt;
1024 std::string ats_path;
1025
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001026 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1027 // - it is the one for ATS_TOD (time of day?).
1028 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001029 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001030 {
nkk7198fc3992017-12-16 16:26:42 +02001031 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001032 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001033 continue;
1034
Matt Mowera8a89d12016-12-30 18:10:37 -06001035 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001036 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001037 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001038 continue;
1039
Matt Mowera8a89d12016-12-30 18:10:37 -06001040 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001041 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001042 }
1043
1044 closedir(d);
1045 }
1046
nkk7198fc3992017-12-16 16:26:42 +02001047 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001048 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001049 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001050 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001051 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001052 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001053 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001054 } else {
1055 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001056
nkk7198fc3992017-12-16 16:26:42 +02001057 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1058 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1059 fixed = true;
1060 }
1061
1062 if (!fixed) {
Captain Throwbackf74fc052022-01-19 13:25:54 -05001063#ifdef TW_QCOM_ATS_OFFSET
1064 // Offset is the difference between the current time and the time since_epoch
1065 // To calculate the offset in Android, the following expression (from a root shell) can be used:
1066 // echo "$(( ($(date +%s) - $(cat /sys/class/rtc/rtc0/since_epoch)) ))"
1067 // Add 3 zeros to the output and use that in the TW_QCOM_ATS_OFFSET flag in your BoardConfig.mk
1068 // For example, if the result of the calculation is 1642433544, use 1642433544000 as the offset
1069 offset = (uint64_t) TW_QCOM_ATS_OFFSET;
1070 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1071 LOGINFO("TWFunc::Fixup_Time: Setting time offset from TW_QCOM_ATS_OFFSET, offset %llu\n", (unsigned long long) offset);
1072#else
nkk7198fc3992017-12-16 16:26:42 +02001073 // Failed to get offset from ats file, check twrp settings
1074 unsigned long long value;
1075 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1076 return;
1077 } else {
1078 offset = (uint64_t) value;
1079 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1080 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1081 }
Captain Throwbackf74fc052022-01-19 13:25:54 -05001082#endif
nkk7198fc3992017-12-16 16:26:42 +02001083 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001084
1085 gettimeofday(&tv, NULL);
1086
1087 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001088#ifdef TW_CLOCK_OFFSET
1089// Some devices are even quirkier and have ats files that are offset from the actual time
1090 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1091#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001092 tv.tv_usec += (offset%1000)*1000;
1093
Matt Mowera8a89d12016-12-30 18:10:37 -06001094 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001095 {
1096 ++tv.tv_sec;
1097 tv.tv_usec -= 1000000;
1098 }
1099
1100 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001101
1102 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001103#endif
1104}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001105
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001106std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1107{
1108 std::vector<std::string> res;
1109 size_t idx = 0, idx_last = 0;
1110
Matt Mowera8a89d12016-12-30 18:10:37 -06001111 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001112 {
1113 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001114 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001115 idx = str.size();
1116
Matt Mowera8a89d12016-12-30 18:10:37 -06001117 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001118 res.push_back(str.substr(idx_last, idx-idx_last));
1119
1120 idx_last = idx + delimiter.size();
1121 }
1122
1123 return res;
1124}
1125
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001126bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1127{
1128 std::vector<std::string> parts = Split_String(path, "/");
1129 std::string cur_path;
1130 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001131 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001132 {
1133 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001134 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001135 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001136 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001137 return false;
1138 chown(cur_path.c_str(), uid, gid);
1139 }
1140 }
1141 return true;
1142}
1143
xNUTxe85f02d2014-07-18 01:30:58 +02001144int TWFunc::Set_Brightness(std::string brightness_value)
1145{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001146 int result = -1;
1147 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001148
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001149 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001150 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001151 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001152 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1153 if (!secondary_brightness_file.empty()) {
1154 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001155 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001156 }
xNUTxe85f02d2014-07-18 01:30:58 +02001157 }
bigbiff22851b92021-09-01 16:46:57 -04001158 return result ? 0 : -1;
xNUTxe85f02d2014-07-18 01:30:58 +02001159}
1160
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001161bool TWFunc::Toggle_MTP(bool enable) {
1162#ifdef TW_HAS_MTP
1163 static int was_enabled = false;
1164
1165 if (enable && was_enabled) {
1166 if (!PartitionManager.Enable_MTP())
1167 PartitionManager.Disable_MTP();
1168 } else {
1169 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1170 PartitionManager.Disable_MTP();
1171 usleep(500);
1172 }
1173 return was_enabled;
1174#else
1175 return false;
1176#endif
1177}
1178
Tom Hite5a926722014-09-15 01:31:03 +00001179void TWFunc::SetPerformanceMode(bool mode) {
1180 if (mode) {
1181 property_set("recovery.perf.mode", "1");
1182 } else {
1183 property_set("recovery.perf.mode", "0");
1184 }
1185 // Some time for events to catch up to init handlers
1186 usleep(500000);
1187}
1188
Jenkins1710bf22014-10-02 20:22:21 -04001189std::string TWFunc::to_string(unsigned long value) {
1190 std::ostringstream os;
1191 os << value;
1192 return os.str();
1193}
1194
Ethan Yonker9132d912015-02-02 10:32:49 -06001195void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001196 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001197 // Disable flashing of stock recovery
1198 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1199 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001200 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 -06001201 sync();
1202 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001203 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001204 }
1205}
1206
Ethan Yonker483e9f42016-01-11 22:21:18 -06001207unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1208 unsigned long block_device_size;
1209 int ret = 0;
1210
1211 int fd = open(block_device, O_RDONLY);
1212 if (fd < 0) {
1213 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1214 } else {
1215 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1216 close(fd);
1217 if (ret) {
1218 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1219 } else {
1220 return (unsigned long long)(block_device_size) * 512LLU;
1221 }
1222 }
1223 return 0;
1224}
1225
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001226void TWFunc::copy_kernel_log(string curr_storage) {
1227 std::string dmesgDst = curr_storage + "/dmesg.log";
bigbiffad58e1b2020-07-06 20:24:34 -04001228 std::string dmesgCmd = "/system/bin/dmesg";
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001229
1230 std::string result;
bigbiffad58e1b2020-07-06 20:24:34 -04001231 Exec_Cmd(dmesgCmd, result, false);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001232 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001233 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1234 tw_set_default_metadata(dmesgDst.c_str());
1235}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001236
Captain Throwback52978932021-09-05 15:11:07 -04001237void TWFunc::copy_logcat(string curr_storage) {
1238 std::string logcatDst = curr_storage + "/logcat.txt";
1239 std::string logcatCmd = "logcat -d";
1240
1241 std::string result;
1242 Exec_Cmd(logcatCmd, result, false);
1243 write_to_file(logcatDst, result);
1244 gui_msg(Msg("copy_logcat=Copied logcat to {1}")(logcatDst));
1245 tw_set_default_metadata(logcatDst.c_str());
1246}
1247
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001248bool TWFunc::isNumber(string strtocheck) {
1249 int num = 0;
1250 std::istringstream iss(strtocheck);
1251
1252 if (!(iss >> num).fail())
1253 return true;
1254 else
1255 return false;
1256}
1257
1258int TWFunc::stream_adb_backup(string &Restore_Name) {
bigbiffad58e1b2020-07-06 20:24:34 -04001259 string cmd = "/system/bin/bu --twrp stream " + Restore_Name;
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001260 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1261 int ret = TWFunc::Exec_Cmd(cmd);
1262 if (ret != 0)
1263 return -1;
1264 return ret;
1265}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001266
bigbiff25d25b92020-06-19 16:07:38 -04001267std::string TWFunc::get_log_dir() {
1268 if (PartitionManager.Find_Partition_By_Path(CACHE_LOGS_DIR) == NULL) {
1269 if (PartitionManager.Find_Partition_By_Path(DATA_LOGS_DIR) == NULL) {
bigbiffaac58612020-08-30 11:18:39 -04001270 LOGINFO("Unable to find a directory to store TWRP logs.");
1271 return "";
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001272 } else {
bigbiff25d25b92020-06-19 16:07:38 -04001273 return DATA_LOGS_DIR;
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001274 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001275 }
1276 else {
bigbiff25d25b92020-06-19 16:07:38 -04001277 return CACHE_LOGS_DIR;
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001278 }
1279}
1280
1281void TWFunc::check_selinux_support() {
1282 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1283 if (TWFunc::Path_Exists("/file_contexts")) {
1284 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1285 rename("/file_contexts", "/file_contexts.bak");
1286 }
1287 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1288 rename("/prebuilt_file_contexts", "/file_contexts");
1289 }
1290 struct selinux_opt selinux_options[] = {
1291 { SELABEL_OPT_PATH, "/file_contexts" }
1292 };
1293 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1294 if (!selinux_handle)
1295 printf("No file contexts for SELinux\n");
1296 else
1297 printf("SELinux contexts loaded from /file_contexts\n");
1298 { // Check to ensure SELinux can be supported by the kernel
1299 char *contexts = NULL;
bigbiff25d25b92020-06-19 16:07:38 -04001300 std::string cacheDir = TWFunc::get_log_dir();
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001301 std::string se_context_check = cacheDir + "recovery/";
1302 int ret = 0;
1303
bigbiff25d25b92020-06-19 16:07:38 -04001304 if (cacheDir == CACHE_LOGS_DIR) {
1305 PartitionManager.Mount_By_Path(CACHE_LOGS_DIR, false);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001306 }
1307 if (TWFunc::Path_Exists(se_context_check)) {
1308 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001309 if (ret < 0) {
bigbiffad58e1b2020-07-06 20:24:34 -04001310 LOGINFO("Could not check %s SELinux contexts, using /system/bin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1311 lgetfilecon("/system/bin/teamwin", &contexts);
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001312 }
1313 }
1314 if (ret < 0) {
1315 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1316 } else {
1317 free(contexts);
1318 gui_msg("full_selinux=Full SELinux support is present.");
1319 }
1320 }
1321}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001322
1323bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001324 LOGINFO("checking for twrp app\n");
1325 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1326 if (!sys->Get_Super_Status()) {
Captain Throwback31c14922020-12-21 11:28:34 -05001327 bool is_system_mounted = true;
1328 if(!PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path())) {
1329 is_system_mounted = false;
1330 PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001331 }
Captain Throwback31c14922020-12-21 11:28:34 -05001332 string base_path = PartitionManager.Get_Android_Root_Path();
1333 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1334 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1335 string install_path = base_path + "/priv-app";
1336 if (!TWFunc::Path_Exists(install_path))
1337 install_path = base_path + "/app";
1338 install_path += "/twrpapp";
1339 if (TWFunc::Path_Exists(install_path)) {
1340 LOGINFO("App found at '%s'\n", install_path.c_str());
1341 DataManager::SetValue("tw_app_installed_in_system", 1);
1342 return true;
1343 }
1344 if (!is_system_mounted)
1345 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
bigbiffee7b7ff2020-03-23 15:08:27 -04001346 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001347 }
1348 DataManager::SetValue("tw_app_installed_in_system", 0);
1349 return false;
1350}
Chaosmaster461e39f2020-02-07 01:48:13 +01001351
epicX271bb3a2020-12-30 01:03:18 +05301352void TWFunc::checkforapp(){
1353
1354 string sdkverstr = System_Property_Get("ro.build.version.sdk");
1355 int sdkver = 0;
1356 if (!sdkverstr.empty()) {
1357 sdkver = atoi(sdkverstr.c_str());
1358 }
1359 if (sdkver <= 13) {
1360 if (sdkver == 0)
1361 LOGINFO("Unable to read sdk version from build prop\n");
1362 else
1363 LOGINFO("SDK version too low for TWRP app (%i < 14)\n", sdkver);
1364 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1365 goto exit;
1366 }
1367 if (Is_TWRP_App_In_System()) {
1368 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1369 goto exit;
1370 }
1371 if (PartitionManager.Mount_By_Path("/data", false)) {
1372 const char parent_path[] = "/data/app";
1373 const char app_prefix[] = "me.twrp.twrpapp-";
1374 DIR *d = opendir(parent_path);
1375 if (d) {
1376 struct dirent *p;
1377 while ((p = readdir(d))) {
1378 if (p->d_type != DT_DIR || strlen(p->d_name) < strlen(app_prefix) || strncmp(p->d_name, app_prefix, strlen(app_prefix)))
1379 continue;
1380 closedir(d);
1381 LOGINFO("App found at '%s/%s'\n", parent_path, p->d_name);
1382 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1383 goto exit;
1384 }
1385 closedir(d);
1386 }
1387 } else {
1388 LOGINFO("Data partition cannot be mounted during app check\n");
1389 DataManager::SetValue("tw_app_install_status", 2); // 0 = no status, 1 = not installed, 2 = already installed or do not install
1390 }
1391
1392 LOGINFO("App not installed\n");
1393 DataManager::SetValue("tw_app_install_status", 1); // 0 = no status, 1 = not installed, 2 = already installed
1394exit:
1395 return;
1396
1397}
1398
Chaosmaster461e39f2020-02-07 01:48:13 +01001399int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1400#ifdef TW_INCLUDE_LIBRESETPROP
1401 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1402#else
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001403 return NOT_AVAILABLE;
1404#endif
1405}
1406
1407int TWFunc::Delete_Property(string Prop_Name) {
1408#ifdef TW_INCLUDE_LIBRESETPROP
1409 return delprop(Prop_Name.c_str(), false);
1410#else
1411 return NOT_AVAILABLE;
Chaosmaster461e39f2020-02-07 01:48:13 +01001412#endif
1413}
1414
bigbiffee7b7ff2020-03-23 15:08:27 -04001415void TWFunc::List_Mounts() {
1416 std::vector<std::string> mounts;
1417 read_file("/proc/mounts", mounts);
1418 LOGINFO("Mounts:\n");
1419 for (auto&& mount: mounts) {
1420 LOGINFO("%s\n", mount.c_str());
1421 }
1422}
1423
epicXa721f952021-01-04 13:01:31 +05301424string TWFunc::Check_For_TwrpFolder() {
1425 string oldFolder = "";
1426 vector<string> customTWRPFolders;
1427 string mainPath = DataManager::GetCurrentStoragePath();
1428 DIR* d;
1429 struct dirent* de;
1430
Fernando Oliveira073c4302022-10-19 13:33:47 -03001431 if (DataManager::GetIntValue(TW_IS_ENCRYPTED) && DataManager::GetIntValue(TW_CRYPTO_PWTYPE)) {
epicXa721f952021-01-04 13:01:31 +05301432 goto exit;
1433 }
1434
1435
1436 d = opendir(mainPath.c_str());
1437 if (d == NULL) {
1438 goto exit;
1439 }
1440
1441 while ((de = readdir(d)) != NULL) {
1442 string name = de->d_name;
1443 string fullPath = mainPath + '/' + name;
1444 unsigned char type = de->d_type;
1445
epicX11e90832021-03-01 00:02:57 +05301446 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301447
epicX11e90832021-03-01 00:02:57 +05301448 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301449 type = Get_D_Type_From_Stat(fullPath);
1450 }
1451
epicX11e90832021-03-01 00:02:57 +05301452 if (type == DT_DIR && Path_Exists(fullPath + '/' + TW_SETTINGS_FILE)) {
1453 if ('/' + name == TW_DEFAULT_RECOVERY_FOLDER) {
epicXa721f952021-01-04 13:01:31 +05301454 oldFolder = name;
1455 } else {
1456 customTWRPFolders.push_back(name);
1457 }
1458 }
1459 }
1460
1461 closedir(d);
1462
epicX11e90832021-03-01 00:02:57 +05301463 if (oldFolder == "" && customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301464 LOGINFO("No recovery folder found. Using default folder.\n");
1465 goto exit;
epicX11e90832021-03-01 00:02:57 +05301466 } else if (customTWRPFolders.empty()) {
epicXa721f952021-01-04 13:01:31 +05301467 LOGINFO("No custom recovery folder found. Using TWRP as default.\n");
1468 goto exit;
1469 } else {
epicX11e90832021-03-01 00:02:57 +05301470 if (customTWRPFolders.size() > 1) {
epicXa721f952021-01-04 13:01:31 +05301471 LOGINFO("More than one custom recovery folder found. Using first one from the list.\n");
1472 } else {
1473 LOGINFO("One custom recovery folder found.\n");
1474 }
1475 string customPath = '/' + customTWRPFolders.at(0);
1476
epicX11e90832021-03-01 00:02:57 +05301477 if (Path_Exists(mainPath + TW_DEFAULT_RECOVERY_FOLDER)) {
epicXa721f952021-01-04 13:01:31 +05301478 string oldBackupFolder = mainPath + TW_DEFAULT_RECOVERY_FOLDER + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1479 string newBackupFolder = mainPath + customPath + "/BACKUPS/" + DataManager::GetStrValue("device_id");
1480
epicX11e90832021-03-01 00:02:57 +05301481 if (Path_Exists(oldBackupFolder)) {
epicXa721f952021-01-04 13:01:31 +05301482 vector<string> backups;
1483 d = opendir(oldBackupFolder.c_str());
1484
1485 if (d != NULL) {
1486 while ((de = readdir(d)) != NULL) {
1487 string name = de->d_name;
1488 unsigned char type = de->d_type;
1489
epicX11e90832021-03-01 00:02:57 +05301490 if (name == "." || name == "..") continue;
epicXa721f952021-01-04 13:01:31 +05301491
epicX11e90832021-03-01 00:02:57 +05301492 if (type == DT_UNKNOWN) {
epicXa721f952021-01-04 13:01:31 +05301493 type = Get_D_Type_From_Stat(mainPath + '/' + name);
1494 }
1495
epicX11e90832021-03-01 00:02:57 +05301496 if (type == DT_DIR) {
epicXa721f952021-01-04 13:01:31 +05301497 backups.push_back(name);
1498 }
1499 }
1500 closedir(d);
1501 }
1502
epicX11e90832021-03-01 00:02:57 +05301503 for (auto it = backups.begin(); it != backups.end(); it++) {
epicXa721f952021-01-04 13:01:31 +05301504 Exec_Cmd("mv -f \"" + oldBackupFolder + '/' + *it + "\" \"" + newBackupFolder + '/' + *it + (Path_Exists(newBackupFolder + '/' + *it) ? "_new\"" : "\""));
1505 }
1506 }
1507 Exec_Cmd("rm -rf \"" + mainPath + TW_DEFAULT_RECOVERY_FOLDER + '\"');
1508 }
1509
1510 return customPath;
1511 }
1512
1513exit:
1514 return TW_DEFAULT_RECOVERY_FOLDER;
1515}
Darth98f775972022-08-05 09:39:03 +01001516
1517bool TWFunc::Check_Xml_Format(const std::string filename) {
1518 std::string buffer(' ', 4);
1519 std::string abx_hdr("ABX\x00", 4);
1520 std::ifstream File;
1521 File.open(filename);
1522 if (File.is_open()) {
1523 File.get(&buffer[0], buffer.size());
1524 File.close();
1525 // Android Binary Xml start from these bytes
1526 if(!buffer.compare(0, abx_hdr.size(), abx_hdr))
1527 return false; // ABX format - requires conversion
1528 }
1529 return true; // good format, possible to parse
1530}
1531
1532// return true=successful conversion (return the name of the converted file in "result");
1533// return false=an error happened (leave "result" alone)
1534bool TWFunc::abx_to_xml(const std::string path, std::string &result) {
1535 bool res = false;
1536 if (!TWFunc::Path_Exists(path))
1537 return res;
1538
1539 std::ifstream infile(path);
1540 if (!infile.is_open())
1541 return res;
1542
1543 std::string fname = TWFunc::Get_Filename(path);
1544 std::string tmp = "/tmp/converted_xml";
1545 if (!TWFunc::Path_Exists(tmp)) {
1546 if (mkdir(tmp.c_str(), 0777) != 0)
1547 tmp = "/tmp";
1548 }
1549
1550 std::string tmp_path = tmp + "/" + fname;
1551 std::ofstream outfile(tmp_path);
1552 if (!outfile.is_open()) {
1553 LOGINFO("Error. The abx conversion of %s has failed.\n", path.c_str());
1554 infile.close();
1555 return res;
1556 }
1557
1558 AbxToXml r(infile, outfile);
1559 if (r.run() && TWFunc::Path_Exists(tmp_path)) {
1560 res = true;
1561 result = tmp_path;
1562 }
1563
1564 infile.close();
1565 outfile.close();
1566
1567 return res;
1568}
1569
Mohd Faraz446ccbf2023-01-24 19:58:24 +01001570std::string GetFstabPath() {
1571 for (const char* prop : {"fstab_suffix", "hardware", "hardware.platform"}) {
1572 std::string suffix;
1573
1574 if (!fs_mgr_get_boot_config(prop, &suffix)) continue;
1575
1576 for (const char* prefix : {// late-boot/post-boot locations
1577 "/odm/etc/fstab.", "/vendor/etc/fstab.",
1578 // early boot locations
1579 "/system/etc/fstab.", "/first_stage_ramdisk/system/etc/fstab.",
1580 "/fstab.", "/first_stage_ramdisk/fstab."}) {
1581 std::string fstab_path = prefix + suffix;
1582 LOGINFO("%s: %s\n", __func__, fstab_path.c_str());
1583 if (access(fstab_path.c_str(), F_OK) == 0) return fstab_path;
1584 }
1585 }
1586
1587 return "";
1588}
1589
1590bool TWFunc::Find_Fstab(string &fstab) {
1591 fstab = GetFstabPath();
1592 if (fstab == "") return false;
1593 return true;
1594}
1595
1596bool TWFunc::Get_Service_From(TWPartition *Partition, std::string Service, std::string &Res) {
1597 Partition->Mount(true);
1598 std::string Path = Partition->Get_Mount_Point() + "/etc/init/";
1599 std::string Name;
1600 std::vector<std::string> Data;
1601 bool Found = false, ret = false;
1602 DIR* dir;
1603 struct dirent* der;
1604 dir = opendir(Path.c_str());
1605 while ((der = readdir(dir)) != NULL)
1606 {
1607 Name = der->d_name;
1608 if (Name.find(Service) != string::npos) {
1609 Found = true;
1610 Path += Name;
1611 break;
1612 }
1613 }
1614 closedir(dir);
1615
1616 if (!Found) {
1617 LOGINFO("Unable to locate service RC\n");
1618 goto finish;
1619 }
1620
1621 if (read_file(Path, Data) != 0) {
1622 LOGINFO("Unable to read file '%s'\n", Path.c_str());
1623 goto finish;
1624 }
1625
1626 for (int index = 0; index < Data.size(); index++) {
1627 Name = Data.at(index);
1628 if (Name.find("service") != string::npos) {
1629 Res = Name.substr(Name.find_last_of('/')+1);
1630 ret = true;
1631 goto finish;
1632 }
1633 }
1634
1635finish:
1636 Partition->UnMount(true);
1637 return ret;
1638}
1639
1640std::string TWFunc::Get_Version_From_Service(std::string name) {
1641 int start, end;
1642 start = name.find('@') + 1;
1643 end = name.find("-") - start;
1644 return name.substr(start, end);
1645}
1646
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001647#endif // ndef BUILD_TWRPTAR_MAIN