1 /*
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
29 using android::base::ErrnoError;
30 using android::base::Result;
31
32 namespace android {
33 namespace apex {
34 namespace apexd_private {
35
BindMount(const std::string & target,const std::string & source)36 Result<void> BindMount(const std::string& target, const std::string& source) {
37 LOG(VERBOSE) << "Creating bind-mount for " << target << " for " << source;
38 // Ensure the directory exists, try to unmount.
39 {
40 bool exists;
41 bool is_dir;
42 {
43 struct stat buf;
44 if (stat(target.c_str(), &buf) != 0) {
45 if (errno == ENOENT) {
46 exists = false;
47 is_dir = false;
48 } else {
49 PLOG(ERROR) << "Could not stat target directory " << target;
50 // Still attempt to bind-mount.
51 exists = true;
52 is_dir = true;
53 }
54 } else {
55 exists = true;
56 is_dir = S_ISDIR(buf.st_mode);
57 }
58 }
59
60 // Ensure that it is a folder.
61 if (exists && !is_dir) {
62 LOG(WARNING) << target << " is not a directory, attempting to fix";
63 if (unlink(target.c_str()) != 0) {
64 PLOG(ERROR) << "Failed to unlink " << target;
65 // Try mkdir, anyways.
66 }
67 exists = false;
68 }
69 // And create it if necessary.
70 if (!exists) {
71 LOG(VERBOSE) << "Creating mountpoint " << target;
72 if (mkdir(target.c_str(), kMkdirMode) != 0) {
73 return ErrnoError() << "Could not create mountpoint " << target;
74 }
75 };
76 // Unmount any active bind-mount.
77 if (exists) {
78 int rc = umount2(target.c_str(), UMOUNT_NOFOLLOW);
79 if (rc != 0 && errno != EINVAL) {
80 // Log error but ignore.
81 PLOG(ERROR) << "Could not unmount " << target;
82 }
83 }
84 }
85
86 LOG(VERBOSE) << "Bind-mounting " << source << " to " << target;
87 if (mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr) == 0) {
88 return {};
89 }
90 return ErrnoError() << "Could not bind-mount " << source << " to " << target;
91 }
92
93 } // namespace apexd_private
94 } // namespace apex
95 } // namespace android
96