blob: 2a647b1a719ed5f3465dafd98c9b08c6718c69ad [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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080054#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070055#include "ui.h"
Mattias Nissler452df6d2016-04-04 16:17:01 +020056#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080057
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070058using namespace std::chrono_literals;
59
Tianjie Xub0ddae52016-06-08 14:30:04 -070060static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080061
Doug Zongker74406302011-10-28 15:13:10 -070062// Default allocation of progress bar segments to operations
Tao Bao20c581e2016-12-28 20:55:51 -080063static constexpr int VERIFICATION_PROGRESS_TIME = 60;
64static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
Doug Zongker74406302011-10-28 15:13:10 -070065
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -070066static std::condition_variable finish_log_temperature;
67
Tianjie Xub0ddae52016-06-08 14:30:04 -070068// This function parses and returns the build.version.incremental
Chih-Hung Hsieh8b238112016-08-26 14:54:29 -070069static int parse_build_number(const std::string& str) {
70 size_t pos = str.find('=');
Tianjie Xub0ddae52016-06-08 14:30:04 -070071 if (pos != std::string::npos) {
72 std::string num_string = android::base::Trim(str.substr(pos+1));
73 int build_number;
74 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
75 return build_number;
76 }
77 }
78
Tianjie Xuc21edd42016-08-05 18:00:04 -070079 LOG(ERROR) << "Failed to parse build number in " << str;
Tianjie Xub0ddae52016-06-08 14:30:04 -070080 return -1;
81}
82
Tianjie Xu8176cf22016-10-18 14:13:07 -070083bool read_metadata_from_package(ZipArchiveHandle zip, std::string* meta_data) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070084 ZipString metadata_path(METADATA_PATH);
85 ZipEntry meta_entry;
Tianjie Xu8176cf22016-10-18 14:13:07 -070086 if (meta_data == nullptr) {
87 LOG(ERROR) << "string* meta_data can't be nullptr";
88 return false;
89 }
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070090 if (FindEntry(zip, metadata_path, &meta_entry) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -070091 LOG(ERROR) << "Failed to find " << METADATA_PATH << " in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -070092 return false;
Tianjie Xub0ddae52016-06-08 14:30:04 -070093 }
94
Tianjie Xu8176cf22016-10-18 14:13:07 -070095 meta_data->resize(meta_entry.uncompressed_length, '\0');
96 if (ExtractToMemory(zip, &meta_entry, reinterpret_cast<uint8_t*>(&(*meta_data)[0]),
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070097 meta_entry.uncompressed_length) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -070098 LOG(ERROR) << "Failed to read metadata in update package";
Yabin Cui6faf0262016-06-09 14:09:39 -070099 return false;
100 }
101 return true;
102}
103
104// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Tianjie Xu8176cf22016-10-18 14:13:07 -0700105static void read_source_target_build(ZipArchiveHandle zip, std::vector<std::string>& log_buffer) {
Yabin Cui6faf0262016-06-09 14:09:39 -0700106 std::string meta_data;
107 if (!read_metadata_from_package(zip, &meta_data)) {
Tianjie Xub0ddae52016-06-08 14:30:04 -0700108 return;
109 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700110 // Examples of the pre-build and post-build strings in metadata:
111 // pre-build-incremental=2943039
112 // post-build-incremental=2951741
113 std::vector<std::string> lines = android::base::Split(meta_data, "\n");
114 for (const std::string& line : lines) {
115 std::string str = android::base::Trim(line);
116 if (android::base::StartsWith(str, "pre-build-incremental")){
117 int source_build = parse_build_number(str);
118 if (source_build != -1) {
119 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
120 source_build));
121 }
122 } else if (android::base::StartsWith(str, "post-build-incremental")) {
123 int target_build = parse_build_number(str);
124 if (target_build != -1) {
125 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
126 target_build));
127 }
128 }
129 }
130}
131
Tao Baobc4b1fe2017-04-17 16:46:05 -0700132// Extract the update binary from the open zip archive |zip| located at |path| and store into |cmd|
133// the command line that should be called. The |status_fd| is the file descriptor the child process
134// should use to report back the progress of the update.
135int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
136 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700137
Alex Deymo4344d632016-08-03 21:03:53 -0700138#ifdef AB_OTA_UPDATER
139
140// Parses the metadata of the OTA package in |zip| and checks whether we are
141// allowed to accept this A/B package. Downgrading is not allowed unless
142// explicitly enabled in the package and only for incremental packages.
Tao Baoefc35592017-01-08 22:45:47 -0800143static int check_newer_ab_build(ZipArchiveHandle zip) {
144 std::string metadata_str;
145 if (!read_metadata_from_package(zip, &metadata_str)) {
146 return INSTALL_CORRUPT;
147 }
148 std::map<std::string, std::string> metadata;
149 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
150 size_t eq = line.find('=');
151 if (eq != std::string::npos) {
152 metadata[line.substr(0, eq)] = line.substr(eq + 1);
Alex Deymo4344d632016-08-03 21:03:53 -0700153 }
Tao Baoefc35592017-01-08 22:45:47 -0800154 }
Alex Deymo4344d632016-08-03 21:03:53 -0700155
Tao Baoefc35592017-01-08 22:45:47 -0800156 std::string value = android::base::GetProperty("ro.product.device", "");
157 const std::string& pkg_device = metadata["pre-device"];
158 if (pkg_device != value || pkg_device.empty()) {
159 LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << value;
160 return INSTALL_ERROR;
161 }
Alex Deymo4344d632016-08-03 21:03:53 -0700162
Tao Baoefc35592017-01-08 22:45:47 -0800163 // We allow the package to not have any serialno, but if it has a non-empty
164 // value it should match.
165 value = android::base::GetProperty("ro.serialno", "");
166 const std::string& pkg_serial_no = metadata["serialno"];
167 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
168 LOG(ERROR) << "Package is for serial " << pkg_serial_no;
169 return INSTALL_ERROR;
170 }
Alex Deymo4344d632016-08-03 21:03:53 -0700171
Tao Baoefc35592017-01-08 22:45:47 -0800172 if (metadata["ota-type"] != "AB") {
173 LOG(ERROR) << "Package is not A/B";
174 return INSTALL_ERROR;
175 }
Alex Deymo4344d632016-08-03 21:03:53 -0700176
Tao Baoefc35592017-01-08 22:45:47 -0800177 // Incremental updates should match the current build.
178 value = android::base::GetProperty("ro.build.version.incremental", "");
179 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
180 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
181 LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " << value;
182 return INSTALL_ERROR;
183 }
Alex Deymo4344d632016-08-03 21:03:53 -0700184
Tao Baoefc35592017-01-08 22:45:47 -0800185 value = android::base::GetProperty("ro.build.fingerprint", "");
186 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
187 if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != value) {
188 LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
189 << value;
190 return INSTALL_ERROR;
191 }
Alex Deymo4344d632016-08-03 21:03:53 -0700192
Tao Baoefc35592017-01-08 22:45:47 -0800193 // Check for downgrade version.
194 int64_t build_timestamp =
195 android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
196 int64_t pkg_post_timestamp = 0;
197 // We allow to full update to the same version we are running, in case there
198 // is a problem with the current copy of that version.
199 if (metadata["post-timestamp"].empty() ||
200 !android::base::ParseInt(metadata["post-timestamp"].c_str(), &pkg_post_timestamp) ||
201 pkg_post_timestamp < build_timestamp) {
202 if (metadata["ota-downgrade"] != "yes") {
203 LOG(ERROR) << "Update package is older than the current build, expected a build "
204 "newer than timestamp "
205 << build_timestamp << " but package has timestamp " << pkg_post_timestamp
206 << " and downgrade not allowed.";
207 return INSTALL_ERROR;
208 }
209 if (pkg_pre_build_fingerprint.empty()) {
210 LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
211 return INSTALL_ERROR;
212 }
213 }
214
215 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700216}
217
Tao Baobc4b1fe2017-04-17 16:46:05 -0700218int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
219 int status_fd, std::vector<std::string>* cmd) {
220 CHECK(cmd != nullptr);
221 int ret = check_newer_ab_build(zip);
222 if (ret != 0) {
223 return ret;
224 }
Alex Deymo4344d632016-08-03 21:03:53 -0700225
Tao Baobc4b1fe2017-04-17 16:46:05 -0700226 // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
227 // in the zip file.
228 static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
229 ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES);
230 ZipEntry properties_entry;
231 if (FindEntry(zip, property_name, &properties_entry) != 0) {
232 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
233 return INSTALL_CORRUPT;
234 }
235 uint32_t properties_entry_length = properties_entry.uncompressed_length;
236 std::vector<uint8_t> payload_properties(properties_entry_length);
237 int32_t err =
238 ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
239 if (err != 0) {
240 LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
241 return INSTALL_CORRUPT;
242 }
Alex Deymo4344d632016-08-03 21:03:53 -0700243
Tao Baobc4b1fe2017-04-17 16:46:05 -0700244 static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
245 ZipString payload_name(AB_OTA_PAYLOAD);
246 ZipEntry payload_entry;
247 if (FindEntry(zip, payload_name, &payload_entry) != 0) {
248 LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
249 return INSTALL_CORRUPT;
250 }
251 long payload_offset = payload_entry.offset;
252 *cmd = {
253 "/sbin/update_engine_sideload",
254 "--payload=file://" + path,
255 android::base::StringPrintf("--offset=%ld", payload_offset),
256 "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
257 android::base::StringPrintf("--status_fd=%d", status_fd),
258 };
259 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700260}
261
262#else // !AB_OTA_UPDATER
263
Tao Baobc4b1fe2017-04-17 16:46:05 -0700264int update_binary_command(const std::string& path, ZipArchiveHandle zip, int retry_count,
265 int status_fd, std::vector<std::string>* cmd) {
266 CHECK(cmd != nullptr);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700267
Tao Baobc4b1fe2017-04-17 16:46:05 -0700268 // On traditional updates we extract the update binary from the package.
269 static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
270 ZipString binary_name(UPDATE_BINARY_NAME);
271 ZipEntry binary_entry;
272 if (FindEntry(zip, binary_name, &binary_entry) != 0) {
273 LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
274 return INSTALL_CORRUPT;
275 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700276
Tao Baobc4b1fe2017-04-17 16:46:05 -0700277 const char* binary = "/tmp/update_binary";
278 unlink(binary);
279 int fd = creat(binary, 0755);
280 if (fd == -1) {
281 PLOG(ERROR) << "Failed to create " << binary;
282 return INSTALL_ERROR;
283 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700284
Tao Baobc4b1fe2017-04-17 16:46:05 -0700285 int32_t error = ExtractEntryToFile(zip, &binary_entry, fd);
286 close(fd);
287 if (error != 0) {
288 LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
289 return INSTALL_ERROR;
290 }
291
292 *cmd = {
293 binary,
294 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
295 std::to_string(status_fd),
296 path,
297 };
298 if (retry_count > 0) {
299 cmd->push_back("retry");
300 }
301 return 0;
Alex Deymo4344d632016-08-03 21:03:53 -0700302}
303#endif // !AB_OTA_UPDATER
304
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700305static void log_max_temperature(int* max_temperature) {
306 CHECK(max_temperature != nullptr);
307 std::mutex mtx;
308 std::unique_lock<std::mutex> lck(mtx);
309 while (finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
310 *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
311 }
312}
313
Alex Deymo4344d632016-08-03 21:03:53 -0700314// If the package contains an update binary, extract it and run it.
Tao Bao20c581e2016-12-28 20:55:51 -0800315static int try_update_binary(const char* path, ZipArchiveHandle zip, bool* wipe_cache,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700316 std::vector<std::string>& log_buffer, int retry_count,
317 int* max_temperature) {
Tao Bao20c581e2016-12-28 20:55:51 -0800318 read_source_target_build(zip, log_buffer);
Alex Deymo4344d632016-08-03 21:03:53 -0700319
Tao Bao20c581e2016-12-28 20:55:51 -0800320 int pipefd[2];
321 pipe(pipefd);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700322
Tao Bao20c581e2016-12-28 20:55:51 -0800323 std::vector<std::string> args;
324 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
325 if (ret) {
326 close(pipefd[0]);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700327 close(pipefd[1]);
Tao Bao20c581e2016-12-28 20:55:51 -0800328 return ret;
329 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700330
Tao Bao20c581e2016-12-28 20:55:51 -0800331 // When executing the update binary contained in the package, the
332 // arguments passed are:
333 //
334 // - the version number for this interface
335 //
336 // - an FD to which the program can write in order to update the
337 // progress bar. The program can write single-line commands:
338 //
339 // progress <frac> <secs>
340 // fill up the next <frac> part of of the progress bar
341 // over <secs> seconds. If <secs> is zero, use
342 // set_progress commands to manually control the
343 // progress of this segment of the bar.
344 //
345 // set_progress <frac>
346 // <frac> should be between 0.0 and 1.0; sets the
347 // progress bar within the segment defined by the most
348 // recent progress command.
349 //
350 // ui_print <string>
351 // display <string> on the screen.
352 //
353 // wipe_cache
354 // a wipe of cache will be performed following a successful
355 // installation.
356 //
357 // clear_display
358 // turn off the text display.
359 //
360 // enable_reboot
361 // packages can explicitly request that they want the user
362 // to be able to reboot during installation (useful for
363 // debugging packages that don't exit).
364 //
365 // retry_update
366 // updater encounters some issue during the update. It requests
367 // a reboot to retry the same package automatically.
368 //
369 // log <string>
370 // updater requests logging the string (e.g. cause of the
371 // failure).
372 //
373 // - the name of the package zip file.
374 //
375 // - an optional argument "retry" if this update is a retry of a failed
376 // update attempt.
377 //
Doug Zongkerd0181b82011-10-19 10:51:12 -0700378
Tao Bao20c581e2016-12-28 20:55:51 -0800379 // Convert the vector to a NULL-terminated char* array suitable for execv.
380 const char* chr_args[args.size() + 1];
381 chr_args[args.size()] = nullptr;
382 for (size_t i = 0; i < args.size(); i++) {
383 chr_args[i] = args[i].c_str();
384 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700385
Tao Bao20c581e2016-12-28 20:55:51 -0800386 pid_t pid = fork();
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700387
Tao Bao20c581e2016-12-28 20:55:51 -0800388 if (pid == -1) {
389 close(pipefd[0]);
390 close(pipefd[1]);
391 PLOG(ERROR) << "Failed to fork update binary";
392 return INSTALL_ERROR;
393 }
394
395 if (pid == 0) {
396 umask(022);
397 close(pipefd[0]);
398 execv(chr_args[0], const_cast<char**>(chr_args));
Tianjie Xuab1abae2017-01-30 16:48:52 -0800399 // Bug: 34769056
400 // We shouldn't use LOG/PLOG in the forked process, since they may cause
401 // the child process to hang. This deadlock results from an improperly
402 // copied mutex in the ui functions.
403 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Tao Bao3da88012017-02-03 13:09:23 -0800404 _exit(EXIT_FAILURE);
Tao Bao20c581e2016-12-28 20:55:51 -0800405 }
406 close(pipefd[1]);
407
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700408 std::thread temperature_logger(log_max_temperature, max_temperature);
409
Tao Bao20c581e2016-12-28 20:55:51 -0800410 *wipe_cache = false;
411 bool retry_update = false;
412
413 char buffer[1024];
414 FILE* from_child = fdopen(pipefd[0], "r");
415 while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
416 std::string line(buffer);
417 size_t space = line.find_first_of(" \n");
418 std::string command(line.substr(0, space));
419 if (command.empty()) continue;
420
421 // Get rid of the leading and trailing space and/or newline.
422 std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
423
424 if (command == "progress") {
425 std::vector<std::string> tokens = android::base::Split(args, " ");
426 double fraction;
427 int seconds;
428 if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
429 android::base::ParseInt(tokens[1], &seconds)) {
430 ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
431 } else {
432 LOG(ERROR) << "invalid \"progress\" parameters: " << line;
433 }
434 } else if (command == "set_progress") {
435 std::vector<std::string> tokens = android::base::Split(args, " ");
436 double fraction;
437 if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
438 ui->SetProgress(fraction);
439 } else {
440 LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
441 }
442 } else if (command == "ui_print") {
Tao Baof0136422017-01-21 13:03:25 -0800443 ui->PrintOnScreenOnly("%s\n", args.c_str());
Tao Bao20c581e2016-12-28 20:55:51 -0800444 fflush(stdout);
445 } else if (command == "wipe_cache") {
446 *wipe_cache = true;
447 } else if (command == "clear_display") {
448 ui->SetBackground(RecoveryUI::NONE);
449 } else if (command == "enable_reboot") {
450 // packages can explicitly request that they want the user
451 // to be able to reboot during installation (useful for
452 // debugging packages that don't exit).
453 ui->SetEnableReboot(true);
454 } else if (command == "retry_update") {
455 retry_update = true;
456 } else if (command == "log") {
457 if (!args.empty()) {
458 // Save the logging request from updater and write to last_install later.
459 log_buffer.push_back(args);
460 } else {
461 LOG(ERROR) << "invalid \"log\" parameters: " << line;
462 }
463 } else {
464 LOG(ERROR) << "unknown command [" << command << "]";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700465 }
Tao Bao20c581e2016-12-28 20:55:51 -0800466 }
467 fclose(from_child);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700468
Tao Bao20c581e2016-12-28 20:55:51 -0800469 int status;
470 waitpid(pid, &status, 0);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700471
472 finish_log_temperature.notify_one();
473 temperature_logger.join();
474
Tao Bao20c581e2016-12-28 20:55:51 -0800475 if (retry_update) {
476 return INSTALL_RETRY;
477 }
478 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
479 LOG(ERROR) << "Error in " << path << " (Status " << WEXITSTATUS(status) << ")";
480 return INSTALL_ERROR;
481 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700482
Tao Bao20c581e2016-12-28 20:55:51 -0800483 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700484}
485
Tao Bao1d866052017-04-10 16:55:57 -0700486// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
487// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
488// package.
489bool verify_package_compatibility(ZipArchiveHandle package_zip) {
490 LOG(INFO) << "Verifying package compatibility...";
491
492 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
493 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
494 ZipEntry compatibility_entry;
495 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
496 LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry";
497 return true;
498 }
499
500 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
501 int32_t ret;
502 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
503 reinterpret_cast<uint8_t*>(&zip_content[0]),
504 compatibility_entry.uncompressed_length)) != 0) {
505 LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret);
506 return false;
507 }
508
509 ZipArchiveHandle zip_handle;
510 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
511 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
512 if (ret != 0) {
513 LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret);
514 return false;
515 }
516
517 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
518 void* cookie;
519 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
520 if (ret != 0) {
521 LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret);
522 CloseArchive(zip_handle);
523 return false;
524 }
525 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
526
527 std::vector<std::string> compatibility_info;
528 ZipEntry info_entry;
529 ZipString info_name;
530 while (Next(cookie, &info_entry, &info_name) == 0) {
531 std::string content(info_entry.uncompressed_length, '\0');
532 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
533 info_entry.uncompressed_length);
534 if (ret != 0) {
535 LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret);
536 CloseArchive(zip_handle);
537 return false;
538 }
539 compatibility_info.emplace_back(std::move(content));
540 }
Tao Bao1d866052017-04-10 16:55:57 -0700541 CloseArchive(zip_handle);
542
Tao Bao919d2c92017-04-10 16:55:57 -0700543 // VintfObjectRecovery::CheckCompatibility returns zero on success.
544 std::string err;
545 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
546 if (result == 0) {
547 return true;
548 }
549
550 LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err;
551 return false;
Tao Bao1d866052017-04-10 16:55:57 -0700552}
553
Doug Zongker469243e2011-04-12 09:28:10 -0700554static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700555really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700556 std::vector<std::string>& log_buffer, int retry_count, int* max_temperature)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800557{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700558 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700559 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700560 // Give verification half the progress bar...
561 ui->SetProgressType(RecoveryUI::DETERMINATE);
562 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Tianjie Xuc21edd42016-08-05 18:00:04 -0700563 LOG(INFO) << "Update location: " << path;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800564
Doug Zongker99916f02014-01-13 14:16:58 -0800565 // Map the update package into memory.
566 ui->Print("Opening update package...\n");
567
Doug Zongker075ad802014-06-26 15:35:51 -0700568 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800569 if (path[0] == '@') {
570 ensure_path_mounted(path+1);
571 } else {
572 ensure_path_mounted(path);
573 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800574 }
575
Doug Zongker99916f02014-01-13 14:16:58 -0800576 MemMapping map;
577 if (sysMapFile(path, &map) != 0) {
Tianjie Xuc21edd42016-08-05 18:00:04 -0700578 LOG(ERROR) << "failed to map file";
Doug Zongker99916f02014-01-13 14:16:58 -0800579 return INSTALL_CORRUPT;
580 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800581
Elliott Hughes8febafa2016-04-13 16:39:56 -0700582 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700583 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700584 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800585 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700586 return INSTALL_CORRUPT;
587 }
588
Elliott Hughes8febafa2016-04-13 16:39:56 -0700589 // Try to open the package.
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700590 ZipArchiveHandle zip;
Tianjie Xu8176cf22016-10-18 14:13:07 -0700591 int err = OpenArchiveFromMemory(map.addr, map.length, path, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800592 if (err != 0) {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700593 LOG(ERROR) << "Can't open " << path << " : " << ErrorCodeString(err);
Tianjie Xu16255832016-04-30 11:49:59 -0700594 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
595
Doug Zongker99916f02014-01-13 14:16:58 -0800596 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700597 CloseArchive(zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800598 return INSTALL_CORRUPT;
599 }
600
Tao Bao1d866052017-04-10 16:55:57 -0700601 // Additionally verify the compatibility of the package.
602 if (!verify_package_compatibility(zip)) {
Tao Bao1d866052017-04-10 16:55:57 -0700603 log_buffer.push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure));
604 sysReleaseMap(&map);
605 CloseArchive(zip);
606 return INSTALL_CORRUPT;
607 }
608
Elliott Hughes8febafa2016-04-13 16:39:56 -0700609 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700610 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700611 if (retry_count > 0) {
612 ui->Print("Retry attempt: %d\n", retry_count);
613 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700614 ui->SetEnableReboot(false);
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700615 int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature);
Doug Zongkerc704e062014-05-23 08:40:35 -0700616 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700617 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800618
619 sysReleaseMap(&map);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700620 CloseArchive(zip);
Doug Zongker99916f02014-01-13 14:16:58 -0800621 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800622}
Doug Zongker469243e2011-04-12 09:28:10 -0700623
Tao Baof8119fb2017-04-18 21:35:12 -0700624int install_package(const char* path, bool* wipe_cache, const char* install_file, bool needs_mount,
625 int retry_count) {
626 modified_flash = true;
627 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700628
Tao Baof8119fb2017-04-18 21:35:12 -0700629 int start_temperature = GetMaxValueFromThermalZone();
630 int max_temperature = start_temperature;
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700631
Tao Baof8119fb2017-04-18 21:35:12 -0700632 int result;
633 std::vector<std::string> log_buffer;
634 if (setup_install_mounts() != 0) {
635 LOG(ERROR) << "failed to set up expected mounts for install; aborting";
636 result = INSTALL_ERROR;
637 } else {
638 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count,
639 &max_temperature);
640 }
641
642 // Measure the time spent to apply OTA update in seconds.
643 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
644 int time_total = static_cast<int>(duration.count());
645
646 bool has_cache = volume_for_path("/cache") != nullptr;
647 // Skip logging the uncrypt_status on devices without /cache.
648 if (has_cache) {
649 static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
650 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
651 LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700652 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700653 std::string uncrypt_status;
654 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
655 PLOG(WARNING) << "failed to read uncrypt status";
656 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
657 LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
Tianjie Xua2867782017-03-24 14:13:56 -0700658 } else {
Tao Baof8119fb2017-04-18 21:35:12 -0700659 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xua2867782017-03-24 14:13:56 -0700660 }
Doug Zongker469243e2011-04-12 09:28:10 -0700661 }
Tao Baof8119fb2017-04-18 21:35:12 -0700662 }
Tao Baobadaac42016-09-26 11:39:14 -0700663
Tao Baof8119fb2017-04-18 21:35:12 -0700664 // The first two lines need to be the package name and install result.
665 std::vector<std::string> log_header = {
666 path,
667 result == INSTALL_SUCCESS ? "1" : "0",
668 "time_total: " + std::to_string(time_total),
669 "retry: " + std::to_string(retry_count),
670 };
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700671
Tao Baof8119fb2017-04-18 21:35:12 -0700672 int end_temperature = GetMaxValueFromThermalZone();
673 max_temperature = std::max(end_temperature, max_temperature);
674 if (start_temperature > 0) {
675 log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
676 }
677 if (end_temperature > 0) {
678 log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
679 }
680 if (max_temperature > 0) {
681 log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
682 }
Tianjie Xu3ee2b9d2017-03-27 14:12:26 -0700683
Tao Baof8119fb2017-04-18 21:35:12 -0700684 std::string log_content =
685 android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
686 if (!android::base::WriteStringToFile(log_content, install_file)) {
687 PLOG(ERROR) << "failed to write " << install_file;
688 }
Tao Baobadaac42016-09-26 11:39:14 -0700689
Tao Baof8119fb2017-04-18 21:35:12 -0700690 // Write a copy into last_log.
691 LOG(INFO) << log_content;
Tao Baobadaac42016-09-26 11:39:14 -0700692
Tao Baof8119fb2017-04-18 21:35:12 -0700693 return result;
Doug Zongker469243e2011-04-12 09:28:10 -0700694}
Yabin Cui6faf0262016-06-09 14:09:39 -0700695
696bool verify_package(const unsigned char* package_data, size_t package_size) {
Tao Baof8119fb2017-04-18 21:35:12 -0700697 static constexpr const char* PUBLIC_KEYS_FILE = "/res/keys";
Tao Bao5e535012017-03-16 17:37:38 -0700698 std::vector<Certificate> loadedKeys;
699 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
700 LOG(ERROR) << "Failed to load keys";
701 return false;
702 }
703 LOG(INFO) << loadedKeys.size() << " key(s) loaded from " << PUBLIC_KEYS_FILE;
Yabin Cui6faf0262016-06-09 14:09:39 -0700704
Tao Bao5e535012017-03-16 17:37:38 -0700705 // Verify package.
706 ui->Print("Verifying update package...\n");
707 auto t0 = std::chrono::system_clock::now();
Tao Bao76fdb242017-03-20 17:09:13 -0700708 int err = verify_file(package_data, package_size, loadedKeys,
Tao Bao5e535012017-03-16 17:37:38 -0700709 std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
710 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
711 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
712 if (err != VERIFY_SUCCESS) {
713 LOG(ERROR) << "Signature verification failed";
714 LOG(ERROR) << "error: " << kZipVerificationFailure;
715 return false;
716 }
717 return true;
Yabin Cui6faf0262016-06-09 14:09:39 -0700718}