blob: 9f5e2f200d788b18401ca3b7e3ec0d51e374d4cc [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"
Doug Zongker512536a2010-02-17 16:11:44 -080034#include "applypatch.h"
35#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080036#include "edify/expr.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include "print_sha1.h"
Jed Estepf1fc48c2015-12-15 16:04:53 -080038#include "otafault/ota_io.h"
Doug Zongker512536a2010-02-17 16:11:44 -080039
Doug Zongkerf291d852010-07-07 13:55:25 -070040static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070041static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080042static int GenerateTarget(FileContents* source_file,
43 const Value* source_patch_value,
44 FileContents* copy_file,
45 const Value* copy_patch_value,
46 const char* source_filename,
47 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080048 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070049 size_t target_size,
50 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080051
Tao Baoaca8e892015-07-17 11:47:44 -070052static bool mtd_partitions_scanned = false;
Doug Zongker512536a2010-02-17 16:11:44 -080053
Doug Zongkera1bc1482014-02-13 15:18:19 -080054// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070055// metadata in *file.
56//
57// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080058int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongker512536a2010-02-17 16:11:44 -080059 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080060
Doug Zongkerf291d852010-07-07 13:55:25 -070061 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
62 // load the contents of a partition.
63 if (strncmp(filename, "MTD:", 4) == 0 ||
64 strncmp(filename, "EMMC:", 5) == 0) {
65 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080066 }
Doug Zongker512536a2010-02-17 16:11:44 -080067
Doug Zongkerc4351c72010-02-22 14:46:32 -080068 if (stat(filename, &file->st) != 0) {
69 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
70 return -1;
71 }
72
73 file->size = file->st.st_size;
Yabin Cuid483c202016-02-03 17:08:52 -080074 file->data = nullptr;
75
76 std::unique_ptr<unsigned char, decltype(&free)> data(
77 static_cast<unsigned char*>(malloc(file->size)), free);
78 if (data == nullptr) {
79 printf("failed to allocate memory: %s\n", strerror(errno));
80 return -1;
81 }
Doug Zongkerc4351c72010-02-22 14:46:32 -080082
Jed Estepf1fc48c2015-12-15 16:04:53 -080083 FILE* f = ota_fopen(filename, "rb");
Doug Zongkerc4351c72010-02-22 14:46:32 -080084 if (f == NULL) {
85 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -080086 return -1;
87 }
88
Yabin Cuica78c9f2016-02-05 15:27:52 -080089 size_t bytes_read = ota_fread(data.get(), 1, file->size, f);
Tao Baoba9a42a2015-06-23 23:23:33 -070090 if (bytes_read != static_cast<size_t>(file->size)) {
91 printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, file->size);
Yabin Cuid483c202016-02-03 17:08:52 -080092 fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080093 return -1;
94 }
Jed Estepf1fc48c2015-12-15 16:04:53 -080095 ota_fclose(f);
Yabin Cuid483c202016-02-03 17:08:52 -080096 file->data = data.release();
Sen Jiangc48cb5e2016-02-04 16:23:21 +080097 SHA1(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080098 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080099}
100
Doug Zongkerf291d852010-07-07 13:55:25 -0700101// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800102// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700103// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
104// "EMMC:<partition_device>:..."). The smallest size_n bytes for
105// which that prefix of the partition contents has the corresponding
106// sha1 hash will be loaded. It is acceptable for a size value to be
107// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800108//
109// This complexity is needed because if an OTA installation is
110// interrupted, the partition might contain either the source or the
111// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700112// the length in order to read from a partition (there is no
113// "end-of-file" marker), so the caller must specify the possible
114// lengths and the hash of the data, and we'll do the load expecting
115// to find one of those hashes.
116enum PartitionType { MTD, EMMC };
117
118static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700119 std::string copy(filename);
120 std::vector<std::string> pieces = android::base::Split(copy, ":");
121 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
122 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
123 return -1;
124 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700125
126 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700127 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700128 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700129 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700130 type = EMMC;
131 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700132 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800133 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800134 }
Tao Baoaca8e892015-07-17 11:47:44 -0700135 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800136
Tao Baoaca8e892015-07-17 11:47:44 -0700137 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
138 std::vector<size_t> index(pairs);
139 std::vector<size_t> size(pairs);
140 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800141
Tao Baoaca8e892015-07-17 11:47:44 -0700142 for (size_t i = 0; i < pairs; ++i) {
143 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800144 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700145 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800146 return -1;
147 }
Tao Baoaca8e892015-07-17 11:47:44 -0700148 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800149 index[i] = i;
150 }
Doug Zongker512536a2010-02-17 16:11:44 -0800151
Tao Baoaca8e892015-07-17 11:47:44 -0700152 // Sort the index[] array so it indexes the pairs in order of increasing size.
153 sort(index.begin(), index.end(),
154 [&](const size_t& i, const size_t& j) {
155 return (size[i] < size[j]);
156 }
157 );
Doug Zongker512536a2010-02-17 16:11:44 -0800158
Doug Zongkerf291d852010-07-07 13:55:25 -0700159 MtdReadContext* ctx = NULL;
160 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800161
Doug Zongkerf291d852010-07-07 13:55:25 -0700162 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700163 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700164 if (!mtd_partitions_scanned) {
165 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700166 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700167 }
Doug Zongker512536a2010-02-17 16:11:44 -0800168
Doug Zongkerf291d852010-07-07 13:55:25 -0700169 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
170 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700171 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700172 return -1;
173 }
174
175 ctx = mtd_read_partition(mtd);
176 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700177 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700178 return -1;
179 }
180 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700181 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700182
183 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800184 dev = ota_fopen(partition, "rb");
Doug Zongkerf291d852010-07-07 13:55:25 -0700185 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700186 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700187 return -1;
188 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800189 }
Doug Zongker512536a2010-02-17 16:11:44 -0800190
Doug Zongkerc4351c72010-02-22 14:46:32 -0800191 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800192 SHA1_Init(&sha_ctx);
193 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800194
Tao Baoaca8e892015-07-17 11:47:44 -0700195 // Allocate enough memory to hold the largest size.
Yabin Cuid483c202016-02-03 17:08:52 -0800196 file->data = static_cast<unsigned char*>(malloc(size[index[pairs-1]]));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800197 char* p = (char*)file->data;
198 file->size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700199 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800200
Tao Baoaca8e892015-07-17 11:47:44 -0700201 for (size_t i = 0; i < pairs; ++i) {
202 // Read enough additional bytes to get us up to the next size. (Again,
203 // we're trying the possibilities in order of increasing size).
Doug Zongkerc4351c72010-02-22 14:46:32 -0800204 size_t next = size[index[i]] - file->size;
205 size_t read = 0;
206 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700207 switch (type) {
208 case MTD:
209 read = mtd_read_data(ctx, p, next);
210 break;
211
212 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800213 read = ota_fread(p, 1, next, dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700214 break;
215 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800216 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700217 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800218 read, next, partition);
219 free(file->data);
220 file->data = NULL;
221 return -1;
222 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800223 SHA1_Update(&sha_ctx, p, read);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800224 file->size += read;
225 }
226
227 // Duplicate the SHA context and finalize the duplicate so we can
228 // check it against this pair's expected hash.
229 SHA_CTX temp_ctx;
230 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800231 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
232 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800233
Tao Baoaca8e892015-07-17 11:47:44 -0700234 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
235 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800236 free(file->data);
237 file->data = NULL;
238 return -1;
239 }
240
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800241 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800242 // we have a match. stop reading the partition; we'll return
243 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700244 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700245 size[index[i]], sha1sum[index[i]].c_str());
246 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800247 break;
248 }
249
250 p += read;
251 }
252
Doug Zongkerf291d852010-07-07 13:55:25 -0700253 switch (type) {
254 case MTD:
255 mtd_read_close(ctx);
256 break;
257
258 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800259 ota_fclose(dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700260 break;
261 }
262
Doug Zongkerc4351c72010-02-22 14:46:32 -0800263
Tao Baoaca8e892015-07-17 11:47:44 -0700264 if (!found) {
265 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700266 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800267 free(file->data);
268 file->data = NULL;
269 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800270 }
271
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800272 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800273
Doug Zongkerc4351c72010-02-22 14:46:32 -0800274 // Fake some stat() info.
275 file->st.st_mode = 0644;
276 file->st.st_uid = 0;
277 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800278
Doug Zongkerc4351c72010-02-22 14:46:32 -0800279 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800280}
281
282
283// Save the contents of the given FileContents object under the given
284// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800285int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800286 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800287 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700288 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800289 return -1;
290 }
Doug Zongker512536a2010-02-17 16:11:44 -0800291
Doug Zongker1c43c972012-02-28 11:07:09 -0800292 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
293 if (bytes_written != file->size) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700294 printf("short write of \"%s\" (%zd bytes of %zd) (%s)\n",
295 filename, bytes_written, file->size, strerror(errno));
Jed Estepf1fc48c2015-12-15 16:04:53 -0800296 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800297 return -1;
298 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800299 if (ota_fsync(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700300 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
301 return -1;
302 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800303 if (ota_close(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700304 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
305 return -1;
306 }
Doug Zongker512536a2010-02-17 16:11:44 -0800307
Doug Zongker1c43c972012-02-28 11:07:09 -0800308 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800309 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
310 return -1;
311 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800312 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800313 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
314 return -1;
315 }
Doug Zongker512536a2010-02-17 16:11:44 -0800316
Doug Zongkerc4351c72010-02-22 14:46:32 -0800317 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800318}
319
Doug Zongkerf291d852010-07-07 13:55:25 -0700320// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700321// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
322// might contain multiple colons, but WriteToPartition() only uses the first
323// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800324int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700325 std::string copy(target);
326 std::vector<std::string> pieces = android::base::Split(copy, ":");
327
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700328 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700329 printf("WriteToPartition called with bad target (%s)\n", target);
330 return -1;
331 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700332
333 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700334 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700335 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700336 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700337 type = EMMC;
338 } else {
339 printf("WriteToPartition called with bad target (%s)\n", target);
340 return -1;
341 }
Tao Baoaca8e892015-07-17 11:47:44 -0700342 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800343
Doug Zongkerf291d852010-07-07 13:55:25 -0700344 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700345 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700346 if (!mtd_partitions_scanned) {
347 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700348 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700349 }
350
351 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
352 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700353 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700354 return -1;
355 }
356
357 MtdWriteContext* ctx = mtd_write_partition(mtd);
358 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700359 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700360 return -1;
361 }
362
Yabin Cuid483c202016-02-03 17:08:52 -0800363 size_t written = mtd_write_data(ctx, reinterpret_cast<const char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700364 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700365 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700366 mtd_write_close(ctx);
367 return -1;
368 }
369
370 if (mtd_erase_blocks(ctx, -1) < 0) {
371 printf("error finishing mtd write of %s\n", partition);
372 mtd_write_close(ctx);
373 return -1;
374 }
375
376 if (mtd_write_close(ctx)) {
377 printf("error closing mtd write of %s\n", partition);
378 return -1;
379 }
380 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700381 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700382
Tao Baoba9a42a2015-06-23 23:23:33 -0700383 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700384 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700385 bool success = false;
Jed Estepf1fc48c2015-12-15 16:04:53 -0800386 int fd = ota_open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700387 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700388 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700389 return -1;
390 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700391
Tao Baoaca8e892015-07-17 11:47:44 -0700392 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700393 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700394 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700395 return -1;
396 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700397 while (start < len) {
398 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800399 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700400
Jed Estepf1fc48c2015-12-15 16:04:53 -0800401 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data+start, to_write));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700402 if (written == -1) {
403 printf("failed write writing to %s: %s\n", partition, strerror(errno));
404 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700405 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700406 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700407 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800408 if (ota_fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700409 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700410 return -1;
411 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800412 if (ota_close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700413 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700414 return -1;
415 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800416 fd = ota_open(partition, O_RDONLY);
Michael Rungebe81e512014-10-29 12:42:15 -0700417 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700418 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700419 return -1;
420 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700421
Tao Baoba9a42a2015-06-23 23:23:33 -0700422 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700423 // won't just be reading the cache.
424 sync();
Jed Estepf1fc48c2015-12-15 16:04:53 -0800425 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
426 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700427 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
428 } else {
429 printf(" caches dropped\n");
430 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800431 ota_close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700432 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700433
434 // verify
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700435 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
436 printf("failed to seek back to beginning of %s: %s\n",
437 partition, strerror(errno));
438 return -1;
439 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700440 unsigned char buffer[4096];
441 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700442 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700443 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700444 if (to_read > sizeof(buffer)) {
445 to_read = sizeof(buffer);
446 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700447
Doug Zongkerc870a992013-07-09 10:34:46 -0700448 size_t so_far = 0;
449 while (so_far < to_read) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700450 ssize_t read_count =
Jed Estepf1fc48c2015-12-15 16:04:53 -0800451 TEMP_FAILURE_RETRY(ota_read(fd, buffer+so_far, to_read-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700452 if (read_count == -1) {
453 printf("verify read error %s at %zu: %s\n",
454 partition, p, strerror(errno));
455 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700456 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700457 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700458 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700459 partition, p, read_count, to_read, strerror(errno));
460 }
461 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700462 }
463
Tao Baoba9a42a2015-06-23 23:23:33 -0700464 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700465 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700466 start = p;
467 break;
468 }
469 }
470
471 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700472 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700473 success = true;
474 break;
475 }
476 }
477
478 if (!success) {
479 printf("failed to verify after all attempts\n");
480 return -1;
481 }
482
Jed Estepf1fc48c2015-12-15 16:04:53 -0800483 if (ota_close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700484 printf("error closing %s (%s)\n", partition, strerror(errno));
485 return -1;
486 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700487 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700488 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700489 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800490 }
Doug Zongker512536a2010-02-17 16:11:44 -0800491
Doug Zongkerc4351c72010-02-22 14:46:32 -0800492 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800493}
494
495
496// Take a string 'str' of 40 hex digits and parse it into the 20
497// byte array 'digest'. 'str' may contain only the digest or be of
498// the form "<digest>:<anything>". Return 0 on success, -1 on any
499// error.
500int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800501 const char* ps = str;
502 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800503 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800504 int digit;
505 if (*ps >= '0' && *ps <= '9') {
506 digit = *ps - '0';
507 } else if (*ps >= 'a' && *ps <= 'f') {
508 digit = *ps - 'a' + 10;
509 } else if (*ps >= 'A' && *ps <= 'F') {
510 digit = *ps - 'A' + 10;
511 } else {
512 return -1;
513 }
514 if (i % 2 == 0) {
515 *pd = digit << 4;
516 } else {
517 *pd |= digit;
518 ++pd;
519 }
Doug Zongker512536a2010-02-17 16:11:44 -0800520 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800521 if (*ps != '\0') return -1;
522 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800523}
524
Doug Zongkerc4351c72010-02-22 14:46:32 -0800525// Search an array of sha1 strings for one matching the given sha1.
526// Return the index of the match on success, or -1 if no match is
527// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700528int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800529 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800530 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700531 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800532 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800533 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800534 return i;
535 }
Doug Zongker512536a2010-02-17 16:11:44 -0800536 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800537 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800538}
539
540// Returns 0 if the contents of the file (argv[2]) or the cached file
541// match any of the sha1's on the command line (argv[3:]). Returns
542// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700543int applypatch_check(const char* filename, int num_patches,
544 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800545 FileContents file;
546 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800547
Doug Zongkerc4351c72010-02-22 14:46:32 -0800548 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700549 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800550 // partitions, where the filename encodes the sha1s; no need to
551 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800552 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800553 (num_patches > 0 &&
554 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
555 printf("file \"%s\" doesn't have any of expected "
556 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800557
Doug Zongkerc4351c72010-02-22 14:46:32 -0800558 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800559 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800560
Doug Zongkerc4351c72010-02-22 14:46:32 -0800561 // If the source file is missing or corrupted, it might be because
562 // we were killed in the middle of patching it. A copy of it
563 // should have been made in CACHE_TEMP_SOURCE. If that file
564 // exists and matches the sha1 we're looking for, the check still
565 // passes.
566
Doug Zongkera1bc1482014-02-13 15:18:19 -0800567 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568 printf("failed to load cache file\n");
569 return 1;
570 }
571
572 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
573 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
574 free(file.data);
575 return 1;
576 }
577 }
Doug Zongker512536a2010-02-17 16:11:44 -0800578
579 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800580 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800581}
582
583int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800584 ShowBSDiffLicense();
585 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800586}
587
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700588ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800589 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800590 ssize_t done = 0;
591 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700592 while (done < len) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800593 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700594 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700595 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800596 return done;
597 }
598 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800599 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800600 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800601}
602
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700603ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800604 std::string* s = static_cast<std::string*>(token);
605 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800606 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800607}
608
609// Return the amount of free space (in bytes) on the filesystem
610// containing filename. filename must exist. Return -1 on error.
611size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800612 struct statfs sf;
613 if (statfs(filename, &sf) != 0) {
614 printf("failed to statfs %s: %s\n", filename, strerror(errno));
615 return -1;
616 }
caozhiyuan3b497762015-05-19 17:21:00 +0800617 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800618}
619
Doug Zongkerc4351c72010-02-22 14:46:32 -0800620int CacheSizeCheck(size_t bytes) {
621 if (MakeFreeSpaceOnCache(bytes) < 0) {
622 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
623 return 1;
624 } else {
625 return 0;
626 }
627}
628
Doug Zongkerc4351c72010-02-22 14:46:32 -0800629// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800630// (the original file is not touched until we have the desired
631// replacement for it) and idempotent (it's okay to run this program
632// multiple times).
633//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800634// - if the sha1 hash of <target_filename> is <target_sha1_string>,
635// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800636//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800637// - otherwise, if the sha1 hash of <source_filename> is one of the
638// entries in <patch_sha1_str>, the corresponding patch from
639// <patch_data> (which must be a VAL_BLOB) is applied to produce a
640// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700641// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800642// moves it to replace <target_filename>, and exits successfully.
643// Note that if <source_filename> and <target_filename> are not the
644// same, <source_filename> is NOT deleted on success.
645// <target_filename> may be the string "-" to mean "the same as
646// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800647//
648// - otherwise, or if any error is encountered, exits with non-zero
649// status.
650//
Doug Zongkerf291d852010-07-07 13:55:25 -0700651// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700652// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800653// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800654
Doug Zongkerc4351c72010-02-22 14:46:32 -0800655int applypatch(const char* source_filename,
656 const char* target_filename,
657 const char* target_sha1_str,
658 size_t target_size,
659 int num_patches,
660 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700661 Value** patch_data,
662 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700663 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800664
Tao Baoba9a42a2015-06-23 23:23:33 -0700665 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800666 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800667 }
668
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800669 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800670 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
671 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800672 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800673 }
Doug Zongker512536a2010-02-17 16:11:44 -0800674
Doug Zongkerc4351c72010-02-22 14:46:32 -0800675 FileContents copy_file;
676 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800677 copy_file.data = NULL;
678 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800679 const Value* source_patch_value = NULL;
680 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800681
Doug Zongkerc4351c72010-02-22 14:46:32 -0800682 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800683 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800684 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800685 // The early-exit case: the patch was already applied, this file
686 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700687 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongker1c43c972012-02-28 11:07:09 -0800688 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800689 return 0;
690 }
691 }
Doug Zongker512536a2010-02-17 16:11:44 -0800692
Doug Zongkerc4351c72010-02-22 14:46:32 -0800693 if (source_file.data == NULL ||
694 (target_filename != source_filename &&
695 strcmp(target_filename, source_filename) != 0)) {
696 // Need to load the source file: either we failed to load the
697 // target file, or we did but it's different from the source file.
698 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800699 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800700 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800701 }
702
703 if (source_file.data != NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700704 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800705 if (to_use >= 0) {
706 source_patch_value = patch_data[to_use];
707 }
708 }
709
710 if (source_patch_value == NULL) {
711 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800712 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800713 printf("source file is bad; trying copy\n");
714
Doug Zongkera1bc1482014-02-13 15:18:19 -0800715 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800716 // fail.
717 printf("failed to read copy file\n");
718 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800719 }
720
Tao Baoba9a42a2015-06-23 23:23:33 -0700721 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700722 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800723 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800724 }
725
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726 if (copy_patch_value == NULL) {
727 // fail.
728 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800729 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800730 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800731 }
Doug Zongker512536a2010-02-17 16:11:44 -0800732 }
733
Doug Zongker1c43c972012-02-28 11:07:09 -0800734 int result = GenerateTarget(&source_file, source_patch_value,
735 &copy_file, copy_patch_value,
736 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700737 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800738 free(source_file.data);
739 free(copy_file.data);
740
741 return result;
742}
743
Tao Baoabba55b2015-07-17 18:11:12 -0700744/*
745 * This function flashes a given image to the target partition. It verifies
746 * the target cheksum first, and will return if target has the desired hash.
747 * It checks the checksum of the given source image before flashing, and
748 * verifies the target partition afterwards. The function is idempotent.
749 * Returns zero on success.
750 */
751int applypatch_flash(const char* source_filename, const char* target_filename,
752 const char* target_sha1_str, size_t target_size) {
753 printf("flash %s: ", target_filename);
754
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800755 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700756 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
757 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
758 return 1;
759 }
760
761 FileContents source_file;
762 source_file.data = NULL;
763 std::string target_str(target_filename);
764
765 std::vector<std::string> pieces = android::base::Split(target_str, ":");
766 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
767 printf("invalid target name \"%s\"", target_filename);
768 return 1;
769 }
770
771 // Load the target into the source_file object to see if already applied.
772 pieces.push_back(std::to_string(target_size));
773 pieces.push_back(target_sha1_str);
774 std::string fullname = android::base::Join(pieces, ':');
775 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800776 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700777 // The early-exit case: the image was already applied, this partition
778 // has the desired hash, nothing for us to do.
779 printf("already %s\n", short_sha1(target_sha1).c_str());
780 free(source_file.data);
781 return 0;
782 }
783
784 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800785 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700786 // The source doesn't have desired checksum.
787 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
788 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
789 short_sha1(source_file.sha1).c_str());
790 free(source_file.data);
791 return 1;
792 }
793 }
794
795 if (WriteToPartition(source_file.data, target_size, target_filename) != 0) {
796 printf("write of copied data to %s failed\n", target_filename);
797 free(source_file.data);
798 return 1;
799 }
800
801 free(source_file.data);
802 return 0;
803}
804
Doug Zongker1c43c972012-02-28 11:07:09 -0800805static int GenerateTarget(FileContents* source_file,
806 const Value* source_patch_value,
807 FileContents* copy_file,
808 const Value* copy_patch_value,
809 const char* source_filename,
810 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800811 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700812 size_t target_size,
813 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800814 int retry = 1;
815 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800816 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800817 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800818 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800819
Yabin Cuid483c202016-02-03 17:08:52 -0800820 bool target_is_partition = (strncmp(target_filename, "MTD:", 4) == 0 ||
821 strncmp(target_filename, "EMMC:", 5) == 0);
822 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
823
Doug Zongkerc4351c72010-02-22 14:46:32 -0800824 // assume that target_filename (eg "/system/app/Foo.apk") is located
825 // on the same filesystem as its top-level directory ("/system").
826 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800827 std::string target_fs = target_filename;
828 auto slash_pos = target_fs.find('/', 1);
829 if (slash_pos != std::string::npos) {
830 target_fs.resize(slash_pos);
831 }
832
833 const Value* patch;
834 if (source_patch_value != NULL) {
835 source_to_use = source_file;
836 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800837 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800838 source_to_use = copy_file;
839 patch = copy_patch_value;
840 }
841 if (patch->type != VAL_BLOB) {
842 printf("patch is not a blob\n");
843 return 1;
844 }
845 char* header = patch->data;
846 ssize_t header_bytes_read = patch->size;
847 bool use_bsdiff = false;
848 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
849 use_bsdiff = true;
850 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
851 use_bsdiff = false;
852 } else {
853 printf("Unknown patch file format\n");
854 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800855 }
856
Doug Zongkerc4351c72010-02-22 14:46:32 -0800857 do {
858 // Is there enough room in the target filesystem to hold the patched
859 // file?
860
Yabin Cuid483c202016-02-03 17:08:52 -0800861 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700862 // If the target is a partition, we're actually going to
863 // write the output to /tmp and then copy it to the
864 // partition. statfs() always returns 0 blocks free for
865 // /tmp, so instead we'll just assume that /tmp has enough
866 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800867
Doug Zongkerf291d852010-07-07 13:55:25 -0700868 // We still write the original source to cache, in case
869 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800870 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800871 printf("not enough free space on /cache\n");
872 return 1;
873 }
874 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
875 printf("failed to back up source file\n");
876 return 1;
877 }
878 made_copy = 1;
879 retry = 0;
880 } else {
881 int enough_space = 0;
882 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800883 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700884 enough_space =
885 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700887 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700888 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
889 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700890 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800891 }
892
893 if (!enough_space) {
894 retry = 0;
895 }
896
897 if (!enough_space && source_patch_value != NULL) {
898 // Using the original source, but not enough free space. First
899 // copy the source file to cache, then delete it from the original
900 // location.
901
Doug Zongkerf291d852010-07-07 13:55:25 -0700902 if (strncmp(source_filename, "MTD:", 4) == 0 ||
903 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800904 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700905 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800906 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700907 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800908 return 1;
909 }
910
Doug Zongker1c43c972012-02-28 11:07:09 -0800911 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800912 printf("not enough free space on /cache\n");
913 return 1;
914 }
915
916 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
917 printf("failed to back up source file\n");
918 return 1;
919 }
920 made_copy = 1;
921 unlink(source_filename);
922
Yabin Cuid483c202016-02-03 17:08:52 -0800923 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Tao Baoba9a42a2015-06-23 23:23:33 -0700924 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800925 }
926 }
927
Doug Zongkerc4351c72010-02-22 14:46:32 -0800928
929 SinkFn sink = NULL;
930 void* token = NULL;
Yabin Cuid483c202016-02-03 17:08:52 -0800931 int output_fd = -1;
932 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800933 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800934 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800935 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800936 } else {
937 // We write the decoded output to "<tgt-file>.patch".
Yabin Cuica78c9f2016-02-05 15:27:52 -0800938 output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
Yabin Cuid483c202016-02-03 17:08:52 -0800939 S_IRUSR | S_IWUSR);
940 if (output_fd < 0) {
941 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
942 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800943 return 1;
944 }
945 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800946 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800947 }
948
Doug Zongkerc4351c72010-02-22 14:46:32 -0800949
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800950 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800951
952 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800953 if (use_bsdiff) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800954 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
955 patch, 0, sink, token, &ctx);
Yabin Cuid483c202016-02-03 17:08:52 -0800956 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800957 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700958 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800959 }
960
Yabin Cuid483c202016-02-03 17:08:52 -0800961 if (!target_is_partition) {
Yabin Cuica78c9f2016-02-05 15:27:52 -0800962 if (ota_fsync(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800963 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
964 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700965 result = 1;
966 }
Yabin Cuica78c9f2016-02-05 15:27:52 -0800967 if (ota_close(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800968 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
969 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700970 result = 1;
971 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800972 }
973
974 if (result != 0) {
975 if (retry == 0) {
976 printf("applying patch failed\n");
977 return result != 0;
978 } else {
979 printf("applying patch failed; retrying\n");
980 }
Yabin Cuid483c202016-02-03 17:08:52 -0800981 if (!target_is_partition) {
982 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800983 }
984 } else {
985 // succeeded; no need to retry
986 break;
987 }
988 } while (retry-- > 0);
989
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800990 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
991 SHA1_Final(current_target_sha1, &ctx);
992 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800993 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800994 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700995 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700996 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800997 }
998
Yabin Cuid483c202016-02-03 17:08:52 -0800999 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001000 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -08001001 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
1002 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001003 printf("write of patched data to %s failed\n", target_filename);
1004 return 1;
1005 }
Doug Zongker512536a2010-02-17 16:11:44 -08001006 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001007 // Give the .patch file the same owner, group, and mode of the
1008 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -08001009 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
1010 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001011 return 1;
1012 }
Yabin Cuid483c202016-02-03 17:08:52 -08001013 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
1014 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001015 return 1;
1016 }
Doug Zongker512536a2010-02-17 16:11:44 -08001017
Doug Zongkerc4351c72010-02-22 14:46:32 -08001018 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -08001019 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001020 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001021 return 1;
1022 }
Doug Zongker512536a2010-02-17 16:11:44 -08001023 }
1024
Doug Zongkerc4351c72010-02-22 14:46:32 -08001025 // If this run of applypatch created the copy, and we're here, we
1026 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -07001027 if (made_copy) {
1028 unlink(CACHE_TEMP_SOURCE);
1029 }
Doug Zongker512536a2010-02-17 16:11:44 -08001030
Doug Zongkerc4351c72010-02-22 14:46:32 -08001031 // Success!
1032 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001033}