blob: cf155607b8d507e5f3fa19b21dbe5a824f94c406 [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
17#include <errno.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070018#include <fcntl.h>
Doug Zongker512536a2010-02-17 16:11:44 -080019#include <libgen.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <string.h>
23#include <sys/stat.h>
24#include <sys/statfs.h>
25#include <sys/types.h>
Doug Zongker512536a2010-02-17 16:11:44 -080026#include <unistd.h>
27
Yabin Cuid483c202016-02-03 17:08:52 -080028#include <memory>
29#include <string>
30
Elliott Hughes4b166f02015-12-04 15:30:20 -080031#include <android-base/strings.h>
Tao Baoaca8e892015-07-17 11:47:44 -070032
Sen Jiangc48cb5e2016-02-04 16:23:21 +080033#include "openssl/sha.h"
Tao Baod80a9982016-03-03 11:43:47 -080034#include "applypatch/applypatch.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080035#include "edify/expr.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080036#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include "print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080038
Doug Zongkerf291d852010-07-07 13:55:25 -070039static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070040static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080041static int GenerateTarget(FileContents* source_file,
42 const Value* source_patch_value,
43 FileContents* copy_file,
44 const Value* copy_patch_value,
45 const char* source_filename,
46 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080047 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070048 size_t target_size,
49 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080050
Doug Zongkera1bc1482014-02-13 15:18:19 -080051// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070052// metadata in *file.
53//
54// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080055int LoadFileContents(const char* filename, FileContents* file) {
Elliott Hughes63a31922016-06-09 17:41:22 -070056 // A special 'filename' beginning with "EMMC:" means to
Doug Zongkerf291d852010-07-07 13:55:25 -070057 // load the contents of a partition.
Elliott Hughes63a31922016-06-09 17:41:22 -070058 if (strncmp(filename, "EMMC:", 5) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -070059 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080060 }
Doug Zongker512536a2010-02-17 16:11:44 -080061
Doug Zongkerc4351c72010-02-22 14:46:32 -080062 if (stat(filename, &file->st) != 0) {
63 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
64 return -1;
65 }
66
Yabin Cuid6c93af2016-02-10 16:41:10 -080067 std::vector<unsigned char> data(file->st.st_size);
Jed Estepa7b9a462015-12-15 16:04:53 -080068 FILE* f = ota_fopen(filename, "rb");
Doug Zongkerc4351c72010-02-22 14:46:32 -080069 if (f == NULL) {
70 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -080071 return -1;
72 }
73
Yabin Cuid6c93af2016-02-10 16:41:10 -080074 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f);
75 if (bytes_read != data.size()) {
76 printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size());
Jed Estepa7b9a462015-12-15 16:04:53 -080077 ota_fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080078 return -1;
79 }
Jed Estepa7b9a462015-12-15 16:04:53 -080080 ota_fclose(f);
Yabin Cuid6c93af2016-02-10 16:41:10 -080081 file->data = std::move(data);
82 SHA1(file->data.data(), file->data.size(), file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080083 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080084}
85
Elliott Hughes63a31922016-06-09 17:41:22 -070086// Load the contents of an EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080087// FileContents. filename should be a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -070088// "EMMC:<partition_device>:...". The smallest size_n bytes for
Doug Zongkerf291d852010-07-07 13:55:25 -070089// which that prefix of the partition contents has the corresponding
90// sha1 hash will be loaded. It is acceptable for a size value to be
91// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080092//
93// This complexity is needed because if an OTA installation is
94// interrupted, the partition might contain either the source or the
95// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -070096// the length in order to read from a partition (there is no
97// "end-of-file" marker), so the caller must specify the possible
98// lengths and the hash of the data, and we'll do the load expecting
99// to find one of those hashes.
Doug Zongkerf291d852010-07-07 13:55:25 -0700100static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700101 std::string copy(filename);
102 std::vector<std::string> pieces = android::base::Split(copy, ":");
103 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
104 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
105 return -1;
106 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700107
Elliott Hughes63a31922016-06-09 17:41:22 -0700108 if (pieces[0] != "EMMC") {
Tao Baoba9a42a2015-06-23 23:23:33 -0700109 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800110 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800111 }
Tao Baoaca8e892015-07-17 11:47:44 -0700112 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800113
Tao Baoaca8e892015-07-17 11:47:44 -0700114 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
115 std::vector<size_t> index(pairs);
116 std::vector<size_t> size(pairs);
117 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800118
Tao Baoaca8e892015-07-17 11:47:44 -0700119 for (size_t i = 0; i < pairs; ++i) {
120 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800121 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700122 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800123 return -1;
124 }
Tao Baoaca8e892015-07-17 11:47:44 -0700125 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800126 index[i] = i;
127 }
Doug Zongker512536a2010-02-17 16:11:44 -0800128
Tao Baoaca8e892015-07-17 11:47:44 -0700129 // Sort the index[] array so it indexes the pairs in order of increasing size.
130 sort(index.begin(), index.end(),
131 [&](const size_t& i, const size_t& j) {
132 return (size[i] < size[j]);
133 }
134 );
Doug Zongker512536a2010-02-17 16:11:44 -0800135
Elliott Hughes63a31922016-06-09 17:41:22 -0700136 FILE* dev = ota_fopen(partition, "rb");
137 if (dev == NULL) {
138 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
139 return -1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800140 }
Doug Zongker512536a2010-02-17 16:11:44 -0800141
Doug Zongkerc4351c72010-02-22 14:46:32 -0800142 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800143 SHA1_Init(&sha_ctx);
144 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800145
Tao Baoaca8e892015-07-17 11:47:44 -0700146 // Allocate enough memory to hold the largest size.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800147 std::vector<unsigned char> data(size[index[pairs-1]]);
148 char* p = reinterpret_cast<char*>(data.data());
149 size_t data_size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700150 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800151
Tao Baoaca8e892015-07-17 11:47:44 -0700152 for (size_t i = 0; i < pairs; ++i) {
153 // Read enough additional bytes to get us up to the next size. (Again,
154 // we're trying the possibilities in order of increasing size).
Yabin Cuid6c93af2016-02-10 16:41:10 -0800155 size_t next = size[index[i]] - data_size;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800156 if (next > 0) {
Elliott Hughes63a31922016-06-09 17:41:22 -0700157 size_t read = ota_fread(p, 1, next, dev);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800158 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700159 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800160 read, next, partition);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800161 return -1;
162 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800163 SHA1_Update(&sha_ctx, p, read);
Yabin Cuid6c93af2016-02-10 16:41:10 -0800164 data_size += read;
165 p += read;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800166 }
167
168 // Duplicate the SHA context and finalize the duplicate so we can
169 // check it against this pair's expected hash.
170 SHA_CTX temp_ctx;
171 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800172 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
173 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800174
Tao Baoaca8e892015-07-17 11:47:44 -0700175 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
176 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800177 return -1;
178 }
179
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800180 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800181 // we have a match. stop reading the partition; we'll return
182 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700183 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700184 size[index[i]], sha1sum[index[i]].c_str());
185 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800186 break;
187 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800188 }
189
Elliott Hughes63a31922016-06-09 17:41:22 -0700190 ota_fclose(dev);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800191
Tao Baoaca8e892015-07-17 11:47:44 -0700192 if (!found) {
193 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700194 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800195 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800196 }
197
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800198 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800199
Yabin Cuid6c93af2016-02-10 16:41:10 -0800200 data.resize(data_size);
201 file->data = std::move(data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800202 // Fake some stat() info.
203 file->st.st_mode = 0644;
204 file->st.st_uid = 0;
205 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800206
Doug Zongkerc4351c72010-02-22 14:46:32 -0800207 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800208}
209
210
211// Save the contents of the given FileContents object under the given
212// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800213int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800214 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800215 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700216 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800217 return -1;
218 }
Doug Zongker512536a2010-02-17 16:11:44 -0800219
Yabin Cuid6c93af2016-02-10 16:41:10 -0800220 ssize_t bytes_written = FileSink(file->data.data(), file->data.size(), &fd);
221 if (bytes_written != static_cast<ssize_t>(file->data.size())) {
222 printf("short write of \"%s\" (%zd bytes of %zu) (%s)\n",
223 filename, bytes_written, file->data.size(), strerror(errno));
Jed Estepa7b9a462015-12-15 16:04:53 -0800224 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800225 return -1;
226 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800227 if (ota_fsync(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700228 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
229 return -1;
230 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800231 if (ota_close(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700232 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
233 return -1;
234 }
Doug Zongker512536a2010-02-17 16:11:44 -0800235
Doug Zongker1c43c972012-02-28 11:07:09 -0800236 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800237 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
238 return -1;
239 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800240 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800241 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
242 return -1;
243 }
Doug Zongker512536a2010-02-17 16:11:44 -0800244
Doug Zongkerc4351c72010-02-22 14:46:32 -0800245 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800246}
247
Doug Zongkerf291d852010-07-07 13:55:25 -0700248// Write a memory buffer to 'target' partition, a string of the form
Elliott Hughes63a31922016-06-09 17:41:22 -0700249// "EMMC:<partition_device>[:...]". The target name
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700250// might contain multiple colons, but WriteToPartition() only uses the first
251// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800252int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700253 std::string copy(target);
254 std::vector<std::string> pieces = android::base::Split(copy, ":");
255
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700256 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700257 printf("WriteToPartition called with bad target (%s)\n", target);
258 return -1;
259 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700260
Elliott Hughes63a31922016-06-09 17:41:22 -0700261 if (pieces[0] != "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700262 printf("WriteToPartition called with bad target (%s)\n", target);
263 return -1;
264 }
Tao Baoaca8e892015-07-17 11:47:44 -0700265 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800266
Elliott Hughes63a31922016-06-09 17:41:22 -0700267 size_t start = 0;
268 bool success = false;
269 int fd = ota_open(partition, O_RDWR | O_SYNC);
270 if (fd < 0) {
271 printf("failed to open %s: %s\n", partition, strerror(errno));
272 return -1;
273 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700274
Elliott Hughes63a31922016-06-09 17:41:22 -0700275 for (size_t attempt = 0; attempt < 2; ++attempt) {
276 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
277 printf("failed seek on %s: %s\n", partition, strerror(errno));
278 return -1;
279 }
280 while (start < len) {
281 size_t to_write = len - start;
282 if (to_write > 1<<20) to_write = 1<<20;
283
284 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data+start, to_write));
285 if (written == -1) {
286 printf("failed write writing to %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700287 return -1;
288 }
Elliott Hughes63a31922016-06-09 17:41:22 -0700289 start += written;
290 }
291 if (ota_fsync(fd) != 0) {
292 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
293 return -1;
294 }
295 if (ota_close(fd) != 0) {
296 printf("failed to close %s (%s)\n", partition, strerror(errno));
297 return -1;
298 }
299 fd = ota_open(partition, O_RDONLY);
300 if (fd < 0) {
301 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
302 return -1;
Tao Baoba9a42a2015-06-23 23:23:33 -0700303 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700304
Elliott Hughes63a31922016-06-09 17:41:22 -0700305 // Drop caches so our subsequent verification read
306 // won't just be reading the cache.
307 sync();
308 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
309 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
310 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
311 } else {
312 printf(" caches dropped\n");
313 }
314 ota_close(dc);
315 sleep(1);
316
317 // verify
318 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
319 printf("failed to seek back to beginning of %s: %s\n",
320 partition, strerror(errno));
321 return -1;
322 }
323 unsigned char buffer[4096];
324 start = len;
325 for (size_t p = 0; p < len; p += sizeof(buffer)) {
326 size_t to_read = len - p;
327 if (to_read > sizeof(buffer)) {
328 to_read = sizeof(buffer);
Doug Zongkerf291d852010-07-07 13:55:25 -0700329 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700330
Elliott Hughes63a31922016-06-09 17:41:22 -0700331 size_t so_far = 0;
332 while (so_far < to_read) {
333 ssize_t read_count =
334 TEMP_FAILURE_RETRY(ota_read(fd, buffer+so_far, to_read-so_far));
335 if (read_count == -1) {
336 printf("verify read error %s at %zu: %s\n",
337 partition, p, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700338 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700339 } else if (read_count == 0) {
340 printf("verify read reached unexpected EOF, %s at %zu\n", partition, p);
341 return -1;
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700342 }
Elliott Hughes63a31922016-06-09 17:41:22 -0700343 if (static_cast<size_t>(read_count) < to_read) {
344 printf("short verify read %s at %zu: %zd %zu %s\n",
345 partition, p, read_count, to_read, strerror(errno));
Doug Zongker044a0b42013-07-08 09:42:54 -0700346 }
Elliott Hughes63a31922016-06-09 17:41:22 -0700347 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700348 }
349
Elliott Hughes63a31922016-06-09 17:41:22 -0700350 if (memcmp(buffer, data+p, to_read) != 0) {
351 printf("verification failed starting at %zu\n", p);
352 start = p;
353 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700354 }
Elliott Hughes63a31922016-06-09 17:41:22 -0700355 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700356
Elliott Hughes63a31922016-06-09 17:41:22 -0700357 if (start == len) {
358 printf("verification read succeeded (attempt %zu)\n", attempt+1);
359 success = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700360 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700361 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800362 }
Doug Zongker512536a2010-02-17 16:11:44 -0800363
Elliott Hughes63a31922016-06-09 17:41:22 -0700364 if (!success) {
365 printf("failed to verify after all attempts\n");
366 return -1;
367 }
368
369 if (ota_close(fd) != 0) {
370 printf("error closing %s (%s)\n", partition, strerror(errno));
371 return -1;
372 }
373 sync();
374
Doug Zongkerc4351c72010-02-22 14:46:32 -0800375 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800376}
377
378
379// Take a string 'str' of 40 hex digits and parse it into the 20
380// byte array 'digest'. 'str' may contain only the digest or be of
381// the form "<digest>:<anything>". Return 0 on success, -1 on any
382// error.
383int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800384 const char* ps = str;
385 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800386 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800387 int digit;
388 if (*ps >= '0' && *ps <= '9') {
389 digit = *ps - '0';
390 } else if (*ps >= 'a' && *ps <= 'f') {
391 digit = *ps - 'a' + 10;
392 } else if (*ps >= 'A' && *ps <= 'F') {
393 digit = *ps - 'A' + 10;
394 } else {
395 return -1;
396 }
397 if (i % 2 == 0) {
398 *pd = digit << 4;
399 } else {
400 *pd |= digit;
401 ++pd;
402 }
Doug Zongker512536a2010-02-17 16:11:44 -0800403 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800404 if (*ps != '\0') return -1;
405 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800406}
407
Doug Zongkerc4351c72010-02-22 14:46:32 -0800408// Search an array of sha1 strings for one matching the given sha1.
409// Return the index of the match on success, or -1 if no match is
410// found.
Tianjie Xuaced5d92016-10-12 10:55:04 -0700411int FindMatchingPatch(uint8_t* sha1, const std::vector<std::string>& patch_sha1_str) {
412 for (size_t i = 0; i < patch_sha1_str.size(); ++i) {
413 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
414 if (ParseSha1(patch_sha1_str[i].c_str(), patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800415 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800416 return i;
417 }
Doug Zongker512536a2010-02-17 16:11:44 -0800418 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800419 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800420}
421
422// Returns 0 if the contents of the file (argv[2]) or the cached file
423// match any of the sha1's on the command line (argv[3:]). Returns
424// nonzero otherwise.
Tianjie Xuaced5d92016-10-12 10:55:04 -0700425int applypatch_check(const char* filename, const std::vector<std::string>& patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800426 FileContents file;
Doug Zongker512536a2010-02-17 16:11:44 -0800427
Doug Zongkerc4351c72010-02-22 14:46:32 -0800428 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700429 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800430 // partitions, where the filename encodes the sha1s; no need to
431 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800432 if (LoadFileContents(filename, &file) != 0 ||
Tianjie Xuaced5d92016-10-12 10:55:04 -0700433 FindMatchingPatch(file.sha1, patch_sha1_str) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800434 printf("file \"%s\" doesn't have any of expected "
435 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800436
Doug Zongkerc4351c72010-02-22 14:46:32 -0800437 // If the source file is missing or corrupted, it might be because
438 // we were killed in the middle of patching it. A copy of it
439 // should have been made in CACHE_TEMP_SOURCE. If that file
440 // exists and matches the sha1 we're looking for, the check still
441 // passes.
442
Doug Zongkera1bc1482014-02-13 15:18:19 -0800443 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800444 printf("failed to load cache file\n");
445 return 1;
446 }
447
Tianjie Xuaced5d92016-10-12 10:55:04 -0700448 if (FindMatchingPatch(file.sha1, patch_sha1_str) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800449 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800450 return 1;
451 }
452 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800453 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800454}
455
456int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800457 ShowBSDiffLicense();
458 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800459}
460
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700461ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800462 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800463 ssize_t done = 0;
464 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700465 while (done < len) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800466 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700467 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700468 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800469 return done;
470 }
471 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800472 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800473 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800474}
475
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700476ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800477 std::string* s = static_cast<std::string*>(token);
478 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800479 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800480}
481
482// Return the amount of free space (in bytes) on the filesystem
483// containing filename. filename must exist. Return -1 on error.
484size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800485 struct statfs sf;
486 if (statfs(filename, &sf) != 0) {
487 printf("failed to statfs %s: %s\n", filename, strerror(errno));
488 return -1;
489 }
caozhiyuan3b497762015-05-19 17:21:00 +0800490 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800491}
492
Doug Zongkerc4351c72010-02-22 14:46:32 -0800493int CacheSizeCheck(size_t bytes) {
494 if (MakeFreeSpaceOnCache(bytes) < 0) {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700495 printf("unable to make %zu bytes available on /cache\n", bytes);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800496 return 1;
497 } else {
498 return 0;
499 }
500}
501
Doug Zongkerc4351c72010-02-22 14:46:32 -0800502// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800503// (the original file is not touched until we have the desired
504// replacement for it) and idempotent (it's okay to run this program
505// multiple times).
506//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800507// - if the sha1 hash of <target_filename> is <target_sha1_string>,
508// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800509//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800510// - otherwise, if the sha1 hash of <source_filename> is one of the
511// entries in <patch_sha1_str>, the corresponding patch from
512// <patch_data> (which must be a VAL_BLOB) is applied to produce a
513// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700514// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800515// moves it to replace <target_filename>, and exits successfully.
516// Note that if <source_filename> and <target_filename> are not the
517// same, <source_filename> is NOT deleted on success.
518// <target_filename> may be the string "-" to mean "the same as
519// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800520//
521// - otherwise, or if any error is encountered, exits with non-zero
522// status.
523//
Doug Zongkerf291d852010-07-07 13:55:25 -0700524// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700525// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800526// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800527
Doug Zongkerc4351c72010-02-22 14:46:32 -0800528int applypatch(const char* source_filename,
529 const char* target_filename,
530 const char* target_sha1_str,
531 size_t target_size,
Tianjie Xuaced5d92016-10-12 10:55:04 -0700532 const std::vector<std::string>& patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700533 Value** patch_data,
534 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700535 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800536
Tao Baoba9a42a2015-06-23 23:23:33 -0700537 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800538 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800539 }
540
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800541 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800542 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
543 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800544 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800545 }
Doug Zongker512536a2010-02-17 16:11:44 -0800546
Doug Zongkerc4351c72010-02-22 14:46:32 -0800547 FileContents copy_file;
548 FileContents source_file;
549 const Value* source_patch_value = NULL;
550 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800551
Doug Zongkerc4351c72010-02-22 14:46:32 -0800552 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800553 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800554 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800555 // The early-exit case: the patch was already applied, this file
556 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700557 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800558 return 0;
559 }
560 }
Doug Zongker512536a2010-02-17 16:11:44 -0800561
Yabin Cuid6c93af2016-02-10 16:41:10 -0800562 if (source_file.data.empty() ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800563 (target_filename != source_filename &&
564 strcmp(target_filename, source_filename) != 0)) {
565 // Need to load the source file: either we failed to load the
566 // target file, or we did but it's different from the source file.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800567 source_file.data.clear();
Doug Zongkera1bc1482014-02-13 15:18:19 -0800568 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800569 }
570
Yabin Cuid6c93af2016-02-10 16:41:10 -0800571 if (!source_file.data.empty()) {
Tianjie Xuaced5d92016-10-12 10:55:04 -0700572 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800573 if (to_use >= 0) {
574 source_patch_value = patch_data[to_use];
575 }
576 }
577
578 if (source_patch_value == NULL) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800579 source_file.data.clear();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800580 printf("source file is bad; trying copy\n");
581
Doug Zongkera1bc1482014-02-13 15:18:19 -0800582 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800583 // fail.
584 printf("failed to read copy file\n");
585 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800586 }
587
Tianjie Xuaced5d92016-10-12 10:55:04 -0700588 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700589 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800590 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800591 }
592
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593 if (copy_patch_value == NULL) {
594 // fail.
595 printf("copy file doesn't match source SHA-1s either\n");
596 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800597 }
Doug Zongker512536a2010-02-17 16:11:44 -0800598 }
599
Yabin Cuid6c93af2016-02-10 16:41:10 -0800600 return GenerateTarget(&source_file, source_patch_value,
601 &copy_file, copy_patch_value,
602 source_filename, target_filename,
603 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800604}
605
Tao Baoabba55b2015-07-17 18:11:12 -0700606/*
607 * This function flashes a given image to the target partition. It verifies
608 * the target cheksum first, and will return if target has the desired hash.
609 * It checks the checksum of the given source image before flashing, and
610 * verifies the target partition afterwards. The function is idempotent.
611 * Returns zero on success.
612 */
613int applypatch_flash(const char* source_filename, const char* target_filename,
614 const char* target_sha1_str, size_t target_size) {
615 printf("flash %s: ", target_filename);
616
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800617 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700618 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
619 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
620 return 1;
621 }
622
623 FileContents source_file;
Tao Baoabba55b2015-07-17 18:11:12 -0700624 std::string target_str(target_filename);
625
626 std::vector<std::string> pieces = android::base::Split(target_str, ":");
Elliott Hughes63a31922016-06-09 17:41:22 -0700627 if (pieces.size() != 2 || pieces[0] != "EMMC") {
Tao Baoabba55b2015-07-17 18:11:12 -0700628 printf("invalid target name \"%s\"", target_filename);
629 return 1;
630 }
631
632 // Load the target into the source_file object to see if already applied.
633 pieces.push_back(std::to_string(target_size));
634 pieces.push_back(target_sha1_str);
635 std::string fullname = android::base::Join(pieces, ':');
636 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800637 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700638 // The early-exit case: the image was already applied, this partition
639 // has the desired hash, nothing for us to do.
640 printf("already %s\n", short_sha1(target_sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700641 return 0;
642 }
643
644 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800645 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700646 // The source doesn't have desired checksum.
647 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
648 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
649 short_sha1(source_file.sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700650 return 1;
651 }
652 }
653
Yabin Cuid6c93af2016-02-10 16:41:10 -0800654 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700655 printf("write of copied data to %s failed\n", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700656 return 1;
657 }
Tao Baoabba55b2015-07-17 18:11:12 -0700658 return 0;
659}
660
Doug Zongker1c43c972012-02-28 11:07:09 -0800661static int GenerateTarget(FileContents* source_file,
662 const Value* source_patch_value,
663 FileContents* copy_file,
664 const Value* copy_patch_value,
665 const char* source_filename,
666 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800667 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700668 size_t target_size,
669 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800670 int retry = 1;
671 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800672 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800673 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800674 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800675
Elliott Hughes63a31922016-06-09 17:41:22 -0700676 bool target_is_partition = (strncmp(target_filename, "EMMC:", 5) == 0);
Yabin Cuid483c202016-02-03 17:08:52 -0800677 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
678
Doug Zongkerc4351c72010-02-22 14:46:32 -0800679 // assume that target_filename (eg "/system/app/Foo.apk") is located
680 // on the same filesystem as its top-level directory ("/system").
681 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800682 std::string target_fs = target_filename;
683 auto slash_pos = target_fs.find('/', 1);
684 if (slash_pos != std::string::npos) {
685 target_fs.resize(slash_pos);
686 }
687
688 const Value* patch;
689 if (source_patch_value != NULL) {
690 source_to_use = source_file;
691 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800692 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800693 source_to_use = copy_file;
694 patch = copy_patch_value;
695 }
696 if (patch->type != VAL_BLOB) {
697 printf("patch is not a blob\n");
698 return 1;
699 }
Tianjie Xuaced5d92016-10-12 10:55:04 -0700700 const char* header = &patch->data[0];
701 size_t header_bytes_read = patch->data.size();
Yabin Cuid483c202016-02-03 17:08:52 -0800702 bool use_bsdiff = false;
703 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
704 use_bsdiff = true;
705 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
706 use_bsdiff = false;
707 } else {
708 printf("Unknown patch file format\n");
709 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800710 }
711
Doug Zongkerc4351c72010-02-22 14:46:32 -0800712 do {
713 // Is there enough room in the target filesystem to hold the patched
714 // file?
715
Yabin Cuid483c202016-02-03 17:08:52 -0800716 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700717 // If the target is a partition, we're actually going to
718 // write the output to /tmp and then copy it to the
719 // partition. statfs() always returns 0 blocks free for
720 // /tmp, so instead we'll just assume that /tmp has enough
721 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800722
Doug Zongkerf291d852010-07-07 13:55:25 -0700723 // We still write the original source to cache, in case
724 // the partition write is interrupted.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800725 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726 printf("not enough free space on /cache\n");
727 return 1;
728 }
729 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
730 printf("failed to back up source file\n");
731 return 1;
732 }
733 made_copy = 1;
734 retry = 0;
735 } else {
736 int enough_space = 0;
737 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800738 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700739 enough_space =
740 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800741 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700742 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700743 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
744 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700745 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800746 }
747
748 if (!enough_space) {
749 retry = 0;
750 }
751
752 if (!enough_space && source_patch_value != NULL) {
753 // Using the original source, but not enough free space. First
754 // copy the source file to cache, then delete it from the original
755 // location.
756
Elliott Hughes63a31922016-06-09 17:41:22 -0700757 if (strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800758 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700759 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800760 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700761 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800762 return 1;
763 }
764
Yabin Cuid6c93af2016-02-10 16:41:10 -0800765 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800766 printf("not enough free space on /cache\n");
767 return 1;
768 }
769
770 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
771 printf("failed to back up source file\n");
772 return 1;
773 }
774 made_copy = 1;
775 unlink(source_filename);
776
Yabin Cuid483c202016-02-03 17:08:52 -0800777 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Tao Baoba9a42a2015-06-23 23:23:33 -0700778 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800779 }
780 }
781
Doug Zongkerc4351c72010-02-22 14:46:32 -0800782
783 SinkFn sink = NULL;
784 void* token = NULL;
Yabin Cuid483c202016-02-03 17:08:52 -0800785 int output_fd = -1;
786 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800787 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800788 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800789 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800790 } else {
791 // We write the decoded output to "<tgt-file>.patch".
Jed Estepa7b9a462015-12-15 16:04:53 -0800792 output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
793 S_IRUSR | S_IWUSR);
Yabin Cuid483c202016-02-03 17:08:52 -0800794 if (output_fd < 0) {
795 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
796 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800797 return 1;
798 }
799 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800800 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800801 }
802
Doug Zongkerc4351c72010-02-22 14:46:32 -0800803
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800804 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800805
806 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800807 if (use_bsdiff) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800808 result = ApplyBSDiffPatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkerc4351c72010-02-22 14:46:32 -0800809 patch, 0, sink, token, &ctx);
Yabin Cuid483c202016-02-03 17:08:52 -0800810 } else {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800811 result = ApplyImagePatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkera3ccba62012-08-20 15:28:02 -0700812 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800813 }
814
Yabin Cuid483c202016-02-03 17:08:52 -0800815 if (!target_is_partition) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800816 if (ota_fsync(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800817 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
818 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700819 result = 1;
820 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800821 if (ota_close(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800822 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
823 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700824 result = 1;
825 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800826 }
827
828 if (result != 0) {
829 if (retry == 0) {
830 printf("applying patch failed\n");
831 return result != 0;
832 } else {
833 printf("applying patch failed; retrying\n");
834 }
Yabin Cuid483c202016-02-03 17:08:52 -0800835 if (!target_is_partition) {
836 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800837 }
838 } else {
839 // succeeded; no need to retry
840 break;
841 }
842 } while (retry-- > 0);
843
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800844 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
845 SHA1_Final(current_target_sha1, &ctx);
846 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800847 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800848 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700849 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700850 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800851 }
852
Yabin Cuid483c202016-02-03 17:08:52 -0800853 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700854 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -0800855 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
856 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800857 printf("write of patched data to %s failed\n", target_filename);
858 return 1;
859 }
Doug Zongker512536a2010-02-17 16:11:44 -0800860 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800861 // Give the .patch file the same owner, group, and mode of the
862 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -0800863 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
864 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800865 return 1;
866 }
Yabin Cuid483c202016-02-03 17:08:52 -0800867 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
868 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800869 return 1;
870 }
Doug Zongker512536a2010-02-17 16:11:44 -0800871
Doug Zongkerc4351c72010-02-22 14:46:32 -0800872 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -0800873 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700874 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800875 return 1;
876 }
Doug Zongker512536a2010-02-17 16:11:44 -0800877 }
878
Doug Zongkerc4351c72010-02-22 14:46:32 -0800879 // If this run of applypatch created the copy, and we're here, we
880 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -0700881 if (made_copy) {
882 unlink(CACHE_TEMP_SOURCE);
883 }
Doug Zongker512536a2010-02-17 16:11:44 -0800884
Doug Zongkerc4351c72010-02-22 14:46:32 -0800885 // Success!
886 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800887}