blob: e144d9b29f1a4386c9870fe753d3ae3871d9ab37 [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
Doug Zongkerb2ee9202009-06-04 10:24:53 -070017#include <ctype.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080018#include <errno.h>
19#include <fcntl.h>
Alex Deymo53c107f2016-08-12 13:43:04 -070020#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080021#include <limits.h>
Elliott Hughes26dbad22015-01-28 12:09:05 -080022#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080023#include <sys/stat.h>
Doug Zongkerb2ee9202009-06-04 10:24:53 -070024#include <sys/wait.h>
25#include <unistd.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080026
Elliott Hughes8febafa2016-04-13 16:39:56 -070027#include <chrono>
Alex Deymo4344d632016-08-03 21:03:53 -070028#include <limits>
29#include <map>
Tianjie Xudd874b12016-05-13 12:13:15 -070030#include <string>
Tao Bao71e3e092016-02-02 14:02:27 -080031#include <vector>
32
Tianjie Xue16e7992016-09-09 10:55:44 -070033#include <android-base/file.h>
Tianjie Xub0ddae52016-06-08 14:30:04 -070034#include <android-base/parseint.h>
Tianjie Xu16255832016-04-30 11:49:59 -070035#include <android-base/stringprintf.h>
36#include <android-base/strings.h>
Alex Deymo4344d632016-08-03 21:03:53 -070037#include <cutils/properties.h>
Tianjie Xu16255832016-04-30 11:49:59 -070038
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080039#include "common.h"
Tianjie Xu16255832016-04-30 11:49:59 -070040#include "error_code.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080041#include "install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080042#include "minui/minui.h"
43#include "minzip/SysUtil.h"
44#include "minzip/Zip.h"
45#include "mtdutils/mounts.h"
46#include "mtdutils/mtdutils.h"
47#include "roots.h"
Doug Zongker10e418d2011-10-28 10:33:05 -070048#include "ui.h"
Elliott Hughes8febafa2016-04-13 16:39:56 -070049#include "verifier.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080050
Doug Zongker74406302011-10-28 15:13:10 -070051extern RecoveryUI* ui;
52
Doug Zongkerb2ee9202009-06-04 10:24:53 -070053#define ASSUMED_UPDATE_BINARY_NAME "META-INF/com/google/android/update-binary"
Alex Deymo4344d632016-08-03 21:03:53 -070054static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
55static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
Doug Zongkerd1b19b92009-04-01 15:48:46 -070056#define PUBLIC_KEYS_FILE "/res/keys"
Tianjie Xub0ddae52016-06-08 14:30:04 -070057static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
Tianjie Xue16e7992016-09-09 10:55:44 -070058static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080059
Doug Zongker74406302011-10-28 15:13:10 -070060// Default allocation of progress bar segments to operations
61static const int VERIFICATION_PROGRESS_TIME = 60;
62static const float VERIFICATION_PROGRESS_FRACTION = 0.25;
63static const float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
64static const float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;
65
Tianjie Xub0ddae52016-06-08 14:30:04 -070066// This function parses and returns the build.version.incremental
67static int parse_build_number(std::string str) {
68 size_t pos = str.find("=");
69 if (pos != std::string::npos) {
70 std::string num_string = android::base::Trim(str.substr(pos+1));
71 int build_number;
72 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
73 return build_number;
74 }
75 }
76
77 LOGE("Failed to parse build number in %s.\n", str.c_str());
78 return -1;
79}
80
Yabin Cui6faf0262016-06-09 14:09:39 -070081bool read_metadata_from_package(ZipArchive* zip, std::string* meta_data) {
Tianjie Xub0ddae52016-06-08 14:30:04 -070082 const ZipEntry* meta_entry = mzFindZipEntry(zip, METADATA_PATH);
83 if (meta_entry == nullptr) {
84 LOGE("Failed to find %s in update package.\n", METADATA_PATH);
Yabin Cui6faf0262016-06-09 14:09:39 -070085 return false;
Tianjie Xub0ddae52016-06-08 14:30:04 -070086 }
87
Yabin Cui6faf0262016-06-09 14:09:39 -070088 meta_data->resize(meta_entry->uncompLen, '\0');
89 if (!mzReadZipEntry(zip, meta_entry, &(*meta_data)[0], meta_entry->uncompLen)) {
Tianjie Xub0ddae52016-06-08 14:30:04 -070090 LOGE("Failed to read metadata in update package.\n");
Yabin Cui6faf0262016-06-09 14:09:39 -070091 return false;
92 }
93 return true;
94}
95
96// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
97static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
98 std::string meta_data;
99 if (!read_metadata_from_package(zip, &meta_data)) {
Tianjie Xub0ddae52016-06-08 14:30:04 -0700100 return;
101 }
Tianjie Xub0ddae52016-06-08 14:30:04 -0700102 // Examples of the pre-build and post-build strings in metadata:
103 // pre-build-incremental=2943039
104 // post-build-incremental=2951741
105 std::vector<std::string> lines = android::base::Split(meta_data, "\n");
106 for (const std::string& line : lines) {
107 std::string str = android::base::Trim(line);
108 if (android::base::StartsWith(str, "pre-build-incremental")){
109 int source_build = parse_build_number(str);
110 if (source_build != -1) {
111 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
112 source_build));
113 }
114 } else if (android::base::StartsWith(str, "post-build-incremental")) {
115 int target_build = parse_build_number(str);
116 if (target_build != -1) {
117 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
118 target_build));
119 }
120 }
121 }
122}
123
Alex Deymo4344d632016-08-03 21:03:53 -0700124// Extract the update binary from the open zip archive |zip| located at |path|
125// and store into |cmd| the command line that should be called. The |status_fd|
126// is the file descriptor the child process should use to report back the
127// progress of the update.
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700128static int
Alex Deymo4344d632016-08-03 21:03:53 -0700129update_binary_command(const char* path, ZipArchive* zip, int retry_count,
130 int status_fd, std::vector<std::string>* cmd);
Tianjie Xub0ddae52016-06-08 14:30:04 -0700131
Alex Deymo4344d632016-08-03 21:03:53 -0700132#ifdef AB_OTA_UPDATER
133
134// Parses the metadata of the OTA package in |zip| and checks whether we are
135// allowed to accept this A/B package. Downgrading is not allowed unless
136// explicitly enabled in the package and only for incremental packages.
137static int check_newer_ab_build(ZipArchive* zip)
138{
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);
148 }
149 }
150 char value[PROPERTY_VALUE_MAX];
151
152 property_get("ro.product.device", value, "");
153 const std::string& pkg_device = metadata["pre-device"];
154 if (pkg_device != value || pkg_device.empty()) {
155 LOGE("Package is for product %s but expected %s\n",
156 pkg_device.c_str(), value);
157 return INSTALL_ERROR;
158 }
159
160 // We allow the package to not have any serialno, but if it has a non-empty
161 // value it should match.
162 property_get("ro.serialno", value, "");
163 const std::string& pkg_serial_no = metadata["serialno"];
164 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
165 LOGE("Package is for serial %s\n", pkg_serial_no.c_str());
166 return INSTALL_ERROR;
167 }
168
169 if (metadata["ota-type"] != "AB") {
170 LOGE("Package is not A/B\n");
171 return INSTALL_ERROR;
172 }
173
174 // Incremental updates should match the current build.
175 property_get("ro.build.version.incremental", value, "");
176 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
177 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
178 LOGE("Package is for source build %s but expected %s\n",
179 pkg_pre_build.c_str(), value);
180 return INSTALL_ERROR;
181 }
182 property_get("ro.build.fingerprint", value, "");
183 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
184 if (!pkg_pre_build_fingerprint.empty() &&
185 pkg_pre_build_fingerprint != value) {
186 LOGE("Package is for source build %s but expected %s\n",
187 pkg_pre_build_fingerprint.c_str(), value);
188 return INSTALL_ERROR;
189 }
190
191 // Check for downgrade version.
192 int64_t build_timestampt = property_get_int64(
193 "ro.build.date.utc", std::numeric_limits<int64_t>::max());
194 int64_t pkg_post_timespampt = 0;
195 // We allow to full update to the same version we are running, in case there
196 // is a problem with the current copy of that version.
197 if (metadata["post-timestamp"].empty() ||
198 !android::base::ParseInt(metadata["post-timestamp"].c_str(),
199 &pkg_post_timespampt) ||
200 pkg_post_timespampt < build_timestampt) {
201 if (metadata["ota-downgrade"] != "yes") {
202 LOGE("Update package is older than the current build, expected a "
203 "build newer than timestamp %" PRIu64 " but package has "
204 "timestamp %" PRIu64 " and downgrade not allowed.\n",
205 build_timestampt, pkg_post_timespampt);
206 return INSTALL_ERROR;
207 }
208 if (pkg_pre_build_fingerprint.empty()) {
209 LOGE("Downgrade package must have a pre-build version set, not "
210 "allowed.\n");
211 return INSTALL_ERROR;
212 }
213 }
214
215 return 0;
216}
217
218static int
219update_binary_command(const char* path, ZipArchive* zip, int retry_count,
220 int status_fd, std::vector<std::string>* cmd)
221{
222 int ret = check_newer_ab_build(zip);
223 if (ret) {
224 return ret;
225 }
226
227 // For A/B updates we extract the payload properties to a buffer and obtain
228 // the RAW payload offset in the zip file.
229 const ZipEntry* properties_entry =
230 mzFindZipEntry(zip, AB_OTA_PAYLOAD_PROPERTIES);
231 if (!properties_entry) {
232 LOGE("Can't find %s\n", AB_OTA_PAYLOAD_PROPERTIES);
233 return INSTALL_CORRUPT;
234 }
235 std::vector<unsigned char> payload_properties(
236 mzGetZipEntryUncompLen(properties_entry));
237 if (!mzExtractZipEntryToBuffer(zip, properties_entry,
238 payload_properties.data())) {
239 LOGE("Can't extract %s\n", AB_OTA_PAYLOAD_PROPERTIES);
240 return INSTALL_CORRUPT;
241 }
242
243 const ZipEntry* payload_entry = mzFindZipEntry(zip, AB_OTA_PAYLOAD);
244 if (!payload_entry) {
245 LOGE("Can't find %s\n", AB_OTA_PAYLOAD);
246 return INSTALL_CORRUPT;
247 }
248 long payload_offset = mzGetZipEntryOffset(payload_entry);
249 *cmd = {
250 "/sbin/update_engine_sideload",
251 android::base::StringPrintf("--payload=file://%s", path),
252 android::base::StringPrintf("--offset=%ld", payload_offset),
253 "--headers=" + std::string(payload_properties.begin(),
254 payload_properties.end()),
255 android::base::StringPrintf("--status_fd=%d", status_fd),
256 };
257 return 0;
258}
259
260#else // !AB_OTA_UPDATER
261
262static int
263update_binary_command(const char* path, ZipArchive* zip, int retry_count,
264 int status_fd, std::vector<std::string>* cmd)
265{
266 // On traditional updates we extract the update binary from the package.
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700267 const ZipEntry* binary_entry =
268 mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
269 if (binary_entry == NULL) {
270 return INSTALL_CORRUPT;
271 }
272
Doug Zongker10e418d2011-10-28 10:33:05 -0700273 const char* binary = "/tmp/update_binary";
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700274 unlink(binary);
275 int fd = creat(binary, 0755);
276 if (fd < 0) {
277 LOGE("Can't make %s\n", binary);
Doug Zongkerd0181b82011-10-19 10:51:12 -0700278 return INSTALL_ERROR;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700279 }
280 bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
281 close(fd);
282
283 if (!ok) {
284 LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
Doug Zongkerd0181b82011-10-19 10:51:12 -0700285 return INSTALL_ERROR;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700286 }
287
Alex Deymo4344d632016-08-03 21:03:53 -0700288 *cmd = {
289 binary,
290 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
291 std::to_string(status_fd),
292 path,
293 };
294 if (retry_count > 0)
295 cmd->push_back("retry");
296 return 0;
297}
298#endif // !AB_OTA_UPDATER
299
300// If the package contains an update binary, extract it and run it.
301static int
302try_update_binary(const char* path, ZipArchive* zip, bool* wipe_cache,
303 std::vector<std::string>& log_buffer, int retry_count)
304{
305 read_source_target_build(zip, log_buffer);
306
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700307 int pipefd[2];
308 pipe(pipefd);
309
Alex Deymo4344d632016-08-03 21:03:53 -0700310 std::vector<std::string> args;
311 int ret = update_binary_command(path, zip, retry_count, pipefd[1], &args);
312 mzCloseZipArchive(zip);
313 if (ret) {
314 close(pipefd[0]);
315 close(pipefd[1]);
316 return ret;
317 }
318
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700319 // When executing the update binary contained in the package, the
320 // arguments passed are:
321 //
Doug Zongkerfb2e3af2009-06-17 17:29:40 -0700322 // - the version number for this interface
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700323 //
324 // - an fd to which the program can write in order to update the
325 // progress bar. The program can write single-line commands:
326 //
327 // progress <frac> <secs>
Doug Zongkerfbf3c102009-06-24 09:36:20 -0700328 // fill up the next <frac> part of of the progress bar
329 // over <secs> seconds. If <secs> is zero, use
330 // set_progress commands to manually control the
Tao Baob07e1f32015-04-10 16:14:52 -0700331 // progress of this segment of the bar.
Doug Zongkerfbf3c102009-06-24 09:36:20 -0700332 //
333 // set_progress <frac>
334 // <frac> should be between 0.0 and 1.0; sets the
335 // progress bar within the segment defined by the most
336 // recent progress command.
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700337 //
338 // firmware <"hboot"|"radio"> <filename>
339 // arrange to install the contents of <filename> in the
Doug Zongkere08991e2010-02-02 13:09:52 -0800340 // given partition on reboot.
341 //
342 // (API v2: <filename> may start with "PACKAGE:" to
343 // indicate taking a file from the OTA package.)
344 //
345 // (API v3: this command no longer exists.)
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700346 //
Doug Zongkerd9c9d102009-06-12 12:24:39 -0700347 // ui_print <string>
348 // display <string> on the screen.
349 //
Tao Baob07e1f32015-04-10 16:14:52 -0700350 // wipe_cache
351 // a wipe of cache will be performed following a successful
352 // installation.
353 //
354 // clear_display
355 // turn off the text display.
356 //
357 // enable_reboot
358 // packages can explicitly request that they want the user
359 // to be able to reboot during installation (useful for
360 // debugging packages that don't exit).
361 //
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700362 // - the name of the package zip file.
363 //
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700364 // - an optional argument "retry" if this update is a retry of a failed
365 // update attempt.
366 //
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700367
Alex Deymo4344d632016-08-03 21:03:53 -0700368 // Convert the vector to a NULL-terminated char* array suitable for execv.
369 const char* chr_args[args.size() + 1];
370 chr_args[args.size()] = NULL;
371 for (size_t i = 0; i < args.size(); i++) {
372 chr_args[i] = args[i].c_str();
373 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700374
375 pid_t pid = fork();
Matthew Bouyackde1b53d2016-09-16 16:38:11 -0700376
377 if (pid == -1) {
378 close(pipefd[0]);
379 close(pipefd[1]);
380 LOGE("Failed to fork update binary: %s\n", strerror(errno));
381 return INSTALL_ERROR;
382 }
383
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700384 if (pid == 0) {
Alistair Strachan027429a2013-07-17 10:41:49 -0700385 umask(022);
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700386 close(pipefd[0]);
Alex Deymo4344d632016-08-03 21:03:53 -0700387 execv(chr_args[0], const_cast<char**>(chr_args));
388 fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700389 _exit(-1);
390 }
391 close(pipefd[1]);
392
Tao Bao145d8612015-03-25 15:51:15 -0700393 *wipe_cache = false;
Tianjie Xufa12b972016-02-05 18:25:58 -0800394 bool retry_update = false;
Doug Zongkerd0181b82011-10-19 10:51:12 -0700395
Doug Zongker64893cc2009-07-14 16:31:56 -0700396 char buffer[1024];
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700397 FILE* from_child = fdopen(pipefd[0], "r");
398 while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700399 char* command = strtok(buffer, " \n");
400 if (command == NULL) {
401 continue;
402 } else if (strcmp(command, "progress") == 0) {
403 char* fraction_s = strtok(NULL, " \n");
404 char* seconds_s = strtok(NULL, " \n");
405
406 float fraction = strtof(fraction_s, NULL);
407 int seconds = strtol(seconds_s, NULL, 10);
408
Doug Zongker74406302011-10-28 15:13:10 -0700409 ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
Doug Zongkerfbf3c102009-06-24 09:36:20 -0700410 } else if (strcmp(command, "set_progress") == 0) {
411 char* fraction_s = strtok(NULL, " \n");
412 float fraction = strtof(fraction_s, NULL);
Doug Zongker74406302011-10-28 15:13:10 -0700413 ui->SetProgress(fraction);
Doug Zongkerd9c9d102009-06-12 12:24:39 -0700414 } else if (strcmp(command, "ui_print") == 0) {
415 char* str = strtok(NULL, "\n");
416 if (str) {
Tao Baob6918c72015-05-19 17:02:16 -0700417 ui->PrintOnScreenOnly("%s", str);
Doug Zongkerd9c9d102009-06-12 12:24:39 -0700418 } else {
Tao Baob6918c72015-05-19 17:02:16 -0700419 ui->PrintOnScreenOnly("\n");
Doug Zongkerd9c9d102009-06-12 12:24:39 -0700420 }
Doug Zongkerfafc85b2013-07-09 12:29:45 -0700421 fflush(stdout);
Doug Zongkerd0181b82011-10-19 10:51:12 -0700422 } else if (strcmp(command, "wipe_cache") == 0) {
Tao Bao145d8612015-03-25 15:51:15 -0700423 *wipe_cache = true;
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700424 } else if (strcmp(command, "clear_display") == 0) {
425 ui->SetBackground(RecoveryUI::NONE);
Doug Zongkerc704e062014-05-23 08:40:35 -0700426 } else if (strcmp(command, "enable_reboot") == 0) {
427 // packages can explicitly request that they want the user
428 // to be able to reboot during installation (useful for
429 // debugging packages that don't exit).
430 ui->SetEnableReboot(true);
Tianjie Xufa12b972016-02-05 18:25:58 -0800431 } else if (strcmp(command, "retry_update") == 0) {
432 retry_update = true;
Tianjie Xudd874b12016-05-13 12:13:15 -0700433 } else if (strcmp(command, "log") == 0) {
434 // Save the logging request from updater and write to
435 // last_install later.
436 log_buffer.push_back(std::string(strtok(NULL, "\n")));
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700437 } else {
438 LOGE("unknown command [%s]\n", command);
439 }
440 }
441 fclose(from_child);
442
443 int status;
444 waitpid(pid, &status, 0);
Tianjie Xufa12b972016-02-05 18:25:58 -0800445 if (retry_update) {
446 return INSTALL_RETRY;
447 }
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700448 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Doug Zongker9931f7f2009-06-10 14:11:53 -0700449 LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700450 return INSTALL_ERROR;
451 }
452
Doug Zongkere08991e2010-02-02 13:09:52 -0800453 return INSTALL_SUCCESS;
Doug Zongkerb2ee9202009-06-04 10:24:53 -0700454}
455
Doug Zongker469243e2011-04-12 09:28:10 -0700456static int
Tianjie Xudd874b12016-05-13 12:13:15 -0700457really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700458 std::vector<std::string>& log_buffer, int retry_count)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800459{
Doug Zongker02ec6b82012-08-22 17:26:40 -0700460 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Doug Zongker74406302011-10-28 15:13:10 -0700461 ui->Print("Finding update package...\n");
Doug Zongker239ac6a2013-08-20 16:03:25 -0700462 // Give verification half the progress bar...
463 ui->SetProgressType(RecoveryUI::DETERMINATE);
464 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
Doug Zongkercc8cd3f2010-09-20 12:16:13 -0700465 LOGI("Update location: %s\n", path);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800466
Doug Zongker99916f02014-01-13 14:16:58 -0800467 // Map the update package into memory.
468 ui->Print("Opening update package...\n");
469
Doug Zongker075ad802014-06-26 15:35:51 -0700470 if (path && needs_mount) {
Doug Zongker99916f02014-01-13 14:16:58 -0800471 if (path[0] == '@') {
472 ensure_path_mounted(path+1);
473 } else {
474 ensure_path_mounted(path);
475 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800476 }
477
Doug Zongker99916f02014-01-13 14:16:58 -0800478 MemMapping map;
479 if (sysMapFile(path, &map) != 0) {
480 LOGE("failed to map file\n");
481 return INSTALL_CORRUPT;
482 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800483
Elliott Hughes8febafa2016-04-13 16:39:56 -0700484 // Verify package.
Yabin Cui6faf0262016-06-09 14:09:39 -0700485 if (!verify_package(map.addr, map.length)) {
Tianjie Xu16255832016-04-30 11:49:59 -0700486 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
Doug Zongker99916f02014-01-13 14:16:58 -0800487 sysReleaseMap(&map);
Doug Zongker60151a22009-08-12 18:30:03 -0700488 return INSTALL_CORRUPT;
489 }
490
Elliott Hughes8febafa2016-04-13 16:39:56 -0700491 // Try to open the package.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800492 ZipArchive zip;
Yabin Cui6faf0262016-06-09 14:09:39 -0700493 int err = mzOpenZipArchive(map.addr, map.length, &zip);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800494 if (err != 0) {
495 LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
Tianjie Xu16255832016-04-30 11:49:59 -0700496 log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
497
Doug Zongker99916f02014-01-13 14:16:58 -0800498 sysReleaseMap(&map);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800499 return INSTALL_CORRUPT;
500 }
501
Elliott Hughes8febafa2016-04-13 16:39:56 -0700502 // Verify and install the contents of the package.
Doug Zongker74406302011-10-28 15:13:10 -0700503 ui->Print("Installing update...\n");
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700504 if (retry_count > 0) {
505 ui->Print("Retry attempt: %d\n", retry_count);
506 }
Doug Zongkerc704e062014-05-23 08:40:35 -0700507 ui->SetEnableReboot(false);
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700508 int result = try_update_binary(path, &zip, wipe_cache, log_buffer, retry_count);
Doug Zongkerc704e062014-05-23 08:40:35 -0700509 ui->SetEnableReboot(true);
Doug Zongker075ad802014-06-26 15:35:51 -0700510 ui->Print("\n");
Doug Zongker99916f02014-01-13 14:16:58 -0800511
512 sysReleaseMap(&map);
513
514 return result;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800515}
Doug Zongker469243e2011-04-12 09:28:10 -0700516
517int
Tao Bao145d8612015-03-25 15:51:15 -0700518install_package(const char* path, bool* wipe_cache, const char* install_file,
Tianjie Xu16255832016-04-30 11:49:59 -0700519 bool needs_mount, int retry_count)
Doug Zongker469243e2011-04-12 09:28:10 -0700520{
Tao Bao682c34b2015-04-07 17:16:35 -0700521 modified_flash = true;
Tianjie Xudd874b12016-05-13 12:13:15 -0700522 auto start = std::chrono::system_clock::now();
Tao Bao682c34b2015-04-07 17:16:35 -0700523
Doug Zongker239ac6a2013-08-20 16:03:25 -0700524 int result;
Tianjie Xudd874b12016-05-13 12:13:15 -0700525 std::vector<std::string> log_buffer;
Doug Zongker239ac6a2013-08-20 16:03:25 -0700526 if (setup_install_mounts() != 0) {
527 LOGE("failed to set up expected mounts for install; aborting\n");
528 result = INSTALL_ERROR;
529 } else {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700530 result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count);
Doug Zongker239ac6a2013-08-20 16:03:25 -0700531 }
Tianjie Xudd874b12016-05-13 12:13:15 -0700532
Tao Baoa8c0d0b2016-09-26 11:39:14 -0700533 // Measure the time spent to apply OTA update in seconds.
534 std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
535 int time_total = static_cast<int>(duration.count());
Tianjie Xudd874b12016-05-13 12:13:15 -0700536
Tao Baoa8c0d0b2016-09-26 11:39:14 -0700537 if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
538 LOGW("Can't mount %s\n", UNCRYPT_STATUS);
539 } else {
540 std::string uncrypt_status;
541 if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
542 LOGW("failed to read uncrypt status: %s\n", strerror(errno));
Tianjie Xu37d7d672016-09-24 15:31:34 -0700543 } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
Tao Baoa8c0d0b2016-09-26 11:39:14 -0700544 LOGW("corrupted uncrypt_status: %s: %s\n", uncrypt_status.c_str(), strerror(errno));
Tianjie Xue16e7992016-09-09 10:55:44 -0700545 } else {
Tao Baoa8c0d0b2016-09-26 11:39:14 -0700546 log_buffer.push_back(android::base::Trim(uncrypt_status));
Tianjie Xue16e7992016-09-09 10:55:44 -0700547 }
Doug Zongker469243e2011-04-12 09:28:10 -0700548 }
Tao Baoa8c0d0b2016-09-26 11:39:14 -0700549
550 // The first two lines need to be the package name and install result.
551 std::vector<std::string> log_header = {
552 path,
553 result == INSTALL_SUCCESS ? "1" : "0",
554 "time_total: " + std::to_string(time_total),
555 "retry: " + std::to_string(retry_count),
556 };
557 std::string log_content = android::base::Join(log_header, "\n") + "\n" +
558 android::base::Join(log_buffer, "\n");
559 if (!android::base::WriteStringToFile(log_content, install_file)) {
560 LOGE("failed to write %s: %s\n", install_file, strerror(errno));
561 }
562
563 // Write a copy into last_log.
564 LOGI("%s\n", log_content.c_str());
565
Doug Zongker469243e2011-04-12 09:28:10 -0700566 return result;
567}
Yabin Cui6faf0262016-06-09 14:09:39 -0700568
569bool verify_package(const unsigned char* package_data, size_t package_size) {
570 std::vector<Certificate> loadedKeys;
571 if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
572 LOGE("Failed to load keys\n");
573 return false;
574 }
575 LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
576
577 // Verify package.
578 ui->Print("Verifying update package...\n");
579 auto t0 = std::chrono::system_clock::now();
580 int err = verify_file(const_cast<unsigned char*>(package_data), package_size, loadedKeys);
581 std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
582 ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
583 if (err != VERIFY_SUCCESS) {
584 LOGE("Signature verification failed\n");
585 LOGE("error: %d\n", kZipVerificationFailure);
586 return false;
587 }
588 return true;
589}