blob: 443b1949fb659d783ab92b918c715be7df694bb8 [file] [log] [blame]
bigbiff1f9e4842020-10-31 11:33:15 -04001/*
2 * Copyright (C) 2007 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 "twinstall/install.h"
18
19#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <inttypes.h>
23#include <limits.h>
24#include <string.h>
25#include <sys/stat.h>
26#include <sys/wait.h>
27#include <unistd.h>
28
29#include <algorithm>
30#include <atomic>
31#include <chrono>
32#include <condition_variable>
33#include <functional>
34#include <limits>
35#include <mutex>
36#include <thread>
37#include <vector>
38
39#include <android-base/file.h>
40#include <android-base/logging.h>
41#include <android-base/parsedouble.h>
42#include <android-base/parseint.h>
43#include <android-base/properties.h>
44#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
46#include <android-base/unique_fd.h>
47#include <vintf/VintfObjectRecovery.h>
48
49#include "twinstall/package.h"
50#include "twinstall/verifier.h"
51#include "twinstall/wipe_data.h"
52#include "otautil/error_code.h"
53#include "otautil/paths.h"
54#include "otautil/roots.h"
55#include "otautil/sysutil.h"
56#include "otautil/thermalutil.h"
57#include "private/setup_commands.h"
58
59using namespace std::chrono_literals;
60
61static constexpr int kRecoveryApiVersion = 3;
62// Assert the version defined in code and in Android.mk are consistent.
63static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
64
65// Default allocation of progress bar segments to operations
66// static constexpr int VERIFICATION_PROGRESS_TIME = 60;
67// static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
68
69static std::condition_variable finish_log_temperature;
70
71bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map<std::string, std::string>* metadata) {
72 CHECK(metadata != nullptr);
73
74 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
75 ZipString path(METADATA_PATH);
76 ZipEntry entry;
77 if (FindEntry(zip, path, &entry) != 0) {
78 LOG(ERROR) << "Failed to find " << METADATA_PATH;
79 return false;
80 }
81
82 uint32_t length = entry.uncompressed_length;
83 std::string metadata_string(length, '\0');
84 int32_t err =
85 ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&metadata_string[0]), length);
86 if (err != 0) {
87 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
88 return false;
89 }
90
91 for (const std::string& line : android::base::Split(metadata_string, "\n")) {
92 size_t eq = line.find('=');
93 if (eq != std::string::npos) {
94 metadata->emplace(android::base::Trim(line.substr(0, eq)),
95 android::base::Trim(line.substr(eq + 1)));
96 }
97 }
98
99 return true;
100}
101
102// Gets the value for the given key in |metadata|. Returns an emtpy string if the key isn't
103// present.
104static std::string get_value(const std::map<std::string, std::string>& metadata,
105 const std::string& key) {
106 const auto& it = metadata.find(key);
107 return (it == metadata.end()) ? "" : it->second;
108}
109
110static std::string OtaTypeToString(OtaType type) {
111 switch (type) {
112 case OtaType::AB:
113 return "AB";
114 case OtaType::BLOCK:
115 return "BLOCK";
116 case OtaType::BRICK:
117 return "BRICK";
118 }
119}
120
121// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
122static void ReadSourceTargetBuild(const std::map<std::string, std::string>& metadata,
123 std::vector<std::string>* log_buffer) {
124 // Examples of the pre-build and post-build strings in metadata:
125 // pre-build-incremental=2943039
126 // post-build-incremental=2951741
127 auto source_build = get_value(metadata, "pre-build-incremental");
128 if (!source_build.empty()) {
129 log_buffer->push_back("source_build: " + source_build);
130 }
131
132 auto target_build = get_value(metadata, "post-build-incremental");
133 if (!target_build.empty()) {
134 log_buffer->push_back("target_build: " + target_build);
135 }
136}
137
138// Checks the build version, fingerprint and timestamp in the metadata of the A/B package.
139// Downgrading is not allowed unless explicitly enabled in the package and only for
140// incremental packages.
141static int CheckAbSpecificMetadata(const std::map<std::string, std::string>& metadata) {
142 // Incremental updates should match the current build.
143 auto device_pre_build = android::base::GetProperty("ro.build.version.incremental", "");
144 auto pkg_pre_build = get_value(metadata, "pre-build-incremental");
145 if (!pkg_pre_build.empty() && pkg_pre_build != device_pre_build) {
146 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected "
147 << device_pre_build;
148 return INSTALL_ERROR;
149 }
150
151 auto device_fingerprint = android::base::GetProperty("ro.build.fingerprint", "");
152 auto pkg_pre_build_fingerprint = get_value(metadata, "pre-build");
153 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != device_fingerprint) {
154 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
155 << device_fingerprint;
156 return INSTALL_ERROR;
157 }
158
159 // Check for downgrade version.
160 // int64_t build_timestamp =
161 // android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
162 // int64_t pkg_post_timestamp = 0;
163 // We allow to full update to the same version we are running, in case there
164 // is a problem with the current copy of that version.
165 auto pkg_post_timestamp_string = get_value(metadata, "post-timestamp");
166 // if (pkg_post_timestamp_string.empty() ||
167 // !android::base::ParseInt(pkg_post_timestamp_string, &pkg_post_timestamp) ||
168 // pkg_post_timestamp < build_timestamp) {
169 // if (get_value(metadata, "ota-downgrade") != "yes") {
170 // LOG(ERROR) << "Update package is older than the current build, expected a build "
171 // "newer than timestamp "
172 // << build_timestamp << " but package has timestamp " << pkg_post_timestamp
173 // << " and downgrade not allowed.";
174 // return INSTALL_ERROR;
175 // }
176 // if (pkg_pre_build_fingerprint.empty()) {
177 // LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
178 // return INSTALL_ERROR;
179 // }
180 // }
181
182 return 0;
183}
184
185int CheckPackageMetadata(const std::map<std::string, std::string>& metadata, OtaType ota_type) {
186 auto package_ota_type = get_value(metadata, "ota-type");
187 auto expected_ota_type = OtaTypeToString(ota_type);
188 if (ota_type != OtaType::AB && ota_type != OtaType::BRICK) {
189 LOG(INFO) << "Skip package metadata check for ota type " << expected_ota_type;
190 return 0;
191 }
192
193 if (package_ota_type != expected_ota_type) {
194 LOG(ERROR) << "Unexpected ota package type, expects " << expected_ota_type << ", actual "
195 << package_ota_type;
196 return INSTALL_ERROR;
197 }
198
199 auto device = android::base::GetProperty("ro.product.device", "");
200 auto pkg_device = get_value(metadata, "pre-device");
201 if (pkg_device != device || pkg_device.empty()) {
202 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << device;
203 return INSTALL_ERROR;
204 }
205
206 // We allow the package to not have any serialno; and we also allow it to carry multiple serial
207 // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the
208 // verification if the device's serialno doesn't match any of these carried numbers.
209 auto pkg_serial_no = get_value(metadata, "serialno");
210 if (!pkg_serial_no.empty()) {
211 auto device_serial_no = android::base::GetProperty("ro.serialno", "");
212 bool serial_number_match = false;
213 for (const auto& number : android::base::Split(pkg_serial_no, "|")) {
214 if (device_serial_no == android::base::Trim(number)) {
215 serial_number_match = true;
216 }
217 }
218 if (!serial_number_match) {
219 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
220 return INSTALL_ERROR;
221 }
222 }
223
224 if (ota_type == OtaType::AB) {
225 return CheckAbSpecificMetadata(metadata);
226 }
227
228 return 0;
229}
230
231int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd,
232 std::vector<std::string>* cmd) {
233 CHECK(cmd != nullptr);
234
235 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
236 // in the zip file.
237 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
238 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
239 ZipEntry properties_entry;
240 if (FindEntry(zip, property_name, &properties_entry) != 0) {
241 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
242 return INSTALL_CORRUPT;
243 }
244 uint32_t properties_entry_length = properties_entry.uncompressed_length;
245 std::vector<uint8_t> payload_properties(properties_entry_length);
246 int32_t err =
247 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
248 if (err != 0) {
249 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
250 return INSTALL_CORRUPT;
251 }
252
253 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
254 ZipString payload_name(AB_OTA_PAYLOAD);
255 ZipEntry payload_entry;
256 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
257 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
258 return INSTALL_CORRUPT;
259 }
260 long payload_offset = payload_entry.offset;
261 *cmd = {
262 "/system/bin/update_engine_sideload",
263 "--payload=file://" + package,
264 android::base::StringPrintf("--offset=%ld", payload_offset),
265 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
266 android::base::StringPrintf("--status_fd=%d", status_fd),
267 };
268 return 0;
269}
270
271int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count,
272 int status_fd, std::vector<std::string>* cmd) {
273 CHECK(cmd != nullptr);
274
275 // In non-A/B updates we extract the update binary from the package.
276 ZipString binary_name(UPDATE_BINARY_NAME);
277 ZipEntry binary_entry;
278 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
279 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
280 return INSTALL_CORRUPT;
281 }
282
283 LOG(ERROR) << "SetupNonAbUpdateCommands::here1";
284 const std::string binary_path = Paths::Get().temporary_update_binary();
285 unlink(binary_path.c_str());
286 LOG(ERROR) << "SetupNonAbUpdateCommands::here2";
287 android::base::unique_fd fd(
288 open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755));
289 if (fd == -1) {
290 PLOG(ERROR) << "Failed to create " << binary_path;
291 return INSTALL_ERROR;
292 }
293 LOG(ERROR) << "SetupNonAbUpdateCommands::here3";
294
295 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
296 if (error != 0) {
297 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
298 return INSTALL_ERROR;
299 }
bigbiff1f9e4842020-10-31 11:33:15 -0400300
301 // When executing the update binary contained in the package, the arguments passed are:
302 // - the version number for this interface
303 // - an FD to which the program can write in order to update the progress bar.
304 // - the name of the package zip file.
305 // - an optional argument "retry" if this update is a retry of a failed update attempt.
306 *cmd = {
307 binary_path,
308 std::to_string(kRecoveryApiVersion),
309 std::to_string(status_fd),
310 package,
311 };
312 if (retry_count > 0) {
313 cmd->push_back("retry");
314 }
315 return 0;
316}
317
318static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
319 CHECK(max_temperature != nullptr);
320 std::mutex mtx;
321 std::unique_lock<std::mutex> lck(mtx);
322 while (!logger_finished.load() &&
323 finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
324 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
325 }
326}
327
328// If the package contains an update binary, extract it and run it.
329static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
330 std::vector<std::string>* log_buffer, int retry_count,
331 int* max_temperature) {
332 std::map<std::string, std::string> metadata;
333
334 if (!ReadMetadataFromPackage(zip, &metadata)) {
335 LOG(ERROR) << "Failed to parse metadata in the zip file";
336 // return INSTALL_CORRUPT;
337 }
338
339 bool is_ab = android::base::GetBoolProperty("ro.build.ab_update", false);
340 // Verifies against the metadata in the package first.
341 // if (int check_status = is_ab ? CheckPackageMetadata(metadata, OtaType::AB) : 0;
342 // check_status != 0) {
343 // log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
344 // return check_status;
345 // }
346
347 ReadSourceTargetBuild(metadata, log_buffer);
348 LOG(ERROR) << "try_update_binary::here1";
349 // The updater in child process writes to the pipe to communicate with recovery.
350 android::base::unique_fd pipe_read, pipe_write;
351 // Explicitly disable O_CLOEXEC using 0 as the flags (last) parameter to Pipe
352 // so that the child updater process will recieve a non-closed fd.
353 if (!android::base::Pipe(&pipe_read, &pipe_write, 0)) {
354 PLOG(ERROR) << "Failed to create pipe for updater-recovery communication";
355 return INSTALL_CORRUPT;
356 }
357
358 // The updater-recovery communication protocol.
359 //
360 // progress <frac> <secs>
361 // fill up the next <frac> part of of the progress bar over <secs> seconds. If <secs> is
362 // zero, use `set_progress` commands to manually control the progress of this segment of the
363 // bar.
364 //
365 // set_progress <frac>
366 // <frac> should be between 0.0 and 1.0; sets the progress bar within the segment defined by
367 // the most recent progress command.
368 //
369 // ui_print <string>
370 // display <string> on the screen.
371 //
372 // wipe_cache
373 // a wipe of cache will be performed following a successful installation.
374 //
375 // clear_display
376 // turn off the text display.
377 //
378 // enable_reboot
379 // packages can explicitly request that they want the user to be able to reboot during
380 // installation (useful for debugging packages that don't exit).
381 //
382 // retry_update
383 // updater encounters some issue during the update. It requests a reboot to retry the same
384 // package automatically.
385 //
386 // log <string>
387 // updater requests logging the string (e.g. cause of the failure).
388 //
389
390 std::vector<std::string> args;
391
392 is_ab = false;
393 ZipString binary_name(UPDATE_BINARY_NAME);
394 ZipEntry binary_entry;
395 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
396 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
397 is_ab = true;
398 }
399
400 if (int update_status =
401 is_ab ? SetUpAbUpdateCommands(package, zip, pipe_write.get(), &args)
402 : SetUpNonAbUpdateCommands(package, zip, retry_count, pipe_write.get(), &args);
403 update_status != 0) {
404 log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
405 // return update_status;
406 }
407
408 pid_t pid = fork();
409 if (pid == -1) {
410 PLOG(ERROR) << "Failed to fork update binary";
411 log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
412 return INSTALL_ERROR;
413 }
414
415 if (pid == 0) {
416 umask(022);
417 pipe_read.reset();
418
419 // Convert the std::string vector to a NULL-terminated char* vector suitable for execv.
420 auto chr_args = StringVectorToNullTerminatedArray(args);
421 execv(chr_args[0], chr_args.data());
422 // We shouldn't use LOG/PLOG in the forked process, since they may cause the child process to
423 // hang. This deadlock results from an improperly copied mutex in the ui functions.
424 // (Bug: 34769056)
425 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
426 _exit(EXIT_FAILURE);
427 }
428 pipe_write.reset();
429
430 std::atomic<bool> logger_finished(false);
431 std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
432
433 *wipe_cache = false;
434 bool retry_update = false;
435
436 char buffer[1024];
437 FILE* from_child = android::base::Fdopen(std::move(pipe_read), "r");
438 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
439 std::string line(buffer);
440 size_t space = line.find_first_of(" \n");
441 std::string command(line.substr(0, space));
442 if (command.empty()) continue;
443
444 // Get rid of the leading and trailing space and/or newline.
445 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
446
447 if (command == "progress") {
448 std::vector<std::string> tokens = android::base::Split(args, " ");
449 double fraction;
450 int seconds;
451 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
452 android::base::ParseInt(tokens[1], &seconds)) {
453 // ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
454 } else {
455 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
456 }
457 } else if (command == "set_progress") {
458 std::vector<std::string> tokens = android::base::Split(args, " ");
459 double fraction;
460 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
461 // ui->SetProgress(fraction);
462 } else {
463 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
464 }
465 } else if (command == "ui_print") {
466 // ui->PrintOnScreenOnly("%s\n", args.c_str());
467 fflush(stdout);
468 } else if (command == "wipe_cache") {
469 *wipe_cache = true;
470 } else if (command == "clear_display") {
471 // ui->SetBackground(RecoveryUI::NONE);
472 } else if (command == "enable_reboot") {
473 // packages can explicitly request that they want the user
474 // to be able to reboot during installation (useful for
475 // debugging packages that don't exit).
476 // ui->SetEnableReboot(true);
477 } else if (command == "retry_update") {
478 retry_update = true;
479 } else if (command == "log") {
480 if (!args.empty()) {
481 // Save the logging request from updater and write to last_install later.
482 log_buffer->push_back(args);
483 } else {
484 LOG(ERROR) << "invalid \"log\" parameters: " << line;
485 }
486 } else {
487 LOG(ERROR) << "unknown command [" << command << "]";
488 }
489 }
490 fclose(from_child);
491
492 int status;
493 waitpid(pid, &status, 0);
494
495 logger_finished.store(true);
496 finish_log_temperature.notify_one();
497 temperature_logger.join();
498
499 if (retry_update) {
500 return INSTALL_RETRY;
501 }
502 if (WIFEXITED(status)) {
503 if (WEXITSTATUS(status) != EXIT_SUCCESS) {
504 LOG(ERROR) << "Error in " << package << " (status " << WEXITSTATUS(status) << ")";
505 return INSTALL_ERROR;
506 }
507 } else if (WIFSIGNALED(status)) {
508 LOG(ERROR) << "Error in " << package << " (killed by signal " << WTERMSIG(status) << ")";
509 return INSTALL_ERROR;
510 } else {
511 LOG(FATAL) << "Invalid status code " << status;
512 }
513
514 return INSTALL_SUCCESS;
515}
516
517// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
518// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
519// package.
520// bool verify_package_compatibility(ZipArchiveHandle package_zip __unused) {
521// LOG(INFO) << "Verifying package compatibility...";
522
523// static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
524// ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
525// ZipEntry compatibility_entry;
526// if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
527// LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
528// return true;
529// }
530
531// std::string zip_content(compatibility_entry.uncompressed_length, '\0');
532// int32_t ret;
533// if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
534// reinterpret_cast<uint8_t*>(&zip_content[0]),
535// compatibility_entry.uncompressed_length)) != 0) {
536// LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
537// return false;
538// }
539
540// ZipArchiveHandle zip_handle;
541// ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
542// zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
543// if (ret != 0) {
544// LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
545// return false;
546// }
547
548// // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
549// void* cookie;
550// ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
551// if (ret != 0) {
552// LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
553// CloseArchive(zip_handle);
554// return false;
555// }
556// std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
557
558// std::vector<std::string> compatibility_info;
559// ZipEntry info_entry;
560// ZipString info_name;
561// while (Next(cookie, &info_entry, &info_name) == 0) {
562// std::string content(info_entry.uncompressed_length, '\0');
563// int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
564// info_entry.uncompressed_length);
565// if (ret != 0) {
566// LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
567// CloseArchive(zip_handle);
568// return false;
569// }
570// compatibility_info.emplace_back(std::move(content));
571// }
572// CloseArchive(zip_handle);
573
574// // VintfObjectRecovery::CheckCompatibility returns zero on success.
575// std::string err;
576// int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
577// if (result == 0) {
578// return true;
579// }
580
581// LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
582// return false;
583// }
584
585static int really_install_package(const std::string& path, bool* wipe_cache __unused, bool needs_mount __unused,
586 std::vector<std::string>* log_buffer __unused, int retry_count __unused,
587 int* max_temperature __unused) {
588 // ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
589 // ui->Print("Finding update package...\n");
590 // Give verification half the progress bar...
591 // ui->SetProgressType(RecoveryUI::DETERMINATE);
592 // ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
593 LOG(INFO) << "Update location: " << path;
594
595 // Map the update package into memory.
596 // ui->Print("Opening update package...\n");
597 if (needs_mount) {
598 if (path[0] == '@') {
599 ensure_path_mounted(path.substr(1));
600 } else {
601 ensure_path_mounted(path);
602 }
603 }
604
605 auto package = Package::CreateMemoryPackage(
606 path);
607 if (!package) {
608 log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
609 return INSTALL_CORRUPT;
610 }
611
612 // Verify package.
613 if (!verify_package(package.get())) {
614 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
615 return INSTALL_CORRUPT;
616 }
617
618 // Try to open the package.
619 ZipArchiveHandle zip = package->GetZipArchiveHandle();
620 if (!zip) {
621 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
622 return INSTALL_CORRUPT;
623 }
624 LOG(ERROR) << "really_install_package::here1";
625
626 // Additionally verify the compatibility of the package if it's a fresh install.
627 if (retry_count == 0 && !verify_package_compatibility(zip)) {
628 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
629 return INSTALL_CORRUPT;
630 }
631
632 // Verify and install the contents of the package.
633 // ui->Print("Installing update...\n");
634 // if (retry_count > 0) {
635 // ui->Print("Retry attempt: %d\n", retry_count);
636 // }
637 // ui->SetEnableReboot(false);
638 LOG(ERROR) << "really_install_package::here2";
639 int result =
640 try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
641 // ui->SetEnableReboot(true);
642 // ui->Print("\n");
643 return result;
644}
645
646int install_package(const std::string& path, bool should_wipe_cache, bool needs_mount,
647 int retry_count) {
648 CHECK(!path.empty());
649
650 auto start = std::chrono::system_clock::now();
651
652 int start_temperature = GetMaxValueFromThermalZone();
653 int max_temperature = start_temperature;
654
655 int result;
656 std::vector<std::string> log_buffer;
657 // if (setup_install_mounts() != 0) {
658 // LOG(ERROR) << "failed to set up expected mounts for install; aborting";
659 // result = INSTALL_ERROR;
660 // } else {
661 bool updater_wipe_cache = false;
662 result = really_install_package(path, &updater_wipe_cache, needs_mount, &log_buffer,
663 retry_count, &max_temperature);
664 should_wipe_cache = should_wipe_cache || updater_wipe_cache;
665 // }
666
667 // Measure the time spent to apply OTA update in seconds.
668 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
669 int time_total = static_cast<int>(duration.count());
670
671 bool has_cache = volume_for_mount_point("/cache") != nullptr;
672 // Skip logging the uncrypt_status on devices without /cache.
673 if (has_cache) {
674 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
675 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
676 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
677 } else {
678 std::string uncrypt_status;
679 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
680 PLOG(WARNING) << "failed to read uncrypt status";
681 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
682 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
683 } else {
684 log_buffer.push_back(android::base::Trim(uncrypt_status));
685 }
686 }
687 }
688
689 // The first two lines need to be the package name and install result.
690 std::vector<std::string> log_header = {
691 path,
692 result == INSTALL_SUCCESS ? "1" : "0",
693 "time_total: " + std::to_string(time_total),
694 "retry: " + std::to_string(retry_count),
695 };
696
697 int end_temperature = GetMaxValueFromThermalZone();
698 max_temperature = std::max(end_temperature, max_temperature);
699 if (start_temperature > 0) {
700 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
701 }
702 if (end_temperature > 0) {
703 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
704 }
705 if (max_temperature > 0) {
706 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
707 }
708
709 std::string log_content =
710 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
711 const std::string& install_file = Paths::Get().temporary_install_file();
712 if (!android::base::WriteStringToFile(log_content, install_file)) {
713 PLOG(ERROR) << "failed to write " << install_file;
714 }
715
716 // Write a copy into last_log.
717 LOG(INFO) << log_content;
718
719 if (result == INSTALL_SUCCESS && should_wipe_cache) {
720 if (!WipeCache(nullptr)) {
721 result = INSTALL_ERROR;
722 }
723 }
724
725 return result;
726}
727
728bool verify_package(Package* package) {
729 static constexpr const char* CERTIFICATE_ZIP_FILE = "/system/etc/security/otacerts.zip";
730 std::vector<Certificate> loaded_keys = LoadKeysFromZipfile(CERTIFICATE_ZIP_FILE);
731 if (loaded_keys.empty()) {
732 LOG(ERROR) << "Failed to load keys";
733 return false;
734 }
735 LOG(INFO) << loaded_keys.size() << " key(s) loaded from " << CERTIFICATE_ZIP_FILE;
736
737 // Verify package.
738 // ui->Print("Verifying update package...\n");
739 // auto t0 = std::chrono::system_clock::now();
740 int err = verify_file(package, loaded_keys);
741 // if(err != VERIFY_SUCCESS) {
742
743 // }
744 // std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
745 // ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
746 if (err != VERIFY_SUCCESS) {
747 LOG(ERROR) << "Signature verification failed";
748 LOG(ERROR) << "error: " << kZipVerificationFailure;
749 // return false;
750 }
751 return true;
752}