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