• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <filesystem>
18 #include <fstream>
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <linux/loop.h>
23 #include <sched.h>
24 #include <sys/mount.h>
25 
26 #include <android-base/errors.h>
27 #include <android-base/logging.h>
28 #include <android-base/macros.h>
29 #include <android-base/result.h>
30 #include <android-base/stringprintf.h>
31 #include <android-base/strings.h>
32 #include <android-base/unique_fd.h>
33 #include <android/apex/ApexInfo.h>
34 #include <android/apex/ApexSessionInfo.h>
35 #include <binder/IServiceManager.h>
36 #include <fstab/fstab.h>
37 #include <libdm/dm.h>
38 #include <selinux/android.h>
39 
40 #include "apex_file.h"
41 #include "apexd_loop.h"
42 #include "apexd_utils.h"
43 #include "session_state.pb.h"
44 
45 #include "com_android_apex.h"
46 
47 namespace android {
48 namespace apex {
49 namespace testing {
50 
IsOk(const android::binder::Status & status)51 inline ::testing::AssertionResult IsOk(const android::binder::Status& status) {
52   if (status.isOk()) {
53     return ::testing::AssertionSuccess() << " is Ok";
54   } else {
55     return ::testing::AssertionFailure()
56            << " failed with " << status.exceptionMessage().c_str();
57   }
58 }
59 
60 MATCHER_P(SessionInfoEq, other, "") {
61   using ::testing::AllOf;
62   using ::testing::Eq;
63   using ::testing::Field;
64 
65   return ExplainMatchResult(
66       AllOf(
67           Field("sessionId", &ApexSessionInfo::sessionId, Eq(other.sessionId)),
68           Field("isUnknown", &ApexSessionInfo::isUnknown, Eq(other.isUnknown)),
69           Field("isVerified", &ApexSessionInfo::isVerified,
70                 Eq(other.isVerified)),
71           Field("isStaged", &ApexSessionInfo::isStaged, Eq(other.isStaged)),
72           Field("isActivated", &ApexSessionInfo::isActivated,
73                 Eq(other.isActivated)),
74           Field("isRevertInProgress", &ApexSessionInfo::isRevertInProgress,
75                 Eq(other.isRevertInProgress)),
76           Field("isActivationFailed", &ApexSessionInfo::isActivationFailed,
77                 Eq(other.isActivationFailed)),
78           Field("isSuccess", &ApexSessionInfo::isSuccess, Eq(other.isSuccess)),
79           Field("isReverted", &ApexSessionInfo::isReverted,
80                 Eq(other.isReverted)),
81           Field("isRevertFailed", &ApexSessionInfo::isRevertFailed,
82                 Eq(other.isRevertFailed))),
83       arg, result_listener);
84 }
85 
86 MATCHER_P(ApexInfoEq, other, "") {
87   using ::testing::AllOf;
88   using ::testing::Eq;
89   using ::testing::Field;
90 
91   return ExplainMatchResult(
92       AllOf(Field("moduleName", &ApexInfo::moduleName, Eq(other.moduleName)),
93             Field("modulePath", &ApexInfo::modulePath, Eq(other.modulePath)),
94             Field("preinstalledModulePath", &ApexInfo::preinstalledModulePath,
95                   Eq(other.preinstalledModulePath)),
96             Field("versionCode", &ApexInfo::versionCode, Eq(other.versionCode)),
97             Field("isFactory", &ApexInfo::isFactory, Eq(other.isFactory)),
98             Field("isActive", &ApexInfo::isActive, Eq(other.isActive))),
99       arg, result_listener);
100 }
101 
102 MATCHER_P(ApexFileEq, other, "") {
103   using ::testing::AllOf;
104   using ::testing::Eq;
105   using ::testing::Property;
106 
107   return ExplainMatchResult(
108       AllOf(Property("path", &ApexFile::GetPath, Eq(other.get().GetPath())),
109             Property("image_offset", &ApexFile::GetImageOffset,
110                      Eq(other.get().GetImageOffset())),
111             Property("image_size", &ApexFile::GetImageSize,
112                      Eq(other.get().GetImageSize())),
113             Property("fs_type", &ApexFile::GetFsType,
114                      Eq(other.get().GetFsType())),
115             Property("public_key", &ApexFile::GetBundledPublicKey,
116                      Eq(other.get().GetBundledPublicKey())),
117             Property("is_compressed", &ApexFile::IsCompressed,
118                      Eq(other.get().IsCompressed()))),
119       arg, result_listener);
120 }
121 
CreateSessionInfo(int session_id)122 inline ApexSessionInfo CreateSessionInfo(int session_id) {
123   ApexSessionInfo info;
124   info.sessionId = session_id;
125   info.isUnknown = false;
126   info.isVerified = false;
127   info.isStaged = false;
128   info.isActivated = false;
129   info.isRevertInProgress = false;
130   info.isActivationFailed = false;
131   info.isSuccess = false;
132   info.isReverted = false;
133   info.isRevertFailed = false;
134   return info;
135 }
136 
137 }  // namespace testing
138 
139 // Must be in apex::android namespace, otherwise gtest won't be able to find it.
PrintTo(const ApexSessionInfo & session,std::ostream * os)140 inline void PrintTo(const ApexSessionInfo& session, std::ostream* os) {
141   *os << "apex_session: {\n";
142   *os << "  sessionId : " << session.sessionId << "\n";
143   *os << "  isUnknown : " << session.isUnknown << "\n";
144   *os << "  isVerified : " << session.isVerified << "\n";
145   *os << "  isStaged : " << session.isStaged << "\n";
146   *os << "  isActivated : " << session.isActivated << "\n";
147   *os << "  isActivationFailed : " << session.isActivationFailed << "\n";
148   *os << "  isSuccess : " << session.isSuccess << "\n";
149   *os << "  isReverted : " << session.isReverted << "\n";
150   *os << "  isRevertFailed : " << session.isRevertFailed << "\n";
151   *os << "}";
152 }
153 
PrintTo(const ApexInfo & apex,std::ostream * os)154 inline void PrintTo(const ApexInfo& apex, std::ostream* os) {
155   *os << "apex_info: {\n";
156   *os << "  moduleName : " << apex.moduleName << "\n";
157   *os << "  modulePath : " << apex.modulePath << "\n";
158   *os << "  preinstalledModulePath : " << apex.preinstalledModulePath << "\n";
159   *os << "  versionCode : " << apex.versionCode << "\n";
160   *os << "  isFactory : " << apex.isFactory << "\n";
161   *os << "  isActive : " << apex.isActive << "\n";
162   *os << "}";
163 }
164 
CompareFiles(const std::string & filename1,const std::string & filename2)165 inline android::base::Result<bool> CompareFiles(const std::string& filename1,
166                                                 const std::string& filename2) {
167   std::ifstream file1(filename1, std::ios::binary);
168   std::ifstream file2(filename2, std::ios::binary);
169 
170   if (file1.bad() || file2.bad()) {
171     return android::base::Error() << "Could not open one of the file";
172   }
173 
174   std::istreambuf_iterator<char> begin1(file1);
175   std::istreambuf_iterator<char> begin2(file2);
176 
177   return std::equal(begin1, std::istreambuf_iterator<char>(), begin2);
178 }
179 
GetCurrentMountNamespace()180 inline android::base::Result<std::string> GetCurrentMountNamespace() {
181   std::string result;
182   if (!android::base::Readlink("/proc/self/ns/mnt", &result)) {
183     return android::base::ErrnoError() << "Failed to read /proc/self/ns/mnt";
184   }
185   return result;
186 }
187 
188 // A helper class to switch back to the original mount namespace of a process
189 // upon exiting current scope.
190 class MountNamespaceRestorer final {
191  public:
MountNamespaceRestorer()192   explicit MountNamespaceRestorer() {
193     original_namespace_.reset(open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC));
194     if (original_namespace_.get() < 0) {
195       PLOG(ERROR) << "Failed to open /proc/self/ns/mnt";
196     }
197   }
198 
~MountNamespaceRestorer()199   ~MountNamespaceRestorer() {
200     if (original_namespace_.get() != -1) {
201       // Since apexd is a multithread process. setns(fd, CLONE_NEWNS) may not
202       // work (fail with EINVAL). Retrying until success fixes it. This is
203       // acceptable since this class is for only tests. In the worst case tests
204       // will hang with bunch of logs.
205       while (setns(original_namespace_.get(), CLONE_NEWNS) == -1) {
206         PLOG(ERROR) << "Failed to switch back to " << original_namespace_.get();
207       }
208     }
209   }
210 
211  private:
212   android::base::unique_fd original_namespace_;
213   DISALLOW_COPY_AND_ASSIGN(MountNamespaceRestorer);
214 };
215 
GetApexMounts()216 inline std::vector<std::string> GetApexMounts() {
217   std::vector<std::string> apex_mounts;
218   std::string mount_info;
219   if (!android::base::ReadFileToString("/proc/self/mountinfo", &mount_info)) {
220     return apex_mounts;
221   }
222   for (const auto& line : android::base::Split(mount_info, "\n")) {
223     std::vector<std::string> tokens = android::base::Split(line, " ");
224     // line format:
225     // mnt_id parent_mnt_id major:minor source target option propagation_type
226     // ex) 33 260:19 / /apex rw,nosuid,nodev -
227     if (tokens.size() >= 7 && android::base::StartsWith(tokens[4], "/apex/")) {
228       apex_mounts.push_back(tokens[4]);
229     }
230   }
231   return apex_mounts;
232 }
233 
234 // Sets up a test environment for unit testing logic around mounting/unmounting
235 // apexes. For examples of usage see apexd_test.cpp
SetUpApexTestEnvironment()236 inline android::base::Result<void> SetUpApexTestEnvironment() {
237   using android::base::ErrnoError;
238 
239   // 1. Switch to new mount namespace.
240   if (unshare(CLONE_NEWNS) != 0) {
241     return ErrnoError() << "Failed to unshare";
242   }
243 
244   // 2. Make everything private, so that changes don't propagate.
245   if (mount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr) == -1) {
246     return ErrnoError() << "Failed to mount / as private";
247   }
248 
249   // 3. Unmount all apexes. This needs to happen in two phases:
250   // Note: unlike regular unmount flow in apexd, we don't destroy dm and loop
251   // devices, since that would've propagated outside of the test environment.
252   std::vector<std::string> apex_mounts = GetApexMounts();
253 
254   // 3a. First unmount all bind mounds (without @version_code).
255   for (const auto& mount : apex_mounts) {
256     if (mount.find('@') == std::string::npos) {
257       if (umount2(mount.c_str(), 0) != 0) {
258         return ErrnoError() << "Failed to unmount " << mount;
259       }
260     }
261   }
262 
263   // 3.b Now unmount versioned mounts.
264   for (const auto& mount : apex_mounts) {
265     if (mount.find('@') != std::string::npos) {
266       if (umount2(mount.c_str(), 0) != 0) {
267         return ErrnoError() << "Failed to unmount " << mount;
268       }
269     }
270   }
271 
272   static constexpr const char* kApexMountForTest = "/mnt/scratch-apex";
273 
274   // Clean up in case previous test left directory behind.
275   if (access(kApexMountForTest, F_OK) == 0) {
276     if (umount2(kApexMountForTest, MNT_FORCE | UMOUNT_NOFOLLOW) != 0) {
277       PLOG(WARNING) << "Failed to unmount " << kApexMountForTest;
278     }
279     if (rmdir(kApexMountForTest) != 0) {
280       return ErrnoError() << "Failed to rmdir " << kApexMountForTest;
281     }
282   }
283 
284   // 4. Create an empty tmpfs that will substitute /apex in tests.
285   if (mkdir(kApexMountForTest, 0755) != 0) {
286     return ErrnoError() << "Failed to mkdir " << kApexMountForTest;
287   }
288 
289   if (mount("tmpfs", kApexMountForTest, "tmpfs", 0, nullptr) == -1) {
290     return ErrnoError() << "Failed to mount " << kApexMountForTest;
291   }
292 
293   // 5. Overlay it  over /apex via bind mount.
294   if (mount(kApexMountForTest, "/apex", nullptr, MS_BIND, nullptr) == -1) {
295     return ErrnoError() << "Failed to bind mount " << kApexMountForTest
296                         << " over /apex";
297   }
298 
299   // Just in case, run restorecon -R on /apex.
300   if (selinux_android_restorecon("/apex", SELINUX_ANDROID_RESTORECON_RECURSE) <
301       0) {
302     return ErrnoError() << "Failed to restorecon /apex";
303   }
304 
305   return {};
306 }
307 
308 // Simpler version of loop::CreateLoopDevice. Uses LOOP_SET_FD/LOOP_SET_STATUS64
309 // instead of LOOP_CONFIGURE.
310 // TODO(b/191244059) use loop::CreateLoopDevice
CreateLoopDeviceForTest(const std::string & filepath)311 inline base::Result<loop::LoopbackDeviceUniqueFd> CreateLoopDeviceForTest(
312     const std::string& filepath) {
313   base::unique_fd ctl_fd(open("/dev/loop-control", O_RDWR | O_CLOEXEC));
314   if (ctl_fd.get() == -1) {
315     return base::ErrnoError() << "Failed to open loop-control";
316   }
317   int num = ioctl(ctl_fd.get(), LOOP_CTL_GET_FREE);
318   if (num == -1) {
319     return base::ErrnoError() << "Failed LOOP_CTL_GET_FREE";
320   }
321   auto loop_device = loop::WaitForDevice(num);
322   if (!loop_device.ok()) {
323     return loop_device.error();
324   }
325   base::unique_fd target_fd(open(filepath.c_str(), O_RDONLY | O_CLOEXEC));
326   if (target_fd.get() == -1) {
327     return base::ErrnoError() << "Failed to open " << filepath;
328   }
329   struct loop_info64 li = {};
330   strlcpy((char*)li.lo_crypt_name, filepath.c_str(), LO_NAME_SIZE);
331   li.lo_flags |= LO_FLAGS_AUTOCLEAR;
332   if (ioctl(loop_device->device_fd.get(), LOOP_SET_FD, target_fd.get()) == -1) {
333     return base::ErrnoError() << "Failed to LOOP_SET_FD";
334   }
335   if (ioctl(loop_device->device_fd.get(), LOOP_SET_STATUS64, &li) == -1) {
336     return base::ErrnoError() << "Failed to LOOP_SET_STATUS64";
337   }
338   return loop_device;
339 }
340 
MountViaLoopDevice(const std::string & filepath,const std::string & mount_point)341 inline base::Result<loop::LoopbackDeviceUniqueFd> MountViaLoopDevice(
342     const std::string& filepath, const std::string& mount_point) {
343   auto loop_device = CreateLoopDeviceForTest(filepath);
344   if (loop_device.ok()) {
345     close(open(mount_point.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
346                0644));
347     if (0 != mount(loop_device->name.c_str(), mount_point.c_str(), nullptr,
348                    MS_BIND, nullptr)) {
349       return base::ErrnoError() << "can't mount.";
350     }
351   }
352   return loop_device;
353 }
354 
355 // Represents a Block APEX in tests, which is represented as a loop-mounted
356 // file. Created with WriteBlockApex() below. On exit, it umounts the mountpoint
357 // first, and then frees the loop-device.
358 struct BlockApex {
359   loop::LoopbackDeviceUniqueFd loop_device;
360   std::string mount_point;
BlockApexBlockApex361   BlockApex(loop::LoopbackDeviceUniqueFd&& loop_device,
362             const std::string& mount_point)
363       : loop_device(std::move(loop_device)), mount_point(mount_point) {}
BlockApexBlockApex364   BlockApex(BlockApex&& other) noexcept {
365     loop_device = std::move(other.loop_device);
366     mount_point = std::move(other.mount_point);
367   }
368   BlockApex& operator=(BlockApex&& other) noexcept {
369     loop_device = std::move(other.loop_device);
370     mount_point = std::move(other.mount_point);
371     return *this;
372   }
~BlockApexBlockApex373   ~BlockApex() {
374     if (loop_device.Get() != -1) {
375       if (umount2(mount_point.c_str(), UMOUNT_NOFOLLOW) != 0) {
376         PLOG(ERROR) << "can't umount.";
377       }
378       loop_device.CloseGood();
379     }
380   }
381 };
382 
WriteBlockApex(const std::string & apex_file,const std::string & apex_path)383 inline base::Result<BlockApex> WriteBlockApex(const std::string& apex_file,
384                                               const std::string& apex_path) {
385   std::string intermediate_path = apex_path + ".intermediate";
386   std::filesystem::copy(apex_file, intermediate_path);
387   auto result = MountViaLoopDevice(intermediate_path, apex_path);
388   if (!result.ok()) {
389     return result.error();
390   }
391   return BlockApex(std::move(*result), apex_path);
392 }
393 
GetBlockDeviceForApex(const std::string & package_id)394 inline android::base::Result<std::string> GetBlockDeviceForApex(
395     const std::string& package_id) {
396   using android::fs_mgr::Fstab;
397   using android::fs_mgr::GetEntryForMountPoint;
398   using android::fs_mgr::ReadFstabFromFile;
399 
400   std::string mount_point = std::string(kApexRoot) + "/" + package_id;
401   Fstab fstab;
402   if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
403     return android::base::Error() << "Failed to read /proc/mounts";
404   }
405   auto entry = GetEntryForMountPoint(&fstab, mount_point);
406   if (entry == nullptr) {
407     return android::base::Error()
408            << "Can't find " << mount_point << " in /proc/mounts";
409   }
410   return entry->blk_device;
411 }
412 
ReadDevice(const std::string & block_device)413 inline android::base::Result<void> ReadDevice(const std::string& block_device) {
414   static constexpr int kBlockSize = 4096;
415   static constexpr size_t kBufSize = 1024 * kBlockSize;
416   std::vector<uint8_t> buffer(kBufSize);
417 
418   android::base::unique_fd fd(
419       TEMP_FAILURE_RETRY(open(block_device.c_str(), O_RDONLY | O_CLOEXEC)));
420   if (fd.get() == -1) {
421     return android::base::ErrnoError() << "Can't open " << block_device;
422   }
423 
424   while (true) {
425     int n = read(fd.get(), buffer.data(), kBufSize);
426     if (n < 0) {
427       return android::base::ErrnoError() << "Failed to read " << block_device;
428     }
429     if (n == 0) {
430       break;
431     }
432   }
433   return {};
434 }
435 
ListChildLoopDevices(const std::string & name)436 inline android::base::Result<std::vector<std::string>> ListChildLoopDevices(
437     const std::string& name) {
438   using android::base::Error;
439   using android::dm::DeviceMapper;
440 
441   DeviceMapper& dm = DeviceMapper::Instance();
442   std::string dm_path;
443   if (!dm.GetDmDevicePathByName(name, &dm_path)) {
444     return Error() << "Failed to get path of dm device " << name;
445   }
446   // It's a little bit sad we can't use ConsumePrefix here :(
447   constexpr std::string_view kDevPrefix = "/dev/";
448   if (!android::base::StartsWith(dm_path, kDevPrefix)) {
449     return Error() << "Illegal path " << dm_path;
450   }
451   dm_path = dm_path.substr(kDevPrefix.length());
452   std::vector<std::string> children;
453   std::string dir = "/sys/" + dm_path + "/slaves";
454   auto status = WalkDir(dir, [&](const auto& entry) {
455     std::error_code ec;
456     if (entry.is_symlink(ec)) {
457       children.push_back("/dev/block/" + entry.path().filename().string());
458     }
459   });
460   if (!status.ok()) {
461     return status.error();
462   }
463   return children;
464 }
465 
466 }  // namespace apex
467 }  // namespace android
468 
469 namespace com {
470 namespace android {
471 namespace apex {
472 
473 namespace testing {
474 
475 // "preinstalledModulePath" is an optional in ApexInfoList.xsd.
476 // getPreinstalledModulePath() should be called when hasPreinstalledModulePath()
477 // returns true. Introducing a simple wrapper which returns optional<string>.
getPreinstalledModulePath(const ApexInfo & obj)478 inline std::optional<std::string> getPreinstalledModulePath(
479     const ApexInfo& obj) {
480   if (obj.hasPreinstalledModulePath()) {
481     return obj.getPreinstalledModulePath();
482   }
483   return std::nullopt;
484 }
485 
486 MATCHER_P(ApexInfoXmlEq, other, "") {
487   using ::testing::AllOf;
488   using ::testing::Eq;
489   using ::testing::ExplainMatchResult;
490   using ::testing::Field;
491   using ::testing::Property;
492   using ::testing::ResultOf;
493 
494   return ExplainMatchResult(
495       AllOf(
496           Property("moduleName", &ApexInfo::getModuleName,
497                    Eq(other.getModuleName())),
498           Property("modulePath", &ApexInfo::getModulePath,
499                    Eq(other.getModulePath())),
500           ResultOf(&getPreinstalledModulePath,
501                    Eq(getPreinstalledModulePath(other))),
502           Property("versionCode", &ApexInfo::getVersionCode,
503                    Eq(other.getVersionCode())),
504           Property("isFactory", &ApexInfo::getIsFactory,
505                    Eq(other.getIsFactory())),
506           Property("isActive", &ApexInfo::getIsActive, Eq(other.getIsActive())),
507           Property("lastUpdateMillis", &ApexInfo::getLastUpdateMillis,
508                    Eq(other.getLastUpdateMillis()))),
509       arg, result_listener);
510 }
511 
512 }  // namespace testing
513 
514 // Must be in com::android::apex namespace for gtest to pick it up.
PrintTo(const ApexInfo & apex,std::ostream * os)515 inline void PrintTo(const ApexInfo& apex, std::ostream* os) {
516   *os << "apex_info: {\n";
517   *os << "  moduleName : " << apex.getModuleName() << "\n";
518   *os << "  modulePath : " << apex.getModulePath() << "\n";
519   if (apex.hasPreinstalledModulePath()) {
520     *os << "  preinstalledModulePath : " << apex.getPreinstalledModulePath()
521         << "\n";
522   }
523   *os << "  versionCode : " << apex.getVersionCode() << "\n";
524   *os << "  isFactory : " << apex.getIsFactory() << "\n";
525   *os << "  isActive : " << apex.getIsActive() << "\n";
526   *os << "}";
527 }
528 
529 }  // namespace apex
530 }  // namespace android
531 }  // namespace com
532