blob: 394c5841959b9c2ae0557fa1a89a661f82b7033d [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 Zongker6c770462009-07-22 18:27:31 -0700285// Write a memory buffer to target_mtd partition, a string of the form
286// "MTD:<partition>[:...]". Return 0 on success.
287int WriteToMTDPartition(unsigned char* data, size_t len,
288 const char* target_mtd) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700289 char* partition = strchr(target_mtd, ':');
290 if (partition == NULL) {
291 fprintf(stderr, "bad MTD target name \"%s\"\n", target_mtd);
292 return -1;
293 }
294 ++partition;
295 // Trim off anything after a colon, eg "MTD:boot:blah:blah:blah...".
296 // We want just the partition name "boot".
297 partition = strdup(partition);
298 char* end = strchr(partition, ':');
299 if (end != NULL)
300 *end = '\0';
301
Doug Zongker5da317e2009-06-02 13:38:17 -0700302 if (!mtd_partitions_scanned) {
303 mtd_scan_partitions();
304 mtd_partitions_scanned = 1;
305 }
306
307 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
308 if (mtd == NULL) {
309 fprintf(stderr, "mtd partition \"%s\" not found for writing\n", partition);
310 return -1;
311 }
312
313 MtdWriteContext* ctx = mtd_write_partition(mtd);
314 if (ctx == NULL) {
315 fprintf(stderr, "failed to init mtd partition \"%s\" for writing\n",
316 partition);
317 return -1;
318 }
319
Doug Zongker6c770462009-07-22 18:27:31 -0700320 size_t written = mtd_write_data(ctx, (char*)data, len);
321 if (written != len) {
322 fprintf(stderr, "only wrote %d of %d bytes to MTD %s\n",
323 written, len, partition);
324 mtd_write_close(ctx);
325 return -1;
Doug Zongker5da317e2009-06-02 13:38:17 -0700326 }
327
Doug Zongker5da317e2009-06-02 13:38:17 -0700328 if (mtd_erase_blocks(ctx, -1) < 0) {
329 fprintf(stderr, "error finishing mtd write of %s\n", partition);
330 mtd_write_close(ctx);
331 return -1;
332 }
333
334 if (mtd_write_close(ctx)) {
335 fprintf(stderr, "error closing mtd write of %s\n", partition);
336 return -1;
337 }
338
339 free(partition);
340 return 0;
341}
342
The Android Open Source Project88b60792009-03-03 19:28:42 -0800343
344// Take a string 'str' of 40 hex digits and parse it into the 20
345// byte array 'digest'. 'str' may contain only the digest or be of
346// the form "<digest>:<anything>". Return 0 on success, -1 on any
347// error.
348int ParseSha1(const char* str, uint8_t* digest) {
349 int i;
350 const char* ps = str;
351 uint8_t* pd = digest;
352 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
353 int digit;
354 if (*ps >= '0' && *ps <= '9') {
355 digit = *ps - '0';
356 } else if (*ps >= 'a' && *ps <= 'f') {
357 digit = *ps - 'a' + 10;
358 } else if (*ps >= 'A' && *ps <= 'F') {
359 digit = *ps - 'A' + 10;
360 } else {
361 return -1;
362 }
363 if (i % 2 == 0) {
364 *pd = digit << 4;
365 } else {
366 *pd |= digit;
367 ++pd;
368 }
369 }
370 if (*ps != '\0' && *ps != ':') return -1;
371 return 0;
372}
373
374// Parse arguments (which should be of the form "<sha1>" or
375// "<sha1>:<filename>" into the array *patches, returning the number
376// of Patch objects in *num_patches. Return 0 on success.
377int ParseShaArgs(int argc, char** argv, Patch** patches, int* num_patches) {
378 *num_patches = argc;
379 *patches = malloc(*num_patches * sizeof(Patch));
380
381 int i;
382 for (i = 0; i < *num_patches; ++i) {
383 if (ParseSha1(argv[i], (*patches)[i].sha1) != 0) {
384 fprintf(stderr, "failed to parse sha1 \"%s\"\n", argv[i]);
385 return -1;
386 }
387 if (argv[i][SHA_DIGEST_SIZE*2] == '\0') {
388 (*patches)[i].patch_filename = NULL;
389 } else if (argv[i][SHA_DIGEST_SIZE*2] == ':') {
390 (*patches)[i].patch_filename = argv[i] + (SHA_DIGEST_SIZE*2+1);
391 } else {
392 fprintf(stderr, "failed to parse filename \"%s\"\n", argv[i]);
393 return -1;
394 }
395 }
396
397 return 0;
398}
399
400// Search an array of Patch objects for one matching the given sha1.
401// Return the Patch object on success, or NULL if no match is found.
402const Patch* FindMatchingPatch(uint8_t* sha1, Patch* patches, int num_patches) {
403 int i;
404 for (i = 0; i < num_patches; ++i) {
405 if (memcmp(patches[i].sha1, sha1, SHA_DIGEST_SIZE) == 0) {
406 return patches+i;
407 }
408 }
409 return NULL;
410}
411
412// Returns 0 if the contents of the file (argv[2]) or the cached file
413// match any of the sha1's on the command line (argv[3:]). Returns
414// nonzero otherwise.
415int CheckMode(int argc, char** argv) {
416 if (argc < 3) {
417 fprintf(stderr, "no filename given\n");
418 return 2;
419 }
420
421 int num_patches;
422 Patch* patches;
423 if (ParseShaArgs(argc-3, argv+3, &patches, &num_patches) != 0) { return 1; }
424
425 FileContents file;
426 file.data = NULL;
427
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700428 // It's okay to specify no sha1s; the check will pass if the
429 // LoadFileContents is successful. (Useful for reading MTD
430 // partitions, where the filename encodes the sha1s; no need to
431 // check them twice.)
The Android Open Source Project88b60792009-03-03 19:28:42 -0800432 if (LoadFileContents(argv[2], &file) != 0 ||
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700433 (num_patches > 0 &&
434 FindMatchingPatch(file.sha1, patches, num_patches) == NULL)) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800435 fprintf(stderr, "file \"%s\" doesn't have any of expected "
436 "sha1 sums; checking cache\n", argv[2]);
437
438 free(file.data);
439
440 // If the source file is missing or corrupted, it might be because
441 // we were killed in the middle of patching it. A copy of it
442 // should have been made in CACHE_TEMP_SOURCE. If that file
443 // exists and matches the sha1 we're looking for, the check still
444 // passes.
445
446 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
447 fprintf(stderr, "failed to load cache file\n");
448 return 1;
449 }
450
451 if (FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
452 fprintf(stderr, "cache bits don't match any sha1 for \"%s\"\n",
453 argv[2]);
454 return 1;
455 }
456 }
457
458 free(file.data);
459 return 0;
460}
461
462int ShowLicenses() {
463 ShowBSDiffLicense();
464 return 0;
465}
466
Doug Zongker6c770462009-07-22 18:27:31 -0700467size_t FileSink(unsigned char* data, size_t len, void* token) {
468 return fwrite(data, 1, len, (FILE*)token);
469}
470
471typedef struct {
472 unsigned char* buffer;
473 size_t size;
474 size_t pos;
475} MemorySinkInfo;
476
477size_t MemorySink(unsigned char* data, size_t len, void* token) {
478 MemorySinkInfo* msi = (MemorySinkInfo*)token;
479 if (msi->size - msi->pos < len) {
480 return -1;
481 }
482 memcpy(msi->buffer + msi->pos, data, len);
483 msi->pos += len;
484 return len;
485}
486
The Android Open Source Project88b60792009-03-03 19:28:42 -0800487// Return the amount of free space (in bytes) on the filesystem
488// containing filename. filename must exist. Return -1 on error.
489size_t FreeSpaceForFile(const char* filename) {
490 struct statfs sf;
491 if (statfs(filename, &sf) != 0) {
492 fprintf(stderr, "failed to statfs %s: %s\n", filename, strerror(errno));
493 return -1;
494 }
495 return sf.f_bsize * sf.f_bfree;
496}
497
498// This program applies binary patches to files in a way that is safe
499// (the original file is not touched until we have the desired
500// replacement for it) and idempotent (it's okay to run this program
501// multiple times).
502//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700503// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
The Android Open Source Project88b60792009-03-03 19:28:42 -0800504// successfully.
505//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700506// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
507// bsdiff <patch> to <src-file> to produce a new file (the type of patch
The Android Open Source Project88b60792009-03-03 19:28:42 -0800508// is automatically detected from the file header). If that new
Doug Zongkeref85ea62009-05-08 13:46:25 -0700509// file has sha1 hash <tgt-sha1>, moves it to replace <tgt-file>, and
510// exits successfully. Note that if <src-file> and <tgt-file> are
511// not the same, <src-file> is NOT deleted on success. <tgt-file>
512// may be the string "-" to mean "the same as src-file".
The Android Open Source Project88b60792009-03-03 19:28:42 -0800513//
514// - otherwise, or if any error is encountered, exits with non-zero
515// status.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700516//
517// <src-file> (or <file> in check mode) may refer to an MTD partition
518// to read the source data. See the comments for the
519// LoadMTDContents() function above for the format of such a filename.
Doug Zongker5a790872009-06-12 09:42:43 -0700520//
521//
522// As you might guess from the arguments, this function used to be
523// main(); it was split out this way so applypatch could be built as a
524// static library and linked into other executables as well. In the
525// future only the library form will exist; we will not need to build
526// this as a standalone executable.
527//
528// The arguments to this function are just the command-line of the
529// standalone executable:
530//
531// <src-file> <tgt-file> <tgt-sha1> <tgt-size> [<src-sha1>:<patch> ...]
532// to apply a patch. Returns 0 on success, 1 on failure.
533//
534// "-c" <file> [<sha1> ...]
535// to check a file's contents against zero or more sha1s. Returns
536// 0 if it matches any of them, 1 if it doesn't.
537//
538// "-s" <bytes>
539// returns 0 if enough free space is available on /cache; 1 if it
540// does not.
541//
542// "-l"
543// shows open-source license information and returns 0.
544//
545// This function returns 2 if the arguments are not understood (in the
546// standalone executable, this causes the usage message to be
547// printed).
548//
549// TODO: make the interface more sensible for use as a library.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800550
Doug Zongker5a790872009-06-12 09:42:43 -0700551int applypatch(int argc, char** argv) {
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;
Doug Zongker6c770462009-07-22 18:27:31 -0700731 FILE* output = NULL;
732 MemorySinkInfo msi;
733 SinkFn sink = NULL;
734 void* token = NULL;
Doug Zongker5da317e2009-06-02 13:38:17 -0700735 if (strncmp(target_filename, "MTD:", 4) == 0) {
Doug Zongker6c770462009-07-22 18:27:31 -0700736 // We store the decoded output in memory.
737 msi.buffer = malloc(target_size);
738 if (msi.buffer == NULL) {
739 fprintf(stderr, "failed to alloc %ld bytes for output\n",
740 (long)target_size);
741 return 1;
742 }
743 msi.pos = 0;
744 msi.size = target_size;
745 sink = MemorySink;
746 token = &msi;
Doug Zongker5da317e2009-06-02 13:38:17 -0700747 } else {
748 // We write the decoded output to "<tgt-file>.patch".
749 outname = (char*)malloc(strlen(target_filename) + 10);
750 strcpy(outname, target_filename);
751 strcat(outname, ".patch");
Doug Zongker6c770462009-07-22 18:27:31 -0700752
753 output = fopen(outname, "wb");
754 if (output == NULL) {
755 fprintf(stderr, "failed to open output file %s: %s\n",
756 outname, strerror(errno));
757 return 1;
758 }
759 sink = FileSink;
760 token = output;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800761 }
762
763#define MAX_HEADER_LENGTH 8
764 unsigned char header[MAX_HEADER_LENGTH];
765 FILE* patchf = fopen(patch_filename, "rb");
766 if (patchf == NULL) {
767 fprintf(stderr, "failed to open patch file %s: %s\n",
768 patch_filename, strerror(errno));
769 return 1;
770 }
771 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
772 fclose(patchf);
773
774 SHA_CTX ctx;
775 SHA_init(&ctx);
776
777 if (header_bytes_read >= 4 &&
778 header[0] == 0xd6 && header[1] == 0xc3 &&
779 header[2] == 0xc4 && header[3] == 0) {
780 // xdelta3 patches begin "VCD" (with the high bits set) followed
781 // by a zero byte (the version number).
782 fprintf(stderr, "error: xdelta3 patches no longer supported\n");
783 return 1;
784 } else if (header_bytes_read >= 8 &&
785 memcmp(header, "BSDIFF40", 8) == 0) {
786 int result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
Doug Zongker6c770462009-07-22 18:27:31 -0700787 patch_filename, 0, sink, token, &ctx);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800788 if (result != 0) {
789 fprintf(stderr, "ApplyBSDiffPatch failed\n");
790 return result;
791 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700792 } else if (header_bytes_read >= 8 &&
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700793 memcmp(header, "IMGDIFF", 7) == 0 &&
794 (header[7] == '1' || header[7] == '2')) {
Doug Zongker02d444b2009-05-27 18:24:03 -0700795 int result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongker6c770462009-07-22 18:27:31 -0700796 patch_filename, sink, token, &ctx);
Doug Zongker02d444b2009-05-27 18:24:03 -0700797 if (result != 0) {
798 fprintf(stderr, "ApplyImagePatch failed\n");
799 return result;
800 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800801 } else {
Doug Zongker6b2bb3d2009-07-20 14:45:29 -0700802 fprintf(stderr, "Unknown patch file format\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800803 return 1;
804 }
805
Doug Zongker6c770462009-07-22 18:27:31 -0700806 if (output != NULL) {
807 fflush(output);
808 fsync(fileno(output));
809 fclose(output);
810 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800811
812 const uint8_t* current_target_sha1 = SHA_final(&ctx);
813 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
814 fprintf(stderr, "patch did not produce expected sha1\n");
815 return 1;
816 }
817
Doug Zongker6c770462009-07-22 18:27:31 -0700818 if (output == NULL) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700819 // Copy the temp file to the MTD partition.
Doug Zongker6c770462009-07-22 18:27:31 -0700820 if (WriteToMTDPartition(msi.buffer, msi.pos, target_filename) != 0) {
821 fprintf(stderr, "write of patched data to %s failed\n", target_filename);
Doug Zongker5da317e2009-06-02 13:38:17 -0700822 return 1;
823 }
Doug Zongker6c770462009-07-22 18:27:31 -0700824 free(msi.buffer);
Doug Zongker5da317e2009-06-02 13:38:17 -0700825 } else {
826 // Give the .patch file the same owner, group, and mode of the
827 // original source file.
828 if (chmod(outname, source_to_use->st.st_mode) != 0) {
829 fprintf(stderr, "chmod of \"%s\" failed: %s\n", outname, strerror(errno));
830 return 1;
831 }
832 if (chown(outname, source_to_use->st.st_uid,
833 source_to_use->st.st_gid) != 0) {
834 fprintf(stderr, "chown of \"%s\" failed: %s\n", outname, strerror(errno));
835 return 1;
836 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800837
Doug Zongker5da317e2009-06-02 13:38:17 -0700838 // Finally, rename the .patch file to replace the target file.
839 if (rename(outname, target_filename) != 0) {
840 fprintf(stderr, "rename of .patch to \"%s\" failed: %s\n",
841 target_filename, strerror(errno));
842 return 1;
843 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800844 }
845
846 // If this run of applypatch created the copy, and we're here, we
847 // can delete it.
848 if (made_copy) unlink(CACHE_TEMP_SOURCE);
849
850 // Success!
851 return 0;
852}