blob: b20f6ff9912805b5b2ddea97488a191bb2373a00 [file] [log] [blame]
Dees Troy3be70a82013-10-22 14:25:12 +00001/*
2 Copyright 2012 bigbiff/Dees_Troy TeamWin
3 This file is part of TWRP/TeamWin Recovery Project.
4
5 TWRP is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 TWRP is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with TWRP. If not, see <http://www.gnu.org/licenses/>.
17*/
18
Dees_Troy38bd7602012-09-14 13:33:53 -040019#include <stdio.h>
20#include <stdlib.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060021#include <string>
Dees_Troy38bd7602012-09-14 13:33:53 -040022#include <unistd.h>
23#include <vector>
24#include <dirent.h>
25#include <time.h>
Dees_Troy43d8b002012-09-17 16:00:01 -040026#include <errno.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050027#include <fcntl.h>
28#include <sys/mount.h>
Dees_Troya58bead2012-09-27 09:49:29 -040029#include <sys/reboot.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050030#include <sys/sendfile.h>
31#include <sys/stat.h>
32#include <sys/vfs.h>
Dees_Troy83bd4832013-05-04 12:39:56 +000033#include <sys/types.h>
34#include <sys/wait.h>
bigbiff bigbiff9c754052013-01-09 09:09:08 -050035#include <iostream>
36#include <fstream>
Dees_Troy83bd4832013-05-04 12:39:56 +000037#include <sstream>
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -040038#include <cctype>
bigbiff74a6d0d2015-02-14 20:49:44 -050039#include <algorithm>
bigbiff bigbiff19874f12019-01-08 20:06:57 -050040#include <selinux/label.h>
Dees_Troy38bd7602012-09-14 13:33:53 -040041#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000042#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060043#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060044#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040045#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060046#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040047#include "variables.h"
Ethan Yonker8373cfe2017-09-08 06:50:54 -050048#include "bootloader_message_twrp/include/bootloader_message_twrp/bootloader_message.h"
Tom Hite5a926722014-09-15 01:31:03 +000049#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050050#include "cutils/android_reboot.h"
51#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060052#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000053#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
54 #include "openaes/inc/oaes_lib.h"
55#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050056#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040057
Dees_Troyb05ddee2013-01-28 20:24:50 +000058extern "C" {
59 #include "libcrecovery/common.h"
60}
61
Chaosmaster461e39f2020-02-07 01:48:13 +010062#ifdef TW_INCLUDE_LIBRESETPROP
63 #include <resetprop.h>
64#endif
65
bigbiff bigbiff19874f12019-01-08 20:06:57 -050066struct selabel_handle *selinux_handle;
67
bigbiff bigbiff9c754052013-01-09 09:09:08 -050068/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020069int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000070 FILE* exec;
71 char buffer[130];
72 int ret = 0;
73 exec = __popen(cmd.c_str(), "r");
74 if (!exec) return -1;
Matt Mowera8a89d12016-12-30 18:10:37 -060075 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000076 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050077 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000078 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050079 }
Dees_Troy29a06352013-08-24 12:06:47 +000080 ret = __pclose(exec);
81 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050082}
83
Ethan Yonker7e941582019-03-22 08:18:21 -050084int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020085 pid_t pid;
86 int status;
87 switch(pid = fork())
88 {
89 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050090 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020091 return -1;
92 case 0: // child
93 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
94 _exit(127);
95 break;
96 default:
97 {
Ethan Yonker7e941582019-03-22 08:18:21 -050098 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +020099 return -1;
100 else
101 return 0;
102 }
103 }
104}
105
Dees_Troy38bd7602012-09-14 13:33:53 -0400106// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600107string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400108 size_t pos = Path.find_last_of("/");
109 if (pos != string::npos) {
110 string Filename;
111 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
112 return Filename;
113 } else
114 return Path;
115}
116
117// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600118string TWFunc::Get_Path(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 Pathonly;
122 Pathonly = Path.substr(0, pos + 1);
123 return Pathonly;
124 } else
125 return Path;
126}
127
Ethan Yonker7e941582019-03-22 08:18:21 -0500128int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600129 pid_t rc_pid;
130
131 rc_pid = waitpid(pid, status, 0);
132 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100133 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500134 if (Show_Errors)
135 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 -0600136 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100137 } else if (WEXITSTATUS(*status) == 0) {
138 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
139 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500140 if (Show_Errors)
141 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 -0600142 return -1;
143 }
144 } else { // no PID returned
145 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200146 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600147 else {
that2252d242015-04-03 22:33:04 +0200148 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600149 return -1;
150 }
151 }
152 return 0;
153}
154
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600155int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
156 pid_t retpid = waitpid(pid, status, WNOHANG);
157 for (; retpid == 0 && timeout; --timeout) {
158 sleep(1);
159 retpid = waitpid(pid, status, WNOHANG);
160 }
161 if (retpid == 0 && timeout == 0) {
162 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
163 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600164 for (timeout = 5; retpid == 0 && timeout; --timeout) {
165 sleep(1);
166 retpid = waitpid(pid, status, WNOHANG);
167 }
168 if (retpid)
169 LOGINFO("Child process killed successfully\n");
170 else
171 LOGINFO("Child process took too long to kill, may be a zombie process\n");
172 return -1;
173 } else if (retpid > 0) {
174 if (WIFSIGNALED(*status)) {
175 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
176 return -1;
177 }
178 } else if (retpid < 0) { // no PID returned
179 if (errno == ECHILD)
180 LOGERR("%s no child process exist\n", Child_Name.c_str());
181 else {
182 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
183 return -1;
184 }
185 }
186 return 0;
187}
188
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600189bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600190 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400191 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600192}
193
bigbiffce8f83c2015-12-12 18:30:21 -0500194Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600195 string::size_type i = 0;
196 int firstbyte = 0, secondbyte = 0;
197 char header[3];
198
199 ifstream f;
200 f.open(fn.c_str(), ios::in | ios::binary);
201 f.get(header, 3);
202 f.close();
203 firstbyte = header[i] & 0xff;
204 secondbyte = header[++i] & 0xff;
205
206 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500207 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600208 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500209 return ENCRYPTED;
210 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600211}
212
213int TWFunc::Try_Decrypting_File(string fn, string password) {
214#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
215 OAES_CTX * ctx = NULL;
216 uint8_t _key_data[32] = "";
217 FILE *f;
218 uint8_t buffer[4096];
219 uint8_t *buffer_out = NULL;
220 uint8_t *ptr = NULL;
221 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600222 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600223 size_t _j = 0;
224 size_t _key_data_len = 0;
225
226 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600227 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600228 _key_data[_j] = _j + 1;
229 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600230 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600231 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600232 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600233 _key_data_len = 24;
234 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600235 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600236 memcpy(_key_data, password.c_str(), password.size());
237
238 ctx = oaes_alloc();
239 if (ctx == NULL) {
240 LOGERR("Failed to allocate OAES\n");
241 return -1;
242 }
243
244 oaes_key_import_data(ctx, _key_data, _key_data_len);
245
246 f = fopen(fn.c_str(), "rb");
247 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500248 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500249 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600250 return -1;
251 }
252 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
253 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500254 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600255 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500256 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600257 return -1;
258 }
259 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
260 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
261 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500262 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600263 return -1;
264 }
265 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
266 if (buffer_out == NULL) {
267 LOGERR("Failed to allocate output buffer for try decrypt.\n");
268 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500269 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600270 return -1;
271 }
272 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
273 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
274 fclose(f);
275 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500276 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600277 return 0;
278 }
279 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500280 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600281 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500282 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600283 free(buffer_out);
284 return 1; // Decrypted successfully
285 }
286 ptr = buffer_out;
287 firstbyte = *ptr & 0xff;
288 ptr++;
289 secondbyte = *ptr & 0xff;
290 if (firstbyte == 0x1f && secondbyte == 0x8b) {
291 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
292 free(buffer_out);
293 return 3; // Compressed
294 }
295 if (out_len >= 262) {
296 ptr = buffer_out + 257;
297 if (strncmp((char*)ptr, "ustar", 5) == 0) {
298 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
299 free(buffer_out);
300 return 2; // Tar
301 }
302 }
303 free(buffer_out);
304 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
305 return 1; // Decrypted successfully
306#else
307 LOGERR("Encrypted backup support not included.\n");
308 return -1;
309#endif
310}
311
Ethan Yonker472f5062016-02-25 13:47:30 -0600312unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600313 struct stat st;
314
315 if (stat(Path.c_str(), &st) != 0)
316 return 0;
317 return st.st_size;
318}
319
bigbiffee7b7ff2020-03-23 15:08:27 -0400320std::string TWFunc::Remove_Beginning_Slash(const std::string& path) {
321 std::string res;
322 size_t pos = path.find_first_of("/");
323 if (pos != std::string::npos) {
324 res = path.substr(pos+1);
325 }
326 return res;
327}
328
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100329std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
330{
331 std::string res;
332 size_t last_idx = 0, idx = 0;
333
Matt Mowera8a89d12016-12-30 18:10:37 -0600334 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100335 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600336 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100337 res += '/';
338
339 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600340 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100341 res += path.substr(last_idx, idx);
342 break;
343 }
344
345 res += path.substr(last_idx, idx-last_idx);
346 last_idx = path.find_first_not_of('/', idx);
347 }
348
Matt Mowera8a89d12016-12-30 18:10:37 -0600349 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100350 res += '/';
351 return res;
352}
353
Matt Mower2416a502016-04-12 19:54:46 -0500354void TWFunc::Strip_Quotes(char* &str) {
355 if (strlen(str) > 0 && str[0] == '\"')
356 str++;
357 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
358 str[strlen(str)-1] = 0;
359}
360
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500361vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
362 vector<string> res;
363
364 if (in.empty() || del == '\0')
365 return res;
366
367 string field;
368 istringstream f(in);
369 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600370 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500371 if (field.empty() && skip_empty)
372 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600373 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500374 }
375 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600376 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500377 if (field.empty() && skip_empty)
378 continue;
379 res.push_back(field);
380 }
381 }
382 return res;
383}
384
Ethan Yonker472f5062016-02-25 13:47:30 -0600385timespec TWFunc::timespec_diff(timespec& start, timespec& end)
386{
387 timespec temp;
388 if ((end.tv_nsec-start.tv_nsec)<0) {
389 temp.tv_sec = end.tv_sec-start.tv_sec-1;
390 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
391 } else {
392 temp.tv_sec = end.tv_sec-start.tv_sec;
393 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
394 }
395 return temp;
396}
397
398int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
399{
400 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
401 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
402}
403
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600404#ifndef BUILD_TWRPTAR_MAIN
405
Dees_Troy38bd7602012-09-14 13:33:53 -0400406// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600407string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400408 string Local_Path = Path;
409
410 // Make sure that we have a leading slash
411 if (Local_Path.substr(0, 1) != "/")
412 Local_Path = "/" + Local_Path;
413
414 // Trim the path to get the root path only
415 size_t position = Local_Path.find("/", 2);
416 if (position != string::npos) {
417 Local_Path.resize(position);
418 }
419 return Local_Path;
420}
421
422void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400423 int need_libs = 0;
424
Captain Throwback9d6feb52018-07-27 10:05:24 -0400425 if (!PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), true))
Dees_Troy38bd7602012-09-14 13:33:53 -0400426 return;
427
428 if (!PartitionManager.Mount_By_Path("/data", true))
429 return;
430
Ethan Yonker74db1572015-10-28 12:44:49 -0500431 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000432 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400433 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500434 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000435 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400436 need_libs = 1;
437 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500438 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400439 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500440 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000441 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400442 need_libs = 1;
443 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500444 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400445 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500446 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000447 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
448 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
449 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
450 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400451 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500452 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400453 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500454 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000455 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400456 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500457 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400458}
459
460void TWFunc::htc_dumlock_restore_original_boot(void) {
461 if (!PartitionManager.Mount_By_Path("/sdcard", true))
462 return;
463
Ethan Yonker74db1572015-10-28 12:44:49 -0500464 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200465 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500466 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400467}
468
469void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
470 if (!PartitionManager.Mount_By_Path("/sdcard", true))
471 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500472 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200473 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500474 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400475}
Dees_Troy43d8b002012-09-17 16:00:01 -0400476
477int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100478 std::vector<std::string> parts = Split_String(Path, "/", true);
479 std::string cur_path;
480 for (size_t i = 0; i < parts.size(); ++i) {
481 cur_path += "/" + parts[i];
482 if (!TWFunc::Path_Exists(cur_path)) {
483 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600484 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 -0600485 return false;
486 } else {
thatf1408b32016-01-03 11:09:15 +0100487 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600488 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400489 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400490 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400491 return true;
492}
493
Dees_Troyb46a6842012-09-25 11:06:46 -0400494void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
495 string Display_Text;
496
497 DataManager::GetValue(Read_Value, Display_Text);
498 if (Display_Text.empty())
499 Display_Text = Default_Text;
500
501 DataManager::SetValue("tw_operation", Display_Text);
502 DataManager::SetValue("tw_partition", "");
503}
504
505void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
506 string Display_Text;
507
508 DataManager::GetValue(Read_Value, Display_Text);
509 if (Display_Text.empty())
510 Display_Text = Default_Text;
511
512 DataManager::SetValue("tw_operation", Display_Text);
513 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400514}
515
Dees_Troy2673cec2013-04-02 20:22:16 +0000516void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400517 int logPipe[2];
518 int pigz_pid;
519 int destination_fd;
520 std::string destLogBuffer;
521
Dees Troy9d7fdf52013-09-19 20:49:25 +0000522 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400523
524 size_t extPos = Destination.find(".gz");
525 std::string uncompressedLog(Destination);
526 uncompressedLog.replace(extPos, Destination.length(), "");
527
528 if (Path_Exists(Destination)) {
529 Archive_Type type = Get_File_Type(Destination);
530 if (type == COMPRESSED) {
531 std::string destFileBuffer;
532 std::string getCompressedContents = "pigz -c -d " + Destination;
533 if (Exec_Cmd(getCompressedContents, destFileBuffer) < 0) {
534 LOGINFO("Unable to get destination logfile contents.\n");
535 return;
536 }
537 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600538 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400539 } else if (Path_Exists(uncompressedLog)) {
bigbiffd3317052019-12-22 16:05:12 -0500540 std::ifstream uncompressedIfs(uncompressedLog.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400541 std::stringstream uncompressedSS;
542 uncompressedSS << uncompressedIfs.rdbuf();
543 uncompressedIfs.close();
544 std::string uncompressedLogBuffer(uncompressedSS.str());
545 destLogBuffer.append(uncompressedLogBuffer);
546 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600547 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400548
bigbiffd3317052019-12-22 16:05:12 -0500549 std::ifstream ifs(Source.c_str());
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400550 std::stringstream ss;
551 ss << ifs.rdbuf();
552 std::string srcLogBuffer(ss.str());
553 ifs.close();
554
555 if (pipe(logPipe) < 0) {
556 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
557 }
558
559 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
560
561 pigz_pid = fork();
562 if (pigz_pid < 0) {
563 LOGINFO("fork() failed\n");
564 close(destination_fd);
565 close(logPipe[0]);
566 close(logPipe[1]);
567 } else if (pigz_pid == 0) {
568 close(logPipe[1]);
569 dup2(logPipe[0], fileno(stdin));
570 dup2(destination_fd, fileno(stdout));
571 if (execlp("pigz", "pigz", "-", NULL) < 0) {
572 close(destination_fd);
573 close(logPipe[0]);
574 _exit(-1);
575 }
576 } else {
577 close(logPipe[0]);
578 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
579 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
580 close(logPipe[1]);
581 close(destination_fd);
582 return;
583 }
584 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
585 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
586 close(logPipe[1]);
587 close(destination_fd);
588 return;
589 }
590 close(logPipe[1]);
591 }
592 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400593}
594
Dees_Troy2673cec2013-04-02 20:22:16 +0000595void TWFunc::Update_Log_File(void) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500596 std::string recoveryDir = get_cache_dir() + "recovery/";
597
598 if (get_cache_dir() == NON_AB_CACHE_DIR) {
599 if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
600 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", NON_AB_CACHE_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000601 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000602 }
Dees_Troya58bead2012-09-27 09:49:29 -0400603
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500604 if (!TWFunc::Path_Exists(recoveryDir)) {
605 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400606 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500607 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
608 }
609 }
610
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400611 std::string logCopy = recoveryDir + "log.gz";
612 std::string lastLogCopy = recoveryDir + "last_log.gz";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500613 copy_file(logCopy, lastLogCopy, 600);
614 Copy_Log(TMP_LOG_FILE, logCopy);
615 chown(logCopy.c_str(), 1000, 1000);
616 chmod(logCopy.c_str(), 0600);
617 chmod(lastLogCopy.c_str(), 0640);
618
Dees_Troy2673cec2013-04-02 20:22:16 +0000619 // Reset bootloader message
620 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
621 if (Part != NULL) {
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500622 std::string err;
623 if (!clear_bootloader_message((void*)&err)) {
Ethan Yonkerb5236502016-11-19 22:24:59 -0600624 if (err == "no misc device set") {
625 LOGINFO("%s\n", err.c_str());
626 } else {
627 LOGERR("%s\n", err.c_str());
628 }
629 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000630 }
Dees_Troya58bead2012-09-27 09:49:29 -0400631
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500632 if (get_cache_dir() == NON_AB_CACHE_DIR) {
633 if (PartitionManager.Mount_By_Path("/cache", false)) {
634 if (unlink("/cache/recovery/command") && errno != ENOENT) {
635 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
636 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000637 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500638 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000639 sync();
640}
641
642void TWFunc::Update_Intent_File(string Intent) {
643 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600644 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000645 }
Dees_Troya58bead2012-09-27 09:49:29 -0400646}
647
648// reboot: Reboot the system. Return -1 on error, no return on success
649int TWFunc::tw_reboot(RebootCommand command)
650{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500651 DataManager::Flush();
bigbiff7ba75002020-04-11 20:47:09 -0400652 if (!Is_Mount_Wiped("/data"))
653 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400654 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600655 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400656
Dees_Troy2673cec2013-04-02 20:22:16 +0000657 switch (command) {
658 case rb_current:
659 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000660 Update_Intent_File("s");
661 sync();
662 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500663#ifdef ANDROID_RB_PROPERTY
664 return property_set(ANDROID_RB_PROPERTY, "reboot,");
665#elif defined(ANDROID_RB_RESTART)
666 return android_reboot(ANDROID_RB_RESTART, 0, 0);
667#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000668 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500669#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000670 case rb_recovery:
671 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600672#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500673 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600674#else
675 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
676#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000677 case rb_bootloader:
678 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600679#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500680 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600681#else
682 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
683#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000684 case rb_poweroff:
685 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500686#ifdef ANDROID_RB_PROPERTY
687 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
688#elif defined(ANDROID_RB_POWEROFF)
689 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
690#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000691 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500692#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000693 case rb_download:
694 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600695#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500696 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600697#else
698 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
699#endif
mauronofrioe9a49ef2018-10-03 13:38:16 +0200700 case rb_edl:
701 check_and_run_script("/sbin/rebootedl.sh", "reboot edl");
702#ifdef ANDROID_RB_PROPERTY
703 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
704#else
705 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "edl");
706#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000707 default:
708 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600709 }
710 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400711}
712
713void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
714{
715 // Check for and run startup script if script exists
716 struct stat st;
717 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500718 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500719 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200720 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500721 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400722 }
Dees_Troy3477d712012-09-27 15:44:01 -0400723}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500724
725int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000726 DIR *d = opendir(path.c_str());
727 int r = 0;
728 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500729
Dees_Troyce675462013-01-09 19:48:21 +0000730 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500731 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000732 return -1;
733 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500734
Dees_Troyce675462013-01-09 19:48:21 +0000735 if (d) {
736 struct dirent *p;
737 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000738 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
739 continue;
740 new_path = path + "/";
741 new_path.append(p->d_name);
742 if (p->d_type == DT_DIR) {
743 r = removeDir(new_path, true);
744 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500745 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500746 r = rmdir(new_path.c_str());
747 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000748 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500749 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500750 } 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 +0000751 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000752 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000753 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000754 }
Dees_Troyce675462013-01-09 19:48:21 +0000755 }
756 }
757 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500758
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500759 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500760 if (skipParent)
761 return 0;
762 else
763 r = rmdir(path.c_str());
764 }
Dees_Troyce675462013-01-09 19:48:21 +0000765 }
766 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500767}
768
769int TWFunc::copy_file(string src, string dst, int mode) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400770 PartitionManager.Mount_By_Path(src, false);
771 PartitionManager.Mount_By_Path(dst, false);
772 if (!Path_Exists(src)) {
773 LOGINFO("Unable to find source file %s\n", src.c_str());
774 return -1;
775 }
bigbiffd3317052019-12-22 16:05:12 -0500776 std::ifstream srcfile(src.c_str(), ios::binary);
777 std::ofstream dstfile(dst.c_str(), ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500778 dstfile << srcfile.rdbuf();
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400779 if (!dstfile.bad()) {
780 LOGINFO("Copied file %s to %s\n", src.c_str(), dst.c_str());
781 }
782 else {
783 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
784 return -1;
785 }
786
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500787 srcfile.close();
788 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500789 if (chmod(dst.c_str(), mode) != 0)
790 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500791 return 0;
792}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000793
794unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
795 struct stat st;
796
797 stat(Path.c_str(), &st);
798 if (st.st_mode & S_IFDIR)
799 return DT_DIR;
800 else if (st.st_mode & S_IFBLK)
801 return DT_BLK;
802 else if (st.st_mode & S_IFCHR)
803 return DT_CHR;
804 else if (st.st_mode & S_IFIFO)
805 return DT_FIFO;
806 else if (st.st_mode & S_IFLNK)
807 return DT_LNK;
808 else if (st.st_mode & S_IFREG)
809 return DT_REG;
810 else if (st.st_mode & S_IFSOCK)
811 return DT_SOCK;
812 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000813}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500814
815int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200816 ifstream file;
817 file.open(fn.c_str(), ios::in);
818
819 if (file.is_open()) {
820 file >> results;
821 file.close();
822 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500823 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200824
825 LOGINFO("Cannot find file %s\n", fn.c_str());
826 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500827}
828
829int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500830 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500831 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500832 file.open(fn.c_str(), ios::in);
833 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500834 while (getline(file, line))
835 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500836 file.close();
837 return 0;
838 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000839 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500840 return -1;
841}
842
xNUTxe85f02d2014-07-18 01:30:58 +0200843int TWFunc::read_file(string fn, uint64_t& results) {
844 ifstream file;
845 file.open(fn.c_str(), ios::in);
846
847 if (file.is_open()) {
848 file >> results;
849 file.close();
850 return 0;
851 }
852
853 LOGINFO("Cannot find file %s\n", fn.c_str());
854 return -1;
855}
856
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600857int TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500858 FILE *file;
859 file = fopen(fn.c_str(), "w");
860 if (file != NULL) {
861 fwrite(line.c_str(), line.size(), 1, file);
862 fclose(file);
863 return 0;
864 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000865 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500866 return -1;
867}
868
Dees_Troy83bd4832013-05-04 12:39:56 +0000869bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
870 DIR* d;
871
872 string Filename;
873 Restore_Path += "/";
874 d = opendir(Restore_Path.c_str());
875 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500876 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000877 return false;
878 }
879
880 struct dirent* de;
881 while ((de = readdir(d)) != NULL) {
882 Filename = Restore_Path;
883 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500884 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000885 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
886 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
887 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
888 closedir(d);
889 return false;
890 }
891 }
892 }
893 closedir(d);
894 return true;
895}
896
Dees Troyb21cc642013-09-10 17:36:41 +0000897string TWFunc::Get_Current_Date() {
898 string Current_Date;
899 time_t seconds = time(0);
900 struct tm *t = localtime(&seconds);
901 char timestamp[255];
902 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);
903 Current_Date = timestamp;
904 return Current_Date;
905}
906
Ethan Yonkerb5557892014-02-07 21:43:20 -0600907string TWFunc::System_Property_Get(string Prop_Name) {
Chaosmaster65633a42020-02-05 15:24:09 +0100908 return System_Property_Get(Prop_Name, PartitionManager, PartitionManager.Get_Android_Root_Path());
909}
910
911string TWFunc::System_Property_Get(string Prop_Name, TWPartitionManager &PartitionManager, string Mount_Point) {
912 bool mount_state = PartitionManager.Is_Mounted_By_Path(Mount_Point);
Dees Troyb21cc642013-09-10 17:36:41 +0000913 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600914 string propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100915 if (!PartitionManager.Mount_By_Path(Mount_Point, true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600916 return propvalue;
Chaosmaster65633a42020-02-05 15:24:09 +0100917 string prop_file = Mount_Point + "/build.prop";
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600918 if (!TWFunc::Path_Exists(prop_file))
Chaosmaster65633a42020-02-05 15:24:09 +0100919 prop_file = Mount_Point + "/system/build.prop"; // for devices with system as a root file system (e.g. Pixel)
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600920 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback9d6feb52018-07-27 10:05:24 -0400921 LOGINFO("Unable to open build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200922 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000923 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100924 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600925 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000926 }
927 int line_count = buildprop.size();
928 int index;
929 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600930 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000931 for (index = 0; index < line_count; index++) {
932 end_pos = buildprop.at(index).find("=", start_pos);
933 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600934 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000935 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600936 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100937 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600938 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000939 }
940 }
Dees Troyb21cc642013-09-10 17:36:41 +0000941 if (!mount_state)
Chaosmaster65633a42020-02-05 15:24:09 +0100942 PartitionManager.UnMount_By_Path(Mount_Point, false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600943 return propvalue;
944}
945
946void TWFunc::Auto_Generate_Backup_Name() {
947 string propvalue = System_Property_Get("ro.build.display.id");
948 if (propvalue.empty()) {
949 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
950 return;
951 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400952 else {
953 //remove periods from build display so it doesn't confuse the extension code
954 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
955 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600956 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500957 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600958 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
959 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
960 // Trailing spaces cause problems on some file systems, so remove them
961 string space_check, space = " ";
962 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
963 while (space_check == space) {
964 Backup_Name.resize(Backup_Name.size() - 1);
965 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
966 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500967 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600968 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
969 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600970 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600971 } else {
972 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600973 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200974}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100975
nkk7198fc3992017-12-16 16:26:42 +0200976void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100977{
978#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200979 static bool fixed = false;
980 if (fixed)
981 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200982
983 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
984
985 struct timeval tv;
986 uint64_t offset = 0;
987 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
988
989 if (TWFunc::read_file(sepoch, offset) == 0) {
990
991 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
992
993 tv.tv_sec = offset;
994 tv.tv_usec = 0;
995 settimeofday(&tv, NULL);
996
997 gettimeofday(&tv, NULL);
998
Phoenix59146b05f22018-02-03 06:41:08 +0000999 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 +02001000
1001 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +02001002 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +02001003 return;
1004
1005 }
1006
1007 } else {
1008
1009 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
1010
1011 }
1012
Ethan Yonker9132d912015-02-02 10:32:49 -06001013 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +02001014
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001015 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
1016 // They never set it, it just ticks forward from 1970-01-01 00:00,
1017 // and then they have files /data/system/time/ats_* with 64bit offset
1018 // in miliseconds which, when added to the RTC, gives the correct time.
1019 // So, the time is: (offset_from_ats + value_from_RTC)
1020 // There are multiple ats files, they are for different systems? Bases?
1021 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1022 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1023
nkk7198fc3992017-12-16 16:26:42 +02001024 std::vector<std::string> paths; // space separated list of paths
1025 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +01001026 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +02001027 if (!PartitionManager.Mount_By_Path("/data", false))
1028 return;
1029 } else {
1030 // When specific path(s) are used, Fixup_Time needs those
1031 // partitions to already be mounted!
1032 paths = Split_String(time_paths, " ");
1033 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001034
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001035 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001036 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001037 struct dirent *dt;
1038 std::string ats_path;
1039
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001040 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1041 // - it is the one for ATS_TOD (time of day?).
1042 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001043 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001044 {
nkk7198fc3992017-12-16 16:26:42 +02001045 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001046 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001047 continue;
1048
Matt Mowera8a89d12016-12-30 18:10:37 -06001049 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001050 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001051 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001052 continue;
1053
Matt Mowera8a89d12016-12-30 18:10:37 -06001054 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001055 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001056 }
1057
1058 closedir(d);
1059 }
1060
nkk7198fc3992017-12-16 16:26:42 +02001061 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001062 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001063 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001064 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001065 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001066 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001067 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001068 } else {
1069 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001070
nkk7198fc3992017-12-16 16:26:42 +02001071 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1072 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1073 fixed = true;
1074 }
1075
1076 if (!fixed) {
1077 // Failed to get offset from ats file, check twrp settings
1078 unsigned long long value;
1079 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1080 return;
1081 } else {
1082 offset = (uint64_t) value;
1083 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1084 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1085 }
1086 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001087
1088 gettimeofday(&tv, NULL);
1089
1090 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001091#ifdef TW_CLOCK_OFFSET
1092// Some devices are even quirkier and have ats files that are offset from the actual time
1093 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1094#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001095 tv.tv_usec += (offset%1000)*1000;
1096
Matt Mowera8a89d12016-12-30 18:10:37 -06001097 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001098 {
1099 ++tv.tv_sec;
1100 tv.tv_usec -= 1000000;
1101 }
1102
1103 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001104
1105 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001106#endif
1107}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001108
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001109std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1110{
1111 std::vector<std::string> res;
1112 size_t idx = 0, idx_last = 0;
1113
Matt Mowera8a89d12016-12-30 18:10:37 -06001114 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001115 {
1116 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001117 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001118 idx = str.size();
1119
Matt Mowera8a89d12016-12-30 18:10:37 -06001120 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001121 res.push_back(str.substr(idx_last, idx-idx_last));
1122
1123 idx_last = idx + delimiter.size();
1124 }
1125
1126 return res;
1127}
1128
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001129bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1130{
1131 std::vector<std::string> parts = Split_String(path, "/");
1132 std::string cur_path;
1133 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001134 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001135 {
1136 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001137 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001138 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001139 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001140 return false;
1141 chown(cur_path.c_str(), uid, gid);
1142 }
1143 }
1144 return true;
1145}
1146
xNUTxe85f02d2014-07-18 01:30:58 +02001147int TWFunc::Set_Brightness(std::string brightness_value)
1148{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001149 int result = -1;
1150 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001151
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001152 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001153 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001154 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001155 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1156 if (!secondary_brightness_file.empty()) {
1157 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001158 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001159 }
xNUTxe85f02d2014-07-18 01:30:58 +02001160 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001161 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001162}
1163
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001164bool TWFunc::Toggle_MTP(bool enable) {
1165#ifdef TW_HAS_MTP
1166 static int was_enabled = false;
1167
1168 if (enable && was_enabled) {
1169 if (!PartitionManager.Enable_MTP())
1170 PartitionManager.Disable_MTP();
1171 } else {
1172 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1173 PartitionManager.Disable_MTP();
1174 usleep(500);
1175 }
1176 return was_enabled;
1177#else
1178 return false;
1179#endif
1180}
1181
Tom Hite5a926722014-09-15 01:31:03 +00001182void TWFunc::SetPerformanceMode(bool mode) {
1183 if (mode) {
1184 property_set("recovery.perf.mode", "1");
1185 } else {
1186 property_set("recovery.perf.mode", "0");
1187 }
1188 // Some time for events to catch up to init handlers
1189 usleep(500000);
1190}
1191
Jenkins1710bf22014-10-02 20:22:21 -04001192std::string TWFunc::to_string(unsigned long value) {
1193 std::ostringstream os;
1194 os << value;
1195 return os.str();
1196}
1197
Ethan Yonker9132d912015-02-02 10:32:49 -06001198void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001199 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001200 // Disable flashing of stock recovery
1201 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1202 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001203 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 -06001204 sync();
1205 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001206 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001207 }
1208}
1209
Ethan Yonker483e9f42016-01-11 22:21:18 -06001210unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1211 unsigned long block_device_size;
1212 int ret = 0;
1213
1214 int fd = open(block_device, O_RDONLY);
1215 if (fd < 0) {
1216 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1217 } else {
1218 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1219 close(fd);
1220 if (ret) {
1221 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1222 } else {
1223 return (unsigned long long)(block_device_size) * 512LLU;
1224 }
1225 }
1226 return 0;
1227}
1228
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001229void TWFunc::copy_kernel_log(string curr_storage) {
1230 std::string dmesgDst = curr_storage + "/dmesg.log";
1231 std::string dmesgCmd = "/sbin/dmesg";
1232
1233 std::string result;
1234 Exec_Cmd(dmesgCmd, result);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001235 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001236 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1237 tw_set_default_metadata(dmesgDst.c_str());
1238}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001239
1240bool TWFunc::isNumber(string strtocheck) {
1241 int num = 0;
1242 std::istringstream iss(strtocheck);
1243
1244 if (!(iss >> num).fail())
1245 return true;
1246 else
1247 return false;
1248}
1249
1250int TWFunc::stream_adb_backup(string &Restore_Name) {
1251 string cmd = "/sbin/bu --twrp stream " + Restore_Name;
1252 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1253 int ret = TWFunc::Exec_Cmd(cmd);
1254 if (ret != 0)
1255 return -1;
1256 return ret;
1257}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001258
1259std::string TWFunc::get_cache_dir() {
1260 if (PartitionManager.Find_Partition_By_Path(NON_AB_CACHE_DIR) == NULL) {
SyberHexena8951182019-10-29 18:08:16 -07001261 if (PartitionManager.Find_Partition_By_Path(AB_CACHE_DIR) == NULL) {
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001262 if (PartitionManager.Find_Partition_By_Path(PERSIST_CACHE_DIR) == NULL) {
1263 LOGINFO("Unable to find a directory to store TWRP logs.");
1264 return "";
1265 }
1266 return PERSIST_CACHE_DIR;
1267 } else {
1268 return AB_CACHE_DIR;
1269 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001270 }
1271 else {
1272 return NON_AB_CACHE_DIR;
1273 }
1274}
1275
1276void TWFunc::check_selinux_support() {
1277 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1278 if (TWFunc::Path_Exists("/file_contexts")) {
1279 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1280 rename("/file_contexts", "/file_contexts.bak");
1281 }
1282 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1283 rename("/prebuilt_file_contexts", "/file_contexts");
1284 }
1285 struct selinux_opt selinux_options[] = {
1286 { SELABEL_OPT_PATH, "/file_contexts" }
1287 };
1288 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1289 if (!selinux_handle)
1290 printf("No file contexts for SELinux\n");
1291 else
1292 printf("SELinux contexts loaded from /file_contexts\n");
1293 { // Check to ensure SELinux can be supported by the kernel
1294 char *contexts = NULL;
1295 std::string cacheDir = TWFunc::get_cache_dir();
1296 std::string se_context_check = cacheDir + "recovery/";
1297 int ret = 0;
1298
1299 if (cacheDir == NON_AB_CACHE_DIR) {
1300 PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false);
1301 }
1302 if (TWFunc::Path_Exists(se_context_check)) {
1303 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001304 if (ret < 0) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001305 LOGINFO("Could not check %s SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1306 lgetfilecon("/sbin/teamwin", &contexts);
1307 }
1308 }
1309 if (ret < 0) {
1310 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1311 } else {
1312 free(contexts);
1313 gui_msg("full_selinux=Full SELinux support is present.");
1314 }
1315 }
1316}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001317
1318bool TWFunc::Is_TWRP_App_In_System() {
bigbiffee7b7ff2020-03-23 15:08:27 -04001319 LOGINFO("checking for twrp app\n");
1320 TWPartition* sys = PartitionManager.Find_Partition_By_Path(PartitionManager.Get_Android_Root_Path());
1321 if (!sys->Get_Super_Status()) {
1322 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
1323 string base_path = PartitionManager.Get_Android_Root_Path();
1324 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1325 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1326 string install_path = base_path + "/priv-app";
1327 if (!TWFunc::Path_Exists(install_path))
1328 install_path = base_path + "/app";
1329 install_path += "/twrpapp";
1330 if (TWFunc::Path_Exists(install_path)) {
1331 LOGINFO("App found at '%s'\n", install_path.c_str());
1332 DataManager::SetValue("tw_app_installed_in_system", 1);
1333 return true;
1334 }
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001335 }
bigbiffee7b7ff2020-03-23 15:08:27 -04001336 DataManager::SetValue("tw_app_installed_in_system", 0);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001337 }
1338 DataManager::SetValue("tw_app_installed_in_system", 0);
bigbiffa34befa2020-03-11 19:24:18 -04001339 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001340 return false;
1341}
Chaosmaster461e39f2020-02-07 01:48:13 +01001342
1343int TWFunc::Property_Override(string Prop_Name, string Prop_Value) {
1344#ifdef TW_INCLUDE_LIBRESETPROP
1345 return setprop(Prop_Name.c_str(), Prop_Value.c_str(), false);
1346#else
1347 return -2;
1348#endif
1349}
1350
bigbiffee7b7ff2020-03-23 15:08:27 -04001351void TWFunc::List_Mounts() {
1352 std::vector<std::string> mounts;
1353 read_file("/proc/mounts", mounts);
1354 LOGINFO("Mounts:\n");
1355 for (auto&& mount: mounts) {
1356 LOGINFO("%s\n", mount.c_str());
1357 }
1358}
1359
bigbiff7ba75002020-04-11 20:47:09 -04001360bool TWFunc::Get_Encryption_Policy(fscrypt_encryption_policy &policy, std::string path) {
1361 if (!TWFunc::Path_Exists(path)) {
1362 LOGERR("Unable to find %s to get policy\n", path.c_str());
1363 return false;
1364 }
1365 if (!fscrypt_policy_get_struct(path.c_str(), &policy)) {
1366 LOGERR("No policy set for path %s\n", path.c_str());
1367 return false;
1368 }
1369 return true;
1370}
1371
1372bool TWFunc::Set_Encryption_Policy(std::string path, const fscrypt_encryption_policy &policy) {
1373 if (!TWFunc::Path_Exists(path)) {
1374 LOGERR("unable to find %s to set policy\n", path.c_str());
1375 return false;
1376 }
1377 uint8_t binary_policy[FS_KEY_DESCRIPTOR_SIZE];
1378 char policy_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
1379 policy_to_hex(binary_policy, policy_hex);
1380 if (!fscrypt_policy_set_struct(path.c_str(), &policy)) {
1381 LOGERR("unable to set policy for path: %s\n", path.c_str());
1382 return false;
1383 }
1384 return true;
1385}
1386
1387bool TWFunc::Is_Mount_Wiped(std::string path) {
1388 DIR* d = opendir(path.c_str());
1389 size_t file_count = 0;
1390 if (d != NULL) {
1391 struct dirent* de;
1392 while ((de = readdir(d)) != NULL) {
1393 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1394 continue;
1395 if (strncmp(de->d_name, "lost+found", 10) == 0 || strncmp(de->d_name, "media", 5) == 0 || strncmp(de->d_name, "misc", 4) == 0
1396 || strncmp(de->d_name, "system", 6) == 0 || strncmp(de->d_name, "unencrypted", 11) == 0
1397 || strncmp(de->d_name, "per_boot", 8) == 0)
1398 continue;
1399 file_count++;
1400
1401 }
1402 closedir(d);
1403 }
1404 return file_count == 0;
1405}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001406#endif // ndef BUILD_TWRPTAR_MAIN