init: service file keyword
Solve one more issue where privilege is required to open a file and
we do not want to grant such to the service. This is the service side
of the picture, android_get_control_file() in libcutils is the client.
The file's descriptor is placed into the environment as
"ANDROID_FILE_<path>". For socket and files where non-alpha and
non-numeric characters in the <name/path> are replaced with _. There
was an accompanying change in android_get_control_socket() to match
in commit 'libcutils: add android_get_control_socket() test'
Add a gTest unit test for this that tests create_file and
android_get_control_file().
Test: gTest init_tests --gtest_filter=util.create_file
Bug: 32450474
Change-Id: I96eb970c707db6d51a9885873329ba1cb1f23140
diff --git a/init/util_test.cpp b/init/util_test.cpp
index 228954b..6ecbf90 100644
--- a/init/util_test.cpp
+++ b/init/util_test.cpp
@@ -17,7 +17,15 @@
#include "util.h"
#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <cutils/files.h>
#include <gtest/gtest.h>
+#include <selinux/android.h>
TEST(util, read_file_ENOENT) {
std::string s("hello");
@@ -41,3 +49,51 @@
EXPECT_EQ(UINT_MAX, decode_uid("toot"));
EXPECT_EQ(123U, decode_uid("123"));
}
+
+struct selabel_handle *sehandle;
+
+TEST(util, create_file) {
+ if (!sehandle) sehandle = selinux_android_file_context_handle();
+
+ static const char path[] = "/data/local/tmp/util.create_file.test";
+ static const char key[] = ANDROID_FILE_ENV_PREFIX "_data_local_tmp_util_create_file_test";
+ EXPECT_EQ(unsetenv(key), 0);
+ unlink(path);
+
+ int fd;
+ uid_t uid = decode_uid("logd");
+ gid_t gid = decode_uid("system");
+ mode_t perms = S_IRWXU | S_IWGRP | S_IRGRP | S_IROTH;
+ static const char context[] = "u:object_r:misc_logd_file:s0";
+ EXPECT_GE(fd = create_file(path, O_RDWR | O_CREAT, perms, uid, gid, context), 0);
+ if (fd < 0) return;
+ static const char hello[] = "hello world\n";
+ static const ssize_t len = strlen(hello);
+ EXPECT_EQ(write(fd, hello, len), len);
+ char buffer[sizeof(hello)];
+ memset(buffer, 0, sizeof(buffer));
+ EXPECT_GE(lseek(fd, 0, SEEK_SET), 0);
+ EXPECT_EQ(read(fd, buffer, sizeof(buffer)), len);
+ EXPECT_EQ(strcmp(hello, buffer), 0);
+ char val[32];
+ snprintf(val, sizeof(val), "%d", fd);
+ EXPECT_EQ(android_get_control_file(path), -1);
+ setenv(key, val, true);
+ EXPECT_EQ(android_get_control_file(path), fd);
+ close(fd);
+ EXPECT_EQ(android_get_control_file(path), -1);
+ EXPECT_EQ(unsetenv(key), 0);
+ struct stat st;
+ EXPECT_EQ(stat(path, &st), 0);
+ EXPECT_EQ(st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO), perms);
+ EXPECT_EQ(st.st_uid, uid);
+ EXPECT_EQ(st.st_gid, gid);
+ security_context_t con;
+ EXPECT_GE(getfilecon(path, &con), 0);
+ EXPECT_NE(con, static_cast<security_context_t>(NULL));
+ if (con) {
+ EXPECT_EQ(context, std::string(con));
+ }
+ freecon(con);
+ EXPECT_EQ(unlink(path), 0);
+}