blob: 5f591b05abb2214bc4ce9e40b009a5d0c9e50202 [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
Elliott Hughes4b166f02015-12-04 15:30:20 -080028#include <android-base/strings.h>
Tao Baoaca8e892015-07-17 11:47:44 -070029
Sen Jiangc48cb5e2016-02-04 16:23:21 +080030#include "openssl/sha.h"
Doug Zongker512536a2010-02-17 16:11:44 -080031#include "applypatch.h"
32#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080033#include "edify/expr.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070034#include "print_sha1.h"
Jed Estepf1fc48c2015-12-15 16:04:53 -080035#include "otafault/ota_io.h"
Doug Zongker512536a2010-02-17 16:11:44 -080036
Doug Zongkerf291d852010-07-07 13:55:25 -070037static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070038static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080039static int GenerateTarget(FileContents* source_file,
40 const Value* source_patch_value,
41 FileContents* copy_file,
42 const Value* copy_patch_value,
43 const char* source_filename,
44 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080045 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070046 size_t target_size,
47 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080048
Tao Baoaca8e892015-07-17 11:47:44 -070049static bool mtd_partitions_scanned = false;
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) {
Doug Zongker512536a2010-02-17 16:11:44 -080056 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080057
Doug Zongkerf291d852010-07-07 13:55:25 -070058 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
59 // load the contents of a partition.
60 if (strncmp(filename, "MTD:", 4) == 0 ||
61 strncmp(filename, "EMMC:", 5) == 0) {
62 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080063 }
Doug Zongker512536a2010-02-17 16:11:44 -080064
Doug Zongkerc4351c72010-02-22 14:46:32 -080065 if (stat(filename, &file->st) != 0) {
66 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
67 return -1;
68 }
69
70 file->size = file->st.st_size;
Tao Baoba9a42a2015-06-23 23:23:33 -070071 file->data = reinterpret_cast<unsigned char*>(malloc(file->size));
Doug Zongkerc4351c72010-02-22 14:46:32 -080072
Jed Estepf1fc48c2015-12-15 16:04:53 -080073 FILE* f = ota_fopen(filename, "rb");
Doug Zongkerc4351c72010-02-22 14:46:32 -080074 if (f == NULL) {
75 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
76 free(file->data);
77 file->data = NULL;
78 return -1;
79 }
80
Jed Estepf1fc48c2015-12-15 16:04:53 -080081 size_t bytes_read = ota_fread(file->data, 1, file->size, f);
Tao Baoba9a42a2015-06-23 23:23:33 -070082 if (bytes_read != static_cast<size_t>(file->size)) {
83 printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
Doug Zongkerc4351c72010-02-22 14:46:32 -080084 free(file->data);
85 file->data = NULL;
86 return -1;
87 }
Jed Estepf1fc48c2015-12-15 16:04:53 -080088 ota_fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080089
Sen Jiangc48cb5e2016-02-04 16:23:21 +080090 SHA1(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080091 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080092}
93
Doug Zongkerf291d852010-07-07 13:55:25 -070094// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080095// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -070096// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
97// "EMMC:<partition_device>:..."). The smallest size_n bytes for
98// which that prefix of the partition contents has the corresponding
99// sha1 hash will be loaded. It is acceptable for a size value to be
100// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800101//
102// This complexity is needed because if an OTA installation is
103// interrupted, the partition might contain either the source or the
104// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700105// the length in order to read from a partition (there is no
106// "end-of-file" marker), so the caller must specify the possible
107// lengths and the hash of the data, and we'll do the load expecting
108// to find one of those hashes.
109enum PartitionType { MTD, EMMC };
110
111static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700112 std::string copy(filename);
113 std::vector<std::string> pieces = android::base::Split(copy, ":");
114 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
115 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
116 return -1;
117 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700118
119 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700120 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700121 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700122 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700123 type = EMMC;
124 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700125 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800126 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800127 }
Tao Baoaca8e892015-07-17 11:47:44 -0700128 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800129
Tao Baoaca8e892015-07-17 11:47:44 -0700130 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
131 std::vector<size_t> index(pairs);
132 std::vector<size_t> size(pairs);
133 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800134
Tao Baoaca8e892015-07-17 11:47:44 -0700135 for (size_t i = 0; i < pairs; ++i) {
136 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800137 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700138 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800139 return -1;
140 }
Tao Baoaca8e892015-07-17 11:47:44 -0700141 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800142 index[i] = i;
143 }
Doug Zongker512536a2010-02-17 16:11:44 -0800144
Tao Baoaca8e892015-07-17 11:47:44 -0700145 // Sort the index[] array so it indexes the pairs in order of increasing size.
146 sort(index.begin(), index.end(),
147 [&](const size_t& i, const size_t& j) {
148 return (size[i] < size[j]);
149 }
150 );
Doug Zongker512536a2010-02-17 16:11:44 -0800151
Doug Zongkerf291d852010-07-07 13:55:25 -0700152 MtdReadContext* ctx = NULL;
153 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800154
Doug Zongkerf291d852010-07-07 13:55:25 -0700155 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700156 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700157 if (!mtd_partitions_scanned) {
158 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700159 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700160 }
Doug Zongker512536a2010-02-17 16:11:44 -0800161
Doug Zongkerf291d852010-07-07 13:55:25 -0700162 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
163 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700164 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700165 return -1;
166 }
167
168 ctx = mtd_read_partition(mtd);
169 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700170 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700171 return -1;
172 }
173 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700174 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700175
176 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800177 dev = ota_fopen(partition, "rb");
Doug Zongkerf291d852010-07-07 13:55:25 -0700178 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700179 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700180 return -1;
181 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800182 }
Doug Zongker512536a2010-02-17 16:11:44 -0800183
Doug Zongkerc4351c72010-02-22 14:46:32 -0800184 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800185 SHA1_Init(&sha_ctx);
186 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800187
Tao Baoaca8e892015-07-17 11:47:44 -0700188 // Allocate enough memory to hold the largest size.
Tao Baoba9a42a2015-06-23 23:23:33 -0700189 file->data = reinterpret_cast<unsigned char*>(malloc(size[index[pairs-1]]));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800190 char* p = (char*)file->data;
191 file->size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700192 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800193
Tao Baoaca8e892015-07-17 11:47:44 -0700194 for (size_t i = 0; i < pairs; ++i) {
195 // Read enough additional bytes to get us up to the next size. (Again,
196 // we're trying the possibilities in order of increasing size).
Doug Zongkerc4351c72010-02-22 14:46:32 -0800197 size_t next = size[index[i]] - file->size;
198 size_t read = 0;
199 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700200 switch (type) {
201 case MTD:
202 read = mtd_read_data(ctx, p, next);
203 break;
204
205 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800206 read = ota_fread(p, 1, next, dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700207 break;
208 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800209 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700210 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800211 read, next, partition);
212 free(file->data);
213 file->data = NULL;
214 return -1;
215 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800216 SHA1_Update(&sha_ctx, p, read);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800217 file->size += read;
218 }
219
220 // Duplicate the SHA context and finalize the duplicate so we can
221 // check it against this pair's expected hash.
222 SHA_CTX temp_ctx;
223 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800224 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
225 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800226
Tao Baoaca8e892015-07-17 11:47:44 -0700227 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
228 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800229 free(file->data);
230 file->data = NULL;
231 return -1;
232 }
233
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800234 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800235 // we have a match. stop reading the partition; we'll return
236 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700237 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700238 size[index[i]], sha1sum[index[i]].c_str());
239 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800240 break;
241 }
242
243 p += read;
244 }
245
Doug Zongkerf291d852010-07-07 13:55:25 -0700246 switch (type) {
247 case MTD:
248 mtd_read_close(ctx);
249 break;
250
251 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800252 ota_fclose(dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700253 break;
254 }
255
Doug Zongkerc4351c72010-02-22 14:46:32 -0800256
Tao Baoaca8e892015-07-17 11:47:44 -0700257 if (!found) {
258 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700259 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800260 free(file->data);
261 file->data = NULL;
262 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800263 }
264
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800265 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800266
Doug Zongkerc4351c72010-02-22 14:46:32 -0800267 // Fake some stat() info.
268 file->st.st_mode = 0644;
269 file->st.st_uid = 0;
270 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800271
Doug Zongkerc4351c72010-02-22 14:46:32 -0800272 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800273}
274
275
276// Save the contents of the given FileContents object under the given
277// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800278int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800279 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800280 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700281 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800282 return -1;
283 }
Doug Zongker512536a2010-02-17 16:11:44 -0800284
Doug Zongker1c43c972012-02-28 11:07:09 -0800285 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
286 if (bytes_written != file->size) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700287 printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
288 filename, bytes_written, file->size, strerror(errno));
Jed Estepf1fc48c2015-12-15 16:04:53 -0800289 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800290 return -1;
291 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800292 if (ota_fsync(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700293 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
294 return -1;
295 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800296 if (ota_close(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700297 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
298 return -1;
299 }
Doug Zongker512536a2010-02-17 16:11:44 -0800300
Doug Zongker1c43c972012-02-28 11:07:09 -0800301 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800302 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
303 return -1;
304 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800305 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800306 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
307 return -1;
308 }
Doug Zongker512536a2010-02-17 16:11:44 -0800309
Doug Zongkerc4351c72010-02-22 14:46:32 -0800310 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800311}
312
Doug Zongkerf291d852010-07-07 13:55:25 -0700313// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700314// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
315// might contain multiple colons, but WriteToPartition() only uses the first
316// two and ignores the rest. Return 0 on success.
Tao Baoba9a42a2015-06-23 23:23:33 -0700317int WriteToPartition(unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700318 std::string copy(target);
319 std::vector<std::string> pieces = android::base::Split(copy, ":");
320
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700321 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700322 printf("WriteToPartition called with bad target (%s)\n", target);
323 return -1;
324 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700325
326 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700327 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700328 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700329 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700330 type = EMMC;
331 } else {
332 printf("WriteToPartition called with bad target (%s)\n", target);
333 return -1;
334 }
Tao Baoaca8e892015-07-17 11:47:44 -0700335 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800336
Doug Zongkerf291d852010-07-07 13:55:25 -0700337 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700338 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700339 if (!mtd_partitions_scanned) {
340 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700341 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700342 }
343
344 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
345 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700346 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700347 return -1;
348 }
349
350 MtdWriteContext* ctx = mtd_write_partition(mtd);
351 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700352 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700353 return -1;
354 }
355
Tao Baoba9a42a2015-06-23 23:23:33 -0700356 size_t written = mtd_write_data(ctx, reinterpret_cast<char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700357 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700358 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700359 mtd_write_close(ctx);
360 return -1;
361 }
362
363 if (mtd_erase_blocks(ctx, -1) < 0) {
364 printf("error finishing mtd write of %s\n", partition);
365 mtd_write_close(ctx);
366 return -1;
367 }
368
369 if (mtd_write_close(ctx)) {
370 printf("error closing mtd write of %s\n", partition);
371 return -1;
372 }
373 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700374 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700375
Tao Baoba9a42a2015-06-23 23:23:33 -0700376 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700377 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700378 bool success = false;
Jed Estepf1fc48c2015-12-15 16:04:53 -0800379 int fd = ota_open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700380 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700381 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700382 return -1;
383 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700384
Tao Baoaca8e892015-07-17 11:47:44 -0700385 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700386 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700387 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700388 return -1;
389 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700390 while (start < len) {
391 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800392 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700393
Jed Estepf1fc48c2015-12-15 16:04:53 -0800394 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data+start, to_write));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700395 if (written == -1) {
396 printf("failed write writing to %s: %s\n", partition, strerror(errno));
397 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700398 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700399 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700400 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800401 if (ota_fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700402 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700403 return -1;
404 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800405 if (ota_close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700406 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700407 return -1;
408 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800409 fd = ota_open(partition, O_RDONLY);
Michael Rungebe81e512014-10-29 12:42:15 -0700410 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700411 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700412 return -1;
413 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700414
Tao Baoba9a42a2015-06-23 23:23:33 -0700415 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700416 // won't just be reading the cache.
417 sync();
Jed Estepf1fc48c2015-12-15 16:04:53 -0800418 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
419 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700420 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
421 } else {
422 printf(" caches dropped\n");
423 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800424 ota_close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700425 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700426
427 // verify
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700428 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
429 printf("failed to seek back to beginning of %s: %s\n",
430 partition, strerror(errno));
431 return -1;
432 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700433 unsigned char buffer[4096];
434 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700435 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700436 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700437 if (to_read > sizeof(buffer)) {
438 to_read = sizeof(buffer);
439 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700440
Doug Zongkerc870a992013-07-09 10:34:46 -0700441 size_t so_far = 0;
442 while (so_far < to_read) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700443 ssize_t read_count =
Jed Estepf1fc48c2015-12-15 16:04:53 -0800444 TEMP_FAILURE_RETRY(ota_read(fd, buffer+so_far, to_read-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700445 if (read_count == -1) {
446 printf("verify read error %s at %zu: %s\n",
447 partition, p, strerror(errno));
448 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700449 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700450 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700451 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700452 partition, p, read_count, to_read, strerror(errno));
453 }
454 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700455 }
456
Tao Baoba9a42a2015-06-23 23:23:33 -0700457 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700458 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700459 start = p;
460 break;
461 }
462 }
463
464 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700465 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700466 success = true;
467 break;
468 }
469 }
470
471 if (!success) {
472 printf("failed to verify after all attempts\n");
473 return -1;
474 }
475
Jed Estepf1fc48c2015-12-15 16:04:53 -0800476 if (ota_close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700477 printf("error closing %s (%s)\n", partition, strerror(errno));
478 return -1;
479 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700480 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700481 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700482 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800483 }
Doug Zongker512536a2010-02-17 16:11:44 -0800484
Doug Zongkerc4351c72010-02-22 14:46:32 -0800485 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800486}
487
488
489// Take a string 'str' of 40 hex digits and parse it into the 20
490// byte array 'digest'. 'str' may contain only the digest or be of
491// the form "<digest>:<anything>". Return 0 on success, -1 on any
492// error.
493int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800494 const char* ps = str;
495 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800496 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800497 int digit;
498 if (*ps >= '0' && *ps <= '9') {
499 digit = *ps - '0';
500 } else if (*ps >= 'a' && *ps <= 'f') {
501 digit = *ps - 'a' + 10;
502 } else if (*ps >= 'A' && *ps <= 'F') {
503 digit = *ps - 'A' + 10;
504 } else {
505 return -1;
506 }
507 if (i % 2 == 0) {
508 *pd = digit << 4;
509 } else {
510 *pd |= digit;
511 ++pd;
512 }
Doug Zongker512536a2010-02-17 16:11:44 -0800513 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800514 if (*ps != '\0') return -1;
515 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800516}
517
Doug Zongkerc4351c72010-02-22 14:46:32 -0800518// Search an array of sha1 strings for one matching the given sha1.
519// Return the index of the match on success, or -1 if no match is
520// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700521int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800522 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800523 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700524 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800525 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800526 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800527 return i;
528 }
Doug Zongker512536a2010-02-17 16:11:44 -0800529 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800530 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800531}
532
533// Returns 0 if the contents of the file (argv[2]) or the cached file
534// match any of the sha1's on the command line (argv[3:]). Returns
535// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700536int applypatch_check(const char* filename, int num_patches,
537 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800538 FileContents file;
539 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800540
Doug Zongkerc4351c72010-02-22 14:46:32 -0800541 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700542 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800543 // partitions, where the filename encodes the sha1s; no need to
544 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800545 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800546 (num_patches > 0 &&
547 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
548 printf("file \"%s\" doesn't have any of expected "
549 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800550
Doug Zongkerc4351c72010-02-22 14:46:32 -0800551 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800552 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800553
Doug Zongkerc4351c72010-02-22 14:46:32 -0800554 // If the source file is missing or corrupted, it might be because
555 // we were killed in the middle of patching it. A copy of it
556 // should have been made in CACHE_TEMP_SOURCE. If that file
557 // exists and matches the sha1 we're looking for, the check still
558 // passes.
559
Doug Zongkera1bc1482014-02-13 15:18:19 -0800560 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800561 printf("failed to load cache file\n");
562 return 1;
563 }
564
565 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
566 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
567 free(file.data);
568 return 1;
569 }
570 }
Doug Zongker512536a2010-02-17 16:11:44 -0800571
572 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800573 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800574}
575
576int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800577 ShowBSDiffLicense();
578 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800579}
580
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700581ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700582 int fd = *reinterpret_cast<int *>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800583 ssize_t done = 0;
584 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700585 while (done < len) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800586 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700587 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700588 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800589 return done;
590 }
591 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800592 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800594}
595
596typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800597 unsigned char* buffer;
598 ssize_t size;
599 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800600} MemorySinkInfo;
601
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700602ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700603 MemorySinkInfo* msi = reinterpret_cast<MemorySinkInfo*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800604 if (msi->size - msi->pos < len) {
605 return -1;
606 }
607 memcpy(msi->buffer + msi->pos, data, len);
608 msi->pos += len;
609 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800610}
611
612// Return the amount of free space (in bytes) on the filesystem
613// containing filename. filename must exist. Return -1 on error.
614size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800615 struct statfs sf;
616 if (statfs(filename, &sf) != 0) {
617 printf("failed to statfs %s: %s\n", filename, strerror(errno));
618 return -1;
619 }
caozhiyuan3b497762015-05-19 17:21:00 +0800620 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800621}
622
Doug Zongkerc4351c72010-02-22 14:46:32 -0800623int CacheSizeCheck(size_t bytes) {
624 if (MakeFreeSpaceOnCache(bytes) < 0) {
625 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
626 return 1;
627 } else {
628 return 0;
629 }
630}
631
Doug Zongkerc4351c72010-02-22 14:46:32 -0800632// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800633// (the original file is not touched until we have the desired
634// replacement for it) and idempotent (it's okay to run this program
635// multiple times).
636//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800637// - if the sha1 hash of <target_filename> is <target_sha1_string>,
638// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800639//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800640// - otherwise, if the sha1 hash of <source_filename> is one of the
641// entries in <patch_sha1_str>, the corresponding patch from
642// <patch_data> (which must be a VAL_BLOB) is applied to produce a
643// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700644// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800645// moves it to replace <target_filename>, and exits successfully.
646// Note that if <source_filename> and <target_filename> are not the
647// same, <source_filename> is NOT deleted on success.
648// <target_filename> may be the string "-" to mean "the same as
649// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800650//
651// - otherwise, or if any error is encountered, exits with non-zero
652// status.
653//
Doug Zongkerf291d852010-07-07 13:55:25 -0700654// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700655// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800656// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800657
Doug Zongkerc4351c72010-02-22 14:46:32 -0800658int applypatch(const char* source_filename,
659 const char* target_filename,
660 const char* target_sha1_str,
661 size_t target_size,
662 int num_patches,
663 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700664 Value** patch_data,
665 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700666 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800667
Tao Baoba9a42a2015-06-23 23:23:33 -0700668 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800669 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800670 }
671
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800672 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800673 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
674 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800675 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800676 }
Doug Zongker512536a2010-02-17 16:11:44 -0800677
Doug Zongkerc4351c72010-02-22 14:46:32 -0800678 FileContents copy_file;
679 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800680 copy_file.data = NULL;
681 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800682 const Value* source_patch_value = NULL;
683 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800684
Doug Zongkerc4351c72010-02-22 14:46:32 -0800685 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800686 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800687 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800688 // The early-exit case: the patch was already applied, this file
689 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700690 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongker1c43c972012-02-28 11:07:09 -0800691 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800692 return 0;
693 }
694 }
Doug Zongker512536a2010-02-17 16:11:44 -0800695
Doug Zongkerc4351c72010-02-22 14:46:32 -0800696 if (source_file.data == NULL ||
697 (target_filename != source_filename &&
698 strcmp(target_filename, source_filename) != 0)) {
699 // Need to load the source file: either we failed to load the
700 // target file, or we did but it's different from the source file.
701 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800702 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800703 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800704 }
705
706 if (source_file.data != NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700707 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800708 if (to_use >= 0) {
709 source_patch_value = patch_data[to_use];
710 }
711 }
712
713 if (source_patch_value == NULL) {
714 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800715 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800716 printf("source file is bad; trying copy\n");
717
Doug Zongkera1bc1482014-02-13 15:18:19 -0800718 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800719 // fail.
720 printf("failed to read copy file\n");
721 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800722 }
723
Tao Baoba9a42a2015-06-23 23:23:33 -0700724 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700725 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800727 }
728
Doug Zongkerc4351c72010-02-22 14:46:32 -0800729 if (copy_patch_value == NULL) {
730 // fail.
731 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800732 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800733 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800734 }
Doug Zongker512536a2010-02-17 16:11:44 -0800735 }
736
Doug Zongker1c43c972012-02-28 11:07:09 -0800737 int result = GenerateTarget(&source_file, source_patch_value,
738 &copy_file, copy_patch_value,
739 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700740 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800741 free(source_file.data);
742 free(copy_file.data);
743
744 return result;
745}
746
Tao Baoabba55b2015-07-17 18:11:12 -0700747/*
748 * This function flashes a given image to the target partition. It verifies
749 * the target cheksum first, and will return if target has the desired hash.
750 * It checks the checksum of the given source image before flashing, and
751 * verifies the target partition afterwards. The function is idempotent.
752 * Returns zero on success.
753 */
754int applypatch_flash(const char* source_filename, const char* target_filename,
755 const char* target_sha1_str, size_t target_size) {
756 printf("flash %s: ", target_filename);
757
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800758 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700759 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
760 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
761 return 1;
762 }
763
764 FileContents source_file;
765 source_file.data = NULL;
766 std::string target_str(target_filename);
767
768 std::vector<std::string> pieces = android::base::Split(target_str, ":");
769 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
770 printf("invalid target name \"%s\"", target_filename);
771 return 1;
772 }
773
774 // Load the target into the source_file object to see if already applied.
775 pieces.push_back(std::to_string(target_size));
776 pieces.push_back(target_sha1_str);
777 std::string fullname = android::base::Join(pieces, ':');
778 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800779 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700780 // The early-exit case: the image was already applied, this partition
781 // has the desired hash, nothing for us to do.
782 printf("already %s\n", short_sha1(target_sha1).c_str());
783 free(source_file.data);
784 return 0;
785 }
786
787 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800788 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700789 // The source doesn't have desired checksum.
790 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
791 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
792 short_sha1(source_file.sha1).c_str());
793 free(source_file.data);
794 return 1;
795 }
796 }
797
798 if (WriteToPartition(source_file.data, target_size, target_filename) != 0) {
799 printf("write of copied data to %s failed\n", target_filename);
800 free(source_file.data);
801 return 1;
802 }
803
804 free(source_file.data);
805 return 0;
806}
807
Doug Zongker1c43c972012-02-28 11:07:09 -0800808static int GenerateTarget(FileContents* source_file,
809 const Value* source_patch_value,
810 FileContents* copy_file,
811 const Value* copy_patch_value,
812 const char* source_filename,
813 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800814 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700815 size_t target_size,
816 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800817 int retry = 1;
818 SHA_CTX ctx;
819 int output;
820 MemorySinkInfo msi;
821 FileContents* source_to_use;
822 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800823 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800824
825 // assume that target_filename (eg "/system/app/Foo.apk") is located
826 // on the same filesystem as its top-level directory ("/system").
827 // We need something that exists for calling statfs().
828 char target_fs[strlen(target_filename)+1];
829 char* slash = strchr(target_filename+1, '/');
830 if (slash != NULL) {
831 int count = slash - target_filename;
832 strncpy(target_fs, target_filename, count);
833 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800834 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800835 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800836 }
837
Doug Zongkerc4351c72010-02-22 14:46:32 -0800838 do {
839 // Is there enough room in the target filesystem to hold the patched
840 // file?
841
Doug Zongkerf291d852010-07-07 13:55:25 -0700842 if (strncmp(target_filename, "MTD:", 4) == 0 ||
843 strncmp(target_filename, "EMMC:", 5) == 0) {
844 // If the target is a partition, we're actually going to
845 // write the output to /tmp and then copy it to the
846 // partition. statfs() always returns 0 blocks free for
847 // /tmp, so instead we'll just assume that /tmp has enough
848 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800849
Doug Zongkerf291d852010-07-07 13:55:25 -0700850 // We still write the original source to cache, in case
851 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800852 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800853 printf("not enough free space on /cache\n");
854 return 1;
855 }
856 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
857 printf("failed to back up source file\n");
858 return 1;
859 }
860 made_copy = 1;
861 retry = 0;
862 } else {
863 int enough_space = 0;
864 if (retry > 0) {
865 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700866 enough_space =
867 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800868 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700869 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700870 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
871 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700872 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800873 }
874
875 if (!enough_space) {
876 retry = 0;
877 }
878
879 if (!enough_space && source_patch_value != NULL) {
880 // Using the original source, but not enough free space. First
881 // copy the source file to cache, then delete it from the original
882 // location.
883
Doug Zongkerf291d852010-07-07 13:55:25 -0700884 if (strncmp(source_filename, "MTD:", 4) == 0 ||
885 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700887 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800888 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700889 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800890 return 1;
891 }
892
Doug Zongker1c43c972012-02-28 11:07:09 -0800893 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800894 printf("not enough free space on /cache\n");
895 return 1;
896 }
897
898 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
899 printf("failed to back up source file\n");
900 return 1;
901 }
902 made_copy = 1;
903 unlink(source_filename);
904
905 size_t free_space = FreeSpaceForFile(target_fs);
Tao Baoba9a42a2015-06-23 23:23:33 -0700906 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800907 }
908 }
909
910 const Value* patch;
911 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800912 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800913 patch = source_patch_value;
914 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800915 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800916 patch = copy_patch_value;
917 }
918
919 if (patch->type != VAL_BLOB) {
920 printf("patch is not a blob\n");
921 return 1;
922 }
923
924 SinkFn sink = NULL;
925 void* token = NULL;
926 output = -1;
927 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700928 if (strncmp(target_filename, "MTD:", 4) == 0 ||
929 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800930 // We store the decoded output in memory.
Tao Baoba9a42a2015-06-23 23:23:33 -0700931 msi.buffer = reinterpret_cast<unsigned char*>(malloc(target_size));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800932 if (msi.buffer == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700933 printf("failed to alloc %zu bytes for output\n", target_size);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800934 return 1;
935 }
936 msi.pos = 0;
937 msi.size = target_size;
938 sink = MemorySink;
939 token = &msi;
940 } else {
941 // We write the decoded output to "<tgt-file>.patch".
Tao Baoba9a42a2015-06-23 23:23:33 -0700942 outname = reinterpret_cast<char*>(malloc(strlen(target_filename) + 10));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800943 strcpy(outname, target_filename);
944 strcat(outname, ".patch");
945
Jed Estepf1fc48c2015-12-15 16:04:53 -0800946 output = ota_open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800947 if (output < 0) {
948 printf("failed to open output file %s: %s\n",
949 outname, strerror(errno));
950 return 1;
951 }
952 sink = FileSink;
953 token = &output;
954 }
955
956 char* header = patch->data;
957 ssize_t header_bytes_read = patch->size;
958
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800959 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800960
961 int result;
962
963 if (header_bytes_read >= 8 &&
964 memcmp(header, "BSDIFF40", 8) == 0) {
965 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
966 patch, 0, sink, token, &ctx);
967 } else if (header_bytes_read >= 8 &&
968 memcmp(header, "IMGDIFF2", 8) == 0) {
969 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700970 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800971 } else {
972 printf("Unknown patch file format\n");
973 return 1;
974 }
975
976 if (output >= 0) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800977 if (ota_fsync(output) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700978 printf("failed to fsync file \"%s\" (%s)\n", outname, strerror(errno));
979 result = 1;
980 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800981 if (ota_close(output) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700982 printf("failed to close file \"%s\" (%s)\n", outname, strerror(errno));
983 result = 1;
984 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800985 }
986
987 if (result != 0) {
988 if (retry == 0) {
989 printf("applying patch failed\n");
990 return result != 0;
991 } else {
992 printf("applying patch failed; retrying\n");
993 }
994 if (outname != NULL) {
995 unlink(outname);
996 }
997 } else {
998 // succeeded; no need to retry
999 break;
1000 }
1001 } while (retry-- > 0);
1002
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001003 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
1004 SHA1_Final(current_target_sha1, &ctx);
1005 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001006 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -08001007 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -07001008 } else {
Tao Baoabba55b2015-07-17 18:11:12 -07001009 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -08001010 }
1011
1012 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001013 // Copy the temp file to the partition.
1014 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001015 printf("write of patched data to %s failed\n", target_filename);
1016 return 1;
1017 }
1018 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -08001019 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001020 // Give the .patch file the same owner, group, and mode of the
1021 // original source file.
1022 if (chmod(outname, source_to_use->st.st_mode) != 0) {
1023 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
1024 return 1;
1025 }
Tao Baoba9a42a2015-06-23 23:23:33 -07001026 if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001027 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
1028 return 1;
1029 }
Doug Zongker512536a2010-02-17 16:11:44 -08001030
Doug Zongkerc4351c72010-02-22 14:46:32 -08001031 // Finally, rename the .patch file to replace the target file.
1032 if (rename(outname, target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001033 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001034 return 1;
1035 }
Doug Zongker512536a2010-02-17 16:11:44 -08001036 }
1037
Doug Zongkerc4351c72010-02-22 14:46:32 -08001038 // If this run of applypatch created the copy, and we're here, we
1039 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -07001040 if (made_copy) {
1041 unlink(CACHE_TEMP_SOURCE);
1042 }
Doug Zongker512536a2010-02-17 16:11:44 -08001043
Doug Zongkerc4351c72010-02-22 14:46:32 -08001044 // Success!
1045 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001046}