From cf94fe152e220110d606dcbe2f8a2bd9da0546bc Mon Sep 17 00:00:00 2001 From: Jeff Sharkey Date: Tue, 12 Jan 2016 12:42:32 -0700 Subject: [PATCH] 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 --- include/cutils/fs.h | 9 ++++++++- libcutils/fs.c | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/include/cutils/fs.h b/include/cutils/fs.h index 70f0b9291..98c12962a 100644 --- a/include/cutils/fs.h +++ b/include/cutils/fs.h @@ -40,10 +40,17 @@ extern "C" { #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 45c7add4c..88c488cba 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 @@ int fs_prepare_dir(const char* path, mode_t mode, uid_t uid, gid_t gid) { } 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 @@ fixup: 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) {