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(b/158470432): 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(b/158470023): consider supporting a session with more than one
69   //   pre-install hook.
70   int hook_idx = -1;
71   for (size_t i = 0; i < apexes.size(); i++) {
72     if (!(apexes[i].GetManifest().*fn)().empty()) {
73       if (hook_idx != -1) {
74         return Error() << "Missing support for multiple " << name << " hooks";
75       }
76       hook_idx = i;
77     }
78   }
79   CHECK(hook_idx != -1);
80   LOG(VERBOSE) << name << " for " << apexes[hook_idx].GetPath();
81 
82   std::vector<MountedApexData> mounted_apexes;
83   std::vector<std::string> activation_dirs;
84   auto preinstall_guard = android::base::make_scope_guard([&]() {
85     for (const auto& mount : mounted_apexes) {
86       Result<void> st = apexd_private::Unmount(mount);
87       if (!st.ok()) {
88         LOG(ERROR) << "Failed to unmount " << mount.full_path << " from "
89                    << mount.mount_point << " after " << name << ": "
90                    << st.error();
91       }
92     }
93     for (const std::string& active_point : activation_dirs) {
94       if (0 != rmdir(active_point.c_str())) {
95         PLOG(ERROR) << "Could not delete temporary active point "
96                     << active_point;
97       }
98     }
99   });
100 
101   for (const ApexFile& apex : apexes) {
102     // 1) Mount the package.
103     std::string mount_point =
104         apexd_private::GetPackageTempMountPoint(apex.GetManifest());
105 
106     auto mount_data = apexd_private::TempMountPackage(apex, mount_point);
107     if (!mount_data.ok()) {
108       return mount_data.error();
109     }
110     mounted_apexes.push_back(std::move(*mount_data));
111 
112     // Given the fact, that we only allow updates of existing APEXes, all the
113     // activation points will always be already created. Only scenario, when it
114     // won't be the case might be apexservice_test. But even then, it might be
115     // safer to move active_point creation logic to run after unshare.
116     // TODO(b/158470432): maybe move creation of activation points inside
117     //   RunFnInstall?
118     // 2) Ensure there is an activation point, and we will clean it up.
119     std::string active_point =
120         apexd_private::GetActiveMountPoint(apex.GetManifest());
121     if (0 == mkdir(active_point.c_str(), kMkdirMode)) {
122       activation_dirs.emplace_back(std::move(active_point));
123     } else {
124       int saved_errno = errno;
125       if (saved_errno != EEXIST) {
126         return Error() << "Unable to create mount point" << active_point << ": "
127                        << strerror(saved_errno);
128       }
129     }
130   }
131 
132   // 3) Create invocation args.
133   std::vector<std::string> args{
134       "/system/bin/apexd", arg,
135       mounted_apexes[hook_idx].mount_point,  // Make the APEX with hook first.
136   };
137   for (size_t i = 0; i < mounted_apexes.size(); i++) {
138     if ((int)i != hook_idx) {
139       args.push_back(mounted_apexes[i].mount_point);
140     }
141   }
142 
143   return ForkAndRun(args);
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