blob: 5d7bda73c9b711a4984add90b0af688e4ba3b57c [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
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
Tao Bao20c581e2016-12-28 20:55:51 -080017#include "install.h"
18
Doug Zongkerb2ee9202009-06-04 10:24:53 -070019#include <ctype.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080020#include <errno.h>
21#include <fcntl.h>
Alex Deymo4e29ce02016-08-12 13:43:04 -070022#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080023#include <limits.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080024#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080025#include <sys/stat.h>
Doug Zongkerb2ee9202009-06-04 10:24:53 -070026#include <sys/wait.h>
27#include <unistd.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080028
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070029#include <algorithm>
Tianjie Xu37957102017-06-07 17:59:55 -070030#include <atomic>
Elliott Hughes8febafa2016-04-13 16:39:56 -070031#include <chrono>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070032#include <condition_variable>
Tao Bao5e535012017-03-16 17:37:38 -070033#include <functional>
Alex Deymo4344d632016-08-03 21:03:53 -070034#include <limits>
35#include <map>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070036#include <mutex>
Tianjie Xudd874b12016-05-13 12:13:15 -070037#include <string>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070038#include <thread>
Tao Bao71e3e092016-02-02 14:02:27 -080039#include <vector>
40
Tianjie Xue16e7992016-09-09 10:55:44 -070041#include <android-base/file.h>
42#include <android-base/logging.h>
Tao Bao20c581e2016-12-28 20:55:51 -080043#include <android-base/parsedouble.h>
Tianjie Xub0ddae52016-06-08 14:30:04 -070044#include <android-base/parseint.h>
Tao Baoefc35592017-01-08 22:45:47 -080045#include <android-base/properties.h>
Tianjie Xu16255832016-04-30 11:49:59 -070046#include <android-base/stringprintf.h>
47#include <android-base/strings.h>
Tao Bao919d2c92017-04-10 16:55:57 -070048#include <vintf/VintfObjectRecovery.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070049#include <ziparchive/zip_archive.h>
Tianjie Xu16255832016-04-30 11:49:59 -070050
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080051#include "common.h"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070052#include "otautil/SysUtil.h"
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070053#include "otautil/ThermalUtil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070054#include "otautil/error_code.h"
Tao Bao00d57572017-05-02 15:48:54 -070055#include "private/install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080056#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070057#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020058#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080059
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070060using namespace std::chrono_literals;
61
Doug Zongker74406302011-10-28 15:13:10 -070062// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080063static constexpr int VERIFICATION_PROGRESS_TIME = 60;
64static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070065
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070066static std::condition_variable finish_log_temperature;
67
Tianjie Xub0ddae52016-06-08 14:30:04 -070068// This function parses and returns the build.version.incremental
Daniel Micaya29d8d62017-06-23 08:33:24 -040069static std::string parse_build_number(const std::string& str) {
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070070 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070071 if (pos != std::string::npos) {
Daniel Micaya29d8d62017-06-23 08:33:24 -040072 return android::base::Trim(str.substr(pos+1));
Tianjie Xub0ddae52016-06-08 14:30:04 -070073 }
74
Tianjie Xuc21edd42016-08-05 18:00:04 -070075 LOG(ERROR) << "Failed to parse build number in " << str;
Daniel Micaya29d8d62017-06-23 08:33:24 -040076 return "";
Tianjie Xub0ddae52016-06-08 14:30:04 -070077}
78
Tao Bao8a7afcc2017-04-18 22:05:50 -070079bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
80 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070081
Tao Bao8a7afcc2017-04-18 22:05:50 -070082 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
83 ZipString path(METADATA_PATH);
84 ZipEntry entry;
85 if (FindEntry(zip, path, &entry) != 0) {
86 LOG(ERROR) << "Failed to find " << METADATA_PATH;
87 return false;
88 }
89
90 uint32_t length = entry.uncompressed_length;
91 metadata->resize(length, '\0');
92 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
93 if (err != 0) {
94 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
95 return false;
96 }
97 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -070098}
99
100// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tao Bao29ee69b2017-05-01 12:23:17 -0700101static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>* log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700102 std::string metadata;
103 if (!read_metadata_from_package(zip, &metadata)) {
104 return;
105 }
106 // Examples of the pre-build and post-build strings in metadata:
107 // pre-build-incremental=2943039
108 // post-build-incremental=2951741
109 std::vector<std::string> lines = android::base::Split(metadata, "\n");
110 for (const std::string& line : lines) {
111 std::string str = android::base::Trim(line);
112 if (android::base::StartsWith(str, "pre-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400113 std::string source_build = parse_build_number(str);
114 if (!source_build.empty()) {
115 log_buffer->push_back("source_build: " + source_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700116 }
117 } else if (android::base::StartsWith(str, "post-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400118 std::string target_build = parse_build_number(str);
119 if (!target_build.empty()) {
120 log_buffer->push_back("target_build: " + target_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700121 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700122 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700123 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700124}
125
Alex Deymo4344d632016-08-03 21:03:53 -0700126#ifdef AB_OTA_UPDATER
127
128// Parses the metadata of the OTA package in |zip| and checks whether we are
129// allowed to accept this A/B package. Downgrading is not allowed unless
130// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800131static int check_newer_ab_build(ZipArchiveHandle zip) {
132 std::string metadata_str;
133 if (!read_metadata_from_package(zip, &metadata_str)) {
134 return INSTALL_CORRUPT;
135 }
136 std::map<std::string, std::string> metadata;
137 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
138 size_t eq = line.find('=');
139 if (eq != std::string::npos) {
140 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700141 }
Tao Baoefc35592017-01-08 22:45:47 -0800142 }
Alex Deymo4344d632016-08-03 21:03:53 -0700143
Tao Baoefc35592017-01-08 22:45:47 -0800144 std::string value = android::base::GetProperty("ro.product.device", "");
145 const std::string& pkg_device = metadata["pre-device"];
146 if (pkg_device != value || pkg_device.empty()) {
147 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
148 return INSTALL_ERROR;
149 }
Alex Deymo4344d632016-08-03 21:03:53 -0700150
Tianjie Xu69b96492017-08-17 16:42:57 -0700151 // We allow the package to not have any serialno; and we also allow it to carry multiple serial
152 // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the
153 // verification if the device's serialno doesn't match any of these carried numbers.
Tao Baoefc35592017-01-08 22:45:47 -0800154 value = android::base::GetProperty("ro.serialno", "");
155 const std::string& pkg_serial_no = metadata["serialno"];
Tianjie Xu69b96492017-08-17 16:42:57 -0700156 if (!pkg_serial_no.empty()) {
157 bool match = false;
158 for (const std::string& number : android::base::Split(pkg_serial_no, "|")) {
159 if (value == android::base::Trim(number)) {
160 match = true;
161 break;
162 }
163 }
164 if (!match) {
165 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
166 return INSTALL_ERROR;
167 }
Tao Baoefc35592017-01-08 22:45:47 -0800168 }
Alex Deymo4344d632016-08-03 21:03:53 -0700169
Tao Baoefc35592017-01-08 22:45:47 -0800170 if (metadata["ota-type"] != "AB") {
171 LOG(ERROR) << "Package is not A/B";
172 return INSTALL_ERROR;
173 }
Alex Deymo4344d632016-08-03 21:03:53 -0700174
Tao Baoefc35592017-01-08 22:45:47 -0800175 // Incremental updates should match the current build.
176 value = android::base::GetProperty("ro.build.version.incremental", "");
177 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
178 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
179 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
180 return INSTALL_ERROR;
181 }
Alex Deymo4344d632016-08-03 21:03:53 -0700182
Tao Baoefc35592017-01-08 22:45:47 -0800183 value = android::base::GetProperty("ro.build.fingerprint", "");
184 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
185 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
186 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
187 << value;
188 return INSTALL_ERROR;
189 }
Alex Deymo4344d632016-08-03 21:03:53 -0700190
Tao Baoefc35592017-01-08 22:45:47 -0800191 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700192}
193
Tao Bao00d57572017-05-02 15:48:54 -0700194int update_binary_command(const std::string& package, ZipArchiveHandle zip,
195 const std::string& binary_path, int /* retry_count */, int status_fd,
196 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700197 CHECK(cmd != nullptr);
198 int ret = check_newer_ab_build(zip);
199 if (ret != 0) {
200 return ret;
201 }
Alex Deymo4344d632016-08-03 21:03:53 -0700202
Tao Baobc4b1fe2017-04-17 16:46:05 -0700203 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
204 // in the zip file.
205 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
206 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
207 ZipEntry properties_entry;
208 if (FindEntry(zip, property_name, &properties_entry) != 0) {
209 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
210 return INSTALL_CORRUPT;
211 }
212 uint32_t properties_entry_length = properties_entry.uncompressed_length;
213 std::vector<uint8_t> payload_properties(properties_entry_length);
214 int32_t err =
215 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
216 if (err != 0) {
217 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
218 return INSTALL_CORRUPT;
219 }
Alex Deymo4344d632016-08-03 21:03:53 -0700220
Tao Baobc4b1fe2017-04-17 16:46:05 -0700221 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
222 ZipString payload_name(AB_OTA_PAYLOAD);
223 ZipEntry payload_entry;
224 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
225 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
226 return INSTALL_CORRUPT;
227 }
228 long payload_offset = payload_entry.offset;
229 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700230 binary_path,
231 "--payload=file://" + package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700232 android::base::StringPrintf("--offset=%ld", payload_offset),
233 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
234 android::base::StringPrintf("--status_fd=%d", status_fd),
235 };
236 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700237}
238
239#else // !AB_OTA_UPDATER
240
Tao Bao00d57572017-05-02 15:48:54 -0700241int update_binary_command(const std::string& package, ZipArchiveHandle zip,
242 const std::string& binary_path, int retry_count, int status_fd,
243 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700244 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700245
Tao Baobc4b1fe2017-04-17 16:46:05 -0700246 // On traditional updates we extract the update binary from the package.
247 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
248 ZipString binary_name(UPDATE_BINARY_NAME);
249 ZipEntry binary_entry;
250 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
251 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
252 return INSTALL_CORRUPT;
253 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700254
Tao Bao00d57572017-05-02 15:48:54 -0700255 unlink(binary_path.c_str());
Tianjie Xude6735e2017-07-10 15:13:33 -0700256 int fd = open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755);
Tao Baobc4b1fe2017-04-17 16:46:05 -0700257 if (fd == -1) {
Tao Bao00d57572017-05-02 15:48:54 -0700258 PLOG(ERROR) << "Failed to create " << binary_path;
Tao Baobc4b1fe2017-04-17 16:46:05 -0700259 return INSTALL_ERROR;
260 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700261
Tao Baobc4b1fe2017-04-17 16:46:05 -0700262 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
263 close(fd);
264 if (error != 0) {
265 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
266 return INSTALL_ERROR;
267 }
268
269 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700270 binary_path,
Tao Baobd0ddcd2017-05-04 13:03:18 -0700271 std::to_string(kRecoveryApiVersion),
Tao Baobc4b1fe2017-04-17 16:46:05 -0700272 std::to_string(status_fd),
Tao Bao00d57572017-05-02 15:48:54 -0700273 package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700274 };
275 if (retry_count > 0) {
276 cmd->push_back("retry");
277 }
278 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700279}
280#endif // !AB_OTA_UPDATER
281
Tianjie Xu37957102017-06-07 17:59:55 -0700282static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700283 CHECK(max_temperature != nullptr);
284 std::mutex mtx;
285 std::unique_lock<std::mutex> lck(mtx);
Tianjie Xu37957102017-06-07 17:59:55 -0700286 while (!logger_finished.load() &&
287 finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700288 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
289 }
290}
291
Alex Deymo4344d632016-08-03 21:03:53 -0700292// If the package contains an update binary, extract it and run it.
Tao Bao00d57572017-05-02 15:48:54 -0700293static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
Tao Bao29ee69b2017-05-01 12:23:17 -0700294 std::vector<std::string>* log_buffer, int retry_count,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700295 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800296 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700297
Tao Bao20c581e2016-12-28 20:55:51 -0800298 int pipefd[2];
299 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700300
Tao Bao20c581e2016-12-28 20:55:51 -0800301 std::vector<std::string> args;
Tao Bao00d57572017-05-02 15:48:54 -0700302#ifdef AB_OTA_UPDATER
303 int ret = update_binary_command(package, zip, "/sbin/update_engine_sideload", retry_count,
304 pipefd[1], &args);
305#else
306 int ret = update_binary_command(package, zip, "/tmp/update-binary", retry_count, pipefd[1],
307 &args);
308#endif
Tao Bao20c581e2016-12-28 20:55:51 -0800309 if (ret) {
310 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700311 close(pipefd[1]);
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700312 log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800313 return ret;
314 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700315
Tao Bao20c581e2016-12-28 20:55:51 -0800316 // When executing the update binary contained in the package, the
317 // arguments passed are:
318 //
319 // - the version number for this interface
320 //
321 // - an FD to which the program can write in order to update the
322 // progress bar. The program can write single-line commands:
323 //
324 // progress <frac> <secs>
325 // fill up the next <frac> part of of the progress bar
326 // over <secs> seconds. If <secs> is zero, use
327 // set_progress commands to manually control the
328 // progress of this segment of the bar.
329 //
330 // set_progress <frac>
331 // <frac> should be between 0.0 and 1.0; sets the
332 // progress bar within the segment defined by the most
333 // recent progress command.
334 //
335 // ui_print <string>
336 // display <string> on the screen.
337 //
338 // wipe_cache
339 // a wipe of cache will be performed following a successful
340 // installation.
341 //
342 // clear_display
343 // turn off the text display.
344 //
345 // enable_reboot
346 // packages can explicitly request that they want the user
347 // to be able to reboot during installation (useful for
348 // debugging packages that don't exit).
349 //
350 // retry_update
351 // updater encounters some issue during the update. It requests
352 // a reboot to retry the same package automatically.
353 //
354 // log <string>
355 // updater requests logging the string (e.g. cause of the
356 // failure).
357 //
358 // - the name of the package zip file.
359 //
360 // - an optional argument "retry" if this update is a retry of a failed
361 // update attempt.
362 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700363
Tao Bao20c581e2016-12-28 20:55:51 -0800364 // Convert the vector to a NULL-terminated char* array suitable for execv.
365 const char* chr_args[args.size() + 1];
366 chr_args[args.size()] = nullptr;
367 for (size_t i = 0; i < args.size(); i++) {
368 chr_args[i] = args[i].c_str();
369 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700370
Tao Bao20c581e2016-12-28 20:55:51 -0800371 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700372
Tao Bao20c581e2016-12-28 20:55:51 -0800373 if (pid == -1) {
374 close(pipefd[0]);
375 close(pipefd[1]);
376 PLOG(ERROR) << "Failed to fork update binary";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700377 log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800378 return INSTALL_ERROR;
379 }
380
381 if (pid == 0) {
382 umask(022);
383 close(pipefd[0]);
384 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800385 // Bug: 34769056
386 // We shouldn't use LOG/PLOG in the forked process, since they may cause
387 // the child process to hang. This deadlock results from an improperly
388 // copied mutex in the ui functions.
389 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800390 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800391 }
392 close(pipefd[1]);
393
Tianjie Xu37957102017-06-07 17:59:55 -0700394 std::atomic<bool> logger_finished(false);
395 std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700396
Tao Bao20c581e2016-12-28 20:55:51 -0800397 *wipe_cache = false;
398 bool retry_update = false;
399
400 char buffer[1024];
401 FILE* from_child = fdopen(pipefd[0], "r");
402 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
403 std::string line(buffer);
404 size_t space = line.find_first_of(" \n");
405 std::string command(line.substr(0, space));
406 if (command.empty()) continue;
407
408 // Get rid of the leading and trailing space and/or newline.
409 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
410
411 if (command == "progress") {
412 std::vector<std::string> tokens = android::base::Split(args, " ");
413 double fraction;
414 int seconds;
415 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
416 android::base::ParseInt(tokens[1], &seconds)) {
417 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
418 } else {
419 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
420 }
421 } else if (command == "set_progress") {
422 std::vector<std::string> tokens = android::base::Split(args, " ");
423 double fraction;
424 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
425 ui->SetProgress(fraction);
426 } else {
427 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
428 }
429 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800430 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800431 fflush(stdout);
432 } else if (command == "wipe_cache") {
433 *wipe_cache = true;
434 } else if (command == "clear_display") {
435 ui->SetBackground(RecoveryUI::NONE);
436 } else if (command == "enable_reboot") {
437 // packages can explicitly request that they want the user
438 // to be able to reboot during installation (useful for
439 // debugging packages that don't exit).
440 ui->SetEnableReboot(true);
441 } else if (command == "retry_update") {
442 retry_update = true;
443 } else if (command == "log") {
444 if (!args.empty()) {
445 // Save the logging request from updater and write to last_install later.
Tao Bao29ee69b2017-05-01 12:23:17 -0700446 log_buffer->push_back(args);
Tao Bao20c581e2016-12-28 20:55:51 -0800447 } else {
448 LOG(ERROR) << "invalid \"log\" parameters: " << line;
449 }
450 } else {
451 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700452 }
Tao Bao20c581e2016-12-28 20:55:51 -0800453 }
454 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700455
Tao Bao20c581e2016-12-28 20:55:51 -0800456 int status;
457 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700458
Tianjie Xu37957102017-06-07 17:59:55 -0700459 logger_finished.store(true);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700460 finish_log_temperature.notify_one();
461 temperature_logger.join();
462
Tao Bao20c581e2016-12-28 20:55:51 -0800463 if (retry_update) {
464 return INSTALL_RETRY;
465 }
466 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tao Bao00d57572017-05-02 15:48:54 -0700467 LOG(ERROR) << "Error in " << package << " (Status " << WEXITSTATUS(status) << ")";
Tao Bao20c581e2016-12-28 20:55:51 -0800468 return INSTALL_ERROR;
469 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700470
Tao Bao20c581e2016-12-28 20:55:51 -0800471 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700472}
473
Tao Bao1d866052017-04-10 16:55:57 -0700474// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
475// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
476// package.
477bool verify_package_compatibility(ZipArchiveHandle package_zip) {
478 LOG(INFO) << "Verifying package compatibility...";
479
480 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
481 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
482 ZipEntry compatibility_entry;
483 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
484 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
485 return true;
486 }
487
488 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
489 int32_t ret;
490 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
491 reinterpret_cast<uint8_t*>(&zip_content[0]),
492 compatibility_entry.uncompressed_length)) != 0) {
493 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
494 return false;
495 }
496
497 ZipArchiveHandle zip_handle;
498 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
499 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
500 if (ret != 0) {
501 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
502 return false;
503 }
504
505 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
506 void* cookie;
507 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
508 if (ret != 0) {
509 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
510 CloseArchive(zip_handle);
511 return false;
512 }
513 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
514
515 std::vector<std::string> compatibility_info;
516 ZipEntry info_entry;
517 ZipString info_name;
518 while (Next(cookie, &info_entry, &info_name) == 0) {
519 std::string content(info_entry.uncompressed_length, '\0');
520 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
521 info_entry.uncompressed_length);
522 if (ret != 0) {
523 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
524 CloseArchive(zip_handle);
525 return false;
526 }
527 compatibility_info.emplace_back(std::move(content));
528 }
Tao Bao1d866052017-04-10 16:55:57 -0700529 CloseArchive(zip_handle);
530
Tao Bao919d2c92017-04-10 16:55:57 -0700531 // VintfObjectRecovery::CheckCompatibility returns zero on success.
532 std::string err;
533 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
534 if (result == 0) {
535 return true;
536 }
537
538 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
539 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700540}
541
Tao Bao29ee69b2017-05-01 12:23:17 -0700542static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount,
543 std::vector<std::string>* log_buffer, int retry_count,
544 int* max_temperature) {
545 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
546 ui->Print("Finding update package...\n");
547 // Give verification half the progress bar...
548 ui->SetProgressType(RecoveryUI::DETERMINATE);
549 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
550 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800551
Tao Bao29ee69b2017-05-01 12:23:17 -0700552 // Map the update package into memory.
553 ui->Print("Opening update package...\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800554
Tao Bao29ee69b2017-05-01 12:23:17 -0700555 if (needs_mount) {
556 if (path[0] == '@') {
557 ensure_path_mounted(path.substr(1).c_str());
558 } else {
559 ensure_path_mounted(path.c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800560 }
Tao Bao29ee69b2017-05-01 12:23:17 -0700561 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800562
Tao Bao29ee69b2017-05-01 12:23:17 -0700563 MemMapping map;
Tao Baob656a152017-04-18 23:54:29 -0700564 if (!map.MapFile(path)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700565 LOG(ERROR) << "failed to map file";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700566 log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700567 return INSTALL_CORRUPT;
568 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800569
Tao Bao29ee69b2017-05-01 12:23:17 -0700570 // Verify package.
571 if (!verify_package(map.addr, map.length)) {
572 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700573 return INSTALL_CORRUPT;
574 }
Doug Zongker60151a22009-08-12 18:30:03 -0700575
Tao Bao29ee69b2017-05-01 12:23:17 -0700576 // Try to open the package.
577 ZipArchiveHandle zip;
578 int err = OpenArchiveFromMemory(map.addr, map.length, path.c_str(), &zip);
579 if (err != 0) {
580 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
581 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800582
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700583 CloseArchive(zip);
Tao Bao29ee69b2017-05-01 12:23:17 -0700584 return INSTALL_CORRUPT;
585 }
586
587 // Additionally verify the compatibility of the package.
588 if (!verify_package_compatibility(zip)) {
589 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700590 CloseArchive(zip);
591 return INSTALL_CORRUPT;
592 }
593
594 // Verify and install the contents of the package.
595 ui->Print("Installing update...\n");
596 if (retry_count > 0) {
597 ui->Print("Retry attempt: %d\n", retry_count);
598 }
599 ui->SetEnableReboot(false);
600 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
601 ui->SetEnableReboot(true);
602 ui->Print("\n");
603
Tao Bao29ee69b2017-05-01 12:23:17 -0700604 CloseArchive(zip);
605 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800606}
Doug Zongker469243e2011-04-12 09:28:10 -0700607
Tao Bao29ee69b2017-05-01 12:23:17 -0700608int install_package(const std::string& path, bool* wipe_cache, const std::string& install_file,
609 bool needs_mount, int retry_count) {
610 CHECK(!path.empty());
611 CHECK(!install_file.empty());
612 CHECK(wipe_cache != nullptr);
613
Tao Baof8119fb2017-04-18 21:35:12 -0700614 modified_flash = true;
615 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700616
Tao Baof8119fb2017-04-18 21:35:12 -0700617 int start_temperature = GetMaxValueFromThermalZone();
618 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700619
Tao Baof8119fb2017-04-18 21:35:12 -0700620 int result;
621 std::vector<std::string> log_buffer;
622 if (setup_install_mounts() != 0) {
623 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
624 result = INSTALL_ERROR;
625 } else {
Tao Bao29ee69b2017-05-01 12:23:17 -0700626 result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count,
Tao Baof8119fb2017-04-18 21:35:12 -0700627 &max_temperature);
628 }
629
630 // Measure the time spent to apply OTA update in seconds.
631 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
632 int time_total = static_cast<int>(duration.count());
633
Tao Bao3e18f2b2017-09-29 17:11:13 -0700634 bool has_cache = volume_for_mount_point("/cache") != nullptr;
Tao Baof8119fb2017-04-18 21:35:12 -0700635 // Skip logging the uncrypt_status on devices without /cache.
636 if (has_cache) {
637 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
638 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
639 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700640 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700641 std::string uncrypt_status;
642 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
643 PLOG(WARNING) << "failed to read uncrypt status";
644 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
645 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700646 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700647 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700648 }
Doug Zongker469243e2011-04-12 09:28:10 -0700649 }
Tao Baof8119fb2017-04-18 21:35:12 -0700650 }
Tao Baobadaac42016-09-26 11:39:14 -0700651
Tao Baof8119fb2017-04-18 21:35:12 -0700652 // The first two lines need to be the package name and install result.
653 std::vector<std::string> log_header = {
654 path,
655 result == INSTALL_SUCCESS ? "1" : "0",
656 "time_total: " + std::to_string(time_total),
657 "retry: " + std::to_string(retry_count),
658 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700659
Tao Baof8119fb2017-04-18 21:35:12 -0700660 int end_temperature = GetMaxValueFromThermalZone();
661 max_temperature = std::max(end_temperature, max_temperature);
662 if (start_temperature > 0) {
663 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
664 }
665 if (end_temperature > 0) {
666 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
667 }
668 if (max_temperature > 0) {
669 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
670 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700671
Tao Baof8119fb2017-04-18 21:35:12 -0700672 std::string log_content =
673 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
674 if (!android::base::WriteStringToFile(log_content, install_file)) {
675 PLOG(ERROR) << "failed to write " << install_file;
676 }
Tao Baobadaac42016-09-26 11:39:14 -0700677
Tao Baof8119fb2017-04-18 21:35:12 -0700678 // Write a copy into last_log.
679 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700680
Tao Baof8119fb2017-04-18 21:35:12 -0700681 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700682}
Yabin Cui6faf0262016-06-09 14:09:39 -0700683
684bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700685 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700686 std::vector<Certificate> loadedKeys;
687 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
688 LOG(ERROR) << "Failed to load keys";
689 return false;
690 }
691 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700692
Tao Bao5e535012017-03-16 17:37:38 -0700693 // Verify package.
694 ui->Print("Verifying update package...\n");
695 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700696 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700697 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
698 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
699 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
700 if (err != VERIFY_SUCCESS) {
701 LOG(ERROR) << "Signature verification failed";
702 LOG(ERROR) << "error: " << kZipVerificationFailure;
703 return false;
704 }
705 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700706}