blob: 655953354b4cfbba3340edd976b43ee261d6b522 [file] [log] [blame]
The Android Open Source Project88b60792009-03-03 19:28:42 -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 <unistd.h>
25
26#include "mincrypt/sha.h"
27#include "applypatch.h"
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070028#include "mtdutils/mtdutils.h"
29
30int LoadMTDContents(const char* filename, FileContents* file);
31int ParseSha1(const char* str, uint8_t* digest);
The Android Open Source Project88b60792009-03-03 19:28:42 -080032
33// Read a file into memory; store it and its associated metadata in
34// *file. Return 0 on success.
35int LoadFileContents(const char* filename, FileContents* file) {
36 file->data = NULL;
37
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070038 // A special 'filename' beginning with "MTD:" means to load the
39 // contents of an MTD partition.
40 if (strncmp(filename, "MTD:", 4) == 0) {
41 return LoadMTDContents(filename, file);
42 }
43
The Android Open Source Project88b60792009-03-03 19:28:42 -080044 if (stat(filename, &file->st) != 0) {
45 fprintf(stderr, "failed to stat \"%s\": %s\n", filename, strerror(errno));
46 return -1;
47 }
48
49 file->size = file->st.st_size;
50 file->data = malloc(file->size);
51
52 FILE* f = fopen(filename, "rb");
53 if (f == NULL) {
54 fprintf(stderr, "failed to open \"%s\": %s\n", filename, strerror(errno));
55 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070056 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080057 return -1;
58 }
59
60 size_t bytes_read = fread(file->data, 1, file->size, f);
61 if (bytes_read != file->size) {
62 fprintf(stderr, "short read of \"%s\" (%d bytes of %d)\n",
63 filename, bytes_read, file->size);
64 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070065 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080066 return -1;
67 }
68 fclose(f);
69
70 SHA(file->data, file->size, file->sha1);
71 return 0;
72}
73
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070074static size_t* size_array;
75// comparison function for qsort()ing an int array of indexes into
76// size_array[].
77static int compare_size_indices(const void* a, const void* b) {
78 int aa = *(int*)a;
79 int bb = *(int*)b;
80 if (size_array[aa] < size_array[bb]) {
81 return -1;
82 } else if (size_array[aa] > size_array[bb]) {
83 return 1;
84 } else {
85 return 0;
86 }
87}
88
89// Load the contents of an MTD partition into the provided
90// FileContents. filename should be a string of the form
91// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:...".
92// The smallest size_n bytes for which that prefix of the mtd contents
93// has the corresponding sha1 hash will be loaded. It is acceptable
94// for a size value to be repeated with different sha1s. Will return
95// 0 on success.
96//
97// This complexity is needed because if an OTA installation is
98// interrupted, the partition might contain either the source or the
99// target data, which might be of different lengths. We need to know
100// the length in order to read from MTD (there is no "end-of-file"
101// marker), so the caller must specify the possible lengths and the
102// hash of the data, and we'll do the load expecting to find one of
103// those hashes.
104int LoadMTDContents(const char* filename, FileContents* file) {
105 char* copy = strdup(filename);
106 const char* magic = strtok(copy, ":");
107 if (strcmp(magic, "MTD") != 0) {
108 fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
109 filename);
110 return -1;
111 }
112 const char* partition = strtok(NULL, ":");
113
114 int i;
115 int colons = 0;
116 for (i = 0; filename[i] != '\0'; ++i) {
117 if (filename[i] == ':') {
118 ++colons;
119 }
120 }
121 if (colons < 3 || colons%2 == 0) {
122 fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
123 filename);
124 }
125
126 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
127 int* index = malloc(pairs * sizeof(int));
128 size_t* size = malloc(pairs * sizeof(size_t));
129 char** sha1sum = malloc(pairs * sizeof(char*));
130
131 for (i = 0; i < pairs; ++i) {
132 const char* size_str = strtok(NULL, ":");
133 size[i] = strtol(size_str, NULL, 10);
134 if (size[i] == 0) {
135 fprintf(stderr, "LoadMTDContents called with bad size (%s)\n", filename);
136 return -1;
137 }
138 sha1sum[i] = strtok(NULL, ":");
139 index[i] = i;
140 }
141
142 // sort the index[] array so it indexs the pairs in order of
143 // increasing size.
144 size_array = size;
145 qsort(index, pairs, sizeof(int), compare_size_indices);
146
147 static int partitions_scanned = 0;
148 if (!partitions_scanned) {
149 mtd_scan_partitions();
150 partitions_scanned = 1;
151 }
152
153 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
154 if (mtd == NULL) {
155 fprintf(stderr, "mtd partition \"%s\" not found (loading %s)\n",
156 partition, filename);
157 return -1;
158 }
159
160 MtdReadContext* ctx = mtd_read_partition(mtd);
161 if (ctx == NULL) {
162 fprintf(stderr, "failed to initialize read of mtd partition \"%s\"\n",
163 partition);
164 return -1;
165 }
166
167 SHA_CTX sha_ctx;
168 SHA_init(&sha_ctx);
169 uint8_t parsed_sha[SHA_DIGEST_SIZE];
170
171 // allocate enough memory to hold the largest size.
172 file->data = malloc(size[index[pairs-1]]);
173 char* p = (char*)file->data;
174 file->size = 0; // # bytes read so far
175
176 for (i = 0; i < pairs; ++i) {
177 // Read enough additional bytes to get us up to the next size
178 // (again, we're trying the possibilities in order of increasing
179 // size).
180 size_t next = size[index[i]] - file->size;
181 size_t read = 0;
182 if (next > 0) {
183 read = mtd_read_data(ctx, p, next);
184 if (next != read) {
185 fprintf(stderr, "short read (%d bytes of %d) for partition \"%s\"\n",
186 read, next, partition);
187 free(file->data);
188 file->data = NULL;
189 return -1;
190 }
191 SHA_update(&sha_ctx, p, read);
192 file->size += read;
193 }
194
195 // Duplicate the SHA context and finalize the duplicate so we can
196 // check it against this pair's expected hash.
197 SHA_CTX temp_ctx;
198 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
199 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
200
201 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
202 fprintf(stderr, "failed to parse sha1 %s in %s\n",
203 sha1sum[index[i]], filename);
204 free(file->data);
205 file->data = NULL;
206 return -1;
207 }
208
209 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
210 // we have a match. stop reading the partition; we'll return
211 // the data we've read so far.
212 printf("mtd read matched size %d sha %s\n",
213 size[index[i]], sha1sum[index[i]]);
214 break;
215 }
216
217 p += read;
218 }
219
220 mtd_read_close(ctx);
221
222 if (i == pairs) {
223 // Ran off the end of the list of (size,sha1) pairs without
224 // finding a match.
225 fprintf(stderr, "contents of MTD partition \"%s\" didn't match %s\n",
226 partition, filename);
227 free(file->data);
228 file->data = NULL;
229 return -1;
230 }
231
232 const uint8_t* sha_final = SHA_final(&sha_ctx);
233 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
234 file->sha1[i] = sha_final[i];
235 }
236
237 free(copy);
238 free(index);
239 free(size);
240 free(sha1sum);
241
242 return 0;
243}
244
245
The Android Open Source Project88b60792009-03-03 19:28:42 -0800246// Save the contents of the given FileContents object under the given
247// filename. Return 0 on success.
248int SaveFileContents(const char* filename, FileContents file) {
249 FILE* f = fopen(filename, "wb");
250 if (f == NULL) {
251 fprintf(stderr, "failed to open \"%s\" for write: %s\n",
252 filename, strerror(errno));
253 return -1;
254 }
255
256 size_t bytes_written = fwrite(file.data, 1, file.size, f);
257 if (bytes_written != file.size) {
258 fprintf(stderr, "short write of \"%s\" (%d bytes of %d)\n",
259 filename, bytes_written, file.size);
260 return -1;
261 }
262 fflush(f);
263 fsync(fileno(f));
264 fclose(f);
265
266 if (chmod(filename, file.st.st_mode) != 0) {
267 fprintf(stderr, "chmod of \"%s\" failed: %s\n", filename, strerror(errno));
268 return -1;
269 }
270 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
271 fprintf(stderr, "chown of \"%s\" failed: %s\n", filename, strerror(errno));
272 return -1;
273 }
274
275 return 0;
276}
277
278
279// Take a string 'str' of 40 hex digits and parse it into the 20
280// byte array 'digest'. 'str' may contain only the digest or be of
281// the form "<digest>:<anything>". Return 0 on success, -1 on any
282// error.
283int ParseSha1(const char* str, uint8_t* digest) {
284 int i;
285 const char* ps = str;
286 uint8_t* pd = digest;
287 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
288 int digit;
289 if (*ps >= '0' && *ps <= '9') {
290 digit = *ps - '0';
291 } else if (*ps >= 'a' && *ps <= 'f') {
292 digit = *ps - 'a' + 10;
293 } else if (*ps >= 'A' && *ps <= 'F') {
294 digit = *ps - 'A' + 10;
295 } else {
296 return -1;
297 }
298 if (i % 2 == 0) {
299 *pd = digit << 4;
300 } else {
301 *pd |= digit;
302 ++pd;
303 }
304 }
305 if (*ps != '\0' && *ps != ':') return -1;
306 return 0;
307}
308
309// Parse arguments (which should be of the form "<sha1>" or
310// "<sha1>:<filename>" into the array *patches, returning the number
311// of Patch objects in *num_patches. Return 0 on success.
312int ParseShaArgs(int argc, char** argv, Patch** patches, int* num_patches) {
313 *num_patches = argc;
314 *patches = malloc(*num_patches * sizeof(Patch));
315
316 int i;
317 for (i = 0; i < *num_patches; ++i) {
318 if (ParseSha1(argv[i], (*patches)[i].sha1) != 0) {
319 fprintf(stderr, "failed to parse sha1 \"%s\"\n", argv[i]);
320 return -1;
321 }
322 if (argv[i][SHA_DIGEST_SIZE*2] == '\0') {
323 (*patches)[i].patch_filename = NULL;
324 } else if (argv[i][SHA_DIGEST_SIZE*2] == ':') {
325 (*patches)[i].patch_filename = argv[i] + (SHA_DIGEST_SIZE*2+1);
326 } else {
327 fprintf(stderr, "failed to parse filename \"%s\"\n", argv[i]);
328 return -1;
329 }
330 }
331
332 return 0;
333}
334
335// Search an array of Patch objects for one matching the given sha1.
336// Return the Patch object on success, or NULL if no match is found.
337const Patch* FindMatchingPatch(uint8_t* sha1, Patch* patches, int num_patches) {
338 int i;
339 for (i = 0; i < num_patches; ++i) {
340 if (memcmp(patches[i].sha1, sha1, SHA_DIGEST_SIZE) == 0) {
341 return patches+i;
342 }
343 }
344 return NULL;
345}
346
347// Returns 0 if the contents of the file (argv[2]) or the cached file
348// match any of the sha1's on the command line (argv[3:]). Returns
349// nonzero otherwise.
350int CheckMode(int argc, char** argv) {
351 if (argc < 3) {
352 fprintf(stderr, "no filename given\n");
353 return 2;
354 }
355
356 int num_patches;
357 Patch* patches;
358 if (ParseShaArgs(argc-3, argv+3, &patches, &num_patches) != 0) { return 1; }
359
360 FileContents file;
361 file.data = NULL;
362
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700363 // It's okay to specify no sha1s; the check will pass if the
364 // LoadFileContents is successful. (Useful for reading MTD
365 // partitions, where the filename encodes the sha1s; no need to
366 // check them twice.)
The Android Open Source Project88b60792009-03-03 19:28:42 -0800367 if (LoadFileContents(argv[2], &file) != 0 ||
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700368 (num_patches > 0 &&
369 FindMatchingPatch(file.sha1, patches, num_patches) == NULL)) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800370 fprintf(stderr, "file \"%s\" doesn't have any of expected "
371 "sha1 sums; checking cache\n", argv[2]);
372
373 free(file.data);
374
375 // If the source file is missing or corrupted, it might be because
376 // we were killed in the middle of patching it. A copy of it
377 // should have been made in CACHE_TEMP_SOURCE. If that file
378 // exists and matches the sha1 we're looking for, the check still
379 // passes.
380
381 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
382 fprintf(stderr, "failed to load cache file\n");
383 return 1;
384 }
385
386 if (FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
387 fprintf(stderr, "cache bits don't match any sha1 for \"%s\"\n",
388 argv[2]);
389 return 1;
390 }
391 }
392
393 free(file.data);
394 return 0;
395}
396
397int ShowLicenses() {
398 ShowBSDiffLicense();
399 return 0;
400}
401
402// Return the amount of free space (in bytes) on the filesystem
403// containing filename. filename must exist. Return -1 on error.
404size_t FreeSpaceForFile(const char* filename) {
405 struct statfs sf;
406 if (statfs(filename, &sf) != 0) {
407 fprintf(stderr, "failed to statfs %s: %s\n", filename, strerror(errno));
408 return -1;
409 }
410 return sf.f_bsize * sf.f_bfree;
411}
412
413// This program applies binary patches to files in a way that is safe
414// (the original file is not touched until we have the desired
415// replacement for it) and idempotent (it's okay to run this program
416// multiple times).
417//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700418// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
The Android Open Source Project88b60792009-03-03 19:28:42 -0800419// successfully.
420//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700421// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
422// bsdiff <patch> to <src-file> to produce a new file (the type of patch
The Android Open Source Project88b60792009-03-03 19:28:42 -0800423// is automatically detected from the file header). If that new
Doug Zongkeref85ea62009-05-08 13:46:25 -0700424// file has sha1 hash <tgt-sha1>, moves it to replace <tgt-file>, and
425// exits successfully. Note that if <src-file> and <tgt-file> are
426// not the same, <src-file> is NOT deleted on success. <tgt-file>
427// may be the string "-" to mean "the same as src-file".
The Android Open Source Project88b60792009-03-03 19:28:42 -0800428//
429// - otherwise, or if any error is encountered, exits with non-zero
430// status.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700431//
432// <src-file> (or <file> in check mode) may refer to an MTD partition
433// to read the source data. See the comments for the
434// LoadMTDContents() function above for the format of such a filename.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800435
436int main(int argc, char** argv) {
437 if (argc < 2) {
438 usage:
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700439 fprintf(stderr,
440 "usage: %s <src-file> <tgt-file> <tgt-sha1> <tgt-size> "
441 "[<src-sha1>:<patch> ...]\n"
442 " or %s -c <file> [<sha1> ...]\n"
443 " or %s -s <bytes>\n"
444 " or %s -l\n"
445 "\n"
446 "<src-file> or <file> may be of the form\n"
447 " MTD:<partition>:<len_1>:<sha1_1>:<len_2>:<sha1_2>:...\n"
448 "to specify reading from an MTD partition.\n\n",
The Android Open Source Project88b60792009-03-03 19:28:42 -0800449 argv[0], argv[0], argv[0], argv[0]);
450 return 1;
451 }
452
453 if (strncmp(argv[1], "-l", 3) == 0) {
454 return ShowLicenses();
455 }
456
457 if (strncmp(argv[1], "-c", 3) == 0) {
458 return CheckMode(argc, argv);
459 }
460
461 if (strncmp(argv[1], "-s", 3) == 0) {
462 if (argc != 3) {
463 goto usage;
464 }
465 size_t bytes = strtol(argv[2], NULL, 10);
466 if (MakeFreeSpaceOnCache(bytes) < 0) {
467 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
468 return 1;
469 } else {
470 return 0;
471 }
472 }
473
474 uint8_t target_sha1[SHA_DIGEST_SIZE];
475
476 const char* source_filename = argv[1];
Doug Zongkeref85ea62009-05-08 13:46:25 -0700477 const char* target_filename = argv[2];
478 if (target_filename[0] == '-' &&
479 target_filename[1] == '\0') {
480 target_filename = source_filename;
481 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800482
Doug Zongkeref85ea62009-05-08 13:46:25 -0700483 // assume that target_filename (eg "/system/app/Foo.apk") is located
The Android Open Source Project88b60792009-03-03 19:28:42 -0800484 // on the same filesystem as its top-level directory ("/system").
485 // We need something that exists for calling statfs().
Doug Zongkeref85ea62009-05-08 13:46:25 -0700486 char* target_fs = strdup(target_filename);
487 char* slash = strchr(target_fs+1, '/');
The Android Open Source Project88b60792009-03-03 19:28:42 -0800488 if (slash != NULL) {
489 *slash = '\0';
490 }
491
Doug Zongkeref85ea62009-05-08 13:46:25 -0700492 if (ParseSha1(argv[3], target_sha1) != 0) {
493 fprintf(stderr, "failed to parse tgt-sha1 \"%s\"\n", argv[3]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800494 return 1;
495 }
496
Doug Zongkeref85ea62009-05-08 13:46:25 -0700497 unsigned long target_size = strtoul(argv[4], NULL, 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800498
499 int num_patches;
500 Patch* patches;
Doug Zongkeref85ea62009-05-08 13:46:25 -0700501 if (ParseShaArgs(argc-5, argv+5, &patches, &num_patches) < 0) { return 1; }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800502
503 FileContents copy_file;
504 FileContents source_file;
505 const char* source_patch_filename = NULL;
506 const char* copy_patch_filename = NULL;
507 int made_copy = 0;
508
Doug Zongkeref85ea62009-05-08 13:46:25 -0700509 // We try to load the target file into the source_file object.
510 if (LoadFileContents(target_filename, &source_file) == 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800511 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
512 // The early-exit case: the patch was already applied, this file
513 // has the desired hash, nothing for us to do.
514 fprintf(stderr, "\"%s\" is already target; no patch needed\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700515 target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800516 return 0;
517 }
Doug Zongkeref85ea62009-05-08 13:46:25 -0700518 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800519
Doug Zongkeref85ea62009-05-08 13:46:25 -0700520 if (source_file.data == NULL ||
521 (target_filename != source_filename &&
522 strcmp(target_filename, source_filename) != 0)) {
523 // Need to load the source file: either we failed to load the
524 // target file, or we did but it's different from the source file.
525 free(source_file.data);
526 LoadFileContents(source_filename, &source_file);
527 }
528
529 if (source_file.data != NULL) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800530 const Patch* to_use =
531 FindMatchingPatch(source_file.sha1, patches, num_patches);
532 if (to_use != NULL) {
533 source_patch_filename = to_use->patch_filename;
534 }
535 }
536
537 if (source_patch_filename == NULL) {
538 free(source_file.data);
539 fprintf(stderr, "source file is bad; trying copy\n");
540
541 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
542 // fail.
543 fprintf(stderr, "failed to read copy file\n");
544 return 1;
545 }
546
547 const Patch* to_use =
548 FindMatchingPatch(copy_file.sha1, patches, num_patches);
549 if (to_use != NULL) {
550 copy_patch_filename = to_use->patch_filename;
551 }
552
553 if (copy_patch_filename == NULL) {
554 // fail.
555 fprintf(stderr, "copy file doesn't match source SHA-1s either\n");
556 return 1;
557 }
558 }
559
560 // Is there enough room in the target filesystem to hold the patched file?
Doug Zongkeref85ea62009-05-08 13:46:25 -0700561 size_t free_space = FreeSpaceForFile(target_fs);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800562 int enough_space = free_space > (target_size * 3 / 2); // 50% margin of error
563 printf("target %ld bytes; free space %ld bytes; enough %d\n",
564 (long)target_size, (long)free_space, enough_space);
565
566 if (!enough_space && source_patch_filename != NULL) {
567 // Using the original source, but not enough free space. First
568 // copy the source file to cache, then delete it from the original
569 // location.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700570
571 if (strncmp(source_filename, "MTD:", 4) == 0) {
572 // It's impossible to free space on the target filesystem by
573 // deleting the source if the source is an MTD partition. If
574 // we're ever in a state where we need to do this, fail.
575 fprintf(stderr, "not enough free space for target but source is MTD\n");
576 return 1;
577 }
578
The Android Open Source Project88b60792009-03-03 19:28:42 -0800579 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
580 fprintf(stderr, "not enough free space on /cache\n");
581 return 1;
582 }
583
584 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
585 fprintf(stderr, "failed to back up source file\n");
586 return 1;
587 }
588 made_copy = 1;
589 unlink(source_filename);
590
Doug Zongkeref85ea62009-05-08 13:46:25 -0700591 size_t free_space = FreeSpaceForFile(target_fs);
592 printf("(now %ld bytes free for target)\n", (long)free_space);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800593 }
594
595 FileContents* source_to_use;
596 const char* patch_filename;
597 if (source_patch_filename != NULL) {
598 source_to_use = &source_file;
599 patch_filename = source_patch_filename;
600 } else {
601 source_to_use = &copy_file;
602 patch_filename = copy_patch_filename;
603 }
604
Doug Zongkeref85ea62009-05-08 13:46:25 -0700605 // We write the decoded output to "<tgt-file>.patch".
606 char* outname = (char*)malloc(strlen(target_filename) + 10);
607 strcpy(outname, target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800608 strcat(outname, ".patch");
609 FILE* output = fopen(outname, "wb");
610 if (output == NULL) {
611 fprintf(stderr, "failed to patch file %s: %s\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700612 target_filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800613 return 1;
614 }
615
616#define MAX_HEADER_LENGTH 8
617 unsigned char header[MAX_HEADER_LENGTH];
618 FILE* patchf = fopen(patch_filename, "rb");
619 if (patchf == NULL) {
620 fprintf(stderr, "failed to open patch file %s: %s\n",
621 patch_filename, strerror(errno));
622 return 1;
623 }
624 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
625 fclose(patchf);
626
627 SHA_CTX ctx;
628 SHA_init(&ctx);
629
630 if (header_bytes_read >= 4 &&
631 header[0] == 0xd6 && header[1] == 0xc3 &&
632 header[2] == 0xc4 && header[3] == 0) {
633 // xdelta3 patches begin "VCD" (with the high bits set) followed
634 // by a zero byte (the version number).
635 fprintf(stderr, "error: xdelta3 patches no longer supported\n");
636 return 1;
637 } else if (header_bytes_read >= 8 &&
638 memcmp(header, "BSDIFF40", 8) == 0) {
639 int result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
Doug Zongker02d444b2009-05-27 18:24:03 -0700640 patch_filename, 0, output, &ctx);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800641 if (result != 0) {
642 fprintf(stderr, "ApplyBSDiffPatch failed\n");
643 return result;
644 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700645 } else if (header_bytes_read >= 8 &&
646 memcmp(header, "IMGDIFF1", 8) == 0) {
647 int result = ApplyImagePatch(source_to_use->data, source_to_use->size,
648 patch_filename, output, &ctx);
649 if (result != 0) {
650 fprintf(stderr, "ApplyImagePatch failed\n");
651 return result;
652 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800653 } else {
654 fprintf(stderr, "Unknown patch file format");
655 return 1;
656 }
657
658 fflush(output);
659 fsync(fileno(output));
660 fclose(output);
661
662 const uint8_t* current_target_sha1 = SHA_final(&ctx);
663 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
664 fprintf(stderr, "patch did not produce expected sha1\n");
665 return 1;
666 }
667
668 // Give the .patch file the same owner, group, and mode of the
669 // original source file.
670 if (chmod(outname, source_to_use->st.st_mode) != 0) {
671 fprintf(stderr, "chmod of \"%s\" failed: %s\n", outname, strerror(errno));
672 return 1;
673 }
674 if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
675 fprintf(stderr, "chown of \"%s\" failed: %s\n", outname, strerror(errno));
676 return 1;
677 }
678
Doug Zongkeref85ea62009-05-08 13:46:25 -0700679 // Finally, rename the .patch file to replace the target file.
680 if (rename(outname, target_filename) != 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800681 fprintf(stderr, "rename of .patch to \"%s\" failed: %s\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700682 target_filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800683 return 1;
684 }
685
686 // If this run of applypatch created the copy, and we're here, we
687 // can delete it.
688 if (made_copy) unlink(CACHE_TEMP_SOURCE);
689
690 // Success!
691 return 0;
692}