blob: 04b964b17d9ab977d2c1218c078eb7d2a4c7a852 [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 Bao09e468f2017-09-29 14:39:33 -070043#include "otautil/print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080044
Tianjie Xua88cc542017-10-25 13:16:54 -070045std::string cache_temp_source = "/cache/saved.file";
46
Tao Bao8fce75a2016-11-10 12:33:41 -080047static int LoadPartitionContents(const std::string& filename, FileContents* file);
Tao Baoc0e1c462017-02-01 10:20:10 -080048static size_t FileSink(const unsigned char* data, size_t len, int fd);
Tao Bao40e144d2017-03-15 01:10:58 -070049static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
50 const std::string& target_filename,
51 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080052
Tao Bao8fce75a2016-11-10 12:33:41 -080053// Read a file into memory; store the file contents and associated metadata in *file.
Hristo Bojinovdb314d62010-08-02 10:29:49 -070054// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080055int LoadFileContents(const char* filename, FileContents* file) {
Tao Bao8fce75a2016-11-10 12:33:41 -080056 // A special 'filename' beginning with "EMMC:" means to load the contents of a partition.
57 if (strncmp(filename, "EMMC:", 5) == 0) {
58 return LoadPartitionContents(filename, file);
59 }
Doug Zongker512536a2010-02-17 16:11:44 -080060
Tao Bao47e5a8d2017-12-01 10:53:34 -080061 struct stat sb;
62 if (stat(filename, &sb) == -1) {
Tao Bao8fce75a2016-11-10 12:33:41 -080063 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
64 return -1;
65 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080066
Tao Bao47e5a8d2017-12-01 10:53:34 -080067 std::vector<unsigned char> data(sb.st_size);
Tao Bao358c2ec2016-11-28 11:48:43 -080068 unique_file f(ota_fopen(filename, "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -080069 if (!f) {
70 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
71 return -1;
72 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080073
Tao Bao8fce75a2016-11-10 12:33:41 -080074 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f.get());
75 if (bytes_read != data.size()) {
76 printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size());
77 return -1;
78 }
79 file->data = std::move(data);
80 SHA1(file->data.data(), file->data.size(), file->sha1);
81 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080082}
83
Elliott Hughes63a31922016-06-09 17:41:22 -070084// Load the contents of an EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080085// FileContents. filename should be a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -070086// "EMMC:<partition_device>:...". The smallest size_n bytes for
Doug Zongkerf291d852010-07-07 13:55:25 -070087// which that prefix of the partition contents has the corresponding
88// sha1 hash will be loaded. It is acceptable for a size value to be
89// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080090//
91// This complexity is needed because if an OTA installation is
92// interrupted, the partition might contain either the source or the
93// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -070094// the length in order to read from a partition (there is no
95// "end-of-file" marker), so the caller must specify the possible
96// lengths and the hash of the data, and we'll do the load expecting
97// to find one of those hashes.
Tao Bao8fce75a2016-11-10 12:33:41 -080098static int LoadPartitionContents(const std::string& filename, FileContents* file) {
99 std::vector<std::string> pieces = android::base::Split(filename, ":");
100 if (pieces.size() < 4 || pieces.size() % 2 != 0 || pieces[0] != "EMMC") {
101 printf("LoadPartitionContents called with bad filename \"%s\"\n", filename.c_str());
102 return -1;
103 }
104
105 size_t pair_count = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
106 std::vector<std::pair<size_t, std::string>> pairs;
107 for (size_t i = 0; i < pair_count; ++i) {
108 size_t size;
109 if (!android::base::ParseUint(pieces[i * 2 + 2], &size) || size == 0) {
110 printf("LoadPartitionContents called with bad size \"%s\"\n", pieces[i * 2 + 2].c_str());
111 return -1;
112 }
113 pairs.push_back({ size, pieces[i * 2 + 3] });
114 }
115
116 // Sort the pairs array so that they are in order of increasing size.
117 std::sort(pairs.begin(), pairs.end());
118
119 const char* partition = pieces[1].c_str();
Tao Bao358c2ec2016-11-28 11:48:43 -0800120 unique_file dev(ota_fopen(partition, "rb"));
Tao Bao8fce75a2016-11-10 12:33:41 -0800121 if (!dev) {
122 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
123 return -1;
124 }
125
126 SHA_CTX sha_ctx;
127 SHA1_Init(&sha_ctx);
128
129 // Allocate enough memory to hold the largest size.
130 std::vector<unsigned char> buffer(pairs[pair_count - 1].first);
131 unsigned char* buffer_ptr = buffer.data();
132 size_t buffer_size = 0; // # bytes read so far
133 bool found = false;
134
135 for (const auto& pair : pairs) {
136 size_t current_size = pair.first;
137 const std::string& current_sha1 = pair.second;
138
139 // Read enough additional bytes to get us up to the next size. (Again,
140 // we're trying the possibilities in order of increasing size).
141 size_t next = current_size - buffer_size;
142 if (next > 0) {
143 size_t read = ota_fread(buffer_ptr, 1, next, dev.get());
144 if (next != read) {
145 printf("short read (%zu bytes of %zu) for partition \"%s\"\n", read, next, partition);
Tao Baoaca8e892015-07-17 11:47:44 -0700146 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800147 }
148 SHA1_Update(&sha_ctx, buffer_ptr, read);
149 buffer_size += read;
150 buffer_ptr += read;
Tao Baoaca8e892015-07-17 11:47:44 -0700151 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700152
Tao Bao8fce75a2016-11-10 12:33:41 -0800153 // Duplicate the SHA context and finalize the duplicate so we can
154 // check it against this pair's expected hash.
155 SHA_CTX temp_ctx;
156 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
157 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
158 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800159
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800160 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Tao Bao8fce75a2016-11-10 12:33:41 -0800161 if (ParseSha1(current_sha1.c_str(), parsed_sha) != 0) {
162 printf("failed to parse SHA-1 %s in %s\n", current_sha1.c_str(), filename.c_str());
163 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800164 }
165
Tao Bao8fce75a2016-11-10 12:33:41 -0800166 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
167 // We have a match. Stop reading the partition; we'll return the data we've read so far.
168 printf("partition read matched size %zu SHA-1 %s\n", current_size, current_sha1.c_str());
169 found = true;
170 break;
Doug Zongker512536a2010-02-17 16:11:44 -0800171 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800172 }
Doug Zongker512536a2010-02-17 16:11:44 -0800173
Tao Bao8fce75a2016-11-10 12:33:41 -0800174 if (!found) {
175 // Ran off the end of the list of (size, sha1) pairs without finding a match.
176 printf("contents of partition \"%s\" didn't match %s\n", partition, filename.c_str());
177 return -1;
178 }
Doug Zongker512536a2010-02-17 16:11:44 -0800179
Tao Bao8fce75a2016-11-10 12:33:41 -0800180 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800181
Tao Bao8fce75a2016-11-10 12:33:41 -0800182 buffer.resize(buffer_size);
183 file->data = std::move(buffer);
Tao Bao8fce75a2016-11-10 12:33:41 -0800184
185 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800186}
187
Doug Zongker512536a2010-02-17 16:11:44 -0800188// Save the contents of the given FileContents object under the given
189// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800190int SaveFileContents(const char* filename, const FileContents* file) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800191 unique_fd fd(ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR));
192 if (fd == -1) {
193 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
194 return -1;
195 }
Doug Zongker512536a2010-02-17 16:11:44 -0800196
Tao Baoc0e1c462017-02-01 10:20:10 -0800197 size_t bytes_written = FileSink(file->data.data(), file->data.size(), fd);
Tao Baof7eb7602017-03-27 15:12:48 -0700198 if (bytes_written != file->data.size()) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800199 printf("short write of \"%s\" (%zd bytes of %zu): %s\n", filename, bytes_written,
200 file->data.size(), strerror(errno));
201 return -1;
202 }
203 if (ota_fsync(fd) != 0) {
204 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
205 return -1;
206 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800207 if (ota_close(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800208 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
209 return -1;
210 }
Doug Zongker512536a2010-02-17 16:11:44 -0800211
Tao Bao6e02ea92016-11-17 11:24:07 -0800212 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800213}
214
Doug Zongkerf291d852010-07-07 13:55:25 -0700215// Write a memory buffer to 'target' partition, a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -0700216// "EMMC:<partition_device>[:...]". The target name
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700217// might contain multiple colons, but WriteToPartition() only uses the first
218// two and ignores the rest. Return 0 on success.
Tao Bao6e02ea92016-11-17 11:24:07 -0800219int WriteToPartition(const unsigned char* data, size_t len, const std::string& target) {
220 std::vector<std::string> pieces = android::base::Split(target, ":");
Tao Bao8fce75a2016-11-10 12:33:41 -0800221 if (pieces.size() < 2 || pieces[0] != "EMMC") {
Tao Bao6e02ea92016-11-17 11:24:07 -0800222 printf("WriteToPartition called with bad target (%s)\n", target.c_str());
Tao Bao8fce75a2016-11-10 12:33:41 -0800223 return -1;
224 }
225
226 const char* partition = pieces[1].c_str();
Tao Bao6e02ea92016-11-17 11:24:07 -0800227 unique_fd fd(ota_open(partition, O_RDWR));
228 if (fd == -1) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800229 printf("failed to open %s: %s\n", partition, strerror(errno));
230 return -1;
231 }
232
Tao Bao6e02ea92016-11-17 11:24:07 -0800233 size_t start = 0;
234 bool success = false;
Tao Bao8fce75a2016-11-10 12:33:41 -0800235 for (size_t attempt = 0; attempt < 2; ++attempt) {
236 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
237 printf("failed seek on %s: %s\n", partition, strerror(errno));
238 return -1;
239 }
240 while (start < len) {
241 size_t to_write = len - start;
242 if (to_write > 1 << 20) to_write = 1 << 20;
243
244 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data + start, to_write));
245 if (written == -1) {
246 printf("failed write writing to %s: %s\n", partition, strerror(errno));
Tao Baoaca8e892015-07-17 11:47:44 -0700247 return -1;
Tao Bao8fce75a2016-11-10 12:33:41 -0800248 }
249 start += written;
Tao Baoaca8e892015-07-17 11:47:44 -0700250 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700251
Tao Bao8fce75a2016-11-10 12:33:41 -0800252 if (ota_fsync(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800253 printf("failed to sync to %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800254 return -1;
Doug Zongkerf291d852010-07-07 13:55:25 -0700255 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800256 if (ota_close(fd) != 0) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800257 printf("failed to close %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800258 return -1;
Elliott Hughes63a31922016-06-09 17:41:22 -0700259 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800260
Tao Bao6e02ea92016-11-17 11:24:07 -0800261 fd.reset(ota_open(partition, O_RDONLY));
262 if (fd == -1) {
263 printf("failed to reopen %s for verify: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800264 return -1;
265 }
266
267 // Drop caches so our subsequent verification read won't just be reading the cache.
Elliott Hughes63a31922016-06-09 17:41:22 -0700268 sync();
Tao Bao6e02ea92016-11-17 11:24:07 -0800269 unique_fd dc(ota_open("/proc/sys/vm/drop_caches", O_WRONLY));
Tao Bao8fce75a2016-11-10 12:33:41 -0800270 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
271 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
272 } else {
273 printf(" caches dropped\n");
274 }
Tao Bao3dc14cb2016-11-22 11:37:13 -0800275 ota_close(dc);
Tao Bao8fce75a2016-11-10 12:33:41 -0800276 sleep(1);
Elliott Hughes63a31922016-06-09 17:41:22 -0700277
Tao Bao6e02ea92016-11-17 11:24:07 -0800278 // Verify.
Tao Bao8fce75a2016-11-10 12:33:41 -0800279 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
280 printf("failed to seek back to beginning of %s: %s\n", partition, strerror(errno));
281 return -1;
282 }
283
284 unsigned char buffer[4096];
285 start = len;
286 for (size_t p = 0; p < len; p += sizeof(buffer)) {
287 size_t to_read = len - p;
288 if (to_read > sizeof(buffer)) {
289 to_read = sizeof(buffer);
290 }
291
292 size_t so_far = 0;
293 while (so_far < to_read) {
294 ssize_t read_count = TEMP_FAILURE_RETRY(ota_read(fd, buffer + so_far, to_read - so_far));
295 if (read_count == -1) {
296 printf("verify read error %s at %zu: %s\n", partition, p, strerror(errno));
297 return -1;
298 } else if (read_count == 0) {
299 printf("verify read reached unexpected EOF, %s at %zu\n", partition, p);
300 return -1;
301 }
302 if (static_cast<size_t>(read_count) < to_read) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800303 printf("short verify read %s at %zu: %zd %zu\n", partition, p, read_count, to_read);
Tao Bao8fce75a2016-11-10 12:33:41 -0800304 }
305 so_far += read_count;
306 }
307
308 if (memcmp(buffer, data + p, to_read) != 0) {
309 printf("verification failed starting at %zu\n", p);
310 start = p;
311 break;
312 }
313 }
314
315 if (start == len) {
316 printf("verification read succeeded (attempt %zu)\n", attempt + 1);
317 success = true;
318 break;
319 }
katao9a6f5202016-12-19 11:22:30 +0800320
321 if (ota_close(fd) != 0) {
322 printf("failed to close %s: %s\n", partition, strerror(errno));
323 return -1;
324 }
325
326 fd.reset(ota_open(partition, O_RDWR));
327 if (fd == -1) {
328 printf("failed to reopen %s for retry write && verify: %s\n", partition, strerror(errno));
329 return -1;
330 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800331 }
332
333 if (!success) {
334 printf("failed to verify after all attempts\n");
335 return -1;
336 }
337
Tao Bao3dc14cb2016-11-22 11:37:13 -0800338 if (ota_close(fd) == -1) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800339 printf("error closing %s: %s\n", partition, strerror(errno));
Tao Bao8fce75a2016-11-10 12:33:41 -0800340 return -1;
341 }
342 sync();
343
344 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800345}
346
Doug Zongker512536a2010-02-17 16:11:44 -0800347// Take a string 'str' of 40 hex digits and parse it into the 20
348// byte array 'digest'. 'str' may contain only the digest or be of
349// the form "<digest>:<anything>". Return 0 on success, -1 on any
350// error.
351int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800352 const char* ps = str;
353 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800354 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800355 int digit;
356 if (*ps >= '0' && *ps <= '9') {
357 digit = *ps - '0';
358 } else if (*ps >= 'a' && *ps <= 'f') {
359 digit = *ps - 'a' + 10;
360 } else if (*ps >= 'A' && *ps <= 'F') {
361 digit = *ps - 'A' + 10;
362 } else {
363 return -1;
364 }
365 if (i % 2 == 0) {
366 *pd = digit << 4;
367 } else {
368 *pd |= digit;
369 ++pd;
370 }
Doug Zongker512536a2010-02-17 16:11:44 -0800371 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800372 if (*ps != '\0') return -1;
373 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800374}
375
Doug Zongkerc4351c72010-02-22 14:46:32 -0800376// Search an array of sha1 strings for one matching the given sha1.
377// Return the index of the match on success, or -1 if no match is
378// found.
Tao Baoc8e79342016-12-28 10:11:22 -0800379static int FindMatchingPatch(uint8_t* sha1, const std::vector<std::string>& patch_sha1_str) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800380 for (size_t i = 0; i < patch_sha1_str.size(); ++i) {
381 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
382 if (ParseSha1(patch_sha1_str[i].c_str(), patch_sha1) == 0 &&
383 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
384 return i;
Doug Zongker512536a2010-02-17 16:11:44 -0800385 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800386 }
387 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800388}
389
390// Returns 0 if the contents of the file (argv[2]) or the cached file
391// match any of the sha1's on the command line (argv[3:]). Returns
392// nonzero otherwise.
Tianjie Xuaced5d92016-10-12 10:55:04 -0700393int applypatch_check(const char* filename, const std::vector<std::string>& patch_sha1_str) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800394 FileContents file;
Doug Zongker512536a2010-02-17 16:11:44 -0800395
Tao Bao8fce75a2016-11-10 12:33:41 -0800396 // It's okay to specify no sha1s; the check will pass if the
397 // LoadFileContents is successful. (Useful for reading
398 // partitions, where the filename encodes the sha1s; no need to
399 // check them twice.)
400 if (LoadFileContents(filename, &file) != 0 ||
401 (!patch_sha1_str.empty() && FindMatchingPatch(file.sha1, patch_sha1_str) < 0)) {
402 printf("file \"%s\" doesn't have any of expected sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800403
Tianjie Xua88cc542017-10-25 13:16:54 -0700404 // If the source file is missing or corrupted, it might be because we were killed in the middle
405 // of patching it. A copy of it should have been made in cache_temp_source. If that file
406 // exists and matches the sha1 we're looking for, the check still passes.
407 if (LoadFileContents(cache_temp_source.c_str(), &file) != 0) {
Tao Bao8fce75a2016-11-10 12:33:41 -0800408 printf("failed to load cache file\n");
409 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800410 }
Tao Bao8fce75a2016-11-10 12:33:41 -0800411
412 if (FindMatchingPatch(file.sha1, patch_sha1_str) < 0) {
413 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
414 return 1;
415 }
416 }
417 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800418}
419
420int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800421 ShowBSDiffLicense();
422 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800423}
424
Tao Baoc0e1c462017-02-01 10:20:10 -0800425static size_t FileSink(const unsigned char* data, size_t len, int fd) {
Tao Baof7eb7602017-03-27 15:12:48 -0700426 size_t done = 0;
427 while (done < len) {
428 ssize_t wrote = TEMP_FAILURE_RETRY(ota_write(fd, data + done, len - done));
429 if (wrote == -1) {
430 printf("error writing %zd bytes: %s\n", (len - done), strerror(errno));
431 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800432 }
Tao Baof7eb7602017-03-27 15:12:48 -0700433 done += wrote;
434 }
435 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800436}
437
Doug Zongker512536a2010-02-17 16:11:44 -0800438// Return the amount of free space (in bytes) on the filesystem
439// containing filename. filename must exist. Return -1 on error.
440size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800441 struct statfs sf;
442 if (statfs(filename, &sf) != 0) {
443 printf("failed to statfs %s: %s\n", filename, strerror(errno));
444 return -1;
445 }
caozhiyuan3b497762015-05-19 17:21:00 +0800446 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800447}
448
Doug Zongkerc4351c72010-02-22 14:46:32 -0800449int CacheSizeCheck(size_t bytes) {
450 if (MakeFreeSpaceOnCache(bytes) < 0) {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700451 printf("unable to make %zu bytes available on /cache\n", bytes);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800452 return 1;
453 } else {
454 return 0;
455 }
456}
457
Tao Bao40e144d2017-03-15 01:10:58 -0700458// This function applies binary patches to EMMC target files in a way that is safe (the original
459// file is not touched until we have the desired replacement for it) and idempotent (it's okay to
460// run this program multiple times).
Doug Zongker512536a2010-02-17 16:11:44 -0800461//
Tao Bao40e144d2017-03-15 01:10:58 -0700462// - If the SHA-1 hash of <target_filename> is <target_sha1_string>, does nothing and exits
463// successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800464//
Tao Bao40e144d2017-03-15 01:10:58 -0700465// - Otherwise, if the SHA-1 hash of <source_filename> is one of the entries in <patch_sha1_str>,
466// the corresponding patch from <patch_data> (which must be a VAL_BLOB) is applied to produce a
467// new file (the type of patch is automatically detected from the blob data). If that new file
468// has SHA-1 hash <target_sha1_str>, moves it to replace <target_filename>, and exits
469// successfully. Note that if <source_filename> and <target_filename> are not the same,
470// <source_filename> is NOT deleted on success. <target_filename> may be the string "-" to mean
471// "the same as <source_filename>".
Doug Zongker512536a2010-02-17 16:11:44 -0800472//
Tao Bao40e144d2017-03-15 01:10:58 -0700473// - Otherwise, or if any error is encountered, exits with non-zero status.
Doug Zongker512536a2010-02-17 16:11:44 -0800474//
Tao Bao40e144d2017-03-15 01:10:58 -0700475// <source_filename> must refer to an EMMC partition to read the source data. See the comments for
476// the LoadPartitionContents() function above for the format of such a filename. <target_size> has
477// become obsolete since we have dropped the support for patching non-EMMC targets (EMMC targets
478// have the size embedded in the filename).
479int applypatch(const char* source_filename, const char* target_filename,
480 const char* target_sha1_str, size_t target_size __unused,
Tianjie Xuaced5d92016-10-12 10:55:04 -0700481 const std::vector<std::string>& patch_sha1_str,
Tao Bao40e144d2017-03-15 01:10:58 -0700482 const std::vector<std::unique_ptr<Value>>& patch_data, const Value* bonus_data) {
483 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800484
Tao Bao40e144d2017-03-15 01:10:58 -0700485 if (target_filename[0] == '-' && target_filename[1] == '\0') {
486 target_filename = source_filename;
487 }
488
489 if (strncmp(target_filename, "EMMC:", 5) != 0) {
490 printf("Supporting patching EMMC targets only.\n");
491 return 1;
492 }
493
494 uint8_t target_sha1[SHA_DIGEST_LENGTH];
495 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
496 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
497 return 1;
498 }
499
500 // We try to load the target file into the source_file object.
501 FileContents source_file;
502 if (LoadFileContents(target_filename, &source_file) == 0) {
503 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
504 // The early-exit case: the patch was already applied, this file has the desired hash, nothing
505 // for us to do.
506 printf("already %s\n", short_sha1(target_sha1).c_str());
507 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800508 }
Tao Bao40e144d2017-03-15 01:10:58 -0700509 }
Doug Zongker512536a2010-02-17 16:11:44 -0800510
Tao Bao40e144d2017-03-15 01:10:58 -0700511 if (source_file.data.empty() ||
512 (target_filename != source_filename && strcmp(target_filename, source_filename) != 0)) {
513 // Need to load the source file: either we failed to load the target file, or we did but it's
514 // different from the expected.
515 source_file.data.clear();
516 LoadFileContents(source_filename, &source_file);
517 }
518
519 if (!source_file.data.empty()) {
520 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str);
521 if (to_use != -1) {
522 return GenerateTarget(source_file, patch_data[to_use], target_filename, target_sha1,
523 bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800524 }
Tao Bao40e144d2017-03-15 01:10:58 -0700525 }
Doug Zongker512536a2010-02-17 16:11:44 -0800526
Tao Bao40e144d2017-03-15 01:10:58 -0700527 printf("source file is bad; trying copy\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800528
Tao Bao40e144d2017-03-15 01:10:58 -0700529 FileContents copy_file;
Tianjie Xua88cc542017-10-25 13:16:54 -0700530 if (LoadFileContents(cache_temp_source.c_str(), &copy_file) < 0) {
Tao Bao40e144d2017-03-15 01:10:58 -0700531 printf("failed to read copy file\n");
532 return 1;
533 }
Doug Zongker512536a2010-02-17 16:11:44 -0800534
Tao Bao40e144d2017-03-15 01:10:58 -0700535 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str);
536 if (to_use == -1) {
537 printf("copy file doesn't match source SHA-1s either\n");
538 return 1;
539 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800540
Tao Bao40e144d2017-03-15 01:10:58 -0700541 return GenerateTarget(copy_file, patch_data[to_use], target_filename, target_sha1, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800542}
543
Tao Baoabba55b2015-07-17 18:11:12 -0700544/*
545 * This function flashes a given image to the target partition. It verifies
546 * the target cheksum first, and will return if target has the desired hash.
547 * It checks the checksum of the given source image before flashing, and
548 * verifies the target partition afterwards. The function is idempotent.
549 * Returns zero on success.
550 */
551int applypatch_flash(const char* source_filename, const char* target_filename,
552 const char* target_sha1_str, size_t target_size) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800553 printf("flash %s: ", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700554
Tao Bao6e02ea92016-11-17 11:24:07 -0800555 uint8_t target_sha1[SHA_DIGEST_LENGTH];
556 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
557 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
558 return 1;
559 }
Tao Baoabba55b2015-07-17 18:11:12 -0700560
Tao Bao6e02ea92016-11-17 11:24:07 -0800561 std::string target_str(target_filename);
562 std::vector<std::string> pieces = android::base::Split(target_str, ":");
563 if (pieces.size() != 2 || pieces[0] != "EMMC") {
564 printf("invalid target name \"%s\"", target_filename);
565 return 1;
566 }
Tao Baoabba55b2015-07-17 18:11:12 -0700567
Tao Bao6e02ea92016-11-17 11:24:07 -0800568 // Load the target into the source_file object to see if already applied.
569 pieces.push_back(std::to_string(target_size));
570 pieces.push_back(target_sha1_str);
571 std::string fullname = android::base::Join(pieces, ':');
572 FileContents source_file;
573 if (LoadPartitionContents(fullname, &source_file) == 0 &&
574 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
575 // The early-exit case: the image was already applied, this partition
576 // has the desired hash, nothing for us to do.
577 printf("already %s\n", short_sha1(target_sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700578 return 0;
Tao Bao6e02ea92016-11-17 11:24:07 -0800579 }
580
581 if (LoadFileContents(source_filename, &source_file) == 0) {
582 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
583 // The source doesn't have desired checksum.
584 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
585 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
586 short_sha1(source_file.sha1).c_str());
587 return 1;
588 }
589 }
590
591 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
592 printf("write of copied data to %s failed\n", target_filename);
593 return 1;
594 }
595 return 0;
Tao Baoabba55b2015-07-17 18:11:12 -0700596}
597
Tao Bao40e144d2017-03-15 01:10:58 -0700598static int GenerateTarget(const FileContents& source_file, const std::unique_ptr<Value>& patch,
599 const std::string& target_filename,
600 const uint8_t target_sha1[SHA_DIGEST_LENGTH], const Value* bonus_data) {
Tao Bao6e02ea92016-11-17 11:24:07 -0800601 if (patch->type != VAL_BLOB) {
602 printf("patch is not a blob\n");
603 return 1;
604 }
Yabin Cuid483c202016-02-03 17:08:52 -0800605
Tao Bao6e02ea92016-11-17 11:24:07 -0800606 const char* header = &patch->data[0];
607 size_t header_bytes_read = patch->data.size();
608 bool use_bsdiff = false;
609 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
610 use_bsdiff = true;
611 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
612 use_bsdiff = false;
613 } else {
614 printf("Unknown patch file format\n");
615 return 1;
616 }
Doug Zongker512536a2010-02-17 16:11:44 -0800617
Tao Bao40e144d2017-03-15 01:10:58 -0700618 CHECK(android::base::StartsWith(target_filename, "EMMC:"));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619
Tao Bao40e144d2017-03-15 01:10:58 -0700620 // We still write the original source to cache, in case the partition write is interrupted.
621 if (MakeFreeSpaceOnCache(source_file.data.size()) < 0) {
622 printf("not enough free space on /cache\n");
623 return 1;
624 }
Tianjie Xua88cc542017-10-25 13:16:54 -0700625 if (SaveFileContents(cache_temp_source.c_str(), &source_file) < 0) {
Tao Bao40e144d2017-03-15 01:10:58 -0700626 printf("failed to back up source file\n");
627 return 1;
628 }
629
630 // We store the decoded output in memory.
Tao Bao6e02ea92016-11-17 11:24:07 -0800631 std::string memory_sink_str; // Don't need to reserve space.
Tao Baoc0e1c462017-02-01 10:20:10 -0800632 SinkFn sink = [&memory_sink_str](const unsigned char* data, size_t len) {
633 memory_sink_str.append(reinterpret_cast<const char*>(data), len);
634 return len;
635 };
Doug Zongkerc4351c72010-02-22 14:46:32 -0800636
Tao Bao40e144d2017-03-15 01:10:58 -0700637 SHA_CTX ctx;
638 SHA1_Init(&ctx);
Tao Bao6e02ea92016-11-17 11:24:07 -0800639
Tao Bao40e144d2017-03-15 01:10:58 -0700640 int result;
641 if (use_bsdiff) {
Tao Bao1e0941f2017-11-10 11:49:53 -0800642 result =
643 ApplyBSDiffPatch(source_file.data.data(), source_file.data.size(), *patch, 0, sink, &ctx);
Tao Bao40e144d2017-03-15 01:10:58 -0700644 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -0800645 result = ApplyImagePatch(source_file.data.data(), source_file.data.size(), *patch, sink, &ctx,
646 bonus_data);
Tao Bao40e144d2017-03-15 01:10:58 -0700647 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800648
Tao Bao40e144d2017-03-15 01:10:58 -0700649 if (result != 0) {
650 printf("applying patch failed\n");
651 return 1;
652 }
Tao Bao6e02ea92016-11-17 11:24:07 -0800653
654 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
655 SHA1_Final(current_target_sha1, &ctx);
656 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
657 printf("patch did not produce expected sha1\n");
658 return 1;
659 } else {
660 printf("now %s\n", short_sha1(target_sha1).c_str());
661 }
662
Tao Bao40e144d2017-03-15 01:10:58 -0700663 // Write back the temp file to the partition.
664 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
665 memory_sink_str.size(), target_filename) != 0) {
666 printf("write of patched data to %s failed\n", target_filename.c_str());
667 return 1;
Tao Bao6e02ea92016-11-17 11:24:07 -0800668 }
669
Tao Bao40e144d2017-03-15 01:10:58 -0700670 // Delete the backup copy of the source.
Tianjie Xua88cc542017-10-25 13:16:54 -0700671 unlink(cache_temp_source.c_str());
Tao Bao6e02ea92016-11-17 11:24:07 -0800672
673 // Success!
674 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800675}