blob: 95794ce0783a69ae7205ce0c097ba6e968761d54 [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"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070051#include "otautil/SysUtil.h"
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070052#include "otautil/ThermalUtil.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080053#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070054#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020055#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080056
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070057using namespace std::chrono_literals;
58
Tianjie Xub0ddae52016-06-08 14:30:04 -070059static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080060
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
Tianjie Xu8176cf22016-10-18 14:13:07 -070082bool read_metadata_from_package(ZipArchiveHandle zip, std::string* meta_data) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070083 ZipString metadata_path(METADATA_PATH);
84 ZipEntry meta_entry;
Tianjie Xu8176cf22016-10-18 14:13:07 -070085 if (meta_data == nullptr) {
86 LOG(ERROR) << "string* meta_data can't be nullptr";
87 return false;
88 }
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070089 if (FindEntry(zip, metadata_path, &meta_entry) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -070090 LOG(ERROR) << "Failed to find " << METADATA_PATH << " in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -070091 return false;
Tianjie Xub0ddae52016-06-08 14:30:04 -070092 }
93
Tianjie Xu8176cf22016-10-18 14:13:07 -070094 meta_data->resize(meta_entry.uncompressed_length, '\0');
95 if (ExtractToMemory(zip, &meta_entry, reinterpret_cast<uint8_t*>(&(*meta_data)[0]),
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070096 meta_entry.uncompressed_length) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -070097 LOG(ERROR) << "Failed to read metadata in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -070098 return false;
99 }
100 return true;
101}
102
103// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tianjie Xu8176cf22016-10-18 14:13:07 -0700104static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>& log_buffer) {
Yabin Cui6faf0262016-06-09 14:09:39 -0700105 std::string meta_data;
106 if (!read_metadata_from_package(zip, &meta_data)) {
Tianjie Xub0ddae52016-06-08 14:30:04 -0700107 return;
108 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700109 // 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(meta_data, "\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) {
118 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
119 source_build));
120 }
121 } else if (android::base::StartsWith(str, "post-build-incremental")) {
122 int target_build = parse_build_number(str);
123 if (target_build != -1) {
124 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
125 target_build));
126 }
127 }
128 }
129}
130
Tao Baobc4b1fe2017-04-17 16:46:05 -0700131// Extract the update binary from the open zip archive |zip| located at |path| and store into |cmd|
132// the command line that should be called. The |status_fd| is the file descriptor the child process
133// should use to report back the progress of the update.
134int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
135 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700136
Alex Deymo4344d632016-08-03 21:03:53 -0700137#ifdef AB_OTA_UPDATER
138
139// Parses the metadata of the OTA package in |zip| and checks whether we are
140// allowed to accept this A/B package. Downgrading is not allowed unless
141// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800142static int check_newer_ab_build(ZipArchiveHandle zip) {
143 std::string metadata_str;
144 if (!read_metadata_from_package(zip, &metadata_str)) {
145 return INSTALL_CORRUPT;
146 }
147 std::map<std::string, std::string> metadata;
148 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
149 size_t eq = line.find('=');
150 if (eq != std::string::npos) {
151 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700152 }
Tao Baoefc35592017-01-08 22:45:47 -0800153 }
Alex Deymo4344d632016-08-03 21:03:53 -0700154
Tao Baoefc35592017-01-08 22:45:47 -0800155 std::string value = android::base::GetProperty("ro.product.device", "");
156 const std::string& pkg_device = metadata["pre-device"];
157 if (pkg_device != value || pkg_device.empty()) {
158 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
159 return INSTALL_ERROR;
160 }
Alex Deymo4344d632016-08-03 21:03:53 -0700161
Tao Baoefc35592017-01-08 22:45:47 -0800162 // We allow the package to not have any serialno, but if it has a non-empty
163 // value it should match.
164 value = android::base::GetProperty("ro.serialno", "");
165 const std::string& pkg_serial_no = metadata["serialno"];
166 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
167 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
168 return INSTALL_ERROR;
169 }
Alex Deymo4344d632016-08-03 21:03:53 -0700170
Tao Baoefc35592017-01-08 22:45:47 -0800171 if (metadata["ota-type"] != "AB") {
172 LOG(ERROR) << "Package is not A/B";
173 return INSTALL_ERROR;
174 }
Alex Deymo4344d632016-08-03 21:03:53 -0700175
Tao Baoefc35592017-01-08 22:45:47 -0800176 // Incremental updates should match the current build.
177 value = android::base::GetProperty("ro.build.version.incremental", "");
178 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
179 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
180 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
181 return INSTALL_ERROR;
182 }
Alex Deymo4344d632016-08-03 21:03:53 -0700183
Tao Baoefc35592017-01-08 22:45:47 -0800184 value = android::base::GetProperty("ro.build.fingerprint", "");
185 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
186 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
187 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
188 << value;
189 return INSTALL_ERROR;
190 }
Alex Deymo4344d632016-08-03 21:03:53 -0700191
Tao Baoefc35592017-01-08 22:45:47 -0800192 // Check for downgrade version.
193 int64_t build_timestamp =
194 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
195 int64_t pkg_post_timestamp = 0;
196 // We allow to full update to the same version we are running, in case there
197 // is a problem with the current copy of that version.
198 if (metadata["post-timestamp"].empty() ||
199 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
200 pkg_post_timestamp < build_timestamp) {
201 if (metadata["ota-downgrade"] != "yes") {
202 LOG(ERROR) << "Update package is older than the current build, expected a build "
203 "newer than timestamp "
204 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
205 << " and downgrade not allowed.";
206 return INSTALL_ERROR;
207 }
208 if (pkg_pre_build_fingerprint.empty()) {
209 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
210 return INSTALL_ERROR;
211 }
212 }
213
214 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700215}
216
Tao Baobc4b1fe2017-04-17 16:46:05 -0700217int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
218 int status_fd, std::vector<std::string>* cmd) {
219 CHECK(cmd != nullptr);
220 int ret = check_newer_ab_build(zip);
221 if (ret != 0) {
222 return ret;
223 }
Alex Deymo4344d632016-08-03 21:03:53 -0700224
Tao Baobc4b1fe2017-04-17 16:46:05 -0700225 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
226 // in the zip file.
227 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
228 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
229 ZipEntry properties_entry;
230 if (FindEntry(zip, property_name, &properties_entry) != 0) {
231 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
232 return INSTALL_CORRUPT;
233 }
234 uint32_t properties_entry_length = properties_entry.uncompressed_length;
235 std::vector<uint8_t> payload_properties(properties_entry_length);
236 int32_t err =
237 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
238 if (err != 0) {
239 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
240 return INSTALL_CORRUPT;
241 }
Alex Deymo4344d632016-08-03 21:03:53 -0700242
Tao Baobc4b1fe2017-04-17 16:46:05 -0700243 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
244 ZipString payload_name(AB_OTA_PAYLOAD);
245 ZipEntry payload_entry;
246 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
247 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
248 return INSTALL_CORRUPT;
249 }
250 long payload_offset = payload_entry.offset;
251 *cmd = {
252 "/sbin/update_engine_sideload",
253 "--payload=file://" + path,
254 android::base::StringPrintf("--offset=%ld", payload_offset),
255 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
256 android::base::StringPrintf("--status_fd=%d", status_fd),
257 };
258 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700259}
260
261#else // !AB_OTA_UPDATER
262
Tao Baobc4b1fe2017-04-17 16:46:05 -0700263int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
264 int status_fd, std::vector<std::string>* cmd) {
265 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700266
Tao Baobc4b1fe2017-04-17 16:46:05 -0700267 // On traditional updates we extract the update binary from the package.
268 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
269 ZipString binary_name(UPDATE_BINARY_NAME);
270 ZipEntry binary_entry;
271 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
272 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
273 return INSTALL_CORRUPT;
274 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700275
Tao Baobc4b1fe2017-04-17 16:46:05 -0700276 const char* binary = "/tmp/update_binary";
277 unlink(binary);
278 int fd = creat(binary, 0755);
279 if (fd == -1) {
280 PLOG(ERROR) << "Failed to create " << binary;
281 return INSTALL_ERROR;
282 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700283
Tao Baobc4b1fe2017-04-17 16:46:05 -0700284 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
285 close(fd);
286 if (error != 0) {
287 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
288 return INSTALL_ERROR;
289 }
290
291 *cmd = {
292 binary,
293 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
294 std::to_string(status_fd),
295 path,
296 };
297 if (retry_count > 0) {
298 cmd->push_back("retry");
299 }
300 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700301}
302#endif // !AB_OTA_UPDATER
303
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700304static void log_max_temperature(int* max_temperature) {
305 CHECK(max_temperature != nullptr);
306 std::mutex mtx;
307 std::unique_lock<std::mutex> lck(mtx);
308 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
309 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
310 }
311}
312
Alex Deymo4344d632016-08-03 21:03:53 -0700313// If the package contains an update binary, extract it and run it.
Tao Bao20c581e2016-12-28 20:55:51 -0800314static int try_update_binary(const char* path, ZipArchiveHandle zip, bool* wipe_cache,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700315 std::vector<std::string>& log_buffer, int retry_count,
316 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800317 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700318
Tao Bao20c581e2016-12-28 20:55:51 -0800319 int pipefd[2];
320 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700321
Tao Bao20c581e2016-12-28 20:55:51 -0800322 std::vector<std::string> args;
323 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
324 if (ret) {
325 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700326 close(pipefd[1]);
Tao Bao20c581e2016-12-28 20:55:51 -0800327 return ret;
328 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700329
Tao Bao20c581e2016-12-28 20:55:51 -0800330 // When executing the update binary contained in the package, the
331 // arguments passed are:
332 //
333 // - the version number for this interface
334 //
335 // - an FD to which the program can write in order to update the
336 // progress bar. The program can write single-line commands:
337 //
338 // progress <frac> <secs>
339 // fill up the next <frac> part of of the progress bar
340 // over <secs> seconds. If <secs> is zero, use
341 // set_progress commands to manually control the
342 // progress of this segment of the bar.
343 //
344 // set_progress <frac>
345 // <frac> should be between 0.0 and 1.0; sets the
346 // progress bar within the segment defined by the most
347 // recent progress command.
348 //
349 // ui_print <string>
350 // display <string> on the screen.
351 //
352 // wipe_cache
353 // a wipe of cache will be performed following a successful
354 // installation.
355 //
356 // clear_display
357 // turn off the text display.
358 //
359 // enable_reboot
360 // packages can explicitly request that they want the user
361 // to be able to reboot during installation (useful for
362 // debugging packages that don't exit).
363 //
364 // retry_update
365 // updater encounters some issue during the update. It requests
366 // a reboot to retry the same package automatically.
367 //
368 // log <string>
369 // updater requests logging the string (e.g. cause of the
370 // failure).
371 //
372 // - the name of the package zip file.
373 //
374 // - an optional argument "retry" if this update is a retry of a failed
375 // update attempt.
376 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700377
Tao Bao20c581e2016-12-28 20:55:51 -0800378 // Convert the vector to a NULL-terminated char* array suitable for execv.
379 const char* chr_args[args.size() + 1];
380 chr_args[args.size()] = nullptr;
381 for (size_t i = 0; i < args.size(); i++) {
382 chr_args[i] = args[i].c_str();
383 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700384
Tao Bao20c581e2016-12-28 20:55:51 -0800385 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700386
Tao Bao20c581e2016-12-28 20:55:51 -0800387 if (pid == -1) {
388 close(pipefd[0]);
389 close(pipefd[1]);
390 PLOG(ERROR) << "Failed to fork update binary";
391 return INSTALL_ERROR;
392 }
393
394 if (pid == 0) {
395 umask(022);
396 close(pipefd[0]);
397 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800398 // Bug: 34769056
399 // We shouldn't use LOG/PLOG in the forked process, since they may cause
400 // the child process to hang. This deadlock results from an improperly
401 // copied mutex in the ui functions.
402 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800403 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800404 }
405 close(pipefd[1]);
406
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700407 std::thread temperature_logger(log_max_temperature, max_temperature);
408
Tao Bao20c581e2016-12-28 20:55:51 -0800409 *wipe_cache = false;
410 bool retry_update = false;
411
412 char buffer[1024];
413 FILE* from_child = fdopen(pipefd[0], "r");
414 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
415 std::string line(buffer);
416 size_t space = line.find_first_of(" \n");
417 std::string command(line.substr(0, space));
418 if (command.empty()) continue;
419
420 // Get rid of the leading and trailing space and/or newline.
421 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
422
423 if (command == "progress") {
424 std::vector<std::string> tokens = android::base::Split(args, " ");
425 double fraction;
426 int seconds;
427 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
428 android::base::ParseInt(tokens[1], &seconds)) {
429 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
430 } else {
431 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
432 }
433 } else if (command == "set_progress") {
434 std::vector<std::string> tokens = android::base::Split(args, " ");
435 double fraction;
436 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
437 ui->SetProgress(fraction);
438 } else {
439 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
440 }
441 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800442 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800443 fflush(stdout);
444 } else if (command == "wipe_cache") {
445 *wipe_cache = true;
446 } else if (command == "clear_display") {
447 ui->SetBackground(RecoveryUI::NONE);
448 } else if (command == "enable_reboot") {
449 // packages can explicitly request that they want the user
450 // to be able to reboot during installation (useful for
451 // debugging packages that don't exit).
452 ui->SetEnableReboot(true);
453 } else if (command == "retry_update") {
454 retry_update = true;
455 } else if (command == "log") {
456 if (!args.empty()) {
457 // Save the logging request from updater and write to last_install later.
458 log_buffer.push_back(args);
459 } else {
460 LOG(ERROR) << "invalid \"log\" parameters: " << line;
461 }
462 } else {
463 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700464 }
Tao Bao20c581e2016-12-28 20:55:51 -0800465 }
466 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700467
Tao Bao20c581e2016-12-28 20:55:51 -0800468 int status;
469 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700470
471 finish_log_temperature.notify_one();
472 temperature_logger.join();
473
Tao Bao20c581e2016-12-28 20:55:51 -0800474 if (retry_update) {
475 return INSTALL_RETRY;
476 }
477 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
478 LOG(ERROR) << "Error in " << path << " (Status " << WEXITSTATUS(status) << ")";
479 return INSTALL_ERROR;
480 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700481
Tao Bao20c581e2016-12-28 20:55:51 -0800482 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700483}
484
Tao Bao1d866052017-04-10 16:55:57 -0700485// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
486// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
487// package.
488bool verify_package_compatibility(ZipArchiveHandle package_zip) {
489 LOG(INFO) << "Verifying package compatibility...";
490
491 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
492 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
493 ZipEntry compatibility_entry;
494 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
495 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
496 return true;
497 }
498
499 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
500 int32_t ret;
501 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
502 reinterpret_cast<uint8_t*>(&zip_content[0]),
503 compatibility_entry.uncompressed_length)) != 0) {
504 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
505 return false;
506 }
507
508 ZipArchiveHandle zip_handle;
509 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
510 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
511 if (ret != 0) {
512 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
513 return false;
514 }
515
516 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
517 void* cookie;
518 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
519 if (ret != 0) {
520 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
521 CloseArchive(zip_handle);
522 return false;
523 }
524 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
525
526 std::vector<std::string> compatibility_info;
527 ZipEntry info_entry;
528 ZipString info_name;
529 while (Next(cookie, &info_entry, &info_name) == 0) {
530 std::string content(info_entry.uncompressed_length, '\0');
531 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
532 info_entry.uncompressed_length);
533 if (ret != 0) {
534 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
535 CloseArchive(zip_handle);
536 return false;
537 }
538 compatibility_info.emplace_back(std::move(content));
539 }
Tao Bao1d866052017-04-10 16:55:57 -0700540 CloseArchive(zip_handle);
541
542 // TODO(b/36814503): Enable the actual verification when VintfObject::CheckCompatibility() lands.
543 // VintfObject::CheckCompatibility returns zero on success.
544 // return (android::vintf::VintfObject::CheckCompatibility(compatibility_info, true) == 0);
545 return true;
546}
547
Doug Zongker469243e2011-04-12 09:28:10 -0700548static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700549really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700550 std::vector<std::string>& log_buffer, int retry_count, int* max_temperature)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800551{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700552 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700553 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700554 // Give verification half the progress bar...
555 ui->SetProgressType(RecoveryUI::DETERMINATE);
556 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tianjie Xuc21edd42016-08-05 18:00:04 -0700557 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800558
Doug Zongker99916f02014-01-13 14:16:58 -0800559 // Map the update package into memory.
560 ui->Print("Opening update package...\n");
561
Doug Zongker075ad802014-06-26 15:35:51 -0700562 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800563 if (path[0] == '@') {
564 ensure_path_mounted(path+1);
565 } else {
566 ensure_path_mounted(path);
567 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800568 }
569
Doug Zongker99916f02014-01-13 14:16:58 -0800570 MemMapping map;
571 if (sysMapFile(path, &map) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700572 LOG(ERROR) << "failed to map file";
Doug Zongker99916f02014-01-13 14:16:58 -0800573 return INSTALL_CORRUPT;
574 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800575
Elliott Hughes8febafa2016-04-13 16:39:56 -0700576 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700577 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700578 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800579 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700580 return INSTALL_CORRUPT;
581 }
582
Elliott Hughes8febafa2016-04-13 16:39:56 -0700583 // Try to open the package.
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700584 ZipArchiveHandle zip;
Tianjie Xu8176cf22016-10-18 14:13:07 -0700585 int err = OpenArchiveFromMemory(map.addr, map.length, path, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800586 if (err != 0) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700587 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
Tianjie Xu16255832016-04-30 11:49:59 -0700588 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
589
Doug Zongker99916f02014-01-13 14:16:58 -0800590 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700591 CloseArchive(zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800592 return INSTALL_CORRUPT;
593 }
594
Tao Bao1d866052017-04-10 16:55:57 -0700595 // Additionally verify the compatibility of the package.
596 if (!verify_package_compatibility(zip)) {
597 LOG(ERROR) << "Failed to verify package compatibility";
598 log_buffer.push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
599 sysReleaseMap(&map);
600 CloseArchive(zip);
601 return INSTALL_CORRUPT;
602 }
603
Elliott Hughes8febafa2016-04-13 16:39:56 -0700604 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700605 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700606 if (retry_count > 0) {
607 ui->Print("Retry attempt: %d\n", retry_count);
608 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700609 ui->SetEnableReboot(false);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700610 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
Doug Zongkerc704e062014-05-23 08:40:35 -0700611 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700612 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800613
614 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700615 CloseArchive(zip);
Doug Zongker99916f02014-01-13 14:16:58 -0800616 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800617}
Doug Zongker469243e2011-04-12 09:28:10 -0700618
Tao Baof8119fb2017-04-18 21:35:12 -0700619int install_package(const char* path, bool* wipe_cache, const char* install_file, bool needs_mount,
620 int retry_count) {
621 modified_flash = true;
622 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700623
Tao Baof8119fb2017-04-18 21:35:12 -0700624 int start_temperature = GetMaxValueFromThermalZone();
625 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700626
Tao Baof8119fb2017-04-18 21:35:12 -0700627 int result;
628 std::vector<std::string> log_buffer;
629 if (setup_install_mounts() != 0) {
630 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
631 result = INSTALL_ERROR;
632 } else {
633 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count,
634 &max_temperature);
635 }
636
637 // Measure the time spent to apply OTA update in seconds.
638 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
639 int time_total = static_cast<int>(duration.count());
640
641 bool has_cache = volume_for_path("/cache") != nullptr;
642 // Skip logging the uncrypt_status on devices without /cache.
643 if (has_cache) {
644 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
645 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
646 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700647 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700648 std::string uncrypt_status;
649 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
650 PLOG(WARNING) << "failed to read uncrypt status";
651 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
652 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700653 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700654 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700655 }
Doug Zongker469243e2011-04-12 09:28:10 -0700656 }
Tao Baof8119fb2017-04-18 21:35:12 -0700657 }
Tao Baobadaac42016-09-26 11:39:14 -0700658
Tao Baof8119fb2017-04-18 21:35:12 -0700659 // The first two lines need to be the package name and install result.
660 std::vector<std::string> log_header = {
661 path,
662 result == INSTALL_SUCCESS ? "1" : "0",
663 "time_total: " + std::to_string(time_total),
664 "retry: " + std::to_string(retry_count),
665 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700666
Tao Baof8119fb2017-04-18 21:35:12 -0700667 int end_temperature = GetMaxValueFromThermalZone();
668 max_temperature = std::max(end_temperature, max_temperature);
669 if (start_temperature > 0) {
670 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
671 }
672 if (end_temperature > 0) {
673 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
674 }
675 if (max_temperature > 0) {
676 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
677 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700678
Tao Baof8119fb2017-04-18 21:35:12 -0700679 std::string log_content =
680 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
681 if (!android::base::WriteStringToFile(log_content, install_file)) {
682 PLOG(ERROR) << "failed to write " << install_file;
683 }
Tao Baobadaac42016-09-26 11:39:14 -0700684
Tao Baof8119fb2017-04-18 21:35:12 -0700685 // Write a copy into last_log.
686 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700687
Tao Baof8119fb2017-04-18 21:35:12 -0700688 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700689}
Yabin Cui6faf0262016-06-09 14:09:39 -0700690
691bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700692 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700693 std::vector<Certificate> loadedKeys;
694 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
695 LOG(ERROR) << "Failed to load keys";
696 return false;
697 }
698 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700699
Tao Bao5e535012017-03-16 17:37:38 -0700700 // Verify package.
701 ui->Print("Verifying update package...\n");
702 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700703 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700704 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
705 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
706 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
707 if (err != VERIFY_SUCCESS) {
708 LOG(ERROR) << "Signature verification failed";
709 LOG(ERROR) << "error: " << kZipVerificationFailure;
710 return false;
711 }
712 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700713}