blob: ce770263685b5e076175cdb4084388cb2e3438a0 [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 Bao8fce75a2016-11-10 12:33:41 -080060 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
61 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) {
67 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
68 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()) {
73 printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size());
74 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") {
94 printf("LoadPartitionContents called with bad filename \"%s\"\n", filename.c_str());
95 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) {
103 printf("LoadPartitionContents called with bad size \"%s\"\n", pieces[i * 2 + 2].c_str());
104 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) {
115 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
116 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) {
138 printf("short read (%zu bytes of %zu) for partition \"%s\"\n", read, next, partition);
Tao Baoaca8e892015-07-17 11:47:44 -0700139 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800140 }
141 SHA1_Update(&sha_ctx, buffer_ptr, read);
142 buffer_size += read;
143 buffer_ptr += read;
Tao Baoaca8e892015-07-17 11:47:44 -0700144 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700145
Tao Bao8fce75a2016-11-10 12:33:41 -0800146 // Duplicate the SHA context and finalize the duplicate so we can
147 // check it against this pair's expected hash.
148 SHA_CTX temp_ctx;
149 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
150 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
151 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800152
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800153 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Tao Bao8fce75a2016-11-10 12:33:41 -0800154 if (ParseSha1(current_sha1.c_str(), parsed_sha) != 0) {
155 printf("failed to parse SHA-1 %s in %s\n", current_sha1.c_str(), filename.c_str());
156 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800157 }
158
Tao Bao8fce75a2016-11-10 12:33:41 -0800159 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
160 // We have a match. Stop reading the partition; we'll return the data we've read so far.
161 printf("partition read matched size %zu SHA-1 %s\n", current_size, current_sha1.c_str());
162 found = true;
163 break;
Doug Zongker512536a2010-02-17 16:11:44 -0800164 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800165 }
Doug Zongker512536a2010-02-17 16:11:44 -0800166
Tao Bao8fce75a2016-11-10 12:33:41 -0800167 if (!found) {
168 // Ran off the end of the list of (size, sha1) pairs without finding a match.
169 printf("contents of partition \"%s\" didn't match %s\n", partition, filename.c_str());
170 return -1;
171 }
Doug Zongker512536a2010-02-17 16:11:44 -0800172
Tao Bao8fce75a2016-11-10 12:33:41 -0800173 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800174
Tao Bao8fce75a2016-11-10 12:33:41 -0800175 buffer.resize(buffer_size);
176 file->data = std::move(buffer);
Tao Bao8fce75a2016-11-10 12:33:41 -0800177
178 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800179}
180
Doug Zongker1c43c972012-02-28 11:07:09 -0800181int SaveFileContents(const char* filename, const FileContents* file) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800182 unique_fd fd(ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR));
183 if (fd == -1) {
184 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
185 return -1;
186 }
Doug Zongker512536a2010-02-17 16:11:44 -0800187
Tao Baoc0e1c462017-02-01 10:20:10 -0800188 size_t bytes_written = FileSink(file->data.data(), file->data.size(), fd);
Tao Baof7eb7602017-03-27 15:12:48 -0700189 if (bytes_written != file->data.size()) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800190 printf("short write of \"%s\" (%zd bytes of %zu): %s\n", filename, bytes_written,
191 file->data.size(), strerror(errno));
192 return -1;
193 }
194 if (ota_fsync(fd) != 0) {
195 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
196 return -1;
197 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800198 if (ota_close(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800199 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
200 return -1;
201 }
Doug Zongker512536a2010-02-17 16:11:44 -0800202
Tao Bao6e02ea92016-11-17 11:24:07 -0800203 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800204}
205
Tao Bao155771b2018-06-05 11:26:01 -0700206// Writes a memory buffer to 'target' partition, a string of the form
207// "EMMC:<partition_device>[:...]". The target name might contain multiple colons, but
208// WriteToPartition() only uses the first two and ignores the rest. Returns 0 on success.
209static int WriteToPartition(const unsigned char* data, size_t len, const std::string& target) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800210 std::vector<std::string> pieces = android::base::Split(target, ":");
Tao Bao8fce75a2016-11-10 12:33:41 -0800211 if (pieces.size() < 2 || pieces[0] != "EMMC") {
Tao Bao6e02ea92016-11-17 11:24:07 -0800212 printf("WriteToPartition called with bad target (%s)\n", target.c_str());
Tao Bao8fce75a2016-11-10 12:33:41 -0800213 return -1;
214 }
215
216 const char* partition = pieces[1].c_str();
Tao Bao6e02ea92016-11-17 11:24:07 -0800217 unique_fd fd(ota_open(partition, O_RDWR));
218 if (fd == -1) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800219 printf("failed to open %s: %s\n", partition, strerror(errno));
220 return -1;
221 }
222
Tao Bao6e02ea92016-11-17 11:24:07 -0800223 size_t start = 0;
224 bool success = false;
Tao Bao8fce75a2016-11-10 12:33:41 -0800225 for (size_t attempt = 0; attempt < 2; ++attempt) {
226 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
227 printf("failed seek on %s: %s\n", partition, strerror(errno));
228 return -1;
229 }
230 while (start < len) {
231 size_t to_write = len - start;
232 if (to_write > 1 << 20) to_write = 1 << 20;
233
234 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data + start, to_write));
235 if (written == -1) {
236 printf("failed write writing to %s: %s\n", partition, strerror(errno));
Tao Baoaca8e892015-07-17 11:47:44 -0700237 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800238 }
239 start += written;
Tao Baoaca8e892015-07-17 11:47:44 -0700240 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700241
Tao Bao8fce75a2016-11-10 12:33:41 -0800242 if (ota_fsync(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800243 printf("failed to sync to %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800244 return -1;
Doug Zongkerf291d852010-07-07 13:55:25 -0700245 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800246 if (ota_close(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800247 printf("failed to close %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800248 return -1;
Elliott Hughes63a31922016-06-09 17:41:22 -0700249 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800250
Tao Bao6e02ea92016-11-17 11:24:07 -0800251 fd.reset(ota_open(partition, O_RDONLY));
252 if (fd == -1) {
253 printf("failed to reopen %s for verify: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800254 return -1;
255 }
256
257 // Drop caches so our subsequent verification read won't just be reading the cache.
Elliott Hughes63a31922016-06-09 17:41:22 -0700258 sync();
Tao Bao6e02ea92016-11-17 11:24:07 -0800259 unique_fd dc(ota_open("/proc/sys/vm/drop_caches", O_WRONLY));
Tao Bao8fce75a2016-11-10 12:33:41 -0800260 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
261 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
262 } else {
263 printf(" caches dropped\n");
264 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800265 ota_close(dc);
Tao Bao8fce75a2016-11-10 12:33:41 -0800266 sleep(1);
Elliott Hughes63a31922016-06-09 17:41:22 -0700267
Tao Bao6e02ea92016-11-17 11:24:07 -0800268 // Verify.
Tao Bao8fce75a2016-11-10 12:33:41 -0800269 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
270 printf("failed to seek back to beginning of %s: %s\n", partition, strerror(errno));
271 return -1;
272 }
273
274 unsigned char buffer[4096];
275 start = len;
276 for (size_t p = 0; p < len; p += sizeof(buffer)) {
277 size_t to_read = len - p;
278 if (to_read > sizeof(buffer)) {
279 to_read = sizeof(buffer);
280 }
281
282 size_t so_far = 0;
283 while (so_far < to_read) {
284 ssize_t read_count = TEMP_FAILURE_RETRY(ota_read(fd, buffer + so_far, to_read - so_far));
285 if (read_count == -1) {
286 printf("verify read error %s at %zu: %s\n", partition, p, strerror(errno));
287 return -1;
288 } else if (read_count == 0) {
289 printf("verify read reached unexpected EOF, %s at %zu\n", partition, p);
290 return -1;
291 }
292 if (static_cast<size_t>(read_count) < to_read) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800293 printf("short verify read %s at %zu: %zd %zu\n", partition, p, read_count, to_read);
Tao Bao8fce75a2016-11-10 12:33:41 -0800294 }
295 so_far += read_count;
296 }
297
298 if (memcmp(buffer, data + p, to_read) != 0) {
299 printf("verification failed starting at %zu\n", p);
300 start = p;
301 break;
302 }
303 }
304
305 if (start == len) {
306 printf("verification read succeeded (attempt %zu)\n", attempt + 1);
307 success = true;
308 break;
309 }
katao9a6f5202016-12-19 11:22:30 +0800310
311 if (ota_close(fd) != 0) {
312 printf("failed to close %s: %s\n", partition, strerror(errno));
313 return -1;
314 }
315
316 fd.reset(ota_open(partition, O_RDWR));
317 if (fd == -1) {
318 printf("failed to reopen %s for retry write && verify: %s\n", partition, strerror(errno));
319 return -1;
320 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800321 }
322
323 if (!success) {
324 printf("failed to verify after all attempts\n");
325 return -1;
326 }
327
Tao Bao3dc14cb2016-11-22 11:37:13 -0800328 if (ota_close(fd) == -1) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800329 printf("error closing %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800330 return -1;
331 }
332 sync();
333
334 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800335}
336
Doug Zongker512536a2010-02-17 16:11:44 -0800337int ParseSha1(const char* str, uint8_t* digest) {
Tao Bao155771b2018-06-05 11:26:01 -0700338 const char* ps = str;
339 uint8_t* pd = digest;
340 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
341 int digit;
342 if (*ps >= '0' && *ps <= '9') {
343 digit = *ps - '0';
344 } else if (*ps >= 'a' && *ps <= 'f') {
345 digit = *ps - 'a' + 10;
346 } else if (*ps >= 'A' && *ps <= 'F') {
347 digit = *ps - 'A' + 10;
348 } else {
349 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800350 }
Tao Bao155771b2018-06-05 11:26:01 -0700351 if (i % 2 == 0) {
352 *pd = digit << 4;
353 } else {
354 *pd |= digit;
355 ++pd;
356 }
357 }
358 if (*ps != '\0') return -1;
359 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800360}
361
Tao Bao155771b2018-06-05 11:26:01 -0700362// Searches a vector of SHA-1 strings for one matching the given SHA-1. Returns the index of the
363// match on success, or -1 if no match is found.
364static int FindMatchingPatch(const uint8_t* sha1, const std::vector<std::string>& patch_sha1s) {
365 for (size_t i = 0; i < patch_sha1s.size(); ++i) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800366 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Bao155771b2018-06-05 11:26:01 -0700367 if (ParseSha1(patch_sha1s[i].c_str(), patch_sha1) == 0 &&
Tao Bao8fce75a2016-11-10 12:33:41 -0800368 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
369 return i;
Doug Zongker512536a2010-02-17 16:11:44 -0800370 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800371 }
372 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800373}
374
Tao Bao155771b2018-06-05 11:26:01 -0700375int applypatch_check(const char* filename, const std::vector<std::string>& patch_sha1s) {
376 // It's okay to specify no SHA-1s; the check will pass if the LoadFileContents is successful.
377 // (Useful for reading partitions, where the filename encodes the SHA-1s; no need to check them
378 // twice.)
Tao Bao8fce75a2016-11-10 12:33:41 -0800379 FileContents file;
Tao Bao8fce75a2016-11-10 12:33:41 -0800380 if (LoadFileContents(filename, &file) != 0 ||
Tao Bao155771b2018-06-05 11:26:01 -0700381 (!patch_sha1s.empty() && FindMatchingPatch(file.sha1, patch_sha1s) < 0)) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800382 printf("file \"%s\" doesn't have any of expected sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800383
Tianjie Xua88cc542017-10-25 13:16:54 -0700384 // 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 -0700385 // of patching it. A copy should have been made in cache_temp_source. If that file exists and
386 // matches the SHA-1 we're looking for, the check still passes.
Tao Bao641fa972018-04-25 18:59:40 -0700387 if (LoadFileContents(Paths::Get().cache_temp_source().c_str(), &file) != 0) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800388 printf("failed to load cache file\n");
389 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800390 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800391
Tao Bao155771b2018-06-05 11:26:01 -0700392 if (FindMatchingPatch(file.sha1, patch_sha1s) < 0) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800393 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
394 return 1;
395 }
396 }
397 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800398}
399
400int ShowLicenses() {
Tao Bao155771b2018-06-05 11:26:01 -0700401 ShowBSDiffLicense();
402 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800403}
404
Tao Baoc0e1c462017-02-01 10:20:10 -0800405static size_t FileSink(const unsigned char* data, size_t len, int fd) {
Tao Baof7eb7602017-03-27 15:12:48 -0700406 size_t done = 0;
407 while (done < len) {
408 ssize_t wrote = TEMP_FAILURE_RETRY(ota_write(fd, data + done, len - done));
409 if (wrote == -1) {
410 printf("error writing %zd bytes: %s\n", (len - done), strerror(errno));
411 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800412 }
Tao Baof7eb7602017-03-27 15:12:48 -0700413 done += wrote;
414 }
415 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800416}
417
Tianjie Xud5fbcc12018-04-11 14:38:09 -0700418size_t FreeSpaceForFile(const std::string& filename) {
419 struct statfs sf;
420 if (statfs(filename.c_str(), &sf) != 0) {
421 printf("failed to statfs %s: %s\n", filename.c_str(), strerror(errno));
422 return -1;
423 }
424 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800425}
426
Doug Zongkerc4351c72010-02-22 14:46:32 -0800427int CacheSizeCheck(size_t bytes) {
Tao Bao155771b2018-06-05 11:26:01 -0700428 if (MakeFreeSpaceOnCache(bytes) < 0) {
429 printf("unable to make %zu bytes available on /cache\n", bytes);
430 return 1;
431 }
432 return 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800433}
434
Tao Bao40e144d2017-03-15 01:10:58 -0700435int applypatch(const char* source_filename, const char* target_filename,
Tianjie Xue40c80d2018-02-03 17:20:56 -0800436 const char* target_sha1_str, size_t /* target_size */,
Tao Bao155771b2018-06-05 11:26:01 -0700437 const std::vector<std::string>& patch_sha1s,
Tao Bao40e144d2017-03-15 01:10:58 -0700438 const std::vector<std::unique_ptr<Value>>& patch_data, const Value* bonus_data) {
439 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800440
Tao Bao40e144d2017-03-15 01:10:58 -0700441 if (target_filename[0] == '-' && target_filename[1] == '\0') {
442 target_filename = source_filename;
443 }
444
445 if (strncmp(target_filename, "EMMC:", 5) != 0) {
446 printf("Supporting patching EMMC targets only.\n");
447 return 1;
448 }
449
450 uint8_t target_sha1[SHA_DIGEST_LENGTH];
451 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
452 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
453 return 1;
454 }
455
456 // We try to load the target file into the source_file object.
457 FileContents source_file;
458 if (LoadFileContents(target_filename, &source_file) == 0) {
459 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
460 // The early-exit case: the patch was already applied, this file has the desired hash, nothing
461 // for us to do.
462 printf("already %s\n", short_sha1(target_sha1).c_str());
463 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800464 }
Tao Bao40e144d2017-03-15 01:10:58 -0700465 }
Doug Zongker512536a2010-02-17 16:11:44 -0800466
Tao Bao40e144d2017-03-15 01:10:58 -0700467 if (source_file.data.empty() ||
468 (target_filename != source_filename && strcmp(target_filename, source_filename) != 0)) {
469 // Need to load the source file: either we failed to load the target file, or we did but it's
470 // different from the expected.
471 source_file.data.clear();
472 LoadFileContents(source_filename, &source_file);
473 }
474
475 if (!source_file.data.empty()) {
Tao Bao155771b2018-06-05 11:26:01 -0700476 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700477 if (to_use != -1) {
478 return GenerateTarget(source_file, patch_data[to_use], target_filename, target_sha1,
479 bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800480 }
Tao Bao40e144d2017-03-15 01:10:58 -0700481 }
Doug Zongker512536a2010-02-17 16:11:44 -0800482
Tao Bao40e144d2017-03-15 01:10:58 -0700483 printf("source file is bad; trying copy\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800484
Tao Bao40e144d2017-03-15 01:10:58 -0700485 FileContents copy_file;
Tao Bao641fa972018-04-25 18:59:40 -0700486 if (LoadFileContents(Paths::Get().cache_temp_source().c_str(), &copy_file) < 0) {
Tao Bao40e144d2017-03-15 01:10:58 -0700487 printf("failed to read copy file\n");
488 return 1;
489 }
Doug Zongker512536a2010-02-17 16:11:44 -0800490
Tao Bao155771b2018-06-05 11:26:01 -0700491 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1s);
Tao Bao40e144d2017-03-15 01:10:58 -0700492 if (to_use == -1) {
493 printf("copy file doesn't match source SHA-1s either\n");
494 return 1;
495 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800496
Tao Bao40e144d2017-03-15 01:10:58 -0700497 return GenerateTarget(copy_file, patch_data[to_use], target_filename, target_sha1, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800498}
499
Tao Baoabba55b2015-07-17 18:11:12 -0700500int applypatch_flash(const char* source_filename, const char* target_filename,
501 const char* target_sha1_str, size_t target_size) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800502 printf("flash %s: ", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700503
Tao Bao6e02ea92016-11-17 11:24:07 -0800504 uint8_t target_sha1[SHA_DIGEST_LENGTH];
505 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
506 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
507 return 1;
508 }
Tao Baoabba55b2015-07-17 18:11:12 -0700509
Tao Bao6e02ea92016-11-17 11:24:07 -0800510 std::string target_str(target_filename);
511 std::vector<std::string> pieces = android::base::Split(target_str, ":");
512 if (pieces.size() != 2 || pieces[0] != "EMMC") {
513 printf("invalid target name \"%s\"", target_filename);
514 return 1;
515 }
Tao Baoabba55b2015-07-17 18:11:12 -0700516
Tao Bao6e02ea92016-11-17 11:24:07 -0800517 // Load the target into the source_file object to see if already applied.
518 pieces.push_back(std::to_string(target_size));
519 pieces.push_back(target_sha1_str);
520 std::string fullname = android::base::Join(pieces, ':');
521 FileContents source_file;
522 if (LoadPartitionContents(fullname, &source_file) == 0 &&
523 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
524 // The early-exit case: the image was already applied, this partition
525 // has the desired hash, nothing for us to do.
526 printf("already %s\n", short_sha1(target_sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700527 return 0;
Tao Bao6e02ea92016-11-17 11:24:07 -0800528 }
529
530 if (LoadFileContents(source_filename, &source_file) == 0) {
531 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
532 // The source doesn't have desired checksum.
533 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
534 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
535 short_sha1(source_file.sha1).c_str());
536 return 1;
537 }
538 }
539
540 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
541 printf("write of copied data to %s failed\n", target_filename);
542 return 1;
543 }
544 return 0;
Tao Baoabba55b2015-07-17 18:11:12 -0700545}
546
Tao Bao40e144d2017-03-15 01:10:58 -0700547static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
548 const std::string& target_filename,
549 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800550 if (patch->type != VAL_BLOB) {
551 printf("patch is not a blob\n");
552 return 1;
553 }
Yabin Cuid483c202016-02-03 17:08:52 -0800554
Tao Bao6e02ea92016-11-17 11:24:07 -0800555 const char* header = &patch->data[0];
556 size_t header_bytes_read = patch->data.size();
557 bool use_bsdiff = false;
558 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
559 use_bsdiff = true;
560 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
561 use_bsdiff = false;
562 } else {
563 printf("Unknown patch file format\n");
564 return 1;
565 }
Doug Zongker512536a2010-02-17 16:11:44 -0800566
Tao Bao40e144d2017-03-15 01:10:58 -0700567 CHECK(android::base::StartsWith(target_filename, "EMMC:"));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568
Tao Bao40e144d2017-03-15 01:10:58 -0700569 // We still write the original source to cache, in case the partition write is interrupted.
570 if (MakeFreeSpaceOnCache(source_file.data.size()) < 0) {
571 printf("not enough free space on /cache\n");
572 return 1;
573 }
Tao Bao641fa972018-04-25 18:59:40 -0700574 if (SaveFileContents(Paths::Get().cache_temp_source().c_str(), &source_file) < 0) {
Tao Bao40e144d2017-03-15 01:10:58 -0700575 printf("failed to back up source file\n");
576 return 1;
577 }
578
579 // We store the decoded output in memory.
Tao Bao6e02ea92016-11-17 11:24:07 -0800580 std::string memory_sink_str; // Don't need to reserve space.
Tao Bao8b0b0f12018-04-19 21:02:13 -0700581 SHA_CTX ctx;
582 SHA1_Init(&ctx);
583 SinkFn sink = [&memory_sink_str, &ctx](const unsigned char* data, size_t len) {
Tianjie Xuffed57a2018-04-23 17:51:45 -0700584 if (len != 0) {
585 uint8_t digest[SHA_DIGEST_LENGTH];
586 SHA1(data, len, digest);
587 LOG(DEBUG) << "Appending " << len << " bytes data, sha1: " << short_sha1(digest);
588 }
Tao Bao8b0b0f12018-04-19 21:02:13 -0700589 SHA1_Update(&ctx, data, len);
Tao Baoc0e1c462017-02-01 10:20:10 -0800590 memory_sink_str.append(reinterpret_cast<const char*>(data), len);
591 return len;
592 };
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593
Tao Bao40e144d2017-03-15 01:10:58 -0700594 int result;
595 if (use_bsdiff) {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700596 result = ApplyBSDiffPatch(source_file.data.data(), source_file.data.size(), *patch, 0, sink);
Tao Bao40e144d2017-03-15 01:10:58 -0700597 } else {
Tao Bao8b0b0f12018-04-19 21:02:13 -0700598 result =
599 ApplyImagePatch(source_file.data.data(), source_file.data.size(), *patch, sink, bonus_data);
Tao Bao40e144d2017-03-15 01:10:58 -0700600 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800601
Tao Bao40e144d2017-03-15 01:10:58 -0700602 if (result != 0) {
603 printf("applying patch failed\n");
604 return 1;
605 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800606
607 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
608 SHA1_Final(current_target_sha1, &ctx);
609 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Bao4f834302018-04-19 12:35:14 -0700610 printf("patch did not produce expected sha1 of %s\n", short_sha1(target_sha1).c_str());
611
612 printf("target size %zu sha1 %s\n", memory_sink_str.size(),
613 short_sha1(current_target_sha1).c_str());
614 printf("source size %zu sha1 %s\n", source_file.data.size(),
615 short_sha1(source_file.sha1).c_str());
616
617 uint8_t patch_digest[SHA_DIGEST_LENGTH];
618 SHA1(reinterpret_cast<const uint8_t*>(patch->data.data()), patch->data.size(), patch_digest);
619 printf("patch size %zu sha1 %s\n", patch->data.size(), short_sha1(patch_digest).c_str());
620
621 uint8_t bonus_digest[SHA_DIGEST_LENGTH];
622 SHA1(reinterpret_cast<const uint8_t*>(bonus_data->data.data()), bonus_data->data.size(),
623 bonus_digest);
624 printf("bonus size %zu sha1 %s\n", bonus_data->data.size(), short_sha1(bonus_digest).c_str());
625
Tianjie Xu3f638ee2018-04-26 17:23:23 -0700626 // TODO(b/67849209) Remove after debugging the unit test flakiness.
627 if (android::base::GetMinimumLogSeverity() <= android::base::LogSeverity::DEBUG) {
628 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
629 memory_sink_str.size(), target_filename) != 0) {
630 LOG(DEBUG) << "Failed to write patched data " << target_filename;
631 }
632 }
633
Tao Bao6e02ea92016-11-17 11:24:07 -0800634 return 1;
635 } else {
636 printf("now %s\n", short_sha1(target_sha1).c_str());
637 }
638
Tao Bao40e144d2017-03-15 01:10:58 -0700639 // Write back the temp file to the partition.
640 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
641 memory_sink_str.size(), target_filename) != 0) {
642 printf("write of patched data to %s failed\n", target_filename.c_str());
643 return 1;
Tao Bao6e02ea92016-11-17 11:24:07 -0800644 }
645
Tao Bao40e144d2017-03-15 01:10:58 -0700646 // Delete the backup copy of the source.
Tao Bao641fa972018-04-25 18:59:40 -0700647 unlink(Paths::Get().cache_temp_source().c_str());
Tao Bao6e02ea92016-11-17 11:24:07 -0800648
649 // Success!
650 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800651}