blob: 73195d96a908b90a87757de7bb00571aa2faab5c [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) {
Doug Zongkerc870a992013-07-09 10:34:46 -0700456 lseek(fd, start, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700457 while (start < len) {
458 size_t to_write = len - start;
Doug Zongker168724c2013-12-19 15:16:57 -0800459 if (to_write > 1<<20) to_write = 1<<20;
Doug Zongker044a0b42013-07-08 09:42:54 -0700460
Doug Zongkerc870a992013-07-09 10:34:46 -0700461 ssize_t written = write(fd, data+start, to_write);
462 if (written < 0) {
463 if (errno == EINTR) {
464 written = 0;
465 } else {
466 printf("failed write writing to %s (%s)\n",
467 partition, strerror(errno));
468 return -1;
469 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700470 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700471 start += written;
Doug Zongker044a0b42013-07-08 09:42:54 -0700472 }
Michael Rungecddb68b2014-10-29 12:42:15 -0700473 if (fsync(fd) != 0) {
474 printf("failed to sync to %s (%s)\n",
475 partition, strerror(errno));
476 return -1;
477 }
478 if (close(fd) != 0) {
479 printf("failed to close %s (%s)\n",
480 partition, strerror(errno));
481 return -1;
482 }
483 fd = open(partition, O_RDONLY);
484 if (fd < 0) {
485 printf("failed to reopen %s for verify (%s)\n",
486 partition, strerror(errno));
487 return -1;
488 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700489
490 // drop caches so our subsequent verification read
491 // won't just be reading the cache.
492 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700493 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
494 write(dc, "3\n", 2);
495 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700496 sleep(1);
497 printf(" caches dropped\n");
498
499 // verify
Doug Zongkerc870a992013-07-09 10:34:46 -0700500 lseek(fd, 0, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700501 unsigned char buffer[4096];
502 start = len;
503 size_t p;
504 for (p = 0; p < len; p += sizeof(buffer)) {
505 size_t to_read = len - p;
506 if (to_read > sizeof(buffer)) to_read = sizeof(buffer);
507
Doug Zongkerc870a992013-07-09 10:34:46 -0700508 size_t so_far = 0;
509 while (so_far < to_read) {
510 ssize_t read_count = read(fd, buffer+so_far, to_read-so_far);
511 if (read_count < 0) {
512 if (errno == EINTR) {
513 read_count = 0;
514 } else {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700515 printf("verify read error %s at %zu: %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700516 partition, p, strerror(errno));
517 return -1;
518 }
519 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700520 if ((size_t)read_count < to_read) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700521 printf("short verify read %s at %zu: %zd %zu %s\n",
Doug Zongkerc870a992013-07-09 10:34:46 -0700522 partition, p, read_count, to_read, strerror(errno));
523 }
524 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700525 }
526
527 if (memcmp(buffer, data+p, to_read)) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700528 printf("verification failed starting at %zu\n", p);
Doug Zongker044a0b42013-07-08 09:42:54 -0700529 start = p;
530 break;
531 }
532 }
533
534 if (start == len) {
535 printf("verification read succeeded (attempt %d)\n", attempt+1);
536 success = true;
537 break;
538 }
539 }
540
541 if (!success) {
542 printf("failed to verify after all attempts\n");
543 return -1;
544 }
545
Doug Zongkerc870a992013-07-09 10:34:46 -0700546 if (close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700547 printf("error closing %s (%s)\n", partition, strerror(errno));
548 return -1;
549 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700550 sync();
Doug Zongkerf291d852010-07-07 13:55:25 -0700551 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700552 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800553 }
Doug Zongker512536a2010-02-17 16:11:44 -0800554
Doug Zongkerf291d852010-07-07 13:55:25 -0700555 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800556 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800557}
558
559
560// Take a string 'str' of 40 hex digits and parse it into the 20
561// byte array 'digest'. 'str' may contain only the digest or be of
562// the form "<digest>:<anything>". Return 0 on success, -1 on any
563// error.
564int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800565 int i;
566 const char* ps = str;
567 uint8_t* pd = digest;
568 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
569 int digit;
570 if (*ps >= '0' && *ps <= '9') {
571 digit = *ps - '0';
572 } else if (*ps >= 'a' && *ps <= 'f') {
573 digit = *ps - 'a' + 10;
574 } else if (*ps >= 'A' && *ps <= 'F') {
575 digit = *ps - 'A' + 10;
576 } else {
577 return -1;
578 }
579 if (i % 2 == 0) {
580 *pd = digit << 4;
581 } else {
582 *pd |= digit;
583 ++pd;
584 }
Doug Zongker512536a2010-02-17 16:11:44 -0800585 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800586 if (*ps != '\0') return -1;
587 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800588}
589
Doug Zongkerc4351c72010-02-22 14:46:32 -0800590// Search an array of sha1 strings for one matching the given sha1.
591// Return the index of the match on success, or -1 if no match is
592// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700593int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800594 int num_patches) {
595 int i;
596 uint8_t patch_sha1[SHA_DIGEST_SIZE];
597 for (i = 0; i < num_patches; ++i) {
598 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
599 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
600 return i;
601 }
Doug Zongker512536a2010-02-17 16:11:44 -0800602 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800603 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800604}
605
606// Returns 0 if the contents of the file (argv[2]) or the cached file
607// match any of the sha1's on the command line (argv[3:]). Returns
608// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800609int applypatch_check(const char* filename,
610 int num_patches, char** const patch_sha1_str) {
611 FileContents file;
612 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800613
Doug Zongkerc4351c72010-02-22 14:46:32 -0800614 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700615 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800616 // partitions, where the filename encodes the sha1s; no need to
617 // check them twice.)
Doug Zongkera1bc1482014-02-13 15:18:19 -0800618 if (LoadFileContents(filename, &file) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619 (num_patches > 0 &&
620 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
621 printf("file \"%s\" doesn't have any of expected "
622 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800623
Doug Zongkerc4351c72010-02-22 14:46:32 -0800624 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800625 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800626
Doug Zongkerc4351c72010-02-22 14:46:32 -0800627 // If the source file is missing or corrupted, it might be because
628 // we were killed in the middle of patching it. A copy of it
629 // should have been made in CACHE_TEMP_SOURCE. If that file
630 // exists and matches the sha1 we're looking for, the check still
631 // passes.
632
Doug Zongkera1bc1482014-02-13 15:18:19 -0800633 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800634 printf("failed to load cache file\n");
635 return 1;
636 }
637
638 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
639 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
640 free(file.data);
641 return 1;
642 }
643 }
Doug Zongker512536a2010-02-17 16:11:44 -0800644
645 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800646 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800647}
648
649int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800650 ShowBSDiffLicense();
651 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800652}
653
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700654ssize_t FileSink(const unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800655 int fd = *(int *)token;
656 ssize_t done = 0;
657 ssize_t wrote;
658 while (done < (ssize_t) len) {
659 wrote = write(fd, data+done, len-done);
660 if (wrote <= 0) {
661 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
662 return done;
663 }
664 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800665 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800666 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800667}
668
669typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800670 unsigned char* buffer;
671 ssize_t size;
672 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800673} MemorySinkInfo;
674
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700675ssize_t MemorySink(const unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800676 MemorySinkInfo* msi = (MemorySinkInfo*)token;
677 if (msi->size - msi->pos < len) {
678 return -1;
679 }
680 memcpy(msi->buffer + msi->pos, data, len);
681 msi->pos += len;
682 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800683}
684
685// Return the amount of free space (in bytes) on the filesystem
686// containing filename. filename must exist. Return -1 on error.
687size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800688 struct statfs sf;
689 if (statfs(filename, &sf) != 0) {
690 printf("failed to statfs %s: %s\n", filename, strerror(errno));
691 return -1;
692 }
693 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800694}
695
Doug Zongkerc4351c72010-02-22 14:46:32 -0800696int CacheSizeCheck(size_t bytes) {
697 if (MakeFreeSpaceOnCache(bytes) < 0) {
698 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
699 return 1;
700 } else {
701 return 0;
702 }
703}
704
Doug Zongkerbf80f492012-10-19 12:24:26 -0700705static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
706 int i;
707 const char* hex = "0123456789abcdef";
708 for (i = 0; i < 4; ++i) {
709 putchar(hex[(sha1[i]>>4) & 0xf]);
710 putchar(hex[sha1[i] & 0xf]);
711 }
712}
Doug Zongkerc4351c72010-02-22 14:46:32 -0800713
714// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800715// (the original file is not touched until we have the desired
716// replacement for it) and idempotent (it's okay to run this program
717// multiple times).
718//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800719// - if the sha1 hash of <target_filename> is <target_sha1_string>,
720// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800721//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800722// - otherwise, if the sha1 hash of <source_filename> is one of the
723// entries in <patch_sha1_str>, the corresponding patch from
724// <patch_data> (which must be a VAL_BLOB) is applied to produce a
725// new file (the type of patch is automatically detected from the
726// blob daat). If that new file has sha1 hash <target_sha1_str>,
727// moves it to replace <target_filename>, and exits successfully.
728// Note that if <source_filename> and <target_filename> are not the
729// same, <source_filename> is NOT deleted on success.
730// <target_filename> may be the string "-" to mean "the same as
731// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800732//
733// - otherwise, or if any error is encountered, exits with non-zero
734// status.
735//
Doug Zongkerf291d852010-07-07 13:55:25 -0700736// <source_filename> may refer to a partition to read the source data.
737// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800738// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800739
Doug Zongkerc4351c72010-02-22 14:46:32 -0800740int applypatch(const char* source_filename,
741 const char* target_filename,
742 const char* target_sha1_str,
743 size_t target_size,
744 int num_patches,
745 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700746 Value** patch_data,
747 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700748 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800749
Doug Zongkerc4351c72010-02-22 14:46:32 -0800750 if (target_filename[0] == '-' &&
751 target_filename[1] == '\0') {
752 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800753 }
754
Doug Zongkerc4351c72010-02-22 14:46:32 -0800755 uint8_t target_sha1[SHA_DIGEST_SIZE];
756 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
757 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800758 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800759 }
Doug Zongker512536a2010-02-17 16:11:44 -0800760
Doug Zongkerc4351c72010-02-22 14:46:32 -0800761 FileContents copy_file;
762 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800763 copy_file.data = NULL;
764 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800765 const Value* source_patch_value = NULL;
766 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800767
Doug Zongkerc4351c72010-02-22 14:46:32 -0800768 // We try to load the target file into the source_file object.
Doug Zongkera1bc1482014-02-13 15:18:19 -0800769 if (LoadFileContents(target_filename, &source_file) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800770 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
771 // The early-exit case: the patch was already applied, this file
772 // has the desired hash, nothing for us to do.
Doug Zongkerbf80f492012-10-19 12:24:26 -0700773 printf("already ");
774 print_short_sha1(target_sha1);
775 putchar('\n');
Doug Zongker1c43c972012-02-28 11:07:09 -0800776 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800777 return 0;
778 }
779 }
Doug Zongker512536a2010-02-17 16:11:44 -0800780
Doug Zongkerc4351c72010-02-22 14:46:32 -0800781 if (source_file.data == NULL ||
782 (target_filename != source_filename &&
783 strcmp(target_filename, source_filename) != 0)) {
784 // Need to load the source file: either we failed to load the
785 // target file, or we did but it's different from the source file.
786 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800787 source_file.data = NULL;
Doug Zongkera1bc1482014-02-13 15:18:19 -0800788 LoadFileContents(source_filename, &source_file);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800789 }
790
791 if (source_file.data != NULL) {
792 int to_use = FindMatchingPatch(source_file.sha1,
793 patch_sha1_str, num_patches);
794 if (to_use >= 0) {
795 source_patch_value = patch_data[to_use];
796 }
797 }
798
799 if (source_patch_value == NULL) {
800 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800801 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800802 printf("source file is bad; trying copy\n");
803
Doug Zongkera1bc1482014-02-13 15:18:19 -0800804 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800805 // fail.
806 printf("failed to read copy file\n");
807 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800808 }
809
Doug Zongkerc4351c72010-02-22 14:46:32 -0800810 int to_use = FindMatchingPatch(copy_file.sha1,
811 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700812 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800813 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800814 }
815
Doug Zongkerc4351c72010-02-22 14:46:32 -0800816 if (copy_patch_value == NULL) {
817 // fail.
818 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800819 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800820 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800821 }
Doug Zongker512536a2010-02-17 16:11:44 -0800822 }
823
Doug Zongker1c43c972012-02-28 11:07:09 -0800824 int result = GenerateTarget(&source_file, source_patch_value,
825 &copy_file, copy_patch_value,
826 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700827 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800828 free(source_file.data);
829 free(copy_file.data);
830
831 return result;
832}
833
834static int GenerateTarget(FileContents* source_file,
835 const Value* source_patch_value,
836 FileContents* copy_file,
837 const Value* copy_patch_value,
838 const char* source_filename,
839 const char* target_filename,
840 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700841 size_t target_size,
842 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800843 int retry = 1;
844 SHA_CTX ctx;
845 int output;
846 MemorySinkInfo msi;
847 FileContents* source_to_use;
848 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800849 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800850
851 // assume that target_filename (eg "/system/app/Foo.apk") is located
852 // on the same filesystem as its top-level directory ("/system").
853 // We need something that exists for calling statfs().
854 char target_fs[strlen(target_filename)+1];
855 char* slash = strchr(target_filename+1, '/');
856 if (slash != NULL) {
857 int count = slash - target_filename;
858 strncpy(target_fs, target_filename, count);
859 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800860 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800861 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800862 }
863
Doug Zongkerc4351c72010-02-22 14:46:32 -0800864 do {
865 // Is there enough room in the target filesystem to hold the patched
866 // file?
867
Doug Zongkerf291d852010-07-07 13:55:25 -0700868 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000869 strncmp(target_filename, "EMMC:", 5) == 0 ||
870 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700871 // If the target is a partition, we're actually going to
872 // write the output to /tmp and then copy it to the
873 // partition. statfs() always returns 0 blocks free for
874 // /tmp, so instead we'll just assume that /tmp has enough
875 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800876
Doug Zongkerf291d852010-07-07 13:55:25 -0700877 // We still write the original source to cache, in case
878 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800879 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800880 printf("not enough free space on /cache\n");
881 return 1;
882 }
883 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
884 printf("failed to back up source file\n");
885 return 1;
886 }
887 made_copy = 1;
888 retry = 0;
889 } else {
890 int enough_space = 0;
891 if (retry > 0) {
892 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700893 enough_space =
894 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800895 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700896 if (!enough_space) {
897 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
898 (long)target_size, (long)free_space, retry, enough_space);
899 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800900 }
901
902 if (!enough_space) {
903 retry = 0;
904 }
905
906 if (!enough_space && source_patch_value != NULL) {
907 // Using the original source, but not enough free space. First
908 // copy the source file to cache, then delete it from the original
909 // location.
910
Doug Zongkerf291d852010-07-07 13:55:25 -0700911 if (strncmp(source_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000912 strncmp(source_filename, "EMMC:", 5) == 0 ||
913 strncmp(source_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800914 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700915 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800916 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700917 printf("not enough free space for target but source "
918 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800919 return 1;
920 }
921
Doug Zongker1c43c972012-02-28 11:07:09 -0800922 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800923 printf("not enough free space on /cache\n");
924 return 1;
925 }
926
927 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
928 printf("failed to back up source file\n");
929 return 1;
930 }
931 made_copy = 1;
932 unlink(source_filename);
933
934 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700935 printf("(now %ld bytes free for target) ", (long)free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800936 }
937 }
938
939 const Value* patch;
940 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800941 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800942 patch = source_patch_value;
943 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800944 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800945 patch = copy_patch_value;
946 }
947
948 if (patch->type != VAL_BLOB) {
949 printf("patch is not a blob\n");
950 return 1;
951 }
952
953 SinkFn sink = NULL;
954 void* token = NULL;
955 output = -1;
956 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700957 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000958 strncmp(target_filename, "EMMC:", 5) == 0 ||
959 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800960 // We store the decoded output in memory.
961 msi.buffer = malloc(target_size);
962 if (msi.buffer == NULL) {
963 printf("failed to alloc %ld bytes for output\n",
964 (long)target_size);
965 return 1;
966 }
967 msi.pos = 0;
968 msi.size = target_size;
969 sink = MemorySink;
970 token = &msi;
971 } else {
972 // We write the decoded output to "<tgt-file>.patch".
973 outname = (char*)malloc(strlen(target_filename) + 10);
974 strcpy(outname, target_filename);
975 strcat(outname, ".patch");
976
Michael Rungecddb68b2014-10-29 12:42:15 -0700977 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC,
978 S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800979 if (output < 0) {
980 printf("failed to open output file %s: %s\n",
981 outname, strerror(errno));
982 return 1;
983 }
984 sink = FileSink;
985 token = &output;
986 }
987
988 char* header = patch->data;
989 ssize_t header_bytes_read = patch->size;
990
991 SHA_init(&ctx);
992
993 int result;
994
995 if (header_bytes_read >= 8 &&
996 memcmp(header, "BSDIFF40", 8) == 0) {
997 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
998 patch, 0, sink, token, &ctx);
999 } else if (header_bytes_read >= 8 &&
1000 memcmp(header, "IMGDIFF2", 8) == 0) {
1001 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -07001002 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -08001003 } else {
1004 printf("Unknown patch file format\n");
1005 return 1;
1006 }
1007
1008 if (output >= 0) {
Michael Rungecddb68b2014-10-29 12:42:15 -07001009 if (fsync(output) != 0) {
1010 printf("failed to fsync file \"%s\" (%s)\n", outname, strerror(errno));
1011 result = 1;
1012 }
1013 if (close(output) != 0) {
1014 printf("failed to close file \"%s\" (%s)\n", outname, strerror(errno));
1015 result = 1;
1016 }
Doug Zongkerc4351c72010-02-22 14:46:32 -08001017 }
1018
1019 if (result != 0) {
1020 if (retry == 0) {
1021 printf("applying patch failed\n");
1022 return result != 0;
1023 } else {
1024 printf("applying patch failed; retrying\n");
1025 }
1026 if (outname != NULL) {
1027 unlink(outname);
1028 }
1029 } else {
1030 // succeeded; no need to retry
1031 break;
1032 }
1033 } while (retry-- > 0);
1034
1035 const uint8_t* current_target_sha1 = SHA_final(&ctx);
1036 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
1037 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -08001038 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -07001039 } else {
1040 printf("now ");
1041 print_short_sha1(target_sha1);
1042 putchar('\n');
Doug Zongkerc4351c72010-02-22 14:46:32 -08001043 }
1044
1045 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001046 // Copy the temp file to the partition.
1047 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001048 printf("write of patched data to %s failed\n", target_filename);
1049 return 1;
1050 }
1051 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -08001052 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001053 // Give the .patch file the same owner, group, and mode of the
1054 // original source file.
1055 if (chmod(outname, source_to_use->st.st_mode) != 0) {
1056 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
1057 return 1;
1058 }
1059 if (chown(outname, source_to_use->st.st_uid,
1060 source_to_use->st.st_gid) != 0) {
1061 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
1062 return 1;
1063 }
Doug Zongker512536a2010-02-17 16:11:44 -08001064
Doug Zongkerc4351c72010-02-22 14:46:32 -08001065 // Finally, rename the .patch file to replace the target file.
1066 if (rename(outname, target_filename) != 0) {
1067 printf("rename of .patch to \"%s\" failed: %s\n",
1068 target_filename, strerror(errno));
1069 return 1;
1070 }
Doug Zongker512536a2010-02-17 16:11:44 -08001071 }
1072
Doug Zongkerc4351c72010-02-22 14:46:32 -08001073 // If this run of applypatch created the copy, and we're here, we
1074 // can delete it.
1075 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -08001076
Doug Zongkerc4351c72010-02-22 14:46:32 -08001077 // Success!
1078 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001079}