generate_delta_main.cc revision 9b244df41f1bdaddd87b7dbd8e1559556059ed1b
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/payload_generation_config.h"
24#include "update_engine/payload_generator/payload_signer.h"
25#include "update_engine/payload_verifier.h"
26#include "update_engine/prefs.h"
27#include "update_engine/subprocess.h"
28#include "update_engine/terminator.h"
29#include "update_engine/update_metadata.pb.h"
30#include "update_engine/utils.h"
31
32// This file contains a simple program that takes an old path, a new path,
33// and an output file as arguments and the path to an output file and
34// generates a delta that can be sent to Chrome OS clients.
35
36using std::set;
37using std::string;
38using std::vector;
39
40namespace chromeos_update_engine {
41
42namespace {
43
44void ParseSignatureSizes(const string& signature_sizes_flag,
45                         vector<int>* signature_sizes) {
46  signature_sizes->clear();
47  vector<string> split_strings;
48
49  base::SplitString(signature_sizes_flag, ':', &split_strings);
50  for (const string& str : split_strings) {
51    int size = 0;
52    bool parsing_successful = base::StringToInt(str, &size);
53    LOG_IF(FATAL, !parsing_successful)
54        << "Invalid signature size: " << str;
55
56    LOG_IF(FATAL, size != (2048 / 8)) <<
57        "Only signature sizes of 256 bytes are supported.";
58
59    signature_sizes->push_back(size);
60  }
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_image,
178                const string& prefs_dir) {
179  LOG(INFO) << "Applying delta.";
180  LOG_IF(FATAL, old_image.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  CHECK(DeltaDiffGenerator::InitializePartitionInfo(true,  // is_kernel
191                                                    old_kernel,
192                                                    &kern_info));
193  CHECK(DeltaDiffGenerator::InitializePartitionInfo(false,  // is_kernel
194                                                    old_image,
195                                                    &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_image.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_dir, "",
221                "Directory where the old rootfs is loop mounted read-only");
222  DEFINE_string(new_dir, "",
223                "Directory where the new rootfs is loop mounted read-only");
224  DEFINE_string(old_image, "", "Path to the old rootfs");
225  DEFINE_string(new_image, "", "Path to the new rootfs");
226  DEFINE_string(old_kernel, "", "Path to the old kernel partition image");
227  DEFINE_string(new_kernel, "", "Path to the new kernel partition image");
228  DEFINE_string(in_file, "",
229                "Path to input delta payload file used to hash/sign payloads "
230                "and apply delta over old_image (for debugging)");
231  DEFINE_string(out_file, "", "Path to output delta payload file");
232  DEFINE_string(out_hash_file, "", "Path to output hash file");
233  DEFINE_string(out_metadata_hash_file, "",
234                "Path to output metadata hash file");
235  DEFINE_string(private_key, "", "Path to private key in .pem format");
236  DEFINE_string(public_key, "", "Path to public key in .pem format");
237  DEFINE_int32(public_key_version,
238               chromeos_update_engine::kSignatureMessageCurrentVersion,
239               "Key-check version # of client");
240  DEFINE_string(prefs_dir, "/tmp/update_engine_prefs",
241                "Preferences directory, used with apply_delta");
242  DEFINE_string(signature_size, "",
243                "Raw signature size used for hash calculation. "
244                "You may pass in multiple sizes by colon separating them. E.g. "
245                "2048:2048:4096 will assume 3 signatures, the first two with "
246                "2048 size and the last 4096.");
247  DEFINE_string(signature_file, "",
248                "Raw signature file to sign payload with. To pass multiple "
249                "signatures, use a single argument with a colon between paths, "
250                "e.g. /path/to/sig:/path/to/next:/path/to/last_sig . Each "
251                "signature will be assigned a client version, starting from "
252                "kSignatureOriginalVersion.");
253  DEFINE_int32(chunk_size, -1, "Payload chunk size (-1 -- no limit/default)");
254  DEFINE_uint64(rootfs_partition_size,
255               chromeos_update_engine::kRootFSPartitionSize,
256               "RootFS partition size for the image once installed");
257  DEFINE_int32(minor_version, DeltaPerformer::kFullPayloadMinorVersion,
258               "The minor version of the payload being generated");
259
260  DEFINE_string(old_channel, "",
261                "The channel for the old image. 'dev-channel', 'npo-channel', "
262                "etc. Ignored, except during delta generation.");
263  DEFINE_string(old_board, "",
264                "The board for the old image. 'x86-mario', 'lumpy', "
265                "etc. Ignored, except during delta generation.");
266  DEFINE_string(old_version, "",
267                "The build version of the old image. 1.2.3, etc.");
268  DEFINE_string(old_key, "",
269                "The key used to sign the old image. 'premp', 'mp', 'mp-v3',"
270                " etc");
271  DEFINE_string(old_build_channel, "",
272                "The channel for the build of the old image. 'dev-channel', "
273                "etc, but will never contain special channels such as "
274                "'npo-channel'. Ignored, except during delta generation.");
275  DEFINE_string(old_build_version, "",
276                "The version of the build containing the old image.");
277
278  DEFINE_string(new_channel, "",
279                "The channel for the new image. 'dev-channel', 'npo-channel', "
280                "etc. Ignored, except during delta generation.");
281  DEFINE_string(new_board, "",
282                "The board for the new image. 'x86-mario', 'lumpy', "
283                "etc. Ignored, except during delta generation.");
284  DEFINE_string(new_version, "",
285                "The build version of the new image. 1.2.3, etc.");
286  DEFINE_string(new_key, "",
287                "The key used to sign the new image. 'premp', 'mp', 'mp-v3',"
288                " etc");
289  DEFINE_string(new_build_channel, "",
290                "The channel for the build of the new image. 'dev-channel', "
291                "etc, but will never contain special channels such as "
292                "'npo-channel'. Ignored, except during delta generation.");
293  DEFINE_string(new_build_version, "",
294                "The version of the build containing the new image.");
295
296  chromeos::FlagHelper::Init(argc, argv,
297      "Generates a payload to provide to ChromeOS' update_engine.\n\n"
298      "This tool can create full payloads and also delta payloads if the src\n"
299      "image is provided. It also provides debugging options to apply, sign\n"
300      "and verify payloads.");
301  Terminator::Init();
302  Subprocess::Init();
303
304  logging::LoggingSettings log_settings;
305  log_settings.log_file     = "delta_generator.log";
306  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
307  log_settings.lock_log     = logging::DONT_LOCK_LOG_FILE;
308  log_settings.delete_old   = logging::APPEND_TO_OLD_LOG_FILE;
309
310  logging::InitLogging(log_settings);
311
312  vector<int> signature_sizes;
313  ParseSignatureSizes(FLAGS_signature_size, &signature_sizes);
314
315  if (!FLAGS_out_hash_file.empty() || !FLAGS_out_metadata_hash_file.empty()) {
316    if (!FLAGS_out_hash_file.empty()) {
317      CalculatePayloadHashForSigning(signature_sizes, FLAGS_out_hash_file,
318                                     FLAGS_in_file);
319    }
320    if (!FLAGS_out_metadata_hash_file.empty()) {
321      CalculateMetadataHashForSigning(signature_sizes,
322                                      FLAGS_out_metadata_hash_file,
323                                      FLAGS_in_file);
324    }
325    return 0;
326  }
327  if (!FLAGS_signature_file.empty()) {
328    SignPayload(FLAGS_in_file, FLAGS_out_file, FLAGS_signature_file);
329    return 0;
330  }
331  if (!FLAGS_public_key.empty()) {
332    VerifySignedPayload(FLAGS_in_file, FLAGS_public_key,
333                        FLAGS_public_key_version);
334    return 0;
335  }
336  if (!FLAGS_in_file.empty()) {
337    ApplyDelta(FLAGS_in_file, FLAGS_old_kernel, FLAGS_old_image,
338               FLAGS_prefs_dir);
339    return 0;
340  }
341
342  // A payload generation was requested. Convert the flags to a
343  // PayloadGenerationConfig.
344  PayloadGenerationConfig payload_config;
345  payload_config.source.rootfs_part = FLAGS_old_image;
346  payload_config.source.rootfs_mountpt = FLAGS_old_dir;
347  payload_config.source.kernel_part = FLAGS_old_kernel;
348
349  payload_config.target.rootfs_part = FLAGS_new_image;
350  payload_config.target.rootfs_mountpt = FLAGS_new_dir;
351  payload_config.target.kernel_part = FLAGS_new_kernel;
352
353  payload_config.chunk_size = FLAGS_chunk_size;
354  payload_config.block_size = kBlockSize;
355
356  // The kernel and rootfs size is never passed to the delta_generator, so we
357  // need to detect those from the provided files.
358  if (!FLAGS_old_image.empty()) {
359    CHECK(payload_config.source.LoadImageSize());
360  }
361  if (!FLAGS_new_image.empty()) {
362    CHECK(payload_config.target.LoadImageSize());
363  }
364
365  payload_config.is_delta = !FLAGS_old_image.empty();
366
367  CHECK(!FLAGS_out_file.empty());
368
369  // Ignore failures. These are optional arguments.
370  ParseImageInfo(FLAGS_new_channel,
371                 FLAGS_new_board,
372                 FLAGS_new_version,
373                 FLAGS_new_key,
374                 FLAGS_new_build_channel,
375                 FLAGS_new_build_version,
376                 &payload_config.target.image_info);
377
378  // Ignore failures. These are optional arguments.
379  ParseImageInfo(FLAGS_old_channel,
380                 FLAGS_old_board,
381                 FLAGS_old_version,
382                 FLAGS_old_key,
383                 FLAGS_old_build_channel,
384                 FLAGS_old_build_version,
385                 &payload_config.source.image_info);
386
387  payload_config.rootfs_partition_size = FLAGS_rootfs_partition_size;
388  payload_config.minor_version = FLAGS_minor_version;
389  // Look for the minor version in the old image if it was not given as an
390  // argument.
391  if (payload_config.is_delta &&
392      !CommandLine::ForCurrentProcess()->HasSwitch("minor_version")) {
393    uint32_t minor_version;
394    base::FilePath image_path(FLAGS_old_dir);
395    base::FilePath conf_loc("etc/update_engine.conf");
396    base::FilePath conf_path = image_path.Append(conf_loc);
397    if (utils::GetMinorVersion(conf_path, &minor_version)) {
398      payload_config.minor_version = minor_version;
399    } else {
400      payload_config.minor_version = kInPlaceMinorPayloadVersion;
401    }
402  }
403
404  // Full payloads use a hard-coded chunk_size of 1 MiB.
405  if (!payload_config.is_delta) {
406    payload_config.chunk_size = 1024 * 1024;
407  }
408
409  if (payload_config.is_delta) {
410    LOG(INFO) << "Generating delta update";
411  } else {
412    LOG(INFO) << "Generating full update";
413  }
414
415  // From this point, all the options have been parsed.
416  if (!payload_config.Validate()) {
417    LOG(FATAL) << "Invalid options passed. See errors above.";
418  }
419
420  uint64_t metadata_size;
421  if (!DeltaDiffGenerator::GenerateDeltaUpdateFile(
422      payload_config,
423      FLAGS_out_file,
424      FLAGS_private_key,
425      &metadata_size)) {
426    return 1;
427  }
428
429  return 0;
430}
431
432}  // namespace
433
434}  // namespace chromeos_update_engine
435
436int main(int argc, char** argv) {
437  return chromeos_update_engine::Main(argc, argv);
438}
439