blob: def265ca635798d7b40b14bfed7569295a516efc [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 Yonkeraf2897c2014-02-10 13:07:14 -060041#ifndef BUILD_TWRPTAR_MAIN
Dees_Troyb46a6842012-09-25 11:06:46 -040042#include "data.hpp"
Ethan Yonkeraf2897c2014-02-10 13:07:14 -060043#include "partitions.hpp"
Dees_Troy3477d712012-09-27 15:44:01 -040044#include "variables.h"
Dees_Troy2673cec2013-04-02 20:22:16 +000045#include "bootloader.h"
Tom Hite5a926722014-09-15 01:31:03 +000046#include "cutils/properties.h"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050047#include "cutils/android_reboot.h"
Ethan Yonker74db1572015-10-28 12:44:49 -050048#include "gui/gui.hpp"
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -050049#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
Dees_Troy38bd7602012-09-14 13:33:53 -040054
Dees_Troyb05ddee2013-01-28 20:24:50 +000055extern "C" {
56 #include "libcrecovery/common.h"
Ethan Yonker4b94cfd2014-12-11 10:00:45 -060057 #include "set_metadata.h"
Dees_Troyb05ddee2013-01-28 20:24:50 +000058}
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;
67 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
145bool TWFunc::Path_Exists(string Path) {
146 // Check to see if the Path exists
147 struct stat st;
148 if (stat(Path.c_str(), &st) != 0)
149 return false;
150 else
151 return true;
152}
153
154int TWFunc::Get_File_Type(string fn) {
155 string::size_type i = 0;
156 int firstbyte = 0, secondbyte = 0;
157 char header[3];
158
159 ifstream f;
160 f.open(fn.c_str(), ios::in | ios::binary);
161 f.get(header, 3);
162 f.close();
163 firstbyte = header[i] & 0xff;
164 secondbyte = header[++i] & 0xff;
165
166 if (firstbyte == 0x1f && secondbyte == 0x8b)
167 return 1; // Compressed
168 else if (firstbyte == 0x4f && secondbyte == 0x41)
169 return 2; // Encrypted
170 else
171 return 0; // Unknown
172
173 return 0;
174}
175
176int TWFunc::Try_Decrypting_File(string fn, string password) {
177#ifndef TW_EXCLUDE_ENCRYPTED_BACKUPS
178 OAES_CTX * ctx = NULL;
179 uint8_t _key_data[32] = "";
180 FILE *f;
181 uint8_t buffer[4096];
182 uint8_t *buffer_out = NULL;
183 uint8_t *ptr = NULL;
184 size_t read_len = 0, out_len = 0;
185 int firstbyte = 0, secondbyte = 0, key_len;
186 size_t _j = 0;
187 size_t _key_data_len = 0;
188
189 // mostly kanged from OpenAES oaes.c
190 for( _j = 0; _j < 32; _j++ )
191 _key_data[_j] = _j + 1;
192 _key_data_len = password.size();
193 if( 16 >= _key_data_len )
194 _key_data_len = 16;
195 else if( 24 >= _key_data_len )
196 _key_data_len = 24;
197 else
198 _key_data_len = 32;
199 memcpy(_key_data, password.c_str(), password.size());
200
201 ctx = oaes_alloc();
202 if (ctx == NULL) {
203 LOGERR("Failed to allocate OAES\n");
204 return -1;
205 }
206
207 oaes_key_import_data(ctx, _key_data, _key_data_len);
208
209 f = fopen(fn.c_str(), "rb");
210 if (f == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500211 LOGERR("Failed to open '%s' to try decrypt: %s\n", fn.c_str(), strerror(errno));
Matt Mower13a8f0b2015-09-26 15:40:03 -0500212 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600213 return -1;
214 }
215 read_len = fread(buffer, sizeof(uint8_t), 4096, f);
216 if (read_len <= 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500217 LOGERR("Read size during try decrypt failed: %s\n", strerror(errno));
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600218 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500219 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600220 return -1;
221 }
222 if (oaes_decrypt(ctx, buffer, read_len, NULL, &out_len) != OAES_RET_SUCCESS) {
223 LOGERR("Error: Failed to retrieve required buffer size for trying decryption.\n");
224 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500225 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600226 return -1;
227 }
228 buffer_out = (uint8_t *) calloc(out_len, sizeof(char));
229 if (buffer_out == NULL) {
230 LOGERR("Failed to allocate output buffer for try decrypt.\n");
231 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500232 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600233 return -1;
234 }
235 if (oaes_decrypt(ctx, buffer, read_len, buffer_out, &out_len) != OAES_RET_SUCCESS) {
236 LOGERR("Failed to decrypt file '%s'\n", fn.c_str());
237 fclose(f);
238 free(buffer_out);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500239 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600240 return 0;
241 }
242 fclose(f);
Matt Mower13a8f0b2015-09-26 15:40:03 -0500243 oaes_free(&ctx);
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600244 if (out_len < 2) {
Ethan Yonkerd0514ba2015-10-22 14:17:47 -0500245 LOGINFO("Successfully decrypted '%s' but read length too small.\n", fn.c_str());
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600246 free(buffer_out);
247 return 1; // Decrypted successfully
248 }
249 ptr = buffer_out;
250 firstbyte = *ptr & 0xff;
251 ptr++;
252 secondbyte = *ptr & 0xff;
253 if (firstbyte == 0x1f && secondbyte == 0x8b) {
254 LOGINFO("Successfully decrypted '%s' and file is compressed.\n", fn.c_str());
255 free(buffer_out);
256 return 3; // Compressed
257 }
258 if (out_len >= 262) {
259 ptr = buffer_out + 257;
260 if (strncmp((char*)ptr, "ustar", 5) == 0) {
261 LOGINFO("Successfully decrypted '%s' and file is tar format.\n", fn.c_str());
262 free(buffer_out);
263 return 2; // Tar
264 }
265 }
266 free(buffer_out);
267 LOGINFO("No errors decrypting '%s' but no known file format.\n", fn.c_str());
268 return 1; // Decrypted successfully
269#else
270 LOGERR("Encrypted backup support not included.\n");
271 return -1;
272#endif
273}
274
275unsigned long TWFunc::Get_File_Size(string Path) {
276 struct stat st;
277
278 if (stat(Path.c_str(), &st) != 0)
279 return 0;
280 return st.st_size;
281}
282
Vojtech Bocek05f87d62014-03-11 22:08:23 +0100283std::string TWFunc::Remove_Trailing_Slashes(const std::string& path, bool leaveLast)
284{
285 std::string res;
286 size_t last_idx = 0, idx = 0;
287
288 while(last_idx != std::string::npos)
289 {
290 if(last_idx != 0)
291 res += '/';
292
293 idx = path.find_first_of('/', last_idx);
294 if(idx == std::string::npos) {
295 res += path.substr(last_idx, idx);
296 break;
297 }
298
299 res += path.substr(last_idx, idx-last_idx);
300 last_idx = path.find_first_not_of('/', idx);
301 }
302
303 if(leaveLast)
304 res += '/';
305 return res;
306}
307
Ethan Yonker1b7a31b2014-07-03 15:09:22 -0500308vector<string> TWFunc::split_string(const string &in, char del, bool skip_empty) {
309 vector<string> res;
310
311 if (in.empty() || del == '\0')
312 return res;
313
314 string field;
315 istringstream f(in);
316 if (del == '\n') {
317 while(getline(f, field)) {
318 if (field.empty() && skip_empty)
319 continue;
320 res.push_back(field);
321 }
322 } else {
323 while(getline(f, field, del)) {
324 if (field.empty() && skip_empty)
325 continue;
326 res.push_back(field);
327 }
328 }
329 return res;
330}
331
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600332#ifndef BUILD_TWRPTAR_MAIN
333
Dees_Troy38bd7602012-09-14 13:33:53 -0400334// Returns "/path" from a full /path/to/file.name
335string TWFunc::Get_Root_Path(string Path) {
336 string Local_Path = Path;
337
338 // Make sure that we have a leading slash
339 if (Local_Path.substr(0, 1) != "/")
340 Local_Path = "/" + Local_Path;
341
342 // Trim the path to get the root path only
343 size_t position = Local_Path.find("/", 2);
344 if (position != string::npos) {
345 Local_Path.resize(position);
346 }
347 return Local_Path;
348}
349
350void TWFunc::install_htc_dumlock(void) {
Dees_Troy38bd7602012-09-14 13:33:53 -0400351 int need_libs = 0;
352
353 if (!PartitionManager.Mount_By_Path("/system", true))
354 return;
355
356 if (!PartitionManager.Mount_By_Path("/data", true))
357 return;
358
Ethan Yonker74db1572015-10-28 12:44:49 -0500359 gui_msg("install_dumlock=Installing HTC Dumlock to system...");
Dees Troy3454ade2015-01-20 19:21:04 +0000360 copy_file(TWHTCD_PATH "htcdumlocksys", "/system/bin/htcdumlock", 0755);
Dees_Troy8170a922012-09-18 15:40:25 -0400361 if (!Path_Exists("/system/bin/flash_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500362 LOGINFO("Installing flash_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000363 copy_file(TWHTCD_PATH "flash_imagesys", "/system/bin/flash_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400364 need_libs = 1;
365 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500366 LOGINFO("flash_image is already installed, skipping...\n");
Dees_Troy8170a922012-09-18 15:40:25 -0400367 if (!Path_Exists("/system/bin/dump_image")) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500368 LOGINFO("Installing dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000369 copy_file(TWHTCD_PATH "dump_imagesys", "/system/bin/dump_image", 0755);
Dees_Troy38bd7602012-09-14 13:33:53 -0400370 need_libs = 1;
371 } else
Ethan Yonker74db1572015-10-28 12:44:49 -0500372 LOGINFO("dump_image is already installed, skipping...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400373 if (need_libs) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500374 LOGINFO("Installing libs needed for flash_image and dump_image...\n");
Dees Troy3454ade2015-01-20 19:21:04 +0000375 copy_file(TWHTCD_PATH "libbmlutils.so", "/system/lib/libbmlutils.so", 0644);
376 copy_file(TWHTCD_PATH "libflashutils.so", "/system/lib/libflashutils.so", 0644);
377 copy_file(TWHTCD_PATH "libmmcutils.so", "/system/lib/libmmcutils.so", 0644);
378 copy_file(TWHTCD_PATH "libmtdutils.so", "/system/lib/libmtdutils.so", 0644);
Dees_Troy38bd7602012-09-14 13:33:53 -0400379 }
Ethan Yonker74db1572015-10-28 12:44:49 -0500380 LOGINFO("Installing HTC Dumlock app...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400381 mkdir("/data/app", 0777);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500382 unlink("/data/app/com.teamwin.htcdumlock*");
Dees Troy3454ade2015-01-20 19:21:04 +0000383 copy_file(TWHTCD_PATH "HTCDumlock.apk", "/data/app/com.teamwin.htcdumlock.apk", 0777);
Dees_Troy38bd7602012-09-14 13:33:53 -0400384 sync();
Ethan Yonker74db1572015-10-28 12:44:49 -0500385 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400386}
387
388void TWFunc::htc_dumlock_restore_original_boot(void) {
389 if (!PartitionManager.Mount_By_Path("/sdcard", true))
390 return;
391
Ethan Yonker74db1572015-10-28 12:44:49 -0500392 gui_msg("dumlock_restore=Restoring original boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200393 Exec_Cmd("htcdumlock restore");
Ethan Yonker74db1572015-10-28 12:44:49 -0500394 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400395}
396
397void TWFunc::htc_dumlock_reflash_recovery_to_boot(void) {
398 if (!PartitionManager.Mount_By_Path("/sdcard", true))
399 return;
Ethan Yonker74db1572015-10-28 12:44:49 -0500400 gui_msg("dumlock_reflash=Reflashing recovery to boot...");
Vojtech Bocek05534202013-09-11 08:11:56 +0200401 Exec_Cmd("htcdumlock recovery noreboot");
Ethan Yonker74db1572015-10-28 12:44:49 -0500402 gui_msg("done=Done.");
Dees_Troy38bd7602012-09-14 13:33:53 -0400403}
Dees_Troy43d8b002012-09-17 16:00:01 -0400404
405int TWFunc::Recursive_Mkdir(string Path) {
thatf1408b32016-01-03 11:09:15 +0100406 std::vector<std::string> parts = Split_String(Path, "/", true);
407 std::string cur_path;
408 for (size_t i = 0; i < parts.size(); ++i) {
409 cur_path += "/" + parts[i];
410 if (!TWFunc::Path_Exists(cur_path)) {
411 if (mkdir(cur_path.c_str(), 0777)) {
412 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 -0600413 return false;
414 } else {
thatf1408b32016-01-03 11:09:15 +0100415 tw_set_default_metadata(cur_path.c_str());
Ethan Yonker4b94cfd2014-12-11 10:00:45 -0600416 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400417 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400418 }
Dees_Troy43d8b002012-09-17 16:00:01 -0400419 return true;
420}
421
Dees_Troyb46a6842012-09-25 11:06:46 -0400422void TWFunc::GUI_Operation_Text(string Read_Value, string Default_Text) {
423 string Display_Text;
424
425 DataManager::GetValue(Read_Value, Display_Text);
426 if (Display_Text.empty())
427 Display_Text = Default_Text;
428
429 DataManager::SetValue("tw_operation", Display_Text);
430 DataManager::SetValue("tw_partition", "");
431}
432
433void TWFunc::GUI_Operation_Text(string Read_Value, string Partition_Name, string Default_Text) {
434 string Display_Text;
435
436 DataManager::GetValue(Read_Value, Display_Text);
437 if (Display_Text.empty())
438 Display_Text = Default_Text;
439
440 DataManager::SetValue("tw_operation", Display_Text);
441 DataManager::SetValue("tw_partition", Partition_Name);
Dees_Troy7c2dec82012-09-26 09:49:14 -0400442}
443
Dees_Troy2673cec2013-04-02 20:22:16 +0000444void TWFunc::Copy_Log(string Source, string Destination) {
Dees Troy9d7fdf52013-09-19 20:49:25 +0000445 PartitionManager.Mount_By_Path(Destination, false);
Dees_Troy2673cec2013-04-02 20:22:16 +0000446 FILE *destination_log = fopen(Destination.c_str(), "a");
447 if (destination_log == NULL) {
448 LOGERR("TWFunc::Copy_Log -- Can't open destination log file: '%s'\n", Destination.c_str());
Dees_Troy6ef66352013-02-21 08:26:57 -0600449 } else {
Dees_Troy2673cec2013-04-02 20:22:16 +0000450 FILE *source_log = fopen(Source.c_str(), "r");
451 if (source_log != NULL) {
452 fseek(source_log, Log_Offset, SEEK_SET);
453 char buffer[4096];
454 while (fgets(buffer, sizeof(buffer), source_log))
455 fputs(buffer, destination_log); // Buffered write of log file
456 Log_Offset = ftell(source_log);
457 fflush(source_log);
458 fclose(source_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600459 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000460 fflush(destination_log);
461 fclose(destination_log);
Dees_Troy6ef66352013-02-21 08:26:57 -0600462 }
Dees_Troya58bead2012-09-27 09:49:29 -0400463}
464
Dees_Troy2673cec2013-04-02 20:22:16 +0000465void TWFunc::Update_Log_File(void) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500466 // Copy logs to cache so the system can find out what happened.
Dees Troy9d7fdf52013-09-19 20:49:25 +0000467 if (PartitionManager.Mount_By_Path("/cache", false)) {
468 if (!TWFunc::Path_Exists("/cache/recovery/.")) {
469 LOGINFO("Recreating /cache/recovery folder.\n");
470 if (mkdir("/cache/recovery", S_IRWXU | S_IRWXG | S_IWGRP | S_IXGRP) != 0)
471 LOGINFO("Unable to create /cache/recovery folder.\n");
472 }
473 Copy_Log(TMP_LOG_FILE, "/cache/recovery/log");
474 copy_file("/cache/recovery/log", "/cache/recovery/last_log", 600);
475 chown("/cache/recovery/log", 1000, 1000);
476 chmod("/cache/recovery/log", 0600);
477 chmod("/cache/recovery/last_log", 0640);
478 } else {
479 LOGINFO("Failed to mount /cache for TWFunc::Update_Log_File\n");
480 }
Dees_Troya58bead2012-09-27 09:49:29 -0400481
Dees_Troy2673cec2013-04-02 20:22:16 +0000482 // Reset bootloader message
483 TWPartition* Part = PartitionManager.Find_Partition_By_Path("/misc");
484 if (Part != NULL) {
485 struct bootloader_message boot;
486 memset(&boot, 0, sizeof(boot));
that4e0e3fc2015-04-13 19:52:49 +0200487 if (set_bootloader_message(&boot) != 0)
488 LOGERR("Unable to set bootloader message.\n");
Dees_Troy2673cec2013-04-02 20:22:16 +0000489 }
Dees_Troya58bead2012-09-27 09:49:29 -0400490
Dees Troy9d7fdf52013-09-19 20:49:25 +0000491 if (PartitionManager.Mount_By_Path("/cache", true)) {
492 if (unlink("/cache/recovery/command") && errno != ENOENT) {
493 LOGINFO("Can't unlink %s\n", "/cache/recovery/command");
494 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500495 }
Dees_Troya58bead2012-09-27 09:49:29 -0400496
Dees_Troy2673cec2013-04-02 20:22:16 +0000497 sync();
498}
499
500void TWFunc::Update_Intent_File(string Intent) {
501 if (PartitionManager.Mount_By_Path("/cache", false) && !Intent.empty()) {
502 TWFunc::write_file("/cache/recovery/intent", Intent);
503 }
Dees_Troya58bead2012-09-27 09:49:29 -0400504}
505
506// reboot: Reboot the system. Return -1 on error, no return on success
507int TWFunc::tw_reboot(RebootCommand command)
508{
509 // Always force a sync before we reboot
Dees_Troy6ef66352013-02-21 08:26:57 -0600510 sync();
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500511 Update_Log_File();
Dees_Troya58bead2012-09-27 09:49:29 -0400512
Dees_Troy2673cec2013-04-02 20:22:16 +0000513 switch (command) {
514 case rb_current:
515 case rb_system:
Dees_Troy2673cec2013-04-02 20:22:16 +0000516 Update_Intent_File("s");
517 sync();
518 check_and_run_script("/sbin/rebootsystem.sh", "reboot system");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500519#ifdef ANDROID_RB_PROPERTY
520 return property_set(ANDROID_RB_PROPERTY, "reboot,");
521#elif defined(ANDROID_RB_RESTART)
522 return android_reboot(ANDROID_RB_RESTART, 0, 0);
523#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000524 return reboot(RB_AUTOBOOT);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500525#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000526 case rb_recovery:
527 check_and_run_script("/sbin/rebootrecovery.sh", "reboot recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600528#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500529 return property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600530#else
531 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "recovery");
532#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000533 case rb_bootloader:
534 check_and_run_script("/sbin/rebootbootloader.sh", "reboot bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600535#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500536 return property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600537#else
538 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "bootloader");
539#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000540 case rb_poweroff:
541 check_and_run_script("/sbin/poweroff.sh", "power off");
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500542#ifdef ANDROID_RB_PROPERTY
543 return property_set(ANDROID_RB_PROPERTY, "shutdown,");
544#elif defined(ANDROID_RB_POWEROFF)
545 return android_reboot(ANDROID_RB_POWEROFF, 0, 0);
546#else
Dees_Troy2673cec2013-04-02 20:22:16 +0000547 return reboot(RB_POWER_OFF);
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500548#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000549 case rb_download:
550 check_and_run_script("/sbin/rebootdownload.sh", "reboot download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600551#ifdef ANDROID_RB_PROPERTY
Ethan Yonkerbc2bc6b2015-03-24 21:37:52 -0500552 return property_set(ANDROID_RB_PROPERTY, "reboot,download");
Ethan Yonker75bf0412014-11-21 13:54:27 -0600553#else
554 return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, (void*) "download");
555#endif
Dees_Troy2673cec2013-04-02 20:22:16 +0000556 default:
557 return -1;
Dees_Troy6ef66352013-02-21 08:26:57 -0600558 }
559 return -1;
Dees_Troya58bead2012-09-27 09:49:29 -0400560}
561
562void TWFunc::check_and_run_script(const char* script_file, const char* display_name)
563{
564 // Check for and run startup script if script exists
565 struct stat st;
566 if (stat(script_file, &st) == 0) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500567 gui_msg(Msg("run_script=Running {1} script...")(display_name));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500568 chmod(script_file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
Vojtech Bocek05534202013-09-11 08:11:56 +0200569 TWFunc::Exec_Cmd(script_file);
Ethan Yonker74db1572015-10-28 12:44:49 -0500570 gui_msg("done=Done.");
Dees_Troya58bead2012-09-27 09:49:29 -0400571 }
Dees_Troy3477d712012-09-27 15:44:01 -0400572}
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500573
574int TWFunc::removeDir(const string path, bool skipParent) {
Dees_Troyce675462013-01-09 19:48:21 +0000575 DIR *d = opendir(path.c_str());
576 int r = 0;
577 string new_path;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500578
Dees_Troyce675462013-01-09 19:48:21 +0000579 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500580 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(path)(strerror(errno)));
Dees_Troyce675462013-01-09 19:48:21 +0000581 return -1;
582 }
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500583
Dees_Troyce675462013-01-09 19:48:21 +0000584 if (d) {
585 struct dirent *p;
586 while (!r && (p = readdir(d))) {
Dees_Troyce675462013-01-09 19:48:21 +0000587 if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
588 continue;
589 new_path = path + "/";
590 new_path.append(p->d_name);
591 if (p->d_type == DT_DIR) {
592 r = removeDir(new_path, true);
593 if (!r) {
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500594 if (p->d_type == DT_DIR)
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500595 r = rmdir(new_path.c_str());
596 else
Dees_Troy2673cec2013-04-02 20:22:16 +0000597 LOGINFO("Unable to removeDir '%s': %s\n", new_path.c_str(), strerror(errno));
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500598 }
bigbiff bigbiff98f1f902013-01-19 18:46:13 -0500599 } 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 +0000600 r = unlink(new_path.c_str());
Dees_Troye34c1332013-02-06 19:13:00 +0000601 if (r != 0) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000602 LOGINFO("Unable to unlink '%s: %s'\n", new_path.c_str(), strerror(errno));
Dees_Troye34c1332013-02-06 19:13:00 +0000603 }
Dees_Troyce675462013-01-09 19:48:21 +0000604 }
605 }
606 closedir(d);
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500607
Matt Mowerfb1c4ff2014-04-16 13:43:36 -0500608 if (!r) {
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500609 if (skipParent)
610 return 0;
611 else
612 r = rmdir(path.c_str());
613 }
Dees_Troyce675462013-01-09 19:48:21 +0000614 }
615 return r;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500616}
617
618int TWFunc::copy_file(string src, string dst, int mode) {
Dees_Troy2673cec2013-04-02 20:22:16 +0000619 LOGINFO("Copying file %s to %s\n", src.c_str(), dst.c_str());
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500620 ifstream srcfile(src.c_str(), ios::binary);
621 ofstream dstfile(dst.c_str(), ios::binary);
622 dstfile << srcfile.rdbuf();
623 srcfile.close();
624 dstfile.close();
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500625 if (chmod(dst.c_str(), mode) != 0)
626 return -1;
bigbiff bigbiff9c754052013-01-09 09:09:08 -0500627 return 0;
628}
Dees_Troy3ee47bc2013-01-25 21:47:37 +0000629
630unsigned int TWFunc::Get_D_Type_From_Stat(string Path) {
631 struct stat st;
632
633 stat(Path.c_str(), &st);
634 if (st.st_mode & S_IFDIR)
635 return DT_DIR;
636 else if (st.st_mode & S_IFBLK)
637 return DT_BLK;
638 else if (st.st_mode & S_IFCHR)
639 return DT_CHR;
640 else if (st.st_mode & S_IFIFO)
641 return DT_FIFO;
642 else if (st.st_mode & S_IFLNK)
643 return DT_LNK;
644 else if (st.st_mode & S_IFREG)
645 return DT_REG;
646 else if (st.st_mode & S_IFSOCK)
647 return DT_SOCK;
648 return DT_UNKNOWN;
Dees_Troye34c1332013-02-06 19:13:00 +0000649}
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500650
651int TWFunc::read_file(string fn, string& results) {
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200652 ifstream file;
653 file.open(fn.c_str(), ios::in);
654
655 if (file.is_open()) {
656 file >> results;
657 file.close();
658 return 0;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500659 }
Vojtech Bocekfafb0c52013-07-25 22:53:02 +0200660
661 LOGINFO("Cannot find file %s\n", fn.c_str());
662 return -1;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500663}
664
665int TWFunc::read_file(string fn, vector<string>& results) {
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500666 ifstream file;
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500667 string line;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500668 file.open(fn.c_str(), ios::in);
669 if (file.is_open()) {
bigbiff bigbiffcdcfee42013-02-27 21:11:26 -0500670 while (getline(file, line))
671 results.push_back(line);
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500672 file.close();
673 return 0;
674 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000675 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500676 return -1;
677}
678
xNUTxe85f02d2014-07-18 01:30:58 +0200679int TWFunc::read_file(string fn, uint64_t& results) {
680 ifstream file;
681 file.open(fn.c_str(), ios::in);
682
683 if (file.is_open()) {
684 file >> results;
685 file.close();
686 return 0;
687 }
688
689 LOGINFO("Cannot find file %s\n", fn.c_str());
690 return -1;
691}
692
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500693int TWFunc::write_file(string fn, string& line) {
694 FILE *file;
695 file = fopen(fn.c_str(), "w");
696 if (file != NULL) {
697 fwrite(line.c_str(), line.size(), 1, file);
698 fclose(file);
699 return 0;
700 }
Dees_Troy2673cec2013-04-02 20:22:16 +0000701 LOGINFO("Cannot find file %s\n", fn.c_str());
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500702 return -1;
703}
704
705timespec TWFunc::timespec_diff(timespec& start, timespec& end)
706{
Dees_Troy6ef66352013-02-21 08:26:57 -0600707 timespec temp;
708 if ((end.tv_nsec-start.tv_nsec)<0) {
709 temp.tv_sec = end.tv_sec-start.tv_sec-1;
710 temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
711 } else {
712 temp.tv_sec = end.tv_sec-start.tv_sec;
713 temp.tv_nsec = end.tv_nsec-start.tv_nsec;
714 }
715 return temp;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500716}
717
Vojtech Boceke5ffcd12014-02-06 21:17:32 +0100718int32_t TWFunc::timespec_diff_ms(timespec& start, timespec& end)
719{
720 return ((end.tv_sec * 1000) + end.tv_nsec/1000000) -
721 ((start.tv_sec * 1000) + start.tv_nsec/1000000);
722}
723
Dees_Troy6ef66352013-02-21 08:26:57 -0600724bool TWFunc::Install_SuperSU(void) {
725 if (!PartitionManager.Mount_By_Path("/system", true))
726 return false;
727
Ethan Yonkere3e88292014-12-10 16:17:55 -0600728 check_and_run_script("/supersu/install-supersu.sh", "SuperSU");
Dees_Troy6ef66352013-02-21 08:26:57 -0600729 return true;
bigbiff bigbiff8a68c312013-02-10 14:28:30 -0500730}
Dees_Troy83bd4832013-05-04 12:39:56 +0000731
Dees_Troy83bd4832013-05-04 12:39:56 +0000732bool TWFunc::Try_Decrypting_Backup(string Restore_Path, string Password) {
733 DIR* d;
734
735 string Filename;
736 Restore_Path += "/";
737 d = opendir(Restore_Path.c_str());
738 if (d == NULL) {
Ethan Yonker74db1572015-10-28 12:44:49 -0500739 gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(Restore_Path)(strerror(errno)));
Dees_Troy83bd4832013-05-04 12:39:56 +0000740 return false;
741 }
742
743 struct dirent* de;
744 while ((de = readdir(d)) != NULL) {
745 Filename = Restore_Path;
746 Filename += de->d_name;
747 if (TWFunc::Get_File_Type(Filename) == 2) {
748 if (TWFunc::Try_Decrypting_File(Filename, Password) < 2) {
749 DataManager::SetValue("tw_restore_password", ""); // Clear the bad password
750 DataManager::SetValue("tw_restore_display", ""); // Also clear the display mask
751 closedir(d);
752 return false;
753 }
754 }
755 }
756 closedir(d);
757 return true;
758}
759
Dees Troyb21cc642013-09-10 17:36:41 +0000760string TWFunc::Get_Current_Date() {
761 string Current_Date;
762 time_t seconds = time(0);
763 struct tm *t = localtime(&seconds);
764 char timestamp[255];
765 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);
766 Current_Date = timestamp;
767 return Current_Date;
768}
769
Ethan Yonkerb5557892014-02-07 21:43:20 -0600770string TWFunc::System_Property_Get(string Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000771 bool mount_state = PartitionManager.Is_Mounted_By_Path("/system");
772 std::vector<string> buildprop;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600773 string propvalue;
774 if (!PartitionManager.Mount_By_Path("/system", true))
775 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000776 if (TWFunc::read_file("/system/build.prop", buildprop) != 0) {
Ethan Yonkerb5557892014-02-07 21:43:20 -0600777 LOGINFO("Unable to open /system/build.prop for getting '%s'.\n", Prop_Name.c_str());
Vojtech Boceka2e70162013-09-17 17:05:10 +0200778 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
Dees Troyb21cc642013-09-10 17:36:41 +0000779 if (!mount_state)
780 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600781 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000782 }
783 int line_count = buildprop.size();
784 int index;
785 size_t start_pos = 0, end_pos;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600786 string propname;
Dees Troyb21cc642013-09-10 17:36:41 +0000787 for (index = 0; index < line_count; index++) {
788 end_pos = buildprop.at(index).find("=", start_pos);
789 propname = buildprop.at(index).substr(start_pos, end_pos);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600790 if (propname == Prop_Name) {
Dees Troyb21cc642013-09-10 17:36:41 +0000791 propvalue = buildprop.at(index).substr(end_pos + 1, buildprop.at(index).size());
Ethan Yonkerb5557892014-02-07 21:43:20 -0600792 if (!mount_state)
793 PartitionManager.UnMount_By_Path("/system", false);
794 return propvalue;
Dees Troyb21cc642013-09-10 17:36:41 +0000795 }
796 }
Dees Troyb21cc642013-09-10 17:36:41 +0000797 if (!mount_state)
798 PartitionManager.UnMount_By_Path("/system", false);
Ethan Yonkerb5557892014-02-07 21:43:20 -0600799 return propvalue;
800}
801
802void TWFunc::Auto_Generate_Backup_Name() {
803 string propvalue = System_Property_Get("ro.build.display.id");
804 if (propvalue.empty()) {
805 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
806 return;
807 }
808 string Backup_Name = Get_Current_Date();
bigbiff74a6d0d2015-02-14 20:49:44 -0500809 Backup_Name += "_" + propvalue;
Ethan Yonkerb5557892014-02-07 21:43:20 -0600810 if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
811 Backup_Name.resize(MAX_BACKUP_NAME_LEN);
812 // Trailing spaces cause problems on some file systems, so remove them
813 string space_check, space = " ";
814 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
815 while (space_check == space) {
816 Backup_Name.resize(Backup_Name.size() - 1);
817 space_check = Backup_Name.substr(Backup_Name.size() - 1, 1);
818 }
bigbiff74a6d0d2015-02-14 20:49:44 -0500819 replace(Backup_Name.begin(), Backup_Name.end(), ' ', '_');
Ethan Yonkerb5557892014-02-07 21:43:20 -0600820 DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
Ethan Yonker92d48e02014-02-26 12:05:55 -0600821 if (PartitionManager.Check_Backup_Name(false) != 0) {
822 LOGINFO("Auto generated backup name '%s' contains invalid characters, using date instead.\n", Backup_Name.c_str());
823 DataManager::SetValue(TW_BACKUP_NAME, Get_Current_Date());
824 }
Vojtech Bocek05534202013-09-11 08:11:56 +0200825}
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100826
827void TWFunc::Fixup_Time_On_Boot()
828{
829#ifdef QCOM_RTC_FIX
xNUTxe85f02d2014-07-18 01:30:58 +0200830
831 LOGINFO("TWFunc::Fixup_Time: Pre-fix date and time: %s\n", TWFunc::Get_Current_Date().c_str());
832
833 struct timeval tv;
834 uint64_t offset = 0;
835 std::string sepoch = "/sys/class/rtc/rtc0/since_epoch";
836
837 if (TWFunc::read_file(sepoch, offset) == 0) {
838
839 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s\n", sepoch.c_str());
840
841 tv.tv_sec = offset;
842 tv.tv_usec = 0;
843 settimeofday(&tv, NULL);
844
845 gettimeofday(&tv, NULL);
846
847 if (tv.tv_sec > 1405209403) { // Anything older then 12 Jul 2014 23:56:43 GMT will do nicely thank you ;)
848
849 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
850 return;
851
852 }
853
854 } else {
855
856 LOGINFO("TWFunc::Fixup_Time: opening %s failed\n", sepoch.c_str());
857
858 }
859
Ethan Yonker9132d912015-02-02 10:32:49 -0600860 LOGINFO("TWFunc::Fixup_Time: will attempt to use the ats files now.\n");
xNUTxe85f02d2014-07-18 01:30:58 +0200861
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100862 // Devices with Qualcomm Snapdragon 800 do some shenanigans with RTC.
863 // They never set it, it just ticks forward from 1970-01-01 00:00,
864 // and then they have files /data/system/time/ats_* with 64bit offset
865 // in miliseconds which, when added to the RTC, gives the correct time.
866 // So, the time is: (offset_from_ats + value_from_RTC)
867 // There are multiple ats files, they are for different systems? Bases?
868 // Like, ats_1 is for modem and ats_2 is for TOD (time of day?).
869 // Look at file time_genoff.h in CodeAurora, qcom-opensource/time-services
870
871 static const char *paths[] = { "/data/system/time/", "/data/time/" };
872
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100873 FILE *f;
xNUTxe85f02d2014-07-18 01:30:58 +0200874 DIR *d;
875 offset = 0;
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100876 struct dirent *dt;
877 std::string ats_path;
878
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100879 if(!PartitionManager.Mount_By_Path("/data", false))
880 return;
881
882 // Prefer ats_2, it seems to be the one we want according to logcat on hammerhead
883 // - it is the one for ATS_TOD (time of day?).
884 // However, I never saw a device where the offset differs between ats files.
885 for(size_t i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i)
886 {
887 DIR *d = opendir(paths[i]);
888 if(!d)
889 continue;
890
891 while((dt = readdir(d)))
892 {
893 if(dt->d_type != DT_REG || strncmp(dt->d_name, "ats_", 4) != 0)
894 continue;
895
896 if(ats_path.empty() || strcmp(dt->d_name, "ats_2") == 0)
897 ats_path = std::string(paths[i]).append(dt->d_name);
898 }
899
900 closedir(d);
901 }
902
903 if(ats_path.empty())
904 {
xNUTxe85f02d2014-07-18 01:30:58 +0200905 LOGINFO("TWFunc::Fixup_Time: no ats files found, leaving untouched!\n");
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100906 return;
907 }
908
909 f = fopen(ats_path.c_str(), "r");
910 if(!f)
911 {
Dees Troy3e254b92014-03-06 20:24:54 +0000912 LOGINFO("TWFunc::Fixup_Time: failed to open file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100913 return;
914 }
915
916 if(fread(&offset, sizeof(offset), 1, f) != 1)
917 {
Dees Troy3e254b92014-03-06 20:24:54 +0000918 LOGINFO("TWFunc::Fixup_Time: failed load uint64 from file %s\n", ats_path.c_str());
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100919 fclose(f);
920 return;
921 }
922 fclose(f);
923
924 LOGINFO("TWFunc::Fixup_Time: Setting time offset from file %s, offset %llu\n", ats_path.c_str(), offset);
925
926 gettimeofday(&tv, NULL);
927
928 tv.tv_sec += offset/1000;
929 tv.tv_usec += (offset%1000)*1000;
930
931 while(tv.tv_usec >= 1000000)
932 {
933 ++tv.tv_sec;
934 tv.tv_usec -= 1000000;
935 }
936
937 settimeofday(&tv, NULL);
xNUTxe85f02d2014-07-18 01:30:58 +0200938
939 LOGINFO("TWFunc::Fixup_Time: Date and time corrected: %s\n", TWFunc::Get_Current_Date().c_str());
940
Vojtech Bocekd0e38bc2014-02-03 23:36:57 +0100941#endif
942}
Ethan Yonkeraf2897c2014-02-10 13:07:14 -0600943
Vojtech Bocek0b7fe502014-03-13 17:36:52 +0100944std::vector<std::string> TWFunc::Split_String(const std::string& str, const std::string& delimiter, bool removeEmpty)
945{
946 std::vector<std::string> res;
947 size_t idx = 0, idx_last = 0;
948
949 while(idx < str.size())
950 {
951 idx = str.find_first_of(delimiter, idx_last);
952 if(idx == std::string::npos)
953 idx = str.size();
954
955 if(idx-idx_last != 0 || !removeEmpty)
956 res.push_back(str.substr(idx_last, idx-idx_last));
957
958 idx_last = idx + delimiter.size();
959 }
960
961 return res;
962}
963
Vojtech Bocek03fd6c52014-03-13 18:46:34 +0100964bool TWFunc::Create_Dir_Recursive(const std::string& path, mode_t mode, uid_t uid, gid_t gid)
965{
966 std::vector<std::string> parts = Split_String(path, "/");
967 std::string cur_path;
968 struct stat info;
969 for(size_t i = 0; i < parts.size(); ++i)
970 {
971 cur_path += "/" + parts[i];
972 if(stat(cur_path.c_str(), &info) < 0 || !S_ISDIR(info.st_mode))
973 {
974 if(mkdir(cur_path.c_str(), mode) < 0)
975 return false;
976 chown(cur_path.c_str(), uid, gid);
977 }
978 }
979 return true;
980}
981
xNUTxe85f02d2014-07-18 01:30:58 +0200982int TWFunc::Set_Brightness(std::string brightness_value)
983{
984
985 std::string brightness_file = DataManager::GetStrValue("tw_brightness_file");;
986
987 if (brightness_file.compare("/nobrightness") != 0) {
988 std::string secondary_brightness_file = DataManager::GetStrValue("tw_secondary_brightness_file");
989 LOGINFO("TWFunc::Set_Brightness: Setting brightness control to %s\n", brightness_value.c_str());
990 int result = TWFunc::write_file(brightness_file, brightness_value);
991 if (secondary_brightness_file != "") {
992 LOGINFO("TWFunc::Set_Brightness: Setting SECONDARY brightness control to %s\n", brightness_value.c_str());
993 TWFunc::write_file(secondary_brightness_file, brightness_value);
994 }
995 return result;
996 }
997 return -1;
998}
999
bigbiff bigbiffc7eee6f2014-09-02 18:59:01 -04001000bool TWFunc::Toggle_MTP(bool enable) {
1001#ifdef TW_HAS_MTP
1002 static int was_enabled = false;
1003
1004 if (enable && was_enabled) {
1005 if (!PartitionManager.Enable_MTP())
1006 PartitionManager.Disable_MTP();
1007 } else {
1008 was_enabled = DataManager::GetIntValue("tw_mtp_enabled");
1009 PartitionManager.Disable_MTP();
1010 usleep(500);
1011 }
1012 return was_enabled;
1013#else
1014 return false;
1015#endif
1016}
1017
Tom Hite5a926722014-09-15 01:31:03 +00001018void TWFunc::SetPerformanceMode(bool mode) {
1019 if (mode) {
1020 property_set("recovery.perf.mode", "1");
1021 } else {
1022 property_set("recovery.perf.mode", "0");
1023 }
1024 // Some time for events to catch up to init handlers
1025 usleep(500000);
1026}
1027
Jenkins1710bf22014-10-02 20:22:21 -04001028std::string TWFunc::to_string(unsigned long value) {
1029 std::ostringstream os;
1030 os << value;
1031 return os.str();
1032}
1033
Ethan Yonker9132d912015-02-02 10:32:49 -06001034void TWFunc::Disable_Stock_Recovery_Replace(void) {
1035 if (PartitionManager.Mount_By_Path("/system", false)) {
1036 // Disable flashing of stock recovery
1037 if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
1038 rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
Ethan Yonker74db1572015-10-28 12:44:49 -05001039 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 -06001040 sync();
1041 }
1042 PartitionManager.UnMount_By_Path("/system", false);
1043 }
1044}
1045
Ethan Yonker483e9f42016-01-11 22:21:18 -06001046unsigned long long TWFunc::IOCTL_Get_Block_Size(const char* block_device) {
1047 unsigned long block_device_size;
1048 int ret = 0;
1049
1050 int fd = open(block_device, O_RDONLY);
1051 if (fd < 0) {
1052 LOGINFO("Find_Partition_Size: Failed to open '%s', (%s)\n", block_device, strerror(errno));
1053 } else {
1054 ret = ioctl(fd, BLKGETSIZE, &block_device_size);
1055 close(fd);
1056 if (ret) {
1057 LOGINFO("Find_Partition_Size: ioctl error: (%s)\n", strerror(errno));
1058 } else {
1059 return (unsigned long long)(block_device_size) * 512LLU;
1060 }
1061 }
1062 return 0;
1063}
1064
Ethan Yonkeraf2897c2014-02-10 13:07:14 -06001065#endif // ndef BUILD_TWRPTAR_MAIN