apex: fix selinux denials

We also look to use the loop-control device to identify loop devices.
We only create devices if they don't exist. Modern kernels can have
an option CONFIG_BLK_DEV_LOOP_MIN_COUNT=16 to pre-create the devices.

Change-Id: Ib10cd29f17be4684dd75e0927a2862bf541cd661
diff --git a/sepolicy/twrp.te b/sepolicy/twrp.te
index c27571a..d868cd4 100755
--- a/sepolicy/twrp.te
+++ b/sepolicy/twrp.te
@@ -3,4 +3,6 @@
   permissive init;
   permissive logd;
   permissive adbd;
+  allow kernel tmpfs:file { read };
+  allow kernel recovery:fd { use };
 ')
diff --git a/twrpApex.cpp b/twrpApex.cpp
index a6041f1..52dd9e5 100755
--- a/twrpApex.cpp
+++ b/twrpApex.cpp
@@ -1,4 +1,5 @@
 #include "twrpApex.hpp"
+#include "twrp-functions.hpp"
 
 namespace fs = std::filesystem;
 
@@ -23,16 +24,11 @@
 		}
 		return true;
 	}
-	if (!createLoopBackDevices(apexFiles.size())) {
+	if (!mountApexOnLoopbackDevices(apexFiles)) {
 		LOGERR("Unable to create loop devices to mount apex files\n");
 		return false;
 	}
 
-	size_t apexFileCount = 0;
-	for (auto&& apexFile : apexFiles) {
-		std::string fileToMount = unzipImage(apexFile);
-		loadApexImage(fileToMount, apexFileCount++);
-	}
 	return true;
 }
 
@@ -66,31 +62,36 @@
 		return nullptr;
 	}
 
-	close(fd);
 	CloseArchive(handle);
+	close(fd);
 	return path;
 }
 
-bool twrpApex::createLoopBackDevices(size_t count) {
-	size_t existing_loop_device_count = 0;
-
-	for (const auto& entry : fs::directory_iterator(LOOP_BLOCK_DEVICE_DIR)) {
-	   if (entry.is_block_file() && entry.path().string().find("loop") != std::string::npos) {
-		   existing_loop_device_count++;
-	   }
+bool twrpApex::mountApexOnLoopbackDevices(std::vector<std::string> apexFiles) {
+	int fd = open(LOOP_CONTROL, O_RDWR | O_CLOEXEC);
+	if (fd < 0) {
+		LOGERR("Unable to open %s device. Reason: %s\n", LOOP_CONTROL, strerror(errno));
+		return false;
 	}
 
-	if (existing_loop_device_count < count) {
-		size_t devices_to_create = count - existing_loop_device_count;
-		for (size_t i = existing_loop_device_count; i < (devices_to_create + existing_loop_device_count); ++i) {
-			std::string loop_device = LOOP_BLOCK_DEVICE_DIR;
-			loop_device = loop_device + "loop" + std::to_string(i);
-			int ret = mknod(loop_device.c_str(), S_IFBLK | S_IRUSR | S_IWUSR , makedev(7, i));
+	size_t device_no = 0;
+	for (auto&& apexFile:apexFiles) {
+		int num = ioctl(fd, LOOP_CTL_GET_FREE);
+		std::string loop_device = LOOP_BLOCK_DEVICE_DIR;
+		loop_device = loop_device + "loop" + std::to_string(num);
+		if (!TWFunc::Path_Exists(loop_device)) {
+			int ret = mknod(loop_device.c_str(), S_IFBLK | S_IRUSR | S_IWUSR , makedev(7, device_no));
 			if (ret != 0) {
-				LOGERR("unable to create loop device: %s\n", loop_device.c_str());
+				LOGERR("Unable to create loop device: %s\n", loop_device.c_str());
 				return false;
 			}
 		}
+		std::string fileToMount = unzipImage(apexFile);
+		bool load_result = loadApexImage(fileToMount, device_no);
+		if (!load_result) {
+			return false;
+		}
+		device_no++;
 	}
 	return true;
 }
@@ -98,9 +99,9 @@
 bool twrpApex::loadApexImage(std::string fileToMount, size_t loop_device_number) {
 	struct loop_info64 info;
 
-	int fd = open(fileToMount.c_str(), O_RDONLY);
+	int fd = open(fileToMount.c_str(), O_RDONLY | O_CLOEXEC);
 	if (fd < 0) {
-		LOGERR("unable to open apex file: %s\n", fileToMount.c_str());
+		LOGERR("unable to open apex file: %s. Reason: %s\n", fileToMount.c_str(), strerror(errno));
 		return false;
 	}
 
@@ -122,23 +123,35 @@
 	close(fd);
 
 	memset(&info, 0, sizeof(struct loop_info64));
+	strlcpy((char*)info.lo_crypt_name, "twrpApex", LO_NAME_SIZE);
+	off_t apex_size = lseek(fd, 0, SEEK_END);
+	info.lo_sizelimit = apex_size;
 	if (ioctl(loop_fd, LOOP_SET_STATUS64, &info)) {
 		LOGERR("failed to mount loop: %s: %s\n", fileToMount.c_str(), strerror(errno));
 		close(loop_fd);
 		return false;
 	}
+	if (ioctl(loop_fd, BLKFLSBUF, 0) == -1) {
+		LOGERR("Unable to flush loop device buffers\n");
+		return false;
+	}
+	if (ioctl(loop_fd, LOOP_SET_BLOCK_SIZE, 4096) == -1) {
+		LOGINFO("Failed to set DIRECT_IO buffer size\n");
+	}
 	close(loop_fd);
+
 	std::string bind_mount(APEX_BASE);
 	bind_mount = bind_mount + basename(fileToMount.c_str());
+
 	int ret = mkdir(bind_mount.c_str(), 0666);
 	if (ret != 0) {
-		LOGERR("Unable to create mount directory: %s\n", bind_mount.c_str());
+		LOGERR("Unable to create bind mount directory: %s\n", bind_mount.c_str());
 		return false;
 	}
 
 	ret = mount(loop_device.c_str(), bind_mount.c_str(), "ext4", MS_RDONLY, nullptr);
 	if (ret != 0) {
-		LOGERR("unable to mount loop device %s to %s. reason: %s\n", loop_device.c_str(), bind_mount.c_str(), strerror(errno));
+		LOGERR("unable to mount loop device %s to %s. Reason: %s\n", loop_device.c_str(), bind_mount.c_str(), strerror(errno));
 		return false;
 	}
 
diff --git a/twrpApex.hpp b/twrpApex.hpp
index b00b9ae..f42ed8a 100755
--- a/twrpApex.hpp
+++ b/twrpApex.hpp
@@ -18,11 +18,11 @@
 #include <ziparchive/zip_archive.h>
 #include "twcommon.h"
 
-
 #define APEX_DIR "/system_root/system/apex"
 #define APEX_PAYLOAD "apex_payload.img"
 #define LOOP_BLOCK_DEVICE_DIR "/dev/block/"
 #define APEX_BASE "/apex/"
+#define LOOP_CONTROL "/dev/loop-control"
 
 class twrpApex {
 public:
@@ -30,7 +30,7 @@
 
 private:
 	std::string unzipImage(std::string file);
-	bool createLoopBackDevices(size_t count);
+	bool mountApexOnLoopbackDevices(std::vector<std::string> apexFiles);
 	bool loadApexImage(std::string fileToMount, size_t loop_device_number);
 };
 #endif