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