blob: f66dbe3bf9a1e5e855b116fca293cb7b50ef62e8 [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 Estepa7b9a462015-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 Zongkerf291d852010-07-07 13:55:25 -070059 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
60 // load the contents of a partition.
61 if (strncmp(filename, "MTD:", 4) == 0 ||
62 strncmp(filename, "EMMC:", 5) == 0) {
63 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080064 }
Doug Zongker512536a2010-02-17 16:11:44 -080065
Doug Zongkerc4351c72010-02-22 14:46:32 -080066 if (stat(filename, &file->st) != 0) {
67 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
68 return -1;
69 }
70
Yabin Cuid6c93af2016-02-10 16:41:10 -080071 std::vector<unsigned char> data(file->st.st_size);
Jed Estepa7b9a462015-12-15 16:04:53 -080072 FILE* f = ota_fopen(filename, "rb");
Doug Zongkerc4351c72010-02-22 14:46:32 -080073 if (f == NULL) {
74 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -080075 return -1;
76 }
77
Yabin Cuid6c93af2016-02-10 16:41:10 -080078 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f);
79 if (bytes_read != data.size()) {
80 printf("short read of \"%s\" (%zu bytes of %zu)\n", filename, bytes_read, data.size());
Jed Estepa7b9a462015-12-15 16:04:53 -080081 ota_fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080082 return -1;
83 }
Jed Estepa7b9a462015-12-15 16:04:53 -080084 ota_fclose(f);
Yabin Cuid6c93af2016-02-10 16:41:10 -080085 file->data = std::move(data);
86 SHA1(file->data.data(), file->data.size(), file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080087 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080088}
89
Doug Zongkerf291d852010-07-07 13:55:25 -070090// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080091// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -070092// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
93// "EMMC:<partition_device>:..."). The smallest size_n bytes for
94// which that prefix of the partition contents has the corresponding
95// sha1 hash will be loaded. It is acceptable for a size value to be
96// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080097//
98// This complexity is needed because if an OTA installation is
99// interrupted, the partition might contain either the source or the
100// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700101// the length in order to read from a partition (there is no
102// "end-of-file" marker), so the caller must specify the possible
103// lengths and the hash of the data, and we'll do the load expecting
104// to find one of those hashes.
105enum PartitionType { MTD, EMMC };
106
107static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700108 std::string copy(filename);
109 std::vector<std::string> pieces = android::base::Split(copy, ":");
110 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
111 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
112 return -1;
113 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700114
115 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700116 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700117 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700118 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700119 type = EMMC;
120 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700121 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800122 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800123 }
Tao Baoaca8e892015-07-17 11:47:44 -0700124 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800125
Tao Baoaca8e892015-07-17 11:47:44 -0700126 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
127 std::vector<size_t> index(pairs);
128 std::vector<size_t> size(pairs);
129 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800130
Tao Baoaca8e892015-07-17 11:47:44 -0700131 for (size_t i = 0; i < pairs; ++i) {
132 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800133 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700134 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800135 return -1;
136 }
Tao Baoaca8e892015-07-17 11:47:44 -0700137 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800138 index[i] = i;
139 }
Doug Zongker512536a2010-02-17 16:11:44 -0800140
Tao Baoaca8e892015-07-17 11:47:44 -0700141 // Sort the index[] array so it indexes the pairs in order of increasing size.
142 sort(index.begin(), index.end(),
143 [&](const size_t& i, const size_t& j) {
144 return (size[i] < size[j]);
145 }
146 );
Doug Zongker512536a2010-02-17 16:11:44 -0800147
Doug Zongkerf291d852010-07-07 13:55:25 -0700148 MtdReadContext* ctx = NULL;
149 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800150
Doug Zongkerf291d852010-07-07 13:55:25 -0700151 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700152 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700153 if (!mtd_partitions_scanned) {
154 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700155 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700156 }
Doug Zongker512536a2010-02-17 16:11:44 -0800157
Doug Zongkerf291d852010-07-07 13:55:25 -0700158 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
159 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700160 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700161 return -1;
162 }
163
164 ctx = mtd_read_partition(mtd);
165 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700166 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700167 return -1;
168 }
169 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700170 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700171
172 case EMMC:
Jed Estepa7b9a462015-12-15 16:04:53 -0800173 dev = ota_fopen(partition, "rb");
Doug Zongkerf291d852010-07-07 13:55:25 -0700174 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700175 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700176 return -1;
177 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800178 }
Doug Zongker512536a2010-02-17 16:11:44 -0800179
Doug Zongkerc4351c72010-02-22 14:46:32 -0800180 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800181 SHA1_Init(&sha_ctx);
182 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800183
Tao Baoaca8e892015-07-17 11:47:44 -0700184 // Allocate enough memory to hold the largest size.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800185 std::vector<unsigned char> data(size[index[pairs-1]]);
186 char* p = reinterpret_cast<char*>(data.data());
187 size_t data_size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700188 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800189
Tao Baoaca8e892015-07-17 11:47:44 -0700190 for (size_t i = 0; i < pairs; ++i) {
191 // Read enough additional bytes to get us up to the next size. (Again,
192 // we're trying the possibilities in order of increasing size).
Yabin Cuid6c93af2016-02-10 16:41:10 -0800193 size_t next = size[index[i]] - data_size;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800194 if (next > 0) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800195 size_t read = 0;
Doug Zongkerf291d852010-07-07 13:55:25 -0700196 switch (type) {
197 case MTD:
198 read = mtd_read_data(ctx, p, next);
199 break;
200
201 case EMMC:
Jed Estepa7b9a462015-12-15 16:04:53 -0800202 read = ota_fread(p, 1, next, dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700203 break;
204 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800205 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700206 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800207 read, next, partition);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800208 return -1;
209 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800210 SHA1_Update(&sha_ctx, p, read);
Yabin Cuid6c93af2016-02-10 16:41:10 -0800211 data_size += read;
212 p += read;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800213 }
214
215 // Duplicate the SHA context and finalize the duplicate so we can
216 // check it against this pair's expected hash.
217 SHA_CTX temp_ctx;
218 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800219 uint8_t sha_so_far[SHA_DIGEST_LENGTH];
220 SHA1_Final(sha_so_far, &temp_ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800221
Tao Baoaca8e892015-07-17 11:47:44 -0700222 if (ParseSha1(sha1sum[index[i]].c_str(), parsed_sha) != 0) {
223 printf("failed to parse sha1 %s in %s\n", sha1sum[index[i]].c_str(), filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800224 return -1;
225 }
226
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800227 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800228 // we have a match. stop reading the partition; we'll return
229 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700230 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700231 size[index[i]], sha1sum[index[i]].c_str());
232 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800233 break;
234 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800235 }
236
Doug Zongkerf291d852010-07-07 13:55:25 -0700237 switch (type) {
238 case MTD:
239 mtd_read_close(ctx);
240 break;
241
242 case EMMC:
Jed Estepa7b9a462015-12-15 16:04:53 -0800243 ota_fclose(dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700244 break;
245 }
246
Doug Zongkerc4351c72010-02-22 14:46:32 -0800247
Tao Baoaca8e892015-07-17 11:47:44 -0700248 if (!found) {
249 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700250 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800251 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800252 }
253
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800254 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800255
Yabin Cuid6c93af2016-02-10 16:41:10 -0800256 data.resize(data_size);
257 file->data = std::move(data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800258 // Fake some stat() info.
259 file->st.st_mode = 0644;
260 file->st.st_uid = 0;
261 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800262
Doug Zongkerc4351c72010-02-22 14:46:32 -0800263 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800264}
265
266
267// Save the contents of the given FileContents object under the given
268// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800269int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800270 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800271 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700272 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800273 return -1;
274 }
Doug Zongker512536a2010-02-17 16:11:44 -0800275
Yabin Cuid6c93af2016-02-10 16:41:10 -0800276 ssize_t bytes_written = FileSink(file->data.data(), file->data.size(), &fd);
277 if (bytes_written != static_cast<ssize_t>(file->data.size())) {
278 printf("short write of \"%s\" (%zd bytes of %zu) (%s)\n",
279 filename, bytes_written, file->data.size(), strerror(errno));
Jed Estepa7b9a462015-12-15 16:04:53 -0800280 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800281 return -1;
282 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800283 if (ota_fsync(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700284 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
285 return -1;
286 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800287 if (ota_close(fd) != 0) {
Michael Rungebe81e512014-10-29 12:42:15 -0700288 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
289 return -1;
290 }
Doug Zongker512536a2010-02-17 16:11:44 -0800291
Doug Zongker1c43c972012-02-28 11:07:09 -0800292 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800293 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
294 return -1;
295 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800296 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800297 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
298 return -1;
299 }
Doug Zongker512536a2010-02-17 16:11:44 -0800300
Doug Zongkerc4351c72010-02-22 14:46:32 -0800301 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800302}
303
Doug Zongkerf291d852010-07-07 13:55:25 -0700304// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700305// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
306// might contain multiple colons, but WriteToPartition() only uses the first
307// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800308int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700309 std::string copy(target);
310 std::vector<std::string> pieces = android::base::Split(copy, ":");
311
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700312 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700313 printf("WriteToPartition called with bad target (%s)\n", target);
314 return -1;
315 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700316
317 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700318 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700319 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700320 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700321 type = EMMC;
322 } else {
323 printf("WriteToPartition called with bad target (%s)\n", target);
324 return -1;
325 }
Tao Baoaca8e892015-07-17 11:47:44 -0700326 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800327
Doug Zongkerf291d852010-07-07 13:55:25 -0700328 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700329 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700330 if (!mtd_partitions_scanned) {
331 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700332 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700333 }
334
335 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
336 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700337 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700338 return -1;
339 }
340
341 MtdWriteContext* ctx = mtd_write_partition(mtd);
342 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700343 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700344 return -1;
345 }
346
Yabin Cuid483c202016-02-03 17:08:52 -0800347 size_t written = mtd_write_data(ctx, reinterpret_cast<const char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700348 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700349 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700350 mtd_write_close(ctx);
351 return -1;
352 }
353
354 if (mtd_erase_blocks(ctx, -1) < 0) {
355 printf("error finishing mtd write of %s\n", partition);
356 mtd_write_close(ctx);
357 return -1;
358 }
359
360 if (mtd_write_close(ctx)) {
361 printf("error closing mtd write of %s\n", partition);
362 return -1;
363 }
364 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700365 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700366
Tao Baoba9a42a2015-06-23 23:23:33 -0700367 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700368 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700369 bool success = false;
Jed Estepa7b9a462015-12-15 16:04:53 -0800370 int fd = ota_open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700371 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700372 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700373 return -1;
374 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700375
Tao Baoaca8e892015-07-17 11:47:44 -0700376 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700377 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700378 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700379 return -1;
380 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700381 while (start < len) {
382 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800383 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700384
Jed Estepa7b9a462015-12-15 16:04:53 -0800385 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data+start, to_write));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700386 if (written == -1) {
387 printf("failed write writing to %s: %s\n", partition, strerror(errno));
388 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700389 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700390 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700391 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800392 if (ota_fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700393 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700394 return -1;
395 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800396 if (ota_close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700397 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700398 return -1;
399 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800400 fd = ota_open(partition, O_RDONLY);
Michael Rungebe81e512014-10-29 12:42:15 -0700401 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700402 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700403 return -1;
404 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700405
Tao Baoba9a42a2015-06-23 23:23:33 -0700406 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700407 // won't just be reading the cache.
408 sync();
Jed Estepa7b9a462015-12-15 16:04:53 -0800409 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
410 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700411 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
412 } else {
413 printf(" caches dropped\n");
414 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800415 ota_close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700416 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700417
418 // verify
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700419 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
420 printf("failed to seek back to beginning of %s: %s\n",
421 partition, strerror(errno));
422 return -1;
423 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700424 unsigned char buffer[4096];
425 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700426 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700427 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700428 if (to_read > sizeof(buffer)) {
429 to_read = sizeof(buffer);
430 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700431
Doug Zongkerc870a992013-07-09 10:34:46 -0700432 size_t so_far = 0;
433 while (so_far < to_read) {
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700434 ssize_t read_count =
Jed Estepa7b9a462015-12-15 16:04:53 -0800435 TEMP_FAILURE_RETRY(ota_read(fd, buffer+so_far, to_read-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700436 if (read_count == -1) {
437 printf("verify read error %s at %zu: %s\n",
438 partition, p, strerror(errno));
439 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700440 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700441 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700442 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700443 partition, p, read_count, to_read, strerror(errno));
444 }
445 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700446 }
447
Tao Baoba9a42a2015-06-23 23:23:33 -0700448 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700449 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700450 start = p;
451 break;
452 }
453 }
454
455 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700456 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700457 success = true;
458 break;
459 }
460 }
461
462 if (!success) {
463 printf("failed to verify after all attempts\n");
464 return -1;
465 }
466
Jed Estepa7b9a462015-12-15 16:04:53 -0800467 if (ota_close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700468 printf("error closing %s (%s)\n", partition, strerror(errno));
469 return -1;
470 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700471 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700472 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700473 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800474 }
Doug Zongker512536a2010-02-17 16:11:44 -0800475
Doug Zongkerc4351c72010-02-22 14:46:32 -0800476 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800477}
478
479
480// Take a string 'str' of 40 hex digits and parse it into the 20
481// byte array 'digest'. 'str' may contain only the digest or be of
482// the form "<digest>:<anything>". Return 0 on success, -1 on any
483// error.
484int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800485 const char* ps = str;
486 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800487 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800488 int digit;
489 if (*ps >= '0' && *ps <= '9') {
490 digit = *ps - '0';
491 } else if (*ps >= 'a' && *ps <= 'f') {
492 digit = *ps - 'a' + 10;
493 } else if (*ps >= 'A' && *ps <= 'F') {
494 digit = *ps - 'A' + 10;
495 } else {
496 return -1;
497 }
498 if (i % 2 == 0) {
499 *pd = digit << 4;
500 } else {
501 *pd |= digit;
502 ++pd;
503 }
Doug Zongker512536a2010-02-17 16:11:44 -0800504 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800505 if (*ps != '\0') return -1;
506 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800507}
508
Doug Zongkerc4351c72010-02-22 14:46:32 -0800509// Search an array of sha1 strings for one matching the given sha1.
510// Return the index of the match on success, or -1 if no match is
511// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700512int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800513 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800514 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700515 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800516 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800517 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800518 return i;
519 }
Doug Zongker512536a2010-02-17 16:11:44 -0800520 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800521 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800522}
523
524// Returns 0 if the contents of the file (argv[2]) or the cached file
525// match any of the sha1's on the command line (argv[3:]). Returns
526// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700527int applypatch_check(const char* filename, int num_patches,
528 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800529 FileContents file;
Doug Zongker512536a2010-02-17 16:11:44 -0800530
Doug Zongkerc4351c72010-02-22 14:46:32 -0800531 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700532 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800533 // partitions, where the filename encodes the sha1s; no need to
534 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800535 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800536 (num_patches > 0 &&
537 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
538 printf("file \"%s\" doesn't have any of expected "
539 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800540
Doug Zongkerc4351c72010-02-22 14:46:32 -0800541 // If the source file is missing or corrupted, it might be because
542 // we were killed in the middle of patching it. A copy of it
543 // should have been made in CACHE_TEMP_SOURCE. If that file
544 // exists and matches the sha1 we're looking for, the check still
545 // passes.
546
Doug Zongkera1bc1482014-02-13 15:18:19 -0800547 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800548 printf("failed to load cache file\n");
549 return 1;
550 }
551
552 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
553 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800554 return 1;
555 }
556 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800557 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800558}
559
560int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800561 ShowBSDiffLicense();
562 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800563}
564
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700565ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800566 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800567 ssize_t done = 0;
568 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700569 while (done < len) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800570 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700571 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700572 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800573 return done;
574 }
575 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800576 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800577 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800578}
579
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700580ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800581 std::string* s = static_cast<std::string*>(token);
582 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800583 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800584}
585
586// Return the amount of free space (in bytes) on the filesystem
587// containing filename. filename must exist. Return -1 on error.
588size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800589 struct statfs sf;
590 if (statfs(filename, &sf) != 0) {
591 printf("failed to statfs %s: %s\n", filename, strerror(errno));
592 return -1;
593 }
caozhiyuan3b497762015-05-19 17:21:00 +0800594 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800595}
596
Doug Zongkerc4351c72010-02-22 14:46:32 -0800597int CacheSizeCheck(size_t bytes) {
598 if (MakeFreeSpaceOnCache(bytes) < 0) {
599 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
600 return 1;
601 } else {
602 return 0;
603 }
604}
605
Doug Zongkerc4351c72010-02-22 14:46:32 -0800606// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800607// (the original file is not touched until we have the desired
608// replacement for it) and idempotent (it's okay to run this program
609// multiple times).
610//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800611// - if the sha1 hash of <target_filename> is <target_sha1_string>,
612// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800613//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800614// - otherwise, if the sha1 hash of <source_filename> is one of the
615// entries in <patch_sha1_str>, the corresponding patch from
616// <patch_data> (which must be a VAL_BLOB) is applied to produce a
617// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700618// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619// moves it to replace <target_filename>, and exits successfully.
620// Note that if <source_filename> and <target_filename> are not the
621// same, <source_filename> is NOT deleted on success.
622// <target_filename> may be the string "-" to mean "the same as
623// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800624//
625// - otherwise, or if any error is encountered, exits with non-zero
626// status.
627//
Doug Zongkerf291d852010-07-07 13:55:25 -0700628// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700629// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800630// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800631
Doug Zongkerc4351c72010-02-22 14:46:32 -0800632int applypatch(const char* source_filename,
633 const char* target_filename,
634 const char* target_sha1_str,
635 size_t target_size,
636 int num_patches,
637 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700638 Value** patch_data,
639 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700640 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800641
Tao Baoba9a42a2015-06-23 23:23:33 -0700642 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800643 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800644 }
645
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800646 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800647 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
648 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800649 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800650 }
Doug Zongker512536a2010-02-17 16:11:44 -0800651
Doug Zongkerc4351c72010-02-22 14:46:32 -0800652 FileContents copy_file;
653 FileContents source_file;
654 const Value* source_patch_value = NULL;
655 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800656
Doug Zongkerc4351c72010-02-22 14:46:32 -0800657 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800658 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800659 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800660 // The early-exit case: the patch was already applied, this file
661 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700662 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800663 return 0;
664 }
665 }
Doug Zongker512536a2010-02-17 16:11:44 -0800666
Yabin Cuid6c93af2016-02-10 16:41:10 -0800667 if (source_file.data.empty() ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800668 (target_filename != source_filename &&
669 strcmp(target_filename, source_filename) != 0)) {
670 // Need to load the source file: either we failed to load the
671 // target file, or we did but it's different from the source file.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800672 source_file.data.clear();
Doug Zongkera1bc1482014-02-13 15:18:19 -0800673 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800674 }
675
Yabin Cuid6c93af2016-02-10 16:41:10 -0800676 if (!source_file.data.empty()) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700677 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800678 if (to_use >= 0) {
679 source_patch_value = patch_data[to_use];
680 }
681 }
682
683 if (source_patch_value == NULL) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800684 source_file.data.clear();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800685 printf("source file is bad; trying copy\n");
686
Doug Zongkera1bc1482014-02-13 15:18:19 -0800687 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800688 // fail.
689 printf("failed to read copy file\n");
690 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800691 }
692
Tao Baoba9a42a2015-06-23 23:23:33 -0700693 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700694 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800695 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800696 }
697
Doug Zongkerc4351c72010-02-22 14:46:32 -0800698 if (copy_patch_value == NULL) {
699 // fail.
700 printf("copy file doesn't match source SHA-1s either\n");
701 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800702 }
Doug Zongker512536a2010-02-17 16:11:44 -0800703 }
704
Yabin Cuid6c93af2016-02-10 16:41:10 -0800705 return GenerateTarget(&source_file, source_patch_value,
706 &copy_file, copy_patch_value,
707 source_filename, target_filename,
708 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800709}
710
Tao Baoabba55b2015-07-17 18:11:12 -0700711/*
712 * This function flashes a given image to the target partition. It verifies
713 * the target cheksum first, and will return if target has the desired hash.
714 * It checks the checksum of the given source image before flashing, and
715 * verifies the target partition afterwards. The function is idempotent.
716 * Returns zero on success.
717 */
718int applypatch_flash(const char* source_filename, const char* target_filename,
719 const char* target_sha1_str, size_t target_size) {
720 printf("flash %s: ", target_filename);
721
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800722 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700723 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
724 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
725 return 1;
726 }
727
728 FileContents source_file;
Tao Baoabba55b2015-07-17 18:11:12 -0700729 std::string target_str(target_filename);
730
731 std::vector<std::string> pieces = android::base::Split(target_str, ":");
732 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
733 printf("invalid target name \"%s\"", target_filename);
734 return 1;
735 }
736
737 // Load the target into the source_file object to see if already applied.
738 pieces.push_back(std::to_string(target_size));
739 pieces.push_back(target_sha1_str);
740 std::string fullname = android::base::Join(pieces, ':');
741 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800742 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700743 // The early-exit case: the image was already applied, this partition
744 // has the desired hash, nothing for us to do.
745 printf("already %s\n", short_sha1(target_sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700746 return 0;
747 }
748
749 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800750 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700751 // The source doesn't have desired checksum.
752 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
753 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
754 short_sha1(source_file.sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700755 return 1;
756 }
757 }
758
Yabin Cuid6c93af2016-02-10 16:41:10 -0800759 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700760 printf("write of copied data to %s failed\n", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700761 return 1;
762 }
Tao Baoabba55b2015-07-17 18:11:12 -0700763 return 0;
764}
765
Doug Zongker1c43c972012-02-28 11:07:09 -0800766static int GenerateTarget(FileContents* source_file,
767 const Value* source_patch_value,
768 FileContents* copy_file,
769 const Value* copy_patch_value,
770 const char* source_filename,
771 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800772 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700773 size_t target_size,
774 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800775 int retry = 1;
776 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800777 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800778 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800779 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800780
Yabin Cuid483c202016-02-03 17:08:52 -0800781 bool target_is_partition = (strncmp(target_filename, "MTD:", 4) == 0 ||
782 strncmp(target_filename, "EMMC:", 5) == 0);
783 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
784
Doug Zongkerc4351c72010-02-22 14:46:32 -0800785 // assume that target_filename (eg "/system/app/Foo.apk") is located
786 // on the same filesystem as its top-level directory ("/system").
787 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800788 std::string target_fs = target_filename;
789 auto slash_pos = target_fs.find('/', 1);
790 if (slash_pos != std::string::npos) {
791 target_fs.resize(slash_pos);
792 }
793
794 const Value* patch;
795 if (source_patch_value != NULL) {
796 source_to_use = source_file;
797 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800798 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800799 source_to_use = copy_file;
800 patch = copy_patch_value;
801 }
802 if (patch->type != VAL_BLOB) {
803 printf("patch is not a blob\n");
804 return 1;
805 }
806 char* header = patch->data;
807 ssize_t header_bytes_read = patch->size;
808 bool use_bsdiff = false;
809 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
810 use_bsdiff = true;
811 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
812 use_bsdiff = false;
813 } else {
814 printf("Unknown patch file format\n");
815 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800816 }
817
Doug Zongkerc4351c72010-02-22 14:46:32 -0800818 do {
819 // Is there enough room in the target filesystem to hold the patched
820 // file?
821
Yabin Cuid483c202016-02-03 17:08:52 -0800822 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700823 // If the target is a partition, we're actually going to
824 // write the output to /tmp and then copy it to the
825 // partition. statfs() always returns 0 blocks free for
826 // /tmp, so instead we'll just assume that /tmp has enough
827 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800828
Doug Zongkerf291d852010-07-07 13:55:25 -0700829 // We still write the original source to cache, in case
830 // the partition write is interrupted.
Yabin Cuid6c93af2016-02-10 16:41:10 -0800831 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800832 printf("not enough free space on /cache\n");
833 return 1;
834 }
835 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
836 printf("failed to back up source file\n");
837 return 1;
838 }
839 made_copy = 1;
840 retry = 0;
841 } else {
842 int enough_space = 0;
843 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800844 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700845 enough_space =
846 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800847 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700848 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700849 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
850 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700851 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800852 }
853
854 if (!enough_space) {
855 retry = 0;
856 }
857
858 if (!enough_space && source_patch_value != NULL) {
859 // Using the original source, but not enough free space. First
860 // copy the source file to cache, then delete it from the original
861 // location.
862
Doug Zongkerf291d852010-07-07 13:55:25 -0700863 if (strncmp(source_filename, "MTD:", 4) == 0 ||
864 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800865 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700866 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800867 // we're ever in a state where we need to do this, fail.
Tao Baoba9a42a2015-06-23 23:23:33 -0700868 printf("not enough free space for target but source is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800869 return 1;
870 }
871
Yabin Cuid6c93af2016-02-10 16:41:10 -0800872 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800873 printf("not enough free space on /cache\n");
874 return 1;
875 }
876
877 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
878 printf("failed to back up source file\n");
879 return 1;
880 }
881 made_copy = 1;
882 unlink(source_filename);
883
Yabin Cuid483c202016-02-03 17:08:52 -0800884 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Tao Baoba9a42a2015-06-23 23:23:33 -0700885 printf("(now %zu bytes free for target) ", free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886 }
887 }
888
Doug Zongkerc4351c72010-02-22 14:46:32 -0800889
890 SinkFn sink = NULL;
891 void* token = NULL;
Yabin Cuid483c202016-02-03 17:08:52 -0800892 int output_fd = -1;
893 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800894 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800895 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800896 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800897 } else {
898 // We write the decoded output to "<tgt-file>.patch".
Jed Estepa7b9a462015-12-15 16:04:53 -0800899 output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
900 S_IRUSR | S_IWUSR);
Yabin Cuid483c202016-02-03 17:08:52 -0800901 if (output_fd < 0) {
902 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
903 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800904 return 1;
905 }
906 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800907 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800908 }
909
Doug Zongkerc4351c72010-02-22 14:46:32 -0800910
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800911 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800912
913 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800914 if (use_bsdiff) {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800915 result = ApplyBSDiffPatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkerc4351c72010-02-22 14:46:32 -0800916 patch, 0, sink, token, &ctx);
Yabin Cuid483c202016-02-03 17:08:52 -0800917 } else {
Yabin Cuid6c93af2016-02-10 16:41:10 -0800918 result = ApplyImagePatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkera3ccba62012-08-20 15:28:02 -0700919 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800920 }
921
Yabin Cuid483c202016-02-03 17:08:52 -0800922 if (!target_is_partition) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800923 if (ota_fsync(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800924 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
925 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700926 result = 1;
927 }
Jed Estepa7b9a462015-12-15 16:04:53 -0800928 if (ota_close(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800929 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
930 strerror(errno));
Michael Rungebe81e512014-10-29 12:42:15 -0700931 result = 1;
932 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800933 }
934
935 if (result != 0) {
936 if (retry == 0) {
937 printf("applying patch failed\n");
938 return result != 0;
939 } else {
940 printf("applying patch failed; retrying\n");
941 }
Yabin Cuid483c202016-02-03 17:08:52 -0800942 if (!target_is_partition) {
943 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800944 }
945 } else {
946 // succeeded; no need to retry
947 break;
948 }
949 } while (retry-- > 0);
950
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800951 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
952 SHA1_Final(current_target_sha1, &ctx);
953 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800954 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800955 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700956 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700957 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800958 }
959
Yabin Cuid483c202016-02-03 17:08:52 -0800960 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700961 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -0800962 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
963 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800964 printf("write of patched data to %s failed\n", target_filename);
965 return 1;
966 }
Doug Zongker512536a2010-02-17 16:11:44 -0800967 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800968 // Give the .patch file the same owner, group, and mode of the
969 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -0800970 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
971 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800972 return 1;
973 }
Yabin Cuid483c202016-02-03 17:08:52 -0800974 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
975 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800976 return 1;
977 }
Doug Zongker512536a2010-02-17 16:11:44 -0800978
Doug Zongkerc4351c72010-02-22 14:46:32 -0800979 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -0800980 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700981 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800982 return 1;
983 }
Doug Zongker512536a2010-02-17 16:11:44 -0800984 }
985
Doug Zongkerc4351c72010-02-22 14:46:32 -0800986 // If this run of applypatch created the copy, and we're here, we
987 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -0700988 if (made_copy) {
989 unlink(CACHE_TEMP_SOURCE);
990 }
Doug Zongker512536a2010-02-17 16:11:44 -0800991
Doug Zongkerc4351c72010-02-22 14:46:32 -0800992 // Success!
993 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800994}