payload_file.cc revision 720df3eeaecfc9ad229440c59e08c8d52f13dc1e
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
23#include "update_engine/delta_performer.h"
24#include "update_engine/file_writer.h"
25#include "update_engine/omaha_hash_calculator.h"
26#include "update_engine/payload_constants.h"
27#include "update_engine/payload_generator/annotated_operation.h"
28#include "update_engine/payload_generator/delta_diff_utils.h"
29#include "update_engine/payload_generator/payload_signer.h"
30
31using std::string;
32using std::vector;
33
34namespace chromeos_update_engine {
35
36namespace {
37
38struct DeltaObject {
39  DeltaObject(const string& in_name, const int in_type, const off_t in_size)
40      : name(in_name),
41        type(in_type),
42        size(in_size) {}
43  bool operator <(const DeltaObject& object) const {
44    return (size != object.size) ? (size < object.size) : (name < object.name);
45  }
46  string name;
47  int type;
48  off_t size;
49};
50
51// Writes the uint64_t passed in in host-endian to the file as big-endian.
52// Returns true on success.
53bool WriteUint64AsBigEndian(FileWriter* writer, const uint64_t value) {
54  uint64_t value_be = htobe64(value);
55  TEST_AND_RETURN_FALSE(writer->Write(&value_be, sizeof(value_be)));
56  return true;
57}
58
59}  // namespace
60
61bool PayloadFile::Init(const PayloadGenerationConfig& config) {
62  major_version_ = config.major_version;
63  TEST_AND_RETURN_FALSE(major_version_ == kChromeOSMajorPayloadVersion ||
64                        major_version_ == kBrilloMajorPayloadVersion);
65  manifest_.set_minor_version(config.minor_version);
66
67  if (!config.source.ImageInfoIsEmpty())
68    *(manifest_.mutable_old_image_info()) = config.source.image_info;
69
70  if (!config.target.ImageInfoIsEmpty())
71    *(manifest_.mutable_new_image_info()) = config.target.image_info;
72
73  manifest_.set_block_size(config.block_size);
74  return true;
75}
76
77bool PayloadFile::AddPartition(const PartitionConfig& old_conf,
78                               const PartitionConfig& new_conf,
79                               const vector<AnnotatedOperation>& aops) {
80  // Check partitions order for Chrome OS
81  if (major_version_ == kChromeOSMajorPayloadVersion) {
82    const vector<const char*> part_order = { kLegacyPartitionNameRoot,
83                                             kLegacyPartitionNameKernel };
84    TEST_AND_RETURN_FALSE(part_vec_.size() < part_order.size());
85    TEST_AND_RETURN_FALSE(new_conf.name == part_order[part_vec_.size()]);
86  }
87  Partition part;
88  part.name = new_conf.name;
89  part.aops = aops;
90  // Initialize the PartitionInfo objects if present.
91  if (!old_conf.path.empty())
92    TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(old_conf,
93                                                              &part.old_info));
94  TEST_AND_RETURN_FALSE(diff_utils::InitializePartitionInfo(new_conf,
95                                                            &part.new_info));
96  part_vec_.push_back(std::move(part));
97  return true;
98}
99
100bool PayloadFile::WritePayload(const string& payload_file,
101                               const string& data_blobs_path,
102                               const string& private_key_path,
103                               uint64_t* metadata_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  // Check that install op blobs are in order.
114  uint64_t next_blob_offset = 0;
115  for (const auto& part : part_vec_) {
116    for (const auto& aop : part.aops) {
117      if (!aop.op.has_data_offset())
118        continue;
119      if (aop.op.data_offset() != next_blob_offset) {
120        LOG(FATAL) << "bad blob offset! " << aop.op.data_offset() << " != "
121                   << next_blob_offset;
122      }
123      next_blob_offset += aop.op.data_length();
124    }
125  }
126
127  // Copy the operations and partition info from the part_vec_ to the manifest.
128  manifest_.clear_install_operations();
129  manifest_.clear_kernel_install_operations();
130  manifest_.clear_partitions();
131  for (const auto& part : part_vec_) {
132    if (major_version_ == kBrilloMajorPayloadVersion) {
133      PartitionUpdate* partition = manifest_.add_partitions();
134      partition->set_partition_name(part.name);
135      for (const AnnotatedOperation& aop : part.aops) {
136        *partition->add_operations() = aop.op;
137      }
138      if (part.old_info.has_size() || part.old_info.has_hash())
139        *(partition->mutable_old_partition_info()) = part.old_info;
140      if (part.new_info.has_size() || part.new_info.has_hash())
141        *(partition->mutable_new_partition_info()) = part.new_info;
142    } else {
143      // major_version_ == kChromeOSMajorPayloadVersion
144      if (part.name == kLegacyPartitionNameKernel) {
145        for (const AnnotatedOperation& aop : part.aops)
146          *manifest_.add_kernel_install_operations() = aop.op;
147        if (part.old_info.has_size() || part.old_info.has_hash())
148          *manifest_.mutable_old_kernel_info() = part.old_info;
149        if (part.new_info.has_size() || part.new_info.has_hash())
150          *manifest_.mutable_new_kernel_info() = part.new_info;
151      } else {
152        for (const AnnotatedOperation& aop : part.aops)
153          *manifest_.add_install_operations() = aop.op;
154        if (part.old_info.has_size() || part.old_info.has_hash())
155          *manifest_.mutable_old_rootfs_info() = part.old_info;
156        if (part.new_info.has_size() || part.new_info.has_hash())
157          *manifest_.mutable_new_rootfs_info() = part.new_info;
158      }
159    }
160  }
161
162  // Signatures appear at the end of the blobs. Note the offset in the
163  // manifest_.
164  if (!private_key_path.empty()) {
165    uint64_t signature_blob_length = 0;
166    TEST_AND_RETURN_FALSE(
167        PayloadSigner::SignatureBlobLength(vector<string>(1, private_key_path),
168                                           &signature_blob_length));
169    PayloadSigner::AddSignatureOp(next_blob_offset, signature_blob_length,
170                                  &manifest_);
171  }
172
173  // Serialize protobuf
174  string serialized_manifest;
175  TEST_AND_RETURN_FALSE(manifest_.AppendToString(&serialized_manifest));
176
177  uint64_t metadata_size =
178      sizeof(kDeltaMagic) + 2 * sizeof(uint64_t) + serialized_manifest.size();
179
180  LOG(INFO) << "Writing final delta file header...";
181  DirectFileWriter writer;
182  TEST_AND_RETURN_FALSE_ERRNO(writer.Open(payload_file.c_str(),
183                                          O_WRONLY | O_CREAT | O_TRUNC,
184                                          0644) == 0);
185  ScopedFileWriterCloser writer_closer(&writer);
186
187  // Write header
188  TEST_AND_RETURN_FALSE(writer.Write(kDeltaMagic, sizeof(kDeltaMagic)));
189
190  // Write major version number
191  TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer, major_version_));
192
193  // Write protobuf length
194  TEST_AND_RETURN_FALSE(WriteUint64AsBigEndian(&writer,
195                                               serialized_manifest.size()));
196
197  if (major_version_ == kBrilloMajorPayloadVersion) {
198    // Write metadata signature size.
199    uint32_t zero = htobe32(0);
200    TEST_AND_RETURN_FALSE(writer.Write(&zero, sizeof(zero)));
201    metadata_size += sizeof(zero);
202  }
203
204  // Write protobuf
205  LOG(INFO) << "Writing final delta file protobuf... "
206            << serialized_manifest.size();
207  TEST_AND_RETURN_FALSE(writer.Write(serialized_manifest.data(),
208                                     serialized_manifest.size()));
209
210  // Append the data blobs
211  LOG(INFO) << "Writing final delta file data blobs...";
212  int blobs_fd = open(ordered_blobs_path.c_str(), O_RDONLY, 0);
213  ScopedFdCloser blobs_fd_closer(&blobs_fd);
214  TEST_AND_RETURN_FALSE(blobs_fd >= 0);
215  for (;;) {
216    vector<char> buf(1024 * 1024);
217    ssize_t rc = read(blobs_fd, buf.data(), buf.size());
218    if (0 == rc) {
219      // EOF
220      break;
221    }
222    TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
223    TEST_AND_RETURN_FALSE(writer.Write(buf.data(), rc));
224  }
225
226  // Write signature blob.
227  if (!private_key_path.empty()) {
228    LOG(INFO) << "Signing the update...";
229    brillo::Blob signature_blob;
230    TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(
231        payload_file,
232        vector<string>(1, private_key_path),
233        metadata_size,
234        0,
235        metadata_size + manifest_.signatures_offset(),
236        &signature_blob));
237    TEST_AND_RETURN_FALSE(writer.Write(signature_blob.data(),
238                                       signature_blob.size()));
239  }
240
241  ReportPayloadUsage(metadata_size);
242  *metadata_size_out = metadata_size;
243  return true;
244}
245
246bool PayloadFile::ReorderDataBlobs(
247    const string& data_blobs_path,
248    const string& new_data_blobs_path) {
249  int in_fd = open(data_blobs_path.c_str(), O_RDONLY, 0);
250  TEST_AND_RETURN_FALSE_ERRNO(in_fd >= 0);
251  ScopedFdCloser in_fd_closer(&in_fd);
252
253  DirectFileWriter writer;
254  TEST_AND_RETURN_FALSE(
255      writer.Open(new_data_blobs_path.c_str(),
256                  O_WRONLY | O_TRUNC | O_CREAT,
257                  0644) == 0);
258  ScopedFileWriterCloser writer_closer(&writer);
259  uint64_t out_file_size = 0;
260
261  for (auto& part: part_vec_) {
262    for (AnnotatedOperation& aop : part.aops) {
263      if (!aop.op.has_data_offset())
264        continue;
265      CHECK(aop.op.has_data_length());
266      brillo::Blob buf(aop.op.data_length());
267      ssize_t rc = pread(in_fd, buf.data(), buf.size(), aop.op.data_offset());
268      TEST_AND_RETURN_FALSE(rc == static_cast<ssize_t>(buf.size()));
269
270      // Add the hash of the data blobs for this operation
271      TEST_AND_RETURN_FALSE(AddOperationHash(&aop.op, buf));
272
273      aop.op.set_data_offset(out_file_size);
274      TEST_AND_RETURN_FALSE(writer.Write(buf.data(), buf.size()));
275      out_file_size += buf.size();
276    }
277  }
278  return true;
279}
280
281bool PayloadFile::AddOperationHash(InstallOperation* op,
282                                   const brillo::Blob& buf) {
283  OmahaHashCalculator hasher;
284  TEST_AND_RETURN_FALSE(hasher.Update(buf.data(), buf.size()));
285  TEST_AND_RETURN_FALSE(hasher.Finalize());
286  const brillo::Blob& hash = hasher.raw_hash();
287  op->set_data_sha256_hash(hash.data(), hash.size());
288  return true;
289}
290
291void PayloadFile::ReportPayloadUsage(uint64_t metadata_size) const {
292  vector<DeltaObject> objects;
293  off_t total_size = 0;
294
295  for (const auto& part : part_vec_) {
296    for (const AnnotatedOperation& aop : part.aops) {
297      objects.push_back(DeltaObject(aop.name,
298                                    aop.op.type(),
299                                    aop.op.data_length()));
300      total_size += aop.op.data_length();
301    }
302  }
303
304  objects.push_back(DeltaObject("<manifest-metadata>",
305                                -1,
306                                metadata_size));
307  total_size += metadata_size;
308
309  std::sort(objects.begin(), objects.end());
310
311  static const char kFormatString[] = "%6.2f%% %10jd %-10s %s\n";
312  for (const DeltaObject& object : objects) {
313    fprintf(
314        stderr, kFormatString,
315        object.size * 100.0 / total_size,
316        static_cast<intmax_t>(object.size),
317        (object.type >= 0 ? InstallOperationTypeName(
318                                static_cast<InstallOperation_Type>(object.type))
319                          : "-"),
320        object.name.c_str());
321  }
322  fprintf(stderr, kFormatString,
323          100.0, static_cast<intmax_t>(total_size), "", "<total>");
324}
325
326}  // namespace chromeos_update_engine
327