blob: 73ddf5e92aa540a46095efb3501afd779c64a94c [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
Doug Zongker74406302011-10-28 15:13:10 -070059// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080060static constexpr int VERIFICATION_PROGRESS_TIME = 60;
61static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070062
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070063static std::condition_variable finish_log_temperature;
64
Tianjie Xub0ddae52016-06-08 14:30:04 -070065// This function parses and returns the build.version.incremental
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070066static int parse_build_number(const std::string& str) {
67 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070068 if (pos != std::string::npos) {
69 std::string num_string = android::base::Trim(str.substr(pos+1));
70 int build_number;
71 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
72 return build_number;
73 }
74 }
75
Tianjie Xuc21edd42016-08-05 18:00:04 -070076 LOG(ERROR) << "Failed to parse build number in " << str;
Tianjie Xub0ddae52016-06-08 14:30:04 -070077 return -1;
78}
79
Tao Bao8a7afcc2017-04-18 22:05:50 -070080bool read_metadata_from_package(ZipArchiveHandle zip, std::string* metadata) {
81 CHECK(metadata != nullptr);
Tianjie Xub0ddae52016-06-08 14:30:04 -070082
Tao Bao8a7afcc2017-04-18 22:05:50 -070083 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
84 ZipString path(METADATA_PATH);
85 ZipEntry entry;
86 if (FindEntry(zip, path, &entry) != 0) {
87 LOG(ERROR) << "Failed to find " << METADATA_PATH;
88 return false;
89 }
90
91 uint32_t length = entry.uncompressed_length;
92 metadata->resize(length, '\0');
93 int32_t err = ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&(*metadata)[0]), length);
94 if (err != 0) {
95 LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
96 return false;
97 }
98 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -070099}
100
101// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tianjie Xu8176cf22016-10-18 14:13:07 -0700102static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>& log_buffer) {
Tao Bao8a7afcc2017-04-18 22:05:50 -0700103 std::string metadata;
104 if (!read_metadata_from_package(zip, &metadata)) {
105 return;
106 }
107 // Examples of the pre-build and post-build strings in metadata:
108 // pre-build-incremental=2943039
109 // post-build-incremental=2951741
110 std::vector<std::string> lines = android::base::Split(metadata, "\n");
111 for (const std::string& line : lines) {
112 std::string str = android::base::Trim(line);
113 if (android::base::StartsWith(str, "pre-build-incremental")) {
114 int source_build = parse_build_number(str);
115 if (source_build != -1) {
116 log_buffer.push_back(android::base::StringPrintf("source_build: %d", source_build));
117 }
118 } else if (android::base::StartsWith(str, "post-build-incremental")) {
119 int target_build = parse_build_number(str);
120 if (target_build != -1) {
121 log_buffer.push_back(android::base::StringPrintf("target_build: %d", target_build));
122 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700123 }
Tao Bao8a7afcc2017-04-18 22:05:50 -0700124 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700125}
126
Tao Baobc4b1fe2017-04-17 16:46:05 -0700127// Extract the update binary from the open zip archive |zip| located at |path| and store into |cmd|
128// the command line that should be called. The |status_fd| is the file descriptor the child process
129// should use to report back the progress of the update.
130int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
131 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700132
Alex Deymo4344d632016-08-03 21:03:53 -0700133#ifdef AB_OTA_UPDATER
134
135// Parses the metadata of the OTA package in |zip| and checks whether we are
136// allowed to accept this A/B package. Downgrading is not allowed unless
137// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800138static int check_newer_ab_build(ZipArchiveHandle zip) {
139 std::string metadata_str;
140 if (!read_metadata_from_package(zip, &metadata_str)) {
141 return INSTALL_CORRUPT;
142 }
143 std::map<std::string, std::string> metadata;
144 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
145 size_t eq = line.find('=');
146 if (eq != std::string::npos) {
147 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700148 }
Tao Baoefc35592017-01-08 22:45:47 -0800149 }
Alex Deymo4344d632016-08-03 21:03:53 -0700150
Tao Baoefc35592017-01-08 22:45:47 -0800151 std::string value = android::base::GetProperty("ro.product.device", "");
152 const std::string& pkg_device = metadata["pre-device"];
153 if (pkg_device != value || pkg_device.empty()) {
154 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
155 return INSTALL_ERROR;
156 }
Alex Deymo4344d632016-08-03 21:03:53 -0700157
Tao Baoefc35592017-01-08 22:45:47 -0800158 // We allow the package to not have any serialno, but if it has a non-empty
159 // value it should match.
160 value = android::base::GetProperty("ro.serialno", "");
161 const std::string& pkg_serial_no = metadata["serialno"];
162 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
163 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
164 return INSTALL_ERROR;
165 }
Alex Deymo4344d632016-08-03 21:03:53 -0700166
Tao Baoefc35592017-01-08 22:45:47 -0800167 if (metadata["ota-type"] != "AB") {
168 LOG(ERROR) << "Package is not A/B";
169 return INSTALL_ERROR;
170 }
Alex Deymo4344d632016-08-03 21:03:53 -0700171
Tao Baoefc35592017-01-08 22:45:47 -0800172 // Incremental updates should match the current build.
173 value = android::base::GetProperty("ro.build.version.incremental", "");
174 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
175 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
176 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
177 return INSTALL_ERROR;
178 }
Alex Deymo4344d632016-08-03 21:03:53 -0700179
Tao Baoefc35592017-01-08 22:45:47 -0800180 value = android::base::GetProperty("ro.build.fingerprint", "");
181 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
182 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
183 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
184 << value;
185 return INSTALL_ERROR;
186 }
Alex Deymo4344d632016-08-03 21:03:53 -0700187
Tao Baoefc35592017-01-08 22:45:47 -0800188 // Check for downgrade version.
189 int64_t build_timestamp =
190 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
191 int64_t pkg_post_timestamp = 0;
192 // We allow to full update to the same version we are running, in case there
193 // is a problem with the current copy of that version.
194 if (metadata["post-timestamp"].empty() ||
195 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
196 pkg_post_timestamp < build_timestamp) {
197 if (metadata["ota-downgrade"] != "yes") {
198 LOG(ERROR) << "Update package is older than the current build, expected a build "
199 "newer than timestamp "
200 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
201 << " and downgrade not allowed.";
202 return INSTALL_ERROR;
203 }
204 if (pkg_pre_build_fingerprint.empty()) {
205 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
206 return INSTALL_ERROR;
207 }
208 }
209
210 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700211}
212
Tao Baobc4b1fe2017-04-17 16:46:05 -0700213int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
214 int status_fd, std::vector<std::string>* cmd) {
215 CHECK(cmd != nullptr);
216 int ret = check_newer_ab_build(zip);
217 if (ret != 0) {
218 return ret;
219 }
Alex Deymo4344d632016-08-03 21:03:53 -0700220
Tao Baobc4b1fe2017-04-17 16:46:05 -0700221 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
222 // in the zip file.
223 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
224 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
225 ZipEntry properties_entry;
226 if (FindEntry(zip, property_name, &properties_entry) != 0) {
227 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
228 return INSTALL_CORRUPT;
229 }
230 uint32_t properties_entry_length = properties_entry.uncompressed_length;
231 std::vector<uint8_t> payload_properties(properties_entry_length);
232 int32_t err =
233 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
234 if (err != 0) {
235 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
236 return INSTALL_CORRUPT;
237 }
Alex Deymo4344d632016-08-03 21:03:53 -0700238
Tao Baobc4b1fe2017-04-17 16:46:05 -0700239 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
240 ZipString payload_name(AB_OTA_PAYLOAD);
241 ZipEntry payload_entry;
242 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
243 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
244 return INSTALL_CORRUPT;
245 }
246 long payload_offset = payload_entry.offset;
247 *cmd = {
248 "/sbin/update_engine_sideload",
249 "--payload=file://" + path,
250 android::base::StringPrintf("--offset=%ld", payload_offset),
251 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
252 android::base::StringPrintf("--status_fd=%d", status_fd),
253 };
254 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700255}
256
257#else // !AB_OTA_UPDATER
258
Tao Baobc4b1fe2017-04-17 16:46:05 -0700259int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
260 int status_fd, std::vector<std::string>* cmd) {
261 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700262
Tao Baobc4b1fe2017-04-17 16:46:05 -0700263 // On traditional updates we extract the update binary from the package.
264 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
265 ZipString binary_name(UPDATE_BINARY_NAME);
266 ZipEntry binary_entry;
267 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
268 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
269 return INSTALL_CORRUPT;
270 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700271
Tao Baobc4b1fe2017-04-17 16:46:05 -0700272 const char* binary = "/tmp/update_binary";
273 unlink(binary);
274 int fd = creat(binary, 0755);
275 if (fd == -1) {
276 PLOG(ERROR) << "Failed to create " << binary;
277 return INSTALL_ERROR;
278 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700279
Tao Baobc4b1fe2017-04-17 16:46:05 -0700280 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
281 close(fd);
282 if (error != 0) {
283 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
284 return INSTALL_ERROR;
285 }
286
287 *cmd = {
288 binary,
289 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
290 std::to_string(status_fd),
291 path,
292 };
293 if (retry_count > 0) {
294 cmd->push_back("retry");
295 }
296 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700297}
298#endif // !AB_OTA_UPDATER
299
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700300static void log_max_temperature(int* max_temperature) {
301 CHECK(max_temperature != nullptr);
302 std::mutex mtx;
303 std::unique_lock<std::mutex> lck(mtx);
304 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
305 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
306 }
307}
308
Alex Deymo4344d632016-08-03 21:03:53 -0700309// If the package contains an update binary, extract it and run it.
Tao Bao20c581e2016-12-28 20:55:51 -0800310static int try_update_binary(const char* path, ZipArchiveHandle zip, bool* wipe_cache,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700311 std::vector<std::string>& log_buffer, int retry_count,
312 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800313 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700314
Tao Bao20c581e2016-12-28 20:55:51 -0800315 int pipefd[2];
316 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700317
Tao Bao20c581e2016-12-28 20:55:51 -0800318 std::vector<std::string> args;
319 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
320 if (ret) {
321 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700322 close(pipefd[1]);
Tao Bao20c581e2016-12-28 20:55:51 -0800323 return ret;
324 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700325
Tao Bao20c581e2016-12-28 20:55:51 -0800326 // When executing the update binary contained in the package, the
327 // arguments passed are:
328 //
329 // - the version number for this interface
330 //
331 // - an FD to which the program can write in order to update the
332 // progress bar. The program can write single-line commands:
333 //
334 // progress <frac> <secs>
335 // fill up the next <frac> part of of the progress bar
336 // over <secs> seconds. If <secs> is zero, use
337 // set_progress commands to manually control the
338 // progress of this segment of the bar.
339 //
340 // set_progress <frac>
341 // <frac> should be between 0.0 and 1.0; sets the
342 // progress bar within the segment defined by the most
343 // recent progress command.
344 //
345 // ui_print <string>
346 // display <string> on the screen.
347 //
348 // wipe_cache
349 // a wipe of cache will be performed following a successful
350 // installation.
351 //
352 // clear_display
353 // turn off the text display.
354 //
355 // enable_reboot
356 // packages can explicitly request that they want the user
357 // to be able to reboot during installation (useful for
358 // debugging packages that don't exit).
359 //
360 // retry_update
361 // updater encounters some issue during the update. It requests
362 // a reboot to retry the same package automatically.
363 //
364 // log <string>
365 // updater requests logging the string (e.g. cause of the
366 // failure).
367 //
368 // - the name of the package zip file.
369 //
370 // - an optional argument "retry" if this update is a retry of a failed
371 // update attempt.
372 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700373
Tao Bao20c581e2016-12-28 20:55:51 -0800374 // Convert the vector to a NULL-terminated char* array suitable for execv.
375 const char* chr_args[args.size() + 1];
376 chr_args[args.size()] = nullptr;
377 for (size_t i = 0; i < args.size(); i++) {
378 chr_args[i] = args[i].c_str();
379 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700380
Tao Bao20c581e2016-12-28 20:55:51 -0800381 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700382
Tao Bao20c581e2016-12-28 20:55:51 -0800383 if (pid == -1) {
384 close(pipefd[0]);
385 close(pipefd[1]);
386 PLOG(ERROR) << "Failed to fork update binary";
387 return INSTALL_ERROR;
388 }
389
390 if (pid == 0) {
391 umask(022);
392 close(pipefd[0]);
393 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800394 // Bug: 34769056
395 // We shouldn't use LOG/PLOG in the forked process, since they may cause
396 // the child process to hang. This deadlock results from an improperly
397 // copied mutex in the ui functions.
398 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800399 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800400 }
401 close(pipefd[1]);
402
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700403 std::thread temperature_logger(log_max_temperature, max_temperature);
404
Tao Bao20c581e2016-12-28 20:55:51 -0800405 *wipe_cache = false;
406 bool retry_update = false;
407
408 char buffer[1024];
409 FILE* from_child = fdopen(pipefd[0], "r");
410 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
411 std::string line(buffer);
412 size_t space = line.find_first_of(" \n");
413 std::string command(line.substr(0, space));
414 if (command.empty()) continue;
415
416 // Get rid of the leading and trailing space and/or newline.
417 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
418
419 if (command == "progress") {
420 std::vector<std::string> tokens = android::base::Split(args, " ");
421 double fraction;
422 int seconds;
423 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
424 android::base::ParseInt(tokens[1], &seconds)) {
425 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
426 } else {
427 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
428 }
429 } else if (command == "set_progress") {
430 std::vector<std::string> tokens = android::base::Split(args, " ");
431 double fraction;
432 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
433 ui->SetProgress(fraction);
434 } else {
435 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
436 }
437 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800438 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800439 fflush(stdout);
440 } else if (command == "wipe_cache") {
441 *wipe_cache = true;
442 } else if (command == "clear_display") {
443 ui->SetBackground(RecoveryUI::NONE);
444 } else if (command == "enable_reboot") {
445 // packages can explicitly request that they want the user
446 // to be able to reboot during installation (useful for
447 // debugging packages that don't exit).
448 ui->SetEnableReboot(true);
449 } else if (command == "retry_update") {
450 retry_update = true;
451 } else if (command == "log") {
452 if (!args.empty()) {
453 // Save the logging request from updater and write to last_install later.
454 log_buffer.push_back(args);
455 } else {
456 LOG(ERROR) << "invalid \"log\" parameters: " << line;
457 }
458 } else {
459 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700460 }
Tao Bao20c581e2016-12-28 20:55:51 -0800461 }
462 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700463
Tao Bao20c581e2016-12-28 20:55:51 -0800464 int status;
465 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700466
467 finish_log_temperature.notify_one();
468 temperature_logger.join();
469
Tao Bao20c581e2016-12-28 20:55:51 -0800470 if (retry_update) {
471 return INSTALL_RETRY;
472 }
473 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
474 LOG(ERROR) << "Error in " << path << " (Status " << WEXITSTATUS(status) << ")";
475 return INSTALL_ERROR;
476 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700477
Tao Bao20c581e2016-12-28 20:55:51 -0800478 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700479}
480
Tao Bao1d866052017-04-10 16:55:57 -0700481// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
482// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
483// package.
484bool verify_package_compatibility(ZipArchiveHandle package_zip) {
485 LOG(INFO) << "Verifying package compatibility...";
486
487 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
488 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
489 ZipEntry compatibility_entry;
490 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
491 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
492 return true;
493 }
494
495 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
496 int32_t ret;
497 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
498 reinterpret_cast<uint8_t*>(&zip_content[0]),
499 compatibility_entry.uncompressed_length)) != 0) {
500 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
501 return false;
502 }
503
504 ZipArchiveHandle zip_handle;
505 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
506 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
507 if (ret != 0) {
508 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
509 return false;
510 }
511
512 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
513 void* cookie;
514 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
515 if (ret != 0) {
516 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
517 CloseArchive(zip_handle);
518 return false;
519 }
520 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
521
522 std::vector<std::string> compatibility_info;
523 ZipEntry info_entry;
524 ZipString info_name;
525 while (Next(cookie, &info_entry, &info_name) == 0) {
526 std::string content(info_entry.uncompressed_length, '\0');
527 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
528 info_entry.uncompressed_length);
529 if (ret != 0) {
530 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
531 CloseArchive(zip_handle);
532 return false;
533 }
534 compatibility_info.emplace_back(std::move(content));
535 }
Tao Bao1d866052017-04-10 16:55:57 -0700536 CloseArchive(zip_handle);
537
538 // TODO(b/36814503): Enable the actual verification when VintfObject::CheckCompatibility() lands.
539 // VintfObject::CheckCompatibility returns zero on success.
540 // return (android::vintf::VintfObject::CheckCompatibility(compatibility_info, true) == 0);
541 return true;
542}
543
Doug Zongker469243e2011-04-12 09:28:10 -0700544static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700545really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700546 std::vector<std::string>& log_buffer, int retry_count, int* max_temperature)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800547{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700548 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700549 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700550 // Give verification half the progress bar...
551 ui->SetProgressType(RecoveryUI::DETERMINATE);
552 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tianjie Xuc21edd42016-08-05 18:00:04 -0700553 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800554
Doug Zongker99916f02014-01-13 14:16:58 -0800555 // Map the update package into memory.
556 ui->Print("Opening update package...\n");
557
Doug Zongker075ad802014-06-26 15:35:51 -0700558 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800559 if (path[0] == '@') {
560 ensure_path_mounted(path+1);
561 } else {
562 ensure_path_mounted(path);
563 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800564 }
565
Doug Zongker99916f02014-01-13 14:16:58 -0800566 MemMapping map;
567 if (sysMapFile(path, &map) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700568 LOG(ERROR) << "failed to map file";
Doug Zongker99916f02014-01-13 14:16:58 -0800569 return INSTALL_CORRUPT;
570 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800571
Elliott Hughes8febafa2016-04-13 16:39:56 -0700572 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700573 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700574 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800575 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700576 return INSTALL_CORRUPT;
577 }
578
Elliott Hughes8febafa2016-04-13 16:39:56 -0700579 // Try to open the package.
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700580 ZipArchiveHandle zip;
Tianjie Xu8176cf22016-10-18 14:13:07 -0700581 int err = OpenArchiveFromMemory(map.addr, map.length, path, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800582 if (err != 0) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700583 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
Tianjie Xu16255832016-04-30 11:49:59 -0700584 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
585
Doug Zongker99916f02014-01-13 14:16:58 -0800586 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700587 CloseArchive(zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800588 return INSTALL_CORRUPT;
589 }
590
Tao Bao1d866052017-04-10 16:55:57 -0700591 // Additionally verify the compatibility of the package.
592 if (!verify_package_compatibility(zip)) {
593 LOG(ERROR) << "Failed to verify package compatibility";
594 log_buffer.push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
595 sysReleaseMap(&map);
596 CloseArchive(zip);
597 return INSTALL_CORRUPT;
598 }
599
Elliott Hughes8febafa2016-04-13 16:39:56 -0700600 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700601 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700602 if (retry_count > 0) {
603 ui->Print("Retry attempt: %d\n", retry_count);
604 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700605 ui->SetEnableReboot(false);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700606 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
Doug Zongkerc704e062014-05-23 08:40:35 -0700607 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700608 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800609
610 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700611 CloseArchive(zip);
Doug Zongker99916f02014-01-13 14:16:58 -0800612 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800613}
Doug Zongker469243e2011-04-12 09:28:10 -0700614
Tao Baof8119fb2017-04-18 21:35:12 -0700615int install_package(const char* path, bool* wipe_cache, const char* install_file, bool needs_mount,
616 int retry_count) {
617 modified_flash = true;
618 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700619
Tao Baof8119fb2017-04-18 21:35:12 -0700620 int start_temperature = GetMaxValueFromThermalZone();
621 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700622
Tao Baof8119fb2017-04-18 21:35:12 -0700623 int result;
624 std::vector<std::string> log_buffer;
625 if (setup_install_mounts() != 0) {
626 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
627 result = INSTALL_ERROR;
628 } else {
629 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count,
630 &max_temperature);
631 }
632
633 // Measure the time spent to apply OTA update in seconds.
634 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
635 int time_total = static_cast<int>(duration.count());
636
637 bool has_cache = volume_for_path("/cache") != nullptr;
638 // Skip logging the uncrypt_status on devices without /cache.
639 if (has_cache) {
640 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
641 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
642 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700643 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700644 std::string uncrypt_status;
645 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
646 PLOG(WARNING) << "failed to read uncrypt status";
647 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
648 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700649 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700650 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700651 }
Doug Zongker469243e2011-04-12 09:28:10 -0700652 }
Tao Baof8119fb2017-04-18 21:35:12 -0700653 }
Tao Baobadaac42016-09-26 11:39:14 -0700654
Tao Baof8119fb2017-04-18 21:35:12 -0700655 // The first two lines need to be the package name and install result.
656 std::vector<std::string> log_header = {
657 path,
658 result == INSTALL_SUCCESS ? "1" : "0",
659 "time_total: " + std::to_string(time_total),
660 "retry: " + std::to_string(retry_count),
661 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700662
Tao Baof8119fb2017-04-18 21:35:12 -0700663 int end_temperature = GetMaxValueFromThermalZone();
664 max_temperature = std::max(end_temperature, max_temperature);
665 if (start_temperature > 0) {
666 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
667 }
668 if (end_temperature > 0) {
669 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
670 }
671 if (max_temperature > 0) {
672 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
673 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700674
Tao Baof8119fb2017-04-18 21:35:12 -0700675 std::string log_content =
676 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
677 if (!android::base::WriteStringToFile(log_content, install_file)) {
678 PLOG(ERROR) << "failed to write " << install_file;
679 }
Tao Baobadaac42016-09-26 11:39:14 -0700680
Tao Baof8119fb2017-04-18 21:35:12 -0700681 // Write a copy into last_log.
682 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700683
Tao Baof8119fb2017-04-18 21:35:12 -0700684 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700685}
Yabin Cui6faf0262016-06-09 14:09:39 -0700686
687bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700688 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700689 std::vector<Certificate> loadedKeys;
690 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
691 LOG(ERROR) << "Failed to load keys";
692 return false;
693 }
694 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700695
Tao Bao5e535012017-03-16 17:37:38 -0700696 // Verify package.
697 ui->Print("Verifying update package...\n");
698 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700699 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700700 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
701 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
702 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
703 if (err != VERIFY_SUCCESS) {
704 LOG(ERROR) << "Signature verification failed";
705 LOG(ERROR) << "error: " << kZipVerificationFailure;
706 return false;
707 }
708 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700709}