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 <string>
18 #include <vector>
19 
20 #include <base/files/file_path.h>
21 #include <base/files/file_util.h>
22 #include <base/logging.h>
23 #include <base/strings/string_number_conversions.h>
24 #include <base/strings/string_split.h>
25 #include <brillo/flag_helper.h>
26 #include <brillo/key_value_store.h>
27 #include <brillo/message_loops/base_message_loop.h>
28 #include <xz.h>
29 
30 #include "update_engine/common/fake_boot_control.h"
31 #include "update_engine/common/fake_hardware.h"
32 #include "update_engine/common/file_fetcher.h"
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/download_action.h"
37 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
38 #include "update_engine/payload_consumer/payload_constants.h"
39 #include "update_engine/payload_generator/delta_diff_generator.h"
40 #include "update_engine/payload_generator/payload_generation_config.h"
41 #include "update_engine/payload_generator/payload_properties.h"
42 #include "update_engine/payload_generator/payload_signer.h"
43 #include "update_engine/payload_generator/xz.h"
44 #include "update_engine/update_metadata.pb.h"
45 
46 // This file contains a simple program that takes an old path, a new path,
47 // and an output file as arguments and the path to an output file and
48 // generates a delta that can be sent to Chrome OS clients.
49 
50 using std::string;
51 using std::vector;
52 
53 namespace chromeos_update_engine {
54 
55 namespace {
56 
57 constexpr char kPayloadPropertiesFormatKeyValue[] = "key-value";
58 constexpr char kPayloadPropertiesFormatJson[] = "json";
59 
ParseSignatureSizes(const string & signature_sizes_flag,vector<size_t> * signature_sizes)60 void ParseSignatureSizes(const string& signature_sizes_flag,
61                          vector<size_t>* signature_sizes) {
62   signature_sizes->clear();
63   vector<string> split_strings = base::SplitString(
64       signature_sizes_flag, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
65   for (const string& str : split_strings) {
66     size_t size = 0;
67     bool parsing_successful = base::StringToSizeT(str, &size);
68     LOG_IF(FATAL, !parsing_successful) << "Invalid signature size: " << str;
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(build_channel.empty() ? channel
98                                                       : build_channel);
99 
100   image_info->set_build_version(build_version.empty() ? version
101                                                       : build_version);
102 
103   return true;
104 }
105 
CalculateHashForSigning(const vector<size_t> & sizes,const string & out_hash_file,const string & out_metadata_hash_file,const string & in_file)106 void CalculateHashForSigning(const vector<size_t>& 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(
118       in_file, sizes, &payload_hash, &metadata_hash));
119   CHECK(utils::WriteFile(
120       out_hash_file.c_str(), payload_hash.data(), payload_hash.size()));
121   if (!out_metadata_hash_file.empty())
122     CHECK(utils::WriteFile(out_metadata_hash_file.c_str(),
123                            metadata_hash.data(),
124                            metadata_hash.size()));
125 
126   LOG(INFO) << "Done calculating hash for signing.";
127 }
128 
SignatureFileFlagToBlobs(const string & signature_file_flag,vector<brillo::Blob> * signatures)129 void SignatureFileFlagToBlobs(const string& signature_file_flag,
130                               vector<brillo::Blob>* signatures) {
131   vector<string> signature_files = base::SplitString(
132       signature_file_flag, ":", base::TRIM_WHITESPACE, 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 vector<size_t> & signature_sizes,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 vector<size_t>& signature_sizes,
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()) << "Must pass --in_file to sign payload.";
148   LOG_IF(FATAL, out_file.empty()) << "Must pass --out_file to sign payload.";
149   LOG_IF(FATAL, payload_signature_file.empty())
150       << "Must pass --payload_signature_file to sign payload.";
151   vector<brillo::Blob> payload_signatures, metadata_signatures;
152   SignatureFileFlagToBlobs(payload_signature_file, &payload_signatures);
153   SignatureFileFlagToBlobs(metadata_signature_file, &metadata_signatures);
154   uint64_t final_metadata_size;
155   CHECK(PayloadSigner::AddSignatureToPayload(in_file,
156                                              signature_sizes,
157                                              payload_signatures,
158                                              metadata_signatures,
159                                              out_file,
160                                              &final_metadata_size));
161   LOG(INFO) << "Done signing payload. Final metadata size = "
162             << final_metadata_size;
163   if (!out_metadata_size_file.empty()) {
164     string metadata_size_string = std::to_string(final_metadata_size);
165     CHECK(utils::WriteFile(out_metadata_size_file.c_str(),
166                            metadata_size_string.data(),
167                            metadata_size_string.size()));
168   }
169 }
170 
VerifySignedPayload(const string & in_file,const string & public_key)171 int VerifySignedPayload(const string& in_file, const string& public_key) {
172   LOG(INFO) << "Verifying signed payload.";
173   LOG_IF(FATAL, in_file.empty())
174       << "Must pass --in_file to verify signed payload.";
175   LOG_IF(FATAL, public_key.empty())
176       << "Must pass --public_key to verify signed payload.";
177   if (!PayloadSigner::VerifySignedPayload(in_file, public_key)) {
178     LOG(INFO) << "VerifySignedPayload failed";
179     return 1;
180   }
181 
182   LOG(INFO) << "Done verifying signed payload.";
183   return 0;
184 }
185 
186 class ApplyPayloadProcessorDelegate : public ActionProcessorDelegate {
187  public:
ProcessingDone(const ActionProcessor * processor,ErrorCode code)188   void ProcessingDone(const ActionProcessor* processor,
189                       ErrorCode code) override {
190     brillo::MessageLoop::current()->BreakLoop();
191     code_ = code;
192   }
ProcessingStopped(const ActionProcessor * processor)193   void ProcessingStopped(const ActionProcessor* processor) override {
194     brillo::MessageLoop::current()->BreakLoop();
195   }
196   ErrorCode code_;
197 };
198 
199 // TODO(deymo): Move this function to a new file and make the delta_performer
200 // integration tests use this instead.
ApplyPayload(const string & payload_file,const PayloadGenerationConfig & config)201 bool ApplyPayload(const string& payload_file,
202                   // Simply reuses the payload config used for payload
203                   // generation.
204                   const PayloadGenerationConfig& config) {
205   LOG(INFO) << "Applying delta.";
206   FakeBootControl fake_boot_control;
207   FakeHardware fake_hardware;
208   MemoryPrefs prefs;
209   InstallPlan install_plan;
210   InstallPlan::Payload payload;
211   install_plan.source_slot =
212       config.is_delta ? 0 : BootControlInterface::kInvalidSlot;
213   install_plan.target_slot = 1;
214   payload.type =
215       config.is_delta ? InstallPayloadType::kDelta : InstallPayloadType::kFull;
216   payload.size = utils::FileSize(payload_file);
217   // TODO(senj): This hash is only correct for unsigned payload, need to support
218   // signed payload using PayloadSigner.
219   HashCalculator::RawHashOfFile(payload_file, payload.size, &payload.hash);
220   install_plan.payloads = {payload};
221   install_plan.download_url =
222       "file://" +
223       base::MakeAbsoluteFilePath(base::FilePath(payload_file)).value();
224 
225   for (size_t i = 0; i < config.target.partitions.size(); i++) {
226     const string& part_name = config.target.partitions[i].name;
227     const string& target_path = config.target.partitions[i].path;
228     fake_boot_control.SetPartitionDevice(
229         part_name, install_plan.target_slot, target_path);
230 
231     string source_path;
232     if (config.is_delta) {
233       TEST_AND_RETURN_FALSE(config.target.partitions.size() ==
234                             config.source.partitions.size());
235       source_path = config.source.partitions[i].path;
236       fake_boot_control.SetPartitionDevice(
237           part_name, install_plan.source_slot, source_path);
238     }
239 
240     LOG(INFO) << "Install partition:"
241               << " source: " << source_path << "\ttarget: " << target_path;
242   }
243 
244   xz_crc32_init();
245   brillo::BaseMessageLoop loop;
246   loop.SetAsCurrent();
247   auto install_plan_action = std::make_unique<InstallPlanAction>(install_plan);
248   auto download_action =
249       std::make_unique<DownloadAction>(&prefs,
250                                        &fake_boot_control,
251                                        &fake_hardware,
252                                        nullptr,
253                                        new FileFetcher(),
254                                        true /* interactive */);
255   auto filesystem_verifier_action = std::make_unique<FilesystemVerifierAction>(
256       fake_boot_control.GetDynamicPartitionControl());
257 
258   BondActions(install_plan_action.get(), download_action.get());
259   BondActions(download_action.get(), filesystem_verifier_action.get());
260   ActionProcessor processor;
261   ApplyPayloadProcessorDelegate delegate;
262   processor.set_delegate(&delegate);
263   processor.EnqueueAction(std::move(install_plan_action));
264   processor.EnqueueAction(std::move(download_action));
265   processor.EnqueueAction(std::move(filesystem_verifier_action));
266   processor.StartProcessing();
267   loop.Run();
268   CHECK_EQ(delegate.code_, ErrorCode::kSuccess);
269   LOG(INFO) << "Completed applying " << (config.is_delta ? "delta" : "full")
270             << " payload.";
271   return true;
272 }
273 
ExtractProperties(const string & payload_path,const string & props_file,const string & props_format)274 bool ExtractProperties(const string& payload_path,
275                        const string& props_file,
276                        const string& props_format) {
277   string properties;
278   PayloadProperties payload_props(payload_path);
279   if (props_format == kPayloadPropertiesFormatKeyValue) {
280     TEST_AND_RETURN_FALSE(payload_props.GetPropertiesAsKeyValue(&properties));
281   } else if (props_format == kPayloadPropertiesFormatJson) {
282     TEST_AND_RETURN_FALSE(payload_props.GetPropertiesAsJson(&properties));
283   } else {
284     LOG(FATAL) << "Invalid option " << props_format
285                << " for --properties_format flag.";
286   }
287   if (props_file == "-") {
288     printf("%s", properties.c_str());
289   } else {
290     utils::WriteFile(
291         props_file.c_str(), properties.c_str(), properties.length());
292     LOG(INFO) << "Generated properties file at " << props_file;
293   }
294   return true;
295 }
296 
Main(int argc,char ** argv)297 int Main(int argc, char** argv) {
298   DEFINE_string(old_image, "", "Path to the old rootfs");
299   DEFINE_string(new_image, "", "Path to the new rootfs");
300   DEFINE_string(old_kernel, "", "Path to the old kernel partition image");
301   DEFINE_string(new_kernel, "", "Path to the new kernel partition image");
302   DEFINE_string(old_partitions,
303                 "",
304                 "Path to the old partitions. To pass multiple partitions, use "
305                 "a single argument with a colon between paths, e.g. "
306                 "/path/to/part:/path/to/part2::/path/to/last_part . Path can "
307                 "be empty, but it has to match the order of partition_names.");
308   DEFINE_string(new_partitions,
309                 "",
310                 "Path to the new partitions. To pass multiple partitions, use "
311                 "a single argument with a colon between paths, e.g. "
312                 "/path/to/part:/path/to/part2:/path/to/last_part . Path has "
313                 "to match the order of partition_names.");
314   DEFINE_string(old_mapfiles,
315                 "",
316                 "Path to the .map files associated with the partition files "
317                 "in the old partition. The .map file is normally generated "
318                 "when creating the image in Android builds. Only recommended "
319                 "for unsupported filesystem. Pass multiple files separated by "
320                 "a colon as with -old_partitions.");
321   DEFINE_string(new_mapfiles,
322                 "",
323                 "Path to the .map files associated with the partition files "
324                 "in the new partition, similar to the -old_mapfiles flag.");
325   DEFINE_string(partition_names,
326                 string(kPartitionNameRoot) + ":" + kPartitionNameKernel,
327                 "Names of the partitions. To pass multiple names, use a single "
328                 "argument with a colon between names, e.g. "
329                 "name:name2:name3:last_name . Name can not be empty, and it "
330                 "has to match the order of partitions.");
331   DEFINE_string(in_file,
332                 "",
333                 "Path to input delta payload file used to hash/sign payloads "
334                 "and apply delta over old_image (for debugging)");
335   DEFINE_string(out_file, "", "Path to output delta payload file");
336   DEFINE_string(out_hash_file, "", "Path to output hash file");
337   DEFINE_string(
338       out_metadata_hash_file, "", "Path to output metadata hash file");
339   DEFINE_string(
340       out_metadata_size_file, "", "Path to output metadata size file");
341   DEFINE_string(private_key, "", "Path to private key in .pem format");
342   DEFINE_string(public_key, "", "Path to public key in .pem format");
343   DEFINE_int32(
344       public_key_version, -1, "DEPRECATED. Key-check version # of client");
345   DEFINE_string(signature_size,
346                 "",
347                 "Raw signature size used for hash calculation. "
348                 "You may pass in multiple sizes by colon separating them. E.g. "
349                 "2048:2048:4096 will assume 3 signatures, the first two with "
350                 "2048 size and the last 4096.");
351   DEFINE_string(payload_signature_file,
352                 "",
353                 "Raw signature file to sign payload with. To pass multiple "
354                 "signatures, use a single argument with a colon between paths, "
355                 "e.g. /path/to/sig:/path/to/next:/path/to/last_sig . Each "
356                 "signature will be assigned a client version, starting from "
357                 "kSignatureOriginalVersion.");
358   DEFINE_string(metadata_signature_file,
359                 "",
360                 "Raw signature file with the signature of the metadata hash. "
361                 "To pass multiple signatures, use a single argument with a "
362                 "colon between paths, "
363                 "e.g. /path/to/sig:/path/to/next:/path/to/last_sig .");
364   DEFINE_int32(
365       chunk_size, 200 * 1024 * 1024, "Payload chunk size (-1 for whole files)");
366   DEFINE_uint64(rootfs_partition_size,
367                 chromeos_update_engine::kRootFSPartitionSize,
368                 "RootFS partition size for the image once installed");
369   DEFINE_uint64(
370       major_version, 2, "The major version of the payload being generated.");
371   DEFINE_int32(minor_version,
372                -1,
373                "The minor version of the payload being generated "
374                "(-1 means autodetect).");
375   DEFINE_string(properties_file,
376                 "",
377                 "If passed, dumps the payload properties of the payload passed "
378                 "in --in_file and exits. Look at --properties_format.");
379   DEFINE_string(properties_format,
380                 kPayloadPropertiesFormatKeyValue,
381                 "Defines the format of the --properties_file. The acceptable "
382                 "values are: key-value (default) and json");
383   DEFINE_int64(max_timestamp,
384                0,
385                "The maximum timestamp of the OS allowed to apply this "
386                "payload.");
387 
388   DEFINE_string(old_channel,
389                 "",
390                 "The channel for the old image. 'dev-channel', 'npo-channel', "
391                 "etc. Ignored, except during delta generation.");
392   DEFINE_string(old_board,
393                 "",
394                 "The board for the old image. 'x86-mario', 'lumpy', "
395                 "etc. Ignored, except during delta generation.");
396   DEFINE_string(
397       old_version, "", "The build version of the old image. 1.2.3, etc.");
398   DEFINE_string(old_key,
399                 "",
400                 "The key used to sign the old image. 'premp', 'mp', 'mp-v3',"
401                 " etc");
402   DEFINE_string(old_build_channel,
403                 "",
404                 "The channel for the build of the old image. 'dev-channel', "
405                 "etc, but will never contain special channels such as "
406                 "'npo-channel'. Ignored, except during delta generation.");
407   DEFINE_string(old_build_version,
408                 "",
409                 "The version of the build containing the old image.");
410 
411   DEFINE_string(new_channel,
412                 "",
413                 "The channel for the new image. 'dev-channel', 'npo-channel', "
414                 "etc. Ignored, except during delta generation.");
415   DEFINE_string(new_board,
416                 "",
417                 "The board for the new image. 'x86-mario', 'lumpy', "
418                 "etc. Ignored, except during delta generation.");
419   DEFINE_string(
420       new_version, "", "The build version of the new image. 1.2.3, etc.");
421   DEFINE_string(new_key,
422                 "",
423                 "The key used to sign the new image. 'premp', 'mp', 'mp-v3',"
424                 " etc");
425   DEFINE_string(new_build_channel,
426                 "",
427                 "The channel for the build of the new image. 'dev-channel', "
428                 "etc, but will never contain special channels such as "
429                 "'npo-channel'. Ignored, except during delta generation.");
430   DEFINE_string(new_build_version,
431                 "",
432                 "The version of the build containing the new image.");
433   DEFINE_string(new_postinstall_config_file,
434                 "",
435                 "A config file specifying postinstall related metadata. "
436                 "Only allowed in major version 2 or newer.");
437   DEFINE_string(dynamic_partition_info_file,
438                 "",
439                 "An info file specifying dynamic partition metadata. "
440                 "Only allowed in major version 2 or newer.");
441   DEFINE_bool(disable_fec_computation,
442               false,
443               "Disables the fec data computation on device.");
444   DEFINE_string(
445       out_maximum_signature_size_file,
446       "",
447       "Path to the output maximum signature size given a private key.");
448   DEFINE_bool(is_partial_update,
449               false,
450               "The payload only targets a subset of partitions on the device,"
451               "e.g. generic kernel image update.");
452 
453   brillo::FlagHelper::Init(
454       argc,
455       argv,
456       "Generates a payload to provide to ChromeOS' update_engine.\n\n"
457       "This tool can create full payloads and also delta payloads if the src\n"
458       "image is provided. It also provides debugging options to apply, sign\n"
459       "and verify payloads.");
460   Terminator::Init();
461 
462   logging::LoggingSettings log_settings;
463   log_settings.log_file = "delta_generator.log";
464   log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
465   log_settings.lock_log = logging::LOCK_LOG_FILE;
466   log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
467 
468   logging::InitLogging(log_settings);
469 
470   // Initialize the Xz compressor.
471   XzCompressInit();
472 
473   if (!FLAGS_out_maximum_signature_size_file.empty()) {
474     LOG_IF(FATAL, FLAGS_private_key.empty())
475         << "Private key is not provided when calculating the maximum signature "
476            "size.";
477 
478     size_t maximum_signature_size;
479     if (!PayloadSigner::GetMaximumSignatureSize(FLAGS_private_key,
480                                                 &maximum_signature_size)) {
481       LOG(ERROR) << "Failed to get the maximum signature size of private key: "
482                  << FLAGS_private_key;
483       return 1;
484     }
485     // Write the size string to output file.
486     string signature_size_string = std::to_string(maximum_signature_size);
487     if (!utils::WriteFile(FLAGS_out_maximum_signature_size_file.c_str(),
488                           signature_size_string.c_str(),
489                           signature_size_string.size())) {
490       PLOG(ERROR) << "Failed to write the maximum signature size to "
491                   << FLAGS_out_maximum_signature_size_file << ".";
492       return 1;
493     }
494     return 0;
495   }
496 
497   vector<size_t> signature_sizes;
498   if (!FLAGS_signature_size.empty()) {
499     ParseSignatureSizes(FLAGS_signature_size, &signature_sizes);
500   }
501 
502   if (!FLAGS_out_hash_file.empty() || !FLAGS_out_metadata_hash_file.empty()) {
503     CHECK(FLAGS_out_metadata_size_file.empty());
504     CalculateHashForSigning(signature_sizes,
505                             FLAGS_out_hash_file,
506                             FLAGS_out_metadata_hash_file,
507                             FLAGS_in_file);
508     return 0;
509   }
510   if (!FLAGS_payload_signature_file.empty()) {
511     SignPayload(FLAGS_in_file,
512                 FLAGS_out_file,
513                 signature_sizes,
514                 FLAGS_payload_signature_file,
515                 FLAGS_metadata_signature_file,
516                 FLAGS_out_metadata_size_file);
517     return 0;
518   }
519   if (!FLAGS_public_key.empty()) {
520     LOG_IF(WARNING, FLAGS_public_key_version != -1)
521         << "--public_key_version is deprecated and ignored.";
522     return VerifySignedPayload(FLAGS_in_file, FLAGS_public_key);
523   }
524   if (!FLAGS_properties_file.empty()) {
525     return ExtractProperties(
526                FLAGS_in_file, FLAGS_properties_file, FLAGS_properties_format)
527                ? 0
528                : 1;
529   }
530 
531   // A payload generation was requested. Convert the flags to a
532   // PayloadGenerationConfig.
533   PayloadGenerationConfig payload_config;
534   vector<string> partition_names, old_partitions, new_partitions;
535   vector<string> old_mapfiles, new_mapfiles;
536 
537   if (!FLAGS_old_mapfiles.empty()) {
538     old_mapfiles = base::SplitString(
539         FLAGS_old_mapfiles, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
540   }
541   if (!FLAGS_new_mapfiles.empty()) {
542     new_mapfiles = base::SplitString(
543         FLAGS_new_mapfiles, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
544   }
545 
546   partition_names = base::SplitString(
547       FLAGS_partition_names, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
548   CHECK(!partition_names.empty());
549   if (FLAGS_major_version < kMinSupportedMajorPayloadVersion ||
550       FLAGS_major_version > kMaxSupportedMajorPayloadVersion) {
551     LOG(FATAL) << "Unsupported major version " << FLAGS_major_version;
552     return 1;
553   }
554 
555   if (!FLAGS_new_partitions.empty()) {
556     LOG_IF(FATAL, !FLAGS_new_image.empty() || !FLAGS_new_kernel.empty())
557         << "--new_image and --new_kernel are deprecated, please use "
558         << "--new_partitions for all partitions.";
559     new_partitions = base::SplitString(
560         FLAGS_new_partitions, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
561     CHECK(partition_names.size() == new_partitions.size());
562 
563     payload_config.is_delta = !FLAGS_old_partitions.empty();
564     LOG_IF(FATAL, !FLAGS_old_image.empty() || !FLAGS_old_kernel.empty())
565         << "--old_image and --old_kernel are deprecated, please use "
566         << "--old_partitions if you are using --new_partitions.";
567   } else {
568     new_partitions = {FLAGS_new_image, FLAGS_new_kernel};
569     LOG(WARNING) << "--new_partitions is empty, using deprecated --new_image "
570                  << "and --new_kernel flags.";
571 
572     payload_config.is_delta =
573         !FLAGS_old_image.empty() || !FLAGS_old_kernel.empty();
574     LOG_IF(FATAL, !FLAGS_old_partitions.empty())
575         << "Please use --new_partitions if you are using --old_partitions.";
576   }
577   for (size_t i = 0; i < partition_names.size(); i++) {
578     LOG_IF(FATAL, partition_names[i].empty())
579         << "Partition name can't be empty, see --partition_names.";
580     payload_config.target.partitions.emplace_back(partition_names[i]);
581     payload_config.target.partitions.back().path = new_partitions[i];
582     payload_config.target.partitions.back().disable_fec_computation =
583         FLAGS_disable_fec_computation;
584     if (i < new_mapfiles.size())
585       payload_config.target.partitions.back().mapfile_path = new_mapfiles[i];
586   }
587 
588   if (payload_config.is_delta) {
589     if (!FLAGS_old_partitions.empty()) {
590       old_partitions = base::SplitString(FLAGS_old_partitions,
591                                          ":",
592                                          base::TRIM_WHITESPACE,
593                                          base::SPLIT_WANT_ALL);
594       CHECK(old_partitions.size() == new_partitions.size());
595     } else {
596       old_partitions = {FLAGS_old_image, FLAGS_old_kernel};
597       LOG(WARNING) << "--old_partitions is empty, using deprecated --old_image "
598                    << "and --old_kernel flags.";
599     }
600     for (size_t i = 0; i < partition_names.size(); i++) {
601       payload_config.source.partitions.emplace_back(partition_names[i]);
602       payload_config.source.partitions.back().path = old_partitions[i];
603       if (i < old_mapfiles.size())
604         payload_config.source.partitions.back().mapfile_path = old_mapfiles[i];
605     }
606   }
607 
608   if (!FLAGS_in_file.empty()) {
609     return ApplyPayload(FLAGS_in_file, payload_config) ? 0 : 1;
610   }
611 
612   if (!FLAGS_new_postinstall_config_file.empty()) {
613     brillo::KeyValueStore store;
614     CHECK(store.Load(base::FilePath(FLAGS_new_postinstall_config_file)));
615     CHECK(payload_config.target.LoadPostInstallConfig(store));
616   }
617 
618   // Use the default soft_chunk_size defined in the config.
619   payload_config.hard_chunk_size = FLAGS_chunk_size;
620   payload_config.block_size = kBlockSize;
621 
622   // The partition size is never passed to the delta_generator, so we
623   // need to detect those from the provided files.
624   if (payload_config.is_delta) {
625     CHECK(payload_config.source.LoadImageSize());
626   }
627   CHECK(payload_config.target.LoadImageSize());
628 
629   if (!FLAGS_dynamic_partition_info_file.empty()) {
630     brillo::KeyValueStore store;
631     CHECK(store.Load(base::FilePath(FLAGS_dynamic_partition_info_file)));
632     CHECK(payload_config.target.LoadDynamicPartitionMetadata(store));
633     CHECK(payload_config.target.ValidateDynamicPartitionMetadata());
634   }
635 
636   if (FLAGS_is_partial_update) {
637     payload_config.is_partial_update = true;
638   }
639 
640   CHECK(!FLAGS_out_file.empty());
641 
642   // Ignore failures. These are optional arguments.
643   ParseImageInfo(FLAGS_new_channel,
644                  FLAGS_new_board,
645                  FLAGS_new_version,
646                  FLAGS_new_key,
647                  FLAGS_new_build_channel,
648                  FLAGS_new_build_version,
649                  &payload_config.target.image_info);
650 
651   // Ignore failures. These are optional arguments.
652   ParseImageInfo(FLAGS_old_channel,
653                  FLAGS_old_board,
654                  FLAGS_old_version,
655                  FLAGS_old_key,
656                  FLAGS_old_build_channel,
657                  FLAGS_old_build_version,
658                  &payload_config.source.image_info);
659 
660   payload_config.rootfs_partition_size = FLAGS_rootfs_partition_size;
661 
662   if (payload_config.is_delta) {
663     // Avoid opening the filesystem interface for full payloads.
664     for (PartitionConfig& part : payload_config.target.partitions)
665       CHECK(part.OpenFilesystem());
666     for (PartitionConfig& part : payload_config.source.partitions)
667       CHECK(part.OpenFilesystem());
668   }
669 
670   payload_config.version.major = FLAGS_major_version;
671   LOG(INFO) << "Using provided major_version=" << FLAGS_major_version;
672 
673   if (FLAGS_minor_version == -1) {
674     // Autodetect minor_version by looking at the update_engine.conf in the old
675     // image.
676     if (payload_config.is_delta) {
677       brillo::KeyValueStore store;
678       uint32_t minor_version;
679       bool minor_version_found = false;
680       for (const PartitionConfig& part : payload_config.source.partitions) {
681         if (part.fs_interface && part.fs_interface->LoadSettings(&store) &&
682             utils::GetMinorVersion(store, &minor_version)) {
683           payload_config.version.minor = minor_version;
684           minor_version_found = true;
685           LOG(INFO) << "Auto-detected minor_version="
686                     << payload_config.version.minor;
687           break;
688         }
689       }
690       if (!minor_version_found) {
691         LOG(FATAL) << "Failed to detect the minor version.";
692         return 1;
693       }
694     } else {
695       payload_config.version.minor = kFullPayloadMinorVersion;
696       LOG(INFO) << "Using non-delta minor_version="
697                 << payload_config.version.minor;
698     }
699   } else {
700     payload_config.version.minor = FLAGS_minor_version;
701     LOG(INFO) << "Using provided minor_version=" << FLAGS_minor_version;
702   }
703 
704   if (payload_config.version.minor != kFullPayloadMinorVersion &&
705       (payload_config.version.minor < kMinSupportedMinorPayloadVersion ||
706        payload_config.version.minor > kMaxSupportedMinorPayloadVersion)) {
707     LOG(FATAL) << "Unsupported minor version " << payload_config.version.minor;
708     return 1;
709   }
710 
711   payload_config.max_timestamp = FLAGS_max_timestamp;
712 
713   if (payload_config.is_delta &&
714       payload_config.version.minor >= kVerityMinorPayloadVersion)
715     CHECK(payload_config.target.LoadVerityConfig());
716 
717   LOG(INFO) << "Generating " << (payload_config.is_delta ? "delta" : "full")
718             << " update";
719 
720   // From this point, all the options have been parsed.
721   if (!payload_config.Validate()) {
722     LOG(ERROR) << "Invalid options passed. See errors above.";
723     return 1;
724   }
725 
726   uint64_t metadata_size;
727   if (!GenerateUpdatePayloadFile(
728           payload_config, FLAGS_out_file, FLAGS_private_key, &metadata_size)) {
729     return 1;
730   }
731   if (!FLAGS_out_metadata_size_file.empty()) {
732     string metadata_size_string = std::to_string(metadata_size);
733     CHECK(utils::WriteFile(FLAGS_out_metadata_size_file.c_str(),
734                            metadata_size_string.data(),
735                            metadata_size_string.size()));
736   }
737   return 0;
738 }
739 
740 }  // namespace
741 
742 }  // namespace chromeos_update_engine
743 
main(int argc,char ** argv)744 int main(int argc, char** argv) {
745   return chromeos_update_engine::Main(argc, argv);
746 }
747