blob: 42d2641579edd1d2835314f2b423ff43ff1631dd [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 Baocf60a442018-06-18 14:56:20 -070048#include <android-base/unique_fd.h>
Tao Bao919d2c92017-04-10 16:55:57 -070049#include <vintf/VintfObjectRecovery.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070050#include <ziparchive/zip_archive.h>
Tianjie Xu16255832016-04-30 11:49:59 -070051
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080052#include "common.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070053#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070054#include "otautil/paths.h"
Tao Bao17054c02018-05-03 22:41:23 -070055#include "otautil/sysutil.h"
56#include "otautil/thermalutil.h"
Tao Bao00d57572017-05-02 15:48:54 -070057#include "private/install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080058#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070059#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020060#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080061
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070062using namespace std::chrono_literals;
63
Doug Zongker74406302011-10-28 15:13:10 -070064// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080065static constexpr int VERIFICATION_PROGRESS_TIME = 60;
66static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070067
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070068static std::condition_variable finish_log_temperature;
69
Tianjie Xub0ddae52016-06-08 14:30:04 -070070// This function parses and returns the build.version.incremental
Daniel Micaya29d8d62017-06-23 08:33:24 -040071static std::string parse_build_number(const std::string& str) {
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070072 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070073 if (pos != std::string::npos) {
Daniel Micaya29d8d62017-06-23 08:33:24 -040074 return android::base::Trim(str.substr(pos+1));
Tianjie Xub0ddae52016-06-08 14:30:04 -070075 }
76
Tianjie Xuc21edd42016-08-05 18:00:04 -070077 LOG(ERROR) << "Failed to parse build number in " << str;
Daniel Micaya29d8d62017-06-23 08:33:24 -040078 return "";
Tianjie Xub0ddae52016-06-08 14:30:04 -070079}
80
Tao Bao8a7afcc2017-04-18 22:05:50 -070081bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
82 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070083
Tao Bao8a7afcc2017-04-18 22:05:50 -070084 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
85 ZipString path(METADATA_PATH);
86 ZipEntry entry;
87 if (FindEntry(zip, path, &entry) != 0) {
88 LOG(ERROR) << "Failed to find " << METADATA_PATH;
89 return false;
90 }
91
92 uint32_t length = entry.uncompressed_length;
93 metadata->resize(length, '\0');
94 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
95 if (err != 0) {
96 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
97 return false;
98 }
99 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700100}
101
102// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tao Bao29ee69b2017-05-01 12:23:17 -0700103static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>* log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700104 std::string metadata;
105 if (!read_metadata_from_package(zip, &metadata)) {
106 return;
107 }
108 // Examples of the pre-build and post-build strings in metadata:
109 // pre-build-incremental=2943039
110 // post-build-incremental=2951741
111 std::vector<std::string> lines = android::base::Split(metadata, "\n");
112 for (const std::string& line : lines) {
113 std::string str = android::base::Trim(line);
114 if (android::base::StartsWith(str, "pre-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400115 std::string source_build = parse_build_number(str);
116 if (!source_build.empty()) {
117 log_buffer->push_back("source_build: " + source_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700118 }
119 } else if (android::base::StartsWith(str, "post-build-incremental")) {
Daniel Micaya29d8d62017-06-23 08:33:24 -0400120 std::string target_build = parse_build_number(str);
121 if (!target_build.empty()) {
122 log_buffer->push_back("target_build: " + target_build);
Tao Bao8a7afcc2017-04-18 22:05:50 -0700123 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700124 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700125 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700126}
127
Tao Baocf60a442018-06-18 14:56:20 -0700128// Parses the metadata of the OTA package in |zip| and checks whether we are allowed to accept this
129// A/B package. Downgrading is not allowed unless explicitly enabled in the package and only for
130// 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 // Check for downgrade version.
192 int64_t build_timestamp =
193 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
194 int64_t pkg_post_timestamp = 0;
195 // We allow to full update to the same version we are running, in case there
196 // is a problem with the current copy of that version.
197 if (metadata["post-timestamp"].empty() ||
198 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
199 pkg_post_timestamp < build_timestamp) {
200 if (metadata["ota-downgrade"] != "yes") {
201 LOG(ERROR) << "Update package is older than the current build, expected a build "
202 "newer than timestamp "
203 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
204 << " and downgrade not allowed.";
205 return INSTALL_ERROR;
206 }
207 if (pkg_pre_build_fingerprint.empty()) {
208 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
209 return INSTALL_ERROR;
210 }
211 }
212
213 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700214}
215
Tao Baocf60a442018-06-18 14:56:20 -0700216int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd,
Tao Bao00d57572017-05-02 15:48:54 -0700217 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700218 CHECK(cmd != nullptr);
219 int ret = check_newer_ab_build(zip);
220 if (ret != 0) {
221 return ret;
222 }
Alex Deymo4344d632016-08-03 21:03:53 -0700223
Tao Baobc4b1fe2017-04-17 16:46:05 -0700224 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
225 // in the zip file.
226 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
227 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
228 ZipEntry properties_entry;
229 if (FindEntry(zip, property_name, &properties_entry) != 0) {
230 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
231 return INSTALL_CORRUPT;
232 }
233 uint32_t properties_entry_length = properties_entry.uncompressed_length;
234 std::vector<uint8_t> payload_properties(properties_entry_length);
235 int32_t err =
236 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
237 if (err != 0) {
238 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
239 return INSTALL_CORRUPT;
240 }
Alex Deymo4344d632016-08-03 21:03:53 -0700241
Tao Baobc4b1fe2017-04-17 16:46:05 -0700242 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
243 ZipString payload_name(AB_OTA_PAYLOAD);
244 ZipEntry payload_entry;
245 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
246 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
247 return INSTALL_CORRUPT;
248 }
249 long payload_offset = payload_entry.offset;
250 *cmd = {
Tao Bao2cc9bbb2018-08-14 12:34:46 -0700251 "/system/bin/update_engine_sideload",
Tao Bao00d57572017-05-02 15:48:54 -0700252 "--payload=file://" + package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700253 android::base::StringPrintf("--offset=%ld", payload_offset),
254 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
255 android::base::StringPrintf("--status_fd=%d", status_fd),
256 };
257 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700258}
259
Tao Baocf60a442018-06-18 14:56:20 -0700260int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count,
261 int status_fd, std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700262 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700263
Tao Baocf60a442018-06-18 14:56:20 -0700264 // In non-A/B updates we extract the update binary from the package.
Tao Baobc4b1fe2017-04-17 16:46:05 -0700265 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
266 ZipString binary_name(UPDATE_BINARY_NAME);
267 ZipEntry binary_entry;
268 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
269 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
270 return INSTALL_CORRUPT;
271 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700272
Tao Baocf60a442018-06-18 14:56:20 -0700273 const std::string binary_path = Paths::Get().temporary_update_binary();
Tao Bao00d57572017-05-02 15:48:54 -0700274 unlink(binary_path.c_str());
Tao Baocf60a442018-06-18 14:56:20 -0700275 android::base::unique_fd fd(
276 open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755));
Tao Baobc4b1fe2017-04-17 16:46:05 -0700277 if (fd == -1) {
Tao Bao00d57572017-05-02 15:48:54 -0700278 PLOG(ERROR) << "Failed to create " << binary_path;
Tao Baobc4b1fe2017-04-17 16:46:05 -0700279 return INSTALL_ERROR;
280 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700281
Tao Baobc4b1fe2017-04-17 16:46:05 -0700282 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
Tao Baobc4b1fe2017-04-17 16:46:05 -0700283 if (error != 0) {
284 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
285 return INSTALL_ERROR;
286 }
287
288 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700289 binary_path,
Tao Baobd0ddcd2017-05-04 13:03:18 -0700290 std::to_string(kRecoveryApiVersion),
Tao Baobc4b1fe2017-04-17 16:46:05 -0700291 std::to_string(status_fd),
Tao Bao00d57572017-05-02 15:48:54 -0700292 package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700293 };
294 if (retry_count > 0) {
295 cmd->push_back("retry");
296 }
297 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700298}
Alex Deymo4344d632016-08-03 21:03:53 -0700299
Tianjie Xu37957102017-06-07 17:59:55 -0700300static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700301 CHECK(max_temperature != nullptr);
302 std::mutex mtx;
303 std::unique_lock<std::mutex> lck(mtx);
Tianjie Xu37957102017-06-07 17:59:55 -0700304 while (!logger_finished.load() &&
305 finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700306 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
307 }
308}
309
Alex Deymo4344d632016-08-03 21:03:53 -0700310// If the package contains an update binary, extract it and run it.
Tao Bao00d57572017-05-02 15:48:54 -0700311static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
Tao Bao29ee69b2017-05-01 12:23:17 -0700312 std::vector<std::string>* log_buffer, int retry_count,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700313 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800314 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700315
Tao Bao20c581e2016-12-28 20:55:51 -0800316 int pipefd[2];
317 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700318
Tao Baocf60a442018-06-18 14:56:20 -0700319 bool is_ab = android::base::GetBoolProperty("ro.build.ab_update", false);
Tao Bao20c581e2016-12-28 20:55:51 -0800320 std::vector<std::string> args;
Tao Baocf60a442018-06-18 14:56:20 -0700321 int ret = is_ab ? SetUpAbUpdateCommands(package, zip, pipefd[1], &args)
322 : SetUpNonAbUpdateCommands(package, zip, retry_count, pipefd[1], &args);
Tao Bao20c581e2016-12-28 20:55:51 -0800323 if (ret) {
324 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700325 close(pipefd[1]);
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700326 log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800327 return ret;
328 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700329
Tao Bao20c581e2016-12-28 20:55:51 -0800330 // When executing the update binary contained in the package, the
331 // arguments passed are:
332 //
333 // - the version number for this interface
334 //
335 // - an FD to which the program can write in order to update the
336 // progress bar. The program can write single-line commands:
337 //
338 // progress <frac> <secs>
339 // fill up the next <frac> part of of the progress bar
340 // over <secs> seconds. If <secs> is zero, use
341 // set_progress commands to manually control the
342 // progress of this segment of the bar.
343 //
344 // set_progress <frac>
345 // <frac> should be between 0.0 and 1.0; sets the
346 // progress bar within the segment defined by the most
347 // recent progress command.
348 //
349 // ui_print <string>
350 // display <string> on the screen.
351 //
352 // wipe_cache
353 // a wipe of cache will be performed following a successful
354 // installation.
355 //
356 // clear_display
357 // turn off the text display.
358 //
359 // enable_reboot
360 // packages can explicitly request that they want the user
361 // to be able to reboot during installation (useful for
362 // debugging packages that don't exit).
363 //
364 // retry_update
365 // updater encounters some issue during the update. It requests
366 // a reboot to retry the same package automatically.
367 //
368 // log <string>
369 // updater requests logging the string (e.g. cause of the
370 // failure).
371 //
372 // - the name of the package zip file.
373 //
374 // - an optional argument "retry" if this update is a retry of a failed
375 // update attempt.
376 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700377
Tao Bao20c581e2016-12-28 20:55:51 -0800378 // Convert the vector to a NULL-terminated char* array suitable for execv.
379 const char* chr_args[args.size() + 1];
380 chr_args[args.size()] = nullptr;
381 for (size_t i = 0; i < args.size(); i++) {
382 chr_args[i] = args[i].c_str();
383 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700384
Tao Bao20c581e2016-12-28 20:55:51 -0800385 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700386
Tao Bao20c581e2016-12-28 20:55:51 -0800387 if (pid == -1) {
388 close(pipefd[0]);
389 close(pipefd[1]);
390 PLOG(ERROR) << "Failed to fork update binary";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700391 log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
Tao Bao20c581e2016-12-28 20:55:51 -0800392 return INSTALL_ERROR;
393 }
394
395 if (pid == 0) {
396 umask(022);
397 close(pipefd[0]);
398 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800399 // Bug: 34769056
400 // We shouldn't use LOG/PLOG in the forked process, since they may cause
401 // the child process to hang. This deadlock results from an improperly
402 // copied mutex in the ui functions.
403 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800404 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800405 }
406 close(pipefd[1]);
407
Tianjie Xu37957102017-06-07 17:59:55 -0700408 std::atomic<bool> logger_finished(false);
409 std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700410
Tao Bao20c581e2016-12-28 20:55:51 -0800411 *wipe_cache = false;
412 bool retry_update = false;
413
414 char buffer[1024];
415 FILE* from_child = fdopen(pipefd[0], "r");
416 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
417 std::string line(buffer);
418 size_t space = line.find_first_of(" \n");
419 std::string command(line.substr(0, space));
420 if (command.empty()) continue;
421
422 // Get rid of the leading and trailing space and/or newline.
423 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
424
425 if (command == "progress") {
426 std::vector<std::string> tokens = android::base::Split(args, " ");
427 double fraction;
428 int seconds;
429 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
430 android::base::ParseInt(tokens[1], &seconds)) {
431 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
432 } else {
433 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
434 }
435 } else if (command == "set_progress") {
436 std::vector<std::string> tokens = android::base::Split(args, " ");
437 double fraction;
438 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
439 ui->SetProgress(fraction);
440 } else {
441 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
442 }
443 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800444 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800445 fflush(stdout);
446 } else if (command == "wipe_cache") {
447 *wipe_cache = true;
448 } else if (command == "clear_display") {
449 ui->SetBackground(RecoveryUI::NONE);
450 } else if (command == "enable_reboot") {
451 // packages can explicitly request that they want the user
452 // to be able to reboot during installation (useful for
453 // debugging packages that don't exit).
454 ui->SetEnableReboot(true);
455 } else if (command == "retry_update") {
456 retry_update = true;
457 } else if (command == "log") {
458 if (!args.empty()) {
459 // Save the logging request from updater and write to last_install later.
Tao Bao29ee69b2017-05-01 12:23:17 -0700460 log_buffer->push_back(args);
Tao Bao20c581e2016-12-28 20:55:51 -0800461 } else {
462 LOG(ERROR) << "invalid \"log\" parameters: " << line;
463 }
464 } else {
465 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700466 }
Tao Bao20c581e2016-12-28 20:55:51 -0800467 }
468 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700469
Tao Bao20c581e2016-12-28 20:55:51 -0800470 int status;
471 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700472
Tianjie Xu37957102017-06-07 17:59:55 -0700473 logger_finished.store(true);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700474 finish_log_temperature.notify_one();
475 temperature_logger.join();
476
Tao Bao20c581e2016-12-28 20:55:51 -0800477 if (retry_update) {
478 return INSTALL_RETRY;
479 }
480 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tao Bao00d57572017-05-02 15:48:54 -0700481 LOG(ERROR) << "Error in " << package << " (Status " << WEXITSTATUS(status) << ")";
Tao Bao20c581e2016-12-28 20:55:51 -0800482 return INSTALL_ERROR;
483 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700484
Tao Bao20c581e2016-12-28 20:55:51 -0800485 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700486}
487
Tao Bao1d866052017-04-10 16:55:57 -0700488// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
489// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
490// package.
491bool verify_package_compatibility(ZipArchiveHandle package_zip) {
492 LOG(INFO) << "Verifying package compatibility...";
493
494 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
495 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
496 ZipEntry compatibility_entry;
497 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
498 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
499 return true;
500 }
501
502 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
503 int32_t ret;
504 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
505 reinterpret_cast<uint8_t*>(&zip_content[0]),
506 compatibility_entry.uncompressed_length)) != 0) {
507 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
508 return false;
509 }
510
511 ZipArchiveHandle zip_handle;
512 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
513 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
514 if (ret != 0) {
515 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
516 return false;
517 }
518
519 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
520 void* cookie;
521 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
522 if (ret != 0) {
523 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
524 CloseArchive(zip_handle);
525 return false;
526 }
527 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
528
529 std::vector<std::string> compatibility_info;
530 ZipEntry info_entry;
531 ZipString info_name;
532 while (Next(cookie, &info_entry, &info_name) == 0) {
533 std::string content(info_entry.uncompressed_length, '\0');
534 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
535 info_entry.uncompressed_length);
536 if (ret != 0) {
537 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
538 CloseArchive(zip_handle);
539 return false;
540 }
541 compatibility_info.emplace_back(std::move(content));
542 }
Tao Bao1d866052017-04-10 16:55:57 -0700543 CloseArchive(zip_handle);
544
Tao Bao919d2c92017-04-10 16:55:57 -0700545 // VintfObjectRecovery::CheckCompatibility returns zero on success.
546 std::string err;
547 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
548 if (result == 0) {
549 return true;
550 }
551
552 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
553 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700554}
555
Tao Bao29ee69b2017-05-01 12:23:17 -0700556static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount,
557 std::vector<std::string>* log_buffer, int retry_count,
558 int* max_temperature) {
559 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
560 ui->Print("Finding update package...\n");
561 // Give verification half the progress bar...
562 ui->SetProgressType(RecoveryUI::DETERMINATE);
563 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
564 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800565
Tao Bao29ee69b2017-05-01 12:23:17 -0700566 // Map the update package into memory.
567 ui->Print("Opening update package...\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800568
Tao Bao29ee69b2017-05-01 12:23:17 -0700569 if (needs_mount) {
570 if (path[0] == '@') {
571 ensure_path_mounted(path.substr(1).c_str());
572 } else {
573 ensure_path_mounted(path.c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800574 }
Tao Bao29ee69b2017-05-01 12:23:17 -0700575 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800576
Tao Bao29ee69b2017-05-01 12:23:17 -0700577 MemMapping map;
Tao Baob656a152017-04-18 23:54:29 -0700578 if (!map.MapFile(path)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700579 LOG(ERROR) << "failed to map file";
Tianjie Xu3fec8c62017-08-23 00:18:07 -0700580 log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700581 return INSTALL_CORRUPT;
582 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800583
Tao Bao29ee69b2017-05-01 12:23:17 -0700584 // Verify package.
585 if (!verify_package(map.addr, map.length)) {
586 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700587 return INSTALL_CORRUPT;
588 }
Doug Zongker60151a22009-08-12 18:30:03 -0700589
Tao Bao29ee69b2017-05-01 12:23:17 -0700590 // Try to open the package.
591 ZipArchiveHandle zip;
592 int err = OpenArchiveFromMemory(map.addr, map.length, path.c_str(), &zip);
593 if (err != 0) {
594 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
595 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800596
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700597 CloseArchive(zip);
Tao Bao29ee69b2017-05-01 12:23:17 -0700598 return INSTALL_CORRUPT;
599 }
600
601 // Additionally verify the compatibility of the package.
602 if (!verify_package_compatibility(zip)) {
603 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700604 CloseArchive(zip);
605 return INSTALL_CORRUPT;
606 }
607
608 // Verify and install the contents of the package.
609 ui->Print("Installing update...\n");
610 if (retry_count > 0) {
611 ui->Print("Retry attempt: %d\n", retry_count);
612 }
613 ui->SetEnableReboot(false);
614 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
615 ui->SetEnableReboot(true);
616 ui->Print("\n");
617
Tao Bao29ee69b2017-05-01 12:23:17 -0700618 CloseArchive(zip);
619 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800620}
Doug Zongker469243e2011-04-12 09:28:10 -0700621
Tao Bao641fa972018-04-25 18:59:40 -0700622int install_package(const std::string& path, bool* wipe_cache, bool needs_mount, int retry_count) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700623 CHECK(!path.empty());
Tao Bao29ee69b2017-05-01 12:23:17 -0700624 CHECK(wipe_cache != nullptr);
625
Tao Baof8119fb2017-04-18 21:35:12 -0700626 modified_flash = true;
627 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700628
Tao Baof8119fb2017-04-18 21:35:12 -0700629 int start_temperature = GetMaxValueFromThermalZone();
630 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700631
Tao Baof8119fb2017-04-18 21:35:12 -0700632 int result;
633 std::vector<std::string> log_buffer;
634 if (setup_install_mounts() != 0) {
635 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
636 result = INSTALL_ERROR;
637 } else {
Tao Bao29ee69b2017-05-01 12:23:17 -0700638 result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count,
Tao Baof8119fb2017-04-18 21:35:12 -0700639 &max_temperature);
640 }
641
642 // Measure the time spent to apply OTA update in seconds.
643 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
644 int time_total = static_cast<int>(duration.count());
645
Tao Bao3e18f2b2017-09-29 17:11:13 -0700646 bool has_cache = volume_for_mount_point("/cache") != nullptr;
Tao Baof8119fb2017-04-18 21:35:12 -0700647 // Skip logging the uncrypt_status on devices without /cache.
648 if (has_cache) {
649 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
650 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
651 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700652 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700653 std::string uncrypt_status;
654 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
655 PLOG(WARNING) << "failed to read uncrypt status";
656 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
657 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700658 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700659 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700660 }
Doug Zongker469243e2011-04-12 09:28:10 -0700661 }
Tao Baof8119fb2017-04-18 21:35:12 -0700662 }
Tao Baobadaac42016-09-26 11:39:14 -0700663
Tao Baof8119fb2017-04-18 21:35:12 -0700664 // The first two lines need to be the package name and install result.
665 std::vector<std::string> log_header = {
666 path,
667 result == INSTALL_SUCCESS ? "1" : "0",
668 "time_total: " + std::to_string(time_total),
669 "retry: " + std::to_string(retry_count),
670 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700671
Tao Baof8119fb2017-04-18 21:35:12 -0700672 int end_temperature = GetMaxValueFromThermalZone();
673 max_temperature = std::max(end_temperature, max_temperature);
674 if (start_temperature > 0) {
675 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
676 }
677 if (end_temperature > 0) {
678 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
679 }
680 if (max_temperature > 0) {
681 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
682 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700683
Tao Baof8119fb2017-04-18 21:35:12 -0700684 std::string log_content =
685 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
Tao Bao641fa972018-04-25 18:59:40 -0700686 const std::string& install_file = Paths::Get().temporary_install_file();
Tao Baof8119fb2017-04-18 21:35:12 -0700687 if (!android::base::WriteStringToFile(log_content, install_file)) {
688 PLOG(ERROR) << "failed to write " << install_file;
689 }
Tao Baobadaac42016-09-26 11:39:14 -0700690
Tao Baof8119fb2017-04-18 21:35:12 -0700691 // Write a copy into last_log.
692 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700693
Tao Baof8119fb2017-04-18 21:35:12 -0700694 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700695}
Yabin Cui6faf0262016-06-09 14:09:39 -0700696
697bool verify_package(const unsigned char* package_data, size_t package_size) {
Tianjie Xue1d02fb2018-10-19 15:52:17 -0700698 static constexpr const char* CERTIFICATE_ZIP_FILE = "/system/etc/security/otacerts.zip";
699 std::vector<Certificate> loaded_keys = LoadKeysFromZipfile(CERTIFICATE_ZIP_FILE);
700 if (loaded_keys.empty()) {
Tao Bao5e535012017-03-16 17:37:38 -0700701 LOG(ERROR) << "Failed to load keys";
702 return false;
703 }
Tianjie Xue1d02fb2018-10-19 15:52:17 -0700704 LOG(INFO) << loaded_keys.size() << " key(s) loaded from " << CERTIFICATE_ZIP_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700705
Tao Bao5e535012017-03-16 17:37:38 -0700706 // Verify package.
707 ui->Print("Verifying update package...\n");
708 auto t0 = std::chrono::system_clock::now();
Tianjie Xue1d02fb2018-10-19 15:52:17 -0700709 int err = verify_file(package_data, package_size, loaded_keys,
Tao Bao5e535012017-03-16 17:37:38 -0700710 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
711 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
712 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
713 if (err != VERIFY_SUCCESS) {
714 LOG(ERROR) << "Signature verification failed";
715 LOG(ERROR) << "error: " << kZipVerificationFailure;
716 return false;
717 }
718 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700719}