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