blob: db4c30b82c90125d004368fb8e9dad4a924b03cd [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.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800512
513int main(int argc, char** argv) {
514 if (argc < 2) {
515 usage:
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700516 fprintf(stderr,
517 "usage: %s <src-file> <tgt-file> <tgt-sha1> <tgt-size> "
518 "[<src-sha1>:<patch> ...]\n"
519 " or %s -c <file> [<sha1> ...]\n"
520 " or %s -s <bytes>\n"
521 " or %s -l\n"
522 "\n"
Doug Zongker5da317e2009-06-02 13:38:17 -0700523 "Filenames may be of the form\n"
524 " MTD:<partition>:<len_1>:<sha1_1>:<len_2>:<sha1_2>"
525 ":...:<backup-file>\n"
526 "to specify reading from or writing to an MTD partition.\n\n",
The Android Open Source Project88b60792009-03-03 19:28:42 -0800527 argv[0], argv[0], argv[0], argv[0]);
528 return 1;
529 }
530
531 if (strncmp(argv[1], "-l", 3) == 0) {
532 return ShowLicenses();
533 }
534
535 if (strncmp(argv[1], "-c", 3) == 0) {
536 return CheckMode(argc, argv);
537 }
538
539 if (strncmp(argv[1], "-s", 3) == 0) {
540 if (argc != 3) {
541 goto usage;
542 }
543 size_t bytes = strtol(argv[2], NULL, 10);
544 if (MakeFreeSpaceOnCache(bytes) < 0) {
545 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
546 return 1;
547 } else {
548 return 0;
549 }
550 }
551
552 uint8_t target_sha1[SHA_DIGEST_SIZE];
553
554 const char* source_filename = argv[1];
Doug Zongkeref85ea62009-05-08 13:46:25 -0700555 const char* target_filename = argv[2];
556 if (target_filename[0] == '-' &&
557 target_filename[1] == '\0') {
558 target_filename = source_filename;
559 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800560
Doug Zongker5da317e2009-06-02 13:38:17 -0700561 if (ParseSha1(argv[3], target_sha1) != 0) {
Doug Zongkeref85ea62009-05-08 13:46:25 -0700562 fprintf(stderr, "failed to parse tgt-sha1 \"%s\"\n", argv[3]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800563 return 1;
564 }
565
Doug Zongkeref85ea62009-05-08 13:46:25 -0700566 unsigned long target_size = strtoul(argv[4], NULL, 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800567
568 int num_patches;
569 Patch* patches;
Doug Zongkeref85ea62009-05-08 13:46:25 -0700570 if (ParseShaArgs(argc-5, argv+5, &patches, &num_patches) < 0) { return 1; }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800571
572 FileContents copy_file;
573 FileContents source_file;
574 const char* source_patch_filename = NULL;
575 const char* copy_patch_filename = NULL;
576 int made_copy = 0;
577
Doug Zongkeref85ea62009-05-08 13:46:25 -0700578 // We try to load the target file into the source_file object.
579 if (LoadFileContents(target_filename, &source_file) == 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800580 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
581 // The early-exit case: the patch was already applied, this file
582 // has the desired hash, nothing for us to do.
583 fprintf(stderr, "\"%s\" is already target; no patch needed\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700584 target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800585 return 0;
586 }
Doug Zongkeref85ea62009-05-08 13:46:25 -0700587 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800588
Doug Zongkeref85ea62009-05-08 13:46:25 -0700589 if (source_file.data == NULL ||
590 (target_filename != source_filename &&
591 strcmp(target_filename, source_filename) != 0)) {
592 // Need to load the source file: either we failed to load the
593 // target file, or we did but it's different from the source file.
594 free(source_file.data);
595 LoadFileContents(source_filename, &source_file);
596 }
597
598 if (source_file.data != NULL) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800599 const Patch* to_use =
600 FindMatchingPatch(source_file.sha1, patches, num_patches);
601 if (to_use != NULL) {
602 source_patch_filename = to_use->patch_filename;
603 }
604 }
605
606 if (source_patch_filename == NULL) {
607 free(source_file.data);
608 fprintf(stderr, "source file is bad; trying copy\n");
609
610 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
611 // fail.
612 fprintf(stderr, "failed to read copy file\n");
613 return 1;
614 }
615
616 const Patch* to_use =
617 FindMatchingPatch(copy_file.sha1, patches, num_patches);
618 if (to_use != NULL) {
619 copy_patch_filename = to_use->patch_filename;
620 }
621
622 if (copy_patch_filename == NULL) {
623 // fail.
624 fprintf(stderr, "copy file doesn't match source SHA-1s either\n");
625 return 1;
626 }
627 }
628
Doug Zongker5da317e2009-06-02 13:38:17 -0700629 // Is there enough room in the target filesystem to hold the patched
630 // file?
The Android Open Source Project88b60792009-03-03 19:28:42 -0800631
Doug Zongker5da317e2009-06-02 13:38:17 -0700632 if (strncmp(target_filename, "MTD:", 4) == 0) {
633 // If the target is an MTD partition, we're actually going to
634 // write the output to /tmp and then copy it to the partition.
635 // statfs() always returns 0 blocks free for /tmp, so instead
636 // we'll just assume that /tmp has enough space to hold the file.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700637
Doug Zongker5da317e2009-06-02 13:38:17 -0700638 // We still write the original source to cache, in case the MTD
639 // write is interrupted.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800640 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
641 fprintf(stderr, "not enough free space on /cache\n");
642 return 1;
643 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800644 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
645 fprintf(stderr, "failed to back up source file\n");
646 return 1;
647 }
648 made_copy = 1;
Doug Zongker5da317e2009-06-02 13:38:17 -0700649 } else {
650 // assume that target_filename (eg "/system/app/Foo.apk") is located
651 // on the same filesystem as its top-level directory ("/system").
652 // We need something that exists for calling statfs().
653 char* target_fs = strdup(target_filename);
654 char* slash = strchr(target_fs+1, '/');
655 if (slash != NULL) {
656 *slash = '\0';
657 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800658
Doug Zongkeref85ea62009-05-08 13:46:25 -0700659 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker5da317e2009-06-02 13:38:17 -0700660 int enough_space =
661 free_space > (target_size * 3 / 2); // 50% margin of error
662 printf("target %ld bytes; free space %ld bytes; enough %d\n",
663 (long)target_size, (long)free_space, enough_space);
664
665 if (!enough_space && source_patch_filename != NULL) {
666 // Using the original source, but not enough free space. First
667 // copy the source file to cache, then delete it from the original
668 // location.
669
670 if (strncmp(source_filename, "MTD:", 4) == 0) {
671 // It's impossible to free space on the target filesystem by
672 // deleting the source if the source is an MTD partition. If
673 // we're ever in a state where we need to do this, fail.
674 fprintf(stderr, "not enough free space for target but source is MTD\n");
675 return 1;
676 }
677
678 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
679 fprintf(stderr, "not enough free space on /cache\n");
680 return 1;
681 }
682
683 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
684 fprintf(stderr, "failed to back up source file\n");
685 return 1;
686 }
687 made_copy = 1;
688 unlink(source_filename);
689
690 size_t free_space = FreeSpaceForFile(target_fs);
691 printf("(now %ld bytes free for target)\n", (long)free_space);
692 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800693 }
694
695 FileContents* source_to_use;
696 const char* patch_filename;
697 if (source_patch_filename != NULL) {
698 source_to_use = &source_file;
699 patch_filename = source_patch_filename;
700 } else {
701 source_to_use = &copy_file;
702 patch_filename = copy_patch_filename;
703 }
704
Doug Zongker5da317e2009-06-02 13:38:17 -0700705 char* outname = NULL;
706 if (strncmp(target_filename, "MTD:", 4) == 0) {
707 outname = MTD_TARGET_TEMP_FILE;
708 } else {
709 // We write the decoded output to "<tgt-file>.patch".
710 outname = (char*)malloc(strlen(target_filename) + 10);
711 strcpy(outname, target_filename);
712 strcat(outname, ".patch");
713 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800714 FILE* output = fopen(outname, "wb");
715 if (output == NULL) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700716 fprintf(stderr, "failed to open output file %s: %s\n",
717 outname, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800718 return 1;
719 }
720
721#define MAX_HEADER_LENGTH 8
722 unsigned char header[MAX_HEADER_LENGTH];
723 FILE* patchf = fopen(patch_filename, "rb");
724 if (patchf == NULL) {
725 fprintf(stderr, "failed to open patch file %s: %s\n",
726 patch_filename, strerror(errno));
727 return 1;
728 }
729 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
730 fclose(patchf);
731
732 SHA_CTX ctx;
733 SHA_init(&ctx);
734
735 if (header_bytes_read >= 4 &&
736 header[0] == 0xd6 && header[1] == 0xc3 &&
737 header[2] == 0xc4 && header[3] == 0) {
738 // xdelta3 patches begin "VCD" (with the high bits set) followed
739 // by a zero byte (the version number).
740 fprintf(stderr, "error: xdelta3 patches no longer supported\n");
741 return 1;
742 } else if (header_bytes_read >= 8 &&
743 memcmp(header, "BSDIFF40", 8) == 0) {
744 int result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
Doug Zongker02d444b2009-05-27 18:24:03 -0700745 patch_filename, 0, output, &ctx);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800746 if (result != 0) {
747 fprintf(stderr, "ApplyBSDiffPatch failed\n");
748 return result;
749 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700750 } else if (header_bytes_read >= 8 &&
751 memcmp(header, "IMGDIFF1", 8) == 0) {
752 int result = ApplyImagePatch(source_to_use->data, source_to_use->size,
753 patch_filename, output, &ctx);
754 if (result != 0) {
755 fprintf(stderr, "ApplyImagePatch failed\n");
756 return result;
757 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800758 } else {
759 fprintf(stderr, "Unknown patch file format");
760 return 1;
761 }
762
763 fflush(output);
764 fsync(fileno(output));
765 fclose(output);
766
767 const uint8_t* current_target_sha1 = SHA_final(&ctx);
768 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
769 fprintf(stderr, "patch did not produce expected sha1\n");
770 return 1;
771 }
772
Doug Zongker5da317e2009-06-02 13:38:17 -0700773 if (strcmp(outname, MTD_TARGET_TEMP_FILE) == 0) {
774 // Copy the temp file to the MTD partition.
775 if (CopyToMTDPartition(outname, target_filename) != 0) {
776 fprintf(stderr, "copy of %s to %s failed\n", outname, target_filename);
777 return 1;
778 }
779 unlink(outname);
780 } else {
781 // Give the .patch file the same owner, group, and mode of the
782 // original source file.
783 if (chmod(outname, source_to_use->st.st_mode) != 0) {
784 fprintf(stderr, "chmod of \"%s\" failed: %s\n", outname, strerror(errno));
785 return 1;
786 }
787 if (chown(outname, source_to_use->st.st_uid,
788 source_to_use->st.st_gid) != 0) {
789 fprintf(stderr, "chown of \"%s\" failed: %s\n", outname, strerror(errno));
790 return 1;
791 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800792
Doug Zongker5da317e2009-06-02 13:38:17 -0700793 // Finally, rename the .patch file to replace the target file.
794 if (rename(outname, target_filename) != 0) {
795 fprintf(stderr, "rename of .patch to \"%s\" failed: %s\n",
796 target_filename, strerror(errno));
797 return 1;
798 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800799 }
800
801 // If this run of applypatch created the copy, and we're here, we
802 // can delete it.
803 if (made_copy) unlink(CACHE_TEMP_SOURCE);
804
805 // Success!
806 return 0;
807}