blob: d182821171bf76b8c5f0defd0582ff453d5880e3 [file] [log] [blame]
Doug Zongker512536a2010-02-17 16:11:44 -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 <sys/types.h>
25#include <fcntl.h>
26#include <unistd.h>
27
28#include "mincrypt/sha.h"
29#include "applypatch.h"
30#include "mtdutils/mtdutils.h"
Doug Zongkerc4351c72010-02-22 14:46:32 -080031#include "edify/expr.h"
Doug Zongker512536a2010-02-17 16:11:44 -080032
Doug Zongkerf291d852010-07-07 13:55:25 -070033static int SaveFileContents(const char* filename, FileContents file);
34static int LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongker512536a2010-02-17 16:11:44 -080035int ParseSha1(const char* str, uint8_t* digest);
Doug Zongkerf291d852010-07-07 13:55:25 -070036static ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
Doug Zongker512536a2010-02-17 16:11:44 -080037
38static int mtd_partitions_scanned = 0;
39
40// Read a file into memory; store it and its associated metadata in
41// *file. Return 0 on success.
42int LoadFileContents(const char* filename, FileContents* file) {
Doug Zongker512536a2010-02-17 16:11:44 -080043 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080044
Doug Zongkerf291d852010-07-07 13:55:25 -070045 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
46 // load the contents of a partition.
47 if (strncmp(filename, "MTD:", 4) == 0 ||
48 strncmp(filename, "EMMC:", 5) == 0) {
49 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080050 }
Doug Zongker512536a2010-02-17 16:11:44 -080051
Doug Zongkerc4351c72010-02-22 14:46:32 -080052 if (stat(filename, &file->st) != 0) {
53 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
54 return -1;
55 }
56
57 file->size = file->st.st_size;
58 file->data = malloc(file->size);
59
60 FILE* f = fopen(filename, "rb");
61 if (f == NULL) {
62 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
63 free(file->data);
64 file->data = NULL;
65 return -1;
66 }
67
68 ssize_t bytes_read = fread(file->data, 1, file->size, f);
69 if (bytes_read != file->size) {
70 printf("short read of \"%s\" (%ld bytes of %ld)\n",
71 filename, (long)bytes_read, (long)file->size);
72 free(file->data);
73 file->data = NULL;
74 return -1;
75 }
76 fclose(f);
77
78 SHA(file->data, file->size, file->sha1);
79 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080080}
81
82static size_t* size_array;
83// comparison function for qsort()ing an int array of indexes into
84// size_array[].
85static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -080086 int aa = *(int*)a;
87 int bb = *(int*)b;
88 if (size_array[aa] < size_array[bb]) {
89 return -1;
90 } else if (size_array[aa] > size_array[bb]) {
91 return 1;
92 } else {
93 return 0;
94 }
Doug Zongker512536a2010-02-17 16:11:44 -080095}
96
97void FreeFileContents(FileContents* file) {
98 if (file) free(file->data);
99 free(file);
100}
101
Doug Zongkerf291d852010-07-07 13:55:25 -0700102// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800103// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700104// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
105// "EMMC:<partition_device>:..."). The smallest size_n bytes for
106// which that prefix of the partition contents has the corresponding
107// sha1 hash will be loaded. It is acceptable for a size value to be
108// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800109//
110// This complexity is needed because if an OTA installation is
111// interrupted, the partition might contain either the source or the
112// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700113// the length in order to read from a partition (there is no
114// "end-of-file" marker), so the caller must specify the possible
115// lengths and the hash of the data, and we'll do the load expecting
116// to find one of those hashes.
117enum PartitionType { MTD, EMMC };
118
119static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800120 char* copy = strdup(filename);
121 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700122
123 enum PartitionType type;
124
125 if (strcmp(magic, "MTD") == 0) {
126 type = MTD;
127 } else if (strcmp(magic, "EMMC") == 0) {
128 type = EMMC;
129 } else {
130 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800131 filename);
132 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800133 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800134 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800135
Doug Zongkerc4351c72010-02-22 14:46:32 -0800136 int i;
137 int colons = 0;
138 for (i = 0; filename[i] != '\0'; ++i) {
139 if (filename[i] == ':') {
140 ++colons;
141 }
Doug Zongker512536a2010-02-17 16:11:44 -0800142 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800143 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700144 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800145 filename);
146 }
Doug Zongker512536a2010-02-17 16:11:44 -0800147
Doug Zongkerc4351c72010-02-22 14:46:32 -0800148 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
149 int* index = malloc(pairs * sizeof(int));
150 size_t* size = malloc(pairs * sizeof(size_t));
151 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800152
Doug Zongkerc4351c72010-02-22 14:46:32 -0800153 for (i = 0; i < pairs; ++i) {
154 const char* size_str = strtok(NULL, ":");
155 size[i] = strtol(size_str, NULL, 10);
156 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700157 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800158 return -1;
159 }
160 sha1sum[i] = strtok(NULL, ":");
161 index[i] = i;
162 }
Doug Zongker512536a2010-02-17 16:11:44 -0800163
Doug Zongkerc4351c72010-02-22 14:46:32 -0800164 // sort the index[] array so it indexes the pairs in order of
165 // increasing size.
166 size_array = size;
167 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800168
Doug Zongkerf291d852010-07-07 13:55:25 -0700169 MtdReadContext* ctx = NULL;
170 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800171
Doug Zongkerf291d852010-07-07 13:55:25 -0700172 switch (type) {
173 case MTD:
174 if (!mtd_partitions_scanned) {
175 mtd_scan_partitions();
176 mtd_partitions_scanned = 1;
177 }
Doug Zongker512536a2010-02-17 16:11:44 -0800178
Doug Zongkerf291d852010-07-07 13:55:25 -0700179 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
180 if (mtd == NULL) {
181 printf("mtd partition \"%s\" not found (loading %s)\n",
182 partition, filename);
183 return -1;
184 }
185
186 ctx = mtd_read_partition(mtd);
187 if (ctx == NULL) {
188 printf("failed to initialize read of mtd partition \"%s\"\n",
189 partition);
190 return -1;
191 }
192 break;
193
194 case EMMC:
195 dev = fopen(partition, "rb");
196 if (dev == NULL) {
197 printf("failed to open emmc partition \"%s\": %s\n",
198 partition, strerror(errno));
199 return -1;
200 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800201 }
Doug Zongker512536a2010-02-17 16:11:44 -0800202
Doug Zongkerc4351c72010-02-22 14:46:32 -0800203 SHA_CTX sha_ctx;
204 SHA_init(&sha_ctx);
205 uint8_t parsed_sha[SHA_DIGEST_SIZE];
206
207 // allocate enough memory to hold the largest size.
208 file->data = malloc(size[index[pairs-1]]);
209 char* p = (char*)file->data;
210 file->size = 0; // # bytes read so far
211
212 for (i = 0; i < pairs; ++i) {
213 // Read enough additional bytes to get us up to the next size
214 // (again, we're trying the possibilities in order of increasing
215 // size).
216 size_t next = size[index[i]] - file->size;
217 size_t read = 0;
218 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700219 switch (type) {
220 case MTD:
221 read = mtd_read_data(ctx, p, next);
222 break;
223
224 case EMMC:
225 read = fread(p, 1, next, dev);
226 break;
227 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800228 if (next != read) {
229 printf("short read (%d bytes of %d) for partition \"%s\"\n",
230 read, next, partition);
231 free(file->data);
232 file->data = NULL;
233 return -1;
234 }
235 SHA_update(&sha_ctx, p, read);
236 file->size += read;
237 }
238
239 // Duplicate the SHA context and finalize the duplicate so we can
240 // check it against this pair's expected hash.
241 SHA_CTX temp_ctx;
242 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
243 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
244
245 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
246 printf("failed to parse sha1 %s in %s\n",
247 sha1sum[index[i]], filename);
248 free(file->data);
249 file->data = NULL;
250 return -1;
251 }
252
253 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
254 // we have a match. stop reading the partition; we'll return
255 // the data we've read so far.
Doug Zongkerf291d852010-07-07 13:55:25 -0700256 printf("partition read matched size %d sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800257 size[index[i]], sha1sum[index[i]]);
258 break;
259 }
260
261 p += read;
262 }
263
Doug Zongkerf291d852010-07-07 13:55:25 -0700264 switch (type) {
265 case MTD:
266 mtd_read_close(ctx);
267 break;
268
269 case EMMC:
270 fclose(dev);
271 break;
272 }
273
Doug Zongkerc4351c72010-02-22 14:46:32 -0800274
275 if (i == pairs) {
276 // Ran off the end of the list of (size,sha1) pairs without
277 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700278 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800279 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800280 free(file->data);
281 file->data = NULL;
282 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800283 }
284
Doug Zongkerc4351c72010-02-22 14:46:32 -0800285 const uint8_t* sha_final = SHA_final(&sha_ctx);
286 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
287 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800288 }
289
Doug Zongkerc4351c72010-02-22 14:46:32 -0800290 // Fake some stat() info.
291 file->st.st_mode = 0644;
292 file->st.st_uid = 0;
293 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800294
Doug Zongkerc4351c72010-02-22 14:46:32 -0800295 free(copy);
296 free(index);
297 free(size);
298 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800299
Doug Zongkerc4351c72010-02-22 14:46:32 -0800300 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800301}
302
303
304// Save the contents of the given FileContents object under the given
305// filename. Return 0 on success.
Doug Zongkerf291d852010-07-07 13:55:25 -0700306static int SaveFileContents(const char* filename, FileContents file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800307 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
308 if (fd < 0) {
309 printf("failed to open \"%s\" for write: %s\n",
310 filename, strerror(errno));
311 return -1;
312 }
Doug Zongker512536a2010-02-17 16:11:44 -0800313
Doug Zongkerc4351c72010-02-22 14:46:32 -0800314 ssize_t bytes_written = FileSink(file.data, file.size, &fd);
315 if (bytes_written != file.size) {
316 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
317 filename, (long)bytes_written, (long)file.size,
318 strerror(errno));
319 close(fd);
320 return -1;
321 }
322 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800323 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800324
Doug Zongkerc4351c72010-02-22 14:46:32 -0800325 if (chmod(filename, file.st.st_mode) != 0) {
326 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
327 return -1;
328 }
329 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
330 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
331 return -1;
332 }
Doug Zongker512536a2010-02-17 16:11:44 -0800333
Doug Zongkerc4351c72010-02-22 14:46:32 -0800334 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800335}
336
Doug Zongkerf291d852010-07-07 13:55:25 -0700337// Write a memory buffer to 'target' partition, a string of the form
338// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
339// success.
340int WriteToPartition(unsigned char* data, size_t len,
341 const char* target) {
342 char* copy = strdup(target);
343 const char* magic = strtok(copy, ":");
344
345 enum PartitionType type;
346 if (strcmp(magic, "MTD") == 0) {
347 type = MTD;
348 } else if (strcmp(magic, "EMMC") == 0) {
349 type = EMMC;
350 } else {
351 printf("WriteToPartition called with bad target (%s)\n", target);
352 return -1;
353 }
354 const char* partition = strtok(NULL, ":");
355
Doug Zongkerc4351c72010-02-22 14:46:32 -0800356 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700357 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800358 return -1;
359 }
Doug Zongker512536a2010-02-17 16:11:44 -0800360
Doug Zongkerf291d852010-07-07 13:55:25 -0700361 switch (type) {
362 case MTD:
363 if (!mtd_partitions_scanned) {
364 mtd_scan_partitions();
365 mtd_partitions_scanned = 1;
366 }
367
368 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
369 if (mtd == NULL) {
370 printf("mtd partition \"%s\" not found for writing\n",
371 partition);
372 return -1;
373 }
374
375 MtdWriteContext* ctx = mtd_write_partition(mtd);
376 if (ctx == NULL) {
377 printf("failed to init mtd partition \"%s\" for writing\n",
378 partition);
379 return -1;
380 }
381
382 size_t written = mtd_write_data(ctx, (char*)data, len);
383 if (written != len) {
384 printf("only wrote %d of %d bytes to MTD %s\n",
385 written, len, partition);
386 mtd_write_close(ctx);
387 return -1;
388 }
389
390 if (mtd_erase_blocks(ctx, -1) < 0) {
391 printf("error finishing mtd write of %s\n", partition);
392 mtd_write_close(ctx);
393 return -1;
394 }
395
396 if (mtd_write_close(ctx)) {
397 printf("error closing mtd write of %s\n", partition);
398 return -1;
399 }
400 break;
401
402 case EMMC:
403 ;
404 FILE* f = fopen(partition, "wb");
405 if (fwrite(data, 1, len, f) != len) {
406 printf("short write writing to %s (%s)\n",
407 partition, strerror(errno));
408 return -1;
409 }
410 if (fclose(f) != 0) {
411 printf("error closing %s (%s)\n", partition, strerror(errno));
412 return -1;
413 }
414 break;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800415 }
Doug Zongker512536a2010-02-17 16:11:44 -0800416
Doug Zongkerf291d852010-07-07 13:55:25 -0700417 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800418 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800419}
420
421
422// Take a string 'str' of 40 hex digits and parse it into the 20
423// byte array 'digest'. 'str' may contain only the digest or be of
424// the form "<digest>:<anything>". Return 0 on success, -1 on any
425// error.
426int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800427 int i;
428 const char* ps = str;
429 uint8_t* pd = digest;
430 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
431 int digit;
432 if (*ps >= '0' && *ps <= '9') {
433 digit = *ps - '0';
434 } else if (*ps >= 'a' && *ps <= 'f') {
435 digit = *ps - 'a' + 10;
436 } else if (*ps >= 'A' && *ps <= 'F') {
437 digit = *ps - 'A' + 10;
438 } else {
439 return -1;
440 }
441 if (i % 2 == 0) {
442 *pd = digit << 4;
443 } else {
444 *pd |= digit;
445 ++pd;
446 }
Doug Zongker512536a2010-02-17 16:11:44 -0800447 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800448 if (*ps != '\0') return -1;
449 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800450}
451
Doug Zongkerc4351c72010-02-22 14:46:32 -0800452// Search an array of sha1 strings for one matching the given sha1.
453// Return the index of the match on success, or -1 if no match is
454// found.
455int FindMatchingPatch(uint8_t* sha1, char** const patch_sha1_str,
456 int num_patches) {
457 int i;
458 uint8_t patch_sha1[SHA_DIGEST_SIZE];
459 for (i = 0; i < num_patches; ++i) {
460 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
461 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
462 return i;
463 }
Doug Zongker512536a2010-02-17 16:11:44 -0800464 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800465 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800466}
467
468// Returns 0 if the contents of the file (argv[2]) or the cached file
469// match any of the sha1's on the command line (argv[3:]). Returns
470// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800471int applypatch_check(const char* filename,
472 int num_patches, char** const patch_sha1_str) {
473 FileContents file;
474 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800475
Doug Zongkerc4351c72010-02-22 14:46:32 -0800476 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700477 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800478 // partitions, where the filename encodes the sha1s; no need to
479 // check them twice.)
480 if (LoadFileContents(filename, &file) != 0 ||
481 (num_patches > 0 &&
482 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
483 printf("file \"%s\" doesn't have any of expected "
484 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800485
Doug Zongkerc4351c72010-02-22 14:46:32 -0800486 free(file.data);
Doug Zongker512536a2010-02-17 16:11:44 -0800487
Doug Zongkerc4351c72010-02-22 14:46:32 -0800488 // If the source file is missing or corrupted, it might be because
489 // we were killed in the middle of patching it. A copy of it
490 // should have been made in CACHE_TEMP_SOURCE. If that file
491 // exists and matches the sha1 we're looking for, the check still
492 // passes.
493
494 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
495 printf("failed to load cache file\n");
496 return 1;
497 }
498
499 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
500 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
501 free(file.data);
502 return 1;
503 }
504 }
Doug Zongker512536a2010-02-17 16:11:44 -0800505
506 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800507 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800508}
509
510int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800511 ShowBSDiffLicense();
512 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800513}
514
515ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800516 int fd = *(int *)token;
517 ssize_t done = 0;
518 ssize_t wrote;
519 while (done < (ssize_t) len) {
520 wrote = write(fd, data+done, len-done);
521 if (wrote <= 0) {
522 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
523 return done;
524 }
525 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800526 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800527 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800528}
529
530typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800531 unsigned char* buffer;
532 ssize_t size;
533 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800534} MemorySinkInfo;
535
536ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800537 MemorySinkInfo* msi = (MemorySinkInfo*)token;
538 if (msi->size - msi->pos < len) {
539 return -1;
540 }
541 memcpy(msi->buffer + msi->pos, data, len);
542 msi->pos += len;
543 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800544}
545
546// Return the amount of free space (in bytes) on the filesystem
547// containing filename. filename must exist. Return -1 on error.
548size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800549 struct statfs sf;
550 if (statfs(filename, &sf) != 0) {
551 printf("failed to statfs %s: %s\n", filename, strerror(errno));
552 return -1;
553 }
554 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800555}
556
Doug Zongkerc4351c72010-02-22 14:46:32 -0800557int CacheSizeCheck(size_t bytes) {
558 if (MakeFreeSpaceOnCache(bytes) < 0) {
559 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
560 return 1;
561 } else {
562 return 0;
563 }
564}
565
566
567// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800568// (the original file is not touched until we have the desired
569// replacement for it) and idempotent (it's okay to run this program
570// multiple times).
571//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800572// - if the sha1 hash of <target_filename> is <target_sha1_string>,
573// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800574//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800575// - otherwise, if the sha1 hash of <source_filename> is one of the
576// entries in <patch_sha1_str>, the corresponding patch from
577// <patch_data> (which must be a VAL_BLOB) is applied to produce a
578// new file (the type of patch is automatically detected from the
579// blob daat). If that new file has sha1 hash <target_sha1_str>,
580// moves it to replace <target_filename>, and exits successfully.
581// Note that if <source_filename> and <target_filename> are not the
582// same, <source_filename> is NOT deleted on success.
583// <target_filename> may be the string "-" to mean "the same as
584// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800585//
586// - otherwise, or if any error is encountered, exits with non-zero
587// status.
588//
Doug Zongkerf291d852010-07-07 13:55:25 -0700589// <source_filename> may refer to a partition to read the source data.
590// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800591// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800592
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593int applypatch(const char* source_filename,
594 const char* target_filename,
595 const char* target_sha1_str,
596 size_t target_size,
597 int num_patches,
598 char** const patch_sha1_str,
599 Value** patch_data) {
600 printf("\napplying patch to %s\n", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800601
Doug Zongkerc4351c72010-02-22 14:46:32 -0800602 if (target_filename[0] == '-' &&
603 target_filename[1] == '\0') {
604 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800605 }
606
Doug Zongkerc4351c72010-02-22 14:46:32 -0800607 uint8_t target_sha1[SHA_DIGEST_SIZE];
608 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
609 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800610 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800611 }
Doug Zongker512536a2010-02-17 16:11:44 -0800612
Doug Zongkerc4351c72010-02-22 14:46:32 -0800613 FileContents copy_file;
614 FileContents source_file;
615 const Value* source_patch_value = NULL;
616 const Value* copy_patch_value = NULL;
617 int made_copy = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800618
Doug Zongkerc4351c72010-02-22 14:46:32 -0800619 // We try to load the target file into the source_file object.
620 if (LoadFileContents(target_filename, &source_file) == 0) {
621 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
622 // The early-exit case: the patch was already applied, this file
623 // has the desired hash, nothing for us to do.
624 printf("\"%s\" is already target; no patch needed\n",
625 target_filename);
626 return 0;
627 }
628 }
Doug Zongker512536a2010-02-17 16:11:44 -0800629
Doug Zongkerc4351c72010-02-22 14:46:32 -0800630 if (source_file.data == NULL ||
631 (target_filename != source_filename &&
632 strcmp(target_filename, source_filename) != 0)) {
633 // Need to load the source file: either we failed to load the
634 // target file, or we did but it's different from the source file.
635 free(source_file.data);
636 LoadFileContents(source_filename, &source_file);
637 }
638
639 if (source_file.data != NULL) {
640 int to_use = FindMatchingPatch(source_file.sha1,
641 patch_sha1_str, num_patches);
642 if (to_use >= 0) {
643 source_patch_value = patch_data[to_use];
644 }
645 }
646
647 if (source_patch_value == NULL) {
648 free(source_file.data);
649 printf("source file is bad; trying copy\n");
650
651 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
652 // fail.
653 printf("failed to read copy file\n");
654 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800655 }
656
Doug Zongkerc4351c72010-02-22 14:46:32 -0800657 int to_use = FindMatchingPatch(copy_file.sha1,
658 patch_sha1_str, num_patches);
659 if (to_use > 0) {
660 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800661 }
662
Doug Zongkerc4351c72010-02-22 14:46:32 -0800663 if (copy_patch_value == NULL) {
664 // fail.
665 printf("copy file doesn't match source SHA-1s either\n");
666 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800667 }
Doug Zongker512536a2010-02-17 16:11:44 -0800668 }
669
Doug Zongkerc4351c72010-02-22 14:46:32 -0800670 int retry = 1;
671 SHA_CTX ctx;
672 int output;
673 MemorySinkInfo msi;
674 FileContents* source_to_use;
675 char* outname;
676
677 // assume that target_filename (eg "/system/app/Foo.apk") is located
678 // on the same filesystem as its top-level directory ("/system").
679 // We need something that exists for calling statfs().
680 char target_fs[strlen(target_filename)+1];
681 char* slash = strchr(target_filename+1, '/');
682 if (slash != NULL) {
683 int count = slash - target_filename;
684 strncpy(target_fs, target_filename, count);
685 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800686 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800687 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800688 }
689
Doug Zongkerc4351c72010-02-22 14:46:32 -0800690 do {
691 // Is there enough room in the target filesystem to hold the patched
692 // file?
693
Doug Zongkerf291d852010-07-07 13:55:25 -0700694 if (strncmp(target_filename, "MTD:", 4) == 0 ||
695 strncmp(target_filename, "EMMC:", 5) == 0) {
696 // If the target is a partition, we're actually going to
697 // write the output to /tmp and then copy it to the
698 // partition. statfs() always returns 0 blocks free for
699 // /tmp, so instead we'll just assume that /tmp has enough
700 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800701
Doug Zongkerf291d852010-07-07 13:55:25 -0700702 // We still write the original source to cache, in case
703 // the partition write is interrupted.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800704 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
705 printf("not enough free space on /cache\n");
706 return 1;
707 }
708 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
709 printf("failed to back up source file\n");
710 return 1;
711 }
712 made_copy = 1;
713 retry = 0;
714 } else {
715 int enough_space = 0;
716 if (retry > 0) {
717 size_t free_space = FreeSpaceForFile(target_fs);
718 int enough_space =
719 (free_space > (target_size * 3 / 2)); // 50% margin of error
720 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
721 (long)target_size, (long)free_space, retry, enough_space);
722 }
723
724 if (!enough_space) {
725 retry = 0;
726 }
727
728 if (!enough_space && source_patch_value != NULL) {
729 // Using the original source, but not enough free space. First
730 // copy the source file to cache, then delete it from the original
731 // location.
732
Doug Zongkerf291d852010-07-07 13:55:25 -0700733 if (strncmp(source_filename, "MTD:", 4) == 0 ||
734 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800735 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700736 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800737 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700738 printf("not enough free space for target but source "
739 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800740 return 1;
741 }
742
743 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
744 printf("not enough free space on /cache\n");
745 return 1;
746 }
747
748 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
749 printf("failed to back up source file\n");
750 return 1;
751 }
752 made_copy = 1;
753 unlink(source_filename);
754
755 size_t free_space = FreeSpaceForFile(target_fs);
756 printf("(now %ld bytes free for target)\n", (long)free_space);
757 }
758 }
759
760 const Value* patch;
761 if (source_patch_value != NULL) {
762 source_to_use = &source_file;
763 patch = source_patch_value;
764 } else {
765 source_to_use = &copy_file;
766 patch = copy_patch_value;
767 }
768
769 if (patch->type != VAL_BLOB) {
770 printf("patch is not a blob\n");
771 return 1;
772 }
773
774 SinkFn sink = NULL;
775 void* token = NULL;
776 output = -1;
777 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700778 if (strncmp(target_filename, "MTD:", 4) == 0 ||
779 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800780 // We store the decoded output in memory.
781 msi.buffer = malloc(target_size);
782 if (msi.buffer == NULL) {
783 printf("failed to alloc %ld bytes for output\n",
784 (long)target_size);
785 return 1;
786 }
787 msi.pos = 0;
788 msi.size = target_size;
789 sink = MemorySink;
790 token = &msi;
791 } else {
792 // We write the decoded output to "<tgt-file>.patch".
793 outname = (char*)malloc(strlen(target_filename) + 10);
794 strcpy(outname, target_filename);
795 strcat(outname, ".patch");
796
797 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
798 if (output < 0) {
799 printf("failed to open output file %s: %s\n",
800 outname, strerror(errno));
801 return 1;
802 }
803 sink = FileSink;
804 token = &output;
805 }
806
807 char* header = patch->data;
808 ssize_t header_bytes_read = patch->size;
809
810 SHA_init(&ctx);
811
812 int result;
813
814 if (header_bytes_read >= 8 &&
815 memcmp(header, "BSDIFF40", 8) == 0) {
816 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
817 patch, 0, sink, token, &ctx);
818 } else if (header_bytes_read >= 8 &&
819 memcmp(header, "IMGDIFF2", 8) == 0) {
820 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
821 patch, sink, token, &ctx);
822 } else {
823 printf("Unknown patch file format\n");
824 return 1;
825 }
826
827 if (output >= 0) {
828 fsync(output);
829 close(output);
830 }
831
832 if (result != 0) {
833 if (retry == 0) {
834 printf("applying patch failed\n");
835 return result != 0;
836 } else {
837 printf("applying patch failed; retrying\n");
838 }
839 if (outname != NULL) {
840 unlink(outname);
841 }
842 } else {
843 // succeeded; no need to retry
844 break;
845 }
846 } while (retry-- > 0);
847
848 const uint8_t* current_target_sha1 = SHA_final(&ctx);
849 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
850 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800851 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800852 }
853
854 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700855 // Copy the temp file to the partition.
856 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800857 printf("write of patched data to %s failed\n", target_filename);
858 return 1;
859 }
860 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -0800861 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800862 // Give the .patch file the same owner, group, and mode of the
863 // original source file.
864 if (chmod(outname, source_to_use->st.st_mode) != 0) {
865 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
866 return 1;
867 }
868 if (chown(outname, source_to_use->st.st_uid,
869 source_to_use->st.st_gid) != 0) {
870 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
871 return 1;
872 }
Doug Zongker512536a2010-02-17 16:11:44 -0800873
Doug Zongkerc4351c72010-02-22 14:46:32 -0800874 // Finally, rename the .patch file to replace the target file.
875 if (rename(outname, target_filename) != 0) {
876 printf("rename of .patch to \"%s\" failed: %s\n",
877 target_filename, strerror(errno));
878 return 1;
879 }
Doug Zongker512536a2010-02-17 16:11:44 -0800880 }
881
Doug Zongkerc4351c72010-02-22 14:46:32 -0800882 // If this run of applypatch created the copy, and we're here, we
883 // can delete it.
884 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -0800885
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886 // Success!
887 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800888}