blob: fe453a29b90b0eae04c2a607767e25db735bf94b [file] [log] [blame]
Alex Deymo14158572015-06-13 03:37:08 -07001// Copyright 2015 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/payload_generator/payload_file.h"
6
7#include <algorithm>
8
9#include "update_engine/file_writer.h"
10#include "update_engine/omaha_hash_calculator.h"
11#include "update_engine/payload_constants.h"
12#include "update_engine/payload_generator/annotated_operation.h"
13#include "update_engine/payload_generator/delta_diff_generator.h"
14#include "update_engine/payload_generator/delta_diff_utils.h"
15#include "update_engine/payload_generator/payload_signer.h"
16
17using std::string;
18using std::vector;
19
20namespace chromeos_update_engine {
21
22namespace {
23
24const uint64_t kMajorVersionNumber = 1;
25
26static const char* kInstallOperationTypes[] = {
27 "REPLACE",
28 "REPLACE_BZ",
29 "MOVE",
30 "BSDIFF",
31 "SOURCE_COPY",
32 "SOURCE_BSDIFF"
33};
34
35struct DeltaObject {
36 DeltaObject(const string& in_name, const int in_type, const off_t in_size)
37 : name(in_name),
38 type(in_type),
39 size(in_size) {}
40 bool operator <(const DeltaObject& object) const {
41 return (size != object.size) ? (size < object.size) : (name < object.name);
42 }
43 string name;
44 int type;
45 off_t size;
46};
47
48// Writes the uint64_t passed in in host-endian to the file as big-endian.
49// Returns true on success.
50bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
51 uint64_t value_be = htobe64(value);
52 TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
53 return true;
54}
55
56} // namespace
57
58const vector<PartitionName> PayloadFile::partition_disk_order_ = {
59 PartitionName::kRootfs,
60 PartitionName::kKernel,
61};
62
63bool PayloadFile::Init(const PayloadGenerationConfig& config) {
64 manifest_.set_minor_version(config.minor_version);
65
66 if (!config.source.ImageInfoIsEmpty())
67 *(manifest_.mutable_old_image_info()) = config.source.image_info;
68
69 if (!config.target.ImageInfoIsEmpty())
70 *(manifest_.mutable_new_image_info()) = config.target.image_info;
71
72 manifest_.set_block_size(config.block_size);
73
74 // Initialize the PartitionInfo objects if present.
75 if (!config.source.kernel.path.empty()) {
76 TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(
77 config.source.kernel,
78 manifest_.mutable_old_kernel_info()));
79 }
80 TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(
81 config.target.kernel,
82 manifest_.mutable_new_kernel_info()));
83 if (!config.source.rootfs.path.empty()) {
84 TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(
85 config.source.rootfs,
86 manifest_.mutable_old_rootfs_info()));
87 }
88 TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(
89 config.target.rootfs,
90 manifest_.mutable_new_rootfs_info()));
91 return true;
92}
93
94void PayloadFile::AddPartitionOperations(
95 PartitionName name,
96 const vector<AnnotatedOperation>& aops) {
97 aops_map_[name].insert(aops_map_[name].end(), aops.begin(), aops.end());
98}
99
100bool PayloadFile::WritePayload(const string& payload_file,
101 const string& data_blobs_path,
102 const string& private_key_path,
103 uint64_t* medatata_size_out) {
104 // Reorder the data blobs with the manifest_.
105 string ordered_blobs_path;
106 TEST_AND_RETURN_FALSE(utils::MakeTempFile(
107 "CrAU_temp_data.ordered.XXXXXX",
108 &ordered_blobs_path,
109 nullptr));
110 ScopedPathUnlinker ordered_blobs_unlinker(ordered_blobs_path);
111 TEST_AND_RETURN_FALSE(ReorderDataBlobs(data_blobs_path, ordered_blobs_path));
112
113 // Copy the operations from the aops_map_ to the manifest.
114 manifest_.clear_install_operations();
115 manifest_.clear_kernel_install_operations();
116 for (PartitionName name : partition_disk_order_) {
117 for (const AnnotatedOperation& aop : aops_map_[name]) {
118 if (name == PartitionName::kKernel) {
119 *manifest_.add_kernel_install_operations() = aop.op;
120 } else {
121 *manifest_.add_install_operations() = aop.op;
122 }
123 }
124 }
125
126 // Check that install op blobs are in order.
127 uint64_t next_blob_offset = 0;
128 {
129 for (int i = 0; i < (manifest_.install_operations_size() +
130 manifest_.kernel_install_operations_size()); i++) {
131 DeltaArchiveManifest_InstallOperation* op =
132 i < manifest_.install_operations_size() ?
133 manifest_.mutable_install_operations(i) :
134 manifest_.mutable_kernel_install_operations(
135 i - manifest_.install_operations_size());
136 if (op->has_data_offset()) {
137 if (op->data_offset() != next_blob_offset) {
138 LOG(FATAL) << "bad blob offset! " << op->data_offset() << " != "
139 << next_blob_offset;
140 }
141 next_blob_offset += op->data_length();
142 }
143 }
144 }
145
146 // Signatures appear at the end of the blobs. Note the offset in the
147 // manifest_.
148 if (!private_key_path.empty()) {
149 uint64_t signature_blob_length = 0;
150 TEST_AND_RETURN_FALSE(
151 PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
152 &signature_blob_length));
153 AddSignatureOp(next_blob_offset, signature_blob_length, &manifest_);
154 }
155
156 // Serialize protobuf
157 string serialized_manifest;
158 TEST_AND_RETURN_FALSE(manifest_.AppendToString(&serialized_manifest));
159
160 LOG(INFO) << "Writing final delta file header...";
161 DirectFileWriter writer;
162 TEST_AND_RETURN_FALSE_ERRNO(writer.Open(payload_file.c_str(),
163 O_WRONLY | O_CREAT | O_TRUNC,
164 0644) == 0);
165 ScopedFileWriterCloser writer_closer(&writer);
166
167 // Write header
168 TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, strlen(kDeltaMagic)));
169
170 // Write major version number
171 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, kMajorVersionNumber));
172
173 // Write protobuf length
174 TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
175 serialized_manifest.size()));
176
177 // Write protobuf
178 LOG(INFO) << "Writing final delta file protobuf... "
179 << serialized_manifest.size();
180 TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
181 serialized_manifest.size()));
182
183 // Append the data blobs
184 LOG(INFO) << "Writing final delta file data blobs...";
185 int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
186 ScopedFdCloser blobs_fd_closer(&blobs_fd);
187 TEST_AND_RETURN_FALSE(blobs_fd >= 0);
188 for (;;) {
189 vector<char> buf(1024 * 1024);
190 ssize_t rc = read(blobs_fd, buf.data(), buf.size());
191 if (0 == rc) {
192 // EOF
193 break;
194 }
195 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
196 TEST_AND_RETURN_FALSE(writer.Write(buf.data(), rc));
197 }
198
199 // Write signature blob.
200 if (!private_key_path.empty()) {
201 LOG(INFO) << "Signing the update...";
202 chromeos::Blob signature_blob;
203 TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
204 payload_file,
205 vector<string>(1, private_key_path),
206 &signature_blob));
207 TEST_AND_RETURN_FALSE(writer.Write(signature_blob.data(),
208 signature_blob.size()));
209 }
210
211 *medatata_size_out =
212 strlen(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
213 ReportPayloadUsage(*medatata_size_out);
214 return true;
215}
216
217bool PayloadFile::ReorderDataBlobs(
218 const string& data_blobs_path,
219 const string& new_data_blobs_path) {
220 int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
221 TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
222 ScopedFdCloser in_fd_closer(&in_fd);
223
224 DirectFileWriter writer;
225 TEST_AND_RETURN_FALSE(
226 writer.Open(new_data_blobs_path.c_str(),
227 O_WRONLY | O_TRUNC | O_CREAT,
228 0644) == 0);
229 ScopedFileWriterCloser writer_closer(&writer);
230 uint64_t out_file_size = 0;
231
232 for (PartitionName name : partition_disk_order_) {
233 for (AnnotatedOperation& aop : aops_map_[name]) {
234 if (!aop.op.has_data_offset())
235 continue;
236 CHECK(aop.op.has_data_length());
237 chromeos::Blob buf(aop.op.data_length());
238 ssize_t rc = pread(in_fd, buf.data(), buf.size(), aop.op.data_offset());
239 TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
240
241 // Add the hash of the data blobs for this operation
242 TEST_AND_RETURN_FALSE(AddOperationHash(&aop.op, buf));
243
244 aop.op.set_data_offset(out_file_size);
245 TEST_AND_RETURN_FALSE(writer.Write(buf.data(), buf.size()));
246 out_file_size += buf.size();
247 }
248 }
249 return true;
250}
251
252bool PayloadFile::AddOperationHash(
253 DeltaArchiveManifest_InstallOperation* op,
254 const chromeos::Blob& buf) {
255 OmahaHashCalculator hasher;
256 TEST_AND_RETURN_FALSE(hasher.Update(buf.data(), buf.size()));
257 TEST_AND_RETURN_FALSE(hasher.Finalize());
258 const chromeos::Blob& hash = hasher.raw_hash();
259 op->set_data_sha256_hash(hash.data(), hash.size());
260 return true;
261}
262
263void PayloadFile::ReportPayloadUsage(uint64_t metadata_size) const {
264 vector<DeltaObject> objects;
265 off_t total_size = 0;
266
267 for (PartitionName name : partition_disk_order_) {
268 const auto& partition_aops = aops_map_.find(name);
269 if (partition_aops == aops_map_.end())
270 continue;
271 for (const AnnotatedOperation& aop : partition_aops->second) {
272 objects.push_back(DeltaObject(aop.name,
273 aop.op.type(),
274 aop.op.data_length()));
275 total_size += aop.op.data_length();
276 }
277 }
278
279 objects.push_back(DeltaObject("<manifest-metadata>",
280 -1,
281 metadata_size));
282 total_size += metadata_size;
283
284 std::sort(objects.begin(), objects.end());
285
286 static const char kFormatString[] = "%6.2f%% %10jd %-10s %s\n";
287 for (const DeltaObject& object : objects) {
288 fprintf(stderr, kFormatString,
289 object.size * 100.0 / total_size,
290 static_cast<intmax_t>(object.size),
291 object.type >= 0 ? kInstallOperationTypes[object.type] : "-",
292 object.name.c_str());
293 }
294 fprintf(stderr, kFormatString,
295 100.0, static_cast<intmax_t>(total_size), "", "<total>");
296}
297
298void AddSignatureOp(uint64_t signature_blob_offset,
299 uint64_t signature_blob_length,
300 DeltaArchiveManifest* manifest) {
301 LOG(INFO) << "Making room for signature in file";
302 manifest->set_signatures_offset(signature_blob_offset);
303 LOG(INFO) << "set? " << manifest->has_signatures_offset();
304 // Add a dummy op at the end to appease older clients
305 DeltaArchiveManifest_InstallOperation* dummy_op =
306 manifest->add_kernel_install_operations();
307 dummy_op->set_type(DeltaArchiveManifest_InstallOperation_Type_REPLACE);
308 dummy_op->set_data_offset(signature_blob_offset);
309 manifest->set_signatures_offset(signature_blob_offset);
310 dummy_op->set_data_length(signature_blob_length);
311 manifest->set_signatures_size(signature_blob_length);
312 Extent* dummy_extent = dummy_op->add_dst_extents();
313 // Tell the dummy op to write this data to a big sparse hole
314 dummy_extent->set_start_block(kSparseHole);
315 dummy_extent->set_num_blocks((signature_blob_length + kBlockSize - 1) /
316 kBlockSize);
317}
318
319} // namespace chromeos_update_engine