blob: e69a2fb443da1cb2509d4aa588809d11cac189d5 [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>
Doug Zongkercdb621b2010-02-02 08:44:12 -080024#include <sys/types.h>
25#include <fcntl.h>
The Android Open Source Project88b60792009-03-03 19:28:42 -080026#include <unistd.h>
27
28#include "mincrypt/sha.h"
29#include "applypatch.h"
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070030#include "mtdutils/mtdutils.h"
31
Doug Zongker5da317e2009-06-02 13:38:17 -070032int SaveFileContents(const char* filename, FileContents file);
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070033int LoadMTDContents(const char* filename, FileContents* file);
34int ParseSha1(const char* str, uint8_t* digest);
Doug Zongkercdb621b2010-02-02 08:44:12 -080035size_t FileSink(unsigned char* data, size_t len, void* token);
The Android Open Source Project88b60792009-03-03 19:28:42 -080036
Doug Zongker5da317e2009-06-02 13:38:17 -070037static int mtd_partitions_scanned = 0;
38
The Android Open Source Project88b60792009-03-03 19:28:42 -080039// Read a file into memory; store it and its associated metadata in
40// *file. Return 0 on success.
41int LoadFileContents(const char* filename, FileContents* file) {
42 file->data = NULL;
43
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070044 // A special 'filename' beginning with "MTD:" means to load the
45 // contents of an MTD partition.
46 if (strncmp(filename, "MTD:", 4) == 0) {
47 return LoadMTDContents(filename, file);
48 }
49
The Android Open Source Project88b60792009-03-03 19:28:42 -080050 if (stat(filename, &file->st) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -080051 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -080052 return -1;
53 }
54
55 file->size = file->st.st_size;
56 file->data = malloc(file->size);
57
58 FILE* f = fopen(filename, "rb");
59 if (f == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -080060 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -080061 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070062 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080063 return -1;
64 }
65
66 size_t bytes_read = fread(file->data, 1, file->size, f);
67 if (bytes_read != file->size) {
Doug Zongkercdb621b2010-02-02 08:44:12 -080068 printf("short read of \"%s\" (%d bytes of %d)\n",
The Android Open Source Project88b60792009-03-03 19:28:42 -080069 filename, bytes_read, file->size);
70 free(file->data);
Doug Zongkeref85ea62009-05-08 13:46:25 -070071 file->data = NULL;
The Android Open Source Project88b60792009-03-03 19:28:42 -080072 return -1;
73 }
74 fclose(f);
75
76 SHA(file->data, file->size, file->sha1);
77 return 0;
78}
79
Doug Zongkerf6a8bad2009-05-29 11:41:21 -070080static size_t* size_array;
81// comparison function for qsort()ing an int array of indexes into
82// size_array[].
83static int compare_size_indices(const void* a, const void* b) {
84 int aa = *(int*)a;
85 int bb = *(int*)b;
86 if (size_array[aa] < size_array[bb]) {
87 return -1;
88 } else if (size_array[aa] > size_array[bb]) {
89 return 1;
90 } else {
91 return 0;
92 }
93}
94
95// Load the contents of an MTD partition into the provided
96// FileContents. filename should be a string of the form
97// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:...".
98// The smallest size_n bytes for which that prefix of the mtd contents
99// has the corresponding sha1 hash will be loaded. It is acceptable
100// for a size value to be repeated with different sha1s. Will return
101// 0 on success.
102//
103// This complexity is needed because if an OTA installation is
104// interrupted, the partition might contain either the source or the
105// target data, which might be of different lengths. We need to know
106// the length in order to read from MTD (there is no "end-of-file"
107// marker), so the caller must specify the possible lengths and the
108// hash of the data, and we'll do the load expecting to find one of
109// those hashes.
110int LoadMTDContents(const char* filename, FileContents* file) {
111 char* copy = strdup(filename);
112 const char* magic = strtok(copy, ":");
113 if (strcmp(magic, "MTD") != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800114 printf("LoadMTDContents called with bad filename (%s)\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700115 filename);
116 return -1;
117 }
118 const char* partition = strtok(NULL, ":");
119
120 int i;
121 int colons = 0;
122 for (i = 0; filename[i] != '\0'; ++i) {
123 if (filename[i] == ':') {
124 ++colons;
125 }
126 }
127 if (colons < 3 || colons%2 == 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800128 printf("LoadMTDContents called with bad filename (%s)\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700129 filename);
130 }
131
132 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
133 int* index = malloc(pairs * sizeof(int));
134 size_t* size = malloc(pairs * sizeof(size_t));
135 char** sha1sum = malloc(pairs * sizeof(char*));
136
137 for (i = 0; i < pairs; ++i) {
138 const char* size_str = strtok(NULL, ":");
139 size[i] = strtol(size_str, NULL, 10);
140 if (size[i] == 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800141 printf("LoadMTDContents called with bad size (%s)\n", filename);
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700142 return -1;
143 }
144 sha1sum[i] = strtok(NULL, ":");
145 index[i] = i;
146 }
147
Doug Zongker5da317e2009-06-02 13:38:17 -0700148 // sort the index[] array so it indexes the pairs in order of
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700149 // increasing size.
150 size_array = size;
151 qsort(index, pairs, sizeof(int), compare_size_indices);
152
Doug Zongker5da317e2009-06-02 13:38:17 -0700153 if (!mtd_partitions_scanned) {
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700154 mtd_scan_partitions();
Doug Zongker5da317e2009-06-02 13:38:17 -0700155 mtd_partitions_scanned = 1;
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700156 }
157
158 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
159 if (mtd == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800160 printf("mtd partition \"%s\" not found (loading %s)\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700161 partition, filename);
162 return -1;
163 }
164
165 MtdReadContext* ctx = mtd_read_partition(mtd);
166 if (ctx == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800167 printf("failed to initialize read of mtd partition \"%s\"\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700168 partition);
169 return -1;
170 }
171
172 SHA_CTX sha_ctx;
173 SHA_init(&sha_ctx);
174 uint8_t parsed_sha[SHA_DIGEST_SIZE];
175
176 // allocate enough memory to hold the largest size.
177 file->data = malloc(size[index[pairs-1]]);
178 char* p = (char*)file->data;
179 file->size = 0; // # bytes read so far
180
181 for (i = 0; i < pairs; ++i) {
182 // Read enough additional bytes to get us up to the next size
183 // (again, we're trying the possibilities in order of increasing
184 // size).
185 size_t next = size[index[i]] - file->size;
186 size_t read = 0;
187 if (next > 0) {
188 read = mtd_read_data(ctx, p, next);
189 if (next != read) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800190 printf("short read (%d bytes of %d) for partition \"%s\"\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700191 read, next, partition);
192 free(file->data);
193 file->data = NULL;
194 return -1;
195 }
196 SHA_update(&sha_ctx, p, read);
197 file->size += read;
198 }
199
200 // Duplicate the SHA context and finalize the duplicate so we can
201 // check it against this pair's expected hash.
202 SHA_CTX temp_ctx;
203 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
204 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
205
206 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800207 printf("failed to parse sha1 %s in %s\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700208 sha1sum[index[i]], filename);
209 free(file->data);
210 file->data = NULL;
211 return -1;
212 }
213
214 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
215 // we have a match. stop reading the partition; we'll return
216 // the data we've read so far.
217 printf("mtd read matched size %d sha %s\n",
218 size[index[i]], sha1sum[index[i]]);
219 break;
220 }
221
222 p += read;
223 }
224
225 mtd_read_close(ctx);
226
227 if (i == pairs) {
228 // Ran off the end of the list of (size,sha1) pairs without
229 // finding a match.
Doug Zongkercdb621b2010-02-02 08:44:12 -0800230 printf("contents of MTD partition \"%s\" didn't match %s\n",
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700231 partition, filename);
232 free(file->data);
233 file->data = NULL;
234 return -1;
235 }
236
237 const uint8_t* sha_final = SHA_final(&sha_ctx);
238 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
239 file->sha1[i] = sha_final[i];
240 }
241
Doug Zongker5da317e2009-06-02 13:38:17 -0700242 // Fake some stat() info.
243 file->st.st_mode = 0644;
244 file->st.st_uid = 0;
245 file->st.st_gid = 0;
246
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700247 free(copy);
248 free(index);
249 free(size);
250 free(sha1sum);
251
252 return 0;
253}
254
255
The Android Open Source Project88b60792009-03-03 19:28:42 -0800256// Save the contents of the given FileContents object under the given
257// filename. Return 0 on success.
258int SaveFileContents(const char* filename, FileContents file) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800259 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
260 if (fd < 0) {
261 printf("failed to open \"%s\" for write: %s\n",
The Android Open Source Project88b60792009-03-03 19:28:42 -0800262 filename, strerror(errno));
263 return -1;
264 }
265
Doug Zongkercdb621b2010-02-02 08:44:12 -0800266 size_t bytes_written = FileSink(file.data, file.size, &fd);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800267 if (bytes_written != file.size) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800268 printf("short write of \"%s\" (%d bytes of %d) (%s)\n",
269 filename, bytes_written, file.size, strerror(errno));
270 close(fd);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800271 return -1;
272 }
Doug Zongkercdb621b2010-02-02 08:44:12 -0800273 fsync(fd);
274 close(fd);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800275
276 if (chmod(filename, file.st.st_mode) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800277 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800278 return -1;
279 }
280 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800281 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800282 return -1;
283 }
284
285 return 0;
286}
287
Doug Zongker6c770462009-07-22 18:27:31 -0700288// Write a memory buffer to target_mtd partition, a string of the form
289// "MTD:<partition>[:...]". Return 0 on success.
290int WriteToMTDPartition(unsigned char* data, size_t len,
291 const char* target_mtd) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700292 char* partition = strchr(target_mtd, ':');
293 if (partition == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800294 printf("bad MTD target name \"%s\"\n", target_mtd);
Doug Zongker5da317e2009-06-02 13:38:17 -0700295 return -1;
296 }
297 ++partition;
298 // Trim off anything after a colon, eg "MTD:boot:blah:blah:blah...".
299 // We want just the partition name "boot".
300 partition = strdup(partition);
301 char* end = strchr(partition, ':');
302 if (end != NULL)
303 *end = '\0';
304
Doug Zongker5da317e2009-06-02 13:38:17 -0700305 if (!mtd_partitions_scanned) {
306 mtd_scan_partitions();
307 mtd_partitions_scanned = 1;
308 }
309
310 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
311 if (mtd == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800312 printf("mtd partition \"%s\" not found for writing\n", partition);
Doug Zongker5da317e2009-06-02 13:38:17 -0700313 return -1;
314 }
315
316 MtdWriteContext* ctx = mtd_write_partition(mtd);
317 if (ctx == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800318 printf("failed to init mtd partition \"%s\" for writing\n",
Doug Zongker5da317e2009-06-02 13:38:17 -0700319 partition);
320 return -1;
321 }
322
Doug Zongker6c770462009-07-22 18:27:31 -0700323 size_t written = mtd_write_data(ctx, (char*)data, len);
324 if (written != len) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800325 printf("only wrote %d of %d bytes to MTD %s\n",
Doug Zongker6c770462009-07-22 18:27:31 -0700326 written, len, partition);
327 mtd_write_close(ctx);
328 return -1;
Doug Zongker5da317e2009-06-02 13:38:17 -0700329 }
330
Doug Zongker5da317e2009-06-02 13:38:17 -0700331 if (mtd_erase_blocks(ctx, -1) < 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800332 printf("error finishing mtd write of %s\n", partition);
Doug Zongker5da317e2009-06-02 13:38:17 -0700333 mtd_write_close(ctx);
334 return -1;
335 }
336
337 if (mtd_write_close(ctx)) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800338 printf("error closing mtd write of %s\n", partition);
Doug Zongker5da317e2009-06-02 13:38:17 -0700339 return -1;
340 }
341
342 free(partition);
343 return 0;
344}
345
The Android Open Source Project88b60792009-03-03 19:28:42 -0800346
347// Take a string 'str' of 40 hex digits and parse it into the 20
348// byte array 'digest'. 'str' may contain only the digest or be of
349// the form "<digest>:<anything>". Return 0 on success, -1 on any
350// error.
351int ParseSha1(const char* str, uint8_t* digest) {
352 int i;
353 const char* ps = str;
354 uint8_t* pd = digest;
355 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
356 int digit;
357 if (*ps >= '0' && *ps <= '9') {
358 digit = *ps - '0';
359 } else if (*ps >= 'a' && *ps <= 'f') {
360 digit = *ps - 'a' + 10;
361 } else if (*ps >= 'A' && *ps <= 'F') {
362 digit = *ps - 'A' + 10;
363 } else {
364 return -1;
365 }
366 if (i % 2 == 0) {
367 *pd = digit << 4;
368 } else {
369 *pd |= digit;
370 ++pd;
371 }
372 }
373 if (*ps != '\0' && *ps != ':') return -1;
374 return 0;
375}
376
377// Parse arguments (which should be of the form "<sha1>" or
378// "<sha1>:<filename>" into the array *patches, returning the number
379// of Patch objects in *num_patches. Return 0 on success.
380int ParseShaArgs(int argc, char** argv, Patch** patches, int* num_patches) {
381 *num_patches = argc;
382 *patches = malloc(*num_patches * sizeof(Patch));
383
384 int i;
385 for (i = 0; i < *num_patches; ++i) {
386 if (ParseSha1(argv[i], (*patches)[i].sha1) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800387 printf("failed to parse sha1 \"%s\"\n", argv[i]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800388 return -1;
389 }
390 if (argv[i][SHA_DIGEST_SIZE*2] == '\0') {
391 (*patches)[i].patch_filename = NULL;
392 } else if (argv[i][SHA_DIGEST_SIZE*2] == ':') {
393 (*patches)[i].patch_filename = argv[i] + (SHA_DIGEST_SIZE*2+1);
394 } else {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800395 printf("failed to parse filename \"%s\"\n", argv[i]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800396 return -1;
397 }
398 }
399
400 return 0;
401}
402
403// Search an array of Patch objects for one matching the given sha1.
404// Return the Patch object on success, or NULL if no match is found.
405const Patch* FindMatchingPatch(uint8_t* sha1, Patch* patches, int num_patches) {
406 int i;
407 for (i = 0; i < num_patches; ++i) {
408 if (memcmp(patches[i].sha1, sha1, SHA_DIGEST_SIZE) == 0) {
409 return patches+i;
410 }
411 }
412 return NULL;
413}
414
415// Returns 0 if the contents of the file (argv[2]) or the cached file
416// match any of the sha1's on the command line (argv[3:]). Returns
417// nonzero otherwise.
418int CheckMode(int argc, char** argv) {
419 if (argc < 3) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800420 printf("no filename given\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800421 return 2;
422 }
423
424 int num_patches;
425 Patch* patches;
426 if (ParseShaArgs(argc-3, argv+3, &patches, &num_patches) != 0) { return 1; }
427
428 FileContents file;
429 file.data = NULL;
430
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700431 // It's okay to specify no sha1s; the check will pass if the
432 // LoadFileContents is successful. (Useful for reading MTD
433 // partitions, where the filename encodes the sha1s; no need to
434 // check them twice.)
The Android Open Source Project88b60792009-03-03 19:28:42 -0800435 if (LoadFileContents(argv[2], &file) != 0 ||
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700436 (num_patches > 0 &&
437 FindMatchingPatch(file.sha1, patches, num_patches) == NULL)) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800438 printf("file \"%s\" doesn't have any of expected "
The Android Open Source Project88b60792009-03-03 19:28:42 -0800439 "sha1 sums; checking cache\n", argv[2]);
440
441 free(file.data);
442
443 // If the source file is missing or corrupted, it might be because
444 // we were killed in the middle of patching it. A copy of it
445 // should have been made in CACHE_TEMP_SOURCE. If that file
446 // exists and matches the sha1 we're looking for, the check still
447 // passes.
448
449 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800450 printf("failed to load cache file\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800451 return 1;
452 }
453
454 if (FindMatchingPatch(file.sha1, patches, num_patches) == NULL) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800455 printf("cache bits don't match any sha1 for \"%s\"\n",
The Android Open Source Project88b60792009-03-03 19:28:42 -0800456 argv[2]);
457 return 1;
458 }
459 }
460
461 free(file.data);
462 return 0;
463}
464
465int ShowLicenses() {
466 ShowBSDiffLicense();
467 return 0;
468}
469
Doug Zongker6c770462009-07-22 18:27:31 -0700470size_t FileSink(unsigned char* data, size_t len, void* token) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800471 int fd = *(int *)token;
472 ssize_t done = 0;
473 ssize_t wrote;
474 while (done < (ssize_t) len) {
475 wrote = write(fd, data+done, len-done);
476 if (wrote <= 0) {
477 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
478 return done;
479 }
480 done += wrote;
481 }
482 printf("wrote %d bytes to output\n", (int)done);
483 return done;
Doug Zongker6c770462009-07-22 18:27:31 -0700484}
485
486typedef struct {
487 unsigned char* buffer;
488 size_t size;
489 size_t pos;
490} MemorySinkInfo;
491
492size_t MemorySink(unsigned char* data, size_t len, void* token) {
493 MemorySinkInfo* msi = (MemorySinkInfo*)token;
494 if (msi->size - msi->pos < len) {
495 return -1;
496 }
497 memcpy(msi->buffer + msi->pos, data, len);
498 msi->pos += len;
499 return len;
500}
501
The Android Open Source Project88b60792009-03-03 19:28:42 -0800502// Return the amount of free space (in bytes) on the filesystem
503// containing filename. filename must exist. Return -1 on error.
504size_t FreeSpaceForFile(const char* filename) {
505 struct statfs sf;
506 if (statfs(filename, &sf) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800507 printf("failed to statfs %s: %s\n", filename, strerror(errno));
The Android Open Source Project88b60792009-03-03 19:28:42 -0800508 return -1;
509 }
510 return sf.f_bsize * sf.f_bfree;
511}
512
513// This program applies binary patches to files in a way that is safe
514// (the original file is not touched until we have the desired
515// replacement for it) and idempotent (it's okay to run this program
516// multiple times).
517//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700518// - if the sha1 hash of <tgt-file> is <tgt-sha1>, does nothing and exits
The Android Open Source Project88b60792009-03-03 19:28:42 -0800519// successfully.
520//
Doug Zongkeref85ea62009-05-08 13:46:25 -0700521// - otherwise, if the sha1 hash of <src-file> is <src-sha1>, applies the
522// bsdiff <patch> to <src-file> to produce a new file (the type of patch
The Android Open Source Project88b60792009-03-03 19:28:42 -0800523// is automatically detected from the file header). If that new
Doug Zongkeref85ea62009-05-08 13:46:25 -0700524// file has sha1 hash <tgt-sha1>, moves it to replace <tgt-file>, and
525// exits successfully. Note that if <src-file> and <tgt-file> are
526// not the same, <src-file> is NOT deleted on success. <tgt-file>
527// may be the string "-" to mean "the same as src-file".
The Android Open Source Project88b60792009-03-03 19:28:42 -0800528//
529// - otherwise, or if any error is encountered, exits with non-zero
530// status.
Doug Zongkerf6a8bad2009-05-29 11:41:21 -0700531//
532// <src-file> (or <file> in check mode) may refer to an MTD partition
533// to read the source data. See the comments for the
534// LoadMTDContents() function above for the format of such a filename.
Doug Zongker5a790872009-06-12 09:42:43 -0700535//
536//
537// As you might guess from the arguments, this function used to be
538// main(); it was split out this way so applypatch could be built as a
539// static library and linked into other executables as well. In the
540// future only the library form will exist; we will not need to build
541// this as a standalone executable.
542//
543// The arguments to this function are just the command-line of the
544// standalone executable:
545//
546// <src-file> <tgt-file> <tgt-sha1> <tgt-size> [<src-sha1>:<patch> ...]
547// to apply a patch. Returns 0 on success, 1 on failure.
548//
549// "-c" <file> [<sha1> ...]
550// to check a file's contents against zero or more sha1s. Returns
551// 0 if it matches any of them, 1 if it doesn't.
552//
553// "-s" <bytes>
554// returns 0 if enough free space is available on /cache; 1 if it
555// does not.
556//
557// "-l"
558// shows open-source license information and returns 0.
559//
560// This function returns 2 if the arguments are not understood (in the
561// standalone executable, this causes the usage message to be
562// printed).
563//
564// TODO: make the interface more sensible for use as a library.
The Android Open Source Project88b60792009-03-03 19:28:42 -0800565
Doug Zongker5a790872009-06-12 09:42:43 -0700566int applypatch(int argc, char** argv) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800567 if (argc < 2) {
Doug Zongker5a790872009-06-12 09:42:43 -0700568 return 2;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800569 }
570
571 if (strncmp(argv[1], "-l", 3) == 0) {
572 return ShowLicenses();
573 }
574
575 if (strncmp(argv[1], "-c", 3) == 0) {
576 return CheckMode(argc, argv);
577 }
578
579 if (strncmp(argv[1], "-s", 3) == 0) {
580 if (argc != 3) {
Doug Zongker5a790872009-06-12 09:42:43 -0700581 return 2;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800582 }
583 size_t bytes = strtol(argv[2], NULL, 10);
584 if (MakeFreeSpaceOnCache(bytes) < 0) {
585 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
586 return 1;
587 } else {
588 return 0;
589 }
590 }
591
592 uint8_t target_sha1[SHA_DIGEST_SIZE];
593
594 const char* source_filename = argv[1];
Doug Zongkeref85ea62009-05-08 13:46:25 -0700595 const char* target_filename = argv[2];
596 if (target_filename[0] == '-' &&
597 target_filename[1] == '\0') {
598 target_filename = source_filename;
599 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800600
Doug Zongkercdb621b2010-02-02 08:44:12 -0800601 printf("\napplying patch to %s\n", source_filename);
602
603 if (ParseSha1(argv[3], target_sha1) != 0) {
604 printf("failed to parse tgt-sha1 \"%s\"\n", argv[3]);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800605 return 1;
606 }
607
Doug Zongkeref85ea62009-05-08 13:46:25 -0700608 unsigned long target_size = strtoul(argv[4], NULL, 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800609
610 int num_patches;
611 Patch* patches;
Doug Zongkeref85ea62009-05-08 13:46:25 -0700612 if (ParseShaArgs(argc-5, argv+5, &patches, &num_patches) < 0) { return 1; }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800613
614 FileContents copy_file;
615 FileContents source_file;
616 const char* source_patch_filename = NULL;
617 const char* copy_patch_filename = NULL;
618 int made_copy = 0;
619
Doug Zongkeref85ea62009-05-08 13:46:25 -0700620 // We try to load the target file into the source_file object.
621 if (LoadFileContents(target_filename, &source_file) == 0) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800622 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
623 // The early-exit case: the patch was already applied, this file
624 // has the desired hash, nothing for us to do.
Doug Zongkercdb621b2010-02-02 08:44:12 -0800625 printf("\"%s\" is already target; no patch needed\n",
Doug Zongkeref85ea62009-05-08 13:46:25 -0700626 target_filename);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800627 return 0;
628 }
Doug Zongkeref85ea62009-05-08 13:46:25 -0700629 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800630
Doug Zongkeref85ea62009-05-08 13:46:25 -0700631 if (source_file.data == NULL ||
632 (target_filename != source_filename &&
633 strcmp(target_filename, source_filename) != 0)) {
634 // Need to load the source file: either we failed to load the
635 // target file, or we did but it's different from the source file.
636 free(source_file.data);
637 LoadFileContents(source_filename, &source_file);
638 }
639
640 if (source_file.data != NULL) {
The Android Open Source Project88b60792009-03-03 19:28:42 -0800641 const Patch* to_use =
642 FindMatchingPatch(source_file.sha1, patches, num_patches);
643 if (to_use != NULL) {
644 source_patch_filename = to_use->patch_filename;
645 }
646 }
647
648 if (source_patch_filename == NULL) {
649 free(source_file.data);
Doug Zongkercdb621b2010-02-02 08:44:12 -0800650 printf("source file is bad; trying copy\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800651
652 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
653 // fail.
Doug Zongkercdb621b2010-02-02 08:44:12 -0800654 printf("failed to read copy file\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800655 return 1;
656 }
657
658 const Patch* to_use =
659 FindMatchingPatch(copy_file.sha1, patches, num_patches);
660 if (to_use != NULL) {
661 copy_patch_filename = to_use->patch_filename;
662 }
663
664 if (copy_patch_filename == NULL) {
665 // fail.
Doug Zongkercdb621b2010-02-02 08:44:12 -0800666 printf("copy file doesn't match source SHA-1s either\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800667 return 1;
668 }
669 }
670
Doug Zongkercdb621b2010-02-02 08:44:12 -0800671 int retry = 1;
672 SHA_CTX ctx;
673 int output;
674 MemorySinkInfo msi;
675 FileContents* source_to_use;
676 char* outname;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800677
Doug Zongkercdb621b2010-02-02 08:44:12 -0800678 // assume that target_filename (eg "/system/app/Foo.apk") is located
679 // on the same filesystem as its top-level directory ("/system").
680 // We need something that exists for calling statfs().
681 char target_fs[strlen(target_filename)+1];
682 char* slash = strchr(target_filename+1, '/');
683 if (slash != NULL) {
684 int count = slash - target_filename;
685 strncpy(target_fs, target_filename, count);
686 target_fs[count] = '\0';
Doug Zongker5da317e2009-06-02 13:38:17 -0700687 } else {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800688 strcpy(target_fs, target_filename);
689 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800690
Doug Zongkercdb621b2010-02-02 08:44:12 -0800691 do {
692 // Is there enough room in the target filesystem to hold the patched
693 // file?
Doug Zongker5da317e2009-06-02 13:38:17 -0700694
Doug Zongkercdb621b2010-02-02 08:44:12 -0800695 if (strncmp(target_filename, "MTD:", 4) == 0) {
696 // If the target is an MTD partition, we're actually going to
697 // write the output to /tmp and then copy it to the partition.
698 // statfs() always returns 0 blocks free for /tmp, so instead
699 // we'll just assume that /tmp has enough space to hold the file.
Doug Zongker5da317e2009-06-02 13:38:17 -0700700
Doug Zongkercdb621b2010-02-02 08:44:12 -0800701 // We still write the original source to cache, in case the MTD
702 // write is interrupted.
Doug Zongker5da317e2009-06-02 13:38:17 -0700703 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800704 printf("not enough free space on /cache\n");
Doug Zongker5da317e2009-06-02 13:38:17 -0700705 return 1;
706 }
Doug Zongker5da317e2009-06-02 13:38:17 -0700707 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800708 printf("failed to back up source file\n");
Doug Zongker5da317e2009-06-02 13:38:17 -0700709 return 1;
710 }
711 made_copy = 1;
Doug Zongkercdb621b2010-02-02 08:44:12 -0800712 retry = 0;
713 } else {
714 int enough_space = 0;
715 if (retry > 0) {
716 size_t free_space = FreeSpaceForFile(target_fs);
717 int enough_space =
718 (free_space > (target_size * 3 / 2)); // 50% margin of error
719 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
720 (long)target_size, (long)free_space, retry, enough_space);
721 }
Doug Zongker5da317e2009-06-02 13:38:17 -0700722
Doug Zongkercdb621b2010-02-02 08:44:12 -0800723 if (!enough_space) {
724 retry = 0;
725 }
726
727 if (!enough_space && source_patch_filename != NULL) {
728 // Using the original source, but not enough free space. First
729 // copy the source file to cache, then delete it from the original
730 // location.
731
732 if (strncmp(source_filename, "MTD:", 4) == 0) {
733 // It's impossible to free space on the target filesystem by
734 // deleting the source if the source is an MTD partition. If
735 // we're ever in a state where we need to do this, fail.
736 printf("not enough free space for target but source is MTD\n");
737 return 1;
738 }
739
740 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
741 printf("not enough free space on /cache\n");
742 return 1;
743 }
744
745 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
746 printf("failed to back up source file\n");
747 return 1;
748 }
749 made_copy = 1;
750 unlink(source_filename);
751
752 size_t free_space = FreeSpaceForFile(target_fs);
753 printf("(now %ld bytes free for target)\n", (long)free_space);
754 }
Doug Zongker5da317e2009-06-02 13:38:17 -0700755 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800756
Doug Zongkercdb621b2010-02-02 08:44:12 -0800757 const char* patch_filename;
758 if (source_patch_filename != NULL) {
759 source_to_use = &source_file;
760 patch_filename = source_patch_filename;
761 } else {
762 source_to_use = &copy_file;
763 patch_filename = copy_patch_filename;
Doug Zongker6c770462009-07-22 18:27:31 -0700764 }
Doug Zongker6c770462009-07-22 18:27:31 -0700765
Doug Zongkercdb621b2010-02-02 08:44:12 -0800766 SinkFn sink = NULL;
767 void* token = NULL;
768 output = -1;
769 outname = NULL;
770 if (strncmp(target_filename, "MTD:", 4) == 0) {
771 // We store the decoded output in memory.
772 msi.buffer = malloc(target_size);
773 if (msi.buffer == NULL) {
774 printf("failed to alloc %ld bytes for output\n",
775 (long)target_size);
776 return 1;
777 }
778 msi.pos = 0;
779 msi.size = target_size;
780 sink = MemorySink;
781 token = &msi;
782 } else {
783 // We write the decoded output to "<tgt-file>.patch".
784 outname = (char*)malloc(strlen(target_filename) + 10);
785 strcpy(outname, target_filename);
786 strcat(outname, ".patch");
787
788 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
789 if (output < 0) {
790 printf("failed to open output file %s: %s\n",
791 outname, strerror(errno));
792 return 1;
793 }
794 sink = FileSink;
795 token = &output;
Doug Zongker6c770462009-07-22 18:27:31 -0700796 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800797
798#define MAX_HEADER_LENGTH 8
Doug Zongkercdb621b2010-02-02 08:44:12 -0800799 unsigned char header[MAX_HEADER_LENGTH];
800 FILE* patchf = fopen(patch_filename, "rb");
801 if (patchf == NULL) {
802 printf("failed to open patch file %s: %s\n",
803 patch_filename, strerror(errno));
804 return 1;
The Android Open Source Project88b60792009-03-03 19:28:42 -0800805 }
Doug Zongkercdb621b2010-02-02 08:44:12 -0800806 int header_bytes_read = fread(header, 1, MAX_HEADER_LENGTH, patchf);
807 fclose(patchf);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800808
Doug Zongkercdb621b2010-02-02 08:44:12 -0800809 SHA_init(&ctx);
810
811 int result;
812
813 if (header_bytes_read >= 4 &&
814 header[0] == 0xd6 && header[1] == 0xc3 &&
815 header[2] == 0xc4 && header[3] == 0) {
816 // xdelta3 patches begin "VCD" (with the high bits set) followed
817 // by a zero byte (the version number).
818 printf("error: xdelta3 patches no longer supported\n");
819 return 1;
820 } else if (header_bytes_read >= 8 &&
821 memcmp(header, "BSDIFF40", 8) == 0) {
822 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
823 patch_filename, 0, sink, token, &ctx);
824 } else if (header_bytes_read >= 8 &&
825 memcmp(header, "IMGDIFF", 7) == 0 &&
826 (header[7] == '1' || header[7] == '2')) {
827 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
828 patch_filename, sink, token, &ctx);
829 } else {
830 printf("Unknown patch file format\n");
831 return 1;
832 }
833
834 if (output >= 0) {
835 fsync(output);
836 close(output);
837 }
838
839 if (result != 0) {
840 if (retry == 0) {
841 printf("applying patch failed\n");
842 return result;
843 } else {
844 printf("applying patch failed; retrying\n");
845 }
846 if (outname != NULL) {
847 unlink(outname);
848 }
849 } else {
850 // succeeded; no need to retry
851 break;
852 }
853 } while (retry-- > 0);
The Android Open Source Project88b60792009-03-03 19:28:42 -0800854
855 const uint8_t* current_target_sha1 = SHA_final(&ctx);
856 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800857 printf("patch did not produce expected sha1\n");
The Android Open Source Project88b60792009-03-03 19:28:42 -0800858 return 1;
859 }
860
Doug Zongkercdb621b2010-02-02 08:44:12 -0800861 if (output < 0) {
Doug Zongker5da317e2009-06-02 13:38:17 -0700862 // Copy the temp file to the MTD partition.
Doug Zongker6c770462009-07-22 18:27:31 -0700863 if (WriteToMTDPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800864 printf("write of patched data to %s failed\n", target_filename);
Doug Zongker5da317e2009-06-02 13:38:17 -0700865 return 1;
866 }
Doug Zongker6c770462009-07-22 18:27:31 -0700867 free(msi.buffer);
Doug Zongker5da317e2009-06-02 13:38:17 -0700868 } else {
869 // Give the .patch file the same owner, group, and mode of the
870 // original source file.
871 if (chmod(outname, source_to_use->st.st_mode) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800872 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
Doug Zongker5da317e2009-06-02 13:38:17 -0700873 return 1;
874 }
875 if (chown(outname, source_to_use->st.st_uid,
876 source_to_use->st.st_gid) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800877 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
Doug Zongker5da317e2009-06-02 13:38:17 -0700878 return 1;
879 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800880
Doug Zongker5da317e2009-06-02 13:38:17 -0700881 // Finally, rename the .patch file to replace the target file.
882 if (rename(outname, target_filename) != 0) {
Doug Zongkercdb621b2010-02-02 08:44:12 -0800883 printf("rename of .patch to \"%s\" failed: %s\n",
Doug Zongker5da317e2009-06-02 13:38:17 -0700884 target_filename, strerror(errno));
885 return 1;
886 }
The Android Open Source Project88b60792009-03-03 19:28:42 -0800887 }
888
889 // If this run of applypatch created the copy, and we're here, we
890 // can delete it.
891 if (made_copy) unlink(CACHE_TEMP_SOURCE);
892
893 // Success!
894 return 0;
895}