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