Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 37efe079 authored by Jeff Sharkey's avatar Jeff Sharkey Committed by android-build-merger
Browse files

Merge "Remove FUSE logic; it's only a sdcardfs wrapper." am: 3b44d284 am: a4a54c94

am: 2393133e

Change-Id: I580982b347f2c9c84d105f9b4d99bd9557feac81
parents 7f49e465 2393133e
Loading
Loading
Loading
Loading

sdcard/Android.bp

0 → 100644
+17 −0
Original line number Original line Diff line number Diff line
cc_binary {
    srcs: ["sdcard.cpp"],
    name: "sdcard",
    cflags: [
        "-Wall",
        "-Wno-unused-parameter",
        "-Werror",
    ],
    shared_libs: [
        "libbase",
        "libcutils",
        "libminijail",
    ],
    sanitize: {
        misc_undefined: ["integer"],
    },
}

sdcard/Android.mk

deleted100644 → 0
+0 −12
Original line number Original line Diff line number Diff line
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_SRC_FILES := sdcard.cpp fuse.cpp
LOCAL_MODULE := sdcard
LOCAL_CFLAGS := -Wall -Wno-unused-parameter -Werror
LOCAL_SHARED_LIBRARIES := libbase libcutils libminijail libpackagelistparser

LOCAL_SANITIZE := integer

include $(BUILD_EXECUTABLE)

sdcard/fuse.cpp

deleted100644 → 0
+0 −1476

File deleted.

Preview size limit exceeded, changes collapsed.

sdcard/fuse.h

deleted100644 → 0
+0 −209
Original line number Original line Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef FUSE_H_
#define FUSE_H_

#include <dirent.h>
#include <fcntl.h>
#include <linux/fuse.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

#include <map>
#include <string>

#include <android-base/logging.h>
#include <cutils/fs.h>
#include <cutils/multiuser.h>
#include <packagelistparser/packagelistparser.h>

#include <private/android_filesystem_config.h>

#define FUSE_TRACE 0

#if FUSE_TRACE
static constexpr bool kEnableDLog = true;
#else  // FUSE_TRACE == 0
static constexpr bool kEnableDLog = false;
#endif

// Use same strategy as DCHECK().
#define DLOG(x) \
    if (kEnableDLog) LOG(x)

/* Maximum number of bytes to write in one request. */
#define MAX_WRITE (256 * 1024)

/* Maximum number of bytes to read in one request. */
#define MAX_READ (128 * 1024)

/* Largest possible request.
 * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
 * the largest possible data payload. */
#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)

namespace {
struct CaseInsensitiveCompare {
    bool operator()(const std::string& lhs, const std::string& rhs) const {
        return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};
}

using AppIdMap = std::map<std::string, appid_t, CaseInsensitiveCompare>;

/* Permission mode for a specific node. Controls how file permissions
 * are derived for children nodes. */
typedef enum {
    /* Nothing special; this node should just inherit from its parent. */
    PERM_INHERIT,
    /* This node is one level above a normal root; used for legacy layouts
     * which use the first level to represent user_id. */
    PERM_PRE_ROOT,
    /* This node is "/" */
    PERM_ROOT,
    /* This node is "/Android" */
    PERM_ANDROID,
    /* This node is "/Android/data" */
    PERM_ANDROID_DATA,
    /* This node is "/Android/obb" */
    PERM_ANDROID_OBB,
    /* This node is "/Android/media" */
    PERM_ANDROID_MEDIA,
} perm_t;

struct handle {
    int fd;
};

struct dirhandle {
    DIR *d;
};

struct node {
    __u32 refcount;
    __u64 nid;
    __u64 gen;
    /*
     * The inode number for this FUSE node. Note that this isn't stable across
     * multiple invocations of the FUSE daemon.
     */
    __u32 ino;

    /* State derived based on current position in hierarchy. */
    perm_t perm;
    userid_t userid;
    uid_t uid;
    bool under_android;

    struct node *next;          /* per-dir sibling list */
    struct node *child;         /* first contained file by this dir */
    struct node *parent;        /* containing directory */

    size_t namelen;
    char *name;
    /* If non-null, this is the real name of the file in the underlying storage.
     * This may differ from the field "name" only by case.
     * strlen(actual_name) will always equal strlen(name), so it is safe to use
     * namelen for both fields.
     */
    char *actual_name;

    /* If non-null, an exact underlying path that should be grafted into this
     * position. Used to support things like OBB. */
    char* graft_path;
    size_t graft_pathlen;

