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