blob: 4fb8099967b3f1ad5724c22914158bb6642da6ce [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>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070047#include <ziparchive/zip_archive.h>
Tianjie Xu16255832016-04-30 11:49:59 -070048
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080049#include "common.h"
Tianjie Xu16255832016-04-30 11:49:59 -070050#include "error_code.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080051#include "minui/minui.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 Zongkerd1b19b92009-04-01 15:48:46 -070060#define PUBLIC_KEYS_FILE "/res/keys"
Tianjie Xub0ddae52016-06-08 14:30:04 -070061static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
Tianjie Xue16e7992016-09-09 10:55:44 -070062static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080063
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;
67static constexpr float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
68static constexpr float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;
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
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070073static int parse_build_number(const std::string& str) {
74 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070075 if (pos != std::string::npos) {
76 std::string num_string = android::base::Trim(str.substr(pos+1));
77 int build_number;
78 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
79 return build_number;
80 }
81 }
82
Tianjie Xuc21edd42016-08-05 18:00:04 -070083 LOG(ERROR) << "Failed to parse build number in " << str;
Tianjie Xub0ddae52016-06-08 14:30:04 -070084 return -1;
85}
86
Tianjie Xu8176cf22016-10-18 14:13:07 -070087bool read_metadata_from_package(ZipArchiveHandle zip, std::string* meta_data) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070088 ZipString metadata_path(METADATA_PATH);
89 ZipEntry meta_entry;
Tianjie Xu8176cf22016-10-18 14:13:07 -070090 if (meta_data == nullptr) {
91 LOG(ERROR) << "string* meta_data can't be nullptr";
92 return false;
93 }
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070094 if (FindEntry(zip, metadata_path, &meta_entry) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -070095 LOG(ERROR) << "Failed to find " << METADATA_PATH << " in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -070096 return false;
Tianjie Xub0ddae52016-06-08 14:30:04 -070097 }
98
Tianjie Xu8176cf22016-10-18 14:13:07 -070099 meta_data->resize(meta_entry.uncompressed_length, '\0');
100 if (ExtractToMemory(zip, &meta_entry, reinterpret_cast<uint8_t*>(&(*meta_data)[0]),
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700101 meta_entry.uncompressed_length) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700102 LOG(ERROR) << "Failed to read metadata in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -0700103 return false;
104 }
105 return true;
106}
107
108// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tianjie Xu8176cf22016-10-18 14:13:07 -0700109static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>& log_buffer) {
Yabin Cui6faf0262016-06-09 14:09:39 -0700110 std::string meta_data;
111 if (!read_metadata_from_package(zip, &meta_data)) {
Tianjie Xub0ddae52016-06-08 14:30:04 -0700112 return;
113 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700114 // Examples of the pre-build and post-build strings in metadata:
115 // pre-build-incremental=2943039
116 // post-build-incremental=2951741
117 std::vector<std::string> lines = android::base::Split(meta_data, "\n");
118 for (const std::string& line : lines) {
119 std::string str = android::base::Trim(line);
120 if (android::base::StartsWith(str, "pre-build-incremental")){
121 int source_build = parse_build_number(str);
122 if (source_build != -1) {
123 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
124 source_build));
125 }
126 } else if (android::base::StartsWith(str, "post-build-incremental")) {
127 int target_build = parse_build_number(str);
128 if (target_build != -1) {
129 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
130 target_build));
131 }
132 }
133 }
134}
135
Tao Baobc4b1fe2017-04-17 16:46:05 -0700136// Extract the update binary from the open zip archive |zip| located at |path| and store into |cmd|
137// the command line that should be called. The |status_fd| is the file descriptor the child process
138// should use to report back the progress of the update.
139int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
140 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700141
Alex Deymo4344d632016-08-03 21:03:53 -0700142#ifdef AB_OTA_UPDATER
143
144// Parses the metadata of the OTA package in |zip| and checks whether we are
145// allowed to accept this A/B package. Downgrading is not allowed unless
146// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800147static int check_newer_ab_build(ZipArchiveHandle zip) {
148 std::string metadata_str;
149 if (!read_metadata_from_package(zip, &metadata_str)) {
150 return INSTALL_CORRUPT;
151 }
152 std::map<std::string, std::string> metadata;
153 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
154 size_t eq = line.find('=');
155 if (eq != std::string::npos) {
156 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700157 }
Tao Baoefc35592017-01-08 22:45:47 -0800158 }
Alex Deymo4344d632016-08-03 21:03:53 -0700159
Tao Baoefc35592017-01-08 22:45:47 -0800160 std::string value = android::base::GetProperty("ro.product.device", "");
161 const std::string& pkg_device = metadata["pre-device"];
162 if (pkg_device != value || pkg_device.empty()) {
163 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
164 return INSTALL_ERROR;
165 }
Alex Deymo4344d632016-08-03 21:03:53 -0700166
Tao Baoefc35592017-01-08 22:45:47 -0800167 // We allow the package to not have any serialno, but if it has a non-empty
168 // value it should match.
169 value = android::base::GetProperty("ro.serialno", "");
170 const std::string& pkg_serial_no = metadata["serialno"];
171 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
172 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
173 return INSTALL_ERROR;
174 }
Alex Deymo4344d632016-08-03 21:03:53 -0700175
Tao Baoefc35592017-01-08 22:45:47 -0800176 if (metadata["ota-type"] != "AB") {
177 LOG(ERROR) << "Package is not A/B";
178 return INSTALL_ERROR;
179 }
Alex Deymo4344d632016-08-03 21:03:53 -0700180
Tao Baoefc35592017-01-08 22:45:47 -0800181 // Incremental updates should match the current build.
182 value = android::base::GetProperty("ro.build.version.incremental", "");
183 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
184 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
185 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
186 return INSTALL_ERROR;
187 }
Alex Deymo4344d632016-08-03 21:03:53 -0700188
Tao Baoefc35592017-01-08 22:45:47 -0800189 value = android::base::GetProperty("ro.build.fingerprint", "");
190 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
191 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
192 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
193 << value;
194 return INSTALL_ERROR;
195 }
Alex Deymo4344d632016-08-03 21:03:53 -0700196
Tao Baoefc35592017-01-08 22:45:47 -0800197 // Check for downgrade version.
198 int64_t build_timestamp =
199 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
200 int64_t pkg_post_timestamp = 0;
201 // We allow to full update to the same version we are running, in case there
202 // is a problem with the current copy of that version.
203 if (metadata["post-timestamp"].empty() ||
204 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
205 pkg_post_timestamp < build_timestamp) {
206 if (metadata["ota-downgrade"] != "yes") {
207 LOG(ERROR) << "Update package is older than the current build, expected a build "
208 "newer than timestamp "
209 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
210 << " and downgrade not allowed.";
211 return INSTALL_ERROR;
212 }
213 if (pkg_pre_build_fingerprint.empty()) {
214 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
215 return INSTALL_ERROR;
216 }
217 }
218
219 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700220}
221
Tao Baobc4b1fe2017-04-17 16:46:05 -0700222int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
223 int status_fd, std::vector<std::string>* cmd) {
224 CHECK(cmd != nullptr);
225 int ret = check_newer_ab_build(zip);
226 if (ret != 0) {
227 return ret;
228 }
Alex Deymo4344d632016-08-03 21:03:53 -0700229
Tao Baobc4b1fe2017-04-17 16:46:05 -0700230 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
231 // in the zip file.
232 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
233 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
234 ZipEntry properties_entry;
235 if (FindEntry(zip, property_name, &properties_entry) != 0) {
236 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
237 return INSTALL_CORRUPT;
238 }
239 uint32_t properties_entry_length = properties_entry.uncompressed_length;
240 std::vector<uint8_t> payload_properties(properties_entry_length);
241 int32_t err =
242 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
243 if (err != 0) {
244 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
245 return INSTALL_CORRUPT;
246 }
Alex Deymo4344d632016-08-03 21:03:53 -0700247
Tao Baobc4b1fe2017-04-17 16:46:05 -0700248 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
249 ZipString payload_name(AB_OTA_PAYLOAD);
250 ZipEntry payload_entry;
251 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
252 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
253 return INSTALL_CORRUPT;
254 }
255 long payload_offset = payload_entry.offset;
256 *cmd = {
257 "/sbin/update_engine_sideload",
258 "--payload=file://" + path,
259 android::base::StringPrintf("--offset=%ld", payload_offset),
260 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
261 android::base::StringPrintf("--status_fd=%d", status_fd),
262 };
263 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700264}
265
266#else // !AB_OTA_UPDATER
267
Tao Baobc4b1fe2017-04-17 16:46:05 -0700268int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
269 int status_fd, std::vector<std::string>* cmd) {
270 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700271
Tao Baobc4b1fe2017-04-17 16:46:05 -0700272 // On traditional updates we extract the update binary from the package.
273 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
274 ZipString binary_name(UPDATE_BINARY_NAME);
275 ZipEntry binary_entry;
276 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
277 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
278 return INSTALL_CORRUPT;
279 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700280
Tao Baobc4b1fe2017-04-17 16:46:05 -0700281 const char* binary = "/tmp/update_binary";
282 unlink(binary);
283 int fd = creat(binary, 0755);
284 if (fd == -1) {
285 PLOG(ERROR) << "Failed to create " << binary;
286 return INSTALL_ERROR;
287 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700288
Tao Baobc4b1fe2017-04-17 16:46:05 -0700289 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
290 close(fd);
291 if (error != 0) {
292 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
293 return INSTALL_ERROR;
294 }
295
296 *cmd = {
297 binary,
298 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
299 std::to_string(status_fd),
300 path,
301 };
302 if (retry_count > 0) {
303 cmd->push_back("retry");
304 }
305 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700306}
307#endif // !AB_OTA_UPDATER
308
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700309static void log_max_temperature(int* max_temperature) {
310 CHECK(max_temperature != nullptr);
311 std::mutex mtx;
312 std::unique_lock<std::mutex> lck(mtx);
313 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
314 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
315 }
316}
317
Alex Deymo4344d632016-08-03 21:03:53 -0700318// If the package contains an update binary, extract it and run it.
Tao Bao20c581e2016-12-28 20:55:51 -0800319static int try_update_binary(const char* path, ZipArchiveHandle zip, bool* wipe_cache,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700320 std::vector<std::string>& log_buffer, int retry_count,
321 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
Tao Bao20c581e2016-12-28 20:55:51 -0800324 int pipefd[2];
325 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700326
Tao Bao20c581e2016-12-28 20:55:51 -0800327 std::vector<std::string> args;
328 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
329 if (ret) {
330 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700331 close(pipefd[1]);
Tao Bao20c581e2016-12-28 20:55:51 -0800332 return ret;
333 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700334
Tao Bao20c581e2016-12-28 20:55:51 -0800335 // When executing the update binary contained in the package, the
336 // arguments passed are:
337 //
338 // - the version number for this interface
339 //
340 // - an FD to which the program can write in order to update the
341 // progress bar. The program can write single-line commands:
342 //
343 // progress <frac> <secs>
344 // fill up the next <frac> part of of the progress bar
345 // over <secs> seconds. If <secs> is zero, use
346 // set_progress commands to manually control the
347 // progress of this segment of the bar.
348 //
349 // set_progress <frac>
350 // <frac> should be between 0.0 and 1.0; sets the
351 // progress bar within the segment defined by the most
352 // recent progress command.
353 //
354 // ui_print <string>
355 // display <string> on the screen.
356 //
357 // wipe_cache
358 // a wipe of cache will be performed following a successful
359 // installation.
360 //
361 // clear_display
362 // turn off the text display.
363 //
364 // enable_reboot
365 // packages can explicitly request that they want the user
366 // to be able to reboot during installation (useful for
367 // debugging packages that don't exit).
368 //
369 // retry_update
370 // updater encounters some issue during the update. It requests
371 // a reboot to retry the same package automatically.
372 //
373 // log <string>
374 // updater requests logging the string (e.g. cause of the
375 // failure).
376 //
377 // - the name of the package zip file.
378 //
379 // - an optional argument "retry" if this update is a retry of a failed
380 // update attempt.
381 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700382
Tao Bao20c581e2016-12-28 20:55:51 -0800383 // Convert the vector to a NULL-terminated char* array suitable for execv.
384 const char* chr_args[args.size() + 1];
385 chr_args[args.size()] = nullptr;
386 for (size_t i = 0; i < args.size(); i++) {
387 chr_args[i] = args[i].c_str();
388 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700389
Tao Bao20c581e2016-12-28 20:55:51 -0800390 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700391
Tao Bao20c581e2016-12-28 20:55:51 -0800392 if (pid == -1) {
393 close(pipefd[0]);
394 close(pipefd[1]);
395 PLOG(ERROR) << "Failed to fork update binary";
396 return INSTALL_ERROR;
397 }
398
399 if (pid == 0) {
400 umask(022);
401 close(pipefd[0]);
402 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800403 // Bug: 34769056
404 // We shouldn't use LOG/PLOG in the forked process, since they may cause
405 // the child process to hang. This deadlock results from an improperly
406 // copied mutex in the ui functions.
407 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800408 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800409 }
410 close(pipefd[1]);
411
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700412 std::thread temperature_logger(log_max_temperature, max_temperature);
413
Tao Bao20c581e2016-12-28 20:55:51 -0800414 *wipe_cache = false;
415 bool retry_update = false;
416
417 char buffer[1024];
418 FILE* from_child = fdopen(pipefd[0], "r");
419 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
420 std::string line(buffer);
421 size_t space = line.find_first_of(" \n");
422 std::string command(line.substr(0, space));
423 if (command.empty()) continue;
424
425 // Get rid of the leading and trailing space and/or newline.
426 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
427
428 if (command == "progress") {
429 std::vector<std::string> tokens = android::base::Split(args, " ");
430 double fraction;
431 int seconds;
432 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
433 android::base::ParseInt(tokens[1], &seconds)) {
434 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
435 } else {
436 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
437 }
438 } else if (command == "set_progress") {
439 std::vector<std::string> tokens = android::base::Split(args, " ");
440 double fraction;
441 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
442 ui->SetProgress(fraction);
443 } else {
444 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
445 }
446 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800447 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800448 fflush(stdout);
449 } else if (command == "wipe_cache") {
450 *wipe_cache = true;
451 } else if (command == "clear_display") {
452 ui->SetBackground(RecoveryUI::NONE);
453 } else if (command == "enable_reboot") {
454 // packages can explicitly request that they want the user
455 // to be able to reboot during installation (useful for
456 // debugging packages that don't exit).
457 ui->SetEnableReboot(true);
458 } else if (command == "retry_update") {
459 retry_update = true;
460 } else if (command == "log") {
461 if (!args.empty()) {
462 // Save the logging request from updater and write to last_install later.
463 log_buffer.push_back(args);
464 } else {
465 LOG(ERROR) << "invalid \"log\" parameters: " << line;
466 }
467 } else {
468 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700469 }
Tao Bao20c581e2016-12-28 20:55:51 -0800470 }
471 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700472
Tao Bao20c581e2016-12-28 20:55:51 -0800473 int status;
474 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700475
476 finish_log_temperature.notify_one();
477 temperature_logger.join();
478
Tao Bao20c581e2016-12-28 20:55:51 -0800479 if (retry_update) {
480 return INSTALL_RETRY;
481 }
482 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
483 LOG(ERROR) << "Error in " << path << " (Status " << WEXITSTATUS(status) << ")";
484 return INSTALL_ERROR;
485 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700486
Tao Bao20c581e2016-12-28 20:55:51 -0800487 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700488}
489
Tao Bao1d866052017-04-10 16:55:57 -0700490// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
491// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
492// package.
493bool verify_package_compatibility(ZipArchiveHandle package_zip) {
494 LOG(INFO) << "Verifying package compatibility...";
495
496 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
497 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
498 ZipEntry compatibility_entry;
499 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
500 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
501 return true;
502 }
503
504 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
505 int32_t ret;
506 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
507 reinterpret_cast<uint8_t*>(&zip_content[0]),
508 compatibility_entry.uncompressed_length)) != 0) {
509 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
510 return false;
511 }
512
513 ZipArchiveHandle zip_handle;
514 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
515 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
516 if (ret != 0) {
517 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
518 return false;
519 }
520
521 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
522 void* cookie;
523 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
524 if (ret != 0) {
525 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
526 CloseArchive(zip_handle);
527 return false;
528 }
529 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
530
531 std::vector<std::string> compatibility_info;
532 ZipEntry info_entry;
533 ZipString info_name;
534 while (Next(cookie, &info_entry, &info_name) == 0) {
535 std::string content(info_entry.uncompressed_length, '\0');
536 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
537 info_entry.uncompressed_length);
538 if (ret != 0) {
539 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
540 CloseArchive(zip_handle);
541 return false;
542 }
543 compatibility_info.emplace_back(std::move(content));
544 }
Tao Bao1d866052017-04-10 16:55:57 -0700545 CloseArchive(zip_handle);
546
547 // TODO(b/36814503): Enable the actual verification when VintfObject::CheckCompatibility() lands.
548 // VintfObject::CheckCompatibility returns zero on success.
549 // return (android::vintf::VintfObject::CheckCompatibility(compatibility_info, true) == 0);
550 return true;
551}
552
Doug Zongker469243e2011-04-12 09:28:10 -0700553static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700554really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700555 std::vector<std::string>& log_buffer, int retry_count, int* max_temperature)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800556{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700557 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700558 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700559 // Give verification half the progress bar...
560 ui->SetProgressType(RecoveryUI::DETERMINATE);
561 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tianjie Xuc21edd42016-08-05 18:00:04 -0700562 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800563
Doug Zongker99916f02014-01-13 14:16:58 -0800564 // Map the update package into memory.
565 ui->Print("Opening update package...\n");
566
Doug Zongker075ad802014-06-26 15:35:51 -0700567 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800568 if (path[0] == '@') {
569 ensure_path_mounted(path+1);
570 } else {
571 ensure_path_mounted(path);
572 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800573 }
574
Doug Zongker99916f02014-01-13 14:16:58 -0800575 MemMapping map;
576 if (sysMapFile(path, &map) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700577 LOG(ERROR) << "failed to map file";
Doug Zongker99916f02014-01-13 14:16:58 -0800578 return INSTALL_CORRUPT;
579 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800580
Elliott Hughes8febafa2016-04-13 16:39:56 -0700581 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700582 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700583 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800584 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700585 return INSTALL_CORRUPT;
586 }
587
Elliott Hughes8febafa2016-04-13 16:39:56 -0700588 // Try to open the package.
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700589 ZipArchiveHandle zip;
Tianjie Xu8176cf22016-10-18 14:13:07 -0700590 int err = OpenArchiveFromMemory(map.addr, map.length, path, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800591 if (err != 0) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700592 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
Tianjie Xu16255832016-04-30 11:49:59 -0700593 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
594
Doug Zongker99916f02014-01-13 14:16:58 -0800595 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700596 CloseArchive(zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800597 return INSTALL_CORRUPT;
598 }
599
Tao Bao1d866052017-04-10 16:55:57 -0700600 // Additionally verify the compatibility of the package.
601 if (!verify_package_compatibility(zip)) {
602 LOG(ERROR) << "Failed to verify package compatibility";
603 log_buffer.push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
604 sysReleaseMap(&map);
605 CloseArchive(zip);
606 return INSTALL_CORRUPT;
607 }
608
Elliott Hughes8febafa2016-04-13 16:39:56 -0700609 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700610 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700611 if (retry_count > 0) {
612 ui->Print("Retry attempt: %d\n", retry_count);
613 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700614 ui->SetEnableReboot(false);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700615 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
Doug Zongkerc704e062014-05-23 08:40:35 -0700616 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700617 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800618
619 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700620 CloseArchive(zip);
Doug Zongker99916f02014-01-13 14:16:58 -0800621 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800622}
Doug Zongker469243e2011-04-12 09:28:10 -0700623
624int
Tao Bao145d8612015-03-25 15:51:15 -0700625install_package(const char* path, bool* wipe_cache, const char* install_file,
Tianjie Xu16255832016-04-30 11:49:59 -0700626 bool needs_mount, int retry_count)
Doug Zongker469243e2011-04-12 09:28:10 -0700627{
Tao Bao682c34b2015-04-07 17:16:35 -0700628 modified_flash = true;
Tianjie Xudd874b12016-05-13 12:13:15 -0700629 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700630
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700631 int start_temperature = GetMaxValueFromThermalZone();
632 int max_temperature = start_temperature;
633
Doug Zongker239ac6a2013-08-20 16:03:25 -0700634 int result;
Tianjie Xudd874b12016-05-13 12:13:15 -0700635 std::vector<std::string> log_buffer;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700636 if (setup_install_mounts() != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700637 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
Doug Zongker239ac6a2013-08-20 16:03:25 -0700638 result = INSTALL_ERROR;
639 } else {
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700640 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count,
641 &max_temperature);
Doug Zongker239ac6a2013-08-20 16:03:25 -0700642 }
Tianjie Xudd874b12016-05-13 12:13:15 -0700643
Tao Baobadaac42016-09-26 11:39:14 -0700644 // Measure the time spent to apply OTA update in seconds.
645 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
646 int time_total = static_cast<int>(duration.count());
Tianjie Xudd874b12016-05-13 12:13:15 -0700647
Tianjie Xua2867782017-03-24 14:13:56 -0700648 bool has_cache = volume_for_path("/cache") != nullptr;
649 // Skip logging the uncrypt_status on devices without /cache.
650 if (has_cache) {
651 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
Tao Baobadaac42016-09-26 11:39:14 -0700652 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Tianjie Xua2867782017-03-24 14:13:56 -0700653 } else {
Tao Baobadaac42016-09-26 11:39:14 -0700654 std::string uncrypt_status;
655 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
Tianjie Xua2867782017-03-24 14:13:56 -0700656 PLOG(WARNING) << "failed to read uncrypt status";
Tianjie Xu68fc81e2016-09-24 15:31:34 -0700657 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
Tianjie Xua2867782017-03-24 14:13:56 -0700658 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xue16e7992016-09-09 10:55:44 -0700659 } else {
Tianjie Xua2867782017-03-24 14:13:56 -0700660 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xue16e7992016-09-09 10:55:44 -0700661 }
Tianjie Xua2867782017-03-24 14:13:56 -0700662 }
Doug Zongker469243e2011-04-12 09:28:10 -0700663 }
Tao Baobadaac42016-09-26 11:39:14 -0700664
665 // The first two lines need to be the package name and install result.
666 std::vector<std::string> log_header = {
667 path,
668 result == INSTALL_SUCCESS ? "1" : "0",
669 "time_total: " + std::to_string(time_total),
670 "retry: " + std::to_string(retry_count),
671 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700672
673 int end_temperature = GetMaxValueFromThermalZone();
674 max_temperature = std::max(end_temperature, max_temperature);
675 if (start_temperature > 0) {
676 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
677 }
678 if (end_temperature > 0) {
679 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
680 }
681 if (max_temperature > 0) {
682 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
683 }
684
Tao Baobadaac42016-09-26 11:39:14 -0700685 std::string log_content = android::base::Join(log_header, "\n") + "\n" +
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700686 android::base::Join(log_buffer, "\n") + "\n";
Tao Baobadaac42016-09-26 11:39:14 -0700687 if (!android::base::WriteStringToFile(log_content, install_file)) {
688 PLOG(ERROR) << "failed to write " << install_file;
689 }
690
691 // Write a copy into last_log.
692 LOG(INFO) << log_content;
693
Doug Zongker469243e2011-04-12 09:28:10 -0700694 return result;
695}
Yabin Cui6faf0262016-06-09 14:09:39 -0700696
697bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Bao5e535012017-03-16 17:37:38 -0700698 std::vector<Certificate> loadedKeys;
699 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
700 LOG(ERROR) << "Failed to load keys";
701 return false;
702 }
703 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700704
Tao Bao5e535012017-03-16 17:37:38 -0700705 // Verify package.
706 ui->Print("Verifying update package...\n");
707 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700708 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700709 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
710 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
711 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
712 if (err != VERIFY_SUCCESS) {
713 LOG(ERROR) << "Signature verification failed";
714 LOG(ERROR) << "error: " << kZipVerificationFailure;
715 return false;
716 }
717 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700718}