• 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_string(
429       apex_info_file, "", "Path to META/apex_info.pb found in target build");
430 
431   brillo::FlagHelper::Init(
432       argc,
433       argv,
434       "Generates a payload to provide to ChromeOS' update_engine.\n\n"
435       "This tool can create full payloads and also delta payloads if the src\n"
436       "image is provided. It also provides debugging options to apply, sign\n"
437       "and verify payloads.");
438   Terminator::Init();
439 
440   logging::LoggingSettings log_settings;
441 #if BASE_VER < 780000
442   log_settings.log_file = "delta_generator.log";
443 #else
444   log_settings.log_file_path = "delta_generator.log";
445 #endif
446   log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
447   log_settings.lock_log = logging::LOCK_LOG_FILE;
448   log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
449 
450   logging::InitLogging(log_settings);
451 
452   // Initialize the Xz compressor.
453   XzCompressInit();
454 
455   if (!FLAGS_out_maximum_signature_size_file.empty()) {
456     LOG_IF(FATAL, FLAGS_private_key.empty())
457         << "Private key is not provided when calculating the maximum signature "
458            "size.";
459 
460     size_t maximum_signature_size;
461     if (!PayloadSigner::GetMaximumSignatureSize(FLAGS_private_key,
462                                                 &maximum_signature_size)) {
463       LOG(ERROR) << "Failed to get the maximum signature size of private key: "
464                  << FLAGS_private_key;
465       return 1;
466     }
467     // Write the size string to output file.
468     string signature_size_string = std::to_string(maximum_signature_size);
469     if (!utils::WriteFile(FLAGS_out_maximum_signature_size_file.c_str(),
470                           signature_size_string.c_str(),
471                           signature_size_string.size())) {
472       PLOG(ERROR) << "Failed to write the maximum signature size to "
473                   << FLAGS_out_maximum_signature_size_file << ".";
474       return 1;
475     }
476     return 0;
477   }
478 
479   vector<size_t> signature_sizes;
480   if (!FLAGS_signature_size.empty()) {
481     ParseSignatureSizes(FLAGS_signature_size, &signature_sizes);
482   }
483 
484   if (!FLAGS_out_hash_file.empty() || !FLAGS_out_metadata_hash_file.empty()) {
485     CHECK(FLAGS_out_metadata_size_file.empty());
486     CalculateHashForSigning(signature_sizes,
487                             FLAGS_out_hash_file,
488                             FLAGS_out_metadata_hash_file,
489                             FLAGS_in_file);
490     return 0;
491   }
492   if (!FLAGS_payload_signature_file.empty()) {
493     SignPayload(FLAGS_in_file,
494                 FLAGS_out_file,
495                 signature_sizes,
496                 FLAGS_payload_signature_file,
497                 FLAGS_metadata_signature_file,
498                 FLAGS_out_metadata_size_file);
499     return 0;
500   }
501   if (!FLAGS_public_key.empty()) {
502     LOG_IF(WARNING, FLAGS_public_key_version != -1)
503         << "--public_key_version is deprecated and ignored.";
504     return VerifySignedPayload(FLAGS_in_file, FLAGS_public_key);
505   }
506   if (!FLAGS_properties_file.empty()) {
507     return ExtractProperties(
508                FLAGS_in_file, FLAGS_properties_file, FLAGS_properties_format)
509                ? 0
510                : 1;
511   }
512 
513   // A payload generation was requested. Convert the flags to a
514   // PayloadGenerationConfig.
515   PayloadGenerationConfig payload_config;
516   vector<string> partition_names, old_partitions, new_partitions;
517   vector<string> old_mapfiles, new_mapfiles;
518 
519   if (!FLAGS_old_mapfiles.empty()) {
520     old_mapfiles = base::SplitString(
521         FLAGS_old_mapfiles, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
522   }
523   if (!FLAGS_new_mapfiles.empty()) {
524     new_mapfiles = base::SplitString(
525         FLAGS_new_mapfiles, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
526   }
527 
528   partition_names = base::SplitString(
529       FLAGS_partition_names, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
530   CHECK(!partition_names.empty());
531   if (FLAGS_major_version < kMinSupportedMajorPayloadVersion ||
532       FLAGS_major_version > kMaxSupportedMajorPayloadVersion) {
533     LOG(FATAL) << "Unsupported major version " << FLAGS_major_version;
534     return 1;
535   }
536 
537   if (!FLAGS_apex_info_file.empty()) {
538     // apex_info_file should point to a regular file(or symlink to a regular
539     // file)
540     CHECK(utils::FileExists(FLAGS_apex_info_file.c_str()));
541     CHECK(utils::IsRegFile(FLAGS_apex_info_file.c_str()) ||
542           utils::IsSymlink(FLAGS_apex_info_file.c_str()));
543     payload_config.apex_info_file = FLAGS_apex_info_file;
544   }
545 
546   if (!FLAGS_new_partitions.empty()) {
547     LOG_IF(FATAL, !FLAGS_new_image.empty() || !FLAGS_new_kernel.empty())
548         << "--new_image and --new_kernel are deprecated, please use "
549         << "--new_partitions for all partitions.";
550     new_partitions = base::SplitString(
551         FLAGS_new_partitions, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
552     CHECK(partition_names.size() == new_partitions.size());
553 
554     payload_config.is_delta = !FLAGS_old_partitions.empty();
555     LOG_IF(FATAL, !FLAGS_old_image.empty() || !FLAGS_old_kernel.empty())
556         << "--old_image and --old_kernel are deprecated, please use "
557         << "--old_partitions if you are using --new_partitions.";
558   } else {
559     new_partitions = {FLAGS_new_image, FLAGS_new_kernel};
560     LOG(WARNING) << "--new_partitions is empty, using deprecated --new_image "
561                  << "and --new_kernel flags.";
562 
563     payload_config.is_delta =
564         !FLAGS_old_image.empty() || !FLAGS_old_kernel.empty();
565     LOG_IF(FATAL, !FLAGS_old_partitions.empty())
566         << "Please use --new_partitions if you are using --old_partitions.";
567   }
568   for (size_t i = 0; i < partition_names.size(); i++) {
569     LOG_IF(FATAL, partition_names[i].empty())
570         << "Partition name can't be empty, see --partition_names.";
571     payload_config.target.partitions.emplace_back(partition_names[i]);
572     payload_config.target.partitions.back().path = new_partitions[i];
573     payload_config.target.partitions.back().disable_fec_computation =
574         FLAGS_disable_fec_computation;
575     if (i < new_mapfiles.size())
576       payload_config.target.partitions.back().mapfile_path = new_mapfiles[i];
577   }
578 
579   if (payload_config.is_delta) {
580     if (!FLAGS_old_partitions.empty()) {
581       old_partitions = base::SplitString(FLAGS_old_partitions,
582                                          ":",
583                                          base::TRIM_WHITESPACE,
584                                          base::SPLIT_WANT_ALL);
585       CHECK(old_partitions.size() == new_partitions.size());
586     } else {
587       old_partitions = {FLAGS_old_image, FLAGS_old_kernel};
588       LOG(WARNING) << "--old_partitions is empty, using deprecated --old_image "
589                    << "and --old_kernel flags.";
590     }
591     for (size_t i = 0; i < partition_names.size(); i++) {
592       payload_config.source.partitions.emplace_back(partition_names[i]);
593       payload_config.source.partitions.back().path = old_partitions[i];
594       if (i < old_mapfiles.size())
595         payload_config.source.partitions.back().mapfile_path = old_mapfiles[i];
596     }
597   }
598 
599   if (FLAGS_is_partial_update) {
600     payload_config.is_partial_update = true;
601   }
602 
603   if (!FLAGS_in_file.empty()) {
604     return ApplyPayload(FLAGS_in_file, payload_config) ? 0 : 1;
605   }
606 
607   if (!FLAGS_new_postinstall_config_file.empty()) {
608     brillo::KeyValueStore store;
609     CHECK(store.Load(base::FilePath(FLAGS_new_postinstall_config_file)));
610     CHECK(payload_config.target.LoadPostInstallConfig(store));
611   }
612 
613   // Use the default soft_chunk_size defined in the config.
614   payload_config.hard_chunk_size = FLAGS_chunk_size;
615   payload_config.block_size = kBlockSize;
616 
617   // The partition size is never passed to the delta_generator, so we
618   // need to detect those from the provided files.
619   if (payload_config.is_delta) {
620     CHECK(payload_config.source.LoadImageSize());
621   }
622   CHECK(payload_config.target.LoadImageSize());
623 
624   if (!FLAGS_dynamic_partition_info_file.empty()) {
625     brillo::KeyValueStore store;
626     CHECK(store.Load(base::FilePath(FLAGS_dynamic_partition_info_file)));
627     CHECK(payload_config.target.LoadDynamicPartitionMetadata(store));
628     CHECK(payload_config.target.ValidateDynamicPartitionMetadata());
629     if (FLAGS_disable_vabc) {
630       LOG(INFO) << "Disabling VABC";
631       payload_config.target.dynamic_partition_metadata->set_vabc_enabled(false);
632       payload_config.target.dynamic_partition_metadata
633           ->set_vabc_compression_param("");
634     }
635   }
636 
637   CHECK(!FLAGS_out_file.empty());
638 
639   payload_config.rootfs_partition_size = FLAGS_rootfs_partition_size;
640 
641   if (payload_config.is_delta) {
642     // Avoid opening the filesystem interface for full payloads.
643     for (PartitionConfig& part : payload_config.target.partitions)
644       CHECK(part.OpenFilesystem());
645     for (PartitionConfig& part : payload_config.source.partitions)
646       CHECK(part.OpenFilesystem());
647   }
648 
649   payload_config.version.major = FLAGS_major_version;
650   LOG(INFO) << "Using provided major_version=" << FLAGS_major_version;
651 
652   if (FLAGS_minor_version == -1) {
653     // Autodetect minor_version by looking at the update_engine.conf in the old
654     // image.
655     if (payload_config.is_delta) {
656       brillo::KeyValueStore store;
657       uint32_t minor_version;
658       bool minor_version_found = false;
659       for (const PartitionConfig& part : payload_config.source.partitions) {
660         if (part.fs_interface && part.fs_interface->LoadSettings(&store) &&
661             utils::GetMinorVersion(store, &minor_version)) {
662           payload_config.version.minor = minor_version;
663           minor_version_found = true;
664           LOG(INFO) << "Auto-detected minor_version="
665                     << payload_config.version.minor;
666           break;
667         }
668       }
669       if (!minor_version_found) {
670         LOG(FATAL) << "Failed to detect the minor version.";
671         return 1;
672       }
673     } else {
674       payload_config.version.minor = kFullPayloadMinorVersion;
675       LOG(INFO) << "Using non-delta minor_version="
676                 << payload_config.version.minor;
677     }
678   } else {
679     payload_config.version.minor = FLAGS_minor_version;
680     LOG(INFO) << "Using provided minor_version=" << FLAGS_minor_version;
681   }
682 
683   if (payload_config.version.minor != kFullPayloadMinorVersion &&
684       (payload_config.version.minor < kMinSupportedMinorPayloadVersion ||
685        payload_config.version.minor > kMaxSupportedMinorPayloadVersion)) {
686     LOG(FATAL) << "Unsupported minor version " << payload_config.version.minor;
687     return 1;
688   }
689 
690   payload_config.max_timestamp = FLAGS_max_timestamp;
691   if (!FLAGS_partition_timestamps.empty()) {
692     CHECK(ParsePerPartitionTimestamps(FLAGS_partition_timestamps,
693                                       &payload_config));
694   }
695 
696   if (payload_config.is_delta &&
697       payload_config.version.minor >= kVerityMinorPayloadVersion &&
698       !FLAGS_disable_verity_computation)
699     CHECK(payload_config.target.LoadVerityConfig());
700 
701   LOG(INFO) << "Generating " << (payload_config.is_delta ? "delta" : "full")
702             << " update";
703 
704   // From this point, all the options have been parsed.
705   if (!payload_config.Validate()) {
706     LOG(ERROR) << "Invalid options passed. See errors above.";
707     return 1;
708   }
709 
710   uint64_t metadata_size;
711   if (!GenerateUpdatePayloadFile(
712           payload_config, FLAGS_out_file, FLAGS_private_key, &metadata_size)) {
713     return 1;
714   }
715   if (!FLAGS_out_metadata_size_file.empty()) {
716     string metadata_size_string = std::to_string(metadata_size);
717     CHECK(utils::WriteFile(FLAGS_out_metadata_size_file.c_str(),
718                            metadata_size_string.data(),
719                            metadata_size_string.size()));
720   }
721   return 0;
722 }
723 
724 }  // namespace
725 
726 }  // namespace chromeos_update_engine
727 
main(int argc,char ** argv)728 int main(int argc, char** argv) {
729   return chromeos_update_engine::Main(argc, argv);
730 }
731