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