twrp.cpp 13.1 KB
Newer Older
1
/*
2 3 4 5
		TWRP is free software: you can redistribute it and/or modify
		it under the terms of the GNU General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		(at your option) any later version.
6

7 8 9 10
		TWRP is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
		GNU General Public License for more details.
11

12 13
		You should have received a copy of the GNU General Public License
		along with TWRP.  If not, see <http://www.gnu.org/licenses/>.
14 15 16 17
*/

#include <stdio.h>
#include <stdlib.h>
Ethan Yonker's avatar
Ethan Yonker committed
18
#include <string>
19 20 21 22
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
Ethan Yonker's avatar
Ethan Yonker committed
23
#include <signal.h>
Ethan Yonker's avatar
Ethan Yonker committed
24
#include "gui/twmsg.h"
25 26

#include "cutils/properties.h"
Ethan Yonker's avatar
Ethan Yonker committed
27
#include "bootloader_message_twrp/include/bootloader_message_twrp/bootloader_message.h"
28 29 30 31 32 33 34 35 36 37

#ifdef ANDROID_RB_RESTART
#include "cutils/android_reboot.h"
#else
#include <sys/reboot.h>
#endif

extern "C" {
#include "gui/gui.h"
}
38
#include "set_metadata.h"
Ethan Yonker's avatar
Ethan Yonker committed
39 40 41
#include "gui/gui.hpp"
#include "gui/pages.hpp"
#include "gui/objects.hpp"
42 43 44 45 46 47
#include "twcommon.h"
#include "twrp-functions.hpp"
#include "data.hpp"
#include "partitions.hpp"
#include "openrecoveryscript.hpp"
#include "variables.h"
48
#include "twrpAdbBuFifo.hpp"
49
#ifdef TW_USE_NEW_MINADBD
Ethan Yonker's avatar
Ethan Yonker committed
50
#include "minadbd/minadbd.h"
51 52
#else
extern "C" {
Ethan Yonker's avatar
Ethan Yonker committed
53
#include "minadbd21/adb.h"
54 55
}
#endif
56

57
#include <selinux/label.h>
Dees_Troy's avatar
Dees_Troy committed
58 59
struct selabel_handle *selinux_handle;

Ethan Yonker's avatar
Ethan Yonker committed
60
//extern int adb_server_main(int is_daemon, int server_port, int /* reply_fd */);
61

62 63
TWPartitionManager PartitionManager;
int Log_Offset;
64
bool datamedia;
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

static void Print_Prop(const char *key, const char *name, void *cookie) {
	printf("%s=%s\n", key, name);
}

