blob: afea1da440b5bb8c8891666296f6f4edabaed2ae [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>
26#include <sys/statfs.h>
27#include <sys/types.h>
Doug Zongker512536a2010-02-17 16:11:44 -080028#include <unistd.h>
29
Tao Baoc0e1c462017-02-01 10:20:10 -080030#include <functional>
Yabin Cuid483c202016-02-03 17:08:52 -080031#include <memory>
32#include <string>
Tao Bao8fce75a2016-11-10 12:33:41 -080033#include <utility>
34#include <vector>
Yabin Cuid483c202016-02-03 17:08:52 -080035
Tao Bao40e144d2017-03-15 01:10:58 -070036#include <android-base/logging.h>
Tao Bao8fce75a2016-11-10 12:33:41 -080037#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080038#include <android-base/strings.h>
Tao Bao8fce75a2016-11-10 12:33:41 -080039#include <openssl/sha.h>
Tao Baoaca8e892015-07-17 11:47:44 -070040
Doug Zongkerc4351c72010-02-22 14:46:32 -080041#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070042#include "otafault/ota_io.h"
Tao Bao641fa972018-04-25 18:59:40 -070043#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070044#include "otautil/print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080045
Tao Bao8fce75a2016-11-10 12:33:41 -080046static int LoadPartitionContents(const std::string& filename, FileContents* file);
Tao Baoc0e1c462017-02-01 10:20:10 -080047static size_t FileSink(const unsigned char* data, size_t len, int fd);
Tao Bao40e144d2017-03-15 01:10:58 -070048static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
49 const std::string& target_filename,
50 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080051
Doug Zongkera1bc1482014-02-13 15:18:19 -080052int LoadFileContents(const char* filename, FileContents* file) {
Tao Bao8fce75a2016-11-10 12:33:41 -080053 // A special 'filename' beginning with "EMMC:" means to load the contents of a partition.
54 if (strncmp(filename, "EMMC:", 5) == 0) {
55 return LoadPartitionContents(filename, file);
56 }
Doug Zongker512536a2010-02-17 16:11:44 -080057
Tao Bao47e5a8d2017-12-01 10:53:34 -080058 struct stat sb;
59 if (stat(filename, &sb) == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -070060 PLOG(ERROR) << "Failed to stat \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080061 return -1;
62 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080063
Tao Bao47e5a8d2017-12-01 10:53:34 -080064 std::vector<unsigned char> data(sb.st_size);
Tao Bao358c2ec2016-11-28 11:48:43 -080065 unique_file f(ota_fopen(filename, "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -080066 if (!f) {
Tao Bao859bfc52018-04-25 23:00:27 -070067 PLOG(ERROR) << "Failed to open \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080068 return -1;
69 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080070
Tao Bao8fce75a2016-11-10 12:33:41 -080071 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f.get());
72 if (bytes_read != data.size()) {
Tao Bao859bfc52018-04-25 23:00:27 -070073 LOG(ERROR) << "Short read of \"" << filename << "\" (" << bytes_read << " bytes of "
74 << data.size() << ")";
Tao Bao8fce75a2016-11-10 12:33:41 -080075 return -1;
76 }
77 file->data = std::move(data);
78 SHA1(file->data.data(), file->data.size(), file->sha1);
79 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080080}
81
Tao Bao155771b2018-06-05 11:26:01 -070082// Loads the contents of an EMMC partition into the provided FileContents. filename should be a
83// string of the form "EMMC:<partition_device>:...". The smallest size_n bytes for which that prefix
84// of the partition contents has the corresponding sha1 hash will be loaded. It is acceptable for a
85// size value to be repeated with different sha1s. Returns 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080086//
Tao Bao155771b2018-06-05 11:26:01 -070087// This complexity is needed because if an OTA installation is interrupted, the partition might
88// contain either the source or the target data, which might be of different lengths. We need to
89// know the length in order to read from a partition (there is no "end-of-file" marker), so the
90// caller must specify the possible lengths and the hash of the data, and we'll do the load
91// expecting to find one of those hashes.
Tao Bao8fce75a2016-11-10 12:33:41 -080092static int LoadPartitionContents(const std::string& filename, FileContents* file) {
93 std::vector<std::string> pieces = android::base::Split(filename, ":");
94 if (pieces.size() < 4 || pieces.size() % 2 != 0 || pieces[0] != "EMMC") {
Tao Bao859bfc52018-04-25 23:00:27 -070095 LOG(ERROR) << "LoadPartitionContents called with bad filename \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -080096 return -1;
97 }
98
99 size_t pair_count = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
100 std::vector<std::pair<size_t, std::string>> pairs;
101 for (size_t i = 0; i < pair_count; ++i) {
102 size_t size;
103 if (!android::base::ParseUint(pieces[i * 2 + 2], &size) || size == 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700104 LOG(ERROR) << "LoadPartitionContents called with bad size \"" << pieces[i * 2 + 2] << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800105 return -1;
106 }
107 pairs.push_back({ size, pieces[i * 2 + 3] });
108 }
109
110 // Sort the pairs array so that they are in order of increasing size.
111 std::sort(pairs.begin(), pairs.end());
112
113 const char* partition = pieces[1].c_str();
Tao Bao358c2ec2016-11-28 11:48:43 -0800114 unique_file dev(ota_fopen(partition, "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -0800115 if (!dev) {
Tao Bao859bfc52018-04-25 23:00:27 -0700116 PLOG(ERROR) << "Failed to open eMMC partition \"" << partition << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800117 return -1;
118 }
119
120 SHA_CTX sha_ctx;
121 SHA1_Init(&sha_ctx);
122
123 // Allocate enough memory to hold the largest size.
124 std::vector<unsigned char> buffer(pairs[pair_count - 1].first);
125 unsigned char* buffer_ptr = buffer.data();
126 size_t buffer_size = 0; // # bytes read so far
127 bool found = false;
128
129 for (const auto& pair : pairs) {
130 size_t current_size = pair.first;
131 const std::string& current_sha1 = pair.second;
132
133 // Read enough additional bytes to get us up to the next size. (Again,
134 // we're trying the possibilities in order of increasing size).
135 size_t next = current_size - buffer_size;
136 if (next > 0) {
137 size_t read = ota_fread(buffer_ptr, 1, next, dev.get());
138 if (next != read) {
Tao Bao859bfc52018-04-25 23:00:27 -0700139 LOG(ERROR) << "Short read (" << read << " bytes of " << next << ") for partition \""
140 << partition << "\"";
Tao Baoaca8e892015-07-17 11:47:44 -0700141 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800142 }
143 SHA1_Update(&sha_ctx, buffer_ptr, read);
144 buffer_size += read;
145 buffer_ptr += read;
Tao Baoaca8e892015-07-17 11:47:44 -0700146 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700147
Tao Bao8fce75a2016-11-10 12:33:41 -0800148 // Duplicate the SHA context and finalize the duplicate so we can
149 // check it against this pair's expected hash.
150 SHA_CTX temp_ctx;
151 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
152 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
153 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800154
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800155 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Tao Bao8fce75a2016-11-10 12:33:41 -0800156 if (ParseSha1(current_sha1.c_str(), parsed_sha) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700157 LOG(ERROR) << "Failed to parse SHA-1 \"" << current_sha1 << "\" in " << filename;
Tao Bao8fce75a2016-11-10 12:33:41 -0800158 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800159 }
160
Tao Bao8fce75a2016-11-10 12:33:41 -0800161 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
162 // 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 -0700163 LOG(INFO) << "Partition read matched size " << current_size << " SHA-1 " << current_sha1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800164 found = true;
165 break;
Doug Zongker512536a2010-02-17 16:11:44 -0800166 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800167 }
Doug Zongker512536a2010-02-17 16:11:44 -0800168
Tao Bao8fce75a2016-11-10 12:33:41 -0800169 if (!found) {
170 // Ran off the end of the list of (size, sha1) pairs without finding a match.
Tao Bao859bfc52018-04-25 23:00:27 -0700171 LOG(ERROR) << "Contents of partition \"" << partition << "\" didn't match " << filename;
Tao Bao8fce75a2016-11-10 12:33:41 -0800172 return -1;
173 }
Doug Zongker512536a2010-02-17 16:11:44 -0800174
Tao Bao8fce75a2016-11-10 12:33:41 -0800175 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800176
Tao Bao8fce75a2016-11-10 12:33:41 -0800177 buffer.resize(buffer_size);
178 file->data = std::move(buffer);
Tao Bao8fce75a2016-11-10 12:33:41 -0800179
180 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800181}
182
Doug Zongker1c43c972012-02-28 11:07:09 -0800183int SaveFileContents(const char* filename, const FileContents* file) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800184 unique_fd fd(ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR));
185 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
Doug Zongker512536a2010-02-17 16:11:44 -0800340int ParseSha1(const char* str, uint8_t* digest) {
Tao Bao155771b2018-06-05 11:26:01 -0700341 const char* ps = str;
342 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 Bao155771b2018-06-05 11:26:01 -0700370 if (ParseSha1(patch_sha1s[i].c_str(), 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 Bao155771b2018-06-05 11:26:01 -0700378int applypatch_check(const char* filename, const std::vector<std::string>& patch_sha1s) {
379 // It's okay to specify no SHA-1s; the check will pass if the LoadFileContents is successful.
380 // (Useful for reading partitions, where the filename encodes the SHA-1s; no need to check them
381 // twice.)
Tao Bao8fce75a2016-11-10 12:33:41 -0800382 FileContents file;
Tao Bao8fce75a2016-11-10 12:33:41 -0800383 if (LoadFileContents(filename, &file) != 0 ||
Tao Bao155771b2018-06-05 11:26:01 -0700384 (!patch_sha1s.empty() && FindMatchingPatch(file.sha1, patch_sha1s) < 0)) {
Tao Bao859bfc52018-04-25 23:00:27 -0700385 LOG(INFO) << "\"" << filename << "\" doesn't have any of expected SHA-1 sums; checking cache";
Doug Zongker512536a2010-02-17 16:11:44 -0800386
Tianjie Xua88cc542017-10-25 13:16:54 -0700387 // If the source file is missing or corrupted, it might be because we were killed in the middle
Tao Bao155771b2018-06-05 11:26:01 -0700388 // of patching it. A copy should have been made in cache_temp_source. If that file exists and
389 // matches the SHA-1 we're looking for, the check still passes.
Tao Bao641fa972018-04-25 18:59:40 -0700390 if (LoadFileContents(Paths::Get().cache_temp_source().c_str(), &file) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700391 LOG(ERROR) << "Failed to load cache file";
Tao Bao8fce75a2016-11-10 12:33:41 -0800392 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800393 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800394
Tao Bao155771b2018-06-05 11:26:01 -0700395 if (FindMatchingPatch(file.sha1, patch_sha1s) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700396 LOG(ERROR) << "The cache bits don't match any SHA-1 for \"" << filename << "\"";
Tao Bao8fce75a2016-11-10 12:33:41 -0800397 return 1;
398 }
399 }
400 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800401}
402
403int ShowLicenses() {
Tao Bao155771b2018-06-05 11:26:01 -0700404 ShowBSDiffLicense();
405 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800406}
407
Tao Baoc0e1c462017-02-01 10:20:10 -0800408static size_t FileSink(const unsigned char* data, size_t len, int fd) {
Tao Baof7eb7602017-03-27 15:12:48 -0700409 size_t done = 0;
410 while (done < len) {
411 ssize_t wrote = TEMP_FAILURE_RETRY(ota_write(fd, data + done, len - done));
412 if (wrote == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700413 PLOG(ERROR) << "Failed to write " << len - done << " bytes";
Tao Baof7eb7602017-03-27 15:12:48 -0700414 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800415 }
Tao Baof7eb7602017-03-27 15:12:48 -0700416 done += wrote;
417 }
418 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800419}
420
Tianjie Xud5fbcc12018-04-11 14:38:09 -0700421size_t FreeSpaceForFile(const std::string& filename) {
422 struct statfs sf;
423 if (statfs(filename.c_str(), &sf) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700424 PLOG(ERROR) << "Failed to statfs " << filename;
Tianjie Xud5fbcc12018-04-11 14:38:09 -0700425 return -1;
426 }
427 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800428}
429
Doug Zongkerc4351c72010-02-22 14:46:32 -0800430int CacheSizeCheck(size_t bytes) {
Tao Bao155771b2018-06-05 11:26:01 -0700431 if (MakeFreeSpaceOnCache(bytes) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700432 LOG(ERROR) << "Failed to make " << bytes << " bytes available on /cache";
Tao Bao155771b2018-06-05 11:26:01 -0700433 return 1;
434 }
435 return 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800436}
437
Tao Bao40e144d2017-03-15 01:10:58 -0700438int applypatch(const char* source_filename, const char* target_filename,
Tianjie Xue40c80d2018-02-03 17:20:56 -0800439 const char* target_sha1_str, size_t /* target_size */,
Tao Bao155771b2018-06-05 11:26:01 -0700440 const std::vector<std::string>& patch_sha1s,
Tao Bao40e144d2017-03-15 01:10:58 -0700441 const std::vector<std::unique_ptr<Value>>& patch_data, const Value* bonus_data) {
Tao Bao859bfc52018-04-25 23:00:27 -0700442 LOG(INFO) << "Patching " << source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800443
Tao Bao40e144d2017-03-15 01:10:58 -0700444 if (target_filename[0] == '-' && target_filename[1] == '\0') {
445 target_filename = source_filename;
446 }
447
448 if (strncmp(target_filename, "EMMC:", 5) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700449 LOG(ERROR) << "Supporting patching EMMC targets only";
Tao Bao40e144d2017-03-15 01:10:58 -0700450 return 1;
451 }
452
453 uint8_t target_sha1[SHA_DIGEST_LENGTH];
454 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700455 LOG(ERROR) << "Failed to parse target SHA-1 \"" << target_sha1_str << "\"";
Tao Bao40e144d2017-03-15 01:10:58 -0700456 return 1;
457 }
458
459 // We try to load the target file into the source_file object.
460 FileContents source_file;
461 if (LoadFileContents(target_filename, &source_file) == 0) {
462 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
463 // The early-exit case: the patch was already applied, this file has the desired hash, nothing
464 // for us to do.
Tao Bao859bfc52018-04-25 23:00:27 -0700465 LOG(INFO) << " already " << short_sha1(target_sha1);
Tao Bao40e144d2017-03-15 01:10:58 -0700466 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800467 }
Tao Bao40e144d2017-03-15 01:10:58 -0700468 }
Doug Zongker512536a2010-02-17 16:11:44 -0800469
Tao Bao40e144d2017-03-15 01:10:58 -0700470 if (source_file.data.empty() ||
471 (target_filename != source_filename && strcmp(target_filename, source_filename) != 0)) {
472 // Need to load the source file: either we failed to load the target file, or we did but it's
473 // different from the expected.
474 source_file.data.clear();
475 LoadFileContents(source_filename, &source_file);
476 }
477
478 if (!source_file.data.empty()) {
Tao Bao155771b2018-06-05 11:26:01 -0700479 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700480 if (to_use != -1) {
481 return GenerateTarget(source_file, patch_data[to_use], target_filename, target_sha1,
482 bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800483 }
Tao Bao40e144d2017-03-15 01:10:58 -0700484 }
Doug Zongker512536a2010-02-17 16:11:44 -0800485
Tao Bao859bfc52018-04-25 23:00:27 -0700486 LOG(INFO) << "Source file is bad; trying copy";
Doug Zongker512536a2010-02-17 16:11:44 -0800487
Tao Bao40e144d2017-03-15 01:10:58 -0700488 FileContents copy_file;
Tao Bao641fa972018-04-25 18:59:40 -0700489 if (LoadFileContents(Paths::Get().cache_temp_source().c_str(), &copy_file) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700490 LOG(ERROR) << "Failed to read copy file";
Tao Bao40e144d2017-03-15 01:10:58 -0700491 return 1;
492 }
Doug Zongker512536a2010-02-17 16:11:44 -0800493
Tao Bao155771b2018-06-05 11:26:01 -0700494 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700495 if (to_use == -1) {
Tao Bao859bfc52018-04-25 23:00:27 -0700496 LOG(ERROR) << "The copy on /cache doesn't match source SHA-1s either";
Tao Bao40e144d2017-03-15 01:10:58 -0700497 return 1;
498 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800499
Tao Bao40e144d2017-03-15 01:10:58 -0700500 return GenerateTarget(copy_file, patch_data[to_use], target_filename, target_sha1, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800501}
502
Tao Baoabba55b2015-07-17 18:11:12 -0700503int applypatch_flash(const char* source_filename, const char* target_filename,
504 const char* target_sha1_str, size_t target_size) {
Tao Bao859bfc52018-04-25 23:00:27 -0700505 LOG(INFO) << "Flashing " << target_filename;
Tao Baoabba55b2015-07-17 18:11:12 -0700506
Tao Bao6e02ea92016-11-17 11:24:07 -0800507 uint8_t target_sha1[SHA_DIGEST_LENGTH];
508 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700509 LOG(ERROR) << "Failed to parse target SHA-1 \"" << target_sha1_str << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800510 return 1;
511 }
Tao Baoabba55b2015-07-17 18:11:12 -0700512
Tao Bao6e02ea92016-11-17 11:24:07 -0800513 std::string target_str(target_filename);
514 std::vector<std::string> pieces = android::base::Split(target_str, ":");
515 if (pieces.size() != 2 || pieces[0] != "EMMC") {
Tao Bao859bfc52018-04-25 23:00:27 -0700516 LOG(ERROR) << "Invalid target name \"" << target_filename << "\"";
Tao Bao6e02ea92016-11-17 11:24:07 -0800517 return 1;
518 }
Tao Baoabba55b2015-07-17 18:11:12 -0700519
Tao Bao6e02ea92016-11-17 11:24:07 -0800520 // Load the target into the source_file object to see if already applied.
521 pieces.push_back(std::to_string(target_size));
522 pieces.push_back(target_sha1_str);
523 std::string fullname = android::base::Join(pieces, ':');
524 FileContents source_file;
525 if (LoadPartitionContents(fullname, &source_file) == 0 &&
526 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700527 // The early-exit case: the image was already applied, this partition has the desired hash,
528 // nothing for us to do.
529 LOG(INFO) << " already " << short_sha1(target_sha1);
Tao Baoabba55b2015-07-17 18:11:12 -0700530 return 0;
Tao Bao6e02ea92016-11-17 11:24:07 -0800531 }
532
533 if (LoadFileContents(source_filename, &source_file) == 0) {
534 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
535 // The source doesn't have desired checksum.
Tao Bao859bfc52018-04-25 23:00:27 -0700536 LOG(ERROR) << "source \"" << source_filename << "\" doesn't have expected SHA-1 sum";
537 LOG(ERROR) << "expected: " << short_sha1(target_sha1)
538 << ", found: " << short_sha1(source_file.sha1);
Tao Bao6e02ea92016-11-17 11:24:07 -0800539 return 1;
540 }
541 }
542
543 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700544 LOG(ERROR) << "Failed to write copied data to " << target_filename;
Tao Bao6e02ea92016-11-17 11:24:07 -0800545 return 1;
546 }
547 return 0;
Tao Baoabba55b2015-07-17 18:11:12 -0700548}
549
Tao Bao40e144d2017-03-15 01:10:58 -0700550static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
551 const std::string& target_filename,
552 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800553 if (patch->type != VAL_BLOB) {
Tao Bao859bfc52018-04-25 23:00:27 -0700554 LOG(ERROR) << "patch is not a blob";
Tao Bao6e02ea92016-11-17 11:24:07 -0800555 return 1;
556 }
Yabin Cuid483c202016-02-03 17:08:52 -0800557
Tao Bao6e02ea92016-11-17 11:24:07 -0800558 const char* header = &patch->data[0];
559 size_t header_bytes_read = patch->data.size();
560 bool use_bsdiff = false;
561 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
562 use_bsdiff = true;
563 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
564 use_bsdiff = false;
565 } else {
Tao Bao859bfc52018-04-25 23:00:27 -0700566 LOG(ERROR) << "Unknown patch file format";
Tao Bao6e02ea92016-11-17 11:24:07 -0800567 return 1;
568 }
Doug Zongker512536a2010-02-17 16:11:44 -0800569
Tao Bao40e144d2017-03-15 01:10:58 -0700570 CHECK(android::base::StartsWith(target_filename, "EMMC:"));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800571
Tao Bao40e144d2017-03-15 01:10:58 -0700572 // We still write the original source to cache, in case the partition write is interrupted.
573 if (MakeFreeSpaceOnCache(source_file.data.size()) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700574 LOG(ERROR) << "Not enough free space on /cache";
Tao Bao40e144d2017-03-15 01:10:58 -0700575 return 1;
576 }
Tao Bao641fa972018-04-25 18:59:40 -0700577 if (SaveFileContents(Paths::Get().cache_temp_source().c_str(), &source_file) < 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700578 LOG(ERROR) << "Failed to back up source file";
Tao Bao40e144d2017-03-15 01:10:58 -0700579 return 1;
580 }
581
582 // We store the decoded output in memory.
Tao Bao6e02ea92016-11-17 11:24:07 -0800583 std::string memory_sink_str; // Don't need to reserve space.
Tao Bao8b0b0f12018-04-19 21:02:13 -0700584 SHA_CTX ctx;
585 SHA1_Init(&ctx);
586 SinkFn sink = [&memory_sink_str, &ctx](const unsigned char* data, size_t len) {
Tianjie Xuffed57a2018-04-23 17:51:45 -0700587 if (len != 0) {
588 uint8_t digest[SHA_DIGEST_LENGTH];
589 SHA1(data, len, digest);
Tao Bao859bfc52018-04-25 23:00:27 -0700590 LOG(DEBUG) << "Appending " << len << " bytes data, SHA-1: " << short_sha1(digest);
Tianjie Xuffed57a2018-04-23 17:51:45 -0700591 }
Tao Bao8b0b0f12018-04-19 21:02:13 -0700592 SHA1_Update(&ctx, data, len);
Tao Baoc0e1c462017-02-01 10:20:10 -0800593 memory_sink_str.append(reinterpret_cast<const char*>(data), len);
594 return len;
595 };
Doug Zongkerc4351c72010-02-22 14:46:32 -0800596
Tao Bao40e144d2017-03-15 01:10:58 -0700597 int result;
598 if (use_bsdiff) {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700599 result = ApplyBSDiffPatch(source_file.data.data(), source_file.data.size(), *patch, 0, sink);
Tao Bao40e144d2017-03-15 01:10:58 -0700600 } else {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700601 result =
602 ApplyImagePatch(source_file.data.data(), source_file.data.size(), *patch, sink, bonus_data);
Tao Bao40e144d2017-03-15 01:10:58 -0700603 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800604
Tao Bao40e144d2017-03-15 01:10:58 -0700605 if (result != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700606 LOG(ERROR) << "Failed to apply the patch: " << result;
Tao Bao40e144d2017-03-15 01:10:58 -0700607 return 1;
608 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800609
610 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
611 SHA1_Final(current_target_sha1, &ctx);
612 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700613 LOG(ERROR) << "Patching did not produce the expected SHA-1 of " << short_sha1(target_sha1);
Tao Bao4f834302018-04-19 12:35:14 -0700614
Tao Bao859bfc52018-04-25 23:00:27 -0700615 LOG(ERROR) << "target size " << memory_sink_str.size() << " SHA-1 "
616 << short_sha1(current_target_sha1);
617 LOG(ERROR) << "source size " << source_file.data.size() << " SHA-1 "
618 << short_sha1(source_file.sha1);
Tao Bao4f834302018-04-19 12:35:14 -0700619
620 uint8_t patch_digest[SHA_DIGEST_LENGTH];
621 SHA1(reinterpret_cast<const uint8_t*>(patch->data.data()), patch->data.size(), patch_digest);
Tao Bao859bfc52018-04-25 23:00:27 -0700622 LOG(ERROR) << "patch size " << patch->data.size() << " SHA-1 " << short_sha1(patch_digest);
Tao Bao4f834302018-04-19 12:35:14 -0700623
624 uint8_t bonus_digest[SHA_DIGEST_LENGTH];
625 SHA1(reinterpret_cast<const uint8_t*>(bonus_data->data.data()), bonus_data->data.size(),
626 bonus_digest);
Tao Bao859bfc52018-04-25 23:00:27 -0700627 LOG(ERROR) << "bonus size " << bonus_data->data.size() << " SHA-1 " << short_sha1(bonus_digest);
Tao Bao4f834302018-04-19 12:35:14 -0700628
Tianjie Xu3f638ee2018-04-26 17:23:23 -0700629 // TODO(b/67849209) Remove after debugging the unit test flakiness.
630 if (android::base::GetMinimumLogSeverity() <= android::base::LogSeverity::DEBUG) {
631 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
632 memory_sink_str.size(), target_filename) != 0) {
633 LOG(DEBUG) << "Failed to write patched data " << target_filename;
634 }
635 }
636
Tao Bao6e02ea92016-11-17 11:24:07 -0800637 return 1;
638 } else {
Tao Bao859bfc52018-04-25 23:00:27 -0700639 LOG(INFO) << " now " << short_sha1(target_sha1);
Tao Bao6e02ea92016-11-17 11:24:07 -0800640 }
641
Tao Bao40e144d2017-03-15 01:10:58 -0700642 // Write back the temp file to the partition.
643 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
644 memory_sink_str.size(), target_filename) != 0) {
Tao Bao859bfc52018-04-25 23:00:27 -0700645 LOG(ERROR) << "Failed to write patched data to " << target_filename;
Tao Bao40e144d2017-03-15 01:10:58 -0700646 return 1;
Tao Bao6e02ea92016-11-17 11:24:07 -0800647 }
648
Tao Bao40e144d2017-03-15 01:10:58 -0700649 // Delete the backup copy of the source.
Tao Bao641fa972018-04-25 18:59:40 -0700650 unlink(Paths::Get().cache_temp_source().c_str());
Tao Bao6e02ea92016-11-17 11:24:07 -0800651
652 // Success!
653 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800654}