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