int main(int argc, char **argv) {
	// Recovery needs to install world-readable files, so clear umask
	// set by init
	umask(0);

	Log_Offset = 0;

	// Set up temporary log file (/tmp/recovery.log)
	freopen(TMP_LOG_FILE, "a", stdout);
	setbuf(stdout, NULL);
	freopen(TMP_LOG_FILE, "a", stderr);
	setbuf(stderr, NULL);

Ethan Yonker's avatar
Ethan Yonker committed
83 84
	signal(SIGPIPE, SIG_IGN);

85 86
	// Handle ADB sideload
	if (argc == 3 && strcmp(argv[1], "--adbd") == 0) {
that's avatar
that committed
87
		property_set("ctl.stop", "adbd");
88
#ifdef TW_USE_NEW_MINADBD
Ethan Yonker's avatar
Ethan Yonker committed
89 90
		//adb_server_main(0, DEFAULT_ADB_PORT, -1); TODO fix this for android8
		minadbd_main();
91
#else
92
		adb_main(argv[2]);
93
#endif
94 95 96
		return 0;
	}

97 98 99 100
#ifdef RECOVERY_SDCARD_ON_DATA
	datamedia = true;
#endif

101 102 103 104 105 106
	char crash_prop_val[PROPERTY_VALUE_MAX];
	int crash_counter;
	property_get("twrp.crash_counter", crash_prop_val, "-1");
	crash_counter = atoi(crash_prop_val) + 1;
	snprintf(crash_prop_val, sizeof(crash_prop_val), "%d", crash_counter);
	property_set("twrp.crash_counter", crash_prop_val);
bigbiff bigbiff's avatar
bigbiff bigbiff committed
107 108
	property_set("ro.twrp.boot", "1");
	property_set("ro.twrp.version", TW_VERSION_STR);
109

110
	time_t StartupTime = time(NULL);
111
	printf("Starting TWRP %s-%s on %s (pid %d)\n", TW_VERSION_STR, TW_GIT_REVISION, ctime(&StartupTime), getpid());
112 113 114

	// Load default values to set DataManager constants and handle ifdefs
	DataManager::SetDefaultValues();
115
	printf("Starting the UI...\n");
116 117 118
	gui_init();
	printf("=> Linking mtab\n");
	symlink("/proc/mounts", "/etc/mtab");
Dees_Troy's avatar
Dees_Troy committed
119 120 121 122 123 124 125 126
	if (TWFunc::Path_Exists("/etc/twrp.fstab")) {
		if (TWFunc::Path_Exists("/etc/recovery.fstab")) {
			printf("Renaming regular /etc/recovery.fstab -> /etc/recovery.fstab.bak\n");
			rename("/etc/recovery.fstab", "/etc/recovery.fstab.bak");
		}
		printf("Moving /etc/twrp.fstab -> /etc/recovery.fstab\n");
		rename("/etc/twrp.fstab", "/etc/recovery.fstab");
	}
127 128 129 130 131 132 133 134 135
	printf("=> Processing recovery.fstab\n");
	if (!PartitionManager.Process_Fstab("/etc/recovery.fstab", 1)) {
		LOGERR("Failing out of recovery due to problem with recovery.fstab.\n");
		return -1;
	}
	PartitionManager.Output_Partition_Logging();
	// Load up all the resources
	gui_loadResources();

136 137 138 139 140 141 142 143
	if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
		if (TWFunc::Path_Exists("/file_contexts")) {
			printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
			rename("/file_contexts", "/file_contexts.bak");
		}
		printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
		rename("/prebuilt_file_contexts", "/file_contexts");
	}
Dees_Troy's avatar
Dees_Troy committed
144 145 146
	struct selinux_opt selinux_options[] = {
		{ SELABEL_OPT_PATH, "/file_contexts" }
	};
147
	selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
Dees_Troy's avatar
Dees_Troy committed
148 149 150 151
	if (!selinux_handle)
		printf("No file contexts for SELinux\n");
	else
		printf("SELinux contexts loaded from /file_contexts\n");
152 153
	{ // Check to ensure SELinux can be supported by the kernel
		char *contexts = NULL;
Dees Troy's avatar
Dees Troy committed
154

155
		if (PartitionManager.Mount_By_Path("/cache", false) && TWFunc::Path_Exists("/cache/recovery")) {
Dees Troy's avatar
Dees Troy committed
156 157 158 159 160 161 162 163 164
			lgetfilecon("/cache/recovery", &contexts);
			if (!contexts) {
				lsetfilecon("/cache/recovery", "test");
				lgetfilecon("/cache/recovery", &contexts);
			}
		} else {
			LOGINFO("Could not check /cache/recovery SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n");
			lgetfilecon("/sbin/teamwin", &contexts);
		}
165
		if (!contexts) {
Ethan Yonker's avatar
Ethan Yonker committed
166
			gui_warn("no_kernel_selinux=Kernel does not have support for reading SELinux contexts.");
167 168
		} else {
			free(contexts);
Ethan Yonker's avatar
Ethan Yonker committed
169
			gui_msg("full_selinux=Full SELinux support is present.");
170 171
		}
	}
Dees_Troy's avatar
Dees_Troy committed
172

173
	PartitionManager.Mount_By_Path("/cache", false);
174

Matt Mower's avatar
Matt Mower committed
175
	bool Shutdown = false;
Ethan Yonker's avatar
Ethan Yonker committed
176
	string Send_Intent = "";
