blob: b5ff12c8028b77ff77e38b31f4deed061ab3dd72 [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>
27
28#include "mincrypt/sha.h"
29#include "applypatch.h"
Conn O'Griofad9201042014-03-25 01:26:49 +000030#include "bmlutils/bmlutils.h"
Doug Zongker512536a2010-02-17 16:11:44 -080031#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080032#include "edify/expr.h"
Doug Zongker512536a2010-02-17 16:11:44 -080033
Doug Zongkerf291d852010-07-07 13:55:25 -070034static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerf291d852010-07-07 13:55:25 -070035static ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080036static int GenerateTarget(FileContents* source_file,
37 const Value* source_patch_value,
38 FileContents* copy_file,
39 const Value* copy_patch_value,
40 const char* source_filename,
41 const char* target_filename,
42 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -070043 size_t target_size,
44 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080045
46static int mtd_partitions_scanned = 0;
47
Hristo Bojinovdb314d62010-08-02 10:29:49 -070048// Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
49// the retouched entries back to their original value (such that SHA-1 checks
50// don't fail due to randomization); store the file contents and associated
51// metadata in *file.
52//
53// Return 0 on success.
54int LoadFileContents(const char* filename, FileContents* file,
55 int retouch_flag) {
Doug Zongker512536a2010-02-17 16:11:44 -080056 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080057
Doug Zongkerf291d852010-07-07 13:55:25 -070058 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
59 // load the contents of a partition.
60 if (strncmp(filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +000061 strncmp(filename, "EMMC:", 5) == 0 ||
62 strncmp(filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -070063 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080064 }
Doug Zongker512536a2010-02-17 16:11:44 -080065
Doug Zongkerc4351c72010-02-22 14:46:32 -080066 if (stat(filename, &file->st) != 0) {
67 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
68 return -1;
69 }
70
71 file->size = file->st.st_size;
72 file->data = malloc(file->size);
73
74 FILE* f = fopen(filename, "rb");
75 if (f == NULL) {
76 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
77 free(file->data);
78 file->data = NULL;
79 return -1;
80 }
81
82 ssize_t bytes_read = fread(file->data, 1, file->size, f);
83 if (bytes_read != file->size) {
84 printf("short read of \"%s\" (%ld bytes of %ld)\n",
85 filename, (long)bytes_read, (long)file->size);
86 free(file->data);
87 file->data = NULL;
88 return -1;
89 }
90 fclose(f);
91
Hristo Bojinovdb314d62010-08-02 10:29:49 -070092 // apply_patch[_check] functions are blind to randomization. Randomization
93 // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
94 // within a file, this means the file is assumed "corrupt" for simplicity.
95 if (retouch_flag) {
96 int32_t desired_offset = 0;
97 if (retouch_mask_data(file->data, file->size,
98 &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
99 printf("error trying to mask retouch entries\n");
100 free(file->data);
101 file->data = NULL;
102 return -1;
103 }
104 }
105
Doug Zongkerbac7fba2013-04-10 11:32:17 -0700106 SHA_hash(file->data, file->size, file->sha1);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800107 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800108}
109
110static size_t* size_array;
111// comparison function for qsort()ing an int array of indexes into
112// size_array[].
113static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800114 int aa = *(int*)a;
115 int bb = *(int*)b;
116 if (size_array[aa] < size_array[bb]) {
117 return -1;
118 } else if (size_array[aa] > size_array[bb]) {
119 return 1;
120 } else {
121 return 0;
122 }
Doug Zongker512536a2010-02-17 16:11:44 -0800123}
124
Doug Zongkerf291d852010-07-07 13:55:25 -0700125// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800126// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700127// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
128// "EMMC:<partition_device>:..."). The smallest size_n bytes for
129// which that prefix of the partition contents has the corresponding
130// sha1 hash will be loaded. It is acceptable for a size value to be
131// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800132//
133// This complexity is needed because if an OTA installation is
134// interrupted, the partition might contain either the source or the
135// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700136// the length in order to read from a partition (there is no
137// "end-of-file" marker), so the caller must specify the possible
138// lengths and the hash of the data, and we'll do the load expecting
139// to find one of those hashes.
140enum PartitionType { MTD, EMMC };
141
142static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800143 char* copy = strdup(filename);
144 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700145
146 enum PartitionType type;
147
148 if (strcmp(magic, "MTD") == 0) {
149 type = MTD;
150 } else if (strcmp(magic, "EMMC") == 0) {
151 type = EMMC;
Conn O'Griofad9201042014-03-25 01:26:49 +0000152 } else if (strcmp(magic, "BML") == 0) {
153 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700154 } else {
155 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800156 filename);
157 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800158 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800159 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800160
Conn O'Griofad9201042014-03-25 01:26:49 +0000161 if (strcmp(magic, "BML") == 0) {
162 if (strcmp(partition, "boot") == 0) {
163 partition = BOARD_BML_BOOT;
164 } else if (strcmp(partition, "recovery") == 0) {
165 partition = BOARD_BML_RECOVERY;
166 }
167 }
168
Doug Zongkerc4351c72010-02-22 14:46:32 -0800169 int i;
170 int colons = 0;
171 for (i = 0; filename[i] != '\0'; ++i) {
172 if (filename[i] == ':') {
173 ++colons;
174 }
Doug Zongker512536a2010-02-17 16:11:44 -0800175 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800176 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700177 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800178 filename);
179 }
Doug Zongker512536a2010-02-17 16:11:44 -0800180
Doug Zongkerc4351c72010-02-22 14:46:32 -0800181 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
182 int* index = malloc(pairs * sizeof(int));
183 size_t* size = malloc(pairs * sizeof(size_t));
184 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800185
Doug Zongkerc4351c72010-02-22 14:46:32 -0800186 for (i = 0; i < pairs; ++i) {
187 const char* size_str = strtok(NULL, ":");
188 size[i] = strtol(size_str, NULL, 10);
189 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700190 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800191 return -1;
192 }
193 sha1sum[i] = strtok(NULL, ":");
194 index[i] = i;
195 }
Doug Zongker512536a2010-02-17 16:11:44 -0800196
Doug Zongkerc4351c72010-02-22 14:46:32 -0800197 // sort the index[] array so it indexes the pairs in order of
198 // increasing size.
199 size_array = size;
200 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800201
Doug Zongkerf291d852010-07-07 13:55:25 -0700202 MtdReadContext* ctx = NULL;
203 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800204
Doug Zongkerf291d852010-07-07 13:55:25 -0700205 switch (type) {
206 case MTD:
207 if (!mtd_partitions_scanned) {
208 mtd_scan_partitions();
209 mtd_partitions_scanned = 1;
210 }
Doug Zongker512536a2010-02-17 16:11:44 -0800211
Doug Zongkerf291d852010-07-07 13:55:25 -0700212 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
213 if (mtd == NULL) {
214 printf("mtd partition \"%s\" not found (loading %s)\n",
215 partition, filename);
216 return -1;
217 }
218
219 ctx = mtd_read_partition(mtd);
220 if (ctx == NULL) {
221 printf("failed to initialize read of mtd partition \"%s\"\n",
222 partition);
223 return -1;
224 }
225 break;
226
227 case EMMC:
228 dev = fopen(partition, "rb");
229 if (dev == NULL) {
230 printf("failed to open emmc partition \"%s\": %s\n",
231 partition, strerror(errno));
232 return -1;
233 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800234 }
Doug Zongker512536a2010-02-17 16:11:44 -0800235
Doug Zongkerc4351c72010-02-22 14:46:32 -0800236 SHA_CTX sha_ctx;
237 SHA_init(&sha_ctx);
238 uint8_t parsed_sha[SHA_DIGEST_SIZE];
239
240 // allocate enough memory to hold the largest size.
241 file->data = malloc(size[index[pairs-1]]);
242 char* p = (char*)file->data;
243 file->size = 0; // # bytes read so far
244
245 for (i = 0; i < pairs; ++i) {
246 // Read enough additional bytes to get us up to the next size
247 // (again, we're trying the possibilities in order of increasing
248 // size).
249 size_t next = size[index[i]] - file->size;
250 size_t read = 0;
251 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700252 switch (type) {
253 case MTD:
254 read = mtd_read_data(ctx, p, next);
255 break;
256
257 case EMMC:
258 read = fread(p, 1, next, dev);
259 break;
260 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800261 if (next != read) {
262 printf("short read (%d bytes of %d) for partition \"%s\"\n",
263 read, next, partition);
264 free(file->data);
265 file->data = NULL;
266 return -1;
267 }
268 SHA_update(&sha_ctx, p, read);
269 file->size += read;
270 }
271
272 // Duplicate the SHA context and finalize the duplicate so we can
273 // check it against this pair's expected hash.
274 SHA_CTX temp_ctx;
275 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
276 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
277
278 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
279 printf("failed to parse sha1 %s in %s\n",
280 sha1sum[index[i]], filename);
281 free(file->data);
282 file->data = NULL;
283 return -1;
284 }
285
286 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
287 // we have a match. stop reading the partition; we'll return
288 // the data we've read so far.
Doug Zongkerf291d852010-07-07 13:55:25 -0700289 printf("partition read matched size %d sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800290 size[index[i]], sha1sum[index[i]]);
291 break;
292 }
293
294 p += read;
295 }
296
Doug Zongkerf291d852010-07-07 13:55:25 -0700297 switch (type) {
298 case MTD:
299 mtd_read_close(ctx);
300 break;
301
302 case EMMC:
303 fclose(dev);
304 break;
305 }
306
Doug Zongkerc4351c72010-02-22 14:46:32 -0800307
308 if (i == pairs) {
309 // Ran off the end of the list of (size,sha1) pairs without
310 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700311 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800312 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800313 free(file->data);
314 file->data = NULL;
315 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800316 }
317
Doug Zongkerc4351c72010-02-22 14:46:32 -0800318 const uint8_t* sha_final = SHA_final(&sha_ctx);
319 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
320 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800321 }
322
Doug Zongkerc4351c72010-02-22 14:46:32 -0800323 // Fake some stat() info.
324 file->st.st_mode = 0644;
325 file->st.st_uid = 0;
326 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800327
Doug Zongkerc4351c72010-02-22 14:46:32 -0800328 free(copy);
329 free(index);
330 free(size);
331 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800332
Doug Zongkerc4351c72010-02-22 14:46:32 -0800333 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800334}
335
336
337// Save the contents of the given FileContents object under the given
338// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800339int SaveFileContents(const char* filename, const FileContents* file) {
Nick Kralevich956cde82012-06-26 15:01:03 -0700340 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800341 if (fd < 0) {
342 printf("failed to open \"%s\" for write: %s\n",
343 filename, strerror(errno));
344 return -1;
345 }
Doug Zongker512536a2010-02-17 16:11:44 -0800346
Doug Zongker1c43c972012-02-28 11:07:09 -0800347 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
348 if (bytes_written != file->size) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800349 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
Doug Zongker1c43c972012-02-28 11:07:09 -0800350 filename, (long)bytes_written, (long)file->size,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800351 strerror(errno));
352 close(fd);
353 return -1;
354 }
355 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800356 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800357
Doug Zongker1c43c972012-02-28 11:07:09 -0800358 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800359 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
360 return -1;
361 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800362 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800363 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
364 return -1;
365 }
Doug Zongker512536a2010-02-17 16:11:44 -0800366
Doug Zongkerc4351c72010-02-22 14:46:32 -0800367 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800368}
369
Doug Zongkerf291d852010-07-07 13:55:25 -0700370// Write a memory buffer to 'target' partition, a string of the form
371// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
372// success.
373int WriteToPartition(unsigned char* data, size_t len,
374 const char* target) {
375 char* copy = strdup(target);
376 const char* magic = strtok(copy, ":");
377
378 enum PartitionType type;
379 if (strcmp(magic, "MTD") == 0) {
380 type = MTD;
381 } else if (strcmp(magic, "EMMC") == 0) {
382 type = EMMC;
Conn O'Griofad9201042014-03-25 01:26:49 +0000383 } else if (strcmp(magic, "BML") == 0) {
384 type = EMMC;
Doug Zongkerf291d852010-07-07 13:55:25 -0700385 } else {
386 printf("WriteToPartition called with bad target (%s)\n", target);
387 return -1;
388 }
389 const char* partition = strtok(NULL, ":");
390
Conn O'Griofad9201042014-03-25 01:26:49 +0000391 if (strcmp(magic, "BML") == 0) {
392 if (strcmp(partition, "boot") == 0) {
393 partition = BOARD_BML_BOOT;
394 } else if (strcmp(partition, "recovery") == 0) {
395 partition = BOARD_BML_RECOVERY;
396 }
397
398 int bmlpartition = open(partition, O_RDWR | O_LARGEFILE);
399 if (bmlpartition < 0)
400 return -1;
401 if (ioctl(bmlpartition, BML_UNLOCK_ALL, 0)) {
402 printf("failed to unlock BML partition: (%s)\n", partition);
403 return -1;
404 }
405 close(bmlpartition);
406 }
407
Doug Zongkerc4351c72010-02-22 14:46:32 -0800408 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700409 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800410 return -1;
411 }
Doug Zongker512536a2010-02-17 16:11:44 -0800412
Doug Zongkerf291d852010-07-07 13:55:25 -0700413 switch (type) {
414 case MTD:
415 if (!mtd_partitions_scanned) {
416 mtd_scan_partitions();
417 mtd_partitions_scanned = 1;
418 }
419
420 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
421 if (mtd == NULL) {
422 printf("mtd partition \"%s\" not found for writing\n",
423 partition);
424 return -1;
425 }
426
427 MtdWriteContext* ctx = mtd_write_partition(mtd);
428 if (ctx == NULL) {
429 printf("failed to init mtd partition \"%s\" for writing\n",
430 partition);
431 return -1;
432 }
433
434 size_t written = mtd_write_data(ctx, (char*)data, len);
435 if (written != len) {
436 printf("only wrote %d of %d bytes to MTD %s\n",
437 written, len, partition);
438 mtd_write_close(ctx);
439 return -1;
440 }
441
442 if (mtd_erase_blocks(ctx, -1) < 0) {
443 printf("error finishing mtd write of %s\n", partition);
444 mtd_write_close(ctx);
445 return -1;
446 }
447
448 if (mtd_write_close(ctx)) {
449 printf("error closing mtd write of %s\n", partition);
450 return -1;
451 }
452 break;
453
454 case EMMC:
Doug Zongker044a0b42013-07-08 09:42:54 -0700455 {
456 size_t start = 0;
457 int success = 0;
Doug Zongker901b8982013-07-11 12:31:25 -0700458 int fd = open(partition, O_RDWR | O_SYNC);
Doug Zongkerc870a992013-07-09 10:34:46 -0700459 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700460 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700461 return -1;
462 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700463 int attempt;
464
Doug Zongkerc870a992013-07-09 10:34:46 -0700465 for (attempt = 0; attempt < 10; ++attempt) {
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700466 size_t next_sync = start + (1<<20);
Doug Zongker901b8982013-07-11 12:31:25 -0700467 printf("raw O_SYNC write %s attempt %d start at %d\n", partition, attempt+1, start);
Doug Zongkerc870a992013-07-09 10:34:46 -0700468 lseek(fd, start, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700469 while (start < len) {
470 size_t to_write = len - start;
Doug Zongkerc870a992013-07-09 10:34:46 -0700471 if (to_write > 4096) to_write = 4096;
Doug Zongker044a0b42013-07-08 09:42:54 -0700472
Doug Zongkerc870a992013-07-09 10:34:46 -0700473 ssize_t written = write(fd, data+start, to_write);
474 if (written < 0) {
475 if (errno == EINTR) {
476 written = 0;
477 } else {
478 printf("failed write writing to %s (%s)\n",
479 partition, strerror(errno));
480 return -1;
481 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700482 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700483 start += written;
484 if (start >= next_sync) {
485 fsync(fd);
486 next_sync = start + (1<<20);
Doug Zongker044a0b42013-07-08 09:42:54 -0700487 }
488 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700489 fsync(fd);
Doug Zongker044a0b42013-07-08 09:42:54 -0700490
491 // drop caches so our subsequent verification read
492 // won't just be reading the cache.
493 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700494 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
495 write(dc, "3\n", 2);
496 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700497 sleep(1);
498 printf(" caches dropped\n");
499
500 // verify
Doug Zongkerc870a992013-07-09 10:34:46 -0700501 lseek(fd, 0, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700502 unsigned char buffer[4096];
503 start = len;
504 size_t p;
505 for (p = 0; p < len; p += sizeof(buffer)) {
506 size_t to_read = len - p;
507 if (to_read > sizeof(buffer)) to_read = sizeof(buffer);
508
Doug Zongkerc870a992013-07-09 10:34:46 -0700509 size_t so_far = 0;
510 while (so_far < to_read) {
511 ssize_t read_count = read(fd, buffer+so_far, to_read-so_far);
512 if (read_count < 0) {
513 if (errno == EINTR) {
514 read_count = 0;
515 } else {
516 printf("verify read error %s at %d: %s\n",
517 partition, p, strerror(errno));
518 return -1;
519 }
520 }
Doug Zongkerbf4a69a2013-07-10 13:39:50 -0700521 if ((size_t)read_count < to_read) {
Doug Zongkerc870a992013-07-09 10:34:46 -0700522 printf("short verify read %s at %d: %d %d %s\n",
523 partition, p, read_count, to_read, strerror(errno));
524 }
525 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700526 }
527
528 if (memcmp(buffer, data+p, to_read)) {
529 printf("verification failed starting at %d\n", p);
530 start = p;
531 break;
532 }
533 }
534
535 if (start == len) {
536 printf("verification read succeeded (attempt %d)\n", attempt+1);
537 success = true;
538 break;
539 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700540
541 sleep(2);
Doug Zongker044a0b42013-07-08 09:42:54 -0700542 }
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 // hack: sync and sleep after closing in hopes of getting
554 // the data actually onto flash.
555 printf("sleeping after close\n");
556 sync();
557 sleep(5);
Doug Zongkerf291d852010-07-07 13:55:25 -0700558 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700559 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800560 }
Doug Zongker512536a2010-02-17 16:11:44 -0800561
Doug Zongkerf291d852010-07-07 13:55:25 -0700562 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800563 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800564}
565
566
567// Take a string 'str' of 40 hex digits and parse it into the 20
568// byte array 'digest'. 'str' may contain only the digest or be of
569// the form "<digest>:<anything>". Return 0 on success, -1 on any
570// error.
571int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800572 int i;
573 const char* ps = str;
574 uint8_t* pd = digest;
575 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
576 int digit;
577 if (*ps >= '0' && *ps <= '9') {
578 digit = *ps - '0';
579 } else if (*ps >= 'a' && *ps <= 'f') {
580 digit = *ps - 'a' + 10;
581 } else if (*ps >= 'A' && *ps <= 'F') {
582 digit = *ps - 'A' + 10;
583 } else {
584 return -1;
585 }
586 if (i % 2 == 0) {
587 *pd = digit << 4;
588 } else {
589 *pd |= digit;
590 ++pd;
591 }
Doug Zongker512536a2010-02-17 16:11:44 -0800592 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593 if (*ps != '\0') return -1;
594 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800595}
596
Doug Zongkerc4351c72010-02-22 14:46:32 -0800597// Search an array of sha1 strings for one matching the given sha1.
598// Return the index of the match on success, or -1 if no match is
599// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700600int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800601 int num_patches) {
602 int i;
603 uint8_t patch_sha1[SHA_DIGEST_SIZE];
604 for (i = 0; i < num_patches; ++i) {
605 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
606 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
607 return i;
608 }
Doug Zongker512536a2010-02-17 16:11:44 -0800609 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800610 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800611}
612
613// Returns 0 if the contents of the file (argv[2]) or the cached file
614// match any of the sha1's on the command line (argv[3:]). Returns
615// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800616int applypatch_check(const char* filename,
617 int num_patches, char** const patch_sha1_str) {
618 FileContents file;
619 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800620
Doug Zongkerc4351c72010-02-22 14:46:32 -0800621 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700622 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800623 // partitions, where the filename encodes the sha1s; no need to
624 // check them twice.)
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700625 if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800626 (num_patches > 0 &&
627 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
628 printf("file \"%s\" doesn't have any of expected "
629 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800630
Doug Zongkerc4351c72010-02-22 14:46:32 -0800631 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800632 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800633
Doug Zongkerc4351c72010-02-22 14:46:32 -0800634 // If the source file is missing or corrupted, it might be because
635 // we were killed in the middle of patching it. A copy of it
636 // should have been made in CACHE_TEMP_SOURCE. If that file
637 // exists and matches the sha1 we're looking for, the check still
638 // passes.
639
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700640 if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800641 printf("failed to load cache file\n");
642 return 1;
643 }
644
645 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
646 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
647 free(file.data);
648 return 1;
649 }
650 }
Doug Zongker512536a2010-02-17 16:11:44 -0800651
652 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800653 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800654}
655
656int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800657 ShowBSDiffLicense();
658 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800659}
660
661ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800662 int fd = *(int *)token;
663 ssize_t done = 0;
664 ssize_t wrote;
665 while (done < (ssize_t) len) {
666 wrote = write(fd, data+done, len-done);
667 if (wrote <= 0) {
668 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
669 return done;
670 }
671 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800672 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800673 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800674}
675
676typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800677 unsigned char* buffer;
678 ssize_t size;
679 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800680} MemorySinkInfo;
681
682ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800683 MemorySinkInfo* msi = (MemorySinkInfo*)token;
684 if (msi->size - msi->pos < len) {
685 return -1;
686 }
687 memcpy(msi->buffer + msi->pos, data, len);
688 msi->pos += len;
689 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800690}
691
692// Return the amount of free space (in bytes) on the filesystem
693// containing filename. filename must exist. Return -1 on error.
694size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800695 struct statfs sf;
696 if (statfs(filename, &sf) != 0) {
697 printf("failed to statfs %s: %s\n", filename, strerror(errno));
698 return -1;
699 }
700 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800701}
702
Doug Zongkerc4351c72010-02-22 14:46:32 -0800703int CacheSizeCheck(size_t bytes) {
704 if (MakeFreeSpaceOnCache(bytes) < 0) {
705 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
706 return 1;
707 } else {
708 return 0;
709 }
710}
711
Doug Zongkerbf80f492012-10-19 12:24:26 -0700712static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
713 int i;
714 const char* hex = "0123456789abcdef";
715 for (i = 0; i < 4; ++i) {
716 putchar(hex[(sha1[i]>>4) & 0xf]);
717 putchar(hex[sha1[i] & 0xf]);
718 }
719}
Doug Zongkerc4351c72010-02-22 14:46:32 -0800720
721// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800722// (the original file is not touched until we have the desired
723// replacement for it) and idempotent (it's okay to run this program
724// multiple times).
725//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726// - if the sha1 hash of <target_filename> is <target_sha1_string>,
727// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800728//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800729// - otherwise, if the sha1 hash of <source_filename> is one of the
730// entries in <patch_sha1_str>, the corresponding patch from
731// <patch_data> (which must be a VAL_BLOB) is applied to produce a
732// new file (the type of patch is automatically detected from the
733// blob daat). If that new file has sha1 hash <target_sha1_str>,
734// moves it to replace <target_filename>, and exits successfully.
735// Note that if <source_filename> and <target_filename> are not the
736// same, <source_filename> is NOT deleted on success.
737// <target_filename> may be the string "-" to mean "the same as
738// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800739//
740// - otherwise, or if any error is encountered, exits with non-zero
741// status.
742//
Doug Zongkerf291d852010-07-07 13:55:25 -0700743// <source_filename> may refer to a partition to read the source data.
744// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800745// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800746
Doug Zongkerc4351c72010-02-22 14:46:32 -0800747int applypatch(const char* source_filename,
748 const char* target_filename,
749 const char* target_sha1_str,
750 size_t target_size,
751 int num_patches,
752 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700753 Value** patch_data,
754 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700755 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800756
Doug Zongkerc4351c72010-02-22 14:46:32 -0800757 if (target_filename[0] == '-' &&
758 target_filename[1] == '\0') {
759 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800760 }
761
Doug Zongkerc4351c72010-02-22 14:46:32 -0800762 uint8_t target_sha1[SHA_DIGEST_SIZE];
763 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
764 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800765 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800766 }
Doug Zongker512536a2010-02-17 16:11:44 -0800767
Doug Zongkerc4351c72010-02-22 14:46:32 -0800768 FileContents copy_file;
769 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800770 copy_file.data = NULL;
771 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800772 const Value* source_patch_value = NULL;
773 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800774
Doug Zongkerc4351c72010-02-22 14:46:32 -0800775 // We try to load the target file into the source_file object.
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700776 if (LoadFileContents(target_filename, &source_file,
777 RETOUCH_DO_MASK) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800778 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
779 // The early-exit case: the patch was already applied, this file
780 // has the desired hash, nothing for us to do.
Doug Zongkerbf80f492012-10-19 12:24:26 -0700781 printf("already ");
782 print_short_sha1(target_sha1);
783 putchar('\n');
Doug Zongker1c43c972012-02-28 11:07:09 -0800784 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800785 return 0;
786 }
787 }
Doug Zongker512536a2010-02-17 16:11:44 -0800788
Doug Zongkerc4351c72010-02-22 14:46:32 -0800789 if (source_file.data == NULL ||
790 (target_filename != source_filename &&
791 strcmp(target_filename, source_filename) != 0)) {
792 // Need to load the source file: either we failed to load the
793 // target file, or we did but it's different from the source file.
794 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800795 source_file.data = NULL;
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700796 LoadFileContents(source_filename, &source_file,
797 RETOUCH_DO_MASK);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800798 }
799
800 if (source_file.data != NULL) {
801 int to_use = FindMatchingPatch(source_file.sha1,
802 patch_sha1_str, num_patches);
803 if (to_use >= 0) {
804 source_patch_value = patch_data[to_use];
805 }
806 }
807
808 if (source_patch_value == NULL) {
809 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800810 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800811 printf("source file is bad; trying copy\n");
812
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700813 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
814 RETOUCH_DO_MASK) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800815 // fail.
816 printf("failed to read copy file\n");
817 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800818 }
819
Doug Zongkerc4351c72010-02-22 14:46:32 -0800820 int to_use = FindMatchingPatch(copy_file.sha1,
821 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700822 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800823 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800824 }
825
Doug Zongkerc4351c72010-02-22 14:46:32 -0800826 if (copy_patch_value == NULL) {
827 // fail.
828 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800829 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800830 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800831 }
Doug Zongker512536a2010-02-17 16:11:44 -0800832 }
833
Doug Zongker1c43c972012-02-28 11:07:09 -0800834 int result = GenerateTarget(&source_file, source_patch_value,
835 &copy_file, copy_patch_value,
836 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700837 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800838 free(source_file.data);
839 free(copy_file.data);
840
841 return result;
842}
843
844static int GenerateTarget(FileContents* source_file,
845 const Value* source_patch_value,
846 FileContents* copy_file,
847 const Value* copy_patch_value,
848 const char* source_filename,
849 const char* target_filename,
850 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700851 size_t target_size,
852 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800853 int retry = 1;
854 SHA_CTX ctx;
855 int output;
856 MemorySinkInfo msi;
857 FileContents* source_to_use;
858 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800859 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800860
861 // assume that target_filename (eg "/system/app/Foo.apk") is located
862 // on the same filesystem as its top-level directory ("/system").
863 // We need something that exists for calling statfs().
864 char target_fs[strlen(target_filename)+1];
865 char* slash = strchr(target_filename+1, '/');
866 if (slash != NULL) {
867 int count = slash - target_filename;
868 strncpy(target_fs, target_filename, count);
869 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800870 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800871 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800872 }
873
Doug Zongkerc4351c72010-02-22 14:46:32 -0800874 do {
875 // Is there enough room in the target filesystem to hold the patched
876 // file?
877
Doug Zongkerf291d852010-07-07 13:55:25 -0700878 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000879 strncmp(target_filename, "EMMC:", 5) == 0 ||
880 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700881 // If the target is a partition, we're actually going to
882 // write the output to /tmp and then copy it to the
883 // partition. statfs() always returns 0 blocks free for
884 // /tmp, so instead we'll just assume that /tmp has enough
885 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886
Doug Zongkerf291d852010-07-07 13:55:25 -0700887 // We still write the original source to cache, in case
888 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800889 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800890 printf("not enough free space on /cache\n");
891 return 1;
892 }
893 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
894 printf("failed to back up source file\n");
895 return 1;
896 }
897 made_copy = 1;
898 retry = 0;
899 } else {
900 int enough_space = 0;
901 if (retry > 0) {
902 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700903 enough_space =
904 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800905 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700906 if (!enough_space) {
907 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
908 (long)target_size, (long)free_space, retry, enough_space);
909 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800910 }
911
912 if (!enough_space) {
913 retry = 0;
914 }
915
916 if (!enough_space && source_patch_value != NULL) {
917 // Using the original source, but not enough free space. First
918 // copy the source file to cache, then delete it from the original
919 // location.
920
Doug Zongkerf291d852010-07-07 13:55:25 -0700921 if (strncmp(source_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000922 strncmp(source_filename, "EMMC:", 5) == 0 ||
923 strncmp(source_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800924 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700925 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800926 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700927 printf("not enough free space for target but source "
928 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800929 return 1;
930 }
931
Doug Zongker1c43c972012-02-28 11:07:09 -0800932 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800933 printf("not enough free space on /cache\n");
934 return 1;
935 }
936
937 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
938 printf("failed to back up source file\n");
939 return 1;
940 }
941 made_copy = 1;
942 unlink(source_filename);
943
944 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700945 printf("(now %ld bytes free for target) ", (long)free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800946 }
947 }
948
949 const Value* patch;
950 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800951 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800952 patch = source_patch_value;
953 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800954 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800955 patch = copy_patch_value;
956 }
957
958 if (patch->type != VAL_BLOB) {
959 printf("patch is not a blob\n");
960 return 1;
961 }
962
963 SinkFn sink = NULL;
964 void* token = NULL;
965 output = -1;
966 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700967 if (strncmp(target_filename, "MTD:", 4) == 0 ||
Conn O'Griofad9201042014-03-25 01:26:49 +0000968 strncmp(target_filename, "EMMC:", 5) == 0 ||
969 strncmp(target_filename, "BML:", 4) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800970 // We store the decoded output in memory.
971 msi.buffer = malloc(target_size);
972 if (msi.buffer == NULL) {
973 printf("failed to alloc %ld bytes for output\n",
974 (long)target_size);
975 return 1;
976 }
977 msi.pos = 0;
978 msi.size = target_size;
979 sink = MemorySink;
980 token = &msi;
981 } else {
982 // We write the decoded output to "<tgt-file>.patch".
983 outname = (char*)malloc(strlen(target_filename) + 10);
984 strcpy(outname, target_filename);
985 strcat(outname, ".patch");
986
Nick Kralevich956cde82012-06-26 15:01:03 -0700987 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800988 if (output < 0) {
989 printf("failed to open output file %s: %s\n",
990 outname, strerror(errno));
991 return 1;
992 }
993 sink = FileSink;
994 token = &output;
995 }
996
997 char* header = patch->data;
998 ssize_t header_bytes_read = patch->size;
999
1000 SHA_init(&ctx);
1001
1002 int result;
1003
1004 if (header_bytes_read >= 8 &&
1005 memcmp(header, "BSDIFF40", 8) == 0) {
1006 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
1007 patch, 0, sink, token, &ctx);
1008 } else if (header_bytes_read >= 8 &&
1009 memcmp(header, "IMGDIFF2", 8) == 0) {
1010 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -07001011 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -08001012 } else {
1013 printf("Unknown patch file format\n");
1014 return 1;
1015 }
1016
1017 if (output >= 0) {
1018 fsync(output);
1019 close(output);
1020 }
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}