blob: aa368492dcd70a4be43115b8161da22802d1f469 [file] [log] [blame]
Jiyong Park68660412019-01-16 23:00:59 +09001/*
2 * Copyright (C) 2019 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#include "mount_namespace.h"
18
19#include <sys/mount.h>
20
21#include <string>
22#include <vector>
23
Jiyong Park8502ed32019-02-25 22:18:37 +090024#include <ApexProperties.sysprop.h>
Jiyong Park68660412019-01-16 23:00:59 +090025#include <android-base/file.h>
26#include <android-base/logging.h>
27#include <android-base/properties.h>
Jooyung Han5bb9d212019-11-25 13:50:44 +090028#include <android-base/result.h>
Jiyong Park68660412019-01-16 23:00:59 +090029#include <android-base/unique_fd.h>
Jiyong Park648ae3a2019-12-08 00:25:15 +090030#include <apex_manifest.pb.h>
Jiyong Park68660412019-01-16 23:00:59 +090031
Tom Cherry7205c622020-01-29 14:09:24 -080032#include "property_service.h"
Jiyong Park68660412019-01-16 23:00:59 +090033#include "util.h"
34
35namespace android {
36namespace init {
37namespace {
38
Martijn Coenenc70c0662020-01-10 15:42:15 +010039static bool BindMount(const std::string& source, const std::string& mount_point,
40 bool recursive = false) {
41 unsigned long mountflags = MS_BIND;
42 if (recursive) {
43 mountflags |= MS_REC;
44 }
45 if (mount(source.c_str(), mount_point.c_str(), nullptr, mountflags, nullptr) == -1) {
46 PLOG(ERROR) << "Failed to bind mount " << source;
47 return false;
48 }
49 return true;
50}
51
Jiyong Park68660412019-01-16 23:00:59 +090052static bool MakeShared(const std::string& mount_point, bool recursive = false) {
53 unsigned long mountflags = MS_SHARED;
54 if (recursive) {
55 mountflags |= MS_REC;
56 }
57 if (mount(nullptr, mount_point.c_str(), nullptr, mountflags, nullptr) == -1) {
58 PLOG(ERROR) << "Failed to change propagation type to shared";
59 return false;
60 }
61 return true;
62}
63
Martijn Coenenc70c0662020-01-10 15:42:15 +010064static bool MakeSlave(const std::string& mount_point, bool recursive = false) {
65 unsigned long mountflags = MS_SLAVE;
66 if (recursive) {
67 mountflags |= MS_REC;
68 }
69 if (mount(nullptr, mount_point.c_str(), nullptr, mountflags, nullptr) == -1) {
70 PLOG(ERROR) << "Failed to change propagation type to slave";
71 return false;
72 }
73 return true;
74}
75
Jiyong Park68660412019-01-16 23:00:59 +090076static bool MakePrivate(const std::string& mount_point, bool recursive = false) {
77 unsigned long mountflags = MS_PRIVATE;
78 if (recursive) {
79 mountflags |= MS_REC;
80 }
81 if (mount(nullptr, mount_point.c_str(), nullptr, mountflags, nullptr) == -1) {
82 PLOG(ERROR) << "Failed to change propagation type to private";
83 return false;
84 }
85 return true;
86}
87
88static int OpenMountNamespace() {
89 int fd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
90 if (fd < 0) {
91 PLOG(ERROR) << "Cannot open fd for current mount namespace";
92 }
93 return fd;
94}
95
96static std::string GetMountNamespaceId() {
97 std::string ret;
98 if (!android::base::Readlink("/proc/self/ns/mnt", &ret)) {
99 PLOG(ERROR) << "Failed to read namespace ID";
100 return "";
101 }
102 return ret;
103}
104
Jiyong Park8502ed32019-02-25 22:18:37 +0900105static bool IsApexUpdatable() {
106 static bool updatable = android::sysprop::ApexProperties::updatable().value_or(false);
107 return updatable;
Jiyong Park68660412019-01-16 23:00:59 +0900108}
109
Jooyung Han5bb9d212019-11-25 13:50:44 +0900110static Result<void> MountDir(const std::string& path, const std::string& mount_path) {
Satoshi Niwa1eb300d2020-01-20 18:00:49 +0900111 if (int ret = mkdir(mount_path.c_str(), 0755); ret != 0 && errno != EEXIST) {
Jooyung Han5bb9d212019-11-25 13:50:44 +0900112 return ErrnoError() << "Could not create mount point " << mount_path;
113 }
114 if (mount(path.c_str(), mount_path.c_str(), nullptr, MS_BIND, nullptr) != 0) {
115 return ErrnoError() << "Could not bind mount " << path << " to " << mount_path;
116 }
117 return {};
118}
119
Jiyong Park648ae3a2019-12-08 00:25:15 +0900120static Result<std::string> GetApexName(const std::string& apex_dir) {
121 const std::string manifest_path = apex_dir + "/apex_manifest.pb";
122 std::string content;
123 if (!android::base::ReadFileToString(manifest_path, &content)) {
124 return Error() << "Failed to read manifest file: " << manifest_path;
125 }
126 apex::proto::ApexManifest manifest;
127 if (!manifest.ParseFromString(content)) {
128 return Error() << "Can't parse manifest file: " << manifest_path;
129 }
130 return manifest.name();
131}
132
Jooyung Han5bb9d212019-11-25 13:50:44 +0900133static Result<void> ActivateFlattenedApexesFrom(const std::string& from_dir,
134 const std::string& to_dir) {
135 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(from_dir.c_str()), closedir);
136 if (!dir) {
137 return {};
138 }
139 dirent* entry;
140 while ((entry = readdir(dir.get())) != nullptr) {
141 if (entry->d_name[0] == '.') continue;
142 if (entry->d_type == DT_DIR) {
143 const std::string apex_path = from_dir + "/" + entry->d_name;
Jiyong Park648ae3a2019-12-08 00:25:15 +0900144 const auto apex_name = GetApexName(apex_path);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900145 if (!apex_name.ok()) {
Jiyong Park648ae3a2019-12-08 00:25:15 +0900146 LOG(ERROR) << apex_path << " is not an APEX directory: " << apex_name.error();
147 continue;
148 }
149 const std::string mount_path = to_dir + "/" + (*apex_name);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900150 if (auto result = MountDir(apex_path, mount_path); !result.ok()) {
Jooyung Han5bb9d212019-11-25 13:50:44 +0900151 return result;
152 }
153 }
154 }
155 return {};
156}
157
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900158static bool ActivateFlattenedApexesIfPossible() {
159 if (IsRecoveryMode() || IsApexUpdatable()) {
160 return true;
161 }
162
Jooyung Han5bb9d212019-11-25 13:50:44 +0900163 const std::string kApexTop = "/apex";
164 const std::vector<std::string> kBuiltinDirsForApexes = {
165 "/system/apex",
166 "/system_ext/apex",
167 "/product/apex",
168 "/vendor/apex",
169 };
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900170
Jooyung Han5bb9d212019-11-25 13:50:44 +0900171 for (const auto& dir : kBuiltinDirsForApexes) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900172 if (auto result = ActivateFlattenedApexesFrom(dir, kApexTop); !result.ok()) {
Jooyung Han5bb9d212019-11-25 13:50:44 +0900173 LOG(ERROR) << result.error();
174 return false;
175 }
176 }
Jiyong Park648ae3a2019-12-08 00:25:15 +0900177 return true;
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900178}
179
Kiyoung Kime4d3f212019-12-16 14:31:04 +0900180static Result<void> MountLinkerConfigForDefaultNamespace() {
181 // No need to mount linkerconfig for default mount namespace if the path does not exist (which
182 // would mean it is already mounted)
183 if (access("/linkerconfig/default", 0) != 0) {
184 return {};
185 }
186
187 if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
188 return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
189 }
190
191 return {};
192}
193
Jiyong Park68660412019-01-16 23:00:59 +0900194static android::base::unique_fd bootstrap_ns_fd;
195static android::base::unique_fd default_ns_fd;
196
197static std::string bootstrap_ns_id;
198static std::string default_ns_id;
199
200} // namespace
201
202bool SetupMountNamespaces() {
203 // Set the propagation type of / as shared so that any mounting event (e.g.
204 // /data) is by default visible to all processes. When private mounting is
205 // needed for /foo/bar, then we will make /foo/bar as a mount point (by
206 // bind-mounting by to itself) and set the propagation type of the mount
207 // point to private.
208 if (!MakeShared("/", true /*recursive*/)) return false;
209
Jiyong Park7b4801a2019-02-25 16:41:38 +0900210 // /apex is a private mountpoint to give different sets of APEXes for
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +0900211 // the bootstrap and default mount namespaces. The processes running with
212 // the bootstrap namespace get APEXes from the read-only partition.
213 if (!(MakePrivate("/apex"))) return false;
214
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900215 // /linkerconfig is a private mountpoint to give a different linker configuration
216 // based on the mount namespace. Subdirectory will be bind-mounted based on current mount
217 // namespace
218 if (!(MakePrivate("/linkerconfig"))) return false;
219
Martijn Coenenc70c0662020-01-10 15:42:15 +0100220 // The two mount namespaces present challenges for scoped storage, because
221 // vold, which is responsible for most of the mounting, lives in the
222 // bootstrap mount namespace, whereas most other daemons and all apps live
223 // in the default namespace. Scoped storage has a need for a
224 // /mnt/installer view that is a slave bind mount of /mnt/user - in other
225 // words, all mounts under /mnt/user should automatically show up under
226 // /mnt/installer. However, additional mounts done under /mnt/installer
227 // should not propagate back to /mnt/user. In a single mount namespace
228 // this is easy to achieve, by simply marking the /mnt/installer a slave
229 // bind mount. Unfortunately, if /mnt/installer is only created and
230 // bind mounted after the two namespaces are created below, we end up
231 // with the following situation:
232 // /mnt/user and /mnt/installer share the same peer group in both the
233 // bootstrap and default namespaces. Marking /mnt/installer slave in either
234 // namespace means that it won't propagate events to the /mnt/installer in
235 // the other namespace, which is still something we require - vold is the
236 // one doing the mounting under /mnt/installer, and those mounts should
237 // show up in the default namespace as well.
238 //
239 // The simplest solution is to do the bind mount before the two namespaces
240 // are created: the effect is that in both namespaces, /mnt/installer is a
241 // slave to the /mnt/user mount, and at the same time /mnt/installer in the
242 // bootstrap namespace shares a peer group with /mnt/installer in the
243 // default namespace.
244 if (!mkdir_recursive("/mnt/user", 0755)) return false;
245 if (!mkdir_recursive("/mnt/installer", 0755)) return false;
246 if (!(BindMount("/mnt/user", "/mnt/installer", true))) return false;
247 // First, make /mnt/installer a slave bind mount
248 if (!(MakeSlave("/mnt/installer"))) return false;
249 // Then, make it shared again - effectively creating a new peer group, that
250 // will be inherited by new mount namespaces.
251 if (!(MakeShared("/mnt/installer"))) return false;
252
Jiyong Park68660412019-01-16 23:00:59 +0900253 bootstrap_ns_fd.reset(OpenMountNamespace());
254 bootstrap_ns_id = GetMountNamespaceId();
255
Jiyong Park7b4801a2019-02-25 16:41:38 +0900256 // When APEXes are updatable (e.g. not-flattened), we create separate mount
Jiyong Park68660412019-01-16 23:00:59 +0900257 // namespaces for processes that are started before and after the APEX is
Jiyong Park7b4801a2019-02-25 16:41:38 +0900258 // activated by apexd. In the namespace for pre-apexd processes, small
259 // number of essential APEXes (e.g. com.android.runtime) are activated.
260 // In the namespace for post-apexd processes, all APEXes are activated.
Jiyong Park68660412019-01-16 23:00:59 +0900261 bool success = true;
Jiyong Park8502ed32019-02-25 22:18:37 +0900262 if (IsApexUpdatable() && !IsRecoveryMode()) {
Jiyong Park68660412019-01-16 23:00:59 +0900263 // Creating a new namespace by cloning, saving, and switching back to
264 // the original namespace.
265 if (unshare(CLONE_NEWNS) == -1) {
266 PLOG(ERROR) << "Cannot create mount namespace";
267 return false;
268 }
269 default_ns_fd.reset(OpenMountNamespace());
270 default_ns_id = GetMountNamespaceId();
271
Jiyong Park68660412019-01-16 23:00:59 +0900272 if (setns(bootstrap_ns_fd.get(), CLONE_NEWNS) == -1) {
273 PLOG(ERROR) << "Cannot switch back to bootstrap mount namespace";
274 return false;
275 }
276 } else {
277 // Otherwise, default == bootstrap
278 default_ns_fd.reset(OpenMountNamespace());
279 default_ns_id = GetMountNamespaceId();
280 }
281
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900282 success &= ActivateFlattenedApexesIfPossible();
283
Jiyong Park68660412019-01-16 23:00:59 +0900284 LOG(INFO) << "SetupMountNamespaces done";
285 return success;
286}
287
288bool SwitchToDefaultMountNamespace() {
289 if (IsRecoveryMode()) {
290 // we don't have multiple namespaces in recovery mode
291 return true;
292 }
293 if (default_ns_id != GetMountNamespaceId()) {
Tom Cherry7205c622020-01-29 14:09:24 -0800294 // The property service thread and its descendent threads must be in the correct mount
295 // namespace to call Service::Start(), however setns() only operates on a single thread and
296 // fails when secondary threads attempt to join the same mount namespace. Therefore, we
297 // must join the property service thread and its descendents before the setns() call. Those
298 // threads are then started again after the setns() call, and they'll be in the proper
299 // namespace.
300 PausePropertyService();
301
Jiyong Park68660412019-01-16 23:00:59 +0900302 if (setns(default_ns_fd.get(), CLONE_NEWNS) == -1) {
303 PLOG(ERROR) << "Failed to switch back to the default mount namespace.";
304 return false;
305 }
Kiyoung Kime4d3f212019-12-16 14:31:04 +0900306
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900307 if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
Kiyoung Kime4d3f212019-12-16 14:31:04 +0900308 LOG(ERROR) << result.error();
309 return false;
310 }
Tom Cherry7205c622020-01-29 14:09:24 -0800311
312 ResumePropertyService();
Jiyong Park68660412019-01-16 23:00:59 +0900313 }
314
Jiyong Parkdcbaf9f2019-02-22 22:15:25 +0900315 LOG(INFO) << "Switched to default mount namespace";
316 return true;
317}
318
Jiyong Park68660412019-01-16 23:00:59 +0900319bool SwitchToBootstrapMountNamespaceIfNeeded() {
320 if (IsRecoveryMode()) {
321 // we don't have multiple namespaces in recovery mode
322 return true;
323 }
324 if (bootstrap_ns_id != GetMountNamespaceId() && bootstrap_ns_fd.get() != -1 &&
Jiyong Park8502ed32019-02-25 22:18:37 +0900325 IsApexUpdatable()) {
Jiyong Park68660412019-01-16 23:00:59 +0900326 if (setns(bootstrap_ns_fd.get(), CLONE_NEWNS) == -1) {
327 PLOG(ERROR) << "Failed to switch to bootstrap mount namespace.";
328 return false;
329 }
Jiyong Park68660412019-01-16 23:00:59 +0900330 }
331 return true;
332}
333
334} // namespace init
335} // namespace android