blob: 30fd2c6bee57601a014734a1698295deefae0412 [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 Bao641fa972018-04-25 18:59:40 -070055#include "otautil/paths.h"
Tao Bao00d57572017-05-02 15:48:54 -070056#include "private/install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080057#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070058#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020059#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080060
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070061using namespace std::chrono_literals;
62
Doug Zongker74406302011-10-28 15:13:10 -070063// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080064static constexpr int VERIFICATION_PROGRESS_TIME = 60;
65static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070066
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070067static std::condition_variable finish_log_temperature;
68
Tianjie Xub0ddae52016-06-08 14:30:04 -070069// This function parses and returns the build.version.incremental
Daniel Micaya29d8d62017-06-23 08:33:24 -040070static std::string parse_build_number(const std::string& str) {
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070071 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070072 if (pos != std::string::npos) {
Daniel Micaya29d8d62017-06-23 08:33:24 -040073 return android::base::Trim(str.substr(pos+1));
Tianjie Xub0ddae52016-06-08 14:30:04 -070074 }
75
Tianjie Xuc21edd42016-08-05 18:00:04 -070076 LOG(ERROR) << "Failed to parse build number in " << str;
Daniel Micaya29d8d62017-06-23 08:33:24 -040077 return "";
Tianjie Xub0ddae52016-06-08 14:30:04 -070078}
79
Tao Bao8a7afcc2017-04-18 22:05:50 -070080bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
81 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070082
Tao Bao8a7afcc2017-04-18 22:05:50 -070083 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
84 ZipString path(METADATA_PATH);
85 ZipEntry entry;
86 if (FindEntry(zip, path, &entry) != 0) {
87 LOG(ERROR) << "Failed to find " << METADATA_PATH;
88 return false;
89 }
90
91 uint32_t length = entry.uncompressed_length;
92 metadata->resize(length, '\0');
93 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
94 if (err != 0) {
95 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
96 return false;
97 }
98 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -070099}
100
101// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tao Bao29ee69b2017-05-01 12:23:17 -0700102static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>* log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700103 std::string metadata;
104 if (!read_metadata_from_package(zip, &metadata)) {
105 return;
106 }
107 // Examples of the pre-build and post-build strings in metadata:
108 // pre-build-incremental=2943039
109 // post-build-incremental=2951741
110 std::vector<std::string> lines = android::base::Split(metadata, "\n");
111 for (const std::string& line : lines) {
112 std::string str = android::base::Trim(line);
113 if (android::base::StartsWith(str, "pre-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400114 std::string source_build = parse_build_number(str);
115 if (!source_build.empty()) {
116 log_buffer->push_back("source_build: " + source_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700117 }
118 } else if (android::base::StartsWith(str, "post-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400119 std::string target_build = parse_build_number(str);
120 if (!target_build.empty()) {
121 log_buffer->push_back("target_build: " + target_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700122 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700123 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700124 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700125}
126
Alex Deymo4344d632016-08-03 21:03:53 -0700127#ifdef AB_OTA_UPDATER
128
129// Parses the metadata of the OTA package in |zip| and checks whether we are
130// allowed to accept this A/B package. Downgrading is not allowed unless
131// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800132static int check_newer_ab_build(ZipArchiveHandle zip) {
133 std::string metadata_str;
134 if (!read_metadata_from_package(zip, &metadata_str)) {
135 return INSTALL_CORRUPT;
136 }
137 std::map<std::string, std::string> metadata;
138 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
139 size_t eq = line.find('=');
140 if (eq != std::string::npos) {
141 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700142 }
Tao Baoefc35592017-01-08 22:45:47 -0800143 }
Alex Deymo4344d632016-08-03 21:03:53 -0700144
Tao Baoefc35592017-01-08 22:45:47 -0800145 std::string value = android::base::GetProperty("ro.product.device", "");
146 const std::string& pkg_device = metadata["pre-device"];
147 if (pkg_device != value || pkg_device.empty()) {
148 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
149 return INSTALL_ERROR;
150 }
Alex Deymo4344d632016-08-03 21:03:53 -0700151
Tianjie Xu69b96492017-08-17 16:42:57 -0700152 // We allow the package to not have any serialno; and we also allow it to carry multiple serial
153 // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the
154 // verification if the device's serialno doesn't match any of these carried numbers.
Tao Baoefc35592017-01-08 22:45:47 -0800155 value = android::base::GetProperty("ro.serialno", "");
156 const std::string& pkg_serial_no = metadata["serialno"];
Tianjie Xu69b96492017-08-17 16:42:57 -0700157 if (!pkg_serial_no.empty()) {
158 bool match = false;
159 for (const std::string& number : android::base::Split(pkg_serial_no, "|")) {
160 if (value == android::base::Trim(number)) {
161 match = true;
162 break;
163 }
164 }
165 if (!match) {
166 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
167 return INSTALL_ERROR;
168 }
Tao Baoefc35592017-01-08 22:45:47 -0800169 }
Alex Deymo4344d632016-08-03 21:03:53 -0700170
Tao Baoefc35592017-01-08 22:45:47 -0800171 if (metadata["ota-type"] != "AB") {
172 LOG(ERROR) << "Package is not A/B";
173 return INSTALL_ERROR;
174 }
Alex Deymo4344d632016-08-03 21:03:53 -0700175
Tao Baoefc35592017-01-08 22:45:47 -0800176 // Incremental updates should match the current build.
177 value = android::base::GetProperty("ro.build.version.incremental", "");
178 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
179 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
180 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
181 return INSTALL_ERROR;
182 }
Alex Deymo4344d632016-08-03 21:03:53 -0700183
Tao Baoefc35592017-01-08 22:45:47 -0800184 value = android::base::GetProperty("ro.build.fingerprint", "");
185 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
186 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
187 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
188 << value;
189 return INSTALL_ERROR;
190 }
Alex Deymo4344d632016-08-03 21:03:53 -0700191
Tao Baoefc35592017-01-08 22:45:47 -0800192 // Check for downgrade version.
193 int64_t build_timestamp =
194 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
195 int64_t pkg_post_timestamp = 0;
196 // We allow to full update to the same version we are running, in case there
197 // is a problem with the current copy of that version.
198 if (metadata["post-timestamp"].empty() ||
199 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
200 pkg_post_timestamp < build_timestamp) {
201 if (metadata["ota-downgrade"] != "yes") {
202 LOG(ERROR) << "Update package is older than the current build, expected a build "
203 "newer than timestamp "
204 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
205 << " and downgrade not allowed.";
206 return INSTALL_ERROR;
207 }
208 if (pkg_pre_build_fingerprint.empty()) {
209 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
210 return INSTALL_ERROR;
211 }
212 }
213
214 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700215}
216
Tao Bao00d57572017-05-02 15:48:54 -0700217int update_binary_command(const std::string& package, ZipArchiveHandle zip,
218 const std::string& binary_path, int /* retry_count */, int status_fd,
219 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700220 CHECK(cmd != nullptr);
221 int ret = check_newer_ab_build(zip);
222 if (ret != 0) {
223 return ret;
224 }
Alex Deymo4344d632016-08-03 21:03:53 -0700225
Tao Baobc4b1fe2017-04-17 16:46:05 -0700226 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
227 // in the zip file.
228 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
229 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
230 ZipEntry properties_entry;
231 if (FindEntry(zip, property_name, &properties_entry) != 0) {
232 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
233 return INSTALL_CORRUPT;
234 }
235 uint32_t properties_entry_length = properties_entry.uncompressed_length;
236 std::vector<uint8_t> payload_properties(properties_entry_length);
237 int32_t err =
238 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
239 if (err != 0) {
240 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
241 return INSTALL_CORRUPT;
242 }
Alex Deymo4344d632016-08-03 21:03:53 -0700243
Tao Baobc4b1fe2017-04-17 16:46:05 -0700244 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
245 ZipString payload_name(AB_OTA_PAYLOAD);
246 ZipEntry payload_entry;
247 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
248 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
249 return INSTALL_CORRUPT;
250 }
251 long payload_offset = payload_entry.offset;
252 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700253 binary_path,
254 "--payload=file://" + package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700255 android::base::StringPrintf("--offset=%ld", payload_offset),
256 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
257 android::base::StringPrintf("--status_fd=%d", status_fd),
258 };
259 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700260}
261
262#else // !AB_OTA_UPDATER
263
Tao Bao00d57572017-05-02 15:48:54 -0700264int update_binary_command(const std::string& package, ZipArchiveHandle zip,
265 const std::string& binary_path, int retry_count, int status_fd,
266 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700267 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700268
Tao Baobc4b1fe2017-04-17 16:46:05 -0700269 // On traditional updates we extract the update binary from the package.
270 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
271 ZipString binary_name(UPDATE_BINARY_NAME);
272 ZipEntry binary_entry;
273 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
274 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
275 return INSTALL_CORRUPT;
276 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700277
Tao Bao00d57572017-05-02 15:48:54 -0700278 unlink(binary_path.c_str());
Tianjie Xude6735e2017-07-10 15:13:33 -0700279 int fd = open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755);
Tao Baobc4b1fe2017-04-17 16:46:05 -0700280 if (fd == -1) {
Tao Bao00d57572017-05-02 15:48:54 -0700281 PLOG(ERROR) << "Failed to create " << binary_path;
Tao Baobc4b1fe2017-04-17 16:46:05 -0700282 return INSTALL_ERROR;
283 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700284
Tao Baobc4b1fe2017-04-17 16:46:05 -0700285 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
286 close(fd);
287 if (error != 0) {
288 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
289 return INSTALL_ERROR;
290 }
291
292 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700293 binary_path,
Tao Baobd0ddcd2017-05-04 13:03:18 -0700294 std::to_string(kRecoveryApiVersion),
Tao Baobc4b1fe2017-04-17 16:46:05 -0700295 std::to_string(status_fd),
Tao Bao00d57572017-05-02 15:48:54 -0700296 package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700297 };
298 if (retry_count > 0) {
299 cmd->push_back("retry");
300 }
301 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700302}
303#endif // !AB_OTA_UPDATER
304
Tianjie Xu37957102017-06-07 17:59:55 -0700305static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700306 CHECK(max_temperature != nullptr);
307 std::mutex mtx;
308 std::unique_lock<std::mutex> lck(mtx);
Tianjie Xu37957102017-06-07 17:59:55 -0700309 while (!logger_finished.load() &&
310 finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700311 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
312 }
313}
314
Alex Deymo4344d632016-08-03 21:03:53 -0700315// If the package contains an update binary, extract it and run it.
Tao Bao00d57572017-05-02 15:48:54 -0700316static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
Tao Bao29ee69b2017-05-01 12:23:17 -0700317 std::vector<std::string>* log_buffer, int retry_count,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700318 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800319 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700320
Tao Bao20c581e2016-12-28 20:55:51 -0800321 int pipefd[2];
322 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700323
Tao Bao20c581e2016-12-28 20:55:51 -0800324 std::vector<std::string> args;
Tao Bao00d57572017-05-02 15:48:54 -0700325#ifdef AB_OTA_UPDATER
326 int ret = update_binary_command(package, zip, "/sbin/update_engine_sideload", retry_count,
327 pipefd[1], &args);
328#else
329 int ret = update_binary_command(package, zip, "/tmp/update-binary", retry_count, pipefd[1],
330 &args);
331#endif
Tao Bao20c581e2016-12-28 20:55:51 -0800332 if (ret) {
333 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700334 close(pipefd[1]);
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700335 log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800336 return ret;
337 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700338
Tao Bao20c581e2016-12-28 20:55:51 -0800339 // When executing the update binary contained in the package, the
340 // arguments passed are:
341 //
342 // - the version number for this interface
343 //
344 // - an FD to which the program can write in order to update the
345 // progress bar. The program can write single-line commands:
346 //
347 // progress <frac> <secs>
348 // fill up the next <frac> part of of the progress bar
349 // over <secs> seconds. If <secs> is zero, use
350 // set_progress commands to manually control the
351 // progress of this segment of the bar.
352 //
353 // set_progress <frac>
354 // <frac> should be between 0.0 and 1.0; sets the
355 // progress bar within the segment defined by the most
356 // recent progress command.
357 //
358 // ui_print <string>
359 // display <string> on the screen.
360 //
361 // wipe_cache
362 // a wipe of cache will be performed following a successful
363 // installation.
364 //
365 // clear_display
366 // turn off the text display.
367 //
368 // enable_reboot
369 // packages can explicitly request that they want the user
370 // to be able to reboot during installation (useful for
371 // debugging packages that don't exit).
372 //
373 // retry_update
374 // updater encounters some issue during the update. It requests
375 // a reboot to retry the same package automatically.
376 //
377 // log <string>
378 // updater requests logging the string (e.g. cause of the
379 // failure).
380 //
381 // - the name of the package zip file.
382 //
383 // - an optional argument "retry" if this update is a retry of a failed
384 // update attempt.
385 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700386
Tao Bao20c581e2016-12-28 20:55:51 -0800387 // Convert the vector to a NULL-terminated char* array suitable for execv.
388 const char* chr_args[args.size() + 1];
389 chr_args[args.size()] = nullptr;
390 for (size_t i = 0; i < args.size(); i++) {
391 chr_args[i] = args[i].c_str();
392 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700393
Tao Bao20c581e2016-12-28 20:55:51 -0800394 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700395
Tao Bao20c581e2016-12-28 20:55:51 -0800396 if (pid == -1) {
397 close(pipefd[0]);
398 close(pipefd[1]);
399 PLOG(ERROR) << "Failed to fork update binary";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700400 log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800401 return INSTALL_ERROR;
402 }
403
404 if (pid == 0) {
405 umask(022);
406 close(pipefd[0]);
407 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800408 // Bug: 34769056
409 // We shouldn't use LOG/PLOG in the forked process, since they may cause
410 // the child process to hang. This deadlock results from an improperly
411 // copied mutex in the ui functions.
412 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800413 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800414 }
415 close(pipefd[1]);
416
Tianjie Xu37957102017-06-07 17:59:55 -0700417 std::atomic<bool> logger_finished(false);
418 std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700419
Tao Bao20c581e2016-12-28 20:55:51 -0800420 *wipe_cache = false;
421 bool retry_update = false;
422
423 char buffer[1024];
424 FILE* from_child = fdopen(pipefd[0], "r");
425 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
426 std::string line(buffer);
427 size_t space = line.find_first_of(" \n");
428 std::string command(line.substr(0, space));
429 if (command.empty()) continue;
430
431 // Get rid of the leading and trailing space and/or newline.
432 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
433
434 if (command == "progress") {
435 std::vector<std::string> tokens = android::base::Split(args, " ");
436 double fraction;
437 int seconds;
438 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
439 android::base::ParseInt(tokens[1], &seconds)) {
440 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
441 } else {
442 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
443 }
444 } else if (command == "set_progress") {
445 std::vector<std::string> tokens = android::base::Split(args, " ");
446 double fraction;
447 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
448 ui->SetProgress(fraction);
449 } else {
450 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
451 }
452 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800453 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800454 fflush(stdout);
455 } else if (command == "wipe_cache") {
456 *wipe_cache = true;
457 } else if (command == "clear_display") {
458 ui->SetBackground(RecoveryUI::NONE);
459 } else if (command == "enable_reboot") {
460 // packages can explicitly request that they want the user
461 // to be able to reboot during installation (useful for
462 // debugging packages that don't exit).
463 ui->SetEnableReboot(true);
464 } else if (command == "retry_update") {
465 retry_update = true;
466 } else if (command == "log") {
467 if (!args.empty()) {
468 // Save the logging request from updater and write to last_install later.
Tao Bao29ee69b2017-05-01 12:23:17 -0700469 log_buffer->push_back(args);
Tao Bao20c581e2016-12-28 20:55:51 -0800470 } else {
471 LOG(ERROR) << "invalid \"log\" parameters: " << line;
472 }
473 } else {
474 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700475 }
Tao Bao20c581e2016-12-28 20:55:51 -0800476 }
477 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700478
Tao Bao20c581e2016-12-28 20:55:51 -0800479 int status;
480 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700481
Tianjie Xu37957102017-06-07 17:59:55 -0700482 logger_finished.store(true);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700483 finish_log_temperature.notify_one();
484 temperature_logger.join();
485
Tao Bao20c581e2016-12-28 20:55:51 -0800486 if (retry_update) {
487 return INSTALL_RETRY;
488 }
489 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tao Bao00d57572017-05-02 15:48:54 -0700490 LOG(ERROR) << "Error in " << package << " (Status " << WEXITSTATUS(status) << ")";
Tao Bao20c581e2016-12-28 20:55:51 -0800491 return INSTALL_ERROR;
492 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700493
Tao Bao20c581e2016-12-28 20:55:51 -0800494 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700495}
496
Tao Bao1d866052017-04-10 16:55:57 -0700497// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
498// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
499// package.
500bool verify_package_compatibility(ZipArchiveHandle package_zip) {
501 LOG(INFO) << "Verifying package compatibility...";
502
503 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
504 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
505 ZipEntry compatibility_entry;
506 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
507 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
508 return true;
509 }
510
511 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
512 int32_t ret;
513 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
514 reinterpret_cast<uint8_t*>(&zip_content[0]),
515 compatibility_entry.uncompressed_length)) != 0) {
516 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
517 return false;
518 }
519
520 ZipArchiveHandle zip_handle;
521 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
522 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
523 if (ret != 0) {
524 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
525 return false;
526 }
527
528 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
529 void* cookie;
530 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
531 if (ret != 0) {
532 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
533 CloseArchive(zip_handle);
534 return false;
535 }
536 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
537
538 std::vector<std::string> compatibility_info;
539 ZipEntry info_entry;
540 ZipString info_name;
541 while (Next(cookie, &info_entry, &info_name) == 0) {
542 std::string content(info_entry.uncompressed_length, '\0');
543 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
544 info_entry.uncompressed_length);
545 if (ret != 0) {
546 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
547 CloseArchive(zip_handle);
548 return false;
549 }
550 compatibility_info.emplace_back(std::move(content));
551 }
Tao Bao1d866052017-04-10 16:55:57 -0700552 CloseArchive(zip_handle);
553
Tao Bao919d2c92017-04-10 16:55:57 -0700554 // VintfObjectRecovery::CheckCompatibility returns zero on success.
555 std::string err;
556 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
557 if (result == 0) {
558 return true;
559 }
560
561 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
562 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700563}
564
Tao Bao29ee69b2017-05-01 12:23:17 -0700565static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount,
566 std::vector<std::string>* log_buffer, int retry_count,
567 int* max_temperature) {
568 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
569 ui->Print("Finding update package...\n");
570 // Give verification half the progress bar...
571 ui->SetProgressType(RecoveryUI::DETERMINATE);
572 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
573 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800574
Tao Bao29ee69b2017-05-01 12:23:17 -0700575 // Map the update package into memory.
576 ui->Print("Opening update package...\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800577
Tao Bao29ee69b2017-05-01 12:23:17 -0700578 if (needs_mount) {
579 if (path[0] == '@') {
580 ensure_path_mounted(path.substr(1).c_str());
581 } else {
582 ensure_path_mounted(path.c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800583 }
Tao Bao29ee69b2017-05-01 12:23:17 -0700584 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800585
Tao Bao29ee69b2017-05-01 12:23:17 -0700586 MemMapping map;
Tao Baob656a152017-04-18 23:54:29 -0700587 if (!map.MapFile(path)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700588 LOG(ERROR) << "failed to map file";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700589 log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700590 return INSTALL_CORRUPT;
591 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800592
Tao Bao29ee69b2017-05-01 12:23:17 -0700593 // Verify package.
594 if (!verify_package(map.addr, map.length)) {
595 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700596 return INSTALL_CORRUPT;
597 }
Doug Zongker60151a22009-08-12 18:30:03 -0700598
Tao Bao29ee69b2017-05-01 12:23:17 -0700599 // Try to open the package.
600 ZipArchiveHandle zip;
601 int err = OpenArchiveFromMemory(map.addr, map.length, path.c_str(), &zip);
602 if (err != 0) {
603 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
604 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800605
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700606 CloseArchive(zip);
Tao Bao29ee69b2017-05-01 12:23:17 -0700607 return INSTALL_CORRUPT;
608 }
609
610 // Additionally verify the compatibility of the package.
611 if (!verify_package_compatibility(zip)) {
612 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700613 CloseArchive(zip);
614 return INSTALL_CORRUPT;
615 }
616
617 // Verify and install the contents of the package.
618 ui->Print("Installing update...\n");
619 if (retry_count > 0) {
620 ui->Print("Retry attempt: %d\n", retry_count);
621 }
622 ui->SetEnableReboot(false);
623 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
624 ui->SetEnableReboot(true);
625 ui->Print("\n");
626
Tao Bao29ee69b2017-05-01 12:23:17 -0700627 CloseArchive(zip);
628 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800629}
Doug Zongker469243e2011-04-12 09:28:10 -0700630
Tao Bao641fa972018-04-25 18:59:40 -0700631int install_package(const std::string& path, bool* wipe_cache, bool needs_mount, int retry_count) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700632 CHECK(!path.empty());
Tao Bao29ee69b2017-05-01 12:23:17 -0700633 CHECK(wipe_cache != nullptr);
634
Tao Baof8119fb2017-04-18 21:35:12 -0700635 modified_flash = true;
636 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700637
Tao Baof8119fb2017-04-18 21:35:12 -0700638 int start_temperature = GetMaxValueFromThermalZone();
639 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700640
Tao Baof8119fb2017-04-18 21:35:12 -0700641 int result;
642 std::vector<std::string> log_buffer;
643 if (setup_install_mounts() != 0) {
644 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
645 result = INSTALL_ERROR;
646 } else {
Tao Bao29ee69b2017-05-01 12:23:17 -0700647 result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count,
Tao Baof8119fb2017-04-18 21:35:12 -0700648 &max_temperature);
649 }
650
651 // Measure the time spent to apply OTA update in seconds.
652 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
653 int time_total = static_cast<int>(duration.count());
654
Tao Bao3e18f2b2017-09-29 17:11:13 -0700655 bool has_cache = volume_for_mount_point("/cache") != nullptr;
Tao Baof8119fb2017-04-18 21:35:12 -0700656 // Skip logging the uncrypt_status on devices without /cache.
657 if (has_cache) {
658 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
659 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
660 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700661 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700662 std::string uncrypt_status;
663 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
664 PLOG(WARNING) << "failed to read uncrypt status";
665 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
666 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700667 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700668 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700669 }
Doug Zongker469243e2011-04-12 09:28:10 -0700670 }
Tao Baof8119fb2017-04-18 21:35:12 -0700671 }
Tao Baobadaac42016-09-26 11:39:14 -0700672
Tao Baof8119fb2017-04-18 21:35:12 -0700673 // The first two lines need to be the package name and install result.
674 std::vector<std::string> log_header = {
675 path,
676 result == INSTALL_SUCCESS ? "1" : "0",
677 "time_total: " + std::to_string(time_total),
678 "retry: " + std::to_string(retry_count),
679 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700680
Tao Baof8119fb2017-04-18 21:35:12 -0700681 int end_temperature = GetMaxValueFromThermalZone();
682 max_temperature = std::max(end_temperature, max_temperature);
683 if (start_temperature > 0) {
684 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
685 }
686 if (end_temperature > 0) {
687 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
688 }
689 if (max_temperature > 0) {
690 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
691 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700692
Tao Baof8119fb2017-04-18 21:35:12 -0700693 std::string log_content =
694 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
Tao Bao641fa972018-04-25 18:59:40 -0700695 const std::string& install_file = Paths::Get().temporary_install_file();
Tao Baof8119fb2017-04-18 21:35:12 -0700696 if (!android::base::WriteStringToFile(log_content, install_file)) {
697 PLOG(ERROR) << "failed to write " << install_file;
698 }
Tao Baobadaac42016-09-26 11:39:14 -0700699
Tao Baof8119fb2017-04-18 21:35:12 -0700700 // Write a copy into last_log.
701 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700702
Tao Baof8119fb2017-04-18 21:35:12 -0700703 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700704}
Yabin Cui6faf0262016-06-09 14:09:39 -0700705
706bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700707 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700708 std::vector<Certificate> loadedKeys;
709 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
710 LOG(ERROR) << "Failed to load keys";
711 return false;
712 }
713 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700714
Tao Bao5e535012017-03-16 17:37:38 -0700715 // Verify package.
716 ui->Print("Verifying update package...\n");
717 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700718 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700719 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
720 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
721 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
722 if (err != VERIFY_SUCCESS) {
723 LOG(ERROR) << "Signature verification failed";
724 LOG(ERROR) << "error: " << kZipVerificationFailure;
725 return false;
726 }
727 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700728}