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