blob: bc45e3c45db28f606ea4a580ac471c106967f7dd [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>
18#include <libgen.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <sys/stat.h>
23#include <sys/statfs.h>
24#include <sys/types.h>
25#include <fcntl.h>
26#include <unistd.h>
Doug Zongkera1bc1482014-02-13 15:18:19 -080027#include <stdbool.h>
Doug Zongker512536a2010-02-17 16:11:44 -080028
29#include "mincrypt/sha.h"
30#include "applypatch.h"
Conn O'Griofad9201042014-03-25 01:26:49 +000031#include "bmlutils/bmlutils.h"
Doug Zongker512536a2010-02-17 16:11:44 -080032#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080033#include "edify/expr.h"
Doug Zongker512536a2010-02-17 16:11:44 -080034
Doug Zongkerf291d852010-07-07 13:55:25 -070035static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070036static ssize_t FileSink(const unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080037static int GenerateTarget(FileContents* source_file,
38 const Value* source_patch_value,
39 FileContents* copy_file,
40 const Value* copy_patch_value,
41 const char* source_filename,
42 const char* target_filename,
43 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -070044 size_t target_size,
45 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080046
47static int mtd_partitions_scanned = 0;
48
Doug Zongkera1bc1482014-02-13 15:18:19 -080049// Read a file into memory; store the file contents and associated
Hristo Bojinovdb314d62010-08-02 10:29:49 -070050// metadata in *file.
51//
52// Return 0 on success.
Doug Zongkera1bc1482014-02-13 15:18:19 -080053int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongker512536a2010-02-17 16:11:44 -080054 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080055
Doug Zongkerf291d852010-07-07 13:55:25 -070056 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
57 // load the contents of a partition.
58 if (strncmp(filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +000059 strncmp(filename, "EMMC:", 5) == 0 ||
60 strncmp(filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -070061 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080062 }
Doug Zongker512536a2010-02-17 16:11:44 -080063
Doug Zongkerc4351c72010-02-22 14:46:32 -080064 if (stat(filename, &file->st) != 0) {
65 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
66 return -1;
67 }
68
69 file->size = file->st.st_size;
70 file->data = malloc(file->size);
71
72 FILE* f = fopen(filename, "rb");
73 if (f == NULL) {
74 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
75 free(file->data);
76 file->data = NULL;
77 return -1;
78 }
79
80 ssize_t bytes_read = fread(file->data, 1, file->size, f);
81 if (bytes_read != file->size) {
82 printf("short read of \"%s\" (%ld bytes of %ld)\n",
83 filename, (long)bytes_read, (long)file->size);
84 free(file->data);
85 file->data = NULL;
86 return -1;
87 }
88 fclose(f);
89
Doug Zongkerbac7fba2013-04-10 11:32:17 -070090 SHA_hash(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -080091 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080092}
93
94static size_t* size_array;
95// comparison function for qsort()ing an int array of indexes into
96// size_array[].
97static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -080098 int aa = *(int*)a;
99 int bb = *(int*)b;
100 if (size_array[aa] < size_array[bb]) {
101 return -1;
102 } else if (size_array[aa] > size_array[bb]) {
103 return 1;
104 } else {
105 return 0;
106 }
Doug Zongker512536a2010-02-17 16:11:44 -0800107}
108
Doug Zongkerf291d852010-07-07 13:55:25 -0700109// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800110// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700111// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
112// "EMMC:<partition_device>:..."). The smallest size_n bytes for
113// which that prefix of the partition contents has the corresponding
114// sha1 hash will be loaded. It is acceptable for a size value to be
115// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800116//
117// This complexity is needed because if an OTA installation is
118// interrupted, the partition might contain either the source or the
119// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700120// the length in order to read from a partition (there is no
121// "end-of-file" marker), so the caller must specify the possible
122// lengths and the hash of the data, and we'll do the load expecting
123// to find one of those hashes.
124enum PartitionType { MTD, EMMC };
125
126static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800127 char* copy = strdup(filename);
128 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700129
130 enum PartitionType type;
131
132 if (strcmp(magic, "MTD") == 0) {
133 type = MTD;
134 } else if (strcmp(magic, "EMMC") == 0) {
135 type = EMMC;
Conn O'Griofad9201042014-03-25 01:26:49 +0000136 } else if (strcmp(magic, "BML") == 0) {
137 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700138 } else {
139 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800140 filename);
141 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800142 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800143 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800144
Conn O'Griofad9201042014-03-25 01:26:49 +0000145 if (strcmp(magic, "BML") == 0) {
146 if (strcmp(partition, "boot") == 0) {
147 partition = BOARD_BML_BOOT;
148 } else if (strcmp(partition, "recovery") == 0) {
149 partition = BOARD_BML_RECOVERY;
150 }
151 }
152
Doug Zongkerc4351c72010-02-22 14:46:32 -0800153 int i;
154 int colons = 0;
155 for (i = 0; filename[i] != '\0'; ++i) {
156 if (filename[i] == ':') {
157 ++colons;
158 }
Doug Zongker512536a2010-02-17 16:11:44 -0800159 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800160 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700161 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800162 filename);
163 }
Doug Zongker512536a2010-02-17 16:11:44 -0800164
Doug Zongkerc4351c72010-02-22 14:46:32 -0800165 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
166 int* index = malloc(pairs * sizeof(int));
167 size_t* size = malloc(pairs * sizeof(size_t));
168 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800169
Doug Zongkerc4351c72010-02-22 14:46:32 -0800170 for (i = 0; i < pairs; ++i) {
171 const char* size_str = strtok(NULL, ":");
172 size[i] = strtol(size_str, NULL, 10);
173 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700174 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800175 return -1;
176 }
177 sha1sum[i] = strtok(NULL, ":");
178 index[i] = i;
179 }
Doug Zongker512536a2010-02-17 16:11:44 -0800180
Doug Zongkerc4351c72010-02-22 14:46:32 -0800181 // sort the index[] array so it indexes the pairs in order of
182 // increasing size.
183 size_array = size;
184 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800185
Doug Zongkerf291d852010-07-07 13:55:25 -0700186 MtdReadContext* ctx = NULL;
187 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800188
Doug Zongkerf291d852010-07-07 13:55:25 -0700189 switch (type) {
190 case MTD:
191 if (!mtd_partitions_scanned) {
192 mtd_scan_partitions();
193 mtd_partitions_scanned = 1;
194 }
Doug Zongker512536a2010-02-17 16:11:44 -0800195
Doug Zongkerf291d852010-07-07 13:55:25 -0700196 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
197 if (mtd == NULL) {
198 printf("mtd partition \"%s\" not found (loading %s)\n",
199 partition, filename);
200 return -1;
201 }
202
203 ctx = mtd_read_partition(mtd);
204 if (ctx == NULL) {
205 printf("failed to initialize read of mtd partition \"%s\"\n",
206 partition);
207 return -1;
208 }
209 break;
210
211 case EMMC:
212 dev = fopen(partition, "rb");
213 if (dev == NULL) {
214 printf("failed to open emmc partition \"%s\": %s\n",
215 partition, strerror(errno));
216 return -1;
217 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800218 }
Doug Zongker512536a2010-02-17 16:11:44 -0800219
Doug Zongkerc4351c72010-02-22 14:46:32 -0800220 SHA_CTX sha_ctx;
221 SHA_init(&sha_ctx);
222 uint8_t parsed_sha[SHA_DIGEST_SIZE];
223
224 // allocate enough memory to hold the largest size.
225 file->data = malloc(size[index[pairs-1]]);
226 char* p = (char*)file->data;
227 file->size = 0; // # bytes read so far
228
229 for (i = 0; i < pairs; ++i) {
230 // Read enough additional bytes to get us up to the next size
231 // (again, we're trying the possibilities in order of increasing
232 // size).
233 size_t next = size[index[i]] - file->size;
234 size_t read = 0;
235 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700236 switch (type) {
237 case MTD:
238 read = mtd_read_data(ctx, p, next);
239 break;
240
241 case EMMC:
242 read = fread(p, 1, next, dev);
243 break;
244 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800245 if (next != read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700246 printf("short read (%zu bytes of %zu) for partition \"%s\"\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800247 read, next, partition);
248 free(file->data);
249 file->data = NULL;
250 return -1;
251 }
252 SHA_update(&sha_ctx, p, read);
253 file->size += read;
254 }
255
256 // Duplicate the SHA context and finalize the duplicate so we can
257 // check it against this pair's expected hash.
258 SHA_CTX temp_ctx;
259 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
260 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
261
262 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
263 printf("failed to parse sha1 %s in %s\n",
264 sha1sum[index[i]], filename);
265 free(file->data);
266 file->data = NULL;
267 return -1;
268 }
269
270 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
271 // we have a match. stop reading the partition; we'll return
272 // the data we've read so far.
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700273 printf("partition read matched size %zu sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800274 size[index[i]], sha1sum[index[i]]);
275 break;
276 }
277
278 p += read;
279 }
280
Doug Zongkerf291d852010-07-07 13:55:25 -0700281 switch (type) {
282 case MTD:
283 mtd_read_close(ctx);
284 break;
285
286 case EMMC:
287 fclose(dev);
288 break;
289 }
290
Doug Zongkerc4351c72010-02-22 14:46:32 -0800291
292 if (i == pairs) {
293 // Ran off the end of the list of (size,sha1) pairs without
294 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700295 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800296 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800297 free(file->data);
298 file->data = NULL;
299 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800300 }
301
Doug Zongkerc4351c72010-02-22 14:46:32 -0800302 const uint8_t* sha_final = SHA_final(&sha_ctx);
303 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
304 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800305 }
306
Doug Zongkerc4351c72010-02-22 14:46:32 -0800307 // Fake some stat() info.
308 file->st.st_mode = 0644;
309 file->st.st_uid = 0;
310 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800311
Doug Zongkerc4351c72010-02-22 14:46:32 -0800312 free(copy);
313 free(index);
314 free(size);
315 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800316
Doug Zongkerc4351c72010-02-22 14:46:32 -0800317 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800318}
319
320
321// Save the contents of the given FileContents object under the given
322// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800323int SaveFileContents(const char* filename, const FileContents* file) {
Michael Rungecddb68b2014-10-29 12:42:15 -0700324 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800325 if (fd < 0) {
326 printf("failed to open \"%s\" for write: %s\n",
327 filename, strerror(errno));
328 return -1;
329 }
Doug Zongker512536a2010-02-17 16:11:44 -0800330
Doug Zongker1c43c972012-02-28 11:07:09 -0800331 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
332 if (bytes_written != file->size) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800333 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
Doug Zongker1c43c972012-02-28 11:07:09 -0800334 filename, (long)bytes_written, (long)file->size,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800335 strerror(errno));
336 close(fd);
337 return -1;
338 }
Michael Rungecddb68b2014-10-29 12:42:15 -0700339 if (fsync(fd) != 0) {
340 printf("fsync of \"%s\" failed: %s\n", filename, strerror(errno));
341 return -1;
342 }
343 if (close(fd) != 0) {
344 printf("close of \"%s\" failed: %s\n", filename, strerror(errno));
345 return -1;
346 }
Doug Zongker512536a2010-02-17 16:11:44 -0800347
Doug Zongker1c43c972012-02-28 11:07:09 -0800348 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800349 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
350 return -1;
351 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800352 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800353 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
354 return -1;
355 }
Doug Zongker512536a2010-02-17 16:11:44 -0800356
Doug Zongkerc4351c72010-02-22 14:46:32 -0800357 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800358}
359
Doug Zongkerf291d852010-07-07 13:55:25 -0700360// Write a memory buffer to 'target' partition, a string of the form
361// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
362// success.
363int WriteToPartition(unsigned char* data, size_t len,
364 const char* target) {
365 char* copy = strdup(target);
366 const char* magic = strtok(copy, ":");
367
368 enum PartitionType type;
369 if (strcmp(magic, "MTD") == 0) {
370 type = MTD;
371 } else if (strcmp(magic, "EMMC") == 0) {
372 type = EMMC;
Conn O'Griofad9201042014-03-25 01:26:49 +0000373 } else if (strcmp(magic, "BML") == 0) {
374 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700375 } else {
376 printf("WriteToPartition called with bad target (%s)\n", target);
377 return -1;
378 }
379 const char* partition = strtok(NULL, ":");
380
Conn O'Griofad9201042014-03-25 01:26:49 +0000381 if (strcmp(magic, "BML") == 0) {
382 if (strcmp(partition, "boot") == 0) {
383 partition = BOARD_BML_BOOT;
384 } else if (strcmp(partition, "recovery") == 0) {
385 partition = BOARD_BML_RECOVERY;
386 }
387
388 int bmlpartition = open(partition, O_RDWR | O_LARGEFILE);
389 if (bmlpartition < 0)
390 return -1;
391 if (ioctl(bmlpartition, BML_UNLOCK_ALL, 0)) {
392 printf("failed to unlock BML partition: (%s)\n", partition);
393 return -1;
394 }
395 close(bmlpartition);
396 }
397
Doug Zongkerc4351c72010-02-22 14:46:32 -0800398 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700399 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800400 return -1;
401 }
Doug Zongker512536a2010-02-17 16:11:44 -0800402
Doug Zongkerf291d852010-07-07 13:55:25 -0700403 switch (type) {
404 case MTD:
405 if (!mtd_partitions_scanned) {
406 mtd_scan_partitions();
407 mtd_partitions_scanned = 1;
408 }
409
410 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
411 if (mtd == NULL) {
412 printf("mtd partition \"%s\" not found for writing\n",
413 partition);
414 return -1;
415 }
416
417 MtdWriteContext* ctx = mtd_write_partition(mtd);
418 if (ctx == NULL) {
419 printf("failed to init mtd partition \"%s\" for writing\n",
420 partition);
421 return -1;
422 }
423
424 size_t written = mtd_write_data(ctx, (char*)data, len);
425 if (written != len) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700426 printf("only wrote %zu of %zu bytes to MTD %s\n",
Doug Zongkerf291d852010-07-07 13:55:25 -0700427 written, len, partition);
428 mtd_write_close(ctx);
429 return -1;
430 }
431
432 if (mtd_erase_blocks(ctx, -1) < 0) {
433 printf("error finishing mtd write of %s\n", partition);
434 mtd_write_close(ctx);
435 return -1;
436 }
437
438 if (mtd_write_close(ctx)) {
439 printf("error closing mtd write of %s\n", partition);
440 return -1;
441 }
442 break;
443
444 case EMMC:
Doug Zongker044a0b42013-07-08 09:42:54 -0700445 {
446 size_t start = 0;
447 int success = 0;
Doug Zongker901b8982013-07-11 12:31:25 -0700448 int fd = open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700449 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700450 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700451 return -1;
452 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700453 int attempt;
454
Doug Zongker168724c2013-12-19 15:16:57 -0800455 for (attempt = 0; attempt < 2; ++attempt) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700456 if (TEMP_FAILURE_RETRY(lseek(fd, start, SEEK_SET)) == -1) {
457 printf("failed seek on %s: %s\n",
458 partition, strerror(errno));
459 return -1;
460 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700461 while (start < len) {
462 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800463 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700464
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700465 ssize_t written = TEMP_FAILURE_RETRY(write(fd, data+start, to_write));
466 if (written == -1) {
467 printf("failed write writing to %s: %s\n", partition, strerror(errno));
468 return -1;
Doug Zongker044a0b42013-07-08 09:42:54 -0700469 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700470 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700471 }
Michael Rungecddb68b2014-10-29 12:42:15 -0700472 if (fsync(fd) != 0) {
473 printf("failed to sync to %s (%s)\n",
474 partition, strerror(errno));
475 return -1;
476 }
477 if (close(fd) != 0) {
478 printf("failed to close %s (%s)\n",
479 partition, strerror(errno));
480 return -1;
481 }
482 fd = open(partition, O_RDONLY);
483 if (fd < 0) {
484 printf("failed to reopen %s for verify (%s)\n",
485 partition, strerror(errno));
486 return -1;
487 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700488
489 // drop caches so our subsequent verification read
490 // won't just be reading the cache.
491 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700492 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700493 if (TEMP_FAILURE_RETRY(write(dc, "3\n", 2)) == -1) {
494 printf("write to /proc/sys/vm/drop_caches failed: %s\n", strerror(errno));
495 } else {
496 printf(" caches dropped\n");
497 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700498 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700499 sleep(1);
Doug Zongker044a0b42013-07-08 09:42:54 -0700500
501 // verify
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700502 if (TEMP_FAILURE_RETRY(lseek(fd, 0, SEEK_SET)) == -1) {
503 printf("failed to seek back to beginning of %s: %s\n",
504 partition, strerror(errno));
505 return -1;
506 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700507 unsigned char buffer[4096];
508 start = len;
509 size_t p;
510 for (p = 0; p < len; p += sizeof(buffer)) {
511 size_t to_read = len - p;
512 if (to_read > sizeof(buffer)) to_read = sizeof(buffer);
513
Doug Zongkerc870a992013-07-09 10:34:46 -0700514 size_t so_far = 0;
515 while (so_far < to_read) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700516 ssize_t read_count =
517 TEMP_FAILURE_RETRY(read(fd, buffer+so_far, to_read-so_far));
518 if (read_count == -1) {
519 printf("verify read error %s at %zu: %s\n",
520 partition, p, strerror(errno));
521 return -1;
Doug Zongkerc870a992013-07-09 10:34:46 -0700522 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700523 if ((size_t)read_count < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700524 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700525 partition, p, read_count, to_read, strerror(errno));
526 }
527 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700528 }
529
530 if (memcmp(buffer, data+p, to_read)) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700531 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700532 start = p;
533 break;
534 }
535 }
536
537 if (start == len) {
538 printf("verification read succeeded (attempt %d)\n", attempt+1);
539 success = true;
540 break;
541 }
542 }
543
544 if (!success) {
545 printf("failed to verify after all attempts\n");
546 return -1;
547 }
548
Doug Zongkerc870a992013-07-09 10:34:46 -0700549 if (close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700550 printf("error closing %s (%s)\n", partition, strerror(errno));
551 return -1;
552 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700553 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700554 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700555 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800556 }
Doug Zongker512536a2010-02-17 16:11:44 -0800557
Doug Zongkerf291d852010-07-07 13:55:25 -0700558 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800559 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800560}
561
562
563// Take a string 'str' of 40 hex digits and parse it into the 20
564// byte array 'digest'. 'str' may contain only the digest or be of
565// the form "<digest>:<anything>". Return 0 on success, -1 on any
566// error.
567int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568 int i;
569 const char* ps = str;
570 uint8_t* pd = digest;
571 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
572 int digit;
573 if (*ps >= '0' && *ps <= '9') {
574 digit = *ps - '0';
575 } else if (*ps >= 'a' && *ps <= 'f') {
576 digit = *ps - 'a' + 10;
577 } else if (*ps >= 'A' && *ps <= 'F') {
578 digit = *ps - 'A' + 10;
579 } else {
580 return -1;
581 }
582 if (i % 2 == 0) {
583 *pd = digit << 4;
584 } else {
585 *pd |= digit;
586 ++pd;
587 }
Doug Zongker512536a2010-02-17 16:11:44 -0800588 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800589 if (*ps != '\0') return -1;
590 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800591}
592
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593// Search an array of sha1 strings for one matching the given sha1.
594// Return the index of the match on success, or -1 if no match is
595// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700596int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800597 int num_patches) {
598 int i;
599 uint8_t patch_sha1[SHA_DIGEST_SIZE];
600 for (i = 0; i < num_patches; ++i) {
601 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
602 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
603 return i;
604 }
Doug Zongker512536a2010-02-17 16:11:44 -0800605 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800606 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800607}
608
609// Returns 0 if the contents of the file (argv[2]) or the cached file
610// match any of the sha1's on the command line (argv[3:]). Returns
611// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800612int applypatch_check(const char* filename,
613 int num_patches, char** const patch_sha1_str) {
614 FileContents file;
615 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800616
Doug Zongkerc4351c72010-02-22 14:46:32 -0800617 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700618 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619 // partitions, where the filename encodes the sha1s; no need to
620 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800621 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800622 (num_patches > 0 &&
623 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
624 printf("file \"%s\" doesn't have any of expected "
625 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800626
Doug Zongkerc4351c72010-02-22 14:46:32 -0800627 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800628 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800629
Doug Zongkerc4351c72010-02-22 14:46:32 -0800630 // If the source file is missing or corrupted, it might be because
631 // we were killed in the middle of patching it. A copy of it
632 // should have been made in CACHE_TEMP_SOURCE. If that file
633 // exists and matches the sha1 we're looking for, the check still
634 // passes.
635
Doug Zongkera1bc1482014-02-13 15:18:19 -0800636 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800637 printf("failed to load cache file\n");
638 return 1;
639 }
640
641 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
642 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
643 free(file.data);
644 return 1;
645 }
646 }
Doug Zongker512536a2010-02-17 16:11:44 -0800647
648 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800649 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800650}
651
652int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800653 ShowBSDiffLicense();
654 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800655}
656
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700657ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800658 int fd = *(int *)token;
659 ssize_t done = 0;
660 ssize_t wrote;
661 while (done < (ssize_t) len) {
Elliott Hughes2f5feed2015-04-28 17:24:24 -0700662 wrote = TEMP_FAILURE_RETRY(write(fd, data+done, len-done));
663 if (wrote == -1) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800664 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
665 return done;
666 }
667 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800668 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800669 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800670}
671
672typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800673 unsigned char* buffer;
674 ssize_t size;
675 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800676} MemorySinkInfo;
677
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700678ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800679 MemorySinkInfo* msi = (MemorySinkInfo*)token;
680 if (msi->size - msi->pos < len) {
681 return -1;
682 }
683 memcpy(msi->buffer + msi->pos, data, len);
684 msi->pos += len;
685 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800686}
687
688// Return the amount of free space (in bytes) on the filesystem
689// containing filename. filename must exist. Return -1 on error.
690size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800691 struct statfs sf;
692 if (statfs(filename, &sf) != 0) {
693 printf("failed to statfs %s: %s\n", filename, strerror(errno));
694 return -1;
695 }
caozhiyuancb9450e2015-05-19 17:21:00 +0800696 return sf.f_bsize * sf.f_bavail;
Doug Zongker512536a2010-02-17 16:11:44 -0800697}
698
Doug Zongkerc4351c72010-02-22 14:46:32 -0800699int CacheSizeCheck(size_t bytes) {
700 if (MakeFreeSpaceOnCache(bytes) < 0) {
701 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
702 return 1;
703 } else {
704 return 0;
705 }
706}
707
Doug Zongkerbf80f492012-10-19 12:24:26 -0700708static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
709 int i;
710 const char* hex = "0123456789abcdef";
711 for (i = 0; i < 4; ++i) {
712 putchar(hex[(sha1[i]>>4) & 0xf]);
713 putchar(hex[sha1[i] & 0xf]);
714 }
715}
Doug Zongkerc4351c72010-02-22 14:46:32 -0800716
717// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800718// (the original file is not touched until we have the desired
719// replacement for it) and idempotent (it's okay to run this program
720// multiple times).
721//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800722// - if the sha1 hash of <target_filename> is <target_sha1_string>,
723// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800724//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800725// - otherwise, if the sha1 hash of <source_filename> is one of the
726// entries in <patch_sha1_str>, the corresponding patch from
727// <patch_data> (which must be a VAL_BLOB) is applied to produce a
728// new file (the type of patch is automatically detected from the
729// blob daat). If that new file has sha1 hash <target_sha1_str>,
730// moves it to replace <target_filename>, and exits successfully.
731// Note that if <source_filename> and <target_filename> are not the
732// same, <source_filename> is NOT deleted on success.
733// <target_filename> may be the string "-" to mean "the same as
734// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800735//
736// - otherwise, or if any error is encountered, exits with non-zero
737// status.
738//
Doug Zongkerf291d852010-07-07 13:55:25 -0700739// <source_filename> may refer to a partition to read the source data.
740// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800741// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800742
Doug Zongkerc4351c72010-02-22 14:46:32 -0800743int applypatch(const char* source_filename,
744 const char* target_filename,
745 const char* target_sha1_str,
746 size_t target_size,
747 int num_patches,
748 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700749 Value** patch_data,
750 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700751 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800752
Doug Zongkerc4351c72010-02-22 14:46:32 -0800753 if (target_filename[0] == '-' &&
754 target_filename[1] == '\0') {
755 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800756 }
757
Doug Zongkerc4351c72010-02-22 14:46:32 -0800758 uint8_t target_sha1[SHA_DIGEST_SIZE];
759 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
760 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800761 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800762 }
Doug Zongker512536a2010-02-17 16:11:44 -0800763
Doug Zongkerc4351c72010-02-22 14:46:32 -0800764 FileContents copy_file;
765 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800766 copy_file.data = NULL;
767 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800768 const Value* source_patch_value = NULL;
769 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800770
Doug Zongkerc4351c72010-02-22 14:46:32 -0800771 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800772 if (LoadFileContents(target_filename, &source_file) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800773 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
774 // The early-exit case: the patch was already applied, this file
775 // has the desired hash, nothing for us to do.
Doug Zongkerbf80f492012-10-19 12:24:26 -0700776 printf("already ");
777 print_short_sha1(target_sha1);
778 putchar('\n');
Doug Zongker1c43c972012-02-28 11:07:09 -0800779 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800780 return 0;
781 }
782 }
Doug Zongker512536a2010-02-17 16:11:44 -0800783
Doug Zongkerc4351c72010-02-22 14:46:32 -0800784 if (source_file.data == NULL ||
785 (target_filename != source_filename &&
786 strcmp(target_filename, source_filename) != 0)) {
787 // Need to load the source file: either we failed to load the
788 // target file, or we did but it's different from the source file.
789 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800790 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800791 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800792 }
793
794 if (source_file.data != NULL) {
795 int to_use = FindMatchingPatch(source_file.sha1,
796 patch_sha1_str, num_patches);
797 if (to_use >= 0) {
798 source_patch_value = patch_data[to_use];
799 }
800 }
801
802 if (source_patch_value == NULL) {
803 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800804 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800805 printf("source file is bad; trying copy\n");
806
Doug Zongkera1bc1482014-02-13 15:18:19 -0800807 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800808 // fail.
809 printf("failed to read copy file\n");
810 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800811 }
812
Doug Zongkerc4351c72010-02-22 14:46:32 -0800813 int to_use = FindMatchingPatch(copy_file.sha1,
814 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700815 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800816 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800817 }
818
Doug Zongkerc4351c72010-02-22 14:46:32 -0800819 if (copy_patch_value == NULL) {
820 // fail.
821 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800822 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800823 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800824 }
Doug Zongker512536a2010-02-17 16:11:44 -0800825 }
826
Doug Zongker1c43c972012-02-28 11:07:09 -0800827 int result = GenerateTarget(&source_file, source_patch_value,
828 &copy_file, copy_patch_value,
829 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700830 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800831 free(source_file.data);
832 free(copy_file.data);
833
834 return result;
835}
836
837static int GenerateTarget(FileContents* source_file,
838 const Value* source_patch_value,
839 FileContents* copy_file,
840 const Value* copy_patch_value,
841 const char* source_filename,
842 const char* target_filename,
843 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700844 size_t target_size,
845 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800846 int retry = 1;
847 SHA_CTX ctx;
848 int output;
849 MemorySinkInfo msi;
850 FileContents* source_to_use;
851 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800852 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800853
854 // assume that target_filename (eg "/system/app/Foo.apk") is located
855 // on the same filesystem as its top-level directory ("/system").
856 // We need something that exists for calling statfs().
857 char target_fs[strlen(target_filename)+1];
858 char* slash = strchr(target_filename+1, '/');
859 if (slash != NULL) {
860 int count = slash - target_filename;
861 strncpy(target_fs, target_filename, count);
862 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800863 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800864 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800865 }
866
Doug Zongkerc4351c72010-02-22 14:46:32 -0800867 do {
868 // Is there enough room in the target filesystem to hold the patched
869 // file?
870
Doug Zongkerf291d852010-07-07 13:55:25 -0700871 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000872 strncmp(target_filename, "EMMC:", 5) == 0 ||
873 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700874 // If the target is a partition, we're actually going to
875 // write the output to /tmp and then copy it to the
876 // partition. statfs() always returns 0 blocks free for
877 // /tmp, so instead we'll just assume that /tmp has enough
878 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800879
Doug Zongkerf291d852010-07-07 13:55:25 -0700880 // We still write the original source to cache, in case
881 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800882 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800883 printf("not enough free space on /cache\n");
884 return 1;
885 }
886 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
887 printf("failed to back up source file\n");
888 return 1;
889 }
890 made_copy = 1;
891 retry = 0;
892 } else {
893 int enough_space = 0;
894 if (retry > 0) {
895 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700896 enough_space =
897 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800898 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700899 if (!enough_space) {
900 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
901 (long)target_size, (long)free_space, retry, enough_space);
902 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800903 }
904
905 if (!enough_space) {
906 retry = 0;
907 }
908
909 if (!enough_space && source_patch_value != NULL) {
910 // Using the original source, but not enough free space. First
911 // copy the source file to cache, then delete it from the original
912 // location.
913
Doug Zongkerf291d852010-07-07 13:55:25 -0700914 if (strncmp(source_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000915 strncmp(source_filename, "EMMC:", 5) == 0 ||
916 strncmp(source_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800917 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700918 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800919 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700920 printf("not enough free space for target but source "
921 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800922 return 1;
923 }
924
Doug Zongker1c43c972012-02-28 11:07:09 -0800925 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800926 printf("not enough free space on /cache\n");
927 return 1;
928 }
929
930 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
931 printf("failed to back up source file\n");
932 return 1;
933 }
934 made_copy = 1;
935 unlink(source_filename);
936
937 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700938 printf("(now %ld bytes free for target) ", (long)free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800939 }
940 }
941
942 const Value* patch;
943 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800944 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800945 patch = source_patch_value;
946 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800947 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800948 patch = copy_patch_value;
949 }
950
951 if (patch->type != VAL_BLOB) {
952 printf("patch is not a blob\n");
953 return 1;
954 }
955
956 SinkFn sink = NULL;
957 void* token = NULL;
958 output = -1;
959 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700960 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000961 strncmp(target_filename, "EMMC:", 5) == 0 ||
962 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800963 // We store the decoded output in memory.
964 msi.buffer = malloc(target_size);
965 if (msi.buffer == NULL) {
966 printf("failed to alloc %ld bytes for output\n",
967 (long)target_size);
968 return 1;
969 }
970 msi.pos = 0;
971 msi.size = target_size;
972 sink = MemorySink;
973 token = &msi;
974 } else {
975 // We write the decoded output to "<tgt-file>.patch".
976 outname = (char*)malloc(strlen(target_filename) + 10);
977 strcpy(outname, target_filename);
978 strcat(outname, ".patch");
979
Michael Rungecddb68b2014-10-29 12:42:15 -0700980 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
981 S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800982 if (output < 0) {
983 printf("failed to open output file %s: %s\n",
984 outname, strerror(errno));
985 return 1;
986 }
987 sink = FileSink;
988 token = &output;
989 }
990
991 char* header = patch->data;
992 ssize_t header_bytes_read = patch->size;
993
994 SHA_init(&ctx);
995
996 int result;
997
998 if (header_bytes_read >= 8 &&
999 memcmp(header, "BSDIFF40", 8) == 0) {
1000 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
1001 patch, 0, sink, token, &ctx);
1002 } else if (header_bytes_read >= 8 &&
1003 memcmp(header, "IMGDIFF2", 8) == 0) {
1004 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -07001005 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -08001006 } else {
1007 printf("Unknown patch file format\n");
1008 return 1;
1009 }
1010
1011 if (output >= 0) {
Michael Rungecddb68b2014-10-29 12:42:15 -07001012 if (fsync(output) != 0) {
1013 printf("failed to fsync file \"%s\" (%s)\n", outname, strerror(errno));
1014 result = 1;
1015 }
1016 if (close(output) != 0) {
1017 printf("failed to close file \"%s\" (%s)\n", outname, strerror(errno));
1018 result = 1;
1019 }
Doug Zongkerc4351c72010-02-22 14:46:32 -08001020 }
1021
1022 if (result != 0) {
1023 if (retry == 0) {
1024 printf("applying patch failed\n");
1025 return result != 0;
1026 } else {
1027 printf("applying patch failed; retrying\n");
1028 }
1029 if (outname != NULL) {
1030 unlink(outname);
1031 }
1032 } else {
1033 // succeeded; no need to retry
1034 break;
1035 }
1036 } while (retry-- > 0);
1037
1038 const uint8_t* current_target_sha1 = SHA_final(&ctx);
1039 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
1040 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -08001041 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -07001042 } else {
1043 printf("now ");
1044 print_short_sha1(target_sha1);
1045 putchar('\n');
Doug Zongkerc4351c72010-02-22 14:46:32 -08001046 }
1047
1048 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001049 // Copy the temp file to the partition.
1050 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001051 printf("write of patched data to %s failed\n", target_filename);
1052 return 1;
1053 }
1054 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -08001055 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001056 // Give the .patch file the same owner, group, and mode of the
1057 // original source file.
1058 if (chmod(outname, source_to_use->st.st_mode) != 0) {
1059 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
1060 return 1;
1061 }
1062 if (chown(outname, source_to_use->st.st_uid,
1063 source_to_use->st.st_gid) != 0) {
1064 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
1065 return 1;
1066 }
Doug Zongker512536a2010-02-17 16:11:44 -08001067
Doug Zongkerc4351c72010-02-22 14:46:32 -08001068 // Finally, rename the .patch file to replace the target file.
1069 if (rename(outname, target_filename) != 0) {
1070 printf("rename of .patch to \"%s\" failed: %s\n",
1071 target_filename, strerror(errno));
1072 return 1;
1073 }
Doug Zongker512536a2010-02-17 16:11:44 -08001074 }
1075
Doug Zongkerc4351c72010-02-22 14:46:32 -08001076 // If this run of applypatch created the copy, and we're here, we
1077 // can delete it.
1078 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -08001079
Doug Zongkerc4351c72010-02-22 14:46:32 -08001080 // Success!
1081 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001082}