177
	{
Dees_Troy's avatar
Dees_Troy committed
178 179 180
		TWPartition* misc = PartitionManager.Find_Partition_By_Path("/misc");
		if (misc != NULL) {
			if (misc->Current_File_System == "emmc") {
Ethan Yonker's avatar
Ethan Yonker committed
181
				set_misc_device(misc->Actual_Block_Device.c_str());
Dees_Troy's avatar
Dees_Troy committed
182
			} else {
183
				LOGERR("Only emmc /misc is supported\n");
Dees_Troy's avatar
Dees_Troy committed
184 185
			}
		}
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
		get_args(&argc, &argv);

		int index, index2, len;
		char* argptr;
		char* ptr;
		printf("Startup Commands: ");
		for (index = 1; index < argc; index++) {
			argptr = argv[index];
			printf(" '%s'", argv[index]);
			len = strlen(argv[index]);
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == 'u') {
				ptr = argptr;
				index2 = 0;
				while (*ptr != '=' && *ptr != '\n')
					ptr++;
203 204 205
				// skip the = before grabbing Zip_File
				while (*ptr == '=')
					ptr++;
206
				if (*ptr) {
207 208 209 210 211
					string ORSCommand = "install ";
					ORSCommand.append(ptr);

					if (!OpenRecoveryScript::Insert_ORS_Command(ORSCommand))
						break;
212 213 214
				} else
					LOGERR("argument error specifying zip file\n");
			} else if (*argptr == 'w') {
215 216 217 218 219 220 221
				if (len == 9) {
					if (!OpenRecoveryScript::Insert_ORS_Command("wipe data\n"))
						break;
				} else if (len == 10) {
					if (!OpenRecoveryScript::Insert_ORS_Command("wipe cache\n"))
						break;
				}
Ethan Yonker's avatar
Ethan Yonker committed
222
				// Other 'w' items are wipe_ab and wipe_package_size which are related to bricking the device remotely. We will not bother to suppor these as having TWRP probably makes "bricking" the device in this manner useless
223
			} else if (*argptr == 'n') {
224 225 226
				DataManager::SetValue(TW_BACKUP_NAME, gui_parse_text("{@auto_generate}"));
				if (!OpenRecoveryScript::Insert_ORS_Command("backup BSDCAE\n"))
					break;
227 228
			} else if (*argptr == 'p') {
				Shutdown = true;
229
			} else if (*argptr == 's') {
230
				if (strncmp(argptr, "send_intent", strlen("send_intent")) == 0) {
Ethan Yonker's avatar
Ethan Yonker committed
231 232
					ptr = argptr + strlen("send_intent") + 1;
					Send_Intent = *ptr;
233
				} else if (strncmp(argptr, "security", strlen("security")) == 0) {
Ethan Yonker's avatar
Ethan Yonker committed
234
					LOGINFO("Security update\n");
235
				} else if (strncmp(argptr, "sideload", strlen("sideload")) == 0) {
Ethan Yonker's avatar
Ethan Yonker committed
236 237
					if (!OpenRecoveryScript::Insert_ORS_Command("sideload\n"))
						break;
238
				} else if (strncmp(argptr, "stages", strlen("stages")) == 0) {
Ethan Yonker's avatar
Ethan Yonker committed
239 240 241
					LOGINFO("ignoring stages command\n");
				}
			} else if (*argptr == 'r') {
242
				if (strncmp(argptr, "reason", strlen("reason")) == 0) {
Ethan Yonker's avatar
Ethan Yonker committed
243 244
					ptr = argptr + strlen("reason") + 1;
					gui_print("%s\n", ptr);
245 246 247
				}
			}
		}
248
		printf("\n");
249 250
	}

Matt Mower's avatar
Matt Mower committed
251
	if (crash_counter == 0) {
252 253
		property_list(Print_Prop, NULL);
		printf("\n");
254 255
	} else {
		printf("twrp.crash_counter=%d\n", crash_counter);
256 257 258 259 260 261 262 263 264 265 266
	}

	// Check for and run startup script if script exists
	TWFunc::check_and_run_script("/sbin/runatboot.sh", "boot");
	TWFunc::check_and_run_script("/sbin/postrecoveryboot.sh", "boot");

