blob: 00004e9a826fa71846e14c654c7e2601c11a7e93 [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 LoadPartitionContents(const char* filename, FileContents* file);
Doug Zongkerf291d852010-07-07 13:55:25 -070034static ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
Doug Zongker1c43c972012-02-28 11:07:09 -080035static int GenerateTarget(FileContents* source_file,
36 const Value* source_patch_value,
37 FileContents* copy_file,
38 const Value* copy_patch_value,
39 const char* source_filename,
40 const char* target_filename,
41 const uint8_t target_sha1[SHA_DIGEST_SIZE],
42 size_t target_size);
Doug Zongker512536a2010-02-17 16:11:44 -080043
44static int mtd_partitions_scanned = 0;
45
Hristo Bojinovdb314d62010-08-02 10:29:49 -070046// Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
47// the retouched entries back to their original value (such that SHA-1 checks
48// don't fail due to randomization); store the file contents and associated
49// metadata in *file.
50//
51// Return 0 on success.
52int LoadFileContents(const char* filename, FileContents* file,
53 int retouch_flag) {
Doug Zongker512536a2010-02-17 16:11:44 -080054 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080055
Doug Zongkerf291d852010-07-07 13:55:25 -070056 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
57 // load the contents of a partition.
58 if (strncmp(filename, "MTD:", 4) == 0 ||
59 strncmp(filename, "EMMC:", 5) == 0) {
60 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080061 }
Doug Zongker512536a2010-02-17 16:11:44 -080062
Doug Zongkerc4351c72010-02-22 14:46:32 -080063 if (stat(filename, &file->st) != 0) {
64 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
65 return -1;
66 }
67
68 file->size = file->st.st_size;
69 file->data = malloc(file->size);
70
71 FILE* f = fopen(filename, "rb");
72 if (f == NULL) {
73 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
74 free(file->data);
75 file->data = NULL;
76 return -1;
77 }
78
79 ssize_t bytes_read = fread(file->data, 1, file->size, f);
80 if (bytes_read != file->size) {
81 printf("short read of \"%s\" (%ld bytes of %ld)\n",
82 filename, (long)bytes_read, (long)file->size);
83 free(file->data);
84 file->data = NULL;
85 return -1;
86 }
87 fclose(f);
88
Hristo Bojinovdb314d62010-08-02 10:29:49 -070089 // apply_patch[_check] functions are blind to randomization. Randomization
90 // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
91 // within a file, this means the file is assumed "corrupt" for simplicity.
92 if (retouch_flag) {
93 int32_t desired_offset = 0;
94 if (retouch_mask_data(file->data, file->size,
95 &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
96 printf("error trying to mask retouch entries\n");
97 free(file->data);
98 file->data = NULL;
99 return -1;
100 }
101 }
102
Doug Zongkerc4351c72010-02-22 14:46:32 -0800103 SHA(file->data, file->size, file->sha1);
104 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800105}
106
107static size_t* size_array;
108// comparison function for qsort()ing an int array of indexes into
109// size_array[].
110static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800111 int aa = *(int*)a;
112 int bb = *(int*)b;
113 if (size_array[aa] < size_array[bb]) {
114 return -1;
115 } else if (size_array[aa] > size_array[bb]) {
116 return 1;
117 } else {
118 return 0;
119 }
Doug Zongker512536a2010-02-17 16:11:44 -0800120}
121
Doug Zongkerf291d852010-07-07 13:55:25 -0700122// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800123// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700124// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
125// "EMMC:<partition_device>:..."). The smallest size_n bytes for
126// which that prefix of the partition contents has the corresponding
127// sha1 hash will be loaded. It is acceptable for a size value to be
128// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800129//
130// This complexity is needed because if an OTA installation is
131// interrupted, the partition might contain either the source or the
132// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700133// the length in order to read from a partition (there is no
134// "end-of-file" marker), so the caller must specify the possible
135// lengths and the hash of the data, and we'll do the load expecting
136// to find one of those hashes.
137enum PartitionType { MTD, EMMC };
138
139static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800140 char* copy = strdup(filename);
141 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700142
143 enum PartitionType type;
144
145 if (strcmp(magic, "MTD") == 0) {
146 type = MTD;
147 } else if (strcmp(magic, "EMMC") == 0) {
148 type = EMMC;
149 } else {
150 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800151 filename);
152 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800153 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800154 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800155
Doug Zongkerc4351c72010-02-22 14:46:32 -0800156 int i;
157 int colons = 0;
158 for (i = 0; filename[i] != '\0'; ++i) {
159 if (filename[i] == ':') {
160 ++colons;
161 }
Doug Zongker512536a2010-02-17 16:11:44 -0800162 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800163 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700164 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800165 filename);
166 }
Doug Zongker512536a2010-02-17 16:11:44 -0800167
Doug Zongkerc4351c72010-02-22 14:46:32 -0800168 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
169 int* index = malloc(pairs * sizeof(int));
170 size_t* size = malloc(pairs * sizeof(size_t));
171 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800172
Doug Zongkerc4351c72010-02-22 14:46:32 -0800173 for (i = 0; i < pairs; ++i) {
174 const char* size_str = strtok(NULL, ":");
175 size[i] = strtol(size_str, NULL, 10);
176 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700177 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800178 return -1;
179 }
180 sha1sum[i] = strtok(NULL, ":");
181 index[i] = i;
182 }
Doug Zongker512536a2010-02-17 16:11:44 -0800183
Doug Zongkerc4351c72010-02-22 14:46:32 -0800184 // sort the index[] array so it indexes the pairs in order of
185 // increasing size.
186 size_array = size;
187 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800188
Doug Zongkerf291d852010-07-07 13:55:25 -0700189 MtdReadContext* ctx = NULL;
190 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800191
Doug Zongkerf291d852010-07-07 13:55:25 -0700192 switch (type) {
193 case MTD:
194 if (!mtd_partitions_scanned) {
195 mtd_scan_partitions();
196 mtd_partitions_scanned = 1;
197 }
Doug Zongker512536a2010-02-17 16:11:44 -0800198
Doug Zongkerf291d852010-07-07 13:55:25 -0700199 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
200 if (mtd == NULL) {
201 printf("mtd partition \"%s\" not found (loading %s)\n",
202 partition, filename);
203 return -1;
204 }
205
206 ctx = mtd_read_partition(mtd);
207 if (ctx == NULL) {
208 printf("failed to initialize read of mtd partition \"%s\"\n",
209 partition);
210 return -1;
211 }
212 break;
213
214 case EMMC:
215 dev = fopen(partition, "rb");
216 if (dev == NULL) {
217 printf("failed to open emmc partition \"%s\": %s\n",
218 partition, strerror(errno));
219 return -1;
220 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800221 }
Doug Zongker512536a2010-02-17 16:11:44 -0800222
Doug Zongkerc4351c72010-02-22 14:46:32 -0800223 SHA_CTX sha_ctx;
224 SHA_init(&sha_ctx);
225 uint8_t parsed_sha[SHA_DIGEST_SIZE];
226
227 // allocate enough memory to hold the largest size.
228 file->data = malloc(size[index[pairs-1]]);
229 char* p = (char*)file->data;
230 file->size = 0; // # bytes read so far
231
232 for (i = 0; i < pairs; ++i) {
233 // Read enough additional bytes to get us up to the next size
234 // (again, we're trying the possibilities in order of increasing
235 // size).
236 size_t next = size[index[i]] - file->size;
237 size_t read = 0;
238 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700239 switch (type) {
240 case MTD:
241 read = mtd_read_data(ctx, p, next);
242 break;
243
244 case EMMC:
245 read = fread(p, 1, next, dev);
246 break;
247 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800248 if (next != read) {
249 printf("short read (%d bytes of %d) for partition \"%s\"\n",
250 read, next, partition);
251 free(file->data);
252 file->data = NULL;
253 return -1;
254 }
255 SHA_update(&sha_ctx, p, read);
256 file->size += read;
257 }
258
259 // Duplicate the SHA context and finalize the duplicate so we can
260 // check it against this pair's expected hash.
261 SHA_CTX temp_ctx;
262 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
263 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
264
265 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
266 printf("failed to parse sha1 %s in %s\n",
267 sha1sum[index[i]], filename);
268 free(file->data);
269 file->data = NULL;
270 return -1;
271 }
272
273 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
274 // we have a match. stop reading the partition; we'll return
275 // the data we've read so far.
Doug Zongkerf291d852010-07-07 13:55:25 -0700276 printf("partition read matched size %d sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800277 size[index[i]], sha1sum[index[i]]);
278 break;
279 }
280
281 p += read;
282 }
283
Doug Zongkerf291d852010-07-07 13:55:25 -0700284 switch (type) {
285 case MTD:
286 mtd_read_close(ctx);
287 break;
288
289 case EMMC:
290 fclose(dev);
291 break;
292 }
293
Doug Zongkerc4351c72010-02-22 14:46:32 -0800294
295 if (i == pairs) {
296 // Ran off the end of the list of (size,sha1) pairs without
297 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700298 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800299 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800300 free(file->data);
301 file->data = NULL;
302 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800303 }
304
Doug Zongkerc4351c72010-02-22 14:46:32 -0800305 const uint8_t* sha_final = SHA_final(&sha_ctx);
306 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
307 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800308 }
309
Doug Zongkerc4351c72010-02-22 14:46:32 -0800310 // Fake some stat() info.
311 file->st.st_mode = 0644;
312 file->st.st_uid = 0;
313 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800314
Doug Zongkerc4351c72010-02-22 14:46:32 -0800315 free(copy);
316 free(index);
317 free(size);
318 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800319
Doug Zongkerc4351c72010-02-22 14:46:32 -0800320 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800321}
322
323
324// Save the contents of the given FileContents object under the given
325// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800326int SaveFileContents(const char* filename, const FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800327 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
328 if (fd < 0) {
329 printf("failed to open \"%s\" for write: %s\n",
330 filename, strerror(errno));
331 return -1;
332 }
Doug Zongker512536a2010-02-17 16:11:44 -0800333
Doug Zongker1c43c972012-02-28 11:07:09 -0800334 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
335 if (bytes_written != file->size) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800336 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
Doug Zongker1c43c972012-02-28 11:07:09 -0800337 filename, (long)bytes_written, (long)file->size,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800338 strerror(errno));
339 close(fd);
340 return -1;
341 }
342 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800343 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800344
Doug Zongker1c43c972012-02-28 11:07:09 -0800345 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800346 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
347 return -1;
348 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800349 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800350 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
351 return -1;
352 }
Doug Zongker512536a2010-02-17 16:11:44 -0800353
Doug Zongkerc4351c72010-02-22 14:46:32 -0800354 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800355}
356
Doug Zongkerf291d852010-07-07 13:55:25 -0700357// Write a memory buffer to 'target' partition, a string of the form
358// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
359// success.
360int WriteToPartition(unsigned char* data, size_t len,
361 const char* target) {
362 char* copy = strdup(target);
363 const char* magic = strtok(copy, ":");
364
365 enum PartitionType type;
366 if (strcmp(magic, "MTD") == 0) {
367 type = MTD;
368 } else if (strcmp(magic, "EMMC") == 0) {
369 type = EMMC;
370 } else {
371 printf("WriteToPartition called with bad target (%s)\n", target);
372 return -1;
373 }
374 const char* partition = strtok(NULL, ":");
375
Doug Zongkerc4351c72010-02-22 14:46:32 -0800376 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700377 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800378 return -1;
379 }
Doug Zongker512536a2010-02-17 16:11:44 -0800380
Doug Zongkerf291d852010-07-07 13:55:25 -0700381 switch (type) {
382 case MTD:
383 if (!mtd_partitions_scanned) {
384 mtd_scan_partitions();
385 mtd_partitions_scanned = 1;
386 }
387
388 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
389 if (mtd == NULL) {
390 printf("mtd partition \"%s\" not found for writing\n",
391 partition);
392 return -1;
393 }
394
395 MtdWriteContext* ctx = mtd_write_partition(mtd);
396 if (ctx == NULL) {
397 printf("failed to init mtd partition \"%s\" for writing\n",
398 partition);
399 return -1;
400 }
401
402 size_t written = mtd_write_data(ctx, (char*)data, len);
403 if (written != len) {
404 printf("only wrote %d of %d bytes to MTD %s\n",
405 written, len, partition);
406 mtd_write_close(ctx);
407 return -1;
408 }
409
410 if (mtd_erase_blocks(ctx, -1) < 0) {
411 printf("error finishing mtd write of %s\n", partition);
412 mtd_write_close(ctx);
413 return -1;
414 }
415
416 if (mtd_write_close(ctx)) {
417 printf("error closing mtd write of %s\n", partition);
418 return -1;
419 }
420 break;
421
422 case EMMC:
423 ;
424 FILE* f = fopen(partition, "wb");
425 if (fwrite(data, 1, len, f) != len) {
426 printf("short write writing to %s (%s)\n",
427 partition, strerror(errno));
428 return -1;
429 }
430 if (fclose(f) != 0) {
431 printf("error closing %s (%s)\n", partition, strerror(errno));
432 return -1;
433 }
434 break;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800435 }
Doug Zongker512536a2010-02-17 16:11:44 -0800436
Doug Zongkerf291d852010-07-07 13:55:25 -0700437 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800438 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800439}
440
441
442// Take a string 'str' of 40 hex digits and parse it into the 20
443// byte array 'digest'. 'str' may contain only the digest or be of
444// the form "<digest>:<anything>". Return 0 on success, -1 on any
445// error.
446int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800447 int i;
448 const char* ps = str;
449 uint8_t* pd = digest;
450 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
451 int digit;
452 if (*ps >= '0' && *ps <= '9') {
453 digit = *ps - '0';
454 } else if (*ps >= 'a' && *ps <= 'f') {
455 digit = *ps - 'a' + 10;
456 } else if (*ps >= 'A' && *ps <= 'F') {
457 digit = *ps - 'A' + 10;
458 } else {
459 return -1;
460 }
461 if (i % 2 == 0) {
462 *pd = digit << 4;
463 } else {
464 *pd |= digit;
465 ++pd;
466 }
Doug Zongker512536a2010-02-17 16:11:44 -0800467 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800468 if (*ps != '\0') return -1;
469 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800470}
471
Doug Zongkerc4351c72010-02-22 14:46:32 -0800472// Search an array of sha1 strings for one matching the given sha1.
473// Return the index of the match on success, or -1 if no match is
474// found.
Doug Zongkerb07b2932012-02-28 12:07:30 -0800475int FindMatchingPatch(uint8_t* sha1, const char** patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800476 int num_patches) {
477 int i;
478 uint8_t patch_sha1[SHA_DIGEST_SIZE];
479 for (i = 0; i < num_patches; ++i) {
480 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
481 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
482 return i;
483 }
Doug Zongker512536a2010-02-17 16:11:44 -0800484 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800485 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800486}
487
488// Returns 0 if the contents of the file (argv[2]) or the cached file
489// match any of the sha1's on the command line (argv[3:]). Returns
490// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800491int applypatch_check(const char* filename,
492 int num_patches, char** const patch_sha1_str) {
493 FileContents file;
494 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800495
Doug Zongkerc4351c72010-02-22 14:46:32 -0800496 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700497 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800498 // partitions, where the filename encodes the sha1s; no need to
499 // check them twice.)
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700500 if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800501 (num_patches > 0 &&
502 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
503 printf("file \"%s\" doesn't have any of expected "
504 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800505
Doug Zongkerc4351c72010-02-22 14:46:32 -0800506 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800507 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800508
Doug Zongkerc4351c72010-02-22 14:46:32 -0800509 // If the source file is missing or corrupted, it might be because
510 // we were killed in the middle of patching it. A copy of it
511 // should have been made in CACHE_TEMP_SOURCE. If that file
512 // exists and matches the sha1 we're looking for, the check still
513 // passes.
514
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700515 if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800516 printf("failed to load cache file\n");
517 return 1;
518 }
519
520 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
521 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
522 free(file.data);
523 return 1;
524 }
525 }
Doug Zongker512536a2010-02-17 16:11:44 -0800526
527 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800528 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800529}
530
531int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800532 ShowBSDiffLicense();
533 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800534}
535
536ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800537 int fd = *(int *)token;
538 ssize_t done = 0;
539 ssize_t wrote;
540 while (done < (ssize_t) len) {
541 wrote = write(fd, data+done, len-done);
542 if (wrote <= 0) {
543 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
544 return done;
545 }
546 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800547 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800548 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800549}
550
551typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800552 unsigned char* buffer;
553 ssize_t size;
554 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800555} MemorySinkInfo;
556
557ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800558 MemorySinkInfo* msi = (MemorySinkInfo*)token;
559 if (msi->size - msi->pos < len) {
560 return -1;
561 }
562 memcpy(msi->buffer + msi->pos, data, len);
563 msi->pos += len;
564 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800565}
566
567// Return the amount of free space (in bytes) on the filesystem
568// containing filename. filename must exist. Return -1 on error.
569size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800570 struct statfs sf;
571 if (statfs(filename, &sf) != 0) {
572 printf("failed to statfs %s: %s\n", filename, strerror(errno));
573 return -1;
574 }
575 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800576}
577
Doug Zongkerc4351c72010-02-22 14:46:32 -0800578int CacheSizeCheck(size_t bytes) {
579 if (MakeFreeSpaceOnCache(bytes) < 0) {
580 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
581 return 1;
582 } else {
583 return 0;
584 }
585}
586
587
588// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800589// (the original file is not touched until we have the desired
590// replacement for it) and idempotent (it's okay to run this program
591// multiple times).
592//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800593// - if the sha1 hash of <target_filename> is <target_sha1_string>,
594// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800595//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800596// - otherwise, if the sha1 hash of <source_filename> is one of the
597// entries in <patch_sha1_str>, the corresponding patch from
598// <patch_data> (which must be a VAL_BLOB) is applied to produce a
599// new file (the type of patch is automatically detected from the
600// blob daat). If that new file has sha1 hash <target_sha1_str>,
601// moves it to replace <target_filename>, and exits successfully.
602// Note that if <source_filename> and <target_filename> are not the
603// same, <source_filename> is NOT deleted on success.
604// <target_filename> may be the string "-" to mean "the same as
605// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800606//
607// - otherwise, or if any error is encountered, exits with non-zero
608// status.
609//
Doug Zongkerf291d852010-07-07 13:55:25 -0700610// <source_filename> may refer to a partition to read the source data.
611// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800612// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800613
Doug Zongkerc4351c72010-02-22 14:46:32 -0800614int applypatch(const char* source_filename,
615 const char* target_filename,
616 const char* target_sha1_str,
617 size_t target_size,
618 int num_patches,
619 char** const patch_sha1_str,
620 Value** patch_data) {
621 printf("\napplying patch to %s\n", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800622
Doug Zongkerc4351c72010-02-22 14:46:32 -0800623 if (target_filename[0] == '-' &&
624 target_filename[1] == '\0') {
625 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800626 }
627
Doug Zongkerc4351c72010-02-22 14:46:32 -0800628 uint8_t target_sha1[SHA_DIGEST_SIZE];
629 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
630 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800631 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800632 }
Doug Zongker512536a2010-02-17 16:11:44 -0800633
Doug Zongkerc4351c72010-02-22 14:46:32 -0800634 FileContents copy_file;
635 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800636 copy_file.data = NULL;
637 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800638 const Value* source_patch_value = NULL;
639 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800640
Doug Zongkerc4351c72010-02-22 14:46:32 -0800641 // We try to load the target file into the source_file object.
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700642 if (LoadFileContents(target_filename, &source_file,
643 RETOUCH_DO_MASK) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800644 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
645 // The early-exit case: the patch was already applied, this file
646 // has the desired hash, nothing for us to do.
647 printf("\"%s\" is already target; no patch needed\n",
648 target_filename);
Doug Zongker1c43c972012-02-28 11:07:09 -0800649 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800650 return 0;
651 }
652 }
Doug Zongker512536a2010-02-17 16:11:44 -0800653
Doug Zongkerc4351c72010-02-22 14:46:32 -0800654 if (source_file.data == NULL ||
655 (target_filename != source_filename &&
656 strcmp(target_filename, source_filename) != 0)) {
657 // Need to load the source file: either we failed to load the
658 // target file, or we did but it's different from the source file.
659 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800660 source_file.data = NULL;
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700661 LoadFileContents(source_filename, &source_file,
662 RETOUCH_DO_MASK);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800663 }
664
665 if (source_file.data != NULL) {
666 int to_use = FindMatchingPatch(source_file.sha1,
667 patch_sha1_str, num_patches);
668 if (to_use >= 0) {
669 source_patch_value = patch_data[to_use];
670 }
671 }
672
673 if (source_patch_value == NULL) {
674 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800675 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800676 printf("source file is bad; trying copy\n");
677
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700678 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
679 RETOUCH_DO_MASK) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800680 // fail.
681 printf("failed to read copy file\n");
682 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800683 }
684
Doug Zongkerc4351c72010-02-22 14:46:32 -0800685 int to_use = FindMatchingPatch(copy_file.sha1,
686 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700687 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800688 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800689 }
690
Doug Zongkerc4351c72010-02-22 14:46:32 -0800691 if (copy_patch_value == NULL) {
692 // fail.
693 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800694 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800695 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800696 }
Doug Zongker512536a2010-02-17 16:11:44 -0800697 }
698
Doug Zongker1c43c972012-02-28 11:07:09 -0800699 int result = GenerateTarget(&source_file, source_patch_value,
700 &copy_file, copy_patch_value,
701 source_filename, target_filename,
702 target_sha1, target_size);
703 free(source_file.data);
704 free(copy_file.data);
705
706 return result;
707}
708
709static int GenerateTarget(FileContents* source_file,
710 const Value* source_patch_value,
711 FileContents* copy_file,
712 const Value* copy_patch_value,
713 const char* source_filename,
714 const char* target_filename,
715 const uint8_t target_sha1[SHA_DIGEST_SIZE],
716 size_t target_size) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800717 int retry = 1;
718 SHA_CTX ctx;
719 int output;
720 MemorySinkInfo msi;
721 FileContents* source_to_use;
722 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800723 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800724
725 // assume that target_filename (eg "/system/app/Foo.apk") is located
726 // on the same filesystem as its top-level directory ("/system").
727 // We need something that exists for calling statfs().
728 char target_fs[strlen(target_filename)+1];
729 char* slash = strchr(target_filename+1, '/');
730 if (slash != NULL) {
731 int count = slash - target_filename;
732 strncpy(target_fs, target_filename, count);
733 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800734 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800735 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800736 }
737
Doug Zongkerc4351c72010-02-22 14:46:32 -0800738 do {
739 // Is there enough room in the target filesystem to hold the patched
740 // file?
741
Doug Zongkerf291d852010-07-07 13:55:25 -0700742 if (strncmp(target_filename, "MTD:", 4) == 0 ||
743 strncmp(target_filename, "EMMC:", 5) == 0) {
744 // If the target is a partition, we're actually going to
745 // write the output to /tmp and then copy it to the
746 // partition. statfs() always returns 0 blocks free for
747 // /tmp, so instead we'll just assume that /tmp has enough
748 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800749
Doug Zongkerf291d852010-07-07 13:55:25 -0700750 // We still write the original source to cache, in case
751 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800752 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800753 printf("not enough free space on /cache\n");
754 return 1;
755 }
756 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
757 printf("failed to back up source file\n");
758 return 1;
759 }
760 made_copy = 1;
761 retry = 0;
762 } else {
763 int enough_space = 0;
764 if (retry > 0) {
765 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700766 enough_space =
767 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800768 (free_space > (target_size * 3 / 2)); // 50% margin of error
769 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
770 (long)target_size, (long)free_space, retry, enough_space);
771 }
772
773 if (!enough_space) {
774 retry = 0;
775 }
776
777 if (!enough_space && source_patch_value != NULL) {
778 // Using the original source, but not enough free space. First
779 // copy the source file to cache, then delete it from the original
780 // location.
781
Doug Zongkerf291d852010-07-07 13:55:25 -0700782 if (strncmp(source_filename, "MTD:", 4) == 0 ||
783 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800784 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700785 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800786 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700787 printf("not enough free space for target but source "
788 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800789 return 1;
790 }
791
Doug Zongker1c43c972012-02-28 11:07:09 -0800792 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800793 printf("not enough free space on /cache\n");
794 return 1;
795 }
796
797 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
798 printf("failed to back up source file\n");
799 return 1;
800 }
801 made_copy = 1;
802 unlink(source_filename);
803
804 size_t free_space = FreeSpaceForFile(target_fs);
805 printf("(now %ld bytes free for target)\n", (long)free_space);
806 }
807 }
808
809 const Value* patch;
810 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800811 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800812 patch = source_patch_value;
813 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800814 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800815 patch = copy_patch_value;
816 }
817
818 if (patch->type != VAL_BLOB) {
819 printf("patch is not a blob\n");
820 return 1;
821 }
822
823 SinkFn sink = NULL;
824 void* token = NULL;
825 output = -1;
826 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700827 if (strncmp(target_filename, "MTD:", 4) == 0 ||
828 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800829 // We store the decoded output in memory.
830 msi.buffer = malloc(target_size);
831 if (msi.buffer == NULL) {
832 printf("failed to alloc %ld bytes for output\n",
833 (long)target_size);
834 return 1;
835 }
836 msi.pos = 0;
837 msi.size = target_size;
838 sink = MemorySink;
839 token = &msi;
840 } else {
841 // We write the decoded output to "<tgt-file>.patch".
842 outname = (char*)malloc(strlen(target_filename) + 10);
843 strcpy(outname, target_filename);
844 strcat(outname, ".patch");
845
846 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
847 if (output < 0) {
848 printf("failed to open output file %s: %s\n",
849 outname, strerror(errno));
850 return 1;
851 }
852 sink = FileSink;
853 token = &output;
854 }
855
856 char* header = patch->data;
857 ssize_t header_bytes_read = patch->size;
858
859 SHA_init(&ctx);
860
861 int result;
862
863 if (header_bytes_read >= 8 &&
864 memcmp(header, "BSDIFF40", 8) == 0) {
865 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
866 patch, 0, sink, token, &ctx);
867 } else if (header_bytes_read >= 8 &&
868 memcmp(header, "IMGDIFF2", 8) == 0) {
869 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
870 patch, sink, token, &ctx);
871 } else {
872 printf("Unknown patch file format\n");
873 return 1;
874 }
875
876 if (output >= 0) {
877 fsync(output);
878 close(output);
879 }
880
881 if (result != 0) {
882 if (retry == 0) {
883 printf("applying patch failed\n");
884 return result != 0;
885 } else {
886 printf("applying patch failed; retrying\n");
887 }
888 if (outname != NULL) {
889 unlink(outname);
890 }
891 } else {
892 // succeeded; no need to retry
893 break;
894 }
895 } while (retry-- > 0);
896
897 const uint8_t* current_target_sha1 = SHA_final(&ctx);
898 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
899 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800900 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800901 }
902
903 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700904 // Copy the temp file to the partition.
905 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800906 printf("write of patched data to %s failed\n", target_filename);
907 return 1;
908 }
909 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -0800910 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800911 // Give the .patch file the same owner, group, and mode of the
912 // original source file.
913 if (chmod(outname, source_to_use->st.st_mode) != 0) {
914 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
915 return 1;
916 }
917 if (chown(outname, source_to_use->st.st_uid,
918 source_to_use->st.st_gid) != 0) {
919 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
920 return 1;
921 }
Doug Zongker512536a2010-02-17 16:11:44 -0800922
Doug Zongkerc4351c72010-02-22 14:46:32 -0800923 // Finally, rename the .patch file to replace the target file.
924 if (rename(outname, target_filename) != 0) {
925 printf("rename of .patch to \"%s\" failed: %s\n",
926 target_filename, strerror(errno));
927 return 1;
928 }
Doug Zongker512536a2010-02-17 16:11:44 -0800929 }
930
Doug Zongkerc4351c72010-02-22 14:46:32 -0800931 // If this run of applypatch created the copy, and we're here, we
932 // can delete it.
933 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -0800934
Doug Zongkerc4351c72010-02-22 14:46:32 -0800935 // Success!
936 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800937}