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_prepostinstall.h"
20
21 #include <algorithm>
22 #include <vector>
23
24 #include <fcntl.h>
25 #include <sys/mount.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <unistd.h>
30
31 #include <android-base/logging.h>
32 #include <android-base/macros.h>
33 #include <android-base/scopeguard.h>
34 #include <android-base/strings.h>
35
36 #include "apex_database.h"
37 #include "apex_file.h"
38 #include "apexd.h"
39 #include "apexd_private.h"
40 #include "apexd_utils.h"
41 #include "string_log.h"
42
43 using android::base::Error;
44 using android::base::Result;
45
46 namespace android {
47 namespace apex {
48
49 namespace {
50
51 using MountedApexData = MountedApexDatabase::MountedApexData;
52
CloseSTDDescriptors()53 void CloseSTDDescriptors() {
54 // exec()d process will reopen STD* file descriptors as
55 // /dev/null
56 close(STDIN_FILENO);
57 close(STDOUT_FILENO);
58 close(STDERR_FILENO);
59 }
60
61 // Instead of temp mounting inside this fuction, we can make a caller do it.
62 // This will align with the plan of extending temp mounting to provide a
63 // way to run additional pre-reboot verification of an APEX.
64 // TODO(ioffe): pass mount points instead of apex files.
65 template <typename Fn>
StageFnInstall(const std::vector<ApexFile> & apexes,Fn fn,const char * arg,const char * name)66 Result<void> StageFnInstall(const std::vector<ApexFile>& apexes, Fn fn,
67 const char* arg, const char* name) {
68 // TODO: Support a session with more than one pre-install hook.
69 int hook_idx = -1;
70 for (size_t i = 0; i < apexes.size(); i++) {
71 if (!(apexes[i].GetManifest().*fn)().empty()) {
72 if (hook_idx != -1) {
73 return Error() << "Missing support for multiple " << name << " hooks";
74 }
75 hook_idx = i;
76 }
77 }
78 CHECK(hook_idx != -1);
79 LOG(VERBOSE) << name << " for " << apexes[hook_idx].GetPath();
80
81 std::vector<MountedApexData> mounted_apexes;
82 std::vector<std::string> activation_dirs;
83 auto preinstall_guard = android::base::make_scope_guard([&]() {
84 for (const auto& mount : mounted_apexes) {
85 Result<void> st = apexd_private::Unmount(mount);
86 if (!st.ok()) {
87 LOG(ERROR) << "Failed to unmount " << mount.full_path << " from "
88 << mount.mount_point << " after " << name << ": "
89 << st.error();
90 }
91 }
92 for (const std::string& active_point : activation_dirs) {
93 if (0 != rmdir(active_point.c_str())) {
94 PLOG(ERROR) << "Could not delete temporary active point "
95 << active_point;
96 }
97 }
98 });
99
100 for (const ApexFile& apex : apexes) {
101 // 1) Mount the package.
102 std::string mount_point =
103 apexd_private::GetPackageTempMountPoint(apex.GetManifest());
104
105 auto mount_data = apexd_private::TempMountPackage(apex, mount_point);
106 if (!mount_data.ok()) {
107 return mount_data.error();
108 }
109 mounted_apexes.push_back(std::move(*mount_data));
110
111 // Given the fact, that we only allow updates of existing APEXes, all the
112 // activation points will always be already created. Only scenario, when it
113 // won't be the case might be apexservice_test. But even then, it might be
114 // safer to move active_point creation logic to run after unshare.
115 // TODO(ioffe): move creation of activation points inside RunFnInstall?
116 // 2) Ensure there is an activation point, and we will clean it up.
117 std::string active_point =
118 apexd_private::GetActiveMountPoint(apex.GetManifest());
119 if (0 == mkdir(active_point.c_str(), kMkdirMode)) {
120 activation_dirs.emplace_back(std::move(active_point));
121 } else {
122 int saved_errno = errno;
123 if (saved_errno != EEXIST) {
124 return Error() << "Unable to create mount point" << active_point << ": "
125 << strerror(saved_errno);
126 }
127 }
128 }
129
130 // 3) Create invocation args.
131 std::vector<std::string> args{
132 "/system/bin/apexd", arg,
133 mounted_apexes[hook_idx].mount_point, // Make the APEX with hook first.
134 };
135 for (size_t i = 0; i < mounted_apexes.size(); i++) {
136 if ((int)i != hook_idx) {
137 args.push_back(mounted_apexes[i].mount_point);
138 }
139 }
140
141 std::string error_msg;
142 int res = ForkAndRun(args, &error_msg);
143 return res == 0 ? Result<void>{} : Error() << error_msg;
144 }
145
146 template <typename Fn>
RunFnInstall(char ** in_argv,Fn fn,const char * name)147 int RunFnInstall(char** in_argv, Fn fn, const char* name) {
148 // 1) Unshare.
149 if (unshare(CLONE_NEWNS) != 0) {
150 PLOG(ERROR) << "Failed to unshare() for apex " << name;
151 _exit(200);
152 }
153
154 // 2) Make everything private, so that our (and hook's) changes do not
155 // propagate.
156 if (mount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr) == -1) {
157 PLOG(ERROR) << "Failed to mount private.";
158 _exit(201);
159 }
160
161 std::string hook_path;
162 {
163 auto bind_fn = [&fn, name](const std::string& mount_point) {
164 std::string hook;
165 std::string active_point;
166 {
167 Result<ApexManifest> manifest_or =
168 ReadManifest(mount_point + "/" + kManifestFilenamePb);
169 if (!manifest_or.ok()) {
170 LOG(ERROR) << "Could not read manifest from " << mount_point << "/"
171 << kManifestFilenamePb << " for " << name << ": "
172 << manifest_or.error();
173 // Fallback to Json manifest if present.
174 LOG(ERROR) << "Trying to find a JSON manifest";
175 manifest_or = ReadManifest(mount_point + "/" + kManifestFilenameJson);
176 if (!manifest_or.ok()) {
177 LOG(ERROR) << "Could not read manifest from " << mount_point << "/"
178 << kManifestFilenameJson << " for " << name << ": "
179 << manifest_or.error();
180 _exit(202);
181 }
182 }
183 const auto& manifest = *manifest_or;
184 hook = (manifest.*fn)();
185 active_point = apexd_private::GetActiveMountPoint(manifest);
186 }
187
188 // 3) Activate the new apex.
189 Result<void> bind_status =
190 apexd_private::BindMount(active_point, mount_point);
191 if (!bind_status.ok()) {
192 LOG(ERROR) << "Failed to bind-mount " << mount_point << " to "
193 << active_point << ": " << bind_status.error();
194 _exit(203);
195 }
196
197 return std::make_pair(active_point, hook);
198 };
199
200 // First/main APEX.
201 auto [active_point, hook] = bind_fn(in_argv[2]);
202 hook_path = active_point + "/" + hook;
203
204 for (size_t i = 3;; ++i) {
205 if (in_argv[i] == nullptr) {
206 break;
207 }
208 bind_fn(in_argv[i]); // Ignore result, hook will be empty.
209 }
210 }
211
212 // 4) Run the hook.
213
214 // For now, just run sh. But this probably needs to run the new linker.
215 std::vector<std::string> args{
216 hook_path,
217 };
218 std::vector<const char*> argv;
219 argv.resize(args.size() + 1, nullptr);
220 std::transform(args.begin(), args.end(), argv.begin(),
221 [](const std::string& in) { return in.c_str(); });
222
223 LOG(ERROR) << "execv of " << android::base::Join(args, " ");
224
225 // Close all file descriptors. They are coming from the caller, we do not
226 // want to pass them on across our fork/exec into a different domain.
227 CloseSTDDescriptors();
228
229 execv(argv[0], const_cast<char**>(argv.data()));
230 PLOG(ERROR) << "execv of " << android::base::Join(args, " ") << " failed";
231 _exit(204);
232 }
233
234 } // namespace
235
StagePreInstall(const std::vector<ApexFile> & apexes)236 Result<void> StagePreInstall(const std::vector<ApexFile>& apexes) {
237 return StageFnInstall(apexes, &ApexManifest::preinstallhook, "--pre-install",
238 "pre-install");
239 }
240
RunPreInstall(char ** in_argv)241 int RunPreInstall(char** in_argv) {
242 return RunFnInstall(in_argv, &ApexManifest::preinstallhook, "pre-install");
243 }
244
StagePostInstall(const std::vector<ApexFile> & apexes)245 Result<void> StagePostInstall(const std::vector<ApexFile>& apexes) {
246 return StageFnInstall(apexes, &ApexManifest::postinstallhook,
247 "--post-install", "post-install");
248 }
249
RunPostInstall(char ** in_argv)250 int RunPostInstall(char** in_argv) {
251 return RunFnInstall(in_argv, &ApexManifest::postinstallhook, "post-install");
252 }
253
254 } // namespace apex
255 } // namespace android
256