#ifdef TW_INCLUDE_INJECTTWRP
	// Back up TWRP Ramdisk if needed:
	TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
	LOGINFO("Backing up TWRP ramdisk...\n");
	if (Boot == NULL || Boot->Current_File_System != "emmc")
267
		TWFunc::Exec_Cmd("injecttwrp --backup /tmp/backup_recovery_ramdisk.img");
268 269
	else {
		string injectcmd = "injecttwrp --backup /tmp/backup_recovery_ramdisk.img bd=" + Boot->Actual_Block_Device;
270
		TWFunc::Exec_Cmd(injectcmd);
271 272 273 274 275 276 277 278
	}
	LOGINFO("Backup of TWRP ramdisk done.\n");
#endif

	TWFunc::Update_Log_File();
	// Offer to decrypt if the device is encrypted
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0) {
		LOGINFO("Is encrypted, do decrypt page first\n");
279
		if (gui_startPage("decrypt", 1, 1) != 0) {
280
			LOGERR("Failed to start decrypt GUI page.\n");
281 282 283
		} else {
			// Check for and load custom theme if present
			gui_loadCustomResources();
284
		}
285 286
	} else if (datamedia) {
		if (tw_get_default_metadata(DataManager::GetSettingsStoragePath().c_str()) != 0) {
287
			LOGINFO("Failed to get default contexts and file mode for storage files.\n");
288 289 290
		} else {
			LOGINFO("Got default contexts and file mode for storage files.\n");
		}
291 292 293 294
	}

	// Read the settings file
	DataManager::ReadSettingsFile();
Ethan Yonker's avatar
Ethan Yonker committed
295 296
	PageManager::LoadLanguage(DataManager::GetStrValue("tw_language"));
	GUIConsole::Translate_Now();
297 298

	// Fixup the RTC clock on devices which require it
Matt Mower's avatar
Matt Mower committed
299
	if (crash_counter == 0)
300
		TWFunc::Fixup_Time_On_Boot();
301

302 303 304 305
	// Run any outstanding OpenRecoveryScript
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(SCRIPT_FILE_CACHE))) {
		OpenRecoveryScript::Run_OpenRecoveryScript();
	}
306

307 308 309
#ifdef TW_HAS_MTP
	char mtp_crash_check[PROPERTY_VALUE_MAX];
	property_get("mtp.crash_check", mtp_crash_check, "0");
Matt Mower's avatar
Matt Mower committed
310 311 312
	if (DataManager::GetIntValue("tw_mtp_enabled")
			&& !strcmp(mtp_crash_check, "0") && !crash_counter
			&& (!DataManager::GetIntValue(TW_IS_ENCRYPTED) || DataManager::GetIntValue(TW_IS_DECRYPTED))) {
313
		property_set("mtp.crash_check", "1");
Matt Mower's avatar
Matt Mower committed
314 315
		LOGINFO("Starting MTP\n");
		if (!PartitionManager.Enable_MTP())
316
			PartitionManager.Disable_MTP();
Matt Mower's avatar
Matt Mower committed
317 318
		else
			gui_msg("mtp_enabled=MTP Enabled");
319
		property_set("mtp.crash_check", "0");
Matt Mower's avatar
Matt Mower committed
320
	} else if (strcmp(mtp_crash_check, "0")) {
Ethan Yonker's avatar
Ethan Yonker committed
321
		gui_warn("mtp_crash=MTP Crashed, not starting MTP on boot.");
322
		DataManager::SetValue("tw_mtp_enabled", 0);
323
		PartitionManager.Disable_MTP();
Matt Mower's avatar
Matt Mower committed
324 325 326
	} else if (crash_counter == 1) {
		LOGINFO("TWRP crashed; disabling MTP as a precaution.\n");
		PartitionManager.Disable_MTP();
bigbiff bigbiff's avatar
bigbiff bigbiff committed
327
	}
328
#endif
bigbiff bigbiff's avatar
bigbiff bigbiff committed
329

