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