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 #include "flashing.h"
17 
18 #include <fcntl.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 
22 #include <algorithm>
23 #include <memory>
24 #include <optional>
25 #include <set>
26 #include <string>
27 
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/properties.h>
31 #include <android-base/strings.h>
32 #include <ext4_utils/ext4_utils.h>
33 #include <fs_mgr_overlayfs.h>
34 #include <fstab/fstab.h>
35 #include <libavb/libavb.h>
36 #include <liblp/builder.h>
37 #include <liblp/liblp.h>
38 #include <libsnapshot/snapshot.h>
39 #include <sparse/sparse.h>
40 
41 #include "fastboot_device.h"
42 #include "utility.h"
43 
44 using namespace android::fs_mgr;
45 using namespace std::literals;
46 
47 namespace {
48 
49 constexpr uint32_t SPARSE_HEADER_MAGIC = 0xed26ff3a;
50 
WipeOverlayfsForPartition(FastbootDevice * device,const std::string & partition_name)51 void WipeOverlayfsForPartition(FastbootDevice* device, const std::string& partition_name) {
52     // May be called, in the case of sparse data, multiple times so cache/skip.
53     static std::set<std::string> wiped;
54     if (wiped.find(partition_name) != wiped.end()) return;
55     wiped.insert(partition_name);
56     // Following appears to have a first time 2% impact on flashing speeds.
57 
58     // Convert partition_name to a validated mount point and wipe.
59     Fstab fstab;
60     ReadDefaultFstab(&fstab);
61 
62     std::optional<AutoMountMetadata> mount_metadata;
63     for (const auto& entry : fstab) {
64         auto partition = android::base::Basename(entry.mount_point);
65         if ("/" == entry.mount_point) {
66             partition = "system";
67         }
68 
69         if ((partition + device->GetCurrentSlot()) == partition_name) {
70             mount_metadata.emplace();
71             android::fs_mgr::TeardownAllOverlayForMountPoint(entry.mount_point);
72         }
73     }
74 }
75 
76 }  // namespace
77 
FlashRawDataChunk(int fd,const char * data,size_t len)78 int FlashRawDataChunk(int fd, const char* data, size_t len) {
79     size_t ret = 0;
80     while (ret < len) {
81         int this_len = std::min(static_cast<size_t>(1048576UL * 8), len - ret);
82         int this_ret = write(fd, data, this_len);
83         if (this_ret < 0) {
84             PLOG(ERROR) << "Failed to flash data of len " << len;
85             return -1;
86         }
87         data += this_ret;
88         ret += this_ret;
89     }
90     return 0;
91 }
92 
FlashRawData(int fd,const std::vector<char> & downloaded_data)93 int FlashRawData(int fd, const std::vector<char>& downloaded_data) {
94     int ret = FlashRawDataChunk(fd, downloaded_data.data(), downloaded_data.size());
95     if (ret < 0) {
96         return -errno;
97     }
98     return ret;
99 }
100 
WriteCallback(void * priv,const void * data,size_t len)101 int WriteCallback(void* priv, const void* data, size_t len) {
102     int fd = reinterpret_cast<long long>(priv);
103     if (!data) {
104         return lseek64(fd, len, SEEK_CUR) >= 0 ? 0 : -errno;
105     }
106     return FlashRawDataChunk(fd, reinterpret_cast<const char*>(data), len);
107 }
108 
FlashSparseData(int fd,std::vector<char> & downloaded_data)109 int FlashSparseData(int fd, std::vector<char>& downloaded_data) {
110     struct sparse_file* file = sparse_file_import_buf(downloaded_data.data(), true, false);
111     if (!file) {
112         return -ENOENT;
113     }
114     return sparse_file_callback(file, false, false, WriteCallback, reinterpret_cast<void*>(fd));
115 }
116 
FlashBlockDevice(int fd,std::vector<char> & downloaded_data)117 int FlashBlockDevice(int fd, std::vector<char>& downloaded_data) {
118     lseek64(fd, 0, SEEK_SET);
119     if (downloaded_data.size() >= sizeof(SPARSE_HEADER_MAGIC) &&
120         *reinterpret_cast<uint32_t*>(downloaded_data.data()) == SPARSE_HEADER_MAGIC) {
121         return FlashSparseData(fd, downloaded_data);
122     } else {
123         return FlashRawData(fd, downloaded_data);
124     }
125 }
126 
CopyAVBFooter(std::vector<char> * data,const uint64_t block_device_size)127 static void CopyAVBFooter(std::vector<char>* data, const uint64_t block_device_size) {
128     if (data->size() < AVB_FOOTER_SIZE) {
129         return;
130     }
131     std::string footer;
132     uint64_t footer_offset = data->size() - AVB_FOOTER_SIZE;
133     for (int idx = 0; idx < AVB_FOOTER_MAGIC_LEN; idx++) {
134         footer.push_back(data->at(footer_offset + idx));
135     }
136     if (0 != footer.compare(AVB_FOOTER_MAGIC)) {
137         return;
138     }
139 
140     // copy AVB footer from end of data to end of block device
141     uint64_t original_data_size = data->size();
142     data->resize(block_device_size, 0);
143     for (int idx = 0; idx < AVB_FOOTER_SIZE; idx++) {
144         data->at(block_device_size - 1 - idx) = data->at(original_data_size - 1 - idx);
145     }
146 }
147 
Flash(FastbootDevice * device,const std::string & partition_name)148 int Flash(FastbootDevice* device, const std::string& partition_name) {
149     PartitionHandle handle;
150     if (!OpenPartition(device, partition_name, &handle)) {
151         return -ENOENT;
152     }
153 
154     std::vector<char> data = std::move(device->download_data());
155     if (data.size() == 0) {
156         return -EINVAL;
157     }
158     uint64_t block_device_size = get_block_device_size(handle.fd());
159     if (data.size() > block_device_size) {
160         return -EOVERFLOW;
161     } else if (data.size() < block_device_size &&
162                (partition_name == "boot" || partition_name == "boot_a" ||
163                 partition_name == "boot_b")) {
164         CopyAVBFooter(&data, block_device_size);
165     }
166     if (android::base::GetProperty("ro.system.build.type", "") != "user") {
167         WipeOverlayfsForPartition(device, partition_name);
168     }
169     int result = FlashBlockDevice(handle.fd(), data);
170     sync();
171     return result;
172 }
173 
UpdateSuper(FastbootDevice * device,const std::string & super_name,bool wipe)174 bool UpdateSuper(FastbootDevice* device, const std::string& super_name, bool wipe) {
175     std::vector<char> data = std::move(device->download_data());
176     if (data.empty()) {
177         return device->WriteFail("No data available");
178     }
179 
180     std::unique_ptr<LpMetadata> new_metadata = ReadFromImageBlob(data.data(), data.size());
181     if (!new_metadata) {
182         return device->WriteFail("Data is not a valid logical partition metadata image");
183     }
184 
185     if (!FindPhysicalPartition(super_name)) {
186         return device->WriteFail("Cannot find " + super_name +
187                                  ", build may be missing broken or missing boot_devices");
188     }
189 
190     std::string slot_suffix = device->GetCurrentSlot();
191     uint32_t slot_number = SlotNumberForSlotSuffix(slot_suffix);
192 
193     std::string other_slot_suffix;
194     if (!slot_suffix.empty()) {
195         other_slot_suffix = (slot_suffix == "_a") ? "_b" : "_a";
196     }
197 
198     // If we are unable to read the existing metadata, then the super partition
199     // is corrupt. In this case we reflash the whole thing using the provided
200     // image.
201     std::unique_ptr<LpMetadata> old_metadata = ReadMetadata(super_name, slot_number);
202     if (wipe || !old_metadata) {
203         if (!FlashPartitionTable(super_name, *new_metadata.get())) {
204             return device->WriteFail("Unable to flash new partition table");
205         }
206         android::fs_mgr::TeardownAllOverlayForMountPoint();
207         sync();
208         return device->WriteOkay("Successfully flashed partition table");
209     }
210 
211     std::set<std::string> partitions_to_keep;
212     bool virtual_ab = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
213     for (const auto& partition : old_metadata->partitions) {
214         // Preserve partitions in the other slot, but not the current slot.
215         std::string partition_name = GetPartitionName(partition);
216         if (!slot_suffix.empty()) {
217             auto part_suffix = GetPartitionSlotSuffix(partition_name);
218             if (part_suffix == slot_suffix || (part_suffix == other_slot_suffix && virtual_ab)) {
219                 continue;
220             }
221         }
222         std::string group_name = GetPartitionGroupName(old_metadata->groups[partition.group_index]);
223         // Skip partitions in the COW group
224         if (group_name == android::snapshot::kCowGroupName) {
225             continue;
226         }
227         partitions_to_keep.emplace(partition_name);
228     }
229 
230     // Do not preserve the scratch partition.
231     partitions_to_keep.erase("scratch");
232 
233     if (!partitions_to_keep.empty()) {
234         std::unique_ptr<MetadataBuilder> builder = MetadataBuilder::New(*new_metadata.get());
235         if (!builder->ImportPartitions(*old_metadata.get(), partitions_to_keep)) {
236             return device->WriteFail(
237                     "Old partitions are not compatible with the new super layout; wipe needed");
238         }
239 
240         new_metadata = builder->Export();
241         if (!new_metadata) {
242             return device->WriteFail("Unable to build new partition table; wipe needed");
243         }
244     }
245 
246     // Write the new table to every metadata slot.
247     if (!UpdateAllPartitionMetadata(device, super_name, *new_metadata.get())) {
248         return device->WriteFail("Unable to write new partition table");
249     }
250     android::fs_mgr::TeardownAllOverlayForMountPoint();
251     sync();
252     return device->WriteOkay("Successfully updated partition table");
253 }
254