330
#ifndef TW_OEM_BUILD
331
	// Check if system has never been changed
332
	TWPartition* sys = PartitionManager.Find_Partition_By_Path("/system");
333
	TWPartition* ven = PartitionManager.Find_Partition_By_Path("/vendor");
334

335
	if (sys) {
336 337 338 339 340
		if ((DataManager::GetIntValue("tw_mount_system_ro") == 0 && sys->Check_Lifetime_Writes() == 0) || DataManager::GetIntValue("tw_mount_system_ro") == 2) {
			if (DataManager::GetIntValue("tw_never_show_system_ro_page") == 0) {
				DataManager::SetValue("tw_back", "main");
				if (gui_startPage("system_readonly", 1, 1) != 0) {
					LOGERR("Failed to start system_readonly GUI page.\n");
341
				}
342
			} else if (DataManager::GetIntValue("tw_mount_system_ro") == 0) {
343
				sys->Change_Mount_Read_Only(false);
344 345
				if (ven)
					ven->Change_Mount_Read_Only(false);
346
			}
347 348
		} else if (DataManager::GetIntValue("tw_mount_system_ro") == 1) {
			// Do nothing, user selected to leave system read only
349
		} else {
350
			sys->Change_Mount_Read_Only(false);
351 352
			if (ven)
				ven->Change_Mount_Read_Only(false);
353 354
		}
	}
355
#endif
356 357 358
	twrpAdbBuFifo *adb_bu_fifo = new twrpAdbBuFifo();
	adb_bu_fifo->threadAdbBuFifo();

359 360 361
	// Launch the main GUI
	gui_start();

362
#ifndef TW_OEM_BUILD
363 364
	// Disable flashing of stock recovery
	TWFunc::Disable_Stock_Recovery_Replace();
365
	// Check for su to see if the device is rooted or not
366
	if (DataManager::GetIntValue("tw_mount_system_ro") == 0 && PartitionManager.Mount_By_Path("/system", false)) {
367 368 369 370 371 372 373
		// read /system/build.prop to get sdk version and do not offer to root if running M or higher (sdk version 23 == M)
		string sdkverstr = TWFunc::System_Property_Get("ro.build.version.sdk");
		int sdkver = 23;
		if (!sdkverstr.empty()) {
			sdkver = atoi(sdkverstr.c_str());
		}
		if (TWFunc::Path_Exists("/supersu/su") && TWFunc::Path_Exists("/system/bin") && !TWFunc::Path_Exists("/system/bin/su") && !TWFunc::Path_Exists("/system/xbin/su") && !TWFunc::Path_Exists("/system/bin/.ext/.su") && sdkver < 23) {
374 375
			// Device doesn't have su installed
			DataManager::SetValue("tw_busy", 1);
376
			if (gui_startPage("installsu", 1, 1) != 0) {
Dees Troy's avatar
Dees Troy committed
377
				LOGERR("Failed to start SuperSU install page.\n");
378 379 380 381 382
			}
		}
		sync();
		PartitionManager.UnMount_By_Path("/system", false);
	}
383
#endif
384

385
	// Reboot
Ethan Yonker's avatar
Ethan Yonker committed
386
	TWFunc::Update_Intent_File(Send_Intent);
387
	delete adb_bu_fifo;
388
	TWFunc::Update_Log_File();
Ethan Yonker's avatar
Ethan Yonker committed
389
	gui_msg(Msg("rebooting=Rebooting..."));
390 391 392 393 394 395 396 397 398 399 400 401 402
	string Reboot_Arg;
	DataManager::GetValue("tw_reboot_arg", Reboot_Arg);
	if (Reboot_Arg == "recovery")
		TWFunc::tw_reboot(rb_recovery);
	else if (Reboot_Arg == "poweroff")
		TWFunc::tw_reboot(rb_poweroff);
	else if (Reboot_Arg == "bootloader")
		TWFunc::tw_reboot(rb_bootloader);
	else if (Reboot_Arg == "download")
		TWFunc::tw_reboot(rb_download);
	else
		TWFunc::tw_reboot(rb_system);

403
	return 0;
404
}