blob: c6b192694d3243590d343ca8020416c17757ed6e [file] [log] [blame]
Ethan Yonker941a8992016-12-05 09:04:30 -06001/*
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
17#include <stdlib.h>
18#include <string>
19#include <vector>
20
21#ifdef AB_OTA_UPDATER
22#include <map>
23#include <android-base/parseint.h>
24#include <android-base/stringprintf.h>
25#include <android-base/strings.h>
26#endif
27#include <cutils/properties.h>
28
29#include "common.h"
30#include "installcommand.h"
Ethan Yonker8373cfe2017-09-08 06:50:54 -050031#include "zipwrap.hpp"
32#ifndef USE_MINZIP
33#include <ziparchive/zip_archive.h>
34#include <vintf/VintfObjectRecovery.h>
35#endif
Ethan Yonker941a8992016-12-05 09:04:30 -060036#ifdef USE_OLD_VERIFIER
37#include "verifier24/verifier.h"
38#else
39#include "verifier.h"
40#endif
41
42#ifdef AB_OTA_UPDATER
43
44static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
45static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
46static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
47
48// This function parses and returns the build.version.incremental
49static int parse_build_number(std::string str) {
50 size_t pos = str.find("=");
51 if (pos != std::string::npos) {
52 std::string num_string = android::base::Trim(str.substr(pos+1));
53 int build_number;
54 if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
55 return build_number;
56 }
57 }
58
59 printf("Failed to parse build number in %s.\n", str.c_str());
60 return -1;
61}
62
Ethan Yonker8373cfe2017-09-08 06:50:54 -050063bool read_metadata_from_package(ZipWrap* zip, std::string* meta_data) {
64 long size = zip->GetUncompressedSize(METADATA_PATH);
65 if (size <= 0)
66 return false;
Ethan Yonker941a8992016-12-05 09:04:30 -060067
Ethan Yonker8373cfe2017-09-08 06:50:54 -050068 meta_data->resize(size, '\0');
69 if (!zip->ExtractToBuffer(METADATA_PATH, reinterpret_cast<uint8_t*>(&(*meta_data)[0]))) {
Ethan Yonker941a8992016-12-05 09:04:30 -060070 printf("Failed to read metadata in update package.\n");
71 return false;
72 }
73 return true;
74}
75
76// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
Ethan Yonker8373cfe2017-09-08 06:50:54 -050077static void read_source_target_build(ZipWrap* zip, std::vector<std::string>& log_buffer) {
Ethan Yonker941a8992016-12-05 09:04:30 -060078 std::string meta_data;
79 if (!read_metadata_from_package(zip, &meta_data)) {
80 return;
81 }
82 // Examples of the pre-build and post-build strings in metadata:
83 // pre-build-incremental=2943039
84 // post-build-incremental=2951741
85 std::vector<std::string> lines = android::base::Split(meta_data, "\n");
86 for (const std::string& line : lines) {
87 std::string str = android::base::Trim(line);
88 if (android::base::StartsWith(str, "pre-build-incremental")){
89 int source_build = parse_build_number(str);
90 if (source_build != -1) {
91 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
92 source_build));
93 }
94 } else if (android::base::StartsWith(str, "post-build-incremental")) {
95 int target_build = parse_build_number(str);
96 if (target_build != -1) {
97 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
98 target_build));
99 }
100 }
101 }
102}
103
104// Parses the metadata of the OTA package in |zip| and checks whether we are
105// allowed to accept this A/B package. Downgrading is not allowed unless
106// explicitly enabled in the package and only for incremental packages.
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500107static int check_newer_ab_build(ZipWrap* zip)
Ethan Yonker941a8992016-12-05 09:04:30 -0600108{
109 std::string metadata_str;
110 if (!read_metadata_from_package(zip, &metadata_str)) {
111 return INSTALL_CORRUPT;
112 }
113 std::map<std::string, std::string> metadata;
114 for (const std::string& line : android::base::Split(metadata_str, "\n")) {
115 size_t eq = line.find('=');
116 if (eq != std::string::npos) {
117 metadata[line.substr(0, eq)] = line.substr(eq + 1);
118 }
119 }
120 char value[PROPERTY_VALUE_MAX];
121
122 property_get("ro.product.device", value, "");
123 const std::string& pkg_device = metadata["pre-device"];
124 if (pkg_device != value || pkg_device.empty()) {
125 printf("Package is for product %s but expected %s\n",
126 pkg_device.c_str(), value);
127 return INSTALL_ERROR;
128 }
129
130 // We allow the package to not have any serialno, but if it has a non-empty
131 // value it should match.
132 property_get("ro.serialno", value, "");
133 const std::string& pkg_serial_no = metadata["serialno"];
134 if (!pkg_serial_no.empty() && pkg_serial_no != value) {
135 printf("Package is for serial %s\n", pkg_serial_no.c_str());
136 return INSTALL_ERROR;
137 }
138
139 if (metadata["ota-type"] != "AB") {
140 printf("Package is not A/B\n");
141 return INSTALL_ERROR;
142 }
143
144 // Incremental updates should match the current build.
145 property_get("ro.build.version.incremental", value, "");
146 const std::string& pkg_pre_build = metadata["pre-build-incremental"];
147 if (!pkg_pre_build.empty() && pkg_pre_build != value) {
148 printf("Package is for source build %s but expected %s\n",
149 pkg_pre_build.c_str(), value);
150 return INSTALL_ERROR;
151 }
152 property_get("ro.build.fingerprint", value, "");
153 const std::string& pkg_pre_build_fingerprint = metadata["pre-build"];
154 if (!pkg_pre_build_fingerprint.empty() &&
155 pkg_pre_build_fingerprint != value) {
156 printf("Package is for source build %s but expected %s\n",
157 pkg_pre_build_fingerprint.c_str(), value);
158 return INSTALL_ERROR;
159 }
160
161 // Check for downgrade version.
162 int64_t build_timestampt = property_get_int64(
163 "ro.build.date.utc", std::numeric_limits<int64_t>::max());
164 int64_t pkg_post_timespampt = 0;
165 // We allow to full update to the same version we are running, in case there
166 // is a problem with the current copy of that version.
167 if (metadata["post-timestamp"].empty() ||
168 !android::base::ParseInt(metadata["post-timestamp"].c_str(),
169 &pkg_post_timespampt) ||
170 pkg_post_timespampt < build_timestampt) {
171 if (metadata["ota-downgrade"] != "yes") {
172 printf("Update package is older than the current build, expected a "
173 "build newer than timestamp %" PRIu64 " but package has "
174 "timestamp %" PRIu64 " and downgrade not allowed.\n",
175 build_timestampt, pkg_post_timespampt);
176 return INSTALL_ERROR;
177 }
178 if (pkg_pre_build_fingerprint.empty()) {
179 printf("Downgrade package must have a pre-build version set, not "
180 "allowed.\n");
181 return INSTALL_ERROR;
182 }
183 }
184
185 return 0;
186}
187
188int
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500189abupdate_binary_command(const char* path, ZipWrap* zip, int retry_count,
Ethan Yonker941a8992016-12-05 09:04:30 -0600190 int status_fd, std::vector<std::string>* cmd)
191{
192 int ret = check_newer_ab_build(zip);
193 if (ret) {
194 return ret;
195 }
196
197 // For A/B updates we extract the payload properties to a buffer and obtain
198 // the RAW payload offset in the zip file.
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500199 if (!zip->EntryExists(AB_OTA_PAYLOAD_PROPERTIES)) {
Ethan Yonker941a8992016-12-05 09:04:30 -0600200 printf("Can't find %s\n", AB_OTA_PAYLOAD_PROPERTIES);
201 return INSTALL_CORRUPT;
202 }
203 std::vector<unsigned char> payload_properties(
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500204 zip->GetUncompressedSize(AB_OTA_PAYLOAD_PROPERTIES));
205 if (!zip->ExtractToBuffer(AB_OTA_PAYLOAD_PROPERTIES, payload_properties.data())) {
Ethan Yonker941a8992016-12-05 09:04:30 -0600206 printf("Can't extract %s\n", AB_OTA_PAYLOAD_PROPERTIES);
207 return INSTALL_CORRUPT;
208 }
209
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500210 if (!zip->EntryExists(AB_OTA_PAYLOAD)) {
Ethan Yonker941a8992016-12-05 09:04:30 -0600211 printf("Can't find %s\n", AB_OTA_PAYLOAD);
212 return INSTALL_CORRUPT;
213 }
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500214 long payload_offset = zip->GetEntryOffset(AB_OTA_PAYLOAD);
Ethan Yonker941a8992016-12-05 09:04:30 -0600215 *cmd = {
216 "/sbin/update_engine_sideload",
217 android::base::StringPrintf("--payload=file://%s", path),
218 android::base::StringPrintf("--offset=%ld", payload_offset),
219 "--headers=" + std::string(payload_properties.begin(),
220 payload_properties.end()),
221 android::base::StringPrintf("--status_fd=%d", status_fd),
222 };
223 return INSTALL_SUCCESS;
224}
225
226#else
227
228int
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500229abupdate_binary_command(__unused const char* path, __unused ZipWrap* zip, __unused int retry_count,
230 __unused int status_fd, __unused std::vector<std::string>* cmd)
Ethan Yonker941a8992016-12-05 09:04:30 -0600231{
232 printf("No support for AB OTA zips included\n");
233 return INSTALL_CORRUPT;
234}
235
236#endif
237
238int
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500239update_binary_command(const char* path, int retry_count,
Ethan Yonker941a8992016-12-05 09:04:30 -0600240 int status_fd, std::vector<std::string>* cmd)
241{
242 char charfd[16];
243 sprintf(charfd, "%i", status_fd);
244 cmd->push_back(TMP_UPDATER_BINARY_PATH);
245 cmd->push_back(EXPAND(RECOVERY_API_VERSION));
246 cmd->push_back(charfd);
247 cmd->push_back(path);
248 /**cmd = {
249 TMP_UPDATER_BINARY_PATH,
250 EXPAND(RECOVERY_API_VERSION), // defined in Android.mk
251 charfd,
252 path,
253 };*/
254 if (retry_count > 0)
255 cmd->push_back("retry");
256 return 0;
257}
Ethan Yonker8373cfe2017-09-08 06:50:54 -0500258
259#ifdef USE_MINZIP
260bool verify_package_compatibility(ZipWrap *package_zip) {
261 if (package_zip->EntryExists("compatibility.zip"))
262 printf("Cannot verify treble package compatibility, must build TWRP in Oreo tree or higher.\n");
263 return true;
264}
265#else
266// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the
267// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA
268// package.
269bool verify_package_compatibility(ZipWrap *zw) {
270 ZipArchiveHandle package_zip = zw->GetZipArchiveHandle();
271 printf("Verifying package compatibility...\n");
272
273 static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip";
274 ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY);
275 ZipEntry compatibility_entry;
276 if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) {
277 printf("Package doesn't contain %s entry\n", COMPATIBILITY_ZIP_ENTRY);
278 return true;
279 }
280
281 std::string zip_content(compatibility_entry.uncompressed_length, '\0');
282 int32_t ret;
283 if ((ret = ExtractToMemory(package_zip, &compatibility_entry,
284 reinterpret_cast<uint8_t*>(&zip_content[0]),
285 compatibility_entry.uncompressed_length)) != 0) {
286 printf("Failed to read %s: %s\n", COMPATIBILITY_ZIP_ENTRY, ErrorCodeString(ret));
287 return false;
288 }
289
290 ZipArchiveHandle zip_handle;
291 ret = OpenArchiveFromMemory(static_cast<void*>(const_cast<char*>(zip_content.data())),
292 zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle);
293 if (ret != 0) {
294 printf("Failed to OpenArchiveFromMemory: %s\n", ErrorCodeString(ret));
295 return false;
296 }
297
298 // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents.
299 void* cookie;
300 ret = StartIteration(zip_handle, &cookie, nullptr, nullptr);
301 if (ret != 0) {
302 printf("Failed to start iterating zip entries: %s\n", ErrorCodeString(ret));
303 CloseArchive(zip_handle);
304 return false;
305 }
306 std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
307
308 std::vector<std::string> compatibility_info;
309 ZipEntry info_entry;
310 ZipString info_name;
311 while (Next(cookie, &info_entry, &info_name) == 0) {
312 std::string content(info_entry.uncompressed_length, '\0');
313 int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast<uint8_t*>(&content[0]),
314 info_entry.uncompressed_length);
315 if (ret != 0) {
316 printf("Failed to read %s: %s\n", info_name.name, ErrorCodeString(ret));
317 CloseArchive(zip_handle);
318 return false;
319 }
320 compatibility_info.emplace_back(std::move(content));
321 }
322 CloseArchive(zip_handle);
323
324 // VintfObjectRecovery::CheckCompatibility returns zero on success.
325 std::string err;
326 int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err);
327 if (result == 0) {
328 return true;
329 }
330
331 printf("Failed to verify package compatibility (result %i): %s\n", result, err.c_str());
332 return false;
333}
334#endif