    bool deleted;
};

/* Global data for all FUSE mounts */
struct fuse_global {
    pthread_mutex_t lock;

    uid_t uid;
    gid_t gid;
    bool multi_user;

    char source_path[PATH_MAX];
    char obb_path[PATH_MAX];

    AppIdMap* package_to_appid;

    __u64 next_generation;
    struct node root;

    /* Used to allocate unique inode numbers for fuse nodes. We use
     * a simple counter based scheme where inode numbers from deleted
     * nodes aren't reused. Note that inode allocations are not stable
     * across multiple invocation of the sdcard daemon, but that shouldn't
     * be a huge problem in practice.
     *
     * Note that we restrict inodes to 32 bit unsigned integers to prevent
     * truncation on 32 bit processes when unsigned long long stat.st_ino is
     * assigned to an unsigned long ino_t type in an LP32 process.
     *
     * Also note that fuse_attr and fuse_dirent inode values are 64 bits wide
     * on both LP32 and LP64, but the fuse kernel code doesn't squash 64 bit
     * inode numbers into 32 bit values on 64 bit kernels (see fuse_squash_ino
     * in fs/fuse/inode.c).
     *
     * Accesses must be guarded by |lock|.
     */
    __u32 inode_ctr;

    struct fuse* fuse_default;
    struct fuse* fuse_read;
    struct fuse* fuse_write;
};

/* Single FUSE mount */
struct fuse {
    struct fuse_global* global;

    char dest_path[PATH_MAX];

    int fd;

    gid_t gid;
    mode_t mask;
};

/* Private data used by a single FUSE handler */
struct fuse_handler {
    struct fuse* fuse;
    int token;

    /* To save memory, we never use the contents of the request buffer and the read
     * buffer at the same time.  This allows us to share the underlying storage. */
    union {
        __u8 request_buffer[MAX_REQUEST_SIZE];
        __u8 read_buffer[MAX_READ + PAGE_SIZE];
    };
};

void handle_fuse_requests(struct fuse_handler* handler);
void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent);

#endif  /* FUSE_H_ */
+5 −304
Original line number Original line Diff line number Diff line
@@ -38,164 +38,18 @@
#include <cutils/multiuser.h>
#include <cutils/multiuser.h>
#include <cutils/properties.h>
#include <cutils/properties.h>


#include <packagelistparser/packagelistparser.h>

#include <libminijail.h>
#include <libminijail.h>
#include <scoped_minijail.h>
#include <scoped_minijail.h>


#include <private/android_filesystem_config.h>
#include <private/android_filesystem_config.h>


// README
// NOTE: This is a vestigial program that simply exists to mount the in-kernel
//
// sdcardfs filesystem.  The older FUSE-based design that used to live here has
// What is this?
// been completely removed to avoid confusion.
//
// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
// directory permissions (all files are given fixed owner, group, and
// permissions at creation, owner, group, and permissions are not
// changeable, symlinks and hardlinks are not createable, etc.
//
// See usage() for command line options.
//
// It must be run as root, but will drop to requested UID/GID as soon as it
// mounts a filesystem.  It will refuse to run if requested UID/GID are zero.
//
// Things I believe to be true:
//
// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
// CREAT) must bump that node's refcount
// - don't forget that FORGET can forget multiple references (req->nlookup)
// - if an op that returns a fuse_entry fails writing the reply to the
// kernel, you must rollback the refcount to reflect the reference the
// kernel did not actually acquire
//
// This daemon can also derive custom filesystem permissions based on directory
// structure when requested. These custom permissions support several features:
//
// - Apps can access their own files in /Android/data/com.example/ without
// requiring any additional GIDs.
// - Separate permissions for protecting directories like Pictures and Music.
// - Multi-user separation on the same physical device.

#include "fuse.h"

#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"


/* Supplementary groups to execute with. */
/* Supplementary groups to execute with. */
static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
static const gid_t kGroups[1] = { AID_PACKAGE_INFO };


static bool package_parse_callback(pkg_info *info, void *userdata) {
    struct fuse_global *global = (struct fuse_global *)userdata;
    bool res = global->package_to_appid->emplace(info->name, info->uid).second;
    packagelist_free(info);
    return res;
}

