blob: c2fe11b3b7846a421c5c06492c3b1861e3418c19 [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"
Conn O'Griofad9201042014-03-25 01:26:49 +000035#include "bmlutils/bmlutils.h"
Doug Zongker512536a2010-02-17 16:11:44 -080036#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080037#include "edify/expr.h"
Jed Estepff6df892015-12-15 16:04:53 -080038#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070039#include "print_sha1.h"
Doug Zongker512536a2010-02-17 16:11:44 -080040
Doug Zongkerf291d852010-07-07 13:55:25 -070041static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070042static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080043static int GenerateTarget(FileContents* source_file,
44 const Value* source_patch_value,
45 FileContents* copy_file,
46 const Value* copy_patch_value,
47 const char* source_filename,
48 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +080049 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -070050 size_t target_size,
51 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080052
Tao Baoaca8e892015-07-17 11:47:44 -070053static bool mtd_partitions_scanned = false;
Doug Zongker512536a2010-02-17 16:11:44 -080054
Doug Zongkera1bc1482014-02-13 15:18:19 -080055// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070056// metadata in *file.
57//
58// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080059int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongkerf291d852010-07-07 13:55:25 -070060 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
61 // load the contents of a partition.
62 if (strncmp(filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +000063 strncmp(filename, "EMMC:", 5) == 0 ||
64 strncmp(filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -070065 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
Yabin Cui1c522df2016-02-10 16:41:10 -080073 std::vector<unsigned char> data(file->st.st_size);
Jed Estepf1fc48c2015-12-15 16:04:53 -080074 FILE* f = ota_fopen(filename, "rb");
Doug Zongkerc4351c72010-02-22 14:46:32 -080075 if (f == NULL) {
76 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -080077 return -1;
78 }
79
Yabin Cui1c522df2016-02-10 16:41:10 -080080 size_t bytes_read = ota_fread(data.data(), 1, data.size(), f);
81 if (bytes_read != data.size()) {
82 printf("short read of \"%s\" (%zu bytes of %zd)\n", filename, bytes_read, data.size());
83 ota_fclose(f);
Doug Zongkerc4351c72010-02-22 14:46:32 -080084 return -1;
85 }
Jed Estepf1fc48c2015-12-15 16:04:53 -080086 ota_fclose(f);
Yabin Cui1c522df2016-02-10 16:41:10 -080087 file->data = std::move(data);
88 SHA1(file->data.data(), file->data.size(), file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080089 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080090}
91
Doug Zongkerf291d852010-07-07 13:55:25 -070092// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -080093// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -070094// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
95// "EMMC:<partition_device>:..."). The smallest size_n bytes for
96// which that prefix of the partition contents has the corresponding
97// sha1 hash will be loaded. It is acceptable for a size value to be
98// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -080099//
100// This complexity is needed because if an OTA installation is
101// interrupted, the partition might contain either the source or the
102// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700103// the length in order to read from a partition (there is no
104// "end-of-file" marker), so the caller must specify the possible
105// lengths and the hash of the data, and we'll do the load expecting
106// to find one of those hashes.
107enum PartitionType { MTD, EMMC };
108
109static int LoadPartitionContents(const char* filename, FileContents* file) {
Tao Baoaca8e892015-07-17 11:47:44 -0700110 std::string copy(filename);
111 std::vector<std::string> pieces = android::base::Split(copy, ":");
112 if (pieces.size() < 4 || pieces.size() % 2 != 0) {
113 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
114 return -1;
115 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700116
117 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700118 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700119 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700120 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700121 type = EMMC;
Ethan Yonkerb8e985c2016-08-31 13:42:11 -0500122 } else if (pieces[0] == "BML") {
Conn O'Griofad9201042014-03-25 01:26:49 +0000123 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700124 } else {
Tao Baoba9a42a2015-06-23 23:23:33 -0700125 printf("LoadPartitionContents called with bad filename (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800126 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800127 }
Tao Baoaca8e892015-07-17 11:47:44 -0700128 const char* partition = pieces[1].c_str();
Doug Zongker512536a2010-02-17 16:11:44 -0800129
Ethan Yonkerb8e985c2016-08-31 13:42:11 -0500130 if (pieces[0] == "BML") {
Conn O'Griofad9201042014-03-25 01:26:49 +0000131 if (strcmp(partition, "boot") == 0) {
132 partition = BOARD_BML_BOOT;
133 } else if (strcmp(partition, "recovery") == 0) {
134 partition = BOARD_BML_RECOVERY;
135 }
136 }
137
Tao Baoaca8e892015-07-17 11:47:44 -0700138 size_t pairs = (pieces.size() - 2) / 2; // # of (size, sha1) pairs in filename
139 std::vector<size_t> index(pairs);
140 std::vector<size_t> size(pairs);
141 std::vector<std::string> sha1sum(pairs);
Doug Zongker512536a2010-02-17 16:11:44 -0800142
Tao Baoaca8e892015-07-17 11:47:44 -0700143 for (size_t i = 0; i < pairs; ++i) {
144 size[i] = strtol(pieces[i*2+2].c_str(), NULL, 10);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800145 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700146 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800147 return -1;
148 }
Tao Baoaca8e892015-07-17 11:47:44 -0700149 sha1sum[i] = pieces[i*2+3].c_str();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800150 index[i] = i;
151 }
Doug Zongker512536a2010-02-17 16:11:44 -0800152
Tao Baoaca8e892015-07-17 11:47:44 -0700153 // Sort the index[] array so it indexes the pairs in order of increasing size.
154 sort(index.begin(), index.end(),
155 [&](const size_t& i, const size_t& j) {
156 return (size[i] < size[j]);
157 }
158 );
Doug Zongker512536a2010-02-17 16:11:44 -0800159
Doug Zongkerf291d852010-07-07 13:55:25 -0700160 MtdReadContext* ctx = NULL;
161 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800162
Doug Zongkerf291d852010-07-07 13:55:25 -0700163 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700164 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700165 if (!mtd_partitions_scanned) {
166 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700167 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700168 }
Doug Zongker512536a2010-02-17 16:11:44 -0800169
Doug Zongkerf291d852010-07-07 13:55:25 -0700170 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
171 if (mtd == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700172 printf("mtd partition \"%s\" not found (loading %s)\n", partition, filename);
Doug Zongkerf291d852010-07-07 13:55:25 -0700173 return -1;
174 }
175
176 ctx = mtd_read_partition(mtd);
177 if (ctx == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700178 printf("failed to initialize read of mtd partition \"%s\"\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700179 return -1;
180 }
181 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700182 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700183
184 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800185 dev = ota_fopen(partition, "rb");
Doug Zongkerf291d852010-07-07 13:55:25 -0700186 if (dev == NULL) {
Tao Baoaca8e892015-07-17 11:47:44 -0700187 printf("failed to open emmc partition \"%s\": %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700188 return -1;
189 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800190 }
Doug Zongker512536a2010-02-17 16:11:44 -0800191
Doug Zongkerc4351c72010-02-22 14:46:32 -0800192 SHA_CTX sha_ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800193 SHA1_Init(&sha_ctx);
194 uint8_t parsed_sha[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800195
Tao Baoaca8e892015-07-17 11:47:44 -0700196 // Allocate enough memory to hold the largest size.
Yabin Cui1c522df2016-02-10 16:41:10 -0800197 std::vector<unsigned char> data(size[index[pairs-1]]);
198 char* p = reinterpret_cast<char*>(data.data());
199 size_t data_size = 0; // # bytes read so far
Tao Baoaca8e892015-07-17 11:47:44 -0700200 bool found = false;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800201
Tao Baoaca8e892015-07-17 11:47:44 -0700202 for (size_t i = 0; i < pairs; ++i) {
203 // Read enough additional bytes to get us up to the next size. (Again,
204 // we're trying the possibilities in order of increasing size).
Yabin Cui1c522df2016-02-10 16:41:10 -0800205 size_t next = size[index[i]] - data_size;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800206 if (next > 0) {
Yabin Cui1c522df2016-02-10 16:41:10 -0800207 size_t read = 0;
Doug Zongkerf291d852010-07-07 13:55:25 -0700208 switch (type) {
209 case MTD:
210 read = mtd_read_data(ctx, p, next);
211 break;
212
213 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800214 read = ota_fread(p, 1, next, dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700215 break;
216 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800217 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700218 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800219 read, next, partition);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800220 return -1;
221 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800222 SHA1_Update(&sha_ctx, p, read);
Yabin Cui1c522df2016-02-10 16:41:10 -0800223 data_size += read;
224 p += read;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800225 }
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 return -1;
237 }
238
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800239 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800240 // we have a match. stop reading the partition; we'll return
241 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700242 printf("partition read matched size %zu sha %s\n",
Tao Baoaca8e892015-07-17 11:47:44 -0700243 size[index[i]], sha1sum[index[i]].c_str());
244 found = true;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800245 break;
246 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800247 }
248
Doug Zongkerf291d852010-07-07 13:55:25 -0700249 switch (type) {
250 case MTD:
251 mtd_read_close(ctx);
252 break;
253
254 case EMMC:
Jed Estepf1fc48c2015-12-15 16:04:53 -0800255 ota_fclose(dev);
Doug Zongkerf291d852010-07-07 13:55:25 -0700256 break;
257 }
258
Doug Zongkerc4351c72010-02-22 14:46:32 -0800259
Tao Baoaca8e892015-07-17 11:47:44 -0700260 if (!found) {
261 // Ran off the end of the list of (size,sha1) pairs without finding a match.
Tao Baoba9a42a2015-06-23 23:23:33 -0700262 printf("contents of partition \"%s\" didn't match %s\n", partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800263 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800264 }
265
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800266 SHA1_Final(file->sha1, &sha_ctx);
Doug Zongker512536a2010-02-17 16:11:44 -0800267
Yabin Cui1c522df2016-02-10 16:41:10 -0800268 data.resize(data_size);
269 file->data = std::move(data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800270 // Fake some stat() info.
271 file->st.st_mode = 0644;
272 file->st.st_uid = 0;
273 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800274
Doug Zongkerc4351c72010-02-22 14:46:32 -0800275 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800276}
277
278
279// Save the contents of the given FileContents object under the given
280// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800281int SaveFileContents(const char* filename, const FileContents* file) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800282 int fd = ota_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800283 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700284 printf("failed to open \"%s\" for write: %s\n", filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800285 return -1;
286 }
Doug Zongker512536a2010-02-17 16:11:44 -0800287
Yabin Cui1c522df2016-02-10 16:41:10 -0800288 ssize_t bytes_written = FileSink(file->data.data(), file->data.size(), &fd);
289 if (bytes_written != static_cast<ssize_t>(file->data.size())) {
290 printf("short write of \"%s\" (%zd bytes of %zu) (%s)\n",
291 filename, bytes_written, file->data.size(), strerror(errno));
Jed Estepf1fc48c2015-12-15 16:04:53 -0800292 ota_close(fd);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800293 return -1;
294 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800295 if (ota_fsync(fd) != 0) {
Michael Rungecddb68b2014-10-29 12:42:15 -0700296 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
297 return -1;
298 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800299 if (ota_close(fd) != 0) {
Michael Rungecddb68b2014-10-29 12:42:15 -0700300 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
301 return -1;
302 }
Doug Zongker512536a2010-02-17 16:11:44 -0800303
Doug Zongker1c43c972012-02-28 11:07:09 -0800304 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800305 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
306 return -1;
307 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800308 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800309 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
310 return -1;
311 }
Doug Zongker512536a2010-02-17 16:11:44 -0800312
Doug Zongkerc4351c72010-02-22 14:46:32 -0800313 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800314}
315
Doug Zongkerf291d852010-07-07 13:55:25 -0700316// Write a memory buffer to 'target' partition, a string of the form
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700317// "MTD:<partition>[:...]" or "EMMC:<partition_device>[:...]". The target name
318// might contain multiple colons, but WriteToPartition() only uses the first
319// two and ignores the rest. Return 0 on success.
Yabin Cuid483c202016-02-03 17:08:52 -0800320int WriteToPartition(const unsigned char* data, size_t len, const char* target) {
Tao Baoaca8e892015-07-17 11:47:44 -0700321 std::string copy(target);
322 std::vector<std::string> pieces = android::base::Split(copy, ":");
323
Tao Bao1ce7a2a2015-07-24 15:29:12 -0700324 if (pieces.size() < 2) {
Tao Baoaca8e892015-07-17 11:47:44 -0700325 printf("WriteToPartition called with bad target (%s)\n", target);
326 return -1;
327 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700328
329 enum PartitionType type;
Tao Baoaca8e892015-07-17 11:47:44 -0700330 if (pieces[0] == "MTD") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700331 type = MTD;
Tao Baoaca8e892015-07-17 11:47:44 -0700332 } else if (pieces[0] == "EMMC") {
Doug Zongkerf291d852010-07-07 13:55:25 -0700333 type = EMMC;
Ethan Yonkerb8e985c2016-08-31 13:42:11 -0500334 } else if (pieces[0] == "BML") {
Conn O'Griofad9201042014-03-25 01:26:49 +0000335 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700336 } else {
337 printf("WriteToPartition called with bad target (%s)\n", target);
338 return -1;
339 }
Ethan Yonker34ae4832016-08-24 15:32:18 -0500340
Tao Baoaca8e892015-07-17 11:47:44 -0700341 const char* partition = pieces[1].c_str();
Doug Zongkerf291d852010-07-07 13:55:25 -0700342
Ethan Yonkerb8e985c2016-08-31 13:42:11 -0500343 if (pieces[0] == "BML") {
Conn O'Griofad9201042014-03-25 01:26:49 +0000344 if (strcmp(partition, "boot") == 0) {
345 partition = BOARD_BML_BOOT;
346 } else if (strcmp(partition, "recovery") == 0) {
347 partition = BOARD_BML_RECOVERY;
348 }
349
350 int bmlpartition = open(partition, O_RDWR | O_LARGEFILE);
351 if (bmlpartition < 0)
352 return -1;
353 if (ioctl(bmlpartition, BML_UNLOCK_ALL, 0)) {
354 printf("failed to unlock BML partition: (%s)\n", partition);
355 return -1;
356 }
357 close(bmlpartition);
358 }
359
Doug Zongkerc4351c72010-02-22 14:46:32 -0800360 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700361 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800362 return -1;
363 }
Doug Zongker512536a2010-02-17 16:11:44 -0800364
Doug Zongkerf291d852010-07-07 13:55:25 -0700365 switch (type) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700366 case MTD: {
Doug Zongkerf291d852010-07-07 13:55:25 -0700367 if (!mtd_partitions_scanned) {
368 mtd_scan_partitions();
Tao Baoaca8e892015-07-17 11:47:44 -0700369 mtd_partitions_scanned = true;
Doug Zongkerf291d852010-07-07 13:55:25 -0700370 }
371
372 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
373 if (mtd == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700374 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700375 return -1;
376 }
377
378 MtdWriteContext* ctx = mtd_write_partition(mtd);
379 if (ctx == NULL) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700380 printf("failed to init mtd partition \"%s\" for writing\n", partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700381 return -1;
382 }
383
Yabin Cuid483c202016-02-03 17:08:52 -0800384 size_t written = mtd_write_data(ctx, reinterpret_cast<const char*>(data), len);
Doug Zongkerf291d852010-07-07 13:55:25 -0700385 if (written != len) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700386 printf("only wrote %zu of %zu bytes to MTD %s\n", written, len, partition);
Doug Zongkerf291d852010-07-07 13:55:25 -0700387 mtd_write_close(ctx);
388 return -1;
389 }
390
391 if (mtd_erase_blocks(ctx, -1) < 0) {
392 printf("error finishing mtd write of %s\n", partition);
393 mtd_write_close(ctx);
394 return -1;
395 }
396
397 if (mtd_write_close(ctx)) {
398 printf("error closing mtd write of %s\n", partition);
399 return -1;
400 }
401 break;
Tao Baoba9a42a2015-06-23 23:23:33 -0700402 }
Doug Zongkerf291d852010-07-07 13:55:25 -0700403
Tao Baoba9a42a2015-06-23 23:23:33 -0700404 case EMMC: {
Doug Zongker044a0b42013-07-08 09:42:54 -0700405 size_t start = 0;
Tao Baoba9a42a2015-06-23 23:23:33 -0700406 bool success = false;
Jed Estepf1fc48c2015-12-15 16:04:53 -0800407 int fd = ota_open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700408 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700409 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700410 return -1;
411 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700412
Tao Baoaca8e892015-07-17 11:47:44 -0700413 for (size_t attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700414 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700415 printf("failed seek on %s: %s\n", partition, strerror(errno));
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700416 return -1;
417 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700418 while (start < len) {
419 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800420 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700421
Jed Estepf1fc48c2015-12-15 16:04:53 -0800422 ssize_t written = TEMP_FAILURE_RETRY(ota_write(fd, data+start, to_write));
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700423 if (written == -1) {
424 printf("failed write writing to %s: %s\n", partition, strerror(errno));
425 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700426 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700427 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700428 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800429 if (ota_fsync(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700430 printf("failed to sync to %s (%s)\n", partition, strerror(errno));
Michael Rungecddb68b2014-10-29 12:42:15 -0700431 return -1;
432 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800433 if (ota_close(fd) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700434 printf("failed to close %s (%s)\n", partition, strerror(errno));
Michael Rungecddb68b2014-10-29 12:42:15 -0700435 return -1;
436 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800437 fd = ota_open(partition, O_RDONLY);
Michael Rungecddb68b2014-10-29 12:42:15 -0700438 if (fd < 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700439 printf("failed to reopen %s for verify (%s)\n", partition, strerror(errno));
Michael Rungecddb68b2014-10-29 12:42:15 -0700440 return -1;
441 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700442
Tao Baoba9a42a2015-06-23 23:23:33 -0700443 // Drop caches so our subsequent verification read
Doug Zongker044a0b42013-07-08 09:42:54 -0700444 // won't just be reading the cache.
445 sync();
Jed Estepf1fc48c2015-12-15 16:04:53 -0800446 int dc = ota_open("/proc/sys/vm/drop_caches", O_WRONLY);
447 if (TEMP_FAILURE_RETRY(ota_write(dc, "3\n", 2)) == -1) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700448 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
449 } else {
450 printf(" caches dropped\n");
451 }
Jed Estepf1fc48c2015-12-15 16:04:53 -0800452 ota_close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700453 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700454
455 // verify
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700456 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
457 printf("failed to seek back to beginning of %s: %s\n",
458 partition, strerror(errno));
459 return -1;
460 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700461 unsigned char buffer[4096];
462 start = len;
Tao Baoba9a42a2015-06-23 23:23:33 -0700463 for (size_t p = 0; p < len; p += sizeof(buffer)) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700464 size_t to_read = len - p;
Tao Baoba9a42a2015-06-23 23:23:33 -0700465 if (to_read > sizeof(buffer)) {
466 to_read = sizeof(buffer);
467 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700468
Doug Zongkerc870a992013-07-09 10:34:46 -0700469 size_t so_far = 0;
470 while (so_far < to_read) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700471 ssize_t read_count =
Jed Estepf1fc48c2015-12-15 16:04:53 -0800472 TEMP_FAILURE_RETRY(ota_read(fd, buffer+so_far, to_read-so_far));
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700473 if (read_count == -1) {
474 printf("verify read error %s at %zu: %s\n",
475 partition, p, strerror(errno));
476 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700477 }
Tao Baoba9a42a2015-06-23 23:23:33 -0700478 if (static_cast<size_t>(read_count) < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700479 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700480 partition, p, read_count, to_read, strerror(errno));
481 }
482 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700483 }
484
Tao Baoba9a42a2015-06-23 23:23:33 -0700485 if (memcmp(buffer, data+p, to_read) != 0) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700486 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700487 start = p;
488 break;
489 }
490 }
491
492 if (start == len) {
Tao Baoabba55b2015-07-17 18:11:12 -0700493 printf("verification read succeeded (attempt %zu)\n", attempt+1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700494 success = true;
495 break;
496 }
497 }
498
499 if (!success) {
500 printf("failed to verify after all attempts\n");
501 return -1;
502 }
503
Jed Estepf1fc48c2015-12-15 16:04:53 -0800504 if (ota_close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700505 printf("error closing %s (%s)\n", partition, strerror(errno));
506 return -1;
507 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700508 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700509 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700510 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800511 }
Doug Zongker512536a2010-02-17 16:11:44 -0800512
Doug Zongkerc4351c72010-02-22 14:46:32 -0800513 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800514}
515
516
517// Take a string 'str' of 40 hex digits and parse it into the 20
518// byte array 'digest'. 'str' may contain only the digest or be of
519// the form "<digest>:<anything>". Return 0 on success, -1 on any
520// error.
521int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800522 const char* ps = str;
523 uint8_t* pd = digest;
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800524 for (int i = 0; i < SHA_DIGEST_LENGTH * 2; ++i, ++ps) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800525 int digit;
526 if (*ps >= '0' && *ps <= '9') {
527 digit = *ps - '0';
528 } else if (*ps >= 'a' && *ps <= 'f') {
529 digit = *ps - 'a' + 10;
530 } else if (*ps >= 'A' && *ps <= 'F') {
531 digit = *ps - 'A' + 10;
532 } else {
533 return -1;
534 }
535 if (i % 2 == 0) {
536 *pd = digit << 4;
537 } else {
538 *pd |= digit;
539 ++pd;
540 }
Doug Zongker512536a2010-02-17 16:11:44 -0800541 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800542 if (*ps != '\0') return -1;
543 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800544}
545
Doug Zongkerc4351c72010-02-22 14:46:32 -0800546// Search an array of sha1 strings for one matching the given sha1.
547// Return the index of the match on success, or -1 if no match is
548// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700549int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800550 int num_patches) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800551 uint8_t patch_sha1[SHA_DIGEST_LENGTH];
Tao Baoba9a42a2015-06-23 23:23:33 -0700552 for (int i = 0; i < num_patches; ++i) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800553 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800554 memcmp(patch_sha1, sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800555 return i;
556 }
Doug Zongker512536a2010-02-17 16:11:44 -0800557 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800558 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800559}
560
561// Returns 0 if the contents of the file (argv[2]) or the cached file
562// match any of the sha1's on the command line (argv[3:]). Returns
563// nonzero otherwise.
Tao Baoba9a42a2015-06-23 23:23:33 -0700564int applypatch_check(const char* filename, int num_patches,
565 char** const patch_sha1_str) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800566 FileContents file;
Doug Zongker512536a2010-02-17 16:11:44 -0800567
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700569 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800570 // partitions, where the filename encodes the sha1s; no need to
571 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800572 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800573 (num_patches > 0 &&
574 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
575 printf("file \"%s\" doesn't have any of expected "
576 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800577
Doug Zongkerc4351c72010-02-22 14:46:32 -0800578 // If the source file is missing or corrupted, it might be because
579 // we were killed in the middle of patching it. A copy of it
580 // should have been made in CACHE_TEMP_SOURCE. If that file
581 // exists and matches the sha1 we're looking for, the check still
582 // passes.
583
Doug Zongkera1bc1482014-02-13 15:18:19 -0800584 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800585 printf("failed to load cache file\n");
586 return 1;
587 }
588
589 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
590 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800591 return 1;
592 }
593 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800594 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800595}
596
597int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800598 ShowBSDiffLicense();
599 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800600}
601
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700602ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800603 int fd = *static_cast<int*>(token);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800604 ssize_t done = 0;
605 ssize_t wrote;
Tao Baoba9a42a2015-06-23 23:23:33 -0700606 while (done < len) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800607 wrote = TEMP_FAILURE_RETRY(ota_write(fd, data+done, len-done));
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700608 if (wrote == -1) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700609 printf("error writing %zd bytes: %s\n", (len-done), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800610 return done;
611 }
612 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800613 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800614 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800615}
616
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700617ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Yabin Cuid483c202016-02-03 17:08:52 -0800618 std::string* s = static_cast<std::string*>(token);
619 s->append(reinterpret_cast<const char*>(data), len);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800620 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800621}
622
623// Return the amount of free space (in bytes) on the filesystem
624// containing filename. filename must exist. Return -1 on error.
625size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800626 struct statfs sf;
627 if (statfs(filename, &sf) != 0) {
628 printf("failed to statfs %s: %s\n", filename, strerror(errno));
629 return -1;
630 }
caozhiyuancb9450e2015-05-19 17:21:00 +0800631 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800632}
633
Doug Zongkerc4351c72010-02-22 14:46:32 -0800634int CacheSizeCheck(size_t bytes) {
635 if (MakeFreeSpaceOnCache(bytes) < 0) {
636 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
637 return 1;
638 } else {
639 return 0;
640 }
641}
642
Doug Zongkerc4351c72010-02-22 14:46:32 -0800643// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800644// (the original file is not touched until we have the desired
645// replacement for it) and idempotent (it's okay to run this program
646// multiple times).
647//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800648// - if the sha1 hash of <target_filename> is <target_sha1_string>,
649// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800650//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800651// - otherwise, if the sha1 hash of <source_filename> is one of the
652// entries in <patch_sha1_str>, the corresponding patch from
653// <patch_data> (which must be a VAL_BLOB) is applied to produce a
654// new file (the type of patch is automatically detected from the
Tao Baoabba55b2015-07-17 18:11:12 -0700655// blob data). If that new file has sha1 hash <target_sha1_str>,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800656// moves it to replace <target_filename>, and exits successfully.
657// Note that if <source_filename> and <target_filename> are not the
658// same, <source_filename> is NOT deleted on success.
659// <target_filename> may be the string "-" to mean "the same as
660// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800661//
662// - otherwise, or if any error is encountered, exits with non-zero
663// status.
664//
Doug Zongkerf291d852010-07-07 13:55:25 -0700665// <source_filename> may refer to a partition to read the source data.
Tao Baoabba55b2015-07-17 18:11:12 -0700666// See the comments for the LoadPartitionContents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800667// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800668
Doug Zongkerc4351c72010-02-22 14:46:32 -0800669int applypatch(const char* source_filename,
670 const char* target_filename,
671 const char* target_sha1_str,
672 size_t target_size,
673 int num_patches,
674 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700675 Value** patch_data,
676 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700677 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800678
Tao Baoba9a42a2015-06-23 23:23:33 -0700679 if (target_filename[0] == '-' && target_filename[1] == '\0') {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800680 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800681 }
682
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800683 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Doug Zongkerc4351c72010-02-22 14:46:32 -0800684 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
685 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800686 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800687 }
Doug Zongker512536a2010-02-17 16:11:44 -0800688
Doug Zongkerc4351c72010-02-22 14:46:32 -0800689 FileContents copy_file;
690 FileContents source_file;
691 const Value* source_patch_value = NULL;
692 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800693
Doug Zongkerc4351c72010-02-22 14:46:32 -0800694 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800695 if (LoadFileContents(target_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800696 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800697 // The early-exit case: the patch was already applied, this file
698 // has the desired hash, nothing for us to do.
Tao Baoabba55b2015-07-17 18:11:12 -0700699 printf("already %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800700 return 0;
701 }
702 }
Doug Zongker512536a2010-02-17 16:11:44 -0800703
Yabin Cui1c522df2016-02-10 16:41:10 -0800704 if (source_file.data.empty() ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800705 (target_filename != source_filename &&
706 strcmp(target_filename, source_filename) != 0)) {
707 // Need to load the source file: either we failed to load the
708 // target file, or we did but it's different from the source file.
Yabin Cui1c522df2016-02-10 16:41:10 -0800709 source_file.data.clear();
Doug Zongkera1bc1482014-02-13 15:18:19 -0800710 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800711 }
712
Yabin Cui1c522df2016-02-10 16:41:10 -0800713 if (!source_file.data.empty()) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700714 int to_use = FindMatchingPatch(source_file.sha1, patch_sha1_str, num_patches);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800715 if (to_use >= 0) {
716 source_patch_value = patch_data[to_use];
717 }
718 }
719
720 if (source_patch_value == NULL) {
Yabin Cui1c522df2016-02-10 16:41:10 -0800721 source_file.data.clear();
Doug Zongkerc4351c72010-02-22 14:46:32 -0800722 printf("source file is bad; trying copy\n");
723
Doug Zongkera1bc1482014-02-13 15:18:19 -0800724 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800725 // fail.
726 printf("failed to read copy file\n");
727 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800728 }
729
Tao Baoba9a42a2015-06-23 23:23:33 -0700730 int to_use = FindMatchingPatch(copy_file.sha1, patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700731 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800732 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800733 }
734
Doug Zongkerc4351c72010-02-22 14:46:32 -0800735 if (copy_patch_value == NULL) {
736 // fail.
737 printf("copy file doesn't match source SHA-1s either\n");
738 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800739 }
Doug Zongker512536a2010-02-17 16:11:44 -0800740 }
741
Yabin Cui1c522df2016-02-10 16:41:10 -0800742 return GenerateTarget(&source_file, source_patch_value,
743 &copy_file, copy_patch_value,
744 source_filename, target_filename,
745 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800746}
Doug Zongker1c43c972012-02-28 11:07:09 -0800747
Tao Baoabba55b2015-07-17 18:11:12 -0700748/*
749 * This function flashes a given image to the target partition. It verifies
750 * the target cheksum first, and will return if target has the desired hash.
751 * It checks the checksum of the given source image before flashing, and
752 * verifies the target partition afterwards. The function is idempotent.
753 * Returns zero on success.
754 */
755int applypatch_flash(const char* source_filename, const char* target_filename,
756 const char* target_sha1_str, size_t target_size) {
757 printf("flash %s: ", target_filename);
758
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800759 uint8_t target_sha1[SHA_DIGEST_LENGTH];
Tao Baoabba55b2015-07-17 18:11:12 -0700760 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
761 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
762 return 1;
763 }
764
765 FileContents source_file;
Tao Baoabba55b2015-07-17 18:11:12 -0700766 std::string target_str(target_filename);
767
768 std::vector<std::string> pieces = android::base::Split(target_str, ":");
769 if (pieces.size() != 2 || (pieces[0] != "MTD" && pieces[0] != "EMMC")) {
770 printf("invalid target name \"%s\"", target_filename);
771 return 1;
772 }
773
774 // Load the target into the source_file object to see if already applied.
775 pieces.push_back(std::to_string(target_size));
776 pieces.push_back(target_sha1_str);
777 std::string fullname = android::base::Join(pieces, ':');
778 if (LoadPartitionContents(fullname.c_str(), &source_file) == 0 &&
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800779 memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) == 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700780 // The early-exit case: the image was already applied, this partition
781 // has the desired hash, nothing for us to do.
782 printf("already %s\n", short_sha1(target_sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700783 return 0;
784 }
785
786 if (LoadFileContents(source_filename, &source_file) == 0) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800787 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700788 // The source doesn't have desired checksum.
789 printf("source \"%s\" doesn't have expected sha1 sum\n", source_filename);
790 printf("expected: %s, found: %s\n", short_sha1(target_sha1).c_str(),
791 short_sha1(source_file.sha1).c_str());
Tao Baoabba55b2015-07-17 18:11:12 -0700792 return 1;
793 }
794 }
795
Yabin Cui1c522df2016-02-10 16:41:10 -0800796 if (WriteToPartition(source_file.data.data(), target_size, target_filename) != 0) {
Tao Baoabba55b2015-07-17 18:11:12 -0700797 printf("write of copied data to %s failed\n", target_filename);
Tao Baoabba55b2015-07-17 18:11:12 -0700798 return 1;
799 }
Tao Baoabba55b2015-07-17 18:11:12 -0700800 return 0;
Doug Zongker1c43c972012-02-28 11:07:09 -0800801}
802
803static int GenerateTarget(FileContents* source_file,
804 const Value* source_patch_value,
805 FileContents* copy_file,
806 const Value* copy_patch_value,
807 const char* source_filename,
808 const char* target_filename,
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800809 const uint8_t target_sha1[SHA_DIGEST_LENGTH],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700810 size_t target_size,
811 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800812 int retry = 1;
813 SHA_CTX ctx;
Yabin Cuid483c202016-02-03 17:08:52 -0800814 std::string memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800815 FileContents* source_to_use;
Doug Zongker1c43c972012-02-28 11:07:09 -0800816 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800817
Yabin Cuid483c202016-02-03 17:08:52 -0800818 bool target_is_partition = (strncmp(target_filename, "MTD:", 4) == 0 ||
Ethan Yonker34ae4832016-08-24 15:32:18 -0500819 strncmp(target_filename, "EMMC:", 5) == 0 ||
820 strncmp(target_filename, "BML:", 4) == 0);
Yabin Cuid483c202016-02-03 17:08:52 -0800821 const std::string tmp_target_filename = std::string(target_filename) + ".patch";
822
Doug Zongkerc4351c72010-02-22 14:46:32 -0800823 // assume that target_filename (eg "/system/app/Foo.apk") is located
824 // on the same filesystem as its top-level directory ("/system").
825 // We need something that exists for calling statfs().
Yabin Cuid483c202016-02-03 17:08:52 -0800826 std::string target_fs = target_filename;
827 auto slash_pos = target_fs.find('/', 1);
828 if (slash_pos != std::string::npos) {
829 target_fs.resize(slash_pos);
830 }
831
832 const Value* patch;
833 if (source_patch_value != NULL) {
834 source_to_use = source_file;
835 patch = source_patch_value;
Doug Zongker512536a2010-02-17 16:11:44 -0800836 } else {
Yabin Cuid483c202016-02-03 17:08:52 -0800837 source_to_use = copy_file;
838 patch = copy_patch_value;
839 }
840 if (patch->type != VAL_BLOB) {
841 printf("patch is not a blob\n");
842 return 1;
843 }
844 char* header = patch->data;
845 ssize_t header_bytes_read = patch->size;
846 bool use_bsdiff = false;
847 if (header_bytes_read >= 8 && memcmp(header, "BSDIFF40", 8) == 0) {
848 use_bsdiff = true;
849 } else if (header_bytes_read >= 8 && memcmp(header, "IMGDIFF2", 8) == 0) {
850 use_bsdiff = false;
851 } else {
852 printf("Unknown patch file format\n");
853 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800854 }
855
Doug Zongkerc4351c72010-02-22 14:46:32 -0800856 do {
857 // Is there enough room in the target filesystem to hold the patched
858 // file?
859
Yabin Cuid483c202016-02-03 17:08:52 -0800860 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700861 // If the target is a partition, we're actually going to
862 // write the output to /tmp and then copy it to the
863 // partition. statfs() always returns 0 blocks free for
864 // /tmp, so instead we'll just assume that /tmp has enough
865 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800866
Doug Zongkerf291d852010-07-07 13:55:25 -0700867 // We still write the original source to cache, in case
868 // the partition write is interrupted.
Yabin Cui1c522df2016-02-10 16:41:10 -0800869 if (MakeFreeSpaceOnCache(source_file->data.size()) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800870 printf("not enough free space on /cache\n");
871 return 1;
872 }
873 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
874 printf("failed to back up source file\n");
875 return 1;
876 }
877 made_copy = 1;
878 retry = 0;
879 } else {
880 int enough_space = 0;
881 if (retry > 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800882 size_t free_space = FreeSpaceForFile(target_fs.c_str());
Doug Zongker201cd462010-08-13 09:41:21 -0700883 enough_space =
884 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800885 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700886 if (!enough_space) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700887 printf("target %zu bytes; free space %zu bytes; retry %d; enough %d\n",
888 target_size, free_space, retry, enough_space);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700889 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800890 }
891
892 if (!enough_space) {
893 retry = 0;
894 }
895
896 if (!enough_space && source_patch_value != NULL) {
897 // Using the original source, but not enough free space. First
898 // copy the source file to cache, then delete it from the original
899 // location.
900
Doug Zongkerf291d852010-07-07 13:55:25 -0700901 if (strncmp(source_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000902 strncmp(source_filename, "EMMC:", 5) == 0 ||
903 strncmp(source_filename, "BML:", 4) == 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
Yabin Cui1c522df2016-02-10 16:41:10 -0800911 if (MakeFreeSpaceOnCache(source_file->data.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;
Ethan Yonker34ae4832016-08-24 15:32:18 -0500931
Yabin Cuid483c202016-02-03 17:08:52 -0800932 int output_fd = -1;
933 if (target_is_partition) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800934 // We store the decoded output in memory.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800935 sink = MemorySink;
Yabin Cuid483c202016-02-03 17:08:52 -0800936 token = &memory_sink_str;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800937 } else {
938 // We write the decoded output to "<tgt-file>.patch".
Yabin Cuica78c9f2016-02-05 15:27:52 -0800939 output_fd = ota_open(tmp_target_filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
Yabin Cuid483c202016-02-03 17:08:52 -0800940 S_IRUSR | S_IWUSR);
941 if (output_fd < 0) {
942 printf("failed to open output file %s: %s\n", tmp_target_filename.c_str(),
943 strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -0800944 return 1;
945 }
946 sink = FileSink;
Yabin Cuid483c202016-02-03 17:08:52 -0800947 token = &output_fd;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800948 }
949
Doug Zongkerc4351c72010-02-22 14:46:32 -0800950
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800951 SHA1_Init(&ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800952
953 int result;
Yabin Cuid483c202016-02-03 17:08:52 -0800954 if (use_bsdiff) {
Yabin Cui1c522df2016-02-10 16:41:10 -0800955 result = ApplyBSDiffPatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkerc4351c72010-02-22 14:46:32 -0800956 patch, 0, sink, token, &ctx);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800957 } else {
Yabin Cui1c522df2016-02-10 16:41:10 -0800958 result = ApplyImagePatch(source_to_use->data.data(), source_to_use->data.size(),
Doug Zongkerc4351c72010-02-22 14:46:32 -0800959 patch, sink, token, &ctx, bonus_data);
960 }
961
Yabin Cuid483c202016-02-03 17:08:52 -0800962 if (!target_is_partition) {
Yabin Cuica78c9f2016-02-05 15:27:52 -0800963 if (ota_fsync(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800964 printf("failed to fsync file \"%s\" (%s)\n", tmp_target_filename.c_str(),
965 strerror(errno));
Michael Rungecddb68b2014-10-29 12:42:15 -0700966 result = 1;
967 }
Yabin Cuica78c9f2016-02-05 15:27:52 -0800968 if (ota_close(output_fd) != 0) {
Yabin Cuid483c202016-02-03 17:08:52 -0800969 printf("failed to close file \"%s\" (%s)\n", tmp_target_filename.c_str(),
970 strerror(errno));
Michael Rungecddb68b2014-10-29 12:42:15 -0700971 result = 1;
972 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800973 }
974
975 if (result != 0) {
976 if (retry == 0) {
977 printf("applying patch failed\n");
978 return result != 0;
979 } else {
980 printf("applying patch failed; retrying\n");
981 }
Yabin Cuid483c202016-02-03 17:08:52 -0800982 if (!target_is_partition) {
983 unlink(tmp_target_filename.c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800984 }
985 } else {
986 // succeeded; no need to retry
987 break;
988 }
989 } while (retry-- > 0);
990
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800991 uint8_t current_target_sha1[SHA_DIGEST_LENGTH];
992 SHA1_Final(current_target_sha1, &ctx);
993 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_LENGTH) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800994 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800995 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -0700996 } else {
Tao Baoabba55b2015-07-17 18:11:12 -0700997 printf("now %s\n", short_sha1(target_sha1).c_str());
Doug Zongkerc4351c72010-02-22 14:46:32 -0800998 }
999
Yabin Cuid483c202016-02-03 17:08:52 -08001000 if (target_is_partition) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001001 // Copy the temp file to the partition.
Yabin Cuid483c202016-02-03 17:08:52 -08001002 if (WriteToPartition(reinterpret_cast<const unsigned char*>(memory_sink_str.c_str()),
1003 memory_sink_str.size(), target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001004 printf("write of patched data to %s failed\n", target_filename);
1005 return 1;
1006 }
Doug Zongker512536a2010-02-17 16:11:44 -08001007 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001008 // Give the .patch file the same owner, group, and mode of the
1009 // original source file.
Yabin Cuid483c202016-02-03 17:08:52 -08001010 if (chmod(tmp_target_filename.c_str(), source_to_use->st.st_mode) != 0) {
1011 printf("chmod of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001012 return 1;
1013 }
Yabin Cuid483c202016-02-03 17:08:52 -08001014 if (chown(tmp_target_filename.c_str(), source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
1015 printf("chown of \"%s\" failed: %s\n", tmp_target_filename.c_str(), strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001016 return 1;
1017 }
Doug Zongker512536a2010-02-17 16:11:44 -08001018
Doug Zongkerc4351c72010-02-22 14:46:32 -08001019 // Finally, rename the .patch file to replace the target file.
Yabin Cuid483c202016-02-03 17:08:52 -08001020 if (rename(tmp_target_filename.c_str(), target_filename) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001021 printf("rename of .patch to \"%s\" failed: %s\n", target_filename, strerror(errno));
Doug Zongkerc4351c72010-02-22 14:46:32 -08001022 return 1;
1023 }
Doug Zongker512536a2010-02-17 16:11:44 -08001024 }
1025
Doug Zongkerc4351c72010-02-22 14:46:32 -08001026 // If this run of applypatch created the copy, and we're here, we
1027 // can delete it.
Tao Baoba9a42a2015-06-23 23:23:33 -07001028 if (made_copy) {
1029 unlink(CACHE_TEMP_SOURCE);
1030 }
Doug Zongker512536a2010-02-17 16:11:44 -08001031
Doug Zongkerc4351c72010-02-22 14:46:32 -08001032 // Success!
1033 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001034}