generate_delta_main.cc revision 7fad7b7d3d7dcdaa7b17855fe333fcc4da000b46
1// Copyright (c) 2010 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 <errno.h>
6#include <fcntl.h>
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <unistd.h>
10
11#include <set>
12#include <string>
13#include <vector>
14
15#include <base/logging.h>
16#include <base/strings/string_number_conversions.h>
17#include <base/strings/string_split.h>
18#include <chromeos/flag_helper.h>
19#include <glib.h>
20
21#include "update_engine/delta_performer.h"
22#include "update_engine/payload_generator/delta_diff_generator.h"
23#include "update_engine/payload_generator/delta_diff_utils.h"
24#include "update_engine/payload_generator/payload_generation_config.h"
25#include "update_engine/payload_generator/payload_signer.h"
26#include "update_engine/payload_verifier.h"
27#include "update_engine/prefs.h"
28#include "update_engine/subprocess.h"
29#include "update_engine/terminator.h"
30#include "update_engine/update_metadata.pb.h"
31#include "update_engine/utils.h"
32
33// This file contains a simple program that takes an old path, a new path,
34// and an output file as arguments and the path to an output file and
35// generates a delta that can be sent to Chrome OS clients.
36
37using std::set;
38using std::string;
39using std::vector;
40
41namespace chromeos_update_engine {
42
43namespace {
44
45void ParseSignatureSizes(const string& signature_sizes_flag,
46                         vector<int>* signature_sizes) {
47  signature_sizes->clear();
48  vector<string> split_strings;
49
50  base::SplitString(signature_sizes_flag, ':', &split_strings);
51  for (const string& str : split_strings) {
52    int size = 0;
53    bool parsing_successful = base::StringToInt(str, &size);
54    LOG_IF(FATAL, !parsing_successful)
55        << "Invalid signature size: " << str;
56
57    LOG_IF(FATAL, size != (2048 / 8)) <<
58        "Only signature sizes of 256 bytes are supported.";
59
60    signature_sizes->push_back(size);
61  }
62}
63
64bool ParseImageInfo(const string& channel,
65                    const string& board,
66                    const string& version,
67                    const string& key,
68                    const string& build_channel,
69                    const string& build_version,
70                    ImageInfo* image_info) {
71  // All of these arguments should be present or missing.
72  bool empty = channel.empty();
73
74  CHECK_EQ(channel.empty(), empty);
75  CHECK_EQ(board.empty(), empty);
76  CHECK_EQ(version.empty(), empty);
77  CHECK_EQ(key.empty(), empty);
78
79  if (empty)
80    return false;
81
82  image_info->set_channel(channel);
83  image_info->set_board(board);
84  image_info->set_version(version);
85  image_info->set_key(key);
86
87  image_info->set_build_channel(
88      build_channel.empty() ? channel : build_channel);
89
90  image_info->set_build_version(
91      build_version.empty() ? version : build_version);
92
93  return true;
94}
95
96void CalculatePayloadHashForSigning(const vector<int> &sizes,
97                                    const string& out_hash_file,
98                                    const string& in_file) {
99  LOG(INFO) << "Calculating payload hash for signing.";
100  LOG_IF(FATAL, in_file.empty())
101      << "Must pass --in_file to calculate hash for signing.";
102  LOG_IF(FATAL, out_hash_file.empty())
103      << "Must pass --out_hash_file to calculate hash for signing.";
104
105  chromeos::Blob hash;
106  bool result = PayloadSigner::HashPayloadForSigning(in_file, sizes,
107                                                     &hash);
108  CHECK(result);
109
110  result = utils::WriteFile(out_hash_file.c_str(), hash.data(), hash.size());
111  CHECK(result);
112  LOG(INFO) << "Done calculating payload hash for signing.";
113}
114
115
116void CalculateMetadataHashForSigning(const vector<int> &sizes,
117                                     const string& out_metadata_hash_file,
118                                     const string& in_file) {
119  LOG(INFO) << "Calculating metadata hash for signing.";
120  LOG_IF(FATAL, in_file.empty())
121      << "Must pass --in_file to calculate metadata hash for signing.";
122  LOG_IF(FATAL, out_metadata_hash_file.empty())
123      << "Must pass --out_metadata_hash_file to calculate metadata hash.";
124
125  chromeos::Blob hash;
126  bool result = PayloadSigner::HashMetadataForSigning(in_file, sizes,
127                                                      &hash);
128  CHECK(result);
129
130  result = utils::WriteFile(out_metadata_hash_file.c_str(), hash.data(),
131                            hash.size());
132  CHECK(result);
133
134  LOG(INFO) << "Done calculating metadata hash for signing.";
135}
136
137void SignPayload(const string& in_file,
138                 const string& out_file,
139                 const string& signature_file) {
140  LOG(INFO) << "Signing payload.";
141  LOG_IF(FATAL, in_file.empty())
142      << "Must pass --in_file to sign payload.";
143  LOG_IF(FATAL, out_file.empty())
144      << "Must pass --out_file to sign payload.";
145  LOG_IF(FATAL, signature_file.empty())
146      << "Must pass --signature_file to sign payload.";
147  vector<chromeos::Blob> signatures;
148  vector<string> signature_files;
149  base::SplitString(signature_file, ':', &signature_files);
150  for (const string& signature_file : signature_files) {
151    chromeos::Blob signature;
152    CHECK(utils::ReadFile(signature_file, &signature));
153    signatures.push_back(signature);
154  }
155  uint64_t final_metadata_size;
156  CHECK(PayloadSigner::AddSignatureToPayload(
157      in_file, signatures, out_file, &final_metadata_size));
158  LOG(INFO) << "Done signing payload. Final metadata size = "
159            << final_metadata_size;
160}
161
162void VerifySignedPayload(const string& in_file,
163                         const string& public_key,
164                         int public_key_version) {
165  LOG(INFO) << "Verifying signed payload.";
166  LOG_IF(FATAL, in_file.empty())
167      << "Must pass --in_file to verify signed payload.";
168  LOG_IF(FATAL, public_key.empty())
169      << "Must pass --public_key to verify signed payload.";
170  CHECK(PayloadVerifier::VerifySignedPayload(in_file, public_key,
171                                             public_key_version));
172  LOG(INFO) << "Done verifying signed payload.";
173}
174
175void ApplyDelta(const string& in_file,
176                const string& old_kernel,
177                const string& old_rootfs,
178                const string& prefs_dir) {
179  LOG(INFO) << "Applying delta.";
180  LOG_IF(FATAL, old_rootfs.empty())
181      << "Must pass --old_image to apply delta.";
182  Prefs prefs;
183  InstallPlan install_plan;
184  LOG(INFO) << "Setting up preferences under: " << prefs_dir;
185  LOG_IF(ERROR, !prefs.Init(base::FilePath(prefs_dir)))
186      << "Failed to initialize preferences.";
187  // Get original checksums
188  LOG(INFO) << "Calculating original checksums";
189  PartitionInfo kern_info, root_info;
190  ImageConfig old_image;
191  old_image.kernel.path = old_kernel;
192  old_image.rootfs.path = old_rootfs;
193  CHECK(old_image.LoadImageSize());
194  CHECK(diff_utils::InitializePartitionInfo(old_image.kernel, &kern_info));
195  CHECK(diff_utils::InitializePartitionInfo(old_image.rootfs, &root_info));
196  install_plan.kernel_hash.assign(kern_info.hash().begin(),
197                                  kern_info.hash().end());
198  install_plan.rootfs_hash.assign(root_info.hash().begin(),
199                                  root_info.hash().end());
200  DeltaPerformer performer(&prefs, nullptr, &install_plan);
201  CHECK_EQ(performer.Open(old_rootfs.c_str(), 0, 0), 0);
202  CHECK(performer.OpenKernel(old_kernel.c_str()));
203  chromeos::Blob buf(1024 * 1024);
204  int fd = open(in_file.c_str(), O_RDONLY, 0);
205  CHECK_GE(fd, 0);
206  ScopedFdCloser fd_closer(&fd);
207  for (off_t offset = 0;; offset += buf.size()) {
208    ssize_t bytes_read;
209    CHECK(utils::PReadAll(fd, buf.data(), buf.size(), offset, &bytes_read));
210    if (bytes_read == 0)
211      break;
212    CHECK_EQ(performer.Write(buf.data(), bytes_read), bytes_read);
213  }
214  CHECK_EQ(performer.Close(), 0);
215  DeltaPerformer::ResetUpdateProgress(&prefs, false);
216  LOG(INFO) << "Done applying delta.";
217}
218
219int Main(int argc, char** argv) {
220  DEFINE_string(old_image, "", "Path to the old rootfs");
221  DEFINE_string(new_image, "", "Path to the new rootfs");
222  DEFINE_string(old_kernel, "", "Path to the old kernel partition image");
223  DEFINE_string(new_kernel, "", "Path to the new kernel partition image");
224  DEFINE_string(in_file, "",
225                "Path to input delta payload file used to hash/sign payloads "
226                "and apply delta over old_image (for debugging)");
227  DEFINE_string(out_file, "", "Path to output delta payload file");
228  DEFINE_string(out_hash_file, "", "Path to output hash file");
229  DEFINE_string(out_metadata_hash_file, "",
230                "Path to output metadata hash file");
231  DEFINE_string(private_key, "", "Path to private key in .pem format");
232  DEFINE_string(public_key, "", "Path to public key in .pem format");
233  DEFINE_int32(public_key_version,
234               chromeos_update_engine::kSignatureMessageCurrentVersion,
235               "Key-check version # of client");
236  DEFINE_string(prefs_dir, "/tmp/update_engine_prefs",
237                "Preferences directory, used with apply_delta");
238  DEFINE_string(signature_size, "",
239                "Raw signature size used for hash calculation. "
240                "You may pass in multiple sizes by colon separating them. E.g. "
241                "2048:2048:4096 will assume 3 signatures, the first two with "
242                "2048 size and the last 4096.");
243  DEFINE_string(signature_file, "",
244                "Raw signature file to sign payload with. To pass multiple "
245                "signatures, use a single argument with a colon between paths, "
246                "e.g. /path/to/sig:/path/to/next:/path/to/last_sig . Each "
247                "signature will be assigned a client version, starting from "
248                "kSignatureOriginalVersion.");
249  DEFINE_int32(chunk_size, 200 * 1024 * 1024,
250               "Payload chunk size (-1 for whole files)");
251  DEFINE_uint64(rootfs_partition_size,
252               chromeos_update_engine::kRootFSPartitionSize,
253               "RootFS partition size for the image once installed");
254  DEFINE_int32(minor_version, -1,
255               "The minor version of the payload being generated "
256               "(-1 means autodetect).");
257
258  DEFINE_string(old_channel, "",
259                "The channel for the old image. 'dev-channel', 'npo-channel', "
260                "etc. Ignored, except during delta generation.");
261  DEFINE_string(old_board, "",
262                "The board for the old image. 'x86-mario', 'lumpy', "
263                "etc. Ignored, except during delta generation.");
264  DEFINE_string(old_version, "",
265                "The build version of the old image. 1.2.3, etc.");
266  DEFINE_string(old_key, "",
267                "The key used to sign the old image. 'premp', 'mp', 'mp-v3',"
268                " etc");
269  DEFINE_string(old_build_channel, "",
270                "The channel for the build of the old image. 'dev-channel', "
271                "etc, but will never contain special channels such as "
272                "'npo-channel'. Ignored, except during delta generation.");
273  DEFINE_string(old_build_version, "",
274                "The version of the build containing the old image.");
275
276  DEFINE_string(new_channel, "",
277                "The channel for the new image. 'dev-channel', 'npo-channel', "
278                "etc. Ignored, except during delta generation.");
279  DEFINE_string(new_board, "",
280                "The board for the new image. 'x86-mario', 'lumpy', "
281                "etc. Ignored, except during delta generation.");
282  DEFINE_string(new_version, "",
283                "The build version of the new image. 1.2.3, etc.");
284  DEFINE_string(new_key, "",
285                "The key used to sign the new image. 'premp', 'mp', 'mp-v3',"
286                " etc");
287  DEFINE_string(new_build_channel, "",
288                "The channel for the build of the new image. 'dev-channel', "
289                "etc, but will never contain special channels such as "
290                "'npo-channel'. Ignored, except during delta generation.");
291  DEFINE_string(new_build_version, "",
292                "The version of the build containing the new image.");
293
294  chromeos::FlagHelper::Init(argc, argv,
295      "Generates a payload to provide to ChromeOS' update_engine.\n\n"
296      "This tool can create full payloads and also delta payloads if the src\n"
297      "image is provided. It also provides debugging options to apply, sign\n"
298      "and verify payloads.");
299  Terminator::Init();
300  Subprocess::Init();
301
302  logging::LoggingSettings log_settings;
303  log_settings.log_file     = "delta_generator.log";
304  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
305  log_settings.lock_log     = logging::LOCK_LOG_FILE;
306  log_settings.delete_old   = logging::APPEND_TO_OLD_LOG_FILE;
307
308  logging::InitLogging(log_settings);
309
310  vector<int> signature_sizes;
311  ParseSignatureSizes(FLAGS_signature_size, &signature_sizes);
312
313  if (!FLAGS_out_hash_file.empty() || !FLAGS_out_metadata_hash_file.empty()) {
314    if (!FLAGS_out_hash_file.empty()) {
315      CalculatePayloadHashForSigning(signature_sizes, FLAGS_out_hash_file,
316                                     FLAGS_in_file);
317    }
318    if (!FLAGS_out_metadata_hash_file.empty()) {
319      CalculateMetadataHashForSigning(signature_sizes,
320                                      FLAGS_out_metadata_hash_file,
321                                      FLAGS_in_file);
322    }
323    return 0;
324  }
325  if (!FLAGS_signature_file.empty()) {
326    SignPayload(FLAGS_in_file, FLAGS_out_file, FLAGS_signature_file);
327    return 0;
328  }
329  if (!FLAGS_public_key.empty()) {
330    VerifySignedPayload(FLAGS_in_file, FLAGS_public_key,
331                        FLAGS_public_key_version);
332    return 0;
333  }
334  if (!FLAGS_in_file.empty()) {
335    ApplyDelta(FLAGS_in_file, FLAGS_old_kernel, FLAGS_old_image,
336               FLAGS_prefs_dir);
337    return 0;
338  }
339
340  // A payload generation was requested. Convert the flags to a
341  // PayloadGenerationConfig.
342  PayloadGenerationConfig payload_config;
343  payload_config.source.rootfs.path = FLAGS_old_image;
344  payload_config.source.kernel.path = FLAGS_old_kernel;
345
346  payload_config.target.rootfs.path = FLAGS_new_image;
347  payload_config.target.kernel.path = FLAGS_new_kernel;
348
349  // Use the default soft_chunk_size defined in the config.
350  payload_config.hard_chunk_size = FLAGS_chunk_size;
351  payload_config.block_size = kBlockSize;
352
353  // The kernel and rootfs size is never passed to the delta_generator, so we
354  // need to detect those from the provided files.
355  if (!FLAGS_old_image.empty()) {
356    CHECK(payload_config.source.LoadImageSize());
357  }
358  if (!FLAGS_new_image.empty()) {
359    CHECK(payload_config.target.LoadImageSize());
360  }
361
362  payload_config.is_delta = !FLAGS_old_image.empty();
363
364  CHECK(!FLAGS_out_file.empty());
365
366  // Ignore failures. These are optional arguments.
367  ParseImageInfo(FLAGS_new_channel,
368                 FLAGS_new_board,
369                 FLAGS_new_version,
370                 FLAGS_new_key,
371                 FLAGS_new_build_channel,
372                 FLAGS_new_build_version,
373                 &payload_config.target.image_info);
374
375  // Ignore failures. These are optional arguments.
376  ParseImageInfo(FLAGS_old_channel,
377                 FLAGS_old_board,
378                 FLAGS_old_version,
379                 FLAGS_old_key,
380                 FLAGS_old_build_channel,
381                 FLAGS_old_build_version,
382                 &payload_config.source.image_info);
383
384  payload_config.rootfs_partition_size = FLAGS_rootfs_partition_size;
385
386  // Load the rootfs size from verity's kernel command line if rootfs
387  // verification is enabled.
388  payload_config.source.LoadVerityRootfsSize();
389  payload_config.target.LoadVerityRootfsSize();
390
391  if (payload_config.is_delta) {
392    // Avoid opening the filesystem interface for full payloads.
393    CHECK(payload_config.target.rootfs.OpenFilesystem());
394    CHECK(payload_config.target.kernel.OpenFilesystem());
395    CHECK(payload_config.source.rootfs.OpenFilesystem());
396    CHECK(payload_config.source.kernel.OpenFilesystem());
397  }
398
399  if (FLAGS_minor_version == -1) {
400    // Autodetect minor_version by looking at the update_engine.conf in the old
401    // image.
402    if (payload_config.is_delta) {
403      CHECK(payload_config.source.rootfs.fs_interface);
404      chromeos::KeyValueStore store;
405      uint32_t minor_version;
406      if (payload_config.source.rootfs.fs_interface->LoadSettings(&store) &&
407          utils::GetMinorVersion(store, &minor_version)) {
408        payload_config.minor_version = minor_version;
409      } else {
410        payload_config.minor_version = kInPlaceMinorPayloadVersion;
411      }
412    } else {
413      payload_config.minor_version = DeltaPerformer::kFullPayloadMinorVersion;
414    }
415    LOG(INFO) << "Auto-detected minor_version=" << payload_config.minor_version;
416  } else {
417    payload_config.minor_version = FLAGS_minor_version;
418    LOG(INFO) << "Using provided minor_version=" << FLAGS_minor_version;
419  }
420
421  if (payload_config.is_delta) {
422    LOG(INFO) << "Generating delta update";
423  } else {
424    LOG(INFO) << "Generating full update";
425  }
426
427  // From this point, all the options have been parsed.
428  if (!payload_config.Validate()) {
429    LOG(ERROR) << "Invalid options passed. See errors above.";
430    return 1;
431  }
432
433  uint64_t metadata_size;
434  if (!GenerateUpdatePayloadFile(payload_config,
435                                 FLAGS_out_file,
436                                 FLAGS_private_key,
437                                 &metadata_size)) {
438    return 1;
439  }
440
441  return 0;
442}
443
444}  // namespace
445
446}  // namespace chromeos_update_engine
447
448int main(int argc, char** argv) {
449  return chromeos_update_engine::Main(argc, argv);
450}
451