static bool read_package_list(struct fuse_global* global) {
    pthread_mutex_lock(&global->lock);

    global->package_to_appid->clear();
    bool rc = packagelist_parse(package_parse_callback, global);
    DLOG(INFO) << "read_package_list: found " << global->package_to_appid->size() << " packages";

    // Regenerate ownership details using newly loaded mapping.
    derive_permissions_recursive_locked(global->fuse_default, &global->root);

    pthread_mutex_unlock(&global->lock);

    return rc;
}

static void watch_package_list(struct fuse_global* global) {
    struct inotify_event *event;
    char event_buf[512];

    int nfd = inotify_init();
    if (nfd == -1) {
        PLOG(ERROR) << "inotify_init failed";
        return;
    }

    bool active = false;
    while (1) {
        if (!active) {
            int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
            if (res == -1) {
                if (errno == ENOENT || errno == EACCES) {
                    /* Framework may not have created the file yet, sleep and retry. */
                    LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
                    sleep(3);
                    continue;
                } else {
                    PLOG(ERROR) << "inotify_add_watch failed";
                    return;
                }
            }

            /* Watch above will tell us about any future changes, so
             * read the current state. */
            if (read_package_list(global) == false) {
                LOG(ERROR) << "read_package_list failed";
                return;
            }
            active = true;
        }

        int event_pos = 0;
        ssize_t res = TEMP_FAILURE_RETRY(read(nfd, event_buf, sizeof(event_buf)));
        if (res == -1) {
            PLOG(ERROR) << "failed to read inotify event";
            return;
        } else if (static_cast<size_t>(res) < sizeof(*event)) {
            LOG(ERROR) << "failed to read inotify event: read " << res << " expected "
                       << sizeof(event_buf);
            return;
        }

        while (res >= static_cast<ssize_t>(sizeof(*event))) {
            int event_size;
            event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);

            DLOG(INFO) << "inotify event: " << std::hex << event->mask << std::dec;
            if ((event->mask & IN_IGNORED) == IN_IGNORED) {
                /* Previously watched file was deleted, probably due to move
                 * that swapped in new data; re-arm the watch and read. */
                active = false;
            }

            event_size = sizeof(*event) + event->len;
            res -= event_size;
            event_pos += event_size;
        }
    }
}

static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
    char opts[256];

    fuse->fd = TEMP_FAILURE_RETRY(open("/dev/fuse", O_RDWR | O_CLOEXEC));
    if (fuse->fd == -1) {
        PLOG(ERROR) << "failed to open fuse device";
        return -1;
    }

    umount2(fuse->dest_path, MNT_DETACH);

    snprintf(opts, sizeof(opts),
            "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
            fuse->fd, fuse->global->uid, fuse->global->gid);
    if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME,
              opts) == -1) {
        PLOG(ERROR) << "failed to mount fuse filesystem";
        return -1;
    }

    fuse->gid = gid;
    fuse->mask = mask;

    return 0;
}

