blob: 8e956c6c332565f8abe23b6d2c79ee2b302ea497 [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
Tom Marshalla08c6f12019-01-04 14:37:31 -08003 * Copyright (C) 2019 The LineageOS Project
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
Tao Bao20c581e2016-12-28 20:55:51 -080018#include "install.h"
19
Doug Zongkerb2ee9202009-06-04 10:24:53 -070020#include <ctype.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080021#include <errno.h>
22#include <fcntl.h>
Alex Deymo4e29ce02016-08-12 13:43:04 -070023#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080024#include <limits.h>
Tom Marshall5b4a9d82018-12-17 15:57:44 -080025#include <setjmp.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080026#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080027#include <sys/stat.h>
Doug Zongkerb2ee9202009-06-04 10:24:53 -070028#include <sys/wait.h>
29#include <unistd.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080030
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070031#include <algorithm>
Tianjie Xu37957102017-06-07 17:59:55 -070032#include <atomic>
Elliott Hughes8febafa2016-04-13 16:39:56 -070033#include <chrono>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070034#include <condition_variable>
Tao Bao5e535012017-03-16 17:37:38 -070035#include <functional>
Alex Deymo4344d632016-08-03 21:03:53 -070036#include <limits>
37#include <map>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070038#include <mutex>
Tianjie Xudd874b12016-05-13 12:13:15 -070039#include <string>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070040#include <thread>
Tao Bao71e3e092016-02-02 14:02:27 -080041#include <vector>
42
Tianjie Xue16e7992016-09-09 10:55:44 -070043#include <android-base/file.h>
44#include <android-base/logging.h>
Tao Bao20c581e2016-12-28 20:55:51 -080045#include <android-base/parsedouble.h>
Tianjie Xub0ddae52016-06-08 14:30:04 -070046#include <android-base/parseint.h>
Tao Baoefc35592017-01-08 22:45:47 -080047#include <android-base/properties.h>
Tianjie Xu16255832016-04-30 11:49:59 -070048#include <android-base/stringprintf.h>
49#include <android-base/strings.h>
Tao Bao919d2c92017-04-10 16:55:57 -070050#include <vintf/VintfObjectRecovery.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070051#include <ziparchive/zip_archive.h>
Tianjie Xu16255832016-04-30 11:49:59 -070052
Steve Kondikb910bb32014-04-03 22:50:38 -070053#include <cutils/properties.h>
54
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080055#include "common.h"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070056#include "otautil/SysUtil.h"
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070057#include "otautil/ThermalUtil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070058#include "otautil/error_code.h"
Tao Bao00d57572017-05-02 15:48:54 -070059#include "private/install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080060#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070061#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020062#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080063
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070064using namespace std::chrono_literals;
65
Doug Zongker74406302011-10-28 15:13:10 -070066// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080067static constexpr int VERIFICATION_PROGRESS_TIME = 60;
68static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070069
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070070static std::condition_variable finish_log_temperature;
71
Tianjie Xub0ddae52016-06-08 14:30:04 -070072// This function parses and returns the build.version.incremental
Daniel Micaya29d8d62017-06-23 08:33:24 -040073static std::string parse_build_number(const std::string& str) {
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070074 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070075 if (pos != std::string::npos) {
Daniel Micaya29d8d62017-06-23 08:33:24 -040076 return android::base::Trim(str.substr(pos+1));
Tianjie Xub0ddae52016-06-08 14:30:04 -070077 }
78
Tianjie Xuc21edd42016-08-05 18:00:04 -070079 LOG(ERROR) << "Failed to parse build number in " << str;
Daniel Micaya29d8d62017-06-23 08:33:24 -040080 return "";
Tianjie Xub0ddae52016-06-08 14:30:04 -070081}
82
Tao Bao8a7afcc2017-04-18 22:05:50 -070083bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
84 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070085
Tao Bao8a7afcc2017-04-18 22:05:50 -070086 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
87 ZipString path(METADATA_PATH);
88 ZipEntry entry;
89 if (FindEntry(zip, path, &entry) != 0) {
90 LOG(ERROR) << "Failed to find " << METADATA_PATH;
91 return false;
92 }
93
94 uint32_t length = entry.uncompressed_length;
95 metadata->resize(length, '\0');
96 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
97 if (err != 0) {
98 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
99 return false;
100 }
101 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700102}
103
104// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tao Bao29ee69b2017-05-01 12:23:17 -0700105static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>* log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700106 std::string metadata;
107 if (!read_metadata_from_package(zip, &metadata)) {
108 return;
109 }
110 // Examples of the pre-build and post-build strings in metadata:
111 // pre-build-incremental=2943039
112 // post-build-incremental=2951741
113 std::vector<std::string> lines = android::base::Split(metadata, "\n");
114 for (const std::string& line : lines) {
115 std::string str = android::base::Trim(line);
116 if (android::base::StartsWith(str, "pre-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400117 std::string source_build = parse_build_number(str);
118 if (!source_build.empty()) {
119 log_buffer->push_back("source_build: " + source_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700120 }
121 } else if (android::base::StartsWith(str, "post-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400122 std::string target_build = parse_build_number(str);
123 if (!target_build.empty()) {
124 log_buffer->push_back("target_build: " + target_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700125 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700126 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700127 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700128}
129
Alex Deymo4344d632016-08-03 21:03:53 -0700130// Parses the metadata of the OTA package in |zip| and checks whether we are
131// allowed to accept this A/B package. Downgrading is not allowed unless
132// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800133static int check_newer_ab_build(ZipArchiveHandle zip) {
134 std::string metadata_str;
135 if (!read_metadata_from_package(zip, &metadata_str)) {
136 return INSTALL_CORRUPT;
137 }
138 std::map<std::string, std::string> metadata;
139 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
140 size_t eq = line.find('=');
141 if (eq != std::string::npos) {
142 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700143 }
Tao Baoefc35592017-01-08 22:45:47 -0800144 }
Alex Deymo4344d632016-08-03 21:03:53 -0700145
Tao Baoefc35592017-01-08 22:45:47 -0800146 std::string value = android::base::GetProperty("ro.product.device", "");
147 const std::string& pkg_device = metadata["pre-device"];
148 if (pkg_device != value || pkg_device.empty()) {
149 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
150 return INSTALL_ERROR;
151 }
Alex Deymo4344d632016-08-03 21:03:53 -0700152
Tianjie Xu69b96492017-08-17 16:42:57 -0700153 // We allow the package to not have any serialno; and we also allow it to carry multiple serial
154 // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the
155 // verification if the device's serialno doesn't match any of these carried numbers.
Tao Baoefc35592017-01-08 22:45:47 -0800156 value = android::base::GetProperty("ro.serialno", "");
157 const std::string& pkg_serial_no = metadata["serialno"];
Tianjie Xu69b96492017-08-17 16:42:57 -0700158 if (!pkg_serial_no.empty()) {
159 bool match = false;
160 for (const std::string& number : android::base::Split(pkg_serial_no, "|")) {
161 if (value == android::base::Trim(number)) {
162 match = true;
163 break;
164 }
165 }
166 if (!match) {
167 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
168 return INSTALL_ERROR;
169 }
Tao Baoefc35592017-01-08 22:45:47 -0800170 }
Alex Deymo4344d632016-08-03 21:03:53 -0700171
Tao Baoefc35592017-01-08 22:45:47 -0800172 if (metadata["ota-type"] != "AB") {
173 LOG(ERROR) << "Package is not A/B";
174 return INSTALL_ERROR;
175 }
Alex Deymo4344d632016-08-03 21:03:53 -0700176
Tao Baoefc35592017-01-08 22:45:47 -0800177 // Incremental updates should match the current build.
178 value = android::base::GetProperty("ro.build.version.incremental", "");
179 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
180 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
181 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
182 return INSTALL_ERROR;
183 }
Alex Deymo4344d632016-08-03 21:03:53 -0700184
Tao Baoefc35592017-01-08 22:45:47 -0800185 value = android::base::GetProperty("ro.build.fingerprint", "");
186 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
187 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
188 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
189 << value;
190 return INSTALL_ERROR;
191 }
Alex Deymo4344d632016-08-03 21:03:53 -0700192
Tao Baoefc35592017-01-08 22:45:47 -0800193 // Check for downgrade version.
194 int64_t build_timestamp =
195 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
196 int64_t pkg_post_timestamp = 0;
197 // We allow to full update to the same version we are running, in case there
198 // is a problem with the current copy of that version.
199 if (metadata["post-timestamp"].empty() ||
200 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
201 pkg_post_timestamp < build_timestamp) {
202 if (metadata["ota-downgrade"] != "yes") {
203 LOG(ERROR) << "Update package is older than the current build, expected a build "
204 "newer than timestamp "
205 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
206 << " and downgrade not allowed.";
207 return INSTALL_ERROR;
208 }
209 if (pkg_pre_build_fingerprint.empty()) {
210 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
211 return INSTALL_ERROR;
212 }
213 }
214
215 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700216}
217
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200218int update_binary_command_ab(const std::string& package, ZipArchiveHandle zip,
219 const std::string& binary_path, int /* retry_count */, int status_fd,
220 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700221 CHECK(cmd != nullptr);
222 int ret = check_newer_ab_build(zip);
223 if (ret != 0) {
224 return ret;
225 }
Alex Deymo4344d632016-08-03 21:03:53 -0700226
Tao Baobc4b1fe2017-04-17 16:46:05 -0700227 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
228 // in the zip file.
229 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
230 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
231 ZipEntry properties_entry;
232 if (FindEntry(zip, property_name, &properties_entry) != 0) {
233 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
234 return INSTALL_CORRUPT;
235 }
236 uint32_t properties_entry_length = properties_entry.uncompressed_length;
237 std::vector<uint8_t> payload_properties(properties_entry_length);
238 int32_t err =
239 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
240 if (err != 0) {
241 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
242 return INSTALL_CORRUPT;
243 }
Alex Deymo4344d632016-08-03 21:03:53 -0700244
Tao Baobc4b1fe2017-04-17 16:46:05 -0700245 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
246 ZipString payload_name(AB_OTA_PAYLOAD);
247 ZipEntry payload_entry;
248 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
249 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
250 return INSTALL_CORRUPT;
251 }
252 long payload_offset = payload_entry.offset;
253 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700254 binary_path,
255 "--payload=file://" + package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700256 android::base::StringPrintf("--offset=%ld", payload_offset),
257 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
258 android::base::StringPrintf("--status_fd=%d", status_fd),
259 };
260 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700261}
262
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200263int update_binary_command_legacy(const std::string& package, ZipArchiveHandle zip,
264 const std::string& binary_path, int retry_count, int status_fd,
265 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700266 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700267
Tao Baobc4b1fe2017-04-17 16:46:05 -0700268 // On traditional updates we extract the update binary from the package.
269 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
270 ZipString binary_name(UPDATE_BINARY_NAME);
271 ZipEntry binary_entry;
272 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
273 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
274 return INSTALL_CORRUPT;
275 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700276
Tao Bao00d57572017-05-02 15:48:54 -0700277 unlink(binary_path.c_str());
Tianjie Xude6735e2017-07-10 15:13:33 -0700278 int fd = open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755);
Tao Baobc4b1fe2017-04-17 16:46:05 -0700279 if (fd == -1) {
Tao Bao00d57572017-05-02 15:48:54 -0700280 PLOG(ERROR) << "Failed to create " << binary_path;
Tao Baobc4b1fe2017-04-17 16:46:05 -0700281 return INSTALL_ERROR;
282 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700283
Tao Baobc4b1fe2017-04-17 16:46:05 -0700284 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
285 close(fd);
286 if (error != 0) {
287 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
288 return INSTALL_ERROR;
289 }
290
291 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700292 binary_path,
Tao Baobd0ddcd2017-05-04 13:03:18 -0700293 std::to_string(kRecoveryApiVersion),
Tao Baobc4b1fe2017-04-17 16:46:05 -0700294 std::to_string(status_fd),
Tao Bao00d57572017-05-02 15:48:54 -0700295 package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700296 };
297 if (retry_count > 0) {
298 cmd->push_back("retry");
299 }
300 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700301}
Alex Deymo4344d632016-08-03 21:03:53 -0700302
Tianjie Xu37957102017-06-07 17:59:55 -0700303static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700304 CHECK(max_temperature != nullptr);
305 std::mutex mtx;
306 std::unique_lock<std::mutex> lck(mtx);
Tianjie Xu37957102017-06-07 17:59:55 -0700307 while (!logger_finished.load() &&
308 finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700309 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
310 }
311}
312
Tom Marshall5b4a9d82018-12-17 15:57:44 -0800313static jmp_buf jb;
314static void sig_bus(int) {
315 longjmp(jb, 1);
316}
317
Alex Deymo4344d632016-08-03 21:03:53 -0700318// If the package contains an update binary, extract it and run it.
Tao Bao00d57572017-05-02 15:48:54 -0700319static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
Tao Bao29ee69b2017-05-01 12:23:17 -0700320 std::vector<std::string>* log_buffer, int retry_count,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700321 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800322 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700323
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200324 int ret;
Tao Bao20c581e2016-12-28 20:55:51 -0800325 int pipefd[2];
326 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700327
Tao Bao20c581e2016-12-28 20:55:51 -0800328 std::vector<std::string> args;
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200329 bool ab_ota = false;
330
Tao Bao00d57572017-05-02 15:48:54 -0700331#ifdef AB_OTA_UPDATER
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200332 // A/B updates contain a payload.bin and a text file describing the payload.
333 // We check for this file to see whether the update package has to be flashed using update_engine
334 // or if it's a traditional package with an updater-script.
335 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
336 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
337 ZipEntry properties_entry;
338 if (FindEntry(zip, property_name, &properties_entry) == 0) {
339 ab_ota = true;
340 }
Tao Bao00d57572017-05-02 15:48:54 -0700341#endif
Christopher N. Hessebc6b4f72018-04-03 21:57:30 +0200342
343 if (ab_ota) {
344 ret = update_binary_command_ab(package, zip, "/sbin/update_engine_sideload", retry_count,
345 pipefd[1], &args);
346 } else {
347 ret = update_binary_command_legacy(package, zip, "/tmp/update-binary", retry_count, pipefd[1],
348 &args);
349 }
Tao Bao20c581e2016-12-28 20:55:51 -0800350 if (ret) {
351 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700352 close(pipefd[1]);
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700353 log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800354 return ret;
355 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700356
Tao Bao20c581e2016-12-28 20:55:51 -0800357 // When executing the update binary contained in the package, the
358 // arguments passed are:
359 //
360 // - the version number for this interface
361 //
362 // - an FD to which the program can write in order to update the
363 // progress bar. The program can write single-line commands:
364 //
365 // progress <frac> <secs>
366 // fill up the next <frac> part of of the progress bar
367 // over <secs> seconds. If <secs> is zero, use
368 // set_progress commands to manually control the
369 // progress of this segment of the bar.
370 //
371 // set_progress <frac>
372 // <frac> should be between 0.0 and 1.0; sets the
373 // progress bar within the segment defined by the most
374 // recent progress command.
375 //
376 // ui_print <string>
377 // display <string> on the screen.
378 //
379 // wipe_cache
380 // a wipe of cache will be performed following a successful
381 // installation.
382 //
383 // clear_display
384 // turn off the text display.
385 //
386 // enable_reboot
387 // packages can explicitly request that they want the user
388 // to be able to reboot during installation (useful for
389 // debugging packages that don't exit).
390 //
391 // retry_update
392 // updater encounters some issue during the update. It requests
393 // a reboot to retry the same package automatically.
394 //
395 // log <string>
396 // updater requests logging the string (e.g. cause of the
397 // failure).
398 //
399 // - the name of the package zip file.
400 //
401 // - an optional argument "retry" if this update is a retry of a failed
402 // update attempt.
403 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700404
Tao Bao20c581e2016-12-28 20:55:51 -0800405 // Convert the vector to a NULL-terminated char* array suitable for execv.
406 const char* chr_args[args.size() + 1];
407 chr_args[args.size()] = nullptr;
408 for (size_t i = 0; i < args.size(); i++) {
409 chr_args[i] = args[i].c_str();
410 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700411
Tao Bao20c581e2016-12-28 20:55:51 -0800412 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700413
Tao Bao20c581e2016-12-28 20:55:51 -0800414 if (pid == -1) {
415 close(pipefd[0]);
416 close(pipefd[1]);
417 PLOG(ERROR) << "Failed to fork update binary";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700418 log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800419 return INSTALL_ERROR;
420 }
421
422 if (pid == 0) {
423 umask(022);
424 close(pipefd[0]);
425 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800426 // Bug: 34769056
427 // We shouldn't use LOG/PLOG in the forked process, since they may cause
428 // the child process to hang. This deadlock results from an improperly
429 // copied mutex in the ui functions.
430 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800431 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800432 }
433 close(pipefd[1]);
434
Tianjie Xu37957102017-06-07 17:59:55 -0700435 std::atomic<bool> logger_finished(false);
436 std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700437
Tao Bao20c581e2016-12-28 20:55:51 -0800438 *wipe_cache = false;
439 bool retry_update = false;
440
441 char buffer[1024];
442 FILE* from_child = fdopen(pipefd[0], "r");
443 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
444 std::string line(buffer);
445 size_t space = line.find_first_of(" \n");
446 std::string command(line.substr(0, space));
447 if (command.empty()) continue;
448
449 // Get rid of the leading and trailing space and/or newline.
450 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
451
452 if (command == "progress") {
453 std::vector<std::string> tokens = android::base::Split(args, " ");
454 double fraction;
455 int seconds;
456 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
457 android::base::ParseInt(tokens[1], &seconds)) {
458 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
459 } else {
460 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
461 }
462 } else if (command == "set_progress") {
463 std::vector<std::string> tokens = android::base::Split(args, " ");
464 double fraction;
465 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
466 ui->SetProgress(fraction);
467 } else {
468 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
469 }
470 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800471 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800472 fflush(stdout);
473 } else if (command == "wipe_cache") {
474 *wipe_cache = true;
475 } else if (command == "clear_display") {
476 ui->SetBackground(RecoveryUI::NONE);
477 } else if (command == "enable_reboot") {
478 // packages can explicitly request that they want the user
479 // to be able to reboot during installation (useful for
480 // debugging packages that don't exit).
481 ui->SetEnableReboot(true);
482 } else if (command == "retry_update") {
483 retry_update = true;
484 } else if (command == "log") {
485 if (!args.empty()) {
486 // Save the logging request from updater and write to last_install later.
Tao Bao29ee69b2017-05-01 12:23:17 -0700487 log_buffer->push_back(args);
Tao Bao20c581e2016-12-28 20:55:51 -0800488 } else {
489 LOG(ERROR) << "invalid \"log\" parameters: " << line;
490 }
491 } else {
492 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700493 }
Tao Bao20c581e2016-12-28 20:55:51 -0800494 }
495 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700496
Tao Bao20c581e2016-12-28 20:55:51 -0800497 int status;
498 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700499
Tianjie Xu37957102017-06-07 17:59:55 -0700500 logger_finished.store(true);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700501 finish_log_temperature.notify_one();
502 temperature_logger.join();
503
Tao Bao20c581e2016-12-28 20:55:51 -0800504 if (retry_update) {
505 return INSTALL_RETRY;
506 }
507 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tao Bao00d57572017-05-02 15:48:54 -0700508 LOG(ERROR) << "Error in " << package << " (Status " << WEXITSTATUS(status) << ")";
Tao Bao20c581e2016-12-28 20:55:51 -0800509 return INSTALL_ERROR;
510 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700511
Tao Bao20c581e2016-12-28 20:55:51 -0800512 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700513}
514
Tao Bao1d866052017-04-10 16:55:57 -0700515// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
516// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
517// package.
518bool verify_package_compatibility(ZipArchiveHandle package_zip) {
519 LOG(INFO) << "Verifying package compatibility...";
520
521 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
522 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
523 ZipEntry compatibility_entry;
524 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
525 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
526 return true;
527 }
528
529 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
530 int32_t ret;
531 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
532 reinterpret_cast<uint8_t*>(&zip_content[0]),
533 compatibility_entry.uncompressed_length)) != 0) {
534 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
535 return false;
536 }
537
538 ZipArchiveHandle zip_handle;
539 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
540 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
541 if (ret != 0) {
542 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
543 return false;
544 }
545
546 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
547 void* cookie;
548 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
549 if (ret != 0) {
550 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
551 CloseArchive(zip_handle);
552 return false;
553 }
554 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
555
556 std::vector<std::string> compatibility_info;
557 ZipEntry info_entry;
558 ZipString info_name;
559 while (Next(cookie, &info_entry, &info_name) == 0) {
560 std::string content(info_entry.uncompressed_length, '\0');
561 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
562 info_entry.uncompressed_length);
563 if (ret != 0) {
564 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
565 CloseArchive(zip_handle);
566 return false;
567 }
568 compatibility_info.emplace_back(std::move(content));
569 }
Tao Bao1d866052017-04-10 16:55:57 -0700570 CloseArchive(zip_handle);
571
Tao Bao919d2c92017-04-10 16:55:57 -0700572 // VintfObjectRecovery::CheckCompatibility returns zero on success.
573 std::string err;
574 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
575 if (result == 0) {
576 return true;
577 }
578
579 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
580 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700581}
582
Tom Marshalla08c6f12019-01-04 14:37:31 -0800583static int really_install_package(std::string path, bool* wipe_cache, bool needs_mount,
Tao Bao29ee69b2017-05-01 12:23:17 -0700584 std::vector<std::string>* log_buffer, int retry_count,
Tom Marshalle2b6a972018-06-21 00:57:24 +0200585 bool verify, int* max_temperature) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700586 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
587 ui->Print("Finding update package...\n");
588 // Give verification half the progress bar...
589 ui->SetProgressType(RecoveryUI::DETERMINATE);
590 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tom Marshalla08c6f12019-01-04 14:37:31 -0800591
592 // Resolve symlink in case legacy /sdcard path is used
593 // Requires: symlink uses absolute path
594 if (path.size() > 1) {
595 size_t root_pos = path.find('/', 1);
596 if (root_pos != std::string::npos) {
597 char link_path[PATH_MAX];
598 ssize_t link_len;
599 memset(link_path, 0, sizeof(link_path));
600 link_len = readlink(path.substr(0, root_pos).c_str(), link_path, sizeof(link_path) - 1);
601 if (link_len > 0) {
602 path = link_path + path.substr(root_pos);
603 }
604 }
605 }
606
Tao Bao29ee69b2017-05-01 12:23:17 -0700607 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800608
Tao Bao29ee69b2017-05-01 12:23:17 -0700609 // Map the update package into memory.
610 ui->Print("Opening update package...\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800611
Tao Bao29ee69b2017-05-01 12:23:17 -0700612 if (needs_mount) {
613 if (path[0] == '@') {
614 ensure_path_mounted(path.substr(1).c_str());
615 } else {
616 ensure_path_mounted(path.c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800617 }
Tao Bao29ee69b2017-05-01 12:23:17 -0700618 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800619
Tao Bao29ee69b2017-05-01 12:23:17 -0700620 MemMapping map;
Tao Baob656a152017-04-18 23:54:29 -0700621 if (!map.MapFile(path)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700622 LOG(ERROR) << "failed to map file";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700623 log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700624 return INSTALL_CORRUPT;
625 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800626
Tao Bao29ee69b2017-05-01 12:23:17 -0700627 // Verify package.
Steve Kondikb910bb32014-04-03 22:50:38 -0700628 set_perf_mode(true);
Tom Marshalle2b6a972018-06-21 00:57:24 +0200629 if (verify && !verify_package(map.addr, map.length)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700630 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Steve Kondikb910bb32014-04-03 22:50:38 -0700631 set_perf_mode(false);
Tom Marshalle2b6a972018-06-21 00:57:24 +0200632 return INSTALL_UNVERIFIED;
Tao Bao29ee69b2017-05-01 12:23:17 -0700633 }
Doug Zongker60151a22009-08-12 18:30:03 -0700634
Tao Bao29ee69b2017-05-01 12:23:17 -0700635 // Try to open the package.
636 ZipArchiveHandle zip;
637 int err = OpenArchiveFromMemory(map.addr, map.length, path.c_str(), &zip);
638 if (err != 0) {
639 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
640 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800641
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700642 CloseArchive(zip);
Steve Kondikb910bb32014-04-03 22:50:38 -0700643 set_perf_mode(false);
Tao Bao29ee69b2017-05-01 12:23:17 -0700644 return INSTALL_CORRUPT;
645 }
646
647 // Additionally verify the compatibility of the package.
648 if (!verify_package_compatibility(zip)) {
649 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700650 CloseArchive(zip);
651 return INSTALL_CORRUPT;
652 }
653
654 // Verify and install the contents of the package.
655 ui->Print("Installing update...\n");
656 if (retry_count > 0) {
657 ui->Print("Retry attempt: %d\n", retry_count);
658 }
659 ui->SetEnableReboot(false);
660 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
661 ui->SetEnableReboot(true);
662 ui->Print("\n");
663
Tao Bao29ee69b2017-05-01 12:23:17 -0700664 CloseArchive(zip);
Steve Kondikb910bb32014-04-03 22:50:38 -0700665 set_perf_mode(false);
Tao Bao29ee69b2017-05-01 12:23:17 -0700666 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800667}
Doug Zongker469243e2011-04-12 09:28:10 -0700668
Tao Bao29ee69b2017-05-01 12:23:17 -0700669int install_package(const std::string& path, bool* wipe_cache, const std::string& install_file,
Tom Marshalle2b6a972018-06-21 00:57:24 +0200670 bool needs_mount, int retry_count, bool verify) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700671 CHECK(!path.empty());
672 CHECK(!install_file.empty());
673 CHECK(wipe_cache != nullptr);
674
Tao Baof8119fb2017-04-18 21:35:12 -0700675 modified_flash = true;
676 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700677
Tao Baof8119fb2017-04-18 21:35:12 -0700678 int start_temperature = GetMaxValueFromThermalZone();
679 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700680
Tao Baof8119fb2017-04-18 21:35:12 -0700681 int result;
682 std::vector<std::string> log_buffer;
683 if (setup_install_mounts() != 0) {
684 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
685 result = INSTALL_ERROR;
686 } else {
Tom Marshalle2b6a972018-06-21 00:57:24 +0200687 result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count, verify,
Tao Baof8119fb2017-04-18 21:35:12 -0700688 &max_temperature);
689 }
690
691 // Measure the time spent to apply OTA update in seconds.
692 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
693 int time_total = static_cast<int>(duration.count());
694
Tao Bao3e18f2b2017-09-29 17:11:13 -0700695 bool has_cache = volume_for_mount_point("/cache") != nullptr;
Tao Baof8119fb2017-04-18 21:35:12 -0700696 // Skip logging the uncrypt_status on devices without /cache.
697 if (has_cache) {
698 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
699 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
700 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700701 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700702 std::string uncrypt_status;
703 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
704 PLOG(WARNING) << "failed to read uncrypt status";
705 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
706 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700707 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700708 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700709 }
Doug Zongker469243e2011-04-12 09:28:10 -0700710 }
Tao Baof8119fb2017-04-18 21:35:12 -0700711 }
Tao Baobadaac42016-09-26 11:39:14 -0700712
Tao Baof8119fb2017-04-18 21:35:12 -0700713 // The first two lines need to be the package name and install result.
714 std::vector<std::string> log_header = {
715 path,
716 result == INSTALL_SUCCESS ? "1" : "0",
717 "time_total: " + std::to_string(time_total),
718 "retry: " + std::to_string(retry_count),
719 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700720
Tao Baof8119fb2017-04-18 21:35:12 -0700721 int end_temperature = GetMaxValueFromThermalZone();
722 max_temperature = std::max(end_temperature, max_temperature);
723 if (start_temperature > 0) {
724 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
725 }
726 if (end_temperature > 0) {
727 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
728 }
729 if (max_temperature > 0) {
730 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
731 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700732
Tao Baof8119fb2017-04-18 21:35:12 -0700733 std::string log_content =
734 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
735 if (!android::base::WriteStringToFile(log_content, install_file)) {
736 PLOG(ERROR) << "failed to write " << install_file;
737 }
Tao Baobadaac42016-09-26 11:39:14 -0700738
Tao Baof8119fb2017-04-18 21:35:12 -0700739 // Write a copy into last_log.
740 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700741
Tao Baof8119fb2017-04-18 21:35:12 -0700742 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700743}
Yabin Cui6faf0262016-06-09 14:09:39 -0700744
745bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700746 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700747 std::vector<Certificate> loadedKeys;
748 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
749 LOG(ERROR) << "Failed to load keys";
750 return false;
751 }
752 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700753
Tao Bao5e535012017-03-16 17:37:38 -0700754 // Verify package.
755 ui->Print("Verifying update package...\n");
756 auto t0 = std::chrono::system_clock::now();
Tom Marshall5b4a9d82018-12-17 15:57:44 -0800757 int err;
758 // Because we mmap() the update file which is backed by FUSE, we get
759 // SIGBUS when the host aborts the transfer. We handle this by using
760 // setjmp/longjmp.
761 signal(SIGBUS, sig_bus);
762 if (setjmp(jb) == 0) {
763 err = verify_file(package_data, package_size, loadedKeys,
764 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
765 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
766 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
767 } else {
768 err = VERIFY_FAILURE;
769 }
770 signal(SIGBUS, SIG_DFL);
771
Tao Bao5e535012017-03-16 17:37:38 -0700772 if (err != VERIFY_SUCCESS) {
773 LOG(ERROR) << "Signature verification failed";
774 LOG(ERROR) << "error: " << kZipVerificationFailure;
775 return false;
776 }
777 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700778}
Steve Kondikb910bb32014-04-03 22:50:38 -0700779
780void set_perf_mode(bool enable) {
781 property_set("recovery.perf.mode", enable ? "1" : "0");
782}