1 /*
2  * Copyright (C) 2016 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 agree 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 <dirent.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <time.h>
25 #include <unistd.h>
26 
27 #include <algorithm>
28 #include <memory>
29 #include <string>
30 #include <vector>
31 
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/unique_fd.h>
36 #include <gtest/gtest.h>
37 
38 #include "applypatch/applypatch.h"
39 #include "common/test_constants.h"
40 #include "edify/expr.h"
41 #include "otautil/paths.h"
42 #include "otautil/print_sha1.h"
43 
44 using namespace std::string_literals;
45 
46 class ApplyPatchTest : public ::testing::Test {
47  protected:
SetUp()48   void SetUp() override {
49     source_file = from_testdata_base("boot.img");
50     FileContents boot_fc;
51     ASSERT_TRUE(LoadFileContents(source_file, &boot_fc));
52     source_size = boot_fc.data.size();
53     source_sha1 = print_sha1(boot_fc.sha1);
54 
55     target_file = from_testdata_base("recovery.img");
56     FileContents recovery_fc;
57     ASSERT_TRUE(LoadFileContents(target_file, &recovery_fc));
58     target_size = recovery_fc.data.size();
59     target_sha1 = print_sha1(recovery_fc.sha1);
60 
61     source_partition = Partition(source_file, source_size, source_sha1);
62     target_partition = Partition(partition_file.path, target_size, target_sha1);
63 
64     srand(time(nullptr));
65     bad_sha1_a = android::base::StringPrintf("%040x", rand());
66     bad_sha1_b = android::base::StringPrintf("%040x", rand());
67 
68     // Reset the cache backup file.
69     Paths::Get().set_cache_temp_source(cache_temp_source.path);
70   }
71 
TearDown()72   void TearDown() override {
73     ASSERT_TRUE(android::base::RemoveFileIfExists(cache_temp_source.path));
74   }
75 
76   std::string source_file;
77   std::string source_sha1;
78   size_t source_size;
79 
80   std::string target_file;
81   std::string target_sha1;
82   size_t target_size;
83 
84   std::string bad_sha1_a;
85   std::string bad_sha1_b;
86 
87   Partition source_partition;
88   Partition target_partition;
89 
90  private:
91   TemporaryFile partition_file;
92   TemporaryFile cache_temp_source;
93 };
94 
TEST_F(ApplyPatchTest,CheckPartition)95 TEST_F(ApplyPatchTest, CheckPartition) {
96   ASSERT_TRUE(CheckPartition(source_partition));
97 }
98 
TEST_F(ApplyPatchTest,CheckPartition_Mismatching)99 TEST_F(ApplyPatchTest, CheckPartition_Mismatching) {
100   ASSERT_FALSE(CheckPartition(Partition(source_file, target_size, target_sha1)));
101   ASSERT_FALSE(CheckPartition(Partition(source_file, source_size, bad_sha1_a)));
102 
103   ASSERT_FALSE(CheckPartition(Partition(source_file, source_size - 1, source_sha1)));
104   ASSERT_FALSE(CheckPartition(Partition(source_file, source_size + 1, source_sha1)));
105 }
106 
TEST_F(ApplyPatchTest,PatchPartitionCheck)107 TEST_F(ApplyPatchTest, PatchPartitionCheck) {
108   ASSERT_TRUE(PatchPartitionCheck(target_partition, source_partition));
109 
110   ASSERT_TRUE(
111       PatchPartitionCheck(Partition(source_file, source_size - 1, source_sha1), source_partition));
112 
113   ASSERT_TRUE(
114       PatchPartitionCheck(Partition(source_file, source_size + 1, source_sha1), source_partition));
115 }
116 
TEST_F(ApplyPatchTest,PatchPartitionCheck_UseBackup)117 TEST_F(ApplyPatchTest, PatchPartitionCheck_UseBackup) {
118   ASSERT_FALSE(
119       PatchPartitionCheck(target_partition, Partition(target_file, source_size, source_sha1)));
120 
121   Paths::Get().set_cache_temp_source(source_file);
122   ASSERT_TRUE(
123       PatchPartitionCheck(target_partition, Partition(target_file, source_size, source_sha1)));
124 }
125 
TEST_F(ApplyPatchTest,PatchPartitionCheck_UseBackup_BothCorrupted)126 TEST_F(ApplyPatchTest, PatchPartitionCheck_UseBackup_BothCorrupted) {
127   ASSERT_FALSE(
128       PatchPartitionCheck(target_partition, Partition(target_file, source_size, source_sha1)));
129 
130   Paths::Get().set_cache_temp_source(target_file);
131   ASSERT_FALSE(
132       PatchPartitionCheck(target_partition, Partition(target_file, source_size, source_sha1)));
133 }
134 
TEST_F(ApplyPatchTest,PatchPartition)135 TEST_F(ApplyPatchTest, PatchPartition) {
136   FileContents patch_fc;
137   ASSERT_TRUE(LoadFileContents(from_testdata_base("recovery-from-boot.p"), &patch_fc));
138   Value patch(Value::Type::BLOB, std::string(patch_fc.data.cbegin(), patch_fc.data.cend()));
139 
140   FileContents bonus_fc;
141   ASSERT_TRUE(LoadFileContents(from_testdata_base("bonus.file"), &bonus_fc));
142   Value bonus(Value::Type::BLOB, std::string(bonus_fc.data.cbegin(), bonus_fc.data.cend()));
143 
144   ASSERT_TRUE(PatchPartition(target_partition, source_partition, patch, &bonus));
145 }
146 
147 // Tests patching an eMMC target without a separate bonus file (i.e. recovery-from-boot patch has
148 // everything).
TEST_F(ApplyPatchTest,PatchPartitionWithoutBonusFile)149 TEST_F(ApplyPatchTest, PatchPartitionWithoutBonusFile) {
150   FileContents patch_fc;
151   ASSERT_TRUE(LoadFileContents(from_testdata_base("recovery-from-boot-with-bonus.p"), &patch_fc));
152   Value patch(Value::Type::BLOB, std::string(patch_fc.data.cbegin(), patch_fc.data.cend()));
153 
154   ASSERT_TRUE(PatchPartition(target_partition, source_partition, patch, nullptr));
155 }
156 
157 class FreeCacheTest : public ::testing::Test {
158  protected:
159   static constexpr size_t PARTITION_SIZE = 4096 * 10;
160 
161   // Returns a sorted list of files in |dirname|.
FindFilesInDir(const std::string & dirname)162   static std::vector<std::string> FindFilesInDir(const std::string& dirname) {
163     std::vector<std::string> file_list;
164 
165     std::unique_ptr<DIR, decltype(&closedir)> d(opendir(dirname.c_str()), closedir);
166     struct dirent* de;
167     while ((de = readdir(d.get())) != 0) {
168       std::string path = dirname + "/" + de->d_name;
169 
170       struct stat st;
171       if (stat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
172         file_list.emplace_back(de->d_name);
173       }
174     }
175 
176     std::sort(file_list.begin(), file_list.end());
177     return file_list;
178   }
179 
AddFilesToDir(const std::string & dir,const std::vector<std::string> & files)180   void AddFilesToDir(const std::string& dir, const std::vector<std::string>& files) {
181     std::string zeros(4096, 0);
182     for (const auto& file : files) {
183       temporary_files_.push_back(dir + "/" + file);
184       ASSERT_TRUE(android::base::WriteStringToFile(zeros, temporary_files_.back()));
185     }
186   }
187 
SetUp()188   void SetUp() override {
189     Paths::Get().set_cache_log_directory(mock_log_dir.path);
190     temporary_files_.clear();
191   }
192 
TearDown()193   void TearDown() override {
194     for (const auto& file : temporary_files_) {
195       ASSERT_TRUE(android::base::RemoveFileIfExists(file));
196     }
197   }
198 
199   // A mock method to calculate the free space. It assumes the partition has a total size of 40960
200   // bytes and all files are 4096 bytes in size.
MockFreeSpaceChecker(const std::string & dirname)201   static size_t MockFreeSpaceChecker(const std::string& dirname) {
202     std::vector<std::string> files = FindFilesInDir(dirname);
203     return PARTITION_SIZE - 4096 * files.size();
204   }
205 
206   TemporaryDir mock_cache;
207   TemporaryDir mock_log_dir;
208 
209  private:
210   std::vector<std::string> temporary_files_;
211 };
212 
TEST_F(FreeCacheTest,FreeCacheSmoke)213 TEST_F(FreeCacheTest, FreeCacheSmoke) {
214   std::vector<std::string> files = { "file1", "file2", "file3" };
215   AddFilesToDir(mock_cache.path, files);
216   ASSERT_EQ(files, FindFilesInDir(mock_cache.path));
217   ASSERT_EQ(4096 * 7, MockFreeSpaceChecker(mock_cache.path));
218 
219   ASSERT_TRUE(RemoveFilesInDirectory(4096 * 9, mock_cache.path, MockFreeSpaceChecker));
220 
221   ASSERT_EQ(std::vector<std::string>{ "file3" }, FindFilesInDir(mock_cache.path));
222   ASSERT_EQ(4096 * 9, MockFreeSpaceChecker(mock_cache.path));
223 }
224 
TEST_F(FreeCacheTest,FreeCacheFreeSpaceCheckerError)225 TEST_F(FreeCacheTest, FreeCacheFreeSpaceCheckerError) {
226   std::vector<std::string> files{ "file1", "file2", "file3" };
227   AddFilesToDir(mock_cache.path, files);
228   ASSERT_EQ(files, FindFilesInDir(mock_cache.path));
229   ASSERT_EQ(4096 * 7, MockFreeSpaceChecker(mock_cache.path));
230 
231   ASSERT_FALSE(
232       RemoveFilesInDirectory(4096 * 9, mock_cache.path, [](const std::string&) { return -1; }));
233 }
234 
TEST_F(FreeCacheTest,FreeCacheOpenFile)235 TEST_F(FreeCacheTest, FreeCacheOpenFile) {
236   std::vector<std::string> files = { "file1", "file2" };
237   AddFilesToDir(mock_cache.path, files);
238   ASSERT_EQ(files, FindFilesInDir(mock_cache.path));
239   ASSERT_EQ(4096 * 8, MockFreeSpaceChecker(mock_cache.path));
240 
241   std::string file1_path = mock_cache.path + "/file1"s;
242   android::base::unique_fd fd(open(file1_path.c_str(), O_RDONLY));
243 
244   // file1 can't be deleted as it's opened by us.
245   ASSERT_FALSE(RemoveFilesInDirectory(4096 * 10, mock_cache.path, MockFreeSpaceChecker));
246 
247   ASSERT_EQ(std::vector<std::string>{ "file1" }, FindFilesInDir(mock_cache.path));
248 }
249 
TEST_F(FreeCacheTest,FreeCacheLogsSmoke)250 TEST_F(FreeCacheTest, FreeCacheLogsSmoke) {
251   std::vector<std::string> log_files = { "last_log", "last_log.1", "last_kmsg.2", "last_log.5",
252                                          "last_log.10" };
253   AddFilesToDir(mock_log_dir.path, log_files);
254   ASSERT_EQ(4096 * 5, MockFreeSpaceChecker(mock_log_dir.path));
255 
256   ASSERT_TRUE(RemoveFilesInDirectory(4096 * 8, mock_log_dir.path, MockFreeSpaceChecker));
257 
258   // Logs with a higher index will be deleted first
259   std::vector<std::string> expected = { "last_log", "last_log.1" };
260   ASSERT_EQ(expected, FindFilesInDir(mock_log_dir.path));
261   ASSERT_EQ(4096 * 8, MockFreeSpaceChecker(mock_log_dir.path));
262 }
263 
TEST_F(FreeCacheTest,FreeCacheLogsStringComparison)264 TEST_F(FreeCacheTest, FreeCacheLogsStringComparison) {
265   std::vector<std::string> log_files = { "last_log.1", "last_kmsg.1", "last_log.not_number",
266                                          "last_kmsgrandom" };
267   AddFilesToDir(mock_log_dir.path, log_files);
268   ASSERT_EQ(4096 * 6, MockFreeSpaceChecker(mock_log_dir.path));
269 
270   ASSERT_TRUE(RemoveFilesInDirectory(4096 * 9, mock_log_dir.path, MockFreeSpaceChecker));
271 
272   // Logs with incorrect format will be deleted first; and the last_kmsg with the same index is
273   // deleted before last_log.
274   std::vector<std::string> expected = { "last_log.1" };
275   ASSERT_EQ(expected, FindFilesInDir(mock_log_dir.path));
276   ASSERT_EQ(4096 * 9, MockFreeSpaceChecker(mock_log_dir.path));
277 }
278 
TEST_F(FreeCacheTest,FreeCacheLogsOtherFiles)279 TEST_F(FreeCacheTest, FreeCacheLogsOtherFiles) {
280   std::vector<std::string> log_files = { "last_install", "command", "block.map", "last_log",
281                                          "last_kmsg.1" };
282   AddFilesToDir(mock_log_dir.path, log_files);
283   ASSERT_EQ(4096 * 5, MockFreeSpaceChecker(mock_log_dir.path));
284 
285   ASSERT_FALSE(RemoveFilesInDirectory(4096 * 8, mock_log_dir.path, MockFreeSpaceChecker));
286 
287   // Non log files in /cache/recovery won't be deleted.
288   std::vector<std::string> expected = { "block.map", "command", "last_install" };
289   ASSERT_EQ(expected, FindFilesInDir(mock_log_dir.path));
290 }
291