Offer a stricter way to prepare directories.
Some callers, such as installd, have stricter requirements around
directory preparation, where they want to assert ownership and mode
without quietly fixing the values.
Bug: 26466827
Change-Id: Id44db5f29a3326cfe178b443fb450ad2edeaefd8
diff --git a/include/cutils/fs.h b/include/cutils/fs.h
index 70f0b92..98c1296 100644
--- a/include/cutils/fs.h
+++ b/include/cutils/fs.h
@@ -40,11 +40,18 @@
#endif
/*
- * Ensure that directory exists with given mode and owners.
+ * Ensure that directory exists with given mode and owners. If it exists
+ * with a different mode or owners, they are fixed to match the given values.
*/
extern int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid);
/*
+ * Ensure that directory exists with given mode and owners. If it exists
+ * with a different mode or owners, they are not fixed and -1 is returned.
+ */
+extern int fs_prepare_dir_strict(const char* path, mode_t mode, uid_t uid, gid_t gid);
+
+/*
* Read single plaintext integer from given file, correctly handling files
* partially written with fs_write_atomic_int().
*/
diff --git a/libcutils/fs.c b/libcutils/fs.c
index 45c7add..88c488c 100644
--- a/libcutils/fs.c
+++ b/libcutils/fs.c
@@ -37,7 +37,8 @@
#define ALL_PERMS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
#define BUF_SIZE 64
-int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid) {
+static int fs_prepare_dir_impl(const char* path, mode_t mode, uid_t uid, gid_t gid,
+ int allow_fixup) {
// Check if path needs to be created
struct stat sb;
if (TEMP_FAILURE_RETRY(lstat(path, &sb)) == -1) {
@@ -56,8 +57,11 @@
}
if (((sb.st_mode & ALL_PERMS) == mode) && (sb.st_uid == uid) && (sb.st_gid == gid)) {
return 0;
- } else {
+ } else if (allow_fixup) {
goto fixup;
+ } else {
+ ALOGE("Path %s exists with unexpected permissions", path);
+ return -1;
}
create:
@@ -81,6 +85,14 @@
return 0;
}
+int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid) {
+ return fs_prepare_dir_impl(path, mode, uid, gid, 1);
+}
+
+int fs_prepare_dir_strict(const char* path, mode_t mode, uid_t uid, gid_t gid) {
+ return fs_prepare_dir_impl(path, mode, uid, gid, 0);
+}
+
int fs_read_atomic_int(const char* path, int* out_value) {
int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY));
if (fd == -1) {