blob: e5a59b8323c4da4b2915f72027a26cbb7e88148c [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>
Elliott Hughes8febafa2016-04-13 16:39:56 -070030#include <chrono>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070031#include <condition_variable>
Tao Bao5e535012017-03-16 17:37:38 -070032#include <functional>
Alex Deymo4344d632016-08-03 21:03:53 -070033#include <limits>
34#include <map>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070035#include <mutex>
Tianjie Xudd874b12016-05-13 12:13:15 -070036#include <string>
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070037#include <thread>
Tao Bao71e3e092016-02-02 14:02:27 -080038#include <vector>
39
Tianjie Xue16e7992016-09-09 10:55:44 -070040#include <android-base/file.h>
41#include <android-base/logging.h>
Tao Bao20c581e2016-12-28 20:55:51 -080042#include <android-base/parsedouble.h>
Tianjie Xub0ddae52016-06-08 14:30:04 -070043#include <android-base/parseint.h>
Tao Baoefc35592017-01-08 22:45:47 -080044#include <android-base/properties.h>
Tianjie Xu16255832016-04-30 11:49:59 -070045#include <android-base/stringprintf.h>
46#include <android-base/strings.h>
Tao Baoda320ac2017-04-10 16:55:57 -070047#include <vintf/VintfObjectRecovery.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070048#include <ziparchive/zip_archive.h>
Tianjie Xu16255832016-04-30 11:49:59 -070049
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080050#include "common.h"
Tianjie Xu16255832016-04-30 11:49:59 -070051#include "error_code.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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080054#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070055#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020056#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080057
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070058using namespace std::chrono_literals;
59
Doug Zongker74406302011-10-28 15:13:10 -070060// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080061static constexpr int VERIFICATION_PROGRESS_TIME = 60;
62static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070063
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070064static std::condition_variable finish_log_temperature;
65
Tianjie Xub0ddae52016-06-08 14:30:04 -070066// This function parses and returns the build.version.incremental
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070067static int parse_build_number(const std::string& str) {
68 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070069 if (pos != std::string::npos) {
70 std::string num_string = android::base::Trim(str.substr(pos+1));
71 int build_number;
72 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
73 return build_number;
74 }
75 }
76
Tianjie Xuc21edd42016-08-05 18:00:04 -070077 LOG(ERROR) << "Failed to parse build number in " << str;
Tianjie Xub0ddae52016-06-08 14:30:04 -070078 return -1;
79}
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.
Tianjie Xu8176cf22016-10-18 14:13:07 -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")) {
115 int source_build = parse_build_number(str);
116 if (source_build != -1) {
117 log_buffer.push_back(android::base::StringPrintf("source_build: %d", source_build));
118 }
119 } else if (android::base::StartsWith(str, "post-build-incremental")) {
120 int target_build = parse_build_number(str);
121 if (target_build != -1) {
122 log_buffer.push_back(android::base::StringPrintf("target_build: %d", target_build));
123 }
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 Baobc4b1fe2017-04-17 16:46:05 -0700128// Extract the update binary from the open zip archive |zip| located at |path| and store into |cmd|
129// the command line that should be called. The |status_fd| is the file descriptor the child process
130// should use to report back the progress of the update.
131int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
132 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700133
Alex Deymo4344d632016-08-03 21:03:53 -0700134#ifdef AB_OTA_UPDATER
135
136// Parses the metadata of the OTA package in |zip| and checks whether we are
137// allowed to accept this A/B package. Downgrading is not allowed unless
138// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800139static int check_newer_ab_build(ZipArchiveHandle zip) {
140 std::string metadata_str;
141 if (!read_metadata_from_package(zip, &metadata_str)) {
142 return INSTALL_CORRUPT;
143 }
144 std::map<std::string, std::string> metadata;
145 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
146 size_t eq = line.find('=');
147 if (eq != std::string::npos) {
148 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700149 }
Tao Baoefc35592017-01-08 22:45:47 -0800150 }
Alex Deymo4344d632016-08-03 21:03:53 -0700151
Tao Baoefc35592017-01-08 22:45:47 -0800152 std::string value = android::base::GetProperty("ro.product.device", "");
153 const std::string& pkg_device = metadata["pre-device"];
154 if (pkg_device != value || pkg_device.empty()) {
155 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
156 return INSTALL_ERROR;
157 }
Alex Deymo4344d632016-08-03 21:03:53 -0700158
Tao Baoefc35592017-01-08 22:45:47 -0800159 // We allow the package to not have any serialno, but if it has a non-empty
160 // value it should match.
161 value = android::base::GetProperty("ro.serialno", "");
162 const std::string& pkg_serial_no = metadata["serialno"];
163 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
164 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
165 return INSTALL_ERROR;
166 }
Alex Deymo4344d632016-08-03 21:03:53 -0700167
Tao Baoefc35592017-01-08 22:45:47 -0800168 if (metadata["ota-type"] != "AB") {
169 LOG(ERROR) << "Package is not A/B";
170 return INSTALL_ERROR;
171 }
Alex Deymo4344d632016-08-03 21:03:53 -0700172
Tao Baoefc35592017-01-08 22:45:47 -0800173 // Incremental updates should match the current build.
174 value = android::base::GetProperty("ro.build.version.incremental", "");
175 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
176 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
177 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
178 return INSTALL_ERROR;
179 }
Alex Deymo4344d632016-08-03 21:03:53 -0700180
Tao Baoefc35592017-01-08 22:45:47 -0800181 value = android::base::GetProperty("ro.build.fingerprint", "");
182 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
183 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
184 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
185 << value;
186 return INSTALL_ERROR;
187 }
Alex Deymo4344d632016-08-03 21:03:53 -0700188
Tao Baoefc35592017-01-08 22:45:47 -0800189 // Check for downgrade version.
190 int64_t build_timestamp =
191 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
192 int64_t pkg_post_timestamp = 0;
193 // We allow to full update to the same version we are running, in case there
194 // is a problem with the current copy of that version.
195 if (metadata["post-timestamp"].empty() ||
196 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
197 pkg_post_timestamp < build_timestamp) {
198 if (metadata["ota-downgrade"] != "yes") {
199 LOG(ERROR) << "Update package is older than the current build, expected a build "
200 "newer than timestamp "
201 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
202 << " and downgrade not allowed.";
203 return INSTALL_ERROR;
204 }
205 if (pkg_pre_build_fingerprint.empty()) {
206 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
207 return INSTALL_ERROR;
208 }
209 }
210
211 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700212}
213
Tao Baobc4b1fe2017-04-17 16:46:05 -0700214int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
215 int status_fd, std::vector<std::string>* cmd) {
216 CHECK(cmd != nullptr);
217 int ret = check_newer_ab_build(zip);
218 if (ret != 0) {
219 return ret;
220 }
Alex Deymo4344d632016-08-03 21:03:53 -0700221
Tao Baobc4b1fe2017-04-17 16:46:05 -0700222 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
223 // in the zip file.
224 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
225 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
226 ZipEntry properties_entry;
227 if (FindEntry(zip, property_name, &properties_entry) != 0) {
228 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
229 return INSTALL_CORRUPT;
230 }
231 uint32_t properties_entry_length = properties_entry.uncompressed_length;
232 std::vector<uint8_t> payload_properties(properties_entry_length);
233 int32_t err =
234 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
235 if (err != 0) {
236 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
237 return INSTALL_CORRUPT;
238 }
Alex Deymo4344d632016-08-03 21:03:53 -0700239
Tao Baobc4b1fe2017-04-17 16:46:05 -0700240 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
241 ZipString payload_name(AB_OTA_PAYLOAD);
242 ZipEntry payload_entry;
243 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
244 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
245 return INSTALL_CORRUPT;
246 }
247 long payload_offset = payload_entry.offset;
248 *cmd = {
249 "/sbin/update_engine_sideload",
250 "--payload=file://" + path,
251 android::base::StringPrintf("--offset=%ld", payload_offset),
252 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
253 android::base::StringPrintf("--status_fd=%d", status_fd),
254 };
255 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700256}
257
258#else // !AB_OTA_UPDATER
259
Tao Baobc4b1fe2017-04-17 16:46:05 -0700260int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
261 int status_fd, std::vector<std::string>* cmd) {
262 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700263
Tao Baobc4b1fe2017-04-17 16:46:05 -0700264 // On traditional updates we extract the update binary from the package.
265 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 Baobc4b1fe2017-04-17 16:46:05 -0700273 const char* binary = "/tmp/update_binary";
274 unlink(binary);
275 int fd = creat(binary, 0755);
276 if (fd == -1) {
277 PLOG(ERROR) << "Failed to create " << binary;
278 return INSTALL_ERROR;
279 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700280
Tao Baobc4b1fe2017-04-17 16:46:05 -0700281 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
282 close(fd);
283 if (error != 0) {
284 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
285 return INSTALL_ERROR;
286 }
287
288 *cmd = {
289 binary,
290 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
291 std::to_string(status_fd),
292 path,
293 };
294 if (retry_count > 0) {
295 cmd->push_back("retry");
296 }
297 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700298}
299#endif // !AB_OTA_UPDATER
300
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700301static void log_max_temperature(int* max_temperature) {
302 CHECK(max_temperature != nullptr);
303 std::mutex mtx;
304 std::unique_lock<std::mutex> lck(mtx);
305 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
306 *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 Bao20c581e2016-12-28 20:55:51 -0800311static int try_update_binary(const char* path, ZipArchiveHandle zip, bool* wipe_cache,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700312 std::vector<std::string>& log_buffer, int retry_count,
313 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 Bao20c581e2016-12-28 20:55:51 -0800319 std::vector<std::string> args;
320 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
321 if (ret) {
322 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700323 close(pipefd[1]);
Tao Bao20c581e2016-12-28 20:55:51 -0800324 return ret;
325 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700326
Tao Bao20c581e2016-12-28 20:55:51 -0800327 // When executing the update binary contained in the package, the
328 // arguments passed are:
329 //
330 // - the version number for this interface
331 //
332 // - an FD to which the program can write in order to update the
333 // progress bar. The program can write single-line commands:
334 //
335 // progress <frac> <secs>
336 // fill up the next <frac> part of of the progress bar
337 // over <secs> seconds. If <secs> is zero, use
338 // set_progress commands to manually control the
339 // progress of this segment of the bar.
340 //
341 // set_progress <frac>
342 // <frac> should be between 0.0 and 1.0; sets the
343 // progress bar within the segment defined by the most
344 // recent progress command.
345 //
346 // ui_print <string>
347 // display <string> on the screen.
348 //
349 // wipe_cache
350 // a wipe of cache will be performed following a successful
351 // installation.
352 //
353 // clear_display
354 // turn off the text display.
355 //
356 // enable_reboot
357 // packages can explicitly request that they want the user
358 // to be able to reboot during installation (useful for
359 // debugging packages that don't exit).
360 //
361 // retry_update
362 // updater encounters some issue during the update. It requests
363 // a reboot to retry the same package automatically.
364 //
365 // log <string>
366 // updater requests logging the string (e.g. cause of the
367 // failure).
368 //
369 // - the name of the package zip file.
370 //
371 // - an optional argument "retry" if this update is a retry of a failed
372 // update attempt.
373 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700374
Tao Bao20c581e2016-12-28 20:55:51 -0800375 // Convert the vector to a NULL-terminated char* array suitable for execv.
376 const char* chr_args[args.size() + 1];
377 chr_args[args.size()] = nullptr;
378 for (size_t i = 0; i < args.size(); i++) {
379 chr_args[i] = args[i].c_str();
380 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700381
Tao Bao20c581e2016-12-28 20:55:51 -0800382 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700383
Tao Bao20c581e2016-12-28 20:55:51 -0800384 if (pid == -1) {
385 close(pipefd[0]);
386 close(pipefd[1]);
387 PLOG(ERROR) << "Failed to fork update binary";
388 return INSTALL_ERROR;
389 }
390
391 if (pid == 0) {
392 umask(022);
393 close(pipefd[0]);
394 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800395 // Bug: 34769056
396 // We shouldn't use LOG/PLOG in the forked process, since they may cause
397 // the child process to hang. This deadlock results from an improperly
398 // copied mutex in the ui functions.
399 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800400 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800401 }
402 close(pipefd[1]);
403
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700404 std::thread temperature_logger(log_max_temperature, max_temperature);
405
Tao Bao20c581e2016-12-28 20:55:51 -0800406 *wipe_cache = false;
407 bool retry_update = false;
408
409 char buffer[1024];
410 FILE* from_child = fdopen(pipefd[0], "r");
411 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
412 std::string line(buffer);
413 size_t space = line.find_first_of(" \n");
414 std::string command(line.substr(0, space));
415 if (command.empty()) continue;
416
417 // Get rid of the leading and trailing space and/or newline.
418 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
419
420 if (command == "progress") {
421 std::vector<std::string> tokens = android::base::Split(args, " ");
422 double fraction;
423 int seconds;
424 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
425 android::base::ParseInt(tokens[1], &seconds)) {
426 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
427 } else {
428 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
429 }
430 } else if (command == "set_progress") {
431 std::vector<std::string> tokens = android::base::Split(args, " ");
432 double fraction;
433 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
434 ui->SetProgress(fraction);
435 } else {
436 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
437 }
438 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800439 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800440 fflush(stdout);
441 } else if (command == "wipe_cache") {
442 *wipe_cache = true;
443 } else if (command == "clear_display") {
444 ui->SetBackground(RecoveryUI::NONE);
445 } else if (command == "enable_reboot") {
446 // packages can explicitly request that they want the user
447 // to be able to reboot during installation (useful for
448 // debugging packages that don't exit).
449 ui->SetEnableReboot(true);
450 } else if (command == "retry_update") {
451 retry_update = true;
452 } else if (command == "log") {
453 if (!args.empty()) {
454 // Save the logging request from updater and write to last_install later.
455 log_buffer.push_back(args);
456 } else {
457 LOG(ERROR) << "invalid \"log\" parameters: " << line;
458 }
459 } else {
460 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700461 }
Tao Bao20c581e2016-12-28 20:55:51 -0800462 }
463 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700464
Tao Bao20c581e2016-12-28 20:55:51 -0800465 int status;
466 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700467
468 finish_log_temperature.notify_one();
469 temperature_logger.join();
470
Tao Bao20c581e2016-12-28 20:55:51 -0800471 if (retry_update) {
472 return INSTALL_RETRY;
473 }
474 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
475 LOG(ERROR) << "Error in " << path << " (Status " << WEXITSTATUS(status) << ")";
476 return INSTALL_ERROR;
477 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700478
Tao Bao20c581e2016-12-28 20:55:51 -0800479 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700480}
481
Tao Bao1d866052017-04-10 16:55:57 -0700482// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
483// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
484// package.
485bool verify_package_compatibility(ZipArchiveHandle package_zip) {
486 LOG(INFO) << "Verifying package compatibility...";
487
488 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
489 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
490 ZipEntry compatibility_entry;
491 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
492 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
493 return true;
494 }
495
496 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
497 int32_t ret;
498 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
499 reinterpret_cast<uint8_t*>(&zip_content[0]),
500 compatibility_entry.uncompressed_length)) != 0) {
501 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
502 return false;
503 }
504
505 ZipArchiveHandle zip_handle;
506 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
507 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
508 if (ret != 0) {
509 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
510 return false;
511 }
512
513 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
514 void* cookie;
515 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
516 if (ret != 0) {
517 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
518 CloseArchive(zip_handle);
519 return false;
520 }
521 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
522
523 std::vector<std::string> compatibility_info;
524 ZipEntry info_entry;
525 ZipString info_name;
526 while (Next(cookie, &info_entry, &info_name) == 0) {
527 std::string content(info_entry.uncompressed_length, '\0');
528 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
529 info_entry.uncompressed_length);
530 if (ret != 0) {
531 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
532 CloseArchive(zip_handle);
533 return false;
534 }
535 compatibility_info.emplace_back(std::move(content));
536 }
Tao Bao1d866052017-04-10 16:55:57 -0700537 CloseArchive(zip_handle);
538
Tao Baoda320ac2017-04-10 16:55:57 -0700539 // VintfObjectRecovery::CheckCompatibility returns zero on success.
540 std::string err;
541 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
542 if (result == 0) {
543 return true;
544 }
545
546 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
547 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700548}
549
Doug Zongker469243e2011-04-12 09:28:10 -0700550static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700551really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700552 std::vector<std::string>& log_buffer, int retry_count, int* max_temperature)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800553{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700554 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700555 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700556 // Give verification half the progress bar...
557 ui->SetProgressType(RecoveryUI::DETERMINATE);
558 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tianjie Xuc21edd42016-08-05 18:00:04 -0700559 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800560
Doug Zongker99916f02014-01-13 14:16:58 -0800561 // Map the update package into memory.
562 ui->Print("Opening update package...\n");
563
Doug Zongker075ad802014-06-26 15:35:51 -0700564 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800565 if (path[0] == '@') {
566 ensure_path_mounted(path+1);
567 } else {
568 ensure_path_mounted(path);
569 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800570 }
571
Doug Zongker99916f02014-01-13 14:16:58 -0800572 MemMapping map;
573 if (sysMapFile(path, &map) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700574 LOG(ERROR) << "failed to map file";
Doug Zongker99916f02014-01-13 14:16:58 -0800575 return INSTALL_CORRUPT;
576 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800577
Elliott Hughes8febafa2016-04-13 16:39:56 -0700578 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700579 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700580 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800581 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700582 return INSTALL_CORRUPT;
583 }
584
Elliott Hughes8febafa2016-04-13 16:39:56 -0700585 // Try to open the package.
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700586 ZipArchiveHandle zip;
Tianjie Xu8176cf22016-10-18 14:13:07 -0700587 int err = OpenArchiveFromMemory(map.addr, map.length, path, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800588 if (err != 0) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700589 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
Tianjie Xu16255832016-04-30 11:49:59 -0700590 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
591
Doug Zongker99916f02014-01-13 14:16:58 -0800592 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700593 CloseArchive(zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800594 return INSTALL_CORRUPT;
595 }
596
Tao Bao1d866052017-04-10 16:55:57 -0700597 // Additionally verify the compatibility of the package.
598 if (!verify_package_compatibility(zip)) {
Tao Bao1d866052017-04-10 16:55:57 -0700599 log_buffer.push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
600 sysReleaseMap(&map);
601 CloseArchive(zip);
602 return INSTALL_CORRUPT;
603 }
604
Elliott Hughes8febafa2016-04-13 16:39:56 -0700605 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700606 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700607 if (retry_count > 0) {
608 ui->Print("Retry attempt: %d\n", retry_count);
609 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700610 ui->SetEnableReboot(false);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700611 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
Doug Zongkerc704e062014-05-23 08:40:35 -0700612 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700613 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800614
615 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700616 CloseArchive(zip);
Doug Zongker99916f02014-01-13 14:16:58 -0800617 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800618}
Doug Zongker469243e2011-04-12 09:28:10 -0700619
Tao Baof8119fb2017-04-18 21:35:12 -0700620int install_package(const char* path, bool* wipe_cache, const char* install_file, bool needs_mount,
621 int retry_count) {
622 modified_flash = true;
623 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700624
Tao Baof8119fb2017-04-18 21:35:12 -0700625 int start_temperature = GetMaxValueFromThermalZone();
626 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700627
Tao Baof8119fb2017-04-18 21:35:12 -0700628 int result;
629 std::vector<std::string> log_buffer;
630 if (setup_install_mounts() != 0) {
631 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
632 result = INSTALL_ERROR;
633 } else {
634 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count,
635 &max_temperature);
636 }
637
638 // Measure the time spent to apply OTA update in seconds.
639 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
640 int time_total = static_cast<int>(duration.count());
641
642 bool has_cache = volume_for_path("/cache") != nullptr;
643 // Skip logging the uncrypt_status on devices without /cache.
644 if (has_cache) {
645 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
646 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
647 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700648 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700649 std::string uncrypt_status;
650 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
651 PLOG(WARNING) << "failed to read uncrypt status";
652 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
653 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700654 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700655 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700656 }
Doug Zongker469243e2011-04-12 09:28:10 -0700657 }
Tao Baof8119fb2017-04-18 21:35:12 -0700658 }
Tao Baobadaac42016-09-26 11:39:14 -0700659
Tao Baof8119fb2017-04-18 21:35:12 -0700660 // The first two lines need to be the package name and install result.
661 std::vector<std::string> log_header = {
662 path,
663 result == INSTALL_SUCCESS ? "1" : "0",
664 "time_total: " + std::to_string(time_total),
665 "retry: " + std::to_string(retry_count),
666 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700667
Tao Baof8119fb2017-04-18 21:35:12 -0700668 int end_temperature = GetMaxValueFromThermalZone();
669 max_temperature = std::max(end_temperature, max_temperature);
670 if (start_temperature > 0) {
671 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
672 }
673 if (end_temperature > 0) {
674 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
675 }
676 if (max_temperature > 0) {
677 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
678 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700679
Tao Baof8119fb2017-04-18 21:35:12 -0700680 std::string log_content =
681 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
682 if (!android::base::WriteStringToFile(log_content, install_file)) {
683 PLOG(ERROR) << "failed to write " << install_file;
684 }
Tao Baobadaac42016-09-26 11:39:14 -0700685
Tao Baof8119fb2017-04-18 21:35:12 -0700686 // Write a copy into last_log.
687 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700688
Tao Baof8119fb2017-04-18 21:35:12 -0700689 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700690}
Yabin Cui6faf0262016-06-09 14:09:39 -0700691
692bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700693 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700694 std::vector<Certificate> loadedKeys;
695 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
696 LOG(ERROR) << "Failed to load keys";
697 return false;
698 }
699 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700700
Tao Bao5e535012017-03-16 17:37:38 -0700701 // Verify package.
702 ui->Print("Verifying update package...\n");
703 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700704 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700705 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
706 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
707 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
708 if (err != VERIFY_SUCCESS) {
709 LOG(ERROR) << "Signature verification failed";
710 LOG(ERROR) << "error: " << kZipVerificationFailure;
711 return false;
712 }
713 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700714}