blob: 12e1399303380df1b5707b2a16786ad3284660e2 [file] [log] [blame]
Doug Zongker512536a2010-02-17 16:11:44 -08001/*
2 * Copyright (C) 2008 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 Bao8fce75a2016-11-10 12:33:41 -080017#include "applypatch/applypatch.h"
18
Doug Zongker512536a2010-02-17 16:11:44 -080019#include <errno.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070020#include <fcntl.h>
Doug Zongker512536a2010-02-17 16:11:44 -080021#include <libgen.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/stat.h>
Doug Zongker512536a2010-02-17 16:11:44 -080026#include <sys/types.h>
Doug Zongker512536a2010-02-17 16:11:44 -080027#include <unistd.h>
28
Tao Baoc0e1c462017-02-01 10:20:10 -080029#include <functional>
Yabin Cuid483c202016-02-03 17:08:52 -080030#include <memory>
31#include <string>
Tao Bao8fce75a2016-11-10 12:33:41 -080032#include <utility>
33#include <vector>
Yabin Cuid483c202016-02-03 17:08:52 -080034
Tao Bao40e144d2017-03-15 01:10:58 -070035#include <android-base/logging.h>
Tao Bao8fce75a2016-11-10 12:33:41 -080036#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080037#include <android-base/strings.h>
Tao Bao8fce75a2016-11-10 12:33:41 -080038#include <openssl/sha.h>
Tao Baoaca8e892015-07-17 11:47:44 -070039
Doug Zongkerc4351c72010-02-22 14:46:32 -080040#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070041#include "otafault/ota_io.h"
Tao Bao641fa972018-04-25 18:59:40 -070042#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070043#include "otautil/print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080044
Tao Bao8fce75a2016-11-10 12:33:41 -080045static int LoadPartitionContents(const std::string& filename, FileContents* file);
Tao Baoc0e1c462017-02-01 10:20:10 -080046static size_t FileSink(const unsigned char* data, size_t len, int fd);
Tao Bao40e144d2017-03-15 01:10:58 -070047static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
48 const std::string& target_filename,
49 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080050
Tao Bao8dc70492018-06-20 10:14:40 -070051int LoadFileContents(const std::string& filename, FileContents* file) {
Tao Bao8fce75a2016-11-10 12:33:41 -080052 // A special 'filename' beginning with "EMMC:" means to load the contents of a partition.
Tao Bao8dc70492018-06-20 10:14:40 -070053 if (android::base::StartsWith(filename, "EMMC:")) {
Tao Bao8fce75a2016-11-10 12:33:41 -080054 return LoadPartitionContents(filename, file);
55 }
Doug Zongker512536a2010-02-17 16:11:44 -080056
Tao Bao47e5a8d2017-12-01 10:53:34 -080057 struct stat sb;
Tao Bao8dc70492018-06-20 10:14:40 -070058 if (stat(filename.c_str(), &sb) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -070059 PLOG(ERROR) << "Failed to stat \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080060 return -1;
61 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080062
Tao Bao47e5a8d2017-12-01 10:53:34 -080063 std::vector<unsigned char> data(sb.st_size);
Tao Bao8dc70492018-06-20 10:14:40 -070064 unique_file f(ota_fopen(filename.c_str(), "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -080065 if (!f) {
Tao Bao859bfc52018-04-25 23:00:27 -070066 PLOG(ERROR) << "Failed to open \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080067 return -1;
68 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080069
Tao Bao8fce75a2016-11-10 12:33:41 -080070 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f.get());
71 if (bytes_read != data.size()) {
Tao Bao859bfc52018-04-25 23:00:27 -070072 LOG(ERROR) << "Short read of \"" << filename << "\" (" << bytes_read << " bytes of "
73 << data.size() << ")";
Tao Bao8fce75a2016-11-10 12:33:41 -080074 return -1;
75 }
76 file->data = std::move(data);
77 SHA1(file->data.data(), file->data.size(), file->sha1);
78 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080079}
80
Tao Bao155771b2018-06-05 11:26:01 -070081// Loads the contents of an EMMC partition into the provided FileContents. filename should be a
82// string of the form "EMMC:<partition_device>:...". The smallest size_n bytes for which that prefix
83// of the partition contents has the corresponding sha1 hash will be loaded. It is acceptable for a
84// size value to be repeated with different sha1s. Returns 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080085//
Tao Bao155771b2018-06-05 11:26:01 -070086// This complexity is needed because if an OTA installation is interrupted, the partition might
87// contain either the source or the target data, which might be of different lengths. We need to
88// know the length in order to read from a partition (there is no "end-of-file" marker), so the
89// caller must specify the possible lengths and the hash of the data, and we'll do the load
90// expecting to find one of those hashes.
Tao Bao8fce75a2016-11-10 12:33:41 -080091static int LoadPartitionContents(const std::string& filename, FileContents* file) {
92 std::vector<std::string> pieces = android::base::Split(filename, ":");
93 if (pieces.size() < 4 || pieces.size() % 2 != 0 || pieces[0] != "EMMC") {
Tao Bao859bfc52018-04-25 23:00:27 -070094 LOG(ERROR) << "LoadPartitionContents called with bad filename \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080095 return -1;
96 }
97
98 size_t pair_count = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
99 std::vector<std::pair<size_t, std::string>> pairs;
100 for (size_t i = 0; i < pair_count; ++i) {
101 size_t size;
102 if (!android::base::ParseUint(pieces[i * 2 + 2], &size) || size == 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700103 LOG(ERROR) << "LoadPartitionContents called with bad size \"" << pieces[i * 2 + 2] << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800104 return -1;
105 }
106 pairs.push_back({ size, pieces[i * 2 + 3] });
107 }
108
109 // Sort the pairs array so that they are in order of increasing size.
110 std::sort(pairs.begin(), pairs.end());
111
112 const char* partition = pieces[1].c_str();
Tao Bao358c2ec2016-11-28 11:48:43 -0800113 unique_file dev(ota_fopen(partition, "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -0800114 if (!dev) {
Tao Bao859bfc52018-04-25 23:00:27 -0700115 PLOG(ERROR) << "Failed to open eMMC partition \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800116 return -1;
117 }
118
119 SHA_CTX sha_ctx;
120 SHA1_Init(&sha_ctx);
121
122 // Allocate enough memory to hold the largest size.
123 std::vector<unsigned char> buffer(pairs[pair_count - 1].first);
124 unsigned char* buffer_ptr = buffer.data();
125 size_t buffer_size = 0; // # bytes read so far
126 bool found = false;
127
128 for (const auto& pair : pairs) {
129 size_t current_size = pair.first;
130 const std::string& current_sha1 = pair.second;
131
132 // Read enough additional bytes to get us up to the next size. (Again,
133 // we're trying the possibilities in order of increasing size).
134 size_t next = current_size - buffer_size;
135 if (next > 0) {
136 size_t read = ota_fread(buffer_ptr, 1, next, dev.get());
137 if (next != read) {
Tao Bao859bfc52018-04-25 23:00:27 -0700138 LOG(ERROR) << "Short read (" << read << " bytes of " << next << ") for partition \""
139 << partition << "\"";
Tao Baoaca8e892015-07-17 11:47:44 -0700140 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800141 }
142 SHA1_Update(&sha_ctx, buffer_ptr, read);
143 buffer_size += read;
144 buffer_ptr += read;
Tao Baoaca8e892015-07-17 11:47:44 -0700145 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700146
Tao Bao8fce75a2016-11-10 12:33:41 -0800147 // Duplicate the SHA context and finalize the duplicate so we can
148 // check it against this pair's expected hash.
149 SHA_CTX temp_ctx;
150 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
151 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
152 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800153
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800154 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Tao Bao8dc70492018-06-20 10:14:40 -0700155 if (ParseSha1(current_sha1, parsed_sha) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700156 LOG(ERROR) << "Failed to parse SHA-1 \"" << current_sha1 << "\" in " << filename;
Tao Bao8fce75a2016-11-10 12:33:41 -0800157 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800158 }
159
Tao Bao8fce75a2016-11-10 12:33:41 -0800160 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
161 // We have a match. Stop reading the partition; we'll return the data we've read so far.
Tao Bao859bfc52018-04-25 23:00:27 -0700162 LOG(INFO) << "Partition read matched size " << current_size << " SHA-1 " << current_sha1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800163 found = true;
164 break;
Doug Zongker512536a2010-02-17 16:11:44 -0800165 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800166 }
Doug Zongker512536a2010-02-17 16:11:44 -0800167
Tao Bao8fce75a2016-11-10 12:33:41 -0800168 if (!found) {
169 // Ran off the end of the list of (size, sha1) pairs without finding a match.
Tao Bao859bfc52018-04-25 23:00:27 -0700170 LOG(ERROR) << "Contents of partition \"" << partition << "\" didn't match " << filename;
Tao Bao8fce75a2016-11-10 12:33:41 -0800171 return -1;
172 }
Doug Zongker512536a2010-02-17 16:11:44 -0800173
Tao Bao8fce75a2016-11-10 12:33:41 -0800174 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800175
Tao Bao8fce75a2016-11-10 12:33:41 -0800176 buffer.resize(buffer_size);
177 file->data = std::move(buffer);
Tao Bao8fce75a2016-11-10 12:33:41 -0800178
179 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800180}
181
Tao Bao8dc70492018-06-20 10:14:40 -0700182int SaveFileContents(const std::string& filename, const FileContents* file) {
183 unique_fd fd(
184 ota_open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR));
Tao Bao6e02ea92016-11-17 11:24:07 -0800185 if (fd == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700186 PLOG(ERROR) << "Failed to open \"" << filename << "\" for write";
Tao Bao6e02ea92016-11-17 11:24:07 -0800187 return -1;
188 }
Doug Zongker512536a2010-02-17 16:11:44 -0800189
Tao Baoc0e1c462017-02-01 10:20:10 -0800190 size_t bytes_written = FileSink(file->data.data(), file->data.size(), fd);
Tao Baof7eb7602017-03-27 15:12:48 -0700191 if (bytes_written != file->data.size()) {
Tao Bao859bfc52018-04-25 23:00:27 -0700192 PLOG(ERROR) << "Short write of \"" << filename << "\" (" << bytes_written << " bytes of "
193 << file->data.size();
Tao Bao6e02ea92016-11-17 11:24:07 -0800194 return -1;
195 }
196 if (ota_fsync(fd) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700197 PLOG(ERROR) << "Failed to fsync \"" << filename << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800198 return -1;
199 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800200 if (ota_close(fd) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700201 PLOG(ERROR) << "Failed to close \"" << filename << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800202 return -1;
203 }
Doug Zongker512536a2010-02-17 16:11:44 -0800204
Tao Bao6e02ea92016-11-17 11:24:07 -0800205 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800206}
207
Tao Bao155771b2018-06-05 11:26:01 -0700208// Writes a memory buffer to 'target' partition, a string of the form
209// "EMMC:<partition_device>[:...]". The target name might contain multiple colons, but
210// WriteToPartition() only uses the first two and ignores the rest. Returns 0 on success.
211static int WriteToPartition(const unsigned char* data, size_t len, const std::string& target) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800212 std::vector<std::string> pieces = android::base::Split(target, ":");
Tao Bao8fce75a2016-11-10 12:33:41 -0800213 if (pieces.size() < 2 || pieces[0] != "EMMC") {
Tao Bao859bfc52018-04-25 23:00:27 -0700214 LOG(ERROR) << "WriteToPartition called with bad target \"" << target << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800215 return -1;
216 }
217
218 const char* partition = pieces[1].c_str();
Tao Bao6e02ea92016-11-17 11:24:07 -0800219 unique_fd fd(ota_open(partition, O_RDWR));
220 if (fd == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700221 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800222 return -1;
223 }
224
Tao Bao6e02ea92016-11-17 11:24:07 -0800225 size_t start = 0;
226 bool success = false;
Tao Bao8fce75a2016-11-10 12:33:41 -0800227 for (size_t attempt = 0; attempt < 2; ++attempt) {
228 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700229 PLOG(ERROR) << "Failed to seek to " << start << " on \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800230 return -1;
231 }
232 while (start < len) {
233 size_t to_write = len - start;
234 if (to_write > 1 << 20) to_write = 1 << 20;
235
236 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data + start, to_write));
237 if (written == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700238 PLOG(ERROR) << "Failed to write to \"" << partition << "\"";
Tao Baoaca8e892015-07-17 11:47:44 -0700239 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800240 }
241 start += written;
Tao Baoaca8e892015-07-17 11:47:44 -0700242 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700243
Tao Bao8fce75a2016-11-10 12:33:41 -0800244 if (ota_fsync(fd) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700245 PLOG(ERROR) << "Failed to sync \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800246 return -1;
Doug Zongkerf291d852010-07-07 13:55:25 -0700247 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800248 if (ota_close(fd) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700249 PLOG(ERROR) << "Failed to close \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800250 return -1;
Elliott Hughes63a31922016-06-09 17:41:22 -0700251 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800252
Tao Bao6e02ea92016-11-17 11:24:07 -0800253 fd.reset(ota_open(partition, O_RDONLY));
254 if (fd == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700255 PLOG(ERROR) << "Failed to reopen \"" << partition << "\" for verification";
Tao Bao8fce75a2016-11-10 12:33:41 -0800256 return -1;
257 }
258
259 // Drop caches so our subsequent verification read won't just be reading the cache.
Elliott Hughes63a31922016-06-09 17:41:22 -0700260 sync();
Tao Bao6e02ea92016-11-17 11:24:07 -0800261 unique_fd dc(ota_open("/proc/sys/vm/drop_caches", O_WRONLY));
Tao Bao8fce75a2016-11-10 12:33:41 -0800262 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700263 PLOG(ERROR) << "Failed to write to /proc/sys/vm/drop_caches";
Tao Bao8fce75a2016-11-10 12:33:41 -0800264 } else {
Tao Bao859bfc52018-04-25 23:00:27 -0700265 LOG(INFO) << " caches dropped";
Tao Bao8fce75a2016-11-10 12:33:41 -0800266 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800267 ota_close(dc);
Tao Bao8fce75a2016-11-10 12:33:41 -0800268 sleep(1);
Elliott Hughes63a31922016-06-09 17:41:22 -0700269
Tao Bao6e02ea92016-11-17 11:24:07 -0800270 // Verify.
Tao Bao8fce75a2016-11-10 12:33:41 -0800271 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700272 PLOG(ERROR) << "Failed to seek to 0 on " << partition;
Tao Bao8fce75a2016-11-10 12:33:41 -0800273 return -1;
274 }
275
276 unsigned char buffer[4096];
277 start = len;
278 for (size_t p = 0; p < len; p += sizeof(buffer)) {
279 size_t to_read = len - p;
280 if (to_read > sizeof(buffer)) {
281 to_read = sizeof(buffer);
282 }
283
284 size_t so_far = 0;
285 while (so_far < to_read) {
286 ssize_t read_count = TEMP_FAILURE_RETRY(ota_read(fd, buffer + so_far, to_read - so_far));
287 if (read_count == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700288 PLOG(ERROR) << "Failed to verify-read " << partition << " at " << p;
Tao Bao8fce75a2016-11-10 12:33:41 -0800289 return -1;
290 } else if (read_count == 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700291 LOG(ERROR) << "Verify-reading " << partition << " reached unexpected EOF at " << p;
Tao Bao8fce75a2016-11-10 12:33:41 -0800292 return -1;
293 }
294 if (static_cast<size_t>(read_count) < to_read) {
Tao Bao859bfc52018-04-25 23:00:27 -0700295 LOG(INFO) << "Short verify-read " << partition << " at " << p << ": expected " << to_read
296 << " actual " << read_count;
Tao Bao8fce75a2016-11-10 12:33:41 -0800297 }
298 so_far += read_count;
299 }
300
301 if (memcmp(buffer, data + p, to_read) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700302 LOG(ERROR) << "Verification failed starting at " << p;
Tao Bao8fce75a2016-11-10 12:33:41 -0800303 start = p;
304 break;
305 }
306 }
307
308 if (start == len) {
Tao Bao859bfc52018-04-25 23:00:27 -0700309 LOG(INFO) << "Verification read succeeded (attempt " << attempt + 1 << ")";
Tao Bao8fce75a2016-11-10 12:33:41 -0800310 success = true;
311 break;
312 }
katao9a6f5202016-12-19 11:22:30 +0800313
314 if (ota_close(fd) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700315 PLOG(ERROR) << "Failed to close " << partition;
katao9a6f5202016-12-19 11:22:30 +0800316 return -1;
317 }
318
319 fd.reset(ota_open(partition, O_RDWR));
320 if (fd == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700321 PLOG(ERROR) << "Failed to reopen " << partition << " for next attempt";
katao9a6f5202016-12-19 11:22:30 +0800322 return -1;
323 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800324 }
325
326 if (!success) {
Tao Bao859bfc52018-04-25 23:00:27 -0700327 LOG(ERROR) << "Failed to verify after all attempts";
Tao Bao8fce75a2016-11-10 12:33:41 -0800328 return -1;
329 }
330
Tao Bao3dc14cb2016-11-22 11:37:13 -0800331 if (ota_close(fd) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700332 PLOG(ERROR) << "Failed to close " << partition;
Tao Bao8fce75a2016-11-10 12:33:41 -0800333 return -1;
334 }
335 sync();
336
337 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800338}
339
Tao Bao8dc70492018-06-20 10:14:40 -0700340int ParseSha1(const std::string& str, uint8_t* digest) {
341 const char* ps = str.c_str();
Tao Bao155771b2018-06-05 11:26:01 -0700342 uint8_t* pd = digest;
343 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
344 int digit;
345 if (*ps >= '0' && *ps <= '9') {
346 digit = *ps - '0';
347 } else if (*ps >= 'a' && *ps <= 'f') {
348 digit = *ps - 'a' + 10;
349 } else if (*ps >= 'A' && *ps <= 'F') {
350 digit = *ps - 'A' + 10;
351 } else {
352 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800353 }
Tao Bao155771b2018-06-05 11:26:01 -0700354 if (i % 2 == 0) {
355 *pd = digit << 4;
356 } else {
357 *pd |= digit;
358 ++pd;
359 }
360 }
361 if (*ps != '\0') return -1;
362 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800363}
364
Tao Bao155771b2018-06-05 11:26:01 -0700365// Searches a vector of SHA-1 strings for one matching the given SHA-1. Returns the index of the
366// match on success, or -1 if no match is found.
367static int FindMatchingPatch(const uint8_t* sha1, const std::vector<std::string>& patch_sha1s) {
368 for (size_t i = 0; i < patch_sha1s.size(); ++i) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800369 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Bao8dc70492018-06-20 10:14:40 -0700370 if (ParseSha1(patch_sha1s[i], patch_sha1) == 0 &&
Tao Bao8fce75a2016-11-10 12:33:41 -0800371 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
372 return i;
Doug Zongker512536a2010-02-17 16:11:44 -0800373 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800374 }
375 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800376}
377
Tao Bao7c1d4262018-07-06 23:18:14 -0700378int applypatch_check(const std::string& filename, const std::vector<std::string>& sha1s) {
379 if (!android::base::StartsWith(filename, "EMMC:")) {
380 return 1;
381 }
382
383 // The check will pass if LoadPartitionContents is successful, because the filename already
384 // encodes the desired SHA-1s.
Tao Bao8fce75a2016-11-10 12:33:41 -0800385 FileContents file;
Tao Bao7c1d4262018-07-06 23:18:14 -0700386 if (LoadPartitionContents(filename, &file) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700387 LOG(INFO) << "\"" << filename << "\" doesn't have any of expected SHA-1 sums; checking cache";
Doug Zongker512536a2010-02-17 16:11:44 -0800388
Tao Bao7c1d4262018-07-06 23:18:14 -0700389 // If the partition is corrupted, it might be because we were killed in the middle of patching
390 // it. A copy should have been made in cache_temp_source. If that file exists and matches the
391 // SHA-1 we're looking for, the check still passes.
Tao Bao8dc70492018-06-20 10:14:40 -0700392 if (LoadFileContents(Paths::Get().cache_temp_source(), &file) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700393 LOG(ERROR) << "Failed to load cache file";
Tao Bao8fce75a2016-11-10 12:33:41 -0800394 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800395 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800396
Tao Bao7c1d4262018-07-06 23:18:14 -0700397 if (FindMatchingPatch(file.sha1, sha1s) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700398 LOG(ERROR) << "The cache bits don't match any SHA-1 for \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800399 return 1;
400 }
401 }
402 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800403}
404
405int ShowLicenses() {
Tao Bao155771b2018-06-05 11:26:01 -0700406 ShowBSDiffLicense();
407 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800408}
409
Tao Baoc0e1c462017-02-01 10:20:10 -0800410static size_t FileSink(const unsigned char* data, size_t len, int fd) {
Tao Baof7eb7602017-03-27 15:12:48 -0700411 size_t done = 0;
412 while (done < len) {
413 ssize_t wrote = TEMP_FAILURE_RETRY(ota_write(fd, data + done, len - done));
414 if (wrote == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700415 PLOG(ERROR) << "Failed to write " << len - done << " bytes";
Tao Baof7eb7602017-03-27 15:12:48 -0700416 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800417 }
Tao Baof7eb7602017-03-27 15:12:48 -0700418 done += wrote;
419 }
420 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800421}
422
Tao Bao40e144d2017-03-15 01:10:58 -0700423int applypatch(const char* source_filename, const char* target_filename,
Tianjie Xue40c80d2018-02-03 17:20:56 -0800424 const char* target_sha1_str, size_t /* target_size */,
Tao Bao155771b2018-06-05 11:26:01 -0700425 const std::vector<std::string>& patch_sha1s,
Tao Bao40e144d2017-03-15 01:10:58 -0700426 const std::vector<std::unique_ptr<Value>>& patch_data, const Value* bonus_data) {
Tao Bao859bfc52018-04-25 23:00:27 -0700427 LOG(INFO) << "Patching " << source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800428
Tao Bao40e144d2017-03-15 01:10:58 -0700429 if (target_filename[0] == '-' && target_filename[1] == '\0') {
430 target_filename = source_filename;
431 }
432
433 if (strncmp(target_filename, "EMMC:", 5) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700434 LOG(ERROR) << "Supporting patching EMMC targets only";
Tao Bao40e144d2017-03-15 01:10:58 -0700435 return 1;
436 }
437
438 uint8_t target_sha1[SHA_DIGEST_LENGTH];
439 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700440 LOG(ERROR) << "Failed to parse target SHA-1 \"" << target_sha1_str << "\"";
Tao Bao40e144d2017-03-15 01:10:58 -0700441 return 1;
442 }
443
444 // We try to load the target file into the source_file object.
445 FileContents source_file;
446 if (LoadFileContents(target_filename, &source_file) == 0) {
447 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
448 // The early-exit case: the patch was already applied, this file has the desired hash, nothing
449 // for us to do.
Tao Bao859bfc52018-04-25 23:00:27 -0700450 LOG(INFO) << " already " << short_sha1(target_sha1);
Tao Bao40e144d2017-03-15 01:10:58 -0700451 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800452 }
Tao Bao40e144d2017-03-15 01:10:58 -0700453 }
Doug Zongker512536a2010-02-17 16:11:44 -0800454
Tao Bao40e144d2017-03-15 01:10:58 -0700455 if (source_file.data.empty() ||
456 (target_filename != source_filename && strcmp(target_filename, source_filename) != 0)) {
457 // Need to load the source file: either we failed to load the target file, or we did but it's
458 // different from the expected.
459 source_file.data.clear();
460 LoadFileContents(source_filename, &source_file);
461 }
462
463 if (!source_file.data.empty()) {
Tao Bao155771b2018-06-05 11:26:01 -0700464 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700465 if (to_use != -1) {
466 return GenerateTarget(source_file, patch_data[to_use], target_filename, target_sha1,
467 bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800468 }
Tao Bao40e144d2017-03-15 01:10:58 -0700469 }
Doug Zongker512536a2010-02-17 16:11:44 -0800470
Tao Bao859bfc52018-04-25 23:00:27 -0700471 LOG(INFO) << "Source file is bad; trying copy";
Doug Zongker512536a2010-02-17 16:11:44 -0800472
Tao Bao40e144d2017-03-15 01:10:58 -0700473 FileContents copy_file;
Tao Bao8dc70492018-06-20 10:14:40 -0700474 if (LoadFileContents(Paths::Get().cache_temp_source(), &copy_file) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700475 LOG(ERROR) << "Failed to read copy file";
Tao Bao40e144d2017-03-15 01:10:58 -0700476 return 1;
477 }
Doug Zongker512536a2010-02-17 16:11:44 -0800478
Tao Bao155771b2018-06-05 11:26:01 -0700479 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700480 if (to_use == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700481 LOG(ERROR) << "The copy on /cache doesn't match source SHA-1s either";
Tao Bao40e144d2017-03-15 01:10:58 -0700482 return 1;
483 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800484
Tao Bao40e144d2017-03-15 01:10:58 -0700485 return GenerateTarget(copy_file, patch_data[to_use], target_filename, target_sha1, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800486}
487
Tao Baoabba55b2015-07-17 18:11:12 -0700488int applypatch_flash(const char* source_filename, const char* target_filename,
489 const char* target_sha1_str, size_t target_size) {
Tao Bao859bfc52018-04-25 23:00:27 -0700490 LOG(INFO) << "Flashing " << target_filename;
Tao Baoabba55b2015-07-17 18:11:12 -0700491
Tao Bao6e02ea92016-11-17 11:24:07 -0800492 uint8_t target_sha1[SHA_DIGEST_LENGTH];
493 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700494 LOG(ERROR) << "Failed to parse target SHA-1 \"" << target_sha1_str << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800495 return 1;
496 }
Tao Baoabba55b2015-07-17 18:11:12 -0700497
Tao Bao6e02ea92016-11-17 11:24:07 -0800498 std::string target_str(target_filename);
499 std::vector<std::string> pieces = android::base::Split(target_str, ":");
500 if (pieces.size() != 2 || pieces[0] != "EMMC") {
Tao Bao859bfc52018-04-25 23:00:27 -0700501 LOG(ERROR) << "Invalid target name \"" << target_filename << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800502 return 1;
503 }
Tao Baoabba55b2015-07-17 18:11:12 -0700504
Tao Bao6e02ea92016-11-17 11:24:07 -0800505 // Load the target into the source_file object to see if already applied.
506 pieces.push_back(std::to_string(target_size));
507 pieces.push_back(target_sha1_str);
508 std::string fullname = android::base::Join(pieces, ':');
509 FileContents source_file;
510 if (LoadPartitionContents(fullname, &source_file) == 0 &&
511 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700512 // The early-exit case: the image was already applied, this partition has the desired hash,
513 // nothing for us to do.
514 LOG(INFO) << " already " << short_sha1(target_sha1);
Tao Baoabba55b2015-07-17 18:11:12 -0700515 return 0;
Tao Bao6e02ea92016-11-17 11:24:07 -0800516 }
517
518 if (LoadFileContents(source_filename, &source_file) == 0) {
519 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
520 // The source doesn't have desired checksum.
Tao Bao859bfc52018-04-25 23:00:27 -0700521 LOG(ERROR) << "source \"" << source_filename << "\" doesn't have expected SHA-1 sum";
522 LOG(ERROR) << "expected: " << short_sha1(target_sha1)
523 << ", found: " << short_sha1(source_file.sha1);
Tao Bao6e02ea92016-11-17 11:24:07 -0800524 return 1;
525 }
526 }
527
528 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700529 LOG(ERROR) << "Failed to write copied data to " << target_filename;
Tao Bao6e02ea92016-11-17 11:24:07 -0800530 return 1;
531 }
532 return 0;
Tao Baoabba55b2015-07-17 18:11:12 -0700533}
534
Tao Bao40e144d2017-03-15 01:10:58 -0700535static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
536 const std::string& target_filename,
537 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data) {
Tao Bao511d7592018-06-19 15:56:49 -0700538 if (patch->type != Value::Type::BLOB) {
Tao Bao859bfc52018-04-25 23:00:27 -0700539 LOG(ERROR) << "patch is not a blob";
Tao Bao6e02ea92016-11-17 11:24:07 -0800540 return 1;
541 }
Yabin Cuid483c202016-02-03 17:08:52 -0800542
Tao Bao6e02ea92016-11-17 11:24:07 -0800543 const char* header = &patch->data[0];
544 size_t header_bytes_read = patch->data.size();
545 bool use_bsdiff = false;
546 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
547 use_bsdiff = true;
548 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
549 use_bsdiff = false;
550 } else {
Tao Bao859bfc52018-04-25 23:00:27 -0700551 LOG(ERROR) << "Unknown patch file format";
Tao Bao6e02ea92016-11-17 11:24:07 -0800552 return 1;
553 }
Doug Zongker512536a2010-02-17 16:11:44 -0800554
Tao Bao40e144d2017-03-15 01:10:58 -0700555 CHECK(android::base::StartsWith(target_filename, "EMMC:"));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800556
Tao Bao5ee25662018-07-11 15:55:32 -0700557 // We write the original source to cache, in case the partition write is interrupted.
558 if (!CheckAndFreeSpaceOnCache(source_file.data.size())) {
Tao Bao859bfc52018-04-25 23:00:27 -0700559 LOG(ERROR) << "Not enough free space on /cache";
Tao Bao40e144d2017-03-15 01:10:58 -0700560 return 1;
561 }
Tao Bao8dc70492018-06-20 10:14:40 -0700562 if (SaveFileContents(Paths::Get().cache_temp_source(), &source_file) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700563 LOG(ERROR) << "Failed to back up source file";
Tao Bao40e144d2017-03-15 01:10:58 -0700564 return 1;
565 }
566
567 // We store the decoded output in memory.
Tao Bao6e02ea92016-11-17 11:24:07 -0800568 std::string memory_sink_str; // Don't need to reserve space.
Tao Bao8b0b0f12018-04-19 21:02:13 -0700569 SHA_CTX ctx;
570 SHA1_Init(&ctx);
571 SinkFn sink = [&memory_sink_str, &ctx](const unsigned char* data, size_t len) {
572 SHA1_Update(&ctx, data, len);
Tao Baoc0e1c462017-02-01 10:20:10 -0800573 memory_sink_str.append(reinterpret_cast<const char*>(data), len);
574 return len;
575 };
Doug Zongkerc4351c72010-02-22 14:46:32 -0800576
Tao Bao40e144d2017-03-15 01:10:58 -0700577 int result;
578 if (use_bsdiff) {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700579 result = ApplyBSDiffPatch(source_file.data.data(), source_file.data.size(), *patch, 0, sink);
Tao Bao40e144d2017-03-15 01:10:58 -0700580 } else {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700581 result =
582 ApplyImagePatch(source_file.data.data(), source_file.data.size(), *patch, sink, bonus_data);
Tao Bao40e144d2017-03-15 01:10:58 -0700583 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800584
Tao Bao40e144d2017-03-15 01:10:58 -0700585 if (result != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700586 LOG(ERROR) << "Failed to apply the patch: " << result;
Tao Bao40e144d2017-03-15 01:10:58 -0700587 return 1;
588 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800589
590 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
591 SHA1_Final(current_target_sha1, &ctx);
592 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700593 LOG(ERROR) << "Patching did not produce the expected SHA-1 of " << short_sha1(target_sha1);
Tao Bao4f834302018-04-19 12:35:14 -0700594
Tao Bao859bfc52018-04-25 23:00:27 -0700595 LOG(ERROR) << "target size " << memory_sink_str.size() << " SHA-1 "
596 << short_sha1(current_target_sha1);
597 LOG(ERROR) << "source size " << source_file.data.size() << " SHA-1 "
598 << short_sha1(source_file.sha1);
Tao Bao4f834302018-04-19 12:35:14 -0700599
600 uint8_t patch_digest[SHA_DIGEST_LENGTH];
601 SHA1(reinterpret_cast<const uint8_t*>(patch->data.data()), patch->data.size(), patch_digest);
Tao Bao859bfc52018-04-25 23:00:27 -0700602 LOG(ERROR) << "patch size " << patch->data.size() << " SHA-1 " << short_sha1(patch_digest);
Tao Bao4f834302018-04-19 12:35:14 -0700603
Tao Bao7ea515e2018-07-09 15:16:13 -0700604 if (bonus_data != nullptr) {
605 uint8_t bonus_digest[SHA_DIGEST_LENGTH];
606 SHA1(reinterpret_cast<const uint8_t*>(bonus_data->data.data()), bonus_data->data.size(),
607 bonus_digest);
608 LOG(ERROR) << "bonus size " << bonus_data->data.size() << " SHA-1 "
609 << short_sha1(bonus_digest);
610 }
Tao Bao4f834302018-04-19 12:35:14 -0700611
Tao Bao6e02ea92016-11-17 11:24:07 -0800612 return 1;
613 } else {
Tao Bao859bfc52018-04-25 23:00:27 -0700614 LOG(INFO) << " now " << short_sha1(target_sha1);
Tao Bao6e02ea92016-11-17 11:24:07 -0800615 }
616
Tao Bao40e144d2017-03-15 01:10:58 -0700617 // Write back the temp file to the partition.
618 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
619 memory_sink_str.size(), target_filename) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700620 LOG(ERROR) << "Failed to write patched data to " << target_filename;
Tao Bao40e144d2017-03-15 01:10:58 -0700621 return 1;
Tao Bao6e02ea92016-11-17 11:24:07 -0800622 }
623
Tao Bao40e144d2017-03-15 01:10:58 -0700624 // Delete the backup copy of the source.
Tao Bao641fa972018-04-25 18:59:40 -0700625 unlink(Paths::Get().cache_temp_source().c_str());
Tao Bao6e02ea92016-11-17 11:24:07 -0800626
627 // Success!
628 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800629}