blob: 49ec97ff62f8f5f0539edfdd451c595938748fca [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
Doug Zongker5da317e2009-06-02 13:38:17 -070030int SaveFileContents(const char* filename, FileContents file);
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070031int LoadMTDContents(const char* filename, FileContents* file);
32int ParseSha1(const char* str, uint8_t* digest);
The Android Open Source Project88b60792009-03-03 19:28:42 -080033
Doug Zongker5da317e2009-06-02 13:38:17 -070034static int mtd_partitions_scanned = 0;
35
The Android Open Source Project88b60792009-03-03 19:28:42 -080036// Read a file into memory; store it and its associated metadata in
37// *file. Return 0 on success.
38int LoadFileContents(const char* filename, FileContents* file) {
39 file->data = NULL;
40
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070041 // A special 'filename' beginning with "MTD:" means to load the
42 // contents of an MTD partition.
43 if (strncmp(filename, "MTD:", 4) == 0) {
44 return LoadMTDContents(filename, file);
45 }
46
The Android Open Source Project88b60792009-03-03 19:28:42 -080047 if (stat(filename, &file->st) != 0) {
48 fprintf(stderr, "failed to stat \"%s\": %s\n", filename, strerror(errno));
49 return -1;
50 }
51
52 file->size = file->st.st_size;
53 file->data = malloc(file->size);
54
55 FILE* f = fopen(filename, "rb");
56 if (f == NULL) {
57 fprintf(stderr, "failed to open \"%s\": %s\n", filename, strerror(errno));
58 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070059 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080060 return -1;
61 }
62
63 size_t bytes_read = fread(file->data, 1, file->size, f);
64 if (bytes_read != file->size) {
65 fprintf(stderr, "short read of \"%s\" (%d bytes of %d)\n",
66 filename, bytes_read, file->size);
67 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070068 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080069 return -1;
70 }
71 fclose(f);
72
73 SHA(file->data, file->size, file->sha1);
74 return 0;
75}
76
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070077static size_t* size_array;
78// comparison function for qsort()ing an int array of indexes into
79// size_array[].
80static int compare_size_indices(const void* a, const void* b) {
81 int aa = *(int*)a;
82 int bb = *(int*)b;
83 if (size_array[aa] < size_array[bb]) {
84 return -1;
85 } else if (size_array[aa] > size_array[bb]) {
86 return 1;
87 } else {
88 return 0;
89 }
90}
91
92// Load the contents of an MTD partition into the provided
93// FileContents. filename should be a string of the form
94// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:...".
95// The smallest size_n bytes for which that prefix of the mtd contents
96// has the corresponding sha1 hash will be loaded. It is acceptable
97// for a size value to be repeated with different sha1s. Will return
98// 0 on success.
99//
100// This complexity is needed because if an OTA installation is
101// interrupted, the partition might contain either the source or the
102// target data, which might be of different lengths. We need to know
103// the length in order to read from MTD (there is no "end-of-file"
104// marker), so the caller must specify the possible lengths and the
105// hash of the data, and we'll do the load expecting to find one of
106// those hashes.
107int LoadMTDContents(const char* filename, FileContents* file) {
108 char* copy = strdup(filename);
109 const char* magic = strtok(copy, ":");
110 if (strcmp(magic, "MTD") != 0) {
111 fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
112 filename);
113 return -1;
114 }
115 const char* partition = strtok(NULL, ":");
116
117 int i;
118 int colons = 0;
119 for (i = 0; filename[i] != '\0'; ++i) {
120 if (filename[i] == ':') {
121 ++colons;
122 }
123 }
124 if (colons < 3 || colons%2 == 0) {
125 fprintf(stderr, "LoadMTDContents called with bad filename (%s)\n",
126 filename);
127 }
128
129 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
130 int* index = malloc(pairs * sizeof(int));
131 size_t* size = malloc(pairs * sizeof(size_t));
132 char** sha1sum = malloc(pairs * sizeof(char*));
133
134 for (i = 0; i < pairs; ++i) {
135 const char* size_str = strtok(NULL, ":");
136 size[i] = strtol(size_str, NULL, 10);
137 if (size[i] == 0) {
138 fprintf(stderr, "LoadMTDContents called with bad size (%s)\n", filename);
139 return -1;
140 }
141 sha1sum[i] = strtok(NULL, ":");
142 index[i] = i;
143 }
144
Doug Zongker5da317e2009-06-02 13:38:17 -0700145 // sort the index[] array so it indexes the pairs in order of
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700146 // increasing size.
147 size_array = size;
148 qsort(index, pairs, sizeof(int), compare_size_indices);
149
Doug Zongker5da317e2009-06-02 13:38:17 -0700150 if (!mtd_partitions_scanned) {
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700151 mtd_scan_partitions();
Doug Zongker5da317e2009-06-02 13:38:17 -0700152 mtd_partitions_scanned = 1;
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700153 }
154
155 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
156 if (mtd == NULL) {
157 fprintf(stderr, "mtd partition \"%s\" not found (loading %s)\n",
158 partition, filename);
159 return -1;
160 }
161
162 MtdReadContext* ctx = mtd_read_partition(mtd);
163 if (ctx == NULL) {
164 fprintf(stderr, "failed to initialize read of mtd partition \"%s\"\n",
165 partition);
166 return -1;
167 }
168
169 SHA_CTX sha_ctx;
170 SHA_init(&sha_ctx);
171 uint8_t parsed_sha[SHA_DIGEST_SIZE];
172
173 // allocate enough memory to hold the largest size.
174 file->data = malloc(size[index[pairs-1]]);
175 char* p = (char*)file->data;
176 file->size = 0; // # bytes read so far
177
178 for (i = 0; i < pairs; ++i) {
179 // Read enough additional bytes to get us up to the next size
180 // (again, we're trying the possibilities in order of increasing
181 // size).
182 size_t next = size[index[i]] - file->size;
183 size_t read = 0;
184 if (next > 0) {
185 read = mtd_read_data(ctx, p, next);
186 if (next != read) {
187 fprintf(stderr, "short read (%d bytes of %d) for partition \"%s\"\n",
188 read, next, partition);
189 free(file->data);
190 file->data = NULL;
191 return -1;
192 }
193 SHA_update(&sha_ctx, p, read);
194 file->size += read;
195 }
196
197 // Duplicate the SHA context and finalize the duplicate so we can
198 // check it against this pair's expected hash.
199 SHA_CTX temp_ctx;
200 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
201 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
202
203 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
204 fprintf(stderr, "failed to parse sha1 %s in %s\n",
205 sha1sum[index[i]], filename);
206 free(file->data);
207 file->data = NULL;
208 return -1;
209 }
210
211 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
212 // we have a match. stop reading the partition; we'll return
213 // the data we've read so far.
214 printf("mtd read matched size %d sha %s\n",
215 size[index[i]], sha1sum[index[i]]);
216 break;
217 }
218
219 p += read;
220 }
221
222 mtd_read_close(ctx);
223
224 if (i == pairs) {
225 // Ran off the end of the list of (size,sha1) pairs without
226 // finding a match.
227 fprintf(stderr, "contents of MTD partition \"%s\" didn't match %s\n",
228 partition, filename);
229 free(file->data);
230 file->data = NULL;
231 return -1;
232 }
233
234 const uint8_t* sha_final = SHA_final(&sha_ctx);
235 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
236 file->sha1[i] = sha_final[i];
237 }
238
Doug Zongker5da317e2009-06-02 13:38:17 -0700239 // Fake some stat() info.
240 file->st.st_mode = 0644;
241 file->st.st_uid = 0;
242 file->st.st_gid = 0;
243
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700244 free(copy);
245 free(index);
246 free(size);
247 free(sha1sum);
248
249 return 0;
250}
251
252
The Android Open Source Project88b60792009-03-03 19:28:42 -0800253// Save the contents of the given FileContents object under the given
254// filename. Return 0 on success.
255int SaveFileContents(const char* filename, FileContents file) {
256 FILE* f = fopen(filename, "wb");
257 if (f == NULL) {
258 fprintf(stderr, "failed to open \"%s\" for write: %s\n",
259 filename, strerror(errno));
260 return -1;
261 }
262
263 size_t bytes_written = fwrite(file.data, 1, file.size, f);
264 if (bytes_written != file.size) {
265 fprintf(stderr, "short write of \"%s\" (%d bytes of %d)\n",
266 filename, bytes_written, file.size);
267 return -1;
268 }
269 fflush(f);
270 fsync(fileno(f));
271 fclose(f);
272
273 if (chmod(filename, file.st.st_mode) != 0) {
274 fprintf(stderr, "chmod of \"%s\" failed: %s\n", filename, strerror(errno));
275 return -1;
276 }
277 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
278 fprintf(stderr, "chown of \"%s\" failed: %s\n", filename, strerror(errno));
279 return -1;
280 }
281
282 return 0;
283}
284
Doug Zongker5da317e2009-06-02 13:38:17 -0700285// Copy the contents of source_file to target_mtd partition, a string
286// of the form "MTD:<partition>[:...]". Return 0 on success.
287int CopyToMTDPartition(const char* source_file, const char* target_mtd) {
288 char* partition = strchr(target_mtd, ':');
289 if (partition == NULL) {
290 fprintf(stderr, "bad MTD target name \"%s\"\n", target_mtd);
291 return -1;
292 }
293 ++partition;
294 // Trim off anything after a colon, eg "MTD:boot:blah:blah:blah...".
295 // We want just the partition name "boot".
296 partition = strdup(partition);
297 char* end = strchr(partition, ':');
298 if (end != NULL)
299 *end = '\0';
300
301 FILE* f = fopen(source_file, "rb");
302 if (f == NULL) {
303 fprintf(stderr, "failed to open %s for reading: %s\n",
304 source_file, strerror(errno));
305 return -1;
306 }
307
308 if (!mtd_partitions_scanned) {
309 mtd_scan_partitions();
310 mtd_partitions_scanned = 1;
311 }
312
313 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
314 if (mtd == NULL) {
315 fprintf(stderr, "mtd partition \"%s\" not found for writing\n", partition);
316 return -1;
317 }
318
319 MtdWriteContext* ctx = mtd_write_partition(mtd);
320 if (ctx == NULL) {
321 fprintf(stderr, "failed to init mtd partition \"%s\" for writing\n",
322 partition);
323 return -1;
324 }
325
326 const int buffer_size = 4096;
327 char buffer[buffer_size];
328 size_t read;
329 while ((read = fread(buffer, 1, buffer_size, f)) > 0) {
330 size_t written = mtd_write_data(ctx, buffer, read);
331 if (written != read) {
332 fprintf(stderr, "only wrote %d of %d bytes to MTD %s\n",
333 written, read, partition);
334 mtd_write_close(ctx);
335 return -1;
336 }
337 }
338
339 fclose(f);
340 if (mtd_erase_blocks(ctx, -1) < 0) {
341 fprintf(stderr, "error finishing mtd write of %s\n", partition);
342 mtd_write_close(ctx);
343 return -1;
344 }
345
346 if (mtd_write_close(ctx)) {
347 fprintf(stderr, "error closing mtd write of %s\n", partition);
348 return -1;
349 }
350
351 free(partition);
352 return 0;
353}
354
The Android Open Source Project88b60792009-03-03 19:28:42 -0800355
356// Take a string 'str' of 40 hex digits and parse it into the 20
357// byte array 'digest'. 'str' may contain only the digest or be of
358// the form "<digest>:<anything>". Return 0 on success, -1 on any
359// error.
360int ParseSha1(const char* str, uint8_t* digest) {
361 int i;
362 const char* ps = str;
363 uint8_t* pd = digest;
364 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
365 int digit;
366 if (*ps >= '0' && *ps <= '9') {
367 digit = *ps - '0';
368 } else if (*ps >= 'a' && *ps <= 'f') {
369 digit = *ps - 'a' + 10;
370 } else if (*ps >= 'A' && *ps <= 'F') {
371 digit = *ps - 'A' + 10;
372 } else {
373 return -1;
374 }
375 if (i % 2 == 0) {
376 *pd = digit << 4;
377 } else {
378 *pd |= digit;
379 ++pd;
380 }
381 }
382 if (*ps != '\0' && *ps != ':') return -1;
383 return 0;
384}
385
386// Parse arguments (which should be of the form "<sha1>" or
387// "<sha1>:<filename>" into the array *patches, returning the number
388// of Patch objects in *num_patches. Return 0 on success.
389int ParseShaArgs(int argc, char** argv, Patch** patches, int* num_patches) {
390 *num_patches = argc;
391 *patches = malloc(*num_patches * sizeof(Patch));
392
393 int i;
394 for (i = 0; i < *num_patches; ++i) {
395 if (ParseSha1(argv[i], (*patches)[i].sha1) != 0) {
396 fprintf(stderr, "failed to parse sha1 \"%s\"\n", argv[i]);
397 return -1;
398 }
399 if (argv[i][SHA_DIGEST_SIZE*2] == '\0') {
400 (*patches)[i].patch_filename = NULL;
401 } else if (argv[i][SHA_DIGEST_SIZE*2] == ':') {
402 (*patches)[i].patch_filename = argv[i] + (SHA_DIGEST_SIZE*2+1);
403 } else {
404 fprintf(stderr, "failed to parse filename \"%s\"\n", argv[i]);
405 return -1;
406 }
407 }
408
409 return 0;
410}
411
412// Search an array of Patch objects for one matching the given sha1.
413// Return the Patch object on success, or NULL if no match is found.
414const Patch* FindMatchingPatch(uint8_t* sha1, Patch* patches, int num_patches) {
415 int i;
416 for (i = 0; i < num_patches; ++i) {
417 if (memcmp(patches[i].sha1, sha1, SHA_DIGEST_SIZE) == 0) {
418 return patches+i;
419 }
420 }
421 return NULL;
422}
423
424// Returns 0 if the contents of the file (argv[2]) or the cached file
425// match any of the sha1's on the command line (argv[3:]). Returns
426// nonzero otherwise.
427int CheckMode(int argc, char** argv) {
428 if (argc < 3) {
429 fprintf(stderr, "no filename given\n");
430 return 2;
431 }
432
433 int num_patches;
434 Patch* patches;
435 if (ParseShaArgs(argc-3, argv+3, &patches, &num_patches) != 0) { return 1; }
436
437 FileContents file;
438 file.data = NULL;
439
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700440 // It's okay to specify no sha1s; the check will pass if the
441 // LoadFileContents is successful. (Useful for reading MTD
442 // partitions, where the filename encodes the sha1s; no need to
443 // check them twice.)
The Android Open Source Project88b60792009-03-03 19:28:42 -0800444 if (LoadFileContents(argv[2], &file) != 0 ||
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700445 (num_patches > 0 &&
446 FindMatchingPatch(file.sha1, patches, num_patches) == NULL)) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800447 fprintf(stderr, "file \"%s\" doesn't have any of expected "
448 "sha1 sums; checking cache\n", argv[2]);
449
450 free(file.data);
451
452 // If the source file is missing or corrupted, it might be because
453 // we were killed in the middle of patching it. A copy of it
454 // should have been made in CACHE_TEMP_SOURCE. If that file
455 // exists and matches the sha1 we're looking for, the check still
456 // passes.
457
458 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
459 fprintf(stderr, "failed to load cache file\n");
460 return 1;
461 }
462
463 if (FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
464 fprintf(stderr, "cache bits don't match any sha1 for \"%s\"\n",
465 argv[2]);
466 return 1;
467 }
468 }
469
470 free(file.data);
471 return 0;
472}
473
474int ShowLicenses() {
475 ShowBSDiffLicense();
476 return 0;
477}
478
479// Return the amount of free space (in bytes) on the filesystem
480// containing filename. filename must exist. Return -1 on error.
481size_t FreeSpaceForFile(const char* filename) {
482 struct statfs sf;
483 if (statfs(filename, &sf) != 0) {
484 fprintf(stderr, "failed to statfs %s: %s\n", filename, strerror(errno));
485 return -1;
486 }
487 return sf.f_bsize * sf.f_bfree;
488}
489
490// This program applies binary patches to files in a way that is safe
491// (the original file is not touched until we have the desired
492// replacement for it) and idempotent (it's okay to run this program
493// multiple times).
494//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700495// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
The Android Open Source Project88b60792009-03-03 19:28:42 -0800496// successfully.
497//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700498// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
499// bsdiff <patch> to <src-file> to produce a new file (the type of patch
The Android Open Source Project88b60792009-03-03 19:28:42 -0800500// is automatically detected from the file header). If that new
Doug Zongkeref85ea62009-05-08 13:46:25 -0700501// file has sha1 hash <tgt-sha1>, moves it to replace <tgt-file>, and
502// exits successfully. Note that if <src-file> and <tgt-file> are
503// not the same, <src-file> is NOT deleted on success. <tgt-file>
504// may be the string "-" to mean "the same as src-file".
The Android Open Source Project88b60792009-03-03 19:28:42 -0800505//
506// - otherwise, or if any error is encountered, exits with non-zero
507// status.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700508//
509// <src-file> (or <file> in check mode) may refer to an MTD partition
510// to read the source data. See the comments for the
511// LoadMTDContents() function above for the format of such a filename.
Doug Zongker5a790872009-06-12 09:42:43 -0700512//
513//
514// As you might guess from the arguments, this function used to be
515// main(); it was split out this way so applypatch could be built as a
516// static library and linked into other executables as well. In the
517// future only the library form will exist; we will not need to build
518// this as a standalone executable.
519//
520// The arguments to this function are just the command-line of the
521// standalone executable:
522//
523// <src-file> <tgt-file> <tgt-sha1> <tgt-size> [<src-sha1>:<patch> ...]
524// to apply a patch. Returns 0 on success, 1 on failure.
525//
526// "-c" <file> [<sha1> ...]
527// to check a file's contents against zero or more sha1s. Returns
528// 0 if it matches any of them, 1 if it doesn't.
529//
530// "-s" <bytes>
531// returns 0 if enough free space is available on /cache; 1 if it
532// does not.
533//
534// "-l"
535// shows open-source license information and returns 0.
536//
537// This function returns 2 if the arguments are not understood (in the
538// standalone executable, this causes the usage message to be
539// printed).
540//
541// TODO: make the interface more sensible for use as a library.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800542
Doug Zongker5a790872009-06-12 09:42:43 -0700543int applypatch(int argc, char** argv) {
544
545 printf("applypatch argc %d\n", argc);
546 int xx;
547 for (xx = 0; xx < argc; ++xx) {
548 printf("%d %p %s\n", xx, argv[xx], argv[xx]);
549 fflush(stdout);
550 }
551
The Android Open Source Project88b60792009-03-03 19:28:42 -0800552 if (argc < 2) {
Doug Zongker5a790872009-06-12 09:42:43 -0700553 return 2;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800554 }
555
556 if (strncmp(argv[1], "-l", 3) == 0) {
557 return ShowLicenses();
558 }
559
560 if (strncmp(argv[1], "-c", 3) == 0) {
561 return CheckMode(argc, argv);
562 }
563
564 if (strncmp(argv[1], "-s", 3) == 0) {
565 if (argc != 3) {
Doug Zongker5a790872009-06-12 09:42:43 -0700566 return 2;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800567 }
568 size_t bytes = strtol(argv[2], NULL, 10);
569 if (MakeFreeSpaceOnCache(bytes) < 0) {
570 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
571 return 1;
572 } else {
573 return 0;
574 }
575 }
576
577 uint8_t target_sha1[SHA_DIGEST_SIZE];
578
579 const char* source_filename = argv[1];
Doug Zongkeref85ea62009-05-08 13:46:25 -0700580 const char* target_filename = argv[2];
581 if (target_filename[0] == '-' &&
582 target_filename[1] == '\0') {
583 target_filename = source_filename;
584 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800585
Doug Zongker5da317e2009-06-02 13:38:17 -0700586 if (ParseSha1(argv[3], target_sha1) != 0) {
Doug Zongkeref85ea62009-05-08 13:46:25 -0700587 fprintf(stderr, "failed to parse tgt-sha1 \"%s\"\n", argv[3]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800588 return 1;
589 }
590
Doug Zongkeref85ea62009-05-08 13:46:25 -0700591 unsigned long target_size = strtoul(argv[4], NULL, 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800592
593 int num_patches;
594 Patch* patches;
Doug Zongkeref85ea62009-05-08 13:46:25 -0700595 if (ParseShaArgs(argc-5, argv+5, &patches, &num_patches) < 0) { return 1; }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800596
597 FileContents copy_file;
598 FileContents source_file;
599 const char* source_patch_filename = NULL;
600 const char* copy_patch_filename = NULL;
601 int made_copy = 0;
602
Doug Zongkeref85ea62009-05-08 13:46:25 -0700603 // We try to load the target file into the source_file object.
604 if (LoadFileContents(target_filename, &source_file) == 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800605 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
606 // The early-exit case: the patch was already applied, this file
607 // has the desired hash, nothing for us to do.
608 fprintf(stderr, "\"%s\" is already target; no patch needed\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700609 target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800610 return 0;
611 }
Doug Zongkeref85ea62009-05-08 13:46:25 -0700612 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800613
Doug Zongkeref85ea62009-05-08 13:46:25 -0700614 if (source_file.data == NULL ||
615 (target_filename != source_filename &&
616 strcmp(target_filename, source_filename) != 0)) {
617 // Need to load the source file: either we failed to load the
618 // target file, or we did but it's different from the source file.
619 free(source_file.data);
620 LoadFileContents(source_filename, &source_file);
621 }
622
623 if (source_file.data != NULL) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800624 const Patch* to_use =
625 FindMatchingPatch(source_file.sha1, patches, num_patches);
626 if (to_use != NULL) {
627 source_patch_filename = to_use->patch_filename;
628 }
629 }
630
631 if (source_patch_filename == NULL) {
632 free(source_file.data);
633 fprintf(stderr, "source file is bad; trying copy\n");
634
635 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
636 // fail.
637 fprintf(stderr, "failed to read copy file\n");
638 return 1;
639 }
640
641 const Patch* to_use =
642 FindMatchingPatch(copy_file.sha1, patches, num_patches);
643 if (to_use != NULL) {
644 copy_patch_filename = to_use->patch_filename;
645 }
646
647 if (copy_patch_filename == NULL) {
648 // fail.
649 fprintf(stderr, "copy file doesn't match source SHA-1s either\n");
650 return 1;
651 }
652 }
653
Doug Zongker5da317e2009-06-02 13:38:17 -0700654 // Is there enough room in the target filesystem to hold the patched
655 // file?
The Android Open Source Project88b60792009-03-03 19:28:42 -0800656
Doug Zongker5da317e2009-06-02 13:38:17 -0700657 if (strncmp(target_filename, "MTD:", 4) == 0) {
658 // If the target is an MTD partition, we're actually going to
659 // write the output to /tmp and then copy it to the partition.
660 // statfs() always returns 0 blocks free for /tmp, so instead
661 // we'll just assume that /tmp has enough space to hold the file.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700662
Doug Zongker5da317e2009-06-02 13:38:17 -0700663 // We still write the original source to cache, in case the MTD
664 // write is interrupted.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800665 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
666 fprintf(stderr, "not enough free space on /cache\n");
667 return 1;
668 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800669 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
670 fprintf(stderr, "failed to back up source file\n");
671 return 1;
672 }
673 made_copy = 1;
Doug Zongker5da317e2009-06-02 13:38:17 -0700674 } else {
675 // assume that target_filename (eg "/system/app/Foo.apk") is located
676 // on the same filesystem as its top-level directory ("/system").
677 // We need something that exists for calling statfs().
678 char* target_fs = strdup(target_filename);
679 char* slash = strchr(target_fs+1, '/');
680 if (slash != NULL) {
681 *slash = '\0';
682 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800683
Doug Zongkeref85ea62009-05-08 13:46:25 -0700684 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker5da317e2009-06-02 13:38:17 -0700685 int enough_space =
686 free_space > (target_size * 3 / 2); // 50% margin of error
687 printf("target %ld bytes; free space %ld bytes; enough %d\n",
688 (long)target_size, (long)free_space, enough_space);
689
690 if (!enough_space && source_patch_filename != NULL) {
691 // Using the original source, but not enough free space. First
692 // copy the source file to cache, then delete it from the original
693 // location.
694
695 if (strncmp(source_filename, "MTD:", 4) == 0) {
696 // It's impossible to free space on the target filesystem by
697 // deleting the source if the source is an MTD partition. If
698 // we're ever in a state where we need to do this, fail.
699 fprintf(stderr, "not enough free space for target but source is MTD\n");
700 return 1;
701 }
702
703 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
704 fprintf(stderr, "not enough free space on /cache\n");
705 return 1;
706 }
707
708 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
709 fprintf(stderr, "failed to back up source file\n");
710 return 1;
711 }
712 made_copy = 1;
713 unlink(source_filename);
714
715 size_t free_space = FreeSpaceForFile(target_fs);
716 printf("(now %ld bytes free for target)\n", (long)free_space);
717 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800718 }
719
720 FileContents* source_to_use;
721 const char* patch_filename;
722 if (source_patch_filename != NULL) {
723 source_to_use = &source_file;
724 patch_filename = source_patch_filename;
725 } else {
726 source_to_use = &copy_file;
727 patch_filename = copy_patch_filename;
728 }
729
Doug Zongker5da317e2009-06-02 13:38:17 -0700730 char* outname = NULL;
731 if (strncmp(target_filename, "MTD:", 4) == 0) {
732 outname = MTD_TARGET_TEMP_FILE;
733 } else {
734 // We write the decoded output to "<tgt-file>.patch".
735 outname = (char*)malloc(strlen(target_filename) + 10);
736 strcpy(outname, target_filename);
737 strcat(outname, ".patch");
738 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800739 FILE* output = fopen(outname, "wb");
740 if (output == NULL) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700741 fprintf(stderr, "failed to open output file %s: %s\n",
742 outname, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800743 return 1;
744 }
745
746#define MAX_HEADER_LENGTH 8
747 unsigned char header[MAX_HEADER_LENGTH];
748 FILE* patchf = fopen(patch_filename, "rb");
749 if (patchf == NULL) {
750 fprintf(stderr, "failed to open patch file %s: %s\n",
751 patch_filename, strerror(errno));
752 return 1;
753 }
754 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
755 fclose(patchf);
756
757 SHA_CTX ctx;
758 SHA_init(&ctx);
759
760 if (header_bytes_read >= 4 &&
761 header[0] == 0xd6 && header[1] == 0xc3 &&
762 header[2] == 0xc4 && header[3] == 0) {
763 // xdelta3 patches begin "VCD" (with the high bits set) followed
764 // by a zero byte (the version number).
765 fprintf(stderr, "error: xdelta3 patches no longer supported\n");
766 return 1;
767 } else if (header_bytes_read >= 8 &&
768 memcmp(header, "BSDIFF40", 8) == 0) {
769 int result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
Doug Zongker02d444b2009-05-27 18:24:03 -0700770 patch_filename, 0, output, &ctx);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800771 if (result != 0) {
772 fprintf(stderr, "ApplyBSDiffPatch failed\n");
773 return result;
774 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700775 } else if (header_bytes_read >= 8 &&
776 memcmp(header, "IMGDIFF1", 8) == 0) {
777 int result = ApplyImagePatch(source_to_use->data, source_to_use->size,
778 patch_filename, output, &ctx);
779 if (result != 0) {
780 fprintf(stderr, "ApplyImagePatch failed\n");
781 return result;
782 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800783 } else {
784 fprintf(stderr, "Unknown patch file format");
785 return 1;
786 }
787
788 fflush(output);
789 fsync(fileno(output));
790 fclose(output);
791
792 const uint8_t* current_target_sha1 = SHA_final(&ctx);
793 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
794 fprintf(stderr, "patch did not produce expected sha1\n");
795 return 1;
796 }
797
Doug Zongker5da317e2009-06-02 13:38:17 -0700798 if (strcmp(outname, MTD_TARGET_TEMP_FILE) == 0) {
799 // Copy the temp file to the MTD partition.
800 if (CopyToMTDPartition(outname, target_filename) != 0) {
801 fprintf(stderr, "copy of %s to %s failed\n", outname, target_filename);
802 return 1;
803 }
804 unlink(outname);
805 } else {
806 // Give the .patch file the same owner, group, and mode of the
807 // original source file.
808 if (chmod(outname, source_to_use->st.st_mode) != 0) {
809 fprintf(stderr, "chmod of \"%s\" failed: %s\n", outname, strerror(errno));
810 return 1;
811 }
812 if (chown(outname, source_to_use->st.st_uid,
813 source_to_use->st.st_gid) != 0) {
814 fprintf(stderr, "chown of \"%s\" failed: %s\n", outname, strerror(errno));
815 return 1;
816 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800817
Doug Zongker5da317e2009-06-02 13:38:17 -0700818 // Finally, rename the .patch file to replace the target file.
819 if (rename(outname, target_filename) != 0) {
820 fprintf(stderr, "rename of .patch to \"%s\" failed: %s\n",
821 target_filename, strerror(errno));
822 return 1;
823 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800824 }
825
826 // If this run of applypatch created the copy, and we're here, we
827 // can delete it.
828 if (made_copy) unlink(CACHE_TEMP_SOURCE);
829
830 // Success!
831 return 0;
832}