1 //
2 // Copyright (C) 2015 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 "update_engine/payload_generator/payload_file.h"
18
19 #include <endian.h>
20
21 #include <map>
22 #include <utility>
23
24 #include <android-base/stringprintf.h>
25
26 #include "update_engine/common/hash_calculator.h"
27 #include "update_engine/common/utils.h"
28 #include "update_engine/payload_consumer/file_writer.h"
29 #include "update_engine/payload_consumer/payload_constants.h"
30 #include "update_engine/payload_generator/annotated_operation.h"
31 #include "update_engine/payload_generator/delta_diff_utils.h"
32 #include "update_engine/payload_generator/payload_signer.h"
33
34 using std::string;
35 using std::vector;
36
37 namespace chromeos_update_engine {
38
39 namespace {
40
41 struct DeltaObject {
DeltaObjectchromeos_update_engine::__anon891be68c0111::DeltaObject42 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
43 : name(in_name), type(in_type), size(in_size) {}
operator <chromeos_update_engine::__anon891be68c0111::DeltaObject44 bool operator<(const DeltaObject& object) const {
45 return (size != object.size) ? (size < object.size) : (name < object.name);
46 }
47 string name;
48 int type;
49 off_t size;
50 };
51
52 // Writes the uint64_t passed in in host-endian to the file as big-endian.
53 // Returns true on success.
WriteUint64AsBigEndian(FileWriter * writer,const uint64_t value)54 bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
55 uint64_t value_be = htobe64(value);
56 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
57 return true;
58 }
59
60 } // namespace
61
Init(const PayloadGenerationConfig & config)62 bool PayloadFile::Init(const PayloadGenerationConfig& config) {
63 TEST_AND_RETURN_FALSE(config.version.Validate());
64 major_version_ = config.version.major;
65 manifest_.set_minor_version(config.version.minor);
66 manifest_.set_block_size(config.block_size);
67 manifest_.set_max_timestamp(config.max_timestamp);
68 if (!config.security_patch_level.empty()) {
69 manifest_.set_security_patch_level(config.security_patch_level);
70 }
71
72 if (config.target.dynamic_partition_metadata != nullptr)
73 *(manifest_.mutable_dynamic_partition_metadata()) =
74 *(config.target.dynamic_partition_metadata);
75
76 if (config.is_partial_update) {
77 manifest_.set_partial_update(true);
78 }
79
80 if (!config.apex_info_file.empty()) {
81 ApexMetadata apex_metadata;
82 int fd = open(config.apex_info_file.c_str(), O_RDONLY);
83 if (fd < 0) {
84 PLOG(FATAL) << "Failed to open " << config.apex_info_file << " for read.";
85 }
86 ScopedFdCloser closer{&fd};
87 CHECK(apex_metadata.ParseFromFileDescriptor(fd));
88 if (apex_metadata.apex_info_size() > 0) {
89 *manifest_.mutable_apex_info() =
90 std::move(*apex_metadata.mutable_apex_info());
91 }
92 }
93 return true;
94 }
95
AddPartition(const PartitionConfig & old_conf,const PartitionConfig & new_conf,vector<AnnotatedOperation> aops,vector<CowMergeOperation> merge_sequence,const android::snapshot::CowSizeInfo & cow_info)96 bool PayloadFile::AddPartition(const PartitionConfig& old_conf,
97 const PartitionConfig& new_conf,
98 vector<AnnotatedOperation> aops,
99 vector<CowMergeOperation> merge_sequence,
100 const android::snapshot::CowSizeInfo& cow_info) {
101 Partition part;
102 part.name = new_conf.name;
103 part.aops = std::move(aops);
104 part.cow_merge_sequence = std::move(merge_sequence);
105 part.postinstall = new_conf.postinstall;
106 part.verity = new_conf.verity;
107 part.version = new_conf.version;
108 part.cow_info = cow_info;
109 // Initialize the PartitionInfo objects if present.
110 if (!old_conf.path.empty())
111 TEST_AND_RETURN_FALSE(
112 diff_utils::InitializePartitionInfo(old_conf, &part.old_info));
113 TEST_AND_RETURN_FALSE(
114 diff_utils::InitializePartitionInfo(new_conf, &part.new_info));
115 part_vec_.push_back(std::move(part));
116 return true;
117 }
118
WritePayload(const string & payload_file,const string & data_blobs_path,const string & private_key_path,uint64_t * metadata_size_out)119 bool PayloadFile::WritePayload(const string& payload_file,
120 const string& data_blobs_path,
121 const string& private_key_path,
122 uint64_t* metadata_size_out) {
123 // Reorder the data blobs with the manifest_.
124 ScopedTempFile ordered_blobs_file("CrAU_temp_data.ordered.XXXXXX");
125 TEST_AND_RETURN_FALSE(
126 ReorderDataBlobs(data_blobs_path, ordered_blobs_file.path()));
127
128 // Check that install op blobs are in order.
129 uint64_t next_blob_offset = 0;
130 for (const auto& part : part_vec_) {
131 for (const auto& aop : part.aops) {
132 if (!aop.op.has_data_offset())
133 continue;
134 if (aop.op.data_offset() != next_blob_offset) {
135 LOG(FATAL) << "bad blob offset! " << aop.op.data_offset()
136 << " != " << next_blob_offset;
137 }
138 next_blob_offset += aop.op.data_length();
139 }
140 }
141
142 // Copy the operations and partition info from the part_vec_ to the manifest.
143 manifest_.clear_partitions();
144 for (const auto& part : part_vec_) {
145 PartitionUpdate* partition = manifest_.add_partitions();
146 partition->set_partition_name(part.name);
147 if (!part.version.empty()) {
148 partition->set_version(part.version);
149 }
150 if (part.cow_info.cow_size > 0) {
151 partition->set_estimate_cow_size(part.cow_info.cow_size);
152 }
153 if (part.cow_info.op_count_max > 0) {
154 partition->set_estimate_op_count_max(part.cow_info.op_count_max);
155 }
156 if (part.postinstall.run) {
157 partition->set_run_postinstall(true);
158 if (!part.postinstall.path.empty())
159 partition->set_postinstall_path(part.postinstall.path);
160 if (!part.postinstall.filesystem_type.empty())
161 partition->set_filesystem_type(part.postinstall.filesystem_type);
162 partition->set_postinstall_optional(part.postinstall.optional);
163 }
164 if (!part.verity.IsEmpty()) {
165 if (part.verity.hash_tree_extent.num_blocks() != 0) {
166 *partition->mutable_hash_tree_data_extent() =
167 part.verity.hash_tree_data_extent;
168 *partition->mutable_hash_tree_extent() = part.verity.hash_tree_extent;
169 partition->set_hash_tree_algorithm(part.verity.hash_tree_algorithm);
170 if (!part.verity.hash_tree_salt.empty())
171 partition->set_hash_tree_salt(part.verity.hash_tree_salt.data(),
172 part.verity.hash_tree_salt.size());
173 }
174 if (part.verity.fec_extent.num_blocks() != 0) {
175 *partition->mutable_fec_data_extent() = part.verity.fec_data_extent;
176 *partition->mutable_fec_extent() = part.verity.fec_extent;
177 partition->set_fec_roots(part.verity.fec_roots);
178 }
179 }
180 for (const AnnotatedOperation& aop : part.aops) {
181 *partition->add_operations() = aop.op;
182 }
183 for (const auto& merge_op : part.cow_merge_sequence) {
184 *partition->add_merge_operations() = merge_op;
185 }
186
187 if (part.old_info.has_size() || part.old_info.has_hash())
188 *(partition->mutable_old_partition_info()) = part.old_info;
189 if (part.new_info.has_size() || part.new_info.has_hash())
190 *(partition->mutable_new_partition_info()) = part.new_info;
191 }
192
193 // Signatures appear at the end of the blobs. Note the offset in the
194 // |manifest_|.
195 uint64_t signature_blob_length = 0;
196 if (!private_key_path.empty()) {
197 TEST_AND_RETURN_FALSE(PayloadSigner::SignatureBlobLength(
198 {private_key_path}, &signature_blob_length));
199 PayloadSigner::AddSignatureToManifest(
200 next_blob_offset, signature_blob_length, &manifest_);
201 }
202 WritePayload(payload_file,
203 ordered_blobs_file.path(),
204 private_key_path,
205 major_version_,
206 manifest_,
207 metadata_size_out);
208
209 ReportPayloadUsage(*metadata_size_out);
210 return true;
211 }
212
WritePayload(const std::string & payload_file,const std::string & ordered_blobs_file,const std::string & private_key_path,uint64_t major_version_,const DeltaArchiveManifest & manifest,uint64_t * metadata_size_out)213 bool PayloadFile::WritePayload(const std::string& payload_file,
214 const std::string& ordered_blobs_file,
215 const std::string& private_key_path,
216 uint64_t major_version_,
217 const DeltaArchiveManifest& manifest,
218 uint64_t* metadata_size_out) {
219 std::string serialized_manifest;
220
221 TEST_AND_RETURN_FALSE(manifest.SerializeToString(&serialized_manifest));
222 uint64_t metadata_size =
223 sizeof(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
224 LOG(INFO) << "Writing final delta file header...";
225 DirectFileWriter writer;
226 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(payload_file.c_str(),
227 O_WRONLY | O_CREAT | O_TRUNC,
228 0644) == 0);
229 ScopedFileWriterCloser writer_closer(&writer);
230
231 // Write header
232 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(kDeltaMagic, sizeof(kDeltaMagic)));
233
234 // Write major version number
235 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, major_version_));
236
237 // Write protobuf length
238 TEST_AND_RETURN_FALSE(
239 WriteUint64AsBigEndian(&writer, serialized_manifest.size()));
240
241 // Metadata signature has the same size as payload signature, because they
242 // are both the same kind of signature for the same kind of hash.
243 const auto signature_blob_length = manifest.signatures_size();
244 // Adding a new scope here so code down below can't access
245 // metadata_signature_size, as the integer is in big endian, not host
246 // endianess.
247 {
248 const uint32_t metadata_signature_size = htobe32(signature_blob_length);
249 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(&metadata_signature_size,
250 sizeof(metadata_signature_size)));
251 metadata_size += sizeof(metadata_signature_size);
252 }
253
254 // Write protobuf
255 LOG(INFO) << "Writing final delta file protobuf... "
256 << serialized_manifest.size();
257 TEST_AND_RETURN_FALSE_ERRNO(
258 writer.Write(serialized_manifest.data(), serialized_manifest.size()));
259
260 // Write metadata signature blob.
261 if (!private_key_path.empty()) {
262 brillo::Blob metadata_hash;
263 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfFile(
264 payload_file, metadata_size, &metadata_hash));
265 string metadata_signature;
266 TEST_AND_RETURN_FALSE(PayloadSigner::SignHashWithKeys(
267 metadata_hash, {private_key_path}, &metadata_signature));
268 TEST_AND_RETURN_FALSE_ERRNO(
269 writer.Write(metadata_signature.data(), metadata_signature.size()));
270 }
271
272 // Append the data blobs.
273 LOG(INFO) << "Writing final delta file data blobs...";
274 int blobs_fd = open(ordered_blobs_file.c_str(), O_RDONLY, 0);
275 ScopedFdCloser blobs_fd_closer(&blobs_fd);
276 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
277 for (;;) {
278 vector<char> buf(1024 * 1024);
279 ssize_t rc = read(blobs_fd, buf.data(), buf.size());
280 if (0 == rc) {
281 // EOF
282 break;
283 }
284 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
285 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(buf.data(), rc));
286 }
287 // Write payload signature blob.
288 if (!private_key_path.empty()) {
289 LOG(INFO) << "Signing the update...";
290 string signature;
291 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
292 payload_file,
293 {private_key_path},
294 metadata_size,
295 signature_blob_length,
296 metadata_size + signature_blob_length + manifest.signatures_offset(),
297 &signature));
298 TEST_AND_RETURN_FALSE_ERRNO(
299 writer.Write(signature.data(), signature.size()));
300 }
301 if (metadata_size_out) {
302 *metadata_size_out = metadata_size;
303 }
304 return true;
305 }
306
ReorderDataBlobs(const string & data_blobs_path,const string & new_data_blobs_path)307 bool PayloadFile::ReorderDataBlobs(const string& data_blobs_path,
308 const string& new_data_blobs_path) {
309 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
310 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
311 ScopedFdCloser in_fd_closer(&in_fd);
312
313 DirectFileWriter writer;
314 int rc = writer.Open(
315 new_data_blobs_path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0644);
316 if (rc != 0) {
317 PLOG(ERROR) << "Error creating " << new_data_blobs_path;
318 return false;
319 }
320 ScopedFileWriterCloser writer_closer(&writer);
321 uint64_t out_file_size = 0;
322
323 for (auto& part : part_vec_) {
324 for (AnnotatedOperation& aop : part.aops) {
325 if (!aop.op.has_data_offset())
326 continue;
327 CHECK(aop.op.has_data_length());
328 brillo::Blob buf(aop.op.data_length());
329 ssize_t rc = pread(in_fd, buf.data(), buf.size(), aop.op.data_offset());
330 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
331
332 // Add the hash of the data blobs for this operation
333 TEST_AND_RETURN_FALSE(AddOperationHash(&aop.op, buf));
334
335 aop.op.set_data_offset(out_file_size);
336 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(buf.data(), buf.size()));
337 out_file_size += buf.size();
338 }
339 }
340 return true;
341 }
342
AddOperationHash(InstallOperation * op,const brillo::Blob & buf)343 bool PayloadFile::AddOperationHash(InstallOperation* op,
344 const brillo::Blob& buf) {
345 brillo::Blob hash;
346 TEST_AND_RETURN_FALSE(HashCalculator::RawHashOfData(buf, &hash));
347 op->set_data_sha256_hash(hash.data(), hash.size());
348 return true;
349 }
350
ReportPayloadUsage(uint64_t metadata_size) const351 void PayloadFile::ReportPayloadUsage(uint64_t metadata_size) const {
352 std::map<DeltaObject, int> object_counts;
353 off_t total_size = 0;
354 int total_op = 0;
355
356 for (const auto& part : part_vec_) {
357 string part_prefix = "<" + part.name + ">:";
358 for (const AnnotatedOperation& aop : part.aops) {
359 DeltaObject delta(
360 part_prefix + aop.name, aop.op.type(), aop.op.data_length());
361 object_counts[delta]++;
362 total_size += aop.op.data_length();
363 }
364 total_op += part.aops.size();
365 }
366
367 object_counts[DeltaObject("<manifest-metadata>", -1, metadata_size)] = 1;
368 total_size += metadata_size;
369
370 constexpr char kFormatString[] = "%6.2f%% %10jd %-13s %s %d\n";
371 for (const auto& object_count : object_counts) {
372 const DeltaObject& object = object_count.first;
373 // Use printf() instead of LOG(INFO) because timestamp makes it difficult to
374 // compare two reports.
375 printf(kFormatString,
376 object.size * 100.0 / total_size,
377 object.size,
378 (object.type >= 0
379 ? InstallOperationTypeName(
380 static_cast<InstallOperation::Type>(object.type))
381 : "-"),
382 object.name.c_str(),
383 object_count.second);
384 }
385 printf(kFormatString, 100.0, total_size, "", "<total>", total_op);
386 fflush(stdout);
387 }
388
389 } // namespace chromeos_update_engine
390