blob: b9f28a2f44707b92c52e34d75fd831e83e22e213 [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"
28
29// Read a file into memory; store it and its associated metadata in
30// *file. Return 0 on success.
31int LoadFileContents(const char* filename, FileContents* file) {
32 file->data = NULL;
33
34 if (stat(filename, &file->st) != 0) {
35 fprintf(stderr, "failed to stat \"%s\": %s\n", filename, strerror(errno));
36 return -1;
37 }
38
39 file->size = file->st.st_size;
40 file->data = malloc(file->size);
41
42 FILE* f = fopen(filename, "rb");
43 if (f == NULL) {
44 fprintf(stderr, "failed to open \"%s\": %s\n", filename, strerror(errno));
45 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070046 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080047 return -1;
48 }
49
50 size_t bytes_read = fread(file->data, 1, file->size, f);
51 if (bytes_read != file->size) {
52 fprintf(stderr, "short read of \"%s\" (%d bytes of %d)\n",
53 filename, bytes_read, file->size);
54 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070055 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080056 return -1;
57 }
58 fclose(f);
59
60 SHA(file->data, file->size, file->sha1);
61 return 0;
62}
63
64// Save the contents of the given FileContents object under the given
65// filename. Return 0 on success.
66int SaveFileContents(const char* filename, FileContents file) {
67 FILE* f = fopen(filename, "wb");
68 if (f == NULL) {
69 fprintf(stderr, "failed to open \"%s\" for write: %s\n",
70 filename, strerror(errno));
71 return -1;
72 }
73
74 size_t bytes_written = fwrite(file.data, 1, file.size, f);
75 if (bytes_written != file.size) {
76 fprintf(stderr, "short write of \"%s\" (%d bytes of %d)\n",
77 filename, bytes_written, file.size);
78 return -1;
79 }
80 fflush(f);
81 fsync(fileno(f));
82 fclose(f);
83
84 if (chmod(filename, file.st.st_mode) != 0) {
85 fprintf(stderr, "chmod of \"%s\" failed: %s\n", filename, strerror(errno));
86 return -1;
87 }
88 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
89 fprintf(stderr, "chown of \"%s\" failed: %s\n", filename, strerror(errno));
90 return -1;
91 }
92
93 return 0;
94}
95
96
97// Take a string 'str' of 40 hex digits and parse it into the 20
98// byte array 'digest'. 'str' may contain only the digest or be of
99// the form "<digest>:<anything>". Return 0 on success, -1 on any
100// error.
101int ParseSha1(const char* str, uint8_t* digest) {
102 int i;
103 const char* ps = str;
104 uint8_t* pd = digest;
105 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
106 int digit;
107 if (*ps >= '0' && *ps <= '9') {
108 digit = *ps - '0';
109 } else if (*ps >= 'a' && *ps <= 'f') {
110 digit = *ps - 'a' + 10;
111 } else if (*ps >= 'A' && *ps <= 'F') {
112 digit = *ps - 'A' + 10;
113 } else {
114 return -1;
115 }
116 if (i % 2 == 0) {
117 *pd = digit << 4;
118 } else {
119 *pd |= digit;
120 ++pd;
121 }
122 }
123 if (*ps != '\0' && *ps != ':') return -1;
124 return 0;
125}
126
127// Parse arguments (which should be of the form "<sha1>" or
128// "<sha1>:<filename>" into the array *patches, returning the number
129// of Patch objects in *num_patches. Return 0 on success.
130int ParseShaArgs(int argc, char** argv, Patch** patches, int* num_patches) {
131 *num_patches = argc;
132 *patches = malloc(*num_patches * sizeof(Patch));
133
134 int i;
135 for (i = 0; i < *num_patches; ++i) {
136 if (ParseSha1(argv[i], (*patches)[i].sha1) != 0) {
137 fprintf(stderr, "failed to parse sha1 \"%s\"\n", argv[i]);
138 return -1;
139 }
140 if (argv[i][SHA_DIGEST_SIZE*2] == '\0') {
141 (*patches)[i].patch_filename = NULL;
142 } else if (argv[i][SHA_DIGEST_SIZE*2] == ':') {
143 (*patches)[i].patch_filename = argv[i] + (SHA_DIGEST_SIZE*2+1);
144 } else {
145 fprintf(stderr, "failed to parse filename \"%s\"\n", argv[i]);
146 return -1;
147 }
148 }
149
150 return 0;
151}
152
153// Search an array of Patch objects for one matching the given sha1.
154// Return the Patch object on success, or NULL if no match is found.
155const Patch* FindMatchingPatch(uint8_t* sha1, Patch* patches, int num_patches) {
156 int i;
157 for (i = 0; i < num_patches; ++i) {
158 if (memcmp(patches[i].sha1, sha1, SHA_DIGEST_SIZE) == 0) {
159 return patches+i;
160 }
161 }
162 return NULL;
163}
164
165// Returns 0 if the contents of the file (argv[2]) or the cached file
166// match any of the sha1's on the command line (argv[3:]). Returns
167// nonzero otherwise.
168int CheckMode(int argc, char** argv) {
169 if (argc < 3) {
170 fprintf(stderr, "no filename given\n");
171 return 2;
172 }
173
174 int num_patches;
175 Patch* patches;
176 if (ParseShaArgs(argc-3, argv+3, &patches, &num_patches) != 0) { return 1; }
177
178 FileContents file;
179 file.data = NULL;
180
181 if (LoadFileContents(argv[2], &file) != 0 ||
182 FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
183 fprintf(stderr, "file \"%s\" doesn't have any of expected "
184 "sha1 sums; checking cache\n", argv[2]);
185
186 free(file.data);
187
188 // If the source file is missing or corrupted, it might be because
189 // we were killed in the middle of patching it. A copy of it
190 // should have been made in CACHE_TEMP_SOURCE. If that file
191 // exists and matches the sha1 we're looking for, the check still
192 // passes.
193
194 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
195 fprintf(stderr, "failed to load cache file\n");
196 return 1;
197 }
198
199 if (FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
200 fprintf(stderr, "cache bits don't match any sha1 for \"%s\"\n",
201 argv[2]);
202 return 1;
203 }
204 }
205
206 free(file.data);
207 return 0;
208}
209
210int ShowLicenses() {
211 ShowBSDiffLicense();
212 return 0;
213}
214
215// Return the amount of free space (in bytes) on the filesystem
216// containing filename. filename must exist. Return -1 on error.
217size_t FreeSpaceForFile(const char* filename) {
218 struct statfs sf;
219 if (statfs(filename, &sf) != 0) {
220 fprintf(stderr, "failed to statfs %s: %s\n", filename, strerror(errno));
221 return -1;
222 }
223 return sf.f_bsize * sf.f_bfree;
224}
225
226// This program applies binary patches to files in a way that is safe
227// (the original file is not touched until we have the desired
228// replacement for it) and idempotent (it's okay to run this program
229// multiple times).
230//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700231// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
The Android Open Source Project88b60792009-03-03 19:28:42 -0800232// successfully.
233//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700234// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
235// bsdiff <patch> to <src-file> to produce a new file (the type of patch
The Android Open Source Project88b60792009-03-03 19:28:42 -0800236// is automatically detected from the file header). If that new
Doug Zongkeref85ea62009-05-08 13:46:25 -0700237// file has sha1 hash <tgt-sha1>, moves it to replace <tgt-file>, and
238// exits successfully. Note that if <src-file> and <tgt-file> are
239// not the same, <src-file> is NOT deleted on success. <tgt-file>
240// may be the string "-" to mean "the same as src-file".
The Android Open Source Project88b60792009-03-03 19:28:42 -0800241//
242// - otherwise, or if any error is encountered, exits with non-zero
243// status.
244
245int main(int argc, char** argv) {
246 if (argc < 2) {
247 usage:
Doug Zongkeref85ea62009-05-08 13:46:25 -0700248 fprintf(stderr, "usage: %s <src-file> <tgt-file> <tgt-sha1> <tgt-size> [<src-sha1>:<patch> ...]\n"
The Android Open Source Project88b60792009-03-03 19:28:42 -0800249 " or %s -c <file> [<sha1> ...]\n"
250 " or %s -s <bytes>\n"
251 " or %s -l\n",
252 argv[0], argv[0], argv[0], argv[0]);
253 return 1;
254 }
255
256 if (strncmp(argv[1], "-l", 3) == 0) {
257 return ShowLicenses();
258 }
259
260 if (strncmp(argv[1], "-c", 3) == 0) {
261 return CheckMode(argc, argv);
262 }
263
264 if (strncmp(argv[1], "-s", 3) == 0) {
265 if (argc != 3) {
266 goto usage;
267 }
268 size_t bytes = strtol(argv[2], NULL, 10);
269 if (MakeFreeSpaceOnCache(bytes) < 0) {
270 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
271 return 1;
272 } else {
273 return 0;
274 }
275 }
276
277 uint8_t target_sha1[SHA_DIGEST_SIZE];
278
279 const char* source_filename = argv[1];
Doug Zongkeref85ea62009-05-08 13:46:25 -0700280 const char* target_filename = argv[2];
281 if (target_filename[0] == '-' &&
282 target_filename[1] == '\0') {
283 target_filename = source_filename;
284 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800285
Doug Zongkeref85ea62009-05-08 13:46:25 -0700286 // assume that target_filename (eg "/system/app/Foo.apk") is located
The Android Open Source Project88b60792009-03-03 19:28:42 -0800287 // on the same filesystem as its top-level directory ("/system").
288 // We need something that exists for calling statfs().
Doug Zongkeref85ea62009-05-08 13:46:25 -0700289 char* target_fs = strdup(target_filename);
290 char* slash = strchr(target_fs+1, '/');
The Android Open Source Project88b60792009-03-03 19:28:42 -0800291 if (slash != NULL) {
292 *slash = '\0';
293 }
294
Doug Zongkeref85ea62009-05-08 13:46:25 -0700295 if (ParseSha1(argv[3], target_sha1) != 0) {
296 fprintf(stderr, "failed to parse tgt-sha1 \"%s\"\n", argv[3]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800297 return 1;
298 }
299
Doug Zongkeref85ea62009-05-08 13:46:25 -0700300 unsigned long target_size = strtoul(argv[4], NULL, 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800301
302 int num_patches;
303 Patch* patches;
Doug Zongkeref85ea62009-05-08 13:46:25 -0700304 if (ParseShaArgs(argc-5, argv+5, &patches, &num_patches) < 0) { return 1; }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800305
306 FileContents copy_file;
307 FileContents source_file;
308 const char* source_patch_filename = NULL;
309 const char* copy_patch_filename = NULL;
310 int made_copy = 0;
311
Doug Zongkeref85ea62009-05-08 13:46:25 -0700312 // We try to load the target file into the source_file object.
313 if (LoadFileContents(target_filename, &source_file) == 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800314 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
315 // The early-exit case: the patch was already applied, this file
316 // has the desired hash, nothing for us to do.
317 fprintf(stderr, "\"%s\" is already target; no patch needed\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700318 target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800319 return 0;
320 }
Doug Zongkeref85ea62009-05-08 13:46:25 -0700321 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800322
Doug Zongkeref85ea62009-05-08 13:46:25 -0700323 if (source_file.data == NULL ||
324 (target_filename != source_filename &&
325 strcmp(target_filename, source_filename) != 0)) {
326 // Need to load the source file: either we failed to load the
327 // target file, or we did but it's different from the source file.
328 free(source_file.data);
329 LoadFileContents(source_filename, &source_file);
330 }
331
332 if (source_file.data != NULL) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800333 const Patch* to_use =
334 FindMatchingPatch(source_file.sha1, patches, num_patches);
335 if (to_use != NULL) {
336 source_patch_filename = to_use->patch_filename;
337 }
338 }
339
340 if (source_patch_filename == NULL) {
341 free(source_file.data);
342 fprintf(stderr, "source file is bad; trying copy\n");
343
344 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
345 // fail.
346 fprintf(stderr, "failed to read copy file\n");
347 return 1;
348 }
349
350 const Patch* to_use =
351 FindMatchingPatch(copy_file.sha1, patches, num_patches);
352 if (to_use != NULL) {
353 copy_patch_filename = to_use->patch_filename;
354 }
355
356 if (copy_patch_filename == NULL) {
357 // fail.
358 fprintf(stderr, "copy file doesn't match source SHA-1s either\n");
359 return 1;
360 }
361 }
362
363 // Is there enough room in the target filesystem to hold the patched file?
Doug Zongkeref85ea62009-05-08 13:46:25 -0700364 size_t free_space = FreeSpaceForFile(target_fs);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800365 int enough_space = free_space > (target_size * 3 / 2); // 50% margin of error
366 printf("target %ld bytes; free space %ld bytes; enough %d\n",
367 (long)target_size, (long)free_space, enough_space);
368
369 if (!enough_space && source_patch_filename != NULL) {
370 // Using the original source, but not enough free space. First
371 // copy the source file to cache, then delete it from the original
372 // location.
373 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
374 fprintf(stderr, "not enough free space on /cache\n");
375 return 1;
376 }
377
378 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
379 fprintf(stderr, "failed to back up source file\n");
380 return 1;
381 }
382 made_copy = 1;
383 unlink(source_filename);
384
Doug Zongkeref85ea62009-05-08 13:46:25 -0700385 size_t free_space = FreeSpaceForFile(target_fs);
386 printf("(now %ld bytes free for target)\n", (long)free_space);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800387 }
388
389 FileContents* source_to_use;
390 const char* patch_filename;
391 if (source_patch_filename != NULL) {
392 source_to_use = &source_file;
393 patch_filename = source_patch_filename;
394 } else {
395 source_to_use = &copy_file;
396 patch_filename = copy_patch_filename;
397 }
398
Doug Zongkeref85ea62009-05-08 13:46:25 -0700399 // We write the decoded output to "<tgt-file>.patch".
400 char* outname = (char*)malloc(strlen(target_filename) + 10);
401 strcpy(outname, target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800402 strcat(outname, ".patch");
403 FILE* output = fopen(outname, "wb");
404 if (output == NULL) {
405 fprintf(stderr, "failed to patch file %s: %s\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700406 target_filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800407 return 1;
408 }
409
410#define MAX_HEADER_LENGTH 8
411 unsigned char header[MAX_HEADER_LENGTH];
412 FILE* patchf = fopen(patch_filename, "rb");
413 if (patchf == NULL) {
414 fprintf(stderr, "failed to open patch file %s: %s\n",
415 patch_filename, strerror(errno));
416 return 1;
417 }
418 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
419 fclose(patchf);
420
421 SHA_CTX ctx;
422 SHA_init(&ctx);
423
424 if (header_bytes_read >= 4 &&
425 header[0] == 0xd6 && header[1] == 0xc3 &&
426 header[2] == 0xc4 && header[3] == 0) {
427 // xdelta3 patches begin "VCD" (with the high bits set) followed
428 // by a zero byte (the version number).
429 fprintf(stderr, "error: xdelta3 patches no longer supported\n");
430 return 1;
431 } else if (header_bytes_read >= 8 &&
432 memcmp(header, "BSDIFF40", 8) == 0) {
433 int result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
Doug Zongker02d444b2009-05-27 18:24:03 -0700434 patch_filename, 0, output, &ctx);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800435 if (result != 0) {
436 fprintf(stderr, "ApplyBSDiffPatch failed\n");
437 return result;
438 }
Doug Zongker02d444b2009-05-27 18:24:03 -0700439 } else if (header_bytes_read >= 8 &&
440 memcmp(header, "IMGDIFF1", 8) == 0) {
441 int result = ApplyImagePatch(source_to_use->data, source_to_use->size,
442 patch_filename, output, &ctx);
443 if (result != 0) {
444 fprintf(stderr, "ApplyImagePatch failed\n");
445 return result;
446 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800447 } else {
448 fprintf(stderr, "Unknown patch file format");
449 return 1;
450 }
451
452 fflush(output);
453 fsync(fileno(output));
454 fclose(output);
455
456 const uint8_t* current_target_sha1 = SHA_final(&ctx);
457 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
458 fprintf(stderr, "patch did not produce expected sha1\n");
459 return 1;
460 }
461
462 // Give the .patch file the same owner, group, and mode of the
463 // original source file.
464 if (chmod(outname, source_to_use->st.st_mode) != 0) {
465 fprintf(stderr, "chmod of \"%s\" failed: %s\n", outname, strerror(errno));
466 return 1;
467 }
468 if (chown(outname, source_to_use->st.st_uid, source_to_use->st.st_gid) != 0) {
469 fprintf(stderr, "chown of \"%s\" failed: %s\n", outname, strerror(errno));
470 return 1;
471 }
472
Doug Zongkeref85ea62009-05-08 13:46:25 -0700473 // Finally, rename the .patch file to replace the target file.
474 if (rename(outname, target_filename) != 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800475 fprintf(stderr, "rename of .patch to \"%s\" failed: %s\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700476 target_filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800477 return 1;
478 }
479
480 // If this run of applypatch created the copy, and we're here, we
481 // can delete it.
482 if (made_copy) unlink(CACHE_TEMP_SOURCE);
483
484 // Success!
485 return 0;
486}