static void drop_privs(uid_t uid, gid_t gid) {
static void drop_privs(uid_t uid, gid_t gid) {
    ScopedMinijail j(minijail_new());
    ScopedMinijail j(minijail_new());
    minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
    minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
@@ -205,120 +59,6 @@ static void drop_privs(uid_t uid, gid_t gid) {
    minijail_enter(j.get());
    minijail_enter(j.get());
}
}


static void* start_handler(void* data) {
    struct fuse_handler* handler = static_cast<fuse_handler*>(data);
    handle_fuse_requests(handler);
    return NULL;
}

static void run(const char* source_path, const char* label, uid_t uid,
        gid_t gid, userid_t userid, bool multi_user, bool full_write) {
    struct fuse_global global;
    struct fuse fuse_default;
    struct fuse fuse_read;
    struct fuse fuse_write;
    struct fuse_handler handler_default;
    struct fuse_handler handler_read;
    struct fuse_handler handler_write;
    pthread_t thread_default;
    pthread_t thread_read;
    pthread_t thread_write;

    memset(&global, 0, sizeof(global));
    memset(&fuse_default, 0, sizeof(fuse_default));
    memset(&fuse_read, 0, sizeof(fuse_read));
    memset(&fuse_write, 0, sizeof(fuse_write));
    memset(&handler_default, 0, sizeof(handler_default));
    memset(&handler_read, 0, sizeof(handler_read));
    memset(&handler_write, 0, sizeof(handler_write));

    pthread_mutex_init(&global.lock, NULL);
    global.package_to_appid = new AppIdMap;
    global.uid = uid;
    global.gid = gid;
    global.multi_user = multi_user;
    global.next_generation = 0;
    global.inode_ctr = 1;

    memset(&global.root, 0, sizeof(global.root));
    global.root.nid = FUSE_ROOT_ID; /* 1 */
    global.root.refcount = 2;
    global.root.namelen = strlen(source_path);
    global.root.name = strdup(source_path);
    global.root.userid = userid;
    global.root.uid = AID_ROOT;
    global.root.under_android = false;

    // Clang static analyzer think strcpy potentially overwrites other fields
    // in global. Use snprintf() to mute the false warning.
    snprintf(global.source_path, sizeof(global.source_path), "%s", source_path);

    if (multi_user) {
        global.root.perm = PERM_PRE_ROOT;
        snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
    } else {
        global.root.perm = PERM_ROOT;
        snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
    }

    fuse_default.global = &global;
    fuse_read.global = &global;
    fuse_write.global = &global;

    global.fuse_default = &fuse_default;
    global.fuse_read = &fuse_read;
    global.fuse_write = &fuse_write;

    snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
    snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
    snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);

    handler_default.fuse = &fuse_default;
    handler_read.fuse = &fuse_read;
    handler_write.fuse = &fuse_write;

    handler_default.token = 0;
    handler_read.token = 1;
    handler_write.token = 2;

    umask(0);

    if (multi_user) {
        /* Multi-user storage is fully isolated per user, so "other"
         * permissions are completely masked off. */
        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
                || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
            PLOG(FATAL) << "failed to fuse_setup";
        }
    } else {
        /* Physical storage is readable by all users on device, but
         * the Android directories are masked off to a single user
         * deep inside attr_from_stat(). */
        if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
                || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
                || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
            PLOG(FATAL) << "failed to fuse_setup";
        }
    }

    // Will abort if priv-dropping fails.
    drop_privs(uid, gid);

    if (multi_user) {
        fs_prepare_dir(global.obb_path, 0775, uid, gid);
    }

    if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
            || pthread_create(&thread_read, NULL, start_handler, &handler_read)
            || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
        LOG(FATAL) << "failed to pthread_create";
    }

    watch_package_list(&global);
    LOG(FATAL) << "terminated prematurely";
}

static bool sdcardfs_setup(const std::string& source_path, const std::string& dest_path,
static bool sdcardfs_setup(const std::string& source_path, const std::string& dest_path,
                           uid_t fsuid, gid_t fsgid, bool multi_user, userid_t userid, gid_t gid,
                           uid_t fsuid, gid_t fsgid, bool multi_user, userid_t userid, gid_t gid,
                           mode_t mask, bool derive_gid, bool default_normal) {
                           mode_t mask, bool derive_gid, bool default_normal) {
@@ -407,41 +147,6 @@ static void run_sdcardfs(const std::string& source_path, const std::string& labe
    exit(0);
    exit(0);
}
}


static bool supports_sdcardfs(void) {
    std::string filesystems;
    if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) {
        PLOG(ERROR) << "Could not read /proc/filesystems";
        return false;
    }
    for (const auto& fs : android::base::Split(filesystems, "\n")) {
        if (fs.find("sdcardfs") != std::string::npos) return true;
    }
    return false;
}

static bool should_use_sdcardfs(void) {
    char property[PROPERTY_VALUE_MAX];

    // Allow user to have a strong opinion about state
    property_get(PROP_SDCARDFS_USER, property, "");
    if (!strcmp(property, "force_on")) {
        LOG(WARNING) << "User explicitly enabled sdcardfs";
        return supports_sdcardfs();
    } else if (!strcmp(property, "force_off")) {
        LOG(WARNING) << "User explicitly disabled sdcardfs";
        return false;
    }

    // Fall back to device opinion about state
    if (property_get_bool(PROP_SDCARDFS_DEVICE, true)) {
        LOG(WARNING) << "Device explicitly enabled sdcardfs";
        return supports_sdcardfs();
    } else {
        LOG(WARNING) << "Device explicitly disabled sdcardfs";
        return false;
    }
}

static int usage() {
static int usage() {
    LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
    LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
               << "    -u: specify UID to run as"
               << "    -u: specify UID to run as"
@@ -536,11 +241,7 @@ int main(int argc, char **argv) {
        sleep(1);
        sleep(1);
    }
    }


    if (should_use_sdcardfs()) {
    run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid,
    run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid,
                 default_normal);
                 default_normal);
    } else {
        run(source_path, label, uid, gid, userid, multi_user, full_write);
    }
    return 1;
    return 1;
}
}