blob: 527332dbf6cfb5816bd375bb14eb820f1ad2e47f [file] [log] [blame]
Andreas Gampe27adafa2018-11-29 12:20:08 -08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "apexd"
18
19#include "apexd_private.h"
20
21#include <sys/mount.h>
22#include <sys/stat.h>
23
24#include <android-base/logging.h>
25#include <android-base/macros.h>
26
27#include "string_log.h"
28
29namespace android {
30namespace apex {
31namespace apexd_private {
32
33Status BindMount(const std::string& target, const std::string& source) {
34 LOG(VERBOSE) << "Creating bind-mount for " << target << " for " << source;
35 // Ensure the directory exists, try to unmount.
36 {
37 bool exists;
38 bool is_dir;
39 {
40 struct stat buf;
41 if (stat(target.c_str(), &buf) != 0) {
42 if (errno == ENOENT) {
43 exists = false;
44 is_dir = false;
45 } else {
46 PLOG(ERROR) << "Could not stat target directory " << target;
47 // Still attempt to bind-mount.
48 exists = true;
49 is_dir = true;
50 }
51 } else {
52 exists = true;
53 is_dir = S_ISDIR(buf.st_mode);
54 }
55 }
56
57 // Ensure that it is a folder.
58 if (exists && !is_dir) {
59 LOG(WARNING) << target << " is not a directory, attempting to fix";
60 if (unlink(target.c_str()) != 0) {
61 PLOG(ERROR) << "Failed to unlink " << target;
62 // Try mkdir, anyways.
63 }
64 exists = false;
65 }
66 // And create it if necessary.
67 if (!exists) {
68 LOG(VERBOSE) << "Creating mountpoint " << target;
69 if (mkdir(target.c_str(), kMkdirMode) != 0) {
70 return Status::Fail(PStringLog()
71 << "Could not create mountpoint " << target);
72 }
73 };
74 // Unmount any active bind-mount.
75 if (exists) {
76 int rc = umount2(target.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH);
77 if (rc != 0 && errno != EINVAL) {
78 // Log error but ignore.
79 PLOG(ERROR) << "Could not unmount " << target;
80 }
81 }
82 }
83
84 LOG(VERBOSE) << "Bind-mounting " << source << " to " << target;
85 if (mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr) == 0) {
86 return Status::Success();
87 }
88 return Status::Fail(PStringLog()
89 << "Could not bind-mount " << source << " to " << target);
90}
91
92} // namespace apexd_private
93} // namespace apex
94} // namespace android