blob: 4386ff6f4997f228e43af21681e627c2b7f1c7d8 [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
bigbiff bigbiff19874f12019-01-08 20:06:57 -050062struct selabel_handle *selinux_handle;
63
bigbiff bigbiff9c754052013-01-09 09:09:08 -050064/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020065int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000066 FILE* exec;
67 char buffer[130];
68 int ret = 0;
69 exec = __popen(cmd.c_str(), "r");
70 if (!exec) return -1;
Matt Mowera8a89d12016-12-30 18:10:37 -060071 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000072 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050073 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000074 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050075 }
Dees_Troy29a06352013-08-24 12:06:47 +000076 ret = __pclose(exec);
77 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050078}
79
Ethan Yonker7e941582019-03-22 08:18:21 -050080int TWFunc::Exec_Cmd(const string& cmd, bool Show_Errors) {
Vojtech Bocek05534202013-09-11 08:11:56 +020081 pid_t pid;
82 int status;
83 switch(pid = fork())
84 {
85 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050086 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020087 return -1;
88 case 0: // child
89 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
90 _exit(127);
91 break;
92 default:
93 {
Ethan Yonker7e941582019-03-22 08:18:21 -050094 if (TWFunc::Wait_For_Child(pid, &status, cmd, Show_Errors) != 0)
Vojtech Bocek05534202013-09-11 08:11:56 +020095 return -1;
96 else
97 return 0;
98 }
99 }
100}
101
Dees_Troy38bd7602012-09-14 13:33:53 -0400102// Returns "file.name" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600103string TWFunc::Get_Filename(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400104 size_t pos = Path.find_last_of("/");
105 if (pos != string::npos) {
106 string Filename;
107 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
108 return Filename;
109 } else
110 return Path;
111}
112
113// Returns "/path/to/" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600114string TWFunc::Get_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400115 size_t pos = Path.find_last_of("/");
116 if (pos != string::npos) {
117 string Pathonly;
118 Pathonly = Path.substr(0, pos + 1);
119 return Pathonly;
120 } else
121 return Path;
122}
123
Ethan Yonker7e941582019-03-22 08:18:21 -0500124int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name, bool Show_Errors) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600125 pid_t rc_pid;
126
127 rc_pid = waitpid(pid, status, 0);
128 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100129 if (WIFSIGNALED(*status)) {
Ethan Yonker7e941582019-03-22 08:18:21 -0500130 if (Show_Errors)
131 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 -0600132 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100133 } else if (WEXITSTATUS(*status) == 0) {
134 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
135 } else {
Ethan Yonker7e941582019-03-22 08:18:21 -0500136 if (Show_Errors)
137 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 -0600138 return -1;
139 }
140 } else { // no PID returned
141 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200142 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600143 else {
that2252d242015-04-03 22:33:04 +0200144 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600145 return -1;
146 }
147 }
148 return 0;
149}
150
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600151int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
152 pid_t retpid = waitpid(pid, status, WNOHANG);
153 for (; retpid == 0 && timeout; --timeout) {
154 sleep(1);
155 retpid = waitpid(pid, status, WNOHANG);
156 }
157 if (retpid == 0 && timeout == 0) {
158 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
159 kill(pid, SIGKILL);
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600160 for (timeout = 5; retpid == 0 && timeout; --timeout) {
161 sleep(1);
162 retpid = waitpid(pid, status, WNOHANG);
163 }
164 if (retpid)
165 LOGINFO("Child process killed successfully\n");
166 else
167 LOGINFO("Child process took too long to kill, may be a zombie process\n");
168 return -1;
169 } else if (retpid > 0) {
170 if (WIFSIGNALED(*status)) {
171 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
172 return -1;
173 }
174 } else if (retpid < 0) { // no PID returned
175 if (errno == ECHILD)
176 LOGERR("%s no child process exist\n", Child_Name.c_str());
177 else {
178 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
179 return -1;
180 }
181 }
182 return 0;
183}
184
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600185bool TWFunc::Path_Exists(string Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600186 struct stat st;
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400187 return stat(Path.c_str(), &st) == 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600188}
189
bigbiffce8f83c2015-12-12 18:30:21 -0500190Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600191 string::size_type i = 0;
192 int firstbyte = 0, secondbyte = 0;
193 char header[3];
194
195 ifstream f;
196 f.open(fn.c_str(), ios::in | ios::binary);
197 f.get(header, 3);
198 f.close();
199 firstbyte = header[i] & 0xff;
200 secondbyte = header[++i] & 0xff;
201
202 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500203 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600204 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500205 return ENCRYPTED;
206 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600207}
208
209int TWFunc::Try_Decrypting_File(string fn, string password) {
210#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
211 OAES_CTX * ctx = NULL;
212 uint8_t _key_data[32] = "";
213 FILE *f;
214 uint8_t buffer[4096];
215 uint8_t *buffer_out = NULL;
216 uint8_t *ptr = NULL;
217 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600218 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600219 size_t _j = 0;
220 size_t _key_data_len = 0;
221
222 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600223 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600224 _key_data[_j] = _j + 1;
225 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600226 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600227 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600228 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600229 _key_data_len = 24;
230 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600231 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600232 memcpy(_key_data, password.c_str(), password.size());
233
234 ctx = oaes_alloc();
235 if (ctx == NULL) {
236 LOGERR("Failed to allocate OAES\n");
237 return -1;
238 }
239
240 oaes_key_import_data(ctx, _key_data, _key_data_len);
241
242 f = fopen(fn.c_str(), "rb");
243 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500244 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500245 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600246 return -1;
247 }
248 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
249 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500250 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600251 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500252 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600253 return -1;
254 }
255 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
256 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
257 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500258 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600259 return -1;
260 }
261 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
262 if (buffer_out == NULL) {
263 LOGERR("Failed to allocate output buffer for try decrypt.\n");
264 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500265 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600266 return -1;
267 }
268 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
269 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
270 fclose(f);
271 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500272 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600273 return 0;
274 }
275 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500276 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600277 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500278 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600279 free(buffer_out);
280 return 1; // Decrypted successfully
281 }
282 ptr = buffer_out;
283 firstbyte = *ptr & 0xff;
284 ptr++;
285 secondbyte = *ptr & 0xff;
286 if (firstbyte == 0x1f && secondbyte == 0x8b) {
287 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
288 free(buffer_out);
289 return 3; // Compressed
290 }
291 if (out_len >= 262) {
292 ptr = buffer_out + 257;
293 if (strncmp((char*)ptr, "ustar", 5) == 0) {
294 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
295 free(buffer_out);
296 return 2; // Tar
297 }
298 }
299 free(buffer_out);
300 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
301 return 1; // Decrypted successfully
302#else
303 LOGERR("Encrypted backup support not included.\n");
304 return -1;
305#endif
306}
307
Ethan Yonker472f5062016-02-25 13:47:30 -0600308unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600309 struct stat st;
310
311 if (stat(Path.c_str(), &st) != 0)
312 return 0;
313 return st.st_size;
314}
315
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100316std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
317{
318 std::string res;
319 size_t last_idx = 0, idx = 0;
320
Matt Mowera8a89d12016-12-30 18:10:37 -0600321 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100322 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600323 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100324 res += '/';
325
326 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600327 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100328 res += path.substr(last_idx, idx);
329 break;
330 }
331
332 res += path.substr(last_idx, idx-last_idx);
333 last_idx = path.find_first_not_of('/', idx);
334 }
335
Matt Mowera8a89d12016-12-30 18:10:37 -0600336 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100337 res += '/';
338 return res;
339}
340
Matt Mower2416a502016-04-12 19:54:46 -0500341void TWFunc::Strip_Quotes(char* &str) {
342 if (strlen(str) > 0 && str[0] == '\"')
343 str++;
344 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
345 str[strlen(str)-1] = 0;
346}
347
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500348vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
349 vector<string> res;
350
351 if (in.empty() || del == '\0')
352 return res;
353
354 string field;
355 istringstream f(in);
356 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600357 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500358 if (field.empty() && skip_empty)
359 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600360 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500361 }
362 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600363 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500364 if (field.empty() && skip_empty)
365 continue;
366 res.push_back(field);
367 }
368 }
369 return res;
370}
371
Ethan Yonker472f5062016-02-25 13:47:30 -0600372timespec TWFunc::timespec_diff(timespec& start, timespec& end)
373{
374 timespec temp;
375 if ((end.tv_nsec-start.tv_nsec)<0) {
376 temp.tv_sec = end.tv_sec-start.tv_sec-1;
377 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
378 } else {
379 temp.tv_sec = end.tv_sec-start.tv_sec;
380 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
381 }
382 return temp;
383}
384
385int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
386{
387 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
388 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
389}
390
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600391#ifndef BUILD_TWRPTAR_MAIN
392
Dees_Troy38bd7602012-09-14 13:33:53 -0400393// Returns "/path" from a full /path/to/file.name
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600394string TWFunc::Get_Root_Path(const string& Path) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400395 string Local_Path = Path;
396
397 // Make sure that we have a leading slash
398 if (Local_Path.substr(0, 1) != "/")
399 Local_Path = "/" + Local_Path;
400
401 // Trim the path to get the root path only
402 size_t position = Local_Path.find("/", 2);
403 if (position != string::npos) {
404 Local_Path.resize(position);
405 }
406 return Local_Path;
407}
408
409void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400410 int need_libs = 0;
411
Captain Throwback9d6feb52018-07-27 10:05:24 -0400412 if (!PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), true))
Dees_Troy38bd7602012-09-14 13:33:53 -0400413 return;
414
415 if (!PartitionManager.Mount_By_Path("/data", true))
416 return;
417
Ethan Yonker74db1572015-10-28 12:44:49 -0500418 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000419 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400420 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500421 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000422 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400423 need_libs = 1;
424 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500425 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400426 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500427 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000428 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400429 need_libs = 1;
430 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500431 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400432 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500433 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000434 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
435 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
436 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
437 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400438 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500439 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400440 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500441 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000442 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400443 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500444 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400445}
446
447void TWFunc::htc_dumlock_restore_original_boot(void) {
448 if (!PartitionManager.Mount_By_Path("/sdcard", true))
449 return;
450
Ethan Yonker74db1572015-10-28 12:44:49 -0500451 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200452 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500453 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400454}
455
456void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
457 if (!PartitionManager.Mount_By_Path("/sdcard", true))
458 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500459 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200460 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500461 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400462}
Dees_Troy43d8b002012-09-17 16:00:01 -0400463
464int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100465 std::vector<std::string> parts = Split_String(Path, "/", true);
466 std::string cur_path;
467 for (size_t i = 0; i < parts.size(); ++i) {
468 cur_path += "/" + parts[i];
469 if (!TWFunc::Path_Exists(cur_path)) {
470 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600471 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 -0600472 return false;
473 } else {
thatf1408b32016-01-03 11:09:15 +0100474 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600475 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400476 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400477 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400478 return true;
479}
480
Dees_Troyb46a6842012-09-25 11:06:46 -0400481void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
482 string Display_Text;
483
484 DataManager::GetValue(Read_Value, Display_Text);
485 if (Display_Text.empty())
486 Display_Text = Default_Text;
487
488 DataManager::SetValue("tw_operation", Display_Text);
489 DataManager::SetValue("tw_partition", "");
490}
491
492void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
493 string Display_Text;
494
495 DataManager::GetValue(Read_Value, Display_Text);
496 if (Display_Text.empty())
497 Display_Text = Default_Text;
498
499 DataManager::SetValue("tw_operation", Display_Text);
500 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400501}
502
Dees_Troy2673cec2013-04-02 20:22:16 +0000503void TWFunc::Copy_Log(string Source, string Destination) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400504 int logPipe[2];
505 int pigz_pid;
506 int destination_fd;
507 std::string destLogBuffer;
508
Dees Troy9d7fdf52013-09-19 20:49:25 +0000509 PartitionManager.Mount_By_Path(Destination, false);
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400510
511 size_t extPos = Destination.find(".gz");
512 std::string uncompressedLog(Destination);
513 uncompressedLog.replace(extPos, Destination.length(), "");
514
515 if (Path_Exists(Destination)) {
516 Archive_Type type = Get_File_Type(Destination);
517 if (type == COMPRESSED) {
518 std::string destFileBuffer;
519 std::string getCompressedContents = "pigz -c -d " + Destination;
520 if (Exec_Cmd(getCompressedContents, destFileBuffer) < 0) {
521 LOGINFO("Unable to get destination logfile contents.\n");
522 return;
523 }
524 destLogBuffer.append(destFileBuffer);
Dees_Troy6ef66352013-02-21 08:26:57 -0600525 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400526 } else if (Path_Exists(uncompressedLog)) {
527 std::ifstream uncompressedIfs(uncompressedLog);
528 std::stringstream uncompressedSS;
529 uncompressedSS << uncompressedIfs.rdbuf();
530 uncompressedIfs.close();
531 std::string uncompressedLogBuffer(uncompressedSS.str());
532 destLogBuffer.append(uncompressedLogBuffer);
533 std::remove(uncompressedLog.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600534 }
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400535
536 std::ifstream ifs(Source);
537 std::stringstream ss;
538 ss << ifs.rdbuf();
539 std::string srcLogBuffer(ss.str());
540 ifs.close();
541
542 if (pipe(logPipe) < 0) {
543 LOGINFO("Unable to open pipe to write to persistent log file: %s\n", Destination.c_str());
544 }
545
546 destination_fd = open(Destination.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
547
548 pigz_pid = fork();
549 if (pigz_pid < 0) {
550 LOGINFO("fork() failed\n");
551 close(destination_fd);
552 close(logPipe[0]);
553 close(logPipe[1]);
554 } else if (pigz_pid == 0) {
555 close(logPipe[1]);
556 dup2(logPipe[0], fileno(stdin));
557 dup2(destination_fd, fileno(stdout));
558 if (execlp("pigz", "pigz", "-", NULL) < 0) {
559 close(destination_fd);
560 close(logPipe[0]);
561 _exit(-1);
562 }
563 } else {
564 close(logPipe[0]);
565 if (write(logPipe[1], destLogBuffer.c_str(), destLogBuffer.size()) < 0) {
566 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
567 close(logPipe[1]);
568 close(destination_fd);
569 return;
570 }
571 if (write(logPipe[1], srcLogBuffer.c_str(), srcLogBuffer.size()) < 0) {
572 LOGINFO("Unable to append to persistent log: %s\n", Destination.c_str());
573 close(logPipe[1]);
574 close(destination_fd);
575 return;
576 }
577 close(logPipe[1]);
578 }
579 close(destination_fd);
Dees_Troya58bead2012-09-27 09:49:29 -0400580}
581
Dees_Troy2673cec2013-04-02 20:22:16 +0000582void TWFunc::Update_Log_File(void) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500583 std::string recoveryDir = get_cache_dir() + "recovery/";
584
585 if (get_cache_dir() == NON_AB_CACHE_DIR) {
586 if (!PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false)) {
587 LOGINFO("Failed to mount %s for TWFunc::Update_Log_File\n", NON_AB_CACHE_DIR);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000588 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000589 }
Dees_Troya58bead2012-09-27 09:49:29 -0400590
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500591 if (!TWFunc::Path_Exists(recoveryDir)) {
592 LOGINFO("Recreating %s folder.\n", recoveryDir.c_str());
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -0400593 if (!Create_Dir_Recursive(recoveryDir, S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP, 0, 0)) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500594 LOGINFO("Unable to create %s folder.\n", recoveryDir.c_str());
595 }
596 }
597
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400598 std::string logCopy = recoveryDir + "log.gz";
599 std::string lastLogCopy = recoveryDir + "last_log.gz";
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500600 copy_file(logCopy, lastLogCopy, 600);
601 Copy_Log(TMP_LOG_FILE, logCopy);
602 chown(logCopy.c_str(), 1000, 1000);
603 chmod(logCopy.c_str(), 0600);
604 chmod(lastLogCopy.c_str(), 0640);
605
Dees_Troy2673cec2013-04-02 20:22:16 +0000606 // Reset bootloader message
607 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
608 if (Part != NULL) {
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500609 std::string err;
610 if (!clear_bootloader_message((void*)&err)) {
Ethan Yonkerb5236502016-11-19 22:24:59 -0600611 if (err == "no misc device set") {
612 LOGINFO("%s\n", err.c_str());
613 } else {
614 LOGERR("%s\n", err.c_str());
615 }
616 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000617 }
Dees_Troya58bead2012-09-27 09:49:29 -0400618
bigbiff bigbiff19874f12019-01-08 20:06:57 -0500619 if (get_cache_dir() == NON_AB_CACHE_DIR) {
620 if (PartitionManager.Mount_By_Path("/cache", false)) {
621 if (unlink("/cache/recovery/command") && errno != ENOENT) {
622 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
623 }
Dees Troy9d7fdf52013-09-19 20:49:25 +0000624 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500625 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000626 sync();
627}
628
629void TWFunc::Update_Intent_File(string Intent) {
630 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600631 TWFunc::write_to_file("/cache/recovery/intent", Intent);
Dees_Troy2673cec2013-04-02 20:22:16 +0000632 }
Dees_Troya58bead2012-09-27 09:49:29 -0400633}
634
635// reboot: Reboot the system. Return -1 on error, no return on success
636int TWFunc::tw_reboot(RebootCommand command)
637{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500638 DataManager::Flush();
639 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400640 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600641 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400642
Dees_Troy2673cec2013-04-02 20:22:16 +0000643 switch (command) {
644 case rb_current:
645 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000646 Update_Intent_File("s");
647 sync();
648 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500649#ifdef ANDROID_RB_PROPERTY
650 return property_set(ANDROID_RB_PROPERTY, "reboot,");
651#elif defined(ANDROID_RB_RESTART)
652 return android_reboot(ANDROID_RB_RESTART, 0, 0);
653#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000654 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500655#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000656 case rb_recovery:
657 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600658#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500659 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600660#else
661 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
662#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000663 case rb_bootloader:
664 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600665#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500666 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600667#else
668 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
669#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000670 case rb_poweroff:
671 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500672#ifdef ANDROID_RB_PROPERTY
673 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
674#elif defined(ANDROID_RB_POWEROFF)
675 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
676#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000677 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500678#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000679 case rb_download:
680 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600681#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500682 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600683#else
684 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
685#endif
mauronofrioe9a49ef2018-10-03 13:38:16 +0200686 case rb_edl:
687 check_and_run_script("/sbin/rebootedl.sh", "reboot edl");
688#ifdef ANDROID_RB_PROPERTY
689 return property_set(ANDROID_RB_PROPERTY, "reboot,edl");
690#else
691 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "edl");
692#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000693 default:
694 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600695 }
696 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400697}
698
699void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
700{
701 // Check for and run startup script if script exists
702 struct stat st;
703 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500704 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500705 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200706 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500707 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400708 }
Dees_Troy3477d712012-09-27 15:44:01 -0400709}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500710
711int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000712 DIR *d = opendir(path.c_str());
713 int r = 0;
714 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500715
Dees_Troyce675462013-01-09 19:48:21 +0000716 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500717 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000718 return -1;
719 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500720
Dees_Troyce675462013-01-09 19:48:21 +0000721 if (d) {
722 struct dirent *p;
723 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000724 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
725 continue;
726 new_path = path + "/";
727 new_path.append(p->d_name);
728 if (p->d_type == DT_DIR) {
729 r = removeDir(new_path, true);
730 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500731 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500732 r = rmdir(new_path.c_str());
733 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000734 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500735 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500736 } 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 +0000737 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000738 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000739 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000740 }
Dees_Troyce675462013-01-09 19:48:21 +0000741 }
742 }
743 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500744
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500745 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500746 if (skipParent)
747 return 0;
748 else
749 r = rmdir(path.c_str());
750 }
Dees_Troyce675462013-01-09 19:48:21 +0000751 }
752 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500753}
754
755int TWFunc::copy_file(string src, string dst, int mode) {
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400756 PartitionManager.Mount_By_Path(src, false);
757 PartitionManager.Mount_By_Path(dst, false);
758 if (!Path_Exists(src)) {
759 LOGINFO("Unable to find source file %s\n", src.c_str());
760 return -1;
761 }
762 std::ifstream srcfile(src, ios::binary);
763 std::ofstream dstfile(dst, ios::binary);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500764 dstfile << srcfile.rdbuf();
bigbiff bigbiffe3ad5342019-09-18 19:05:59 -0400765 if (!dstfile.bad()) {
766 LOGINFO("Copied file %s to %s\n", src.c_str(), dst.c_str());
767 }
768 else {
769 LOGINFO("Unable to copy file %s to %s\n", src.c_str(), dst.c_str());
770 return -1;
771 }
772
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500773 srcfile.close();
774 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500775 if (chmod(dst.c_str(), mode) != 0)
776 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500777 return 0;
778}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000779
780unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
781 struct stat st;
782
783 stat(Path.c_str(), &st);
784 if (st.st_mode & S_IFDIR)
785 return DT_DIR;
786 else if (st.st_mode & S_IFBLK)
787 return DT_BLK;
788 else if (st.st_mode & S_IFCHR)
789 return DT_CHR;
790 else if (st.st_mode & S_IFIFO)
791 return DT_FIFO;
792 else if (st.st_mode & S_IFLNK)
793 return DT_LNK;
794 else if (st.st_mode & S_IFREG)
795 return DT_REG;
796 else if (st.st_mode & S_IFSOCK)
797 return DT_SOCK;
798 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000799}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500800
801int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200802 ifstream file;
803 file.open(fn.c_str(), ios::in);
804
805 if (file.is_open()) {
806 file >> results;
807 file.close();
808 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500809 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200810
811 LOGINFO("Cannot find file %s\n", fn.c_str());
812 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500813}
814
815int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500816 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500817 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500818 file.open(fn.c_str(), ios::in);
819 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500820 while (getline(file, line))
821 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500822 file.close();
823 return 0;
824 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000825 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500826 return -1;
827}
828
xNUTxe85f02d2014-07-18 01:30:58 +0200829int TWFunc::read_file(string fn, uint64_t& results) {
830 ifstream file;
831 file.open(fn.c_str(), ios::in);
832
833 if (file.is_open()) {
834 file >> results;
835 file.close();
836 return 0;
837 }
838
839 LOGINFO("Cannot find file %s\n", fn.c_str());
840 return -1;
841}
842
Ethan Yonker6e8c27a2016-12-22 17:55:57 -0600843int TWFunc::write_to_file(const string& fn, const string& line) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500844 FILE *file;
845 file = fopen(fn.c_str(), "w");
846 if (file != NULL) {
847 fwrite(line.c_str(), line.size(), 1, file);
848 fclose(file);
849 return 0;
850 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000851 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500852 return -1;
853}
854
Dees_Troy83bd4832013-05-04 12:39:56 +0000855bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
856 DIR* d;
857
858 string Filename;
859 Restore_Path += "/";
860 d = opendir(Restore_Path.c_str());
861 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500862 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000863 return false;
864 }
865
866 struct dirent* de;
867 while ((de = readdir(d)) != NULL) {
868 Filename = Restore_Path;
869 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500870 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000871 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
872 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
873 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
874 closedir(d);
875 return false;
876 }
877 }
878 }
879 closedir(d);
880 return true;
881}
882
Dees Troyb21cc642013-09-10 17:36:41 +0000883string TWFunc::Get_Current_Date() {
884 string Current_Date;
885 time_t seconds = time(0);
886 struct tm *t = localtime(&seconds);
887 char timestamp[255];
888 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);
889 Current_Date = timestamp;
890 return Current_Date;
891}
892
Ethan Yonkerb5557892014-02-07 21:43:20 -0600893string TWFunc::System_Property_Get(string Prop_Name) {
Captain Throwback9d6feb52018-07-27 10:05:24 -0400894 bool mount_state = PartitionManager.Is_Mounted_By_Path(PartitionManager.Get_Android_Root_Path());
Dees Troyb21cc642013-09-10 17:36:41 +0000895 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600896 string propvalue;
Captain Throwback9d6feb52018-07-27 10:05:24 -0400897 if (!PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), true))
Ethan Yonkerb5557892014-02-07 21:43:20 -0600898 return propvalue;
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600899 string prop_file = "/system/build.prop";
900 if (!TWFunc::Path_Exists(prop_file))
Captain Throwback9d6feb52018-07-27 10:05:24 -0400901 prop_file = PartitionManager.Get_Android_Root_Path() + "/system/build.prop"; // for devices with system as a root file system (e.g. Pixel)
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600902 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Captain Throwback9d6feb52018-07-27 10:05:24 -0400903 LOGINFO("Unable to open build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200904 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000905 if (!mount_state)
Captain Throwback9d6feb52018-07-27 10:05:24 -0400906 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600907 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000908 }
909 int line_count = buildprop.size();
910 int index;
911 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600912 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000913 for (index = 0; index < line_count; index++) {
914 end_pos = buildprop.at(index).find("=", start_pos);
915 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600916 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000917 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600918 if (!mount_state)
Captain Throwback9d6feb52018-07-27 10:05:24 -0400919 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600920 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000921 }
922 }
Dees Troyb21cc642013-09-10 17:36:41 +0000923 if (!mount_state)
Captain Throwback9d6feb52018-07-27 10:05:24 -0400924 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600925 return propvalue;
926}
927
928void TWFunc::Auto_Generate_Backup_Name() {
929 string propvalue = System_Property_Get("ro.build.display.id");
930 if (propvalue.empty()) {
931 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
932 return;
933 }
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -0400934 else {
935 //remove periods from build display so it doesn't confuse the extension code
936 propvalue.erase(remove(propvalue.begin(), propvalue.end(), '.'), propvalue.end());
937 }
Ethan Yonkerb5557892014-02-07 21:43:20 -0600938 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500939 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600940 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
941 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
942 // Trailing spaces cause problems on some file systems, so remove them
943 string space_check, space = " ";
944 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
945 while (space_check == space) {
946 Backup_Name.resize(Backup_Name.size() - 1);
947 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
948 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500949 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonker53796e72019-01-11 22:49:52 -0600950 if (PartitionManager.Check_Backup_Name(Backup_Name, false, true) != 0) {
951 LOGINFO("Auto generated backup name '%s' is not valid, using date instead.\n", Backup_Name.c_str());
Ethan Yonker92d48e02014-02-26 12:05:55 -0600952 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Ethan Yonker53796e72019-01-11 22:49:52 -0600953 } else {
954 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600955 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200956}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100957
nkk7198fc3992017-12-16 16:26:42 +0200958void TWFunc::Fixup_Time_On_Boot(const string& time_paths /* = "" */)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100959{
960#ifdef QCOM_RTC_FIX
nkk7198fc3992017-12-16 16:26:42 +0200961 static bool fixed = false;
962 if (fixed)
963 return;
xNUTxe85f02d2014-07-18 01:30:58 +0200964
965 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
966
967 struct timeval tv;
968 uint64_t offset = 0;
969 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
970
971 if (TWFunc::read_file(sepoch, offset) == 0) {
972
973 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
974
975 tv.tv_sec = offset;
976 tv.tv_usec = 0;
977 settimeofday(&tv, NULL);
978
979 gettimeofday(&tv, NULL);
980
Phoenix59146b05f22018-02-03 06:41:08 +0000981 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 +0200982
983 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
nkk7198fc3992017-12-16 16:26:42 +0200984 fixed = true;
xNUTxe85f02d2014-07-18 01:30:58 +0200985 return;
986
987 }
988
989 } else {
990
991 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
992
993 }
994
Ethan Yonker9132d912015-02-02 10:32:49 -0600995 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200996
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100997 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
998 // They never set it, it just ticks forward from 1970-01-01 00:00,
999 // and then they have files /data/system/time/ats_* with 64bit offset
1000 // in miliseconds which, when added to the RTC, gives the correct time.
1001 // So, the time is: (offset_from_ats + value_from_RTC)
1002 // There are multiple ats files, they are for different systems? Bases?
1003 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
1004 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
1005
nkk7198fc3992017-12-16 16:26:42 +02001006 std::vector<std::string> paths; // space separated list of paths
1007 if (time_paths.empty()) {
Mauronofrio Matarrese2dab70d2019-03-05 02:22:26 +01001008 paths = Split_String("/data/system/time/ /data/time/ /data/vendor/time/", " ");
nkk7198fc3992017-12-16 16:26:42 +02001009 if (!PartitionManager.Mount_By_Path("/data", false))
1010 return;
1011 } else {
1012 // When specific path(s) are used, Fixup_Time needs those
1013 // partitions to already be mounted!
1014 paths = Split_String(time_paths, " ");
1015 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001016
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001017 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +02001018 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001019 struct dirent *dt;
1020 std::string ats_path;
1021
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001022 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
1023 // - it is the one for ATS_TOD (time of day?).
1024 // However, I never saw a device where the offset differs between ats files.
nkk7198fc3992017-12-16 16:26:42 +02001025 for (size_t i = 0; i < paths.size(); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001026 {
nkk7198fc3992017-12-16 16:26:42 +02001027 DIR *d = opendir(paths[i].c_str());
Matt Mowera8a89d12016-12-30 18:10:37 -06001028 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001029 continue;
1030
Matt Mowera8a89d12016-12-30 18:10:37 -06001031 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001032 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001033 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001034 continue;
1035
Matt Mowera8a89d12016-12-30 18:10:37 -06001036 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
nkk7198fc3992017-12-16 16:26:42 +02001037 ats_path = paths[i] + dt->d_name;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001038 }
1039
1040 closedir(d);
1041 }
1042
nkk7198fc3992017-12-16 16:26:42 +02001043 if (ats_path.empty()) {
xNUTxe85f02d2014-07-18 01:30:58 +02001044 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
nkk7198fc3992017-12-16 16:26:42 +02001045 } else if ((f = fopen(ats_path.c_str(), "r")) == NULL) {
Dees Troy3e254b92014-03-06 20:24:54 +00001046 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
nkk7198fc3992017-12-16 16:26:42 +02001047 } else if (fread(&offset, sizeof(offset), 1, f) != 1) {
Dees Troy3e254b92014-03-06 20:24:54 +00001048 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001049 fclose(f);
nkk7198fc3992017-12-16 16:26:42 +02001050 } else {
1051 fclose(f);
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001052
nkk7198fc3992017-12-16 16:26:42 +02001053 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), (unsigned long long) offset);
1054 DataManager::SetValue("tw_qcom_ats_offset", (unsigned long long) offset, 1);
1055 fixed = true;
1056 }
1057
1058 if (!fixed) {
1059 // Failed to get offset from ats file, check twrp settings
1060 unsigned long long value;
1061 if (DataManager::GetValue("tw_qcom_ats_offset", value) < 0) {
1062 return;
1063 } else {
1064 offset = (uint64_t) value;
1065 LOGINFO("TWFunc::Fixup_Time: Setting time offset from twrp setting file, offset %llu\n", (unsigned long long) offset);
1066 // Do not consider the settings file as a definitive answer, keep fixed=false so next run will try ats files again
1067 }
1068 }
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001069
1070 gettimeofday(&tv, NULL);
1071
1072 tv.tv_sec += offset/1000;
Phoenix591e444d112018-02-03 07:23:54 +00001073#ifdef TW_CLOCK_OFFSET
1074// Some devices are even quirkier and have ats files that are offset from the actual time
1075 tv.tv_sec = tv.tv_sec + TW_CLOCK_OFFSET;
1076#endif
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001077 tv.tv_usec += (offset%1000)*1000;
1078
Matt Mowera8a89d12016-12-30 18:10:37 -06001079 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001080 {
1081 ++tv.tv_sec;
1082 tv.tv_usec -= 1000000;
1083 }
1084
1085 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +02001086
1087 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +01001088#endif
1089}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001090
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001091std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
1092{
1093 std::vector<std::string> res;
1094 size_t idx = 0, idx_last = 0;
1095
Matt Mowera8a89d12016-12-30 18:10:37 -06001096 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001097 {
1098 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001099 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001100 idx = str.size();
1101
Matt Mowera8a89d12016-12-30 18:10:37 -06001102 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001103 res.push_back(str.substr(idx_last, idx-idx_last));
1104
1105 idx_last = idx + delimiter.size();
1106 }
1107
1108 return res;
1109}
1110
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001111bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1112{
1113 std::vector<std::string> parts = Split_String(path, "/");
1114 std::string cur_path;
1115 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001116 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001117 {
1118 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001119 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001120 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001121 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001122 return false;
1123 chown(cur_path.c_str(), uid, gid);
1124 }
1125 }
1126 return true;
1127}
1128
xNUTxe85f02d2014-07-18 01:30:58 +02001129int TWFunc::Set_Brightness(std::string brightness_value)
1130{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001131 int result = -1;
1132 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001133
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001134 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001135 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001136 result = TWFunc::write_to_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001137 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1138 if (!secondary_brightness_file.empty()) {
1139 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001140 TWFunc::write_to_file(secondary_brightness_file, brightness_value);
xNUTxe85f02d2014-07-18 01:30:58 +02001141 }
xNUTxe85f02d2014-07-18 01:30:58 +02001142 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001143 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001144}
1145
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001146bool TWFunc::Toggle_MTP(bool enable) {
1147#ifdef TW_HAS_MTP
1148 static int was_enabled = false;
1149
1150 if (enable && was_enabled) {
1151 if (!PartitionManager.Enable_MTP())
1152 PartitionManager.Disable_MTP();
1153 } else {
1154 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1155 PartitionManager.Disable_MTP();
1156 usleep(500);
1157 }
1158 return was_enabled;
1159#else
1160 return false;
1161#endif
1162}
1163
Tom Hite5a926722014-09-15 01:31:03 +00001164void TWFunc::SetPerformanceMode(bool mode) {
1165 if (mode) {
1166 property_set("recovery.perf.mode", "1");
1167 } else {
1168 property_set("recovery.perf.mode", "0");
1169 }
1170 // Some time for events to catch up to init handlers
1171 usleep(500000);
1172}
1173
Jenkins1710bf22014-10-02 20:22:21 -04001174std::string TWFunc::to_string(unsigned long value) {
1175 std::ostringstream os;
1176 os << value;
1177 return os.str();
1178}
1179
Ethan Yonker9132d912015-02-02 10:32:49 -06001180void TWFunc::Disable_Stock_Recovery_Replace(void) {
Captain Throwback9d6feb52018-07-27 10:05:24 -04001181 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
Ethan Yonker9132d912015-02-02 10:32:49 -06001182 // Disable flashing of stock recovery
1183 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1184 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001185 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 -06001186 sync();
1187 }
Captain Throwback9d6feb52018-07-27 10:05:24 -04001188 PartitionManager.UnMount_By_Path(PartitionManager.Get_Android_Root_Path(), false);
Ethan Yonker9132d912015-02-02 10:32:49 -06001189 }
1190}
1191
Ethan Yonker483e9f42016-01-11 22:21:18 -06001192unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1193 unsigned long block_device_size;
1194 int ret = 0;
1195
1196 int fd = open(block_device, O_RDONLY);
1197 if (fd < 0) {
1198 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1199 } else {
1200 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1201 close(fd);
1202 if (ret) {
1203 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1204 } else {
1205 return (unsigned long long)(block_device_size) * 512LLU;
1206 }
1207 }
1208 return 0;
1209}
1210
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001211void TWFunc::copy_kernel_log(string curr_storage) {
1212 std::string dmesgDst = curr_storage + "/dmesg.log";
1213 std::string dmesgCmd = "/sbin/dmesg";
1214
1215 std::string result;
1216 Exec_Cmd(dmesgCmd, result);
Ethan Yonker6e8c27a2016-12-22 17:55:57 -06001217 write_to_file(dmesgDst, result);
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001218 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1219 tw_set_default_metadata(dmesgDst.c_str());
1220}
bigbiff bigbiff19fb79c2016-09-05 21:04:51 -04001221
1222bool TWFunc::isNumber(string strtocheck) {
1223 int num = 0;
1224 std::istringstream iss(strtocheck);
1225
1226 if (!(iss >> num).fail())
1227 return true;
1228 else
1229 return false;
1230}
1231
1232int TWFunc::stream_adb_backup(string &Restore_Name) {
1233 string cmd = "/sbin/bu --twrp stream " + Restore_Name;
1234 LOGINFO("stream_adb_backup: %s\n", cmd.c_str());
1235 int ret = TWFunc::Exec_Cmd(cmd);
1236 if (ret != 0)
1237 return -1;
1238 return ret;
1239}
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001240
1241std::string TWFunc::get_cache_dir() {
1242 if (PartitionManager.Find_Partition_By_Path(NON_AB_CACHE_DIR) == NULL) {
SyberHexena8951182019-10-29 18:08:16 -07001243 if (PartitionManager.Find_Partition_By_Path(AB_CACHE_DIR) == NULL) {
bigbiff bigbiffe4bdb152019-03-23 18:33:17 -04001244 if (PartitionManager.Find_Partition_By_Path(PERSIST_CACHE_DIR) == NULL) {
1245 LOGINFO("Unable to find a directory to store TWRP logs.");
1246 return "";
1247 }
1248 return PERSIST_CACHE_DIR;
1249 } else {
1250 return AB_CACHE_DIR;
1251 }
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001252 }
1253 else {
1254 return NON_AB_CACHE_DIR;
1255 }
1256}
1257
1258void TWFunc::check_selinux_support() {
1259 if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
1260 if (TWFunc::Path_Exists("/file_contexts")) {
1261 printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
1262 rename("/file_contexts", "/file_contexts.bak");
1263 }
1264 printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
1265 rename("/prebuilt_file_contexts", "/file_contexts");
1266 }
1267 struct selinux_opt selinux_options[] = {
1268 { SELABEL_OPT_PATH, "/file_contexts" }
1269 };
1270 selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
1271 if (!selinux_handle)
1272 printf("No file contexts for SELinux\n");
1273 else
1274 printf("SELinux contexts loaded from /file_contexts\n");
1275 { // Check to ensure SELinux can be supported by the kernel
1276 char *contexts = NULL;
1277 std::string cacheDir = TWFunc::get_cache_dir();
1278 std::string se_context_check = cacheDir + "recovery/";
1279 int ret = 0;
1280
1281 if (cacheDir == NON_AB_CACHE_DIR) {
1282 PartitionManager.Mount_By_Path(NON_AB_CACHE_DIR, false);
1283 }
1284 if (TWFunc::Path_Exists(se_context_check)) {
1285 ret = lgetfilecon(se_context_check.c_str(), &contexts);
Makornthawat Emeryabc299c2019-03-29 13:45:22 +00001286 if (ret < 0) {
bigbiff bigbiff19874f12019-01-08 20:06:57 -05001287 LOGINFO("Could not check %s SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n", se_context_check.c_str());
1288 lgetfilecon("/sbin/teamwin", &contexts);
1289 }
1290 }
1291 if (ret < 0) {
1292 gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
1293 } else {
1294 free(contexts);
1295 gui_msg("full_selinux=Full SELinux support is present.");
1296 }
1297 }
1298}
Ethan Yonker76bbd3a2019-05-10 10:50:04 -05001299
1300bool TWFunc::Is_TWRP_App_In_System() {
1301 if (PartitionManager.Mount_By_Path(PartitionManager.Get_Android_Root_Path(), false)) {
1302 string base_path = PartitionManager.Get_Android_Root_Path();
1303 if (TWFunc::Path_Exists(PartitionManager.Get_Android_Root_Path() + "/system"))
1304 base_path += "/system"; // For devices with system as a root file system (e.g. Pixel)
1305 string install_path = base_path + "/priv-app";
1306 if (!TWFunc::Path_Exists(install_path))
1307 install_path = base_path + "/app";
1308 install_path += "/twrpapp";
1309 if (TWFunc::Path_Exists(install_path)) {
1310 LOGINFO("App found at '%s'\n", install_path.c_str());
1311 DataManager::SetValue("tw_app_installed_in_system", 1);
1312 return true;
1313 }
1314 }
1315 DataManager::SetValue("tw_app_installed_in_system", 0);
1316 return false;
1317}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001318#endif // ndef BUILD_TWRPTAR_MAIN