blob: a1f2e4fbd74ecaaa7930247075b50a9372006656 [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 Bao919d2c92017-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"
Tao Bao00d57572017-05-02 15:48:54 -070054#include "private/install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080055#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070056#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020057#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080058
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070059using namespace std::chrono_literals;
60
Doug Zongker74406302011-10-28 15:13:10 -070061// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080062static constexpr int VERIFICATION_PROGRESS_TIME = 60;
63static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070064
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070065static std::condition_variable finish_log_temperature;
66
Tianjie Xub0ddae52016-06-08 14:30:04 -070067// This function parses and returns the build.version.incremental
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070068static int parse_build_number(const std::string& str) {
69 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070070 if (pos != std::string::npos) {
71 std::string num_string = android::base::Trim(str.substr(pos+1));
72 int build_number;
73 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
74 return build_number;
75 }
76 }
77
Tianjie Xuc21edd42016-08-05 18:00:04 -070078 LOG(ERROR) << "Failed to parse build number in " << str;
Tianjie Xub0ddae52016-06-08 14:30:04 -070079 return -1;
80}
81
Tao Bao8a7afcc2017-04-18 22:05:50 -070082bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
83 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070084
Tao Bao8a7afcc2017-04-18 22:05:50 -070085 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
86 ZipString path(METADATA_PATH);
87 ZipEntry entry;
88 if (FindEntry(zip, path, &entry) != 0) {
89 LOG(ERROR) << "Failed to find " << METADATA_PATH;
90 return false;
91 }
92
93 uint32_t length = entry.uncompressed_length;
94 metadata->resize(length, '\0');
95 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
96 if (err != 0) {
97 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
98 return false;
99 }
100 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700101}
102
103// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tao Bao29ee69b2017-05-01 12:23:17 -0700104static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>* log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700105 std::string metadata;
106 if (!read_metadata_from_package(zip, &metadata)) {
107 return;
108 }
109 // Examples of the pre-build and post-build strings in metadata:
110 // pre-build-incremental=2943039
111 // post-build-incremental=2951741
112 std::vector<std::string> lines = android::base::Split(metadata, "\n");
113 for (const std::string& line : lines) {
114 std::string str = android::base::Trim(line);
115 if (android::base::StartsWith(str, "pre-build-incremental")) {
116 int source_build = parse_build_number(str);
117 if (source_build != -1) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700118 log_buffer->push_back(android::base::StringPrintf("source_build: %d", source_build));
Tao Bao8a7afcc2017-04-18 22:05:50 -0700119 }
120 } else if (android::base::StartsWith(str, "post-build-incremental")) {
121 int target_build = parse_build_number(str);
122 if (target_build != -1) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700123 log_buffer->push_back(android::base::StringPrintf("target_build: %d", target_build));
Tao Bao8a7afcc2017-04-18 22:05:50 -0700124 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700125 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700126 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700127}
128
Alex Deymo4344d632016-08-03 21:03:53 -0700129#ifdef AB_OTA_UPDATER
130
131// Parses the metadata of the OTA package in |zip| and checks whether we are
132// allowed to accept this A/B package. Downgrading is not allowed unless
133// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800134static int check_newer_ab_build(ZipArchiveHandle zip) {
135 std::string metadata_str;
136 if (!read_metadata_from_package(zip, &metadata_str)) {
137 return INSTALL_CORRUPT;
138 }
139 std::map<std::string, std::string> metadata;
140 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
141 size_t eq = line.find('=');
142 if (eq != std::string::npos) {
143 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700144 }
Tao Baoefc35592017-01-08 22:45:47 -0800145 }
Alex Deymo4344d632016-08-03 21:03:53 -0700146
Tao Baoefc35592017-01-08 22:45:47 -0800147 std::string value = android::base::GetProperty("ro.product.device", "");
148 const std::string& pkg_device = metadata["pre-device"];
149 if (pkg_device != value || pkg_device.empty()) {
150 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
151 return INSTALL_ERROR;
152 }
Alex Deymo4344d632016-08-03 21:03:53 -0700153
Tao Baoefc35592017-01-08 22:45:47 -0800154 // We allow the package to not have any serialno, but if it has a non-empty
155 // value it should match.
156 value = android::base::GetProperty("ro.serialno", "");
157 const std::string& pkg_serial_no = metadata["serialno"];
158 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
159 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
160 return INSTALL_ERROR;
161 }
Alex Deymo4344d632016-08-03 21:03:53 -0700162
Tao Baoefc35592017-01-08 22:45:47 -0800163 if (metadata["ota-type"] != "AB") {
164 LOG(ERROR) << "Package is not A/B";
165 return INSTALL_ERROR;
166 }
Alex Deymo4344d632016-08-03 21:03:53 -0700167
Tao Baoefc35592017-01-08 22:45:47 -0800168 // Incremental updates should match the current build.
169 value = android::base::GetProperty("ro.build.version.incremental", "");
170 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
171 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
172 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
173 return INSTALL_ERROR;
174 }
Alex Deymo4344d632016-08-03 21:03:53 -0700175
Tao Baoefc35592017-01-08 22:45:47 -0800176 value = android::base::GetProperty("ro.build.fingerprint", "");
177 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
178 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
179 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
180 << value;
181 return INSTALL_ERROR;
182 }
Alex Deymo4344d632016-08-03 21:03:53 -0700183
Tao Baoefc35592017-01-08 22:45:47 -0800184 // Check for downgrade version.
185 int64_t build_timestamp =
186 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
187 int64_t pkg_post_timestamp = 0;
188 // We allow to full update to the same version we are running, in case there
189 // is a problem with the current copy of that version.
190 if (metadata["post-timestamp"].empty() ||
191 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
192 pkg_post_timestamp < build_timestamp) {
193 if (metadata["ota-downgrade"] != "yes") {
194 LOG(ERROR) << "Update package is older than the current build, expected a build "
195 "newer than timestamp "
196 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
197 << " and downgrade not allowed.";
198 return INSTALL_ERROR;
199 }
200 if (pkg_pre_build_fingerprint.empty()) {
201 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
202 return INSTALL_ERROR;
203 }
204 }
205
206 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700207}
208
Tao Bao00d57572017-05-02 15:48:54 -0700209int update_binary_command(const std::string& package, ZipArchiveHandle zip,
210 const std::string& binary_path, int /* retry_count */, int status_fd,
211 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700212 CHECK(cmd != nullptr);
213 int ret = check_newer_ab_build(zip);
214 if (ret != 0) {
215 return ret;
216 }
Alex Deymo4344d632016-08-03 21:03:53 -0700217
Tao Baobc4b1fe2017-04-17 16:46:05 -0700218 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
219 // in the zip file.
220 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
221 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
222 ZipEntry properties_entry;
223 if (FindEntry(zip, property_name, &properties_entry) != 0) {
224 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
225 return INSTALL_CORRUPT;
226 }
227 uint32_t properties_entry_length = properties_entry.uncompressed_length;
228 std::vector<uint8_t> payload_properties(properties_entry_length);
229 int32_t err =
230 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
231 if (err != 0) {
232 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
233 return INSTALL_CORRUPT;
234 }
Alex Deymo4344d632016-08-03 21:03:53 -0700235
Tao Baobc4b1fe2017-04-17 16:46:05 -0700236 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
237 ZipString payload_name(AB_OTA_PAYLOAD);
238 ZipEntry payload_entry;
239 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
240 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
241 return INSTALL_CORRUPT;
242 }
243 long payload_offset = payload_entry.offset;
244 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700245 binary_path,
246 "--payload=file://" + package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700247 android::base::StringPrintf("--offset=%ld", payload_offset),
248 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
249 android::base::StringPrintf("--status_fd=%d", status_fd),
250 };
251 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700252}
253
254#else // !AB_OTA_UPDATER
255
Tao Bao00d57572017-05-02 15:48:54 -0700256int update_binary_command(const std::string& package, ZipArchiveHandle zip,
257 const std::string& binary_path, int retry_count, int status_fd,
258 std::vector<std::string>* cmd) {
Tao Baobc4b1fe2017-04-17 16:46:05 -0700259 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700260
Tao Baobc4b1fe2017-04-17 16:46:05 -0700261 // On traditional updates we extract the update binary from the package.
262 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
263 ZipString binary_name(UPDATE_BINARY_NAME);
264 ZipEntry binary_entry;
265 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
266 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
267 return INSTALL_CORRUPT;
268 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700269
Tao Bao00d57572017-05-02 15:48:54 -0700270 unlink(binary_path.c_str());
271 int fd = creat(binary_path.c_str(), 0755);
Tao Baobc4b1fe2017-04-17 16:46:05 -0700272 if (fd == -1) {
Tao Bao00d57572017-05-02 15:48:54 -0700273 PLOG(ERROR) << "Failed to create " << binary_path;
Tao Baobc4b1fe2017-04-17 16:46:05 -0700274 return INSTALL_ERROR;
275 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700276
Tao Baobc4b1fe2017-04-17 16:46:05 -0700277 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
278 close(fd);
279 if (error != 0) {
280 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
281 return INSTALL_ERROR;
282 }
283
284 *cmd = {
Tao Bao00d57572017-05-02 15:48:54 -0700285 binary_path,
Tao Bao8be0f392017-05-04 00:29:31 +0000286 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
Tao Baobc4b1fe2017-04-17 16:46:05 -0700287 std::to_string(status_fd),
Tao Bao00d57572017-05-02 15:48:54 -0700288 package,
Tao Baobc4b1fe2017-04-17 16:46:05 -0700289 };
290 if (retry_count > 0) {
291 cmd->push_back("retry");
292 }
293 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700294}
295#endif // !AB_OTA_UPDATER
296
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700297static void log_max_temperature(int* max_temperature) {
298 CHECK(max_temperature != nullptr);
299 std::mutex mtx;
300 std::unique_lock<std::mutex> lck(mtx);
301 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
302 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
303 }
304}
305
Alex Deymo4344d632016-08-03 21:03:53 -0700306// If the package contains an update binary, extract it and run it.
Tao Bao00d57572017-05-02 15:48:54 -0700307static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache,
Tao Bao29ee69b2017-05-01 12:23:17 -0700308 std::vector<std::string>* log_buffer, int retry_count,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700309 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800310 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700311
Tao Bao20c581e2016-12-28 20:55:51 -0800312 int pipefd[2];
313 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700314
Tao Bao20c581e2016-12-28 20:55:51 -0800315 std::vector<std::string> args;
Tao Bao00d57572017-05-02 15:48:54 -0700316#ifdef AB_OTA_UPDATER
317 int ret = update_binary_command(package, zip, "/sbin/update_engine_sideload", retry_count,
318 pipefd[1], &args);
319#else
320 int ret = update_binary_command(package, zip, "/tmp/update-binary", retry_count, pipefd[1],
321 &args);
322#endif
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]);
Tao Bao20c581e2016-12-28 20:55:51 -0800326 return ret;
327 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700328
Tao Bao20c581e2016-12-28 20:55:51 -0800329 // When executing the update binary contained in the package, the
330 // arguments passed are:
331 //
332 // - the version number for this interface
333 //
334 // - an FD to which the program can write in order to update the
335 // progress bar. The program can write single-line commands:
336 //
337 // progress <frac> <secs>
338 // fill up the next <frac> part of of the progress bar
339 // over <secs> seconds. If <secs> is zero, use
340 // set_progress commands to manually control the
341 // progress of this segment of the bar.
342 //
343 // set_progress <frac>
344 // <frac> should be between 0.0 and 1.0; sets the
345 // progress bar within the segment defined by the most
346 // recent progress command.
347 //
348 // ui_print <string>
349 // display <string> on the screen.
350 //
351 // wipe_cache
352 // a wipe of cache will be performed following a successful
353 // installation.
354 //
355 // clear_display
356 // turn off the text display.
357 //
358 // enable_reboot
359 // packages can explicitly request that they want the user
360 // to be able to reboot during installation (useful for
361 // debugging packages that don't exit).
362 //
363 // retry_update
364 // updater encounters some issue during the update. It requests
365 // a reboot to retry the same package automatically.
366 //
367 // log <string>
368 // updater requests logging the string (e.g. cause of the
369 // failure).
370 //
371 // - the name of the package zip file.
372 //
373 // - an optional argument "retry" if this update is a retry of a failed
374 // update attempt.
375 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700376
Tao Bao20c581e2016-12-28 20:55:51 -0800377 // Convert the vector to a NULL-terminated char* array suitable for execv.
378 const char* chr_args[args.size() + 1];
379 chr_args[args.size()] = nullptr;
380 for (size_t i = 0; i < args.size(); i++) {
381 chr_args[i] = args[i].c_str();
382 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700383
Tao Bao20c581e2016-12-28 20:55:51 -0800384 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700385
Tao Bao20c581e2016-12-28 20:55:51 -0800386 if (pid == -1) {
387 close(pipefd[0]);
388 close(pipefd[1]);
389 PLOG(ERROR) << "Failed to fork update binary";
390 return INSTALL_ERROR;
391 }
392
393 if (pid == 0) {
394 umask(022);
395 close(pipefd[0]);
396 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800397 // Bug: 34769056
398 // We shouldn't use LOG/PLOG in the forked process, since they may cause
399 // the child process to hang. This deadlock results from an improperly
400 // copied mutex in the ui functions.
401 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800402 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800403 }
404 close(pipefd[1]);
405
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700406 std::thread temperature_logger(log_max_temperature, max_temperature);
407
Tao Bao20c581e2016-12-28 20:55:51 -0800408 *wipe_cache = false;
409 bool retry_update = false;
410
411 char buffer[1024];
412 FILE* from_child = fdopen(pipefd[0], "r");
413 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
414 std::string line(buffer);
415 size_t space = line.find_first_of(" \n");
416 std::string command(line.substr(0, space));
417 if (command.empty()) continue;
418
419 // Get rid of the leading and trailing space and/or newline.
420 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
421
422 if (command == "progress") {
423 std::vector<std::string> tokens = android::base::Split(args, " ");
424 double fraction;
425 int seconds;
426 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
427 android::base::ParseInt(tokens[1], &seconds)) {
428 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
429 } else {
430 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
431 }
432 } else if (command == "set_progress") {
433 std::vector<std::string> tokens = android::base::Split(args, " ");
434 double fraction;
435 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
436 ui->SetProgress(fraction);
437 } else {
438 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
439 }
440 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800441 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800442 fflush(stdout);
443 } else if (command == "wipe_cache") {
444 *wipe_cache = true;
445 } else if (command == "clear_display") {
446 ui->SetBackground(RecoveryUI::NONE);
447 } else if (command == "enable_reboot") {
448 // packages can explicitly request that they want the user
449 // to be able to reboot during installation (useful for
450 // debugging packages that don't exit).
451 ui->SetEnableReboot(true);
452 } else if (command == "retry_update") {
453 retry_update = true;
454 } else if (command == "log") {
455 if (!args.empty()) {
456 // Save the logging request from updater and write to last_install later.
Tao Bao29ee69b2017-05-01 12:23:17 -0700457 log_buffer->push_back(args);
Tao Bao20c581e2016-12-28 20:55:51 -0800458 } else {
459 LOG(ERROR) << "invalid \"log\" parameters: " << line;
460 }
461 } else {
462 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700463 }
Tao Bao20c581e2016-12-28 20:55:51 -0800464 }
465 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700466
Tao Bao20c581e2016-12-28 20:55:51 -0800467 int status;
468 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700469
470 finish_log_temperature.notify_one();
471 temperature_logger.join();
472
Tao Bao20c581e2016-12-28 20:55:51 -0800473 if (retry_update) {
474 return INSTALL_RETRY;
475 }
476 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tao Bao00d57572017-05-02 15:48:54 -0700477 LOG(ERROR) << "Error in " << package << " (Status " << WEXITSTATUS(status) << ")";
Tao Bao20c581e2016-12-28 20:55:51 -0800478 return INSTALL_ERROR;
479 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700480
Tao Bao20c581e2016-12-28 20:55:51 -0800481 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700482}
483
Tao Bao1d866052017-04-10 16:55:57 -0700484// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
485// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
486// package.
487bool verify_package_compatibility(ZipArchiveHandle package_zip) {
488 LOG(INFO) << "Verifying package compatibility...";
489
490 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
491 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
492 ZipEntry compatibility_entry;
493 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
494 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
495 return true;
496 }
497
498 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
499 int32_t ret;
500 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
501 reinterpret_cast<uint8_t*>(&zip_content[0]),
502 compatibility_entry.uncompressed_length)) != 0) {
503 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
504 return false;
505 }
506
507 ZipArchiveHandle zip_handle;
508 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
509 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
510 if (ret != 0) {
511 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
512 return false;
513 }
514
515 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
516 void* cookie;
517 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
518 if (ret != 0) {
519 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
520 CloseArchive(zip_handle);
521 return false;
522 }
523 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
524
525 std::vector<std::string> compatibility_info;
526 ZipEntry info_entry;
527 ZipString info_name;
528 while (Next(cookie, &info_entry, &info_name) == 0) {
529 std::string content(info_entry.uncompressed_length, '\0');
530 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
531 info_entry.uncompressed_length);
532 if (ret != 0) {
533 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
534 CloseArchive(zip_handle);
535 return false;
536 }
537 compatibility_info.emplace_back(std::move(content));
538 }
Tao Bao1d866052017-04-10 16:55:57 -0700539 CloseArchive(zip_handle);
540
Tao Bao919d2c92017-04-10 16:55:57 -0700541 // VintfObjectRecovery::CheckCompatibility returns zero on success.
542 std::string err;
543 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
544 if (result == 0) {
545 return true;
546 }
547
548 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
549 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700550}
551
Tao Bao29ee69b2017-05-01 12:23:17 -0700552static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount,
553 std::vector<std::string>* log_buffer, int retry_count,
554 int* max_temperature) {
555 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
556 ui->Print("Finding update package...\n");
557 // Give verification half the progress bar...
558 ui->SetProgressType(RecoveryUI::DETERMINATE);
559 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
560 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800561
Tao Bao29ee69b2017-05-01 12:23:17 -0700562 // Map the update package into memory.
563 ui->Print("Opening update package...\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800564
Tao Bao29ee69b2017-05-01 12:23:17 -0700565 if (needs_mount) {
566 if (path[0] == '@') {
567 ensure_path_mounted(path.substr(1).c_str());
568 } else {
569 ensure_path_mounted(path.c_str());
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800570 }
Tao Bao29ee69b2017-05-01 12:23:17 -0700571 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800572
Tao Bao29ee69b2017-05-01 12:23:17 -0700573 MemMapping map;
Tao Baob656a152017-04-18 23:54:29 -0700574 if (!map.MapFile(path)) {
Tao Bao29ee69b2017-05-01 12:23:17 -0700575 LOG(ERROR) << "failed to map file";
576 return INSTALL_CORRUPT;
577 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800578
Tao Bao29ee69b2017-05-01 12:23:17 -0700579 // Verify package.
580 if (!verify_package(map.addr, map.length)) {
581 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700582 return INSTALL_CORRUPT;
583 }
Doug Zongker60151a22009-08-12 18:30:03 -0700584
Tao Bao29ee69b2017-05-01 12:23:17 -0700585 // Try to open the package.
586 ZipArchiveHandle zip;
587 int err = OpenArchiveFromMemory(map.addr, map.length, path.c_str(), &zip);
588 if (err != 0) {
589 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
590 log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800591
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700592 CloseArchive(zip);
Tao Bao29ee69b2017-05-01 12:23:17 -0700593 return INSTALL_CORRUPT;
594 }
595
596 // Additionally verify the compatibility of the package.
597 if (!verify_package_compatibility(zip)) {
598 log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
Tao Bao29ee69b2017-05-01 12:23:17 -0700599 CloseArchive(zip);
600 return INSTALL_CORRUPT;
601 }
602
603 // Verify and install the contents of the package.
604 ui->Print("Installing update...\n");
605 if (retry_count > 0) {
606 ui->Print("Retry attempt: %d\n", retry_count);
607 }
608 ui->SetEnableReboot(false);
609 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
610 ui->SetEnableReboot(true);
611 ui->Print("\n");
612
Tao Bao29ee69b2017-05-01 12:23:17 -0700613 CloseArchive(zip);
614 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800615}
Doug Zongker469243e2011-04-12 09:28:10 -0700616
Tao Bao29ee69b2017-05-01 12:23:17 -0700617int install_package(const std::string& path, bool* wipe_cache, const std::string& install_file,
618 bool needs_mount, int retry_count) {
619 CHECK(!path.empty());
620 CHECK(!install_file.empty());
621 CHECK(wipe_cache != nullptr);
622
Tao Baof8119fb2017-04-18 21:35:12 -0700623 modified_flash = true;
624 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700625
Tao Baof8119fb2017-04-18 21:35:12 -0700626 int start_temperature = GetMaxValueFromThermalZone();
627 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700628
Tao Baof8119fb2017-04-18 21:35:12 -0700629 int result;
630 std::vector<std::string> log_buffer;
631 if (setup_install_mounts() != 0) {
632 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
633 result = INSTALL_ERROR;
634 } else {
Tao Bao29ee69b2017-05-01 12:23:17 -0700635 result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count,
Tao Baof8119fb2017-04-18 21:35:12 -0700636 &max_temperature);
637 }
638
639 // Measure the time spent to apply OTA update in seconds.
640 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
641 int time_total = static_cast<int>(duration.count());
642
643 bool has_cache = volume_for_path("/cache") != nullptr;
644 // Skip logging the uncrypt_status on devices without /cache.
645 if (has_cache) {
646 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
647 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
648 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700649 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700650 std::string uncrypt_status;
651 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
652 PLOG(WARNING) << "failed to read uncrypt status";
653 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
654 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700655 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700656 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700657 }
Doug Zongker469243e2011-04-12 09:28:10 -0700658 }
Tao Baof8119fb2017-04-18 21:35:12 -0700659 }
Tao Baobadaac42016-09-26 11:39:14 -0700660
Tao Baof8119fb2017-04-18 21:35:12 -0700661 // The first two lines need to be the package name and install result.
662 std::vector<std::string> log_header = {
663 path,
664 result == INSTALL_SUCCESS ? "1" : "0",
665 "time_total: " + std::to_string(time_total),
666 "retry: " + std::to_string(retry_count),
667 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700668
Tao Baof8119fb2017-04-18 21:35:12 -0700669 int end_temperature = GetMaxValueFromThermalZone();
670 max_temperature = std::max(end_temperature, max_temperature);
671 if (start_temperature > 0) {
672 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
673 }
674 if (end_temperature > 0) {
675 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
676 }
677 if (max_temperature > 0) {
678 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
679 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700680
Tao Baof8119fb2017-04-18 21:35:12 -0700681 std::string log_content =
682 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
683 if (!android::base::WriteStringToFile(log_content, install_file)) {
684 PLOG(ERROR) << "failed to write " << install_file;
685 }
Tao Baobadaac42016-09-26 11:39:14 -0700686
Tao Baof8119fb2017-04-18 21:35:12 -0700687 // Write a copy into last_log.
688 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700689
Tao Baof8119fb2017-04-18 21:35:12 -0700690 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700691}
Yabin Cui6faf0262016-06-09 14:09:39 -0700692
693bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700694 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700695 std::vector<Certificate> loadedKeys;
696 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
697 LOG(ERROR) << "Failed to load keys";
698 return false;
699 }
700 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700701
Tao Bao5e535012017-03-16 17:37:38 -0700702 // Verify package.
703 ui->Print("Verifying update package...\n");
704 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700705 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700706 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
707 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
708 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
709 if (err != VERIFY_SUCCESS) {
710 LOG(ERROR) << "Signature verification failed";
711 LOG(ERROR) << "error: " << kZipVerificationFailure;
712 return false;
713 }
714 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700715}