blob: c9643570f1fc96b5fa385b3c3ddbc4e206c22406 [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>
bigbiff74a6d0d2015-02-14 20:49:44 -050038#include <algorithm>
Dees_Troy38bd7602012-09-14 13:33:53 -040039#include "twrp-functions.hpp"
Dees_Troy2673cec2013-04-02 20:22:16 +000040#include "twcommon.h"
Ethan Yonker472f5062016-02-25 13:47:30 -060041#include "gui/gui.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060042#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040043#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060044#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040045#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000046#include "bootloader.h"
Tom Hite5a926722014-09-15 01:31:03 +000047#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050048#include "cutils/android_reboot.h"
49#include <sys/reboot.h>
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060050#endif // ndef BUILD_TWRPTAR_MAIN
Dees_Troy83bd4832013-05-04 12:39:56 +000051#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
52 #include "openaes/inc/oaes_lib.h"
53#endif
Ethan Yonkerf1179622016-08-25 15:32:21 -050054#include "set_metadata.h"
Dees_Troy38bd7602012-09-14 13:33:53 -040055
Dees_Troyb05ddee2013-01-28 20:24:50 +000056extern "C" {
57 #include "libcrecovery/common.h"
58}
59
bigbiff bigbiff9c754052013-01-09 09:09:08 -050060/* Execute a command */
Vojtech Bocek05534202013-09-11 08:11:56 +020061int TWFunc::Exec_Cmd(const string& cmd, string &result) {
Dees_Troy29a06352013-08-24 12:06:47 +000062 FILE* exec;
63 char buffer[130];
64 int ret = 0;
65 exec = __popen(cmd.c_str(), "r");
66 if (!exec) return -1;
Matt Mowera8a89d12016-12-30 18:10:37 -060067 while (!feof(exec)) {
Dees_Troy29a06352013-08-24 12:06:47 +000068 if (fgets(buffer, 128, exec) != NULL) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -050069 result += buffer;
Dees_Troyb05ddee2013-01-28 20:24:50 +000070 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -050071 }
Dees_Troy29a06352013-08-24 12:06:47 +000072 ret = __pclose(exec);
73 return ret;
bigbiff bigbiff9c754052013-01-09 09:09:08 -050074}
75
Vojtech Bocek05534202013-09-11 08:11:56 +020076int TWFunc::Exec_Cmd(const string& cmd) {
77 pid_t pid;
78 int status;
79 switch(pid = fork())
80 {
81 case -1:
bigbiff bigbiff731df792014-02-20 18:26:13 -050082 LOGERR("Exec_Cmd(): vfork failed: %d!\n", errno);
Vojtech Bocek05534202013-09-11 08:11:56 +020083 return -1;
84 case 0: // child
85 execl("/sbin/sh", "sh", "-c", cmd.c_str(), NULL);
86 _exit(127);
87 break;
88 default:
89 {
90 if (TWFunc::Wait_For_Child(pid, &status, cmd) != 0)
91 return -1;
92 else
93 return 0;
94 }
95 }
96}
97
Dees_Troy38bd7602012-09-14 13:33:53 -040098// Returns "file.name" from a full /path/to/file.name
99string TWFunc::Get_Filename(string Path) {
100 size_t pos = Path.find_last_of("/");
101 if (pos != string::npos) {
102 string Filename;
103 Filename = Path.substr(pos + 1, Path.size() - pos - 1);
104 return Filename;
105 } else
106 return Path;
107}
108
109// Returns "/path/to/" from a full /path/to/file.name
110string TWFunc::Get_Path(string Path) {
111 size_t pos = Path.find_last_of("/");
112 if (pos != string::npos) {
113 string Pathonly;
114 Pathonly = Path.substr(0, pos + 1);
115 return Pathonly;
116 } else
117 return Path;
118}
119
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600120int TWFunc::Wait_For_Child(pid_t pid, int *status, string Child_Name) {
121 pid_t rc_pid;
122
123 rc_pid = waitpid(pid, status, 0);
124 if (rc_pid > 0) {
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100125 if (WIFSIGNALED(*status)) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500126 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 -0600127 return -1;
Vojtech Bocek0fdcbec2015-03-20 15:36:40 +0100128 } else if (WEXITSTATUS(*status) == 0) {
129 LOGINFO("%s process ended with RC=%d\n", Child_Name.c_str(), WEXITSTATUS(*status)); // Success
130 } else {
Ethan Yonker74db1572015-10-28 12:44:49 -0500131 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 -0600132 return -1;
133 }
134 } else { // no PID returned
135 if (errno == ECHILD)
that2252d242015-04-03 22:33:04 +0200136 LOGERR("%s no child process exist\n", Child_Name.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600137 else {
that2252d242015-04-03 22:33:04 +0200138 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600139 return -1;
140 }
141 }
142 return 0;
143}
144
Ethan Yonkerddb63e22017-01-19 14:01:57 -0600145int TWFunc::Wait_For_Child_Timeout(pid_t pid, int *status, const string& Child_Name, int timeout) {
146 pid_t retpid = waitpid(pid, status, WNOHANG);
147 for (; retpid == 0 && timeout; --timeout) {
148 sleep(1);
149 retpid = waitpid(pid, status, WNOHANG);
150 }
151 if (retpid == 0 && timeout == 0) {
152 LOGERR("%s took too long, killing process\n", Child_Name.c_str());
153 kill(pid, SIGKILL);
154 int died = 0;
155 for (timeout = 5; retpid == 0 && timeout; --timeout) {
156 sleep(1);
157 retpid = waitpid(pid, status, WNOHANG);
158 }
159 if (retpid)
160 LOGINFO("Child process killed successfully\n");
161 else
162 LOGINFO("Child process took too long to kill, may be a zombie process\n");
163 return -1;
164 } else if (retpid > 0) {
165 if (WIFSIGNALED(*status)) {
166 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
167 return -1;
168 }
169 } else if (retpid < 0) { // no PID returned
170 if (errno == ECHILD)
171 LOGERR("%s no child process exist\n", Child_Name.c_str());
172 else {
173 LOGERR("%s Unexpected error %d\n", Child_Name.c_str(), errno);
174 return -1;
175 }
176 }
177 return 0;
178}
179
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600180bool TWFunc::Path_Exists(string Path) {
181 // Check to see if the Path exists
182 struct stat st;
183 if (stat(Path.c_str(), &st) != 0)
184 return false;
185 else
186 return true;
187}
188
bigbiffce8f83c2015-12-12 18:30:21 -0500189Archive_Type TWFunc::Get_File_Type(string fn) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600190 string::size_type i = 0;
191 int firstbyte = 0, secondbyte = 0;
192 char header[3];
193
194 ifstream f;
195 f.open(fn.c_str(), ios::in | ios::binary);
196 f.get(header, 3);
197 f.close();
198 firstbyte = header[i] & 0xff;
199 secondbyte = header[++i] & 0xff;
200
201 if (firstbyte == 0x1f && secondbyte == 0x8b)
bigbiffce8f83c2015-12-12 18:30:21 -0500202 return COMPRESSED;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600203 else if (firstbyte == 0x4f && secondbyte == 0x41)
bigbiffce8f83c2015-12-12 18:30:21 -0500204 return ENCRYPTED;
205 return UNCOMPRESSED; // default
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600206}
207
208int TWFunc::Try_Decrypting_File(string fn, string password) {
209#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
210 OAES_CTX * ctx = NULL;
211 uint8_t _key_data[32] = "";
212 FILE *f;
213 uint8_t buffer[4096];
214 uint8_t *buffer_out = NULL;
215 uint8_t *ptr = NULL;
216 size_t read_len = 0, out_len = 0;
Matt Mower23d8aae2017-01-06 14:30:33 -0600217 int firstbyte = 0, secondbyte = 0;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600218 size_t _j = 0;
219 size_t _key_data_len = 0;
220
221 // mostly kanged from OpenAES oaes.c
Matt Mowera8a89d12016-12-30 18:10:37 -0600222 for ( _j = 0; _j < 32; _j++ )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600223 _key_data[_j] = _j + 1;
224 _key_data_len = password.size();
Matt Mowera8a89d12016-12-30 18:10:37 -0600225 if ( 16 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600226 _key_data_len = 16;
Matt Mowera8a89d12016-12-30 18:10:37 -0600227 else if ( 24 >= _key_data_len )
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600228 _key_data_len = 24;
229 else
Matt Mowera8a89d12016-12-30 18:10:37 -0600230 _key_data_len = 32;
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600231 memcpy(_key_data, password.c_str(), password.size());
232
233 ctx = oaes_alloc();
234 if (ctx == NULL) {
235 LOGERR("Failed to allocate OAES\n");
236 return -1;
237 }
238
239 oaes_key_import_data(ctx, _key_data, _key_data_len);
240
241 f = fopen(fn.c_str(), "rb");
242 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500243 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500244 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600245 return -1;
246 }
247 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
248 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500249 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600250 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500251 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600252 return -1;
253 }
254 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
255 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
256 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500257 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600258 return -1;
259 }
260 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
261 if (buffer_out == NULL) {
262 LOGERR("Failed to allocate output buffer for try decrypt.\n");
263 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500264 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600265 return -1;
266 }
267 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
268 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
269 fclose(f);
270 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500271 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600272 return 0;
273 }
274 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500275 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600276 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500277 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600278 free(buffer_out);
279 return 1; // Decrypted successfully
280 }
281 ptr = buffer_out;
282 firstbyte = *ptr & 0xff;
283 ptr++;
284 secondbyte = *ptr & 0xff;
285 if (firstbyte == 0x1f && secondbyte == 0x8b) {
286 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
287 free(buffer_out);
288 return 3; // Compressed
289 }
290 if (out_len >= 262) {
291 ptr = buffer_out + 257;
292 if (strncmp((char*)ptr, "ustar", 5) == 0) {
293 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
294 free(buffer_out);
295 return 2; // Tar
296 }
297 }
298 free(buffer_out);
299 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
300 return 1; // Decrypted successfully
301#else
302 LOGERR("Encrypted backup support not included.\n");
303 return -1;
304#endif
305}
306
Ethan Yonker472f5062016-02-25 13:47:30 -0600307unsigned long TWFunc::Get_File_Size(const string& Path) {
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600308 struct stat st;
309
310 if (stat(Path.c_str(), &st) != 0)
311 return 0;
312 return st.st_size;
313}
314
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100315std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
316{
317 std::string res;
318 size_t last_idx = 0, idx = 0;
319
Matt Mowera8a89d12016-12-30 18:10:37 -0600320 while (last_idx != std::string::npos)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100321 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600322 if (last_idx != 0)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100323 res += '/';
324
325 idx = path.find_first_of('/', last_idx);
Matt Mowera8a89d12016-12-30 18:10:37 -0600326 if (idx == std::string::npos) {
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100327 res += path.substr(last_idx, idx);
328 break;
329 }
330
331 res += path.substr(last_idx, idx-last_idx);
332 last_idx = path.find_first_not_of('/', idx);
333 }
334
Matt Mowera8a89d12016-12-30 18:10:37 -0600335 if (leaveLast)
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100336 res += '/';
337 return res;
338}
339
Matt Mower2416a502016-04-12 19:54:46 -0500340void TWFunc::Strip_Quotes(char* &str) {
341 if (strlen(str) > 0 && str[0] == '\"')
342 str++;
343 if (strlen(str) > 0 && str[strlen(str)-1] == '\"')
344 str[strlen(str)-1] = 0;
345}
346
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500347vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
348 vector<string> res;
349
350 if (in.empty() || del == '\0')
351 return res;
352
353 string field;
354 istringstream f(in);
355 if (del == '\n') {
Matt Mowera8a89d12016-12-30 18:10:37 -0600356 while (getline(f, field)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500357 if (field.empty() && skip_empty)
358 continue;
Matt Mowera8a89d12016-12-30 18:10:37 -0600359 res.push_back(field);
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500360 }
361 } else {
Matt Mowera8a89d12016-12-30 18:10:37 -0600362 while (getline(f, field, del)) {
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500363 if (field.empty() && skip_empty)
364 continue;
365 res.push_back(field);
366 }
367 }
368 return res;
369}
370
Ethan Yonker472f5062016-02-25 13:47:30 -0600371timespec TWFunc::timespec_diff(timespec& start, timespec& end)
372{
373 timespec temp;
374 if ((end.tv_nsec-start.tv_nsec)<0) {
375 temp.tv_sec = end.tv_sec-start.tv_sec-1;
376 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
377 } else {
378 temp.tv_sec = end.tv_sec-start.tv_sec;
379 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
380 }
381 return temp;
382}
383
384int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
385{
386 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
387 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
388}
389
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600390#ifndef BUILD_TWRPTAR_MAIN
391
Dees_Troy38bd7602012-09-14 13:33:53 -0400392// Returns "/path" from a full /path/to/file.name
393string TWFunc::Get_Root_Path(string Path) {
394 string Local_Path = Path;
395
396 // Make sure that we have a leading slash
397 if (Local_Path.substr(0, 1) != "/")
398 Local_Path = "/" + Local_Path;
399
400 // Trim the path to get the root path only
401 size_t position = Local_Path.find("/", 2);
402 if (position != string::npos) {
403 Local_Path.resize(position);
404 }
405 return Local_Path;
406}
407
408void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400409 int need_libs = 0;
410
411 if (!PartitionManager.Mount_By_Path("/system", true))
412 return;
413
414 if (!PartitionManager.Mount_By_Path("/data", true))
415 return;
416
Ethan Yonker74db1572015-10-28 12:44:49 -0500417 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000418 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400419 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500420 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000421 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400422 need_libs = 1;
423 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500424 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400425 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500426 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000427 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400428 need_libs = 1;
429 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500430 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400431 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500432 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000433 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
434 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
435 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
436 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400437 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500438 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400439 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500440 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000441 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400442 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500443 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400444}
445
446void TWFunc::htc_dumlock_restore_original_boot(void) {
447 if (!PartitionManager.Mount_By_Path("/sdcard", true))
448 return;
449
Ethan Yonker74db1572015-10-28 12:44:49 -0500450 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200451 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500452 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400453}
454
455void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
456 if (!PartitionManager.Mount_By_Path("/sdcard", true))
457 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500458 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200459 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500460 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400461}
Dees_Troy43d8b002012-09-17 16:00:01 -0400462
463int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100464 std::vector<std::string> parts = Split_String(Path, "/", true);
465 std::string cur_path;
466 for (size_t i = 0; i < parts.size(); ++i) {
467 cur_path += "/" + parts[i];
468 if (!TWFunc::Path_Exists(cur_path)) {
469 if (mkdir(cur_path.c_str(), 0777)) {
Matt Mower3c366972015-12-25 19:28:31 -0600470 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 -0600471 return false;
472 } else {
thatf1408b32016-01-03 11:09:15 +0100473 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600474 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400475 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400476 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400477 return true;
478}
479
Dees_Troyb46a6842012-09-25 11:06:46 -0400480void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
481 string Display_Text;
482
483 DataManager::GetValue(Read_Value, Display_Text);
484 if (Display_Text.empty())
485 Display_Text = Default_Text;
486
487 DataManager::SetValue("tw_operation", Display_Text);
488 DataManager::SetValue("tw_partition", "");
489}
490
491void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
492 string Display_Text;
493
494 DataManager::GetValue(Read_Value, Display_Text);
495 if (Display_Text.empty())
496 Display_Text = Default_Text;
497
498 DataManager::SetValue("tw_operation", Display_Text);
499 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400500}
501
Dees_Troy2673cec2013-04-02 20:22:16 +0000502void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000503 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000504 FILE *destination_log = fopen(Destination.c_str(), "a");
505 if (destination_log == NULL) {
506 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600507 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000508 FILE *source_log = fopen(Source.c_str(), "r");
509 if (source_log != NULL) {
510 fseek(source_log, Log_Offset, SEEK_SET);
511 char buffer[4096];
512 while (fgets(buffer, sizeof(buffer), source_log))
513 fputs(buffer, destination_log); // Buffered write of log file
514 Log_Offset = ftell(source_log);
515 fflush(source_log);
516 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600517 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000518 fflush(destination_log);
519 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600520 }
Dees_Troya58bead2012-09-27 09:49:29 -0400521}
522
Dees_Troy2673cec2013-04-02 20:22:16 +0000523void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500524 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000525 if (PartitionManager.Mount_By_Path("/cache", false)) {
526 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
527 LOGINFO("Recreating /cache/recovery folder.\n");
528 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
529 LOGINFO("Unable to create /cache/recovery folder.\n");
530 }
531 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
532 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
533 chown("/cache/recovery/log", 1000, 1000);
534 chmod("/cache/recovery/log", 0600);
535 chmod("/cache/recovery/last_log", 0640);
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600536 } else if (PartitionManager.Mount_By_Path("/data", false) && TWFunc::Path_Exists("/data/cache/recovery/.")) {
537 Copy_Log(TMP_LOG_FILE, "/data/cache/recovery/log");
538 copy_file("/data/cache/recovery/log", "/data/cache/recovery/last_log", 600);
539 chown("/data/cache/recovery/log", 1000, 1000);
540 chmod("/data/cache/recovery/log", 0600);
541 chmod("/data/cache/recovery/last_log", 0640);
Dees Troy9d7fdf52013-09-19 20:49:25 +0000542 } else {
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600543 LOGINFO("Failed to mount /cache or find /data/cache for TWFunc::Update_Log_File\n");
Dees Troy9d7fdf52013-09-19 20:49:25 +0000544 }
Dees_Troya58bead2012-09-27 09:49:29 -0400545
Dees_Troy2673cec2013-04-02 20:22:16 +0000546 // Reset bootloader message
547 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
548 if (Part != NULL) {
Ethan Yonkerb5236502016-11-19 22:24:59 -0600549 string err;
550 if (!clear_bootloader_message(&err)) {
551 if (err == "no misc device set") {
552 LOGINFO("%s\n", err.c_str());
553 } else {
554 LOGERR("%s\n", err.c_str());
555 }
556 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000557 }
Dees_Troya58bead2012-09-27 09:49:29 -0400558
Ethan Yonkerff2b7882016-12-10 09:04:41 -0600559 if (PartitionManager.Mount_By_Path("/cache", false)) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000560 if (unlink("/cache/recovery/command") && errno != ENOENT) {
561 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
562 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500563 }
Dees_Troya58bead2012-09-27 09:49:29 -0400564
Dees_Troy2673cec2013-04-02 20:22:16 +0000565 sync();
566}
567
568void TWFunc::Update_Intent_File(string Intent) {
569 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
570 TWFunc::write_file("/cache/recovery/intent", Intent);
571 }
Dees_Troya58bead2012-09-27 09:49:29 -0400572}
573
574// reboot: Reboot the system. Return -1 on error, no return on success
575int TWFunc::tw_reboot(RebootCommand command)
576{
Ethan Yonkerfe916112016-03-14 14:54:37 -0500577 DataManager::Flush();
578 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400579 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600580 sync();
Dees_Troya58bead2012-09-27 09:49:29 -0400581
Dees_Troy2673cec2013-04-02 20:22:16 +0000582 switch (command) {
583 case rb_current:
584 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000585 Update_Intent_File("s");
586 sync();
587 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500588#ifdef ANDROID_RB_PROPERTY
589 return property_set(ANDROID_RB_PROPERTY, "reboot,");
590#elif defined(ANDROID_RB_RESTART)
591 return android_reboot(ANDROID_RB_RESTART, 0, 0);
592#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000593 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500594#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000595 case rb_recovery:
596 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600597#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500598 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600599#else
600 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
601#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000602 case rb_bootloader:
603 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600604#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500605 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600606#else
607 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
608#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000609 case rb_poweroff:
610 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500611#ifdef ANDROID_RB_PROPERTY
612 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
613#elif defined(ANDROID_RB_POWEROFF)
614 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
615#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000616 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500617#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000618 case rb_download:
619 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600620#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500621 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600622#else
623 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
624#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000625 default:
626 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600627 }
628 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400629}
630
631void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
632{
633 // Check for and run startup script if script exists
634 struct stat st;
635 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500636 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500637 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200638 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500639 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400640 }
Dees_Troy3477d712012-09-27 15:44:01 -0400641}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500642
643int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000644 DIR *d = opendir(path.c_str());
645 int r = 0;
646 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500647
Dees_Troyce675462013-01-09 19:48:21 +0000648 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500649 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000650 return -1;
651 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500652
Dees_Troyce675462013-01-09 19:48:21 +0000653 if (d) {
654 struct dirent *p;
655 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000656 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
657 continue;
658 new_path = path + "/";
659 new_path.append(p->d_name);
660 if (p->d_type == DT_DIR) {
661 r = removeDir(new_path, true);
662 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500663 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500664 r = rmdir(new_path.c_str());
665 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000666 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500667 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500668 } 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 +0000669 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000670 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000671 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000672 }
Dees_Troyce675462013-01-09 19:48:21 +0000673 }
674 }
675 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500676
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500677 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500678 if (skipParent)
679 return 0;
680 else
681 r = rmdir(path.c_str());
682 }
Dees_Troyce675462013-01-09 19:48:21 +0000683 }
684 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500685}
686
687int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000688 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500689 ifstream srcfile(src.c_str(), ios::binary);
690 ofstream dstfile(dst.c_str(), ios::binary);
691 dstfile << srcfile.rdbuf();
692 srcfile.close();
693 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500694 if (chmod(dst.c_str(), mode) != 0)
695 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500696 return 0;
697}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000698
699unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
700 struct stat st;
701
702 stat(Path.c_str(), &st);
703 if (st.st_mode & S_IFDIR)
704 return DT_DIR;
705 else if (st.st_mode & S_IFBLK)
706 return DT_BLK;
707 else if (st.st_mode & S_IFCHR)
708 return DT_CHR;
709 else if (st.st_mode & S_IFIFO)
710 return DT_FIFO;
711 else if (st.st_mode & S_IFLNK)
712 return DT_LNK;
713 else if (st.st_mode & S_IFREG)
714 return DT_REG;
715 else if (st.st_mode & S_IFSOCK)
716 return DT_SOCK;
717 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000718}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500719
720int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200721 ifstream file;
722 file.open(fn.c_str(), ios::in);
723
724 if (file.is_open()) {
725 file >> results;
726 file.close();
727 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500728 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200729
730 LOGINFO("Cannot find file %s\n", fn.c_str());
731 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500732}
733
734int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500735 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500736 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500737 file.open(fn.c_str(), ios::in);
738 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500739 while (getline(file, line))
740 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500741 file.close();
742 return 0;
743 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000744 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500745 return -1;
746}
747
xNUTxe85f02d2014-07-18 01:30:58 +0200748int TWFunc::read_file(string fn, uint64_t& results) {
749 ifstream file;
750 file.open(fn.c_str(), ios::in);
751
752 if (file.is_open()) {
753 file >> results;
754 file.close();
755 return 0;
756 }
757
758 LOGINFO("Cannot find file %s\n", fn.c_str());
759 return -1;
760}
761
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500762int TWFunc::write_file(string fn, string& line) {
763 FILE *file;
764 file = fopen(fn.c_str(), "w");
765 if (file != NULL) {
766 fwrite(line.c_str(), line.size(), 1, file);
767 fclose(file);
768 return 0;
769 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000770 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500771 return -1;
772}
773
Dees_Troy6ef66352013-02-21 08:26:57 -0600774bool TWFunc::Install_SuperSU(void) {
775 if (!PartitionManager.Mount_By_Path("/system", true))
776 return false;
777
Ethan Yonkere3e88292014-12-10 16:17:55 -0600778 check_and_run_script("/supersu/install-supersu.sh", "SuperSU");
Dees_Troy6ef66352013-02-21 08:26:57 -0600779 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500780}
Dees_Troy83bd4832013-05-04 12:39:56 +0000781
Dees_Troy83bd4832013-05-04 12:39:56 +0000782bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
783 DIR* d;
784
785 string Filename;
786 Restore_Path += "/";
787 d = opendir(Restore_Path.c_str());
788 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500789 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000790 return false;
791 }
792
793 struct dirent* de;
794 while ((de = readdir(d)) != NULL) {
795 Filename = Restore_Path;
796 Filename += de->d_name;
bigbiffce8f83c2015-12-12 18:30:21 -0500797 if (TWFunc::Get_File_Type(Filename) == ENCRYPTED) {
Dees_Troy83bd4832013-05-04 12:39:56 +0000798 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
799 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
800 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
801 closedir(d);
802 return false;
803 }
804 }
805 }
806 closedir(d);
807 return true;
808}
809
Dees Troyb21cc642013-09-10 17:36:41 +0000810string TWFunc::Get_Current_Date() {
811 string Current_Date;
812 time_t seconds = time(0);
813 struct tm *t = localtime(&seconds);
814 char timestamp[255];
815 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);
816 Current_Date = timestamp;
817 return Current_Date;
818}
819
Ethan Yonkerb5557892014-02-07 21:43:20 -0600820string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000821 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
822 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600823 string propvalue;
824 if (!PartitionManager.Mount_By_Path("/system", true))
825 return propvalue;
Ethan Yonkerb4bff5e2016-12-16 07:47:58 -0600826 string prop_file = "/system/build.prop";
827 if (!TWFunc::Path_Exists(prop_file))
828 prop_file = "/system/system/build.prop"; // for devices with system as a root file system (e.g. Pixel)
829 if (TWFunc::read_file(prop_file, buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -0600830 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200831 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000832 if (!mount_state)
833 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600834 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000835 }
836 int line_count = buildprop.size();
837 int index;
838 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600839 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000840 for (index = 0; index < line_count; index++) {
841 end_pos = buildprop.at(index).find("=", start_pos);
842 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600843 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000844 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600845 if (!mount_state)
846 PartitionManager.UnMount_By_Path("/system", false);
847 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000848 }
849 }
Dees Troyb21cc642013-09-10 17:36:41 +0000850 if (!mount_state)
851 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600852 return propvalue;
853}
854
855void TWFunc::Auto_Generate_Backup_Name() {
856 string propvalue = System_Property_Get("ro.build.display.id");
857 if (propvalue.empty()) {
858 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
859 return;
860 }
861 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500862 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600863 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
864 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
865 // Trailing spaces cause problems on some file systems, so remove them
866 string space_check, space = " ";
867 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
868 while (space_check == space) {
869 Backup_Name.resize(Backup_Name.size() - 1);
870 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
871 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500872 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonkerb5557892014-02-07 21:43:20 -0600873 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600874 if (PartitionManager.Check_Backup_Name(false) != 0) {
875 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
876 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
877 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200878}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100879
880void TWFunc::Fixup_Time_On_Boot()
881{
882#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +0200883
884 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
885
886 struct timeval tv;
887 uint64_t offset = 0;
888 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
889
890 if (TWFunc::read_file(sepoch, offset) == 0) {
891
892 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
893
894 tv.tv_sec = offset;
895 tv.tv_usec = 0;
896 settimeofday(&tv, NULL);
897
898 gettimeofday(&tv, NULL);
899
900 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
901
902 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
903 return;
904
905 }
906
907 } else {
908
909 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
910
911 }
912
Ethan Yonker9132d912015-02-02 10:32:49 -0600913 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200914
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100915 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
916 // They never set it, it just ticks forward from 1970-01-01 00:00,
917 // and then they have files /data/system/time/ats_* with 64bit offset
918 // in miliseconds which, when added to the RTC, gives the correct time.
919 // So, the time is: (offset_from_ats + value_from_RTC)
920 // There are multiple ats files, they are for different systems? Bases?
921 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
922 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
923
924 static const char *paths[] = { "/data/system/time/", "/data/time/" };
925
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100926 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200927 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100928 struct dirent *dt;
929 std::string ats_path;
930
Matt Mowera8a89d12016-12-30 18:10:37 -0600931 if (!PartitionManager.Mount_By_Path("/data", false))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100932 return;
933
934 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
935 // - it is the one for ATS_TOD (time of day?).
936 // However, I never saw a device where the offset differs between ats files.
Matt Mowera8a89d12016-12-30 18:10:37 -0600937 for (size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100938 {
939 DIR *d = opendir(paths[i]);
Matt Mowera8a89d12016-12-30 18:10:37 -0600940 if (!d)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100941 continue;
942
Matt Mowera8a89d12016-12-30 18:10:37 -0600943 while ((dt = readdir(d)))
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100944 {
Matt Mowera8a89d12016-12-30 18:10:37 -0600945 if (dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100946 continue;
947
Matt Mowera8a89d12016-12-30 18:10:37 -0600948 if (ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100949 ats_path = std::string(paths[i]).append(dt->d_name);
950 }
951
952 closedir(d);
953 }
954
Matt Mowera8a89d12016-12-30 18:10:37 -0600955 if (ats_path.empty())
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100956 {
xNUTxe85f02d2014-07-18 01:30:58 +0200957 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100958 return;
959 }
960
961 f = fopen(ats_path.c_str(), "r");
Matt Mowera8a89d12016-12-30 18:10:37 -0600962 if (!f)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100963 {
Dees Troy3e254b92014-03-06 20:24:54 +0000964 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100965 return;
966 }
967
Matt Mowera8a89d12016-12-30 18:10:37 -0600968 if (fread(&offset, sizeof(offset), 1, f) != 1)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100969 {
Dees Troy3e254b92014-03-06 20:24:54 +0000970 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100971 fclose(f);
972 return;
973 }
974 fclose(f);
975
976 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
977
978 gettimeofday(&tv, NULL);
979
980 tv.tv_sec += offset/1000;
981 tv.tv_usec += (offset%1000)*1000;
982
Matt Mowera8a89d12016-12-30 18:10:37 -0600983 while (tv.tv_usec >= 1000000)
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100984 {
985 ++tv.tv_sec;
986 tv.tv_usec -= 1000000;
987 }
988
989 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +0200990
991 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
992
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100993#endif
994}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600995
Vojtech Bocek0b7fe502014-03-13 17:36:52 +0100996std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
997{
998 std::vector<std::string> res;
999 size_t idx = 0, idx_last = 0;
1000
Matt Mowera8a89d12016-12-30 18:10:37 -06001001 while (idx < str.size())
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001002 {
1003 idx = str.find_first_of(delimiter, idx_last);
Matt Mowera8a89d12016-12-30 18:10:37 -06001004 if (idx == std::string::npos)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001005 idx = str.size();
1006
Matt Mowera8a89d12016-12-30 18:10:37 -06001007 if (idx-idx_last != 0 || !removeEmpty)
Vojtech Bocek0b7fe502014-03-13 17:36:52 +01001008 res.push_back(str.substr(idx_last, idx-idx_last));
1009
1010 idx_last = idx + delimiter.size();
1011 }
1012
1013 return res;
1014}
1015
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001016bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
1017{
1018 std::vector<std::string> parts = Split_String(path, "/");
1019 std::string cur_path;
1020 struct stat info;
Matt Mowera8a89d12016-12-30 18:10:37 -06001021 for (size_t i = 0; i < parts.size(); ++i)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001022 {
1023 cur_path += "/" + parts[i];
Matt Mowera8a89d12016-12-30 18:10:37 -06001024 if (stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001025 {
Matt Mowera8a89d12016-12-30 18:10:37 -06001026 if (mkdir(cur_path.c_str(), mode) < 0)
Vojtech Bocek03fd6c52014-03-13 18:46:34 +01001027 return false;
1028 chown(cur_path.c_str(), uid, gid);
1029 }
1030 }
1031 return true;
1032}
1033
xNUTxe85f02d2014-07-18 01:30:58 +02001034int TWFunc::Set_Brightness(std::string brightness_value)
1035{
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001036 int result = -1;
1037 std::string secondary_brightness_file;
xNUTxe85f02d2014-07-18 01:30:58 +02001038
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001039 if (DataManager::GetIntValue("tw_has_brightnesss_file")) {
xNUTxe85f02d2014-07-18 01:30:58 +02001040 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001041 result = TWFunc::write_file(DataManager::GetStrValue("tw_brightness_file"), brightness_value);
1042 DataManager::GetValue("tw_secondary_brightness_file", secondary_brightness_file);
1043 if (!secondary_brightness_file.empty()) {
1044 LOGINFO("TWFunc::Set_Brightness: Setting secondary brightness control to %s\n", brightness_value.c_str());
xNUTxe85f02d2014-07-18 01:30:58 +02001045 TWFunc::write_file(secondary_brightness_file, brightness_value);
1046 }
xNUTxe85f02d2014-07-18 01:30:58 +02001047 }
Tatsuyuki Ishi548a1752015-12-28 10:08:58 +09001048 return result;
xNUTxe85f02d2014-07-18 01:30:58 +02001049}
1050
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001051bool TWFunc::Toggle_MTP(bool enable) {
1052#ifdef TW_HAS_MTP
1053 static int was_enabled = false;
1054
1055 if (enable && was_enabled) {
1056 if (!PartitionManager.Enable_MTP())
1057 PartitionManager.Disable_MTP();
1058 } else {
1059 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1060 PartitionManager.Disable_MTP();
1061 usleep(500);
1062 }
1063 return was_enabled;
1064#else
1065 return false;
1066#endif
1067}
1068
Tom Hite5a926722014-09-15 01:31:03 +00001069void TWFunc::SetPerformanceMode(bool mode) {
1070 if (mode) {
1071 property_set("recovery.perf.mode", "1");
1072 } else {
1073 property_set("recovery.perf.mode", "0");
1074 }
1075 // Some time for events to catch up to init handlers
1076 usleep(500000);
1077}
1078
Jenkins1710bf22014-10-02 20:22:21 -04001079std::string TWFunc::to_string(unsigned long value) {
1080 std::ostringstream os;
1081 os << value;
1082 return os.str();
1083}
1084
Ethan Yonker9132d912015-02-02 10:32:49 -06001085void TWFunc::Disable_Stock_Recovery_Replace(void) {
1086 if (PartitionManager.Mount_By_Path("/system", false)) {
1087 // Disable flashing of stock recovery
1088 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1089 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001090 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 -06001091 sync();
1092 }
1093 PartitionManager.UnMount_By_Path("/system", false);
1094 }
1095}
1096
Ethan Yonker483e9f42016-01-11 22:21:18 -06001097unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1098 unsigned long block_device_size;
1099 int ret = 0;
1100
1101 int fd = open(block_device, O_RDONLY);
1102 if (fd < 0) {
1103 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1104 } else {
1105 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1106 close(fd);
1107 if (ret) {
1108 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1109 } else {
1110 return (unsigned long long)(block_device_size) * 512LLU;
1111 }
1112 }
1113 return 0;
1114}
1115
bigbiff bigbiffbad332a2016-07-29 21:18:13 -04001116void TWFunc::copy_kernel_log(string curr_storage) {
1117 std::string dmesgDst = curr_storage + "/dmesg.log";
1118 std::string dmesgCmd = "/sbin/dmesg";
1119
1120 std::string result;
1121 Exec_Cmd(dmesgCmd, result);
1122 write_file(dmesgDst, result);
1123 gui_msg(Msg("copy_kernel_log=Copied kernel log to {1}")(dmesgDst));
1124 tw_set_default_metadata(dmesgDst.c_str());
1125}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001126#endif // ndef BUILD_TWRPTAR_MAIN