blob: 106091386c8b873ef0cb8753c8866ed96aebd952 [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
Hristo Bojinovdb314d62010-08-02 10:29:49 -070033int SaveFileContents(const char* filename, FileContents file);
Doug Zongkerf291d852010-07-07 13:55:25 -070034static 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
Hristo Bojinovdb314d62010-08-02 10:29:49 -070040// Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
41// the retouched entries back to their original value (such that SHA-1 checks
42// don't fail due to randomization); store the file contents and associated
43// metadata in *file.
44//
45// Return 0 on success.
46int LoadFileContents(const char* filename, FileContents* file,
47 int retouch_flag) {
Doug Zongker512536a2010-02-17 16:11:44 -080048 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080049
Doug Zongkerf291d852010-07-07 13:55:25 -070050 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
51 // load the contents of a partition.
52 if (strncmp(filename, "MTD:", 4) == 0 ||
53 strncmp(filename, "EMMC:", 5) == 0) {
54 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080055 }
Doug Zongker512536a2010-02-17 16:11:44 -080056
Doug Zongkerc4351c72010-02-22 14:46:32 -080057 if (stat(filename, &file->st) != 0) {
58 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
59 return -1;
60 }
61
62 file->size = file->st.st_size;
63 file->data = malloc(file->size);
64
65 FILE* f = fopen(filename, "rb");
66 if (f == NULL) {
67 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
68 free(file->data);
69 file->data = NULL;
70 return -1;
71 }
72
73 ssize_t bytes_read = fread(file->data, 1, file->size, f);
74 if (bytes_read != file->size) {
75 printf("short read of \"%s\" (%ld bytes of %ld)\n",
76 filename, (long)bytes_read, (long)file->size);
77 free(file->data);
78 file->data = NULL;
79 return -1;
80 }
81 fclose(f);
82
Hristo Bojinovdb314d62010-08-02 10:29:49 -070083 // apply_patch[_check] functions are blind to randomization. Randomization
84 // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
85 // within a file, this means the file is assumed "corrupt" for simplicity.
86 if (retouch_flag) {
87 int32_t desired_offset = 0;
88 if (retouch_mask_data(file->data, file->size,
89 &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
90 printf("error trying to mask retouch entries\n");
91 free(file->data);
92 file->data = NULL;
93 return -1;
94 }
95 }
96
Doug Zongkerc4351c72010-02-22 14:46:32 -080097 SHA(file->data, file->size, file->sha1);
98 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080099}
100
101static size_t* size_array;
102// comparison function for qsort()ing an int array of indexes into
103// size_array[].
104static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800105 int aa = *(int*)a;
106 int bb = *(int*)b;
107 if (size_array[aa] < size_array[bb]) {
108 return -1;
109 } else if (size_array[aa] > size_array[bb]) {
110 return 1;
111 } else {
112 return 0;
113 }
Doug Zongker512536a2010-02-17 16:11:44 -0800114}
115
116void FreeFileContents(FileContents* file) {
117 if (file) free(file->data);
118 free(file);
119}
120
Doug Zongkerf291d852010-07-07 13:55:25 -0700121// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800122// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700123// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
124// "EMMC:<partition_device>:..."). The smallest size_n bytes for
125// which that prefix of the partition contents has the corresponding
126// sha1 hash will be loaded. It is acceptable for a size value to be
127// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800128//
129// This complexity is needed because if an OTA installation is
130// interrupted, the partition might contain either the source or the
131// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700132// the length in order to read from a partition (there is no
133// "end-of-file" marker), so the caller must specify the possible
134// lengths and the hash of the data, and we'll do the load expecting
135// to find one of those hashes.
136enum PartitionType { MTD, EMMC };
137
138static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800139 char* copy = strdup(filename);
140 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700141
142 enum PartitionType type;
143
144 if (strcmp(magic, "MTD") == 0) {
145 type = MTD;
146 } else if (strcmp(magic, "EMMC") == 0) {
147 type = EMMC;
148 } else {
149 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800150 filename);
151 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800152 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800153 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800154
Doug Zongkerc4351c72010-02-22 14:46:32 -0800155 int i;
156 int colons = 0;
157 for (i = 0; filename[i] != '\0'; ++i) {
158 if (filename[i] == ':') {
159 ++colons;
160 }
Doug Zongker512536a2010-02-17 16:11:44 -0800161 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800162 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700163 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800164 filename);
165 }
Doug Zongker512536a2010-02-17 16:11:44 -0800166
Doug Zongkerc4351c72010-02-22 14:46:32 -0800167 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
168 int* index = malloc(pairs * sizeof(int));
169 size_t* size = malloc(pairs * sizeof(size_t));
170 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800171
Doug Zongkerc4351c72010-02-22 14:46:32 -0800172 for (i = 0; i < pairs; ++i) {
173 const char* size_str = strtok(NULL, ":");
174 size[i] = strtol(size_str, NULL, 10);
175 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700176 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800177 return -1;
178 }
179 sha1sum[i] = strtok(NULL, ":");
180 index[i] = i;
181 }
Doug Zongker512536a2010-02-17 16:11:44 -0800182
Doug Zongkerc4351c72010-02-22 14:46:32 -0800183 // sort the index[] array so it indexes the pairs in order of
184 // increasing size.
185 size_array = size;
186 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800187
Doug Zongkerf291d852010-07-07 13:55:25 -0700188 MtdReadContext* ctx = NULL;
189 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800190
Doug Zongkerf291d852010-07-07 13:55:25 -0700191 switch (type) {
192 case MTD:
193 if (!mtd_partitions_scanned) {
194 mtd_scan_partitions();
195 mtd_partitions_scanned = 1;
196 }
Doug Zongker512536a2010-02-17 16:11:44 -0800197
Doug Zongkerf291d852010-07-07 13:55:25 -0700198 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
199 if (mtd == NULL) {
200 printf("mtd partition \"%s\" not found (loading %s)\n",
201 partition, filename);
202 return -1;
203 }
204
205 ctx = mtd_read_partition(mtd);
206 if (ctx == NULL) {
207 printf("failed to initialize read of mtd partition \"%s\"\n",
208 partition);
209 return -1;
210 }
211 break;
212
213 case EMMC:
214 dev = fopen(partition, "rb");
215 if (dev == NULL) {
216 printf("failed to open emmc partition \"%s\": %s\n",
217 partition, strerror(errno));
218 return -1;
219 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800220 }
Doug Zongker512536a2010-02-17 16:11:44 -0800221
Doug Zongkerc4351c72010-02-22 14:46:32 -0800222 SHA_CTX sha_ctx;
223 SHA_init(&sha_ctx);
224 uint8_t parsed_sha[SHA_DIGEST_SIZE];
225
226 // allocate enough memory to hold the largest size.
227 file->data = malloc(size[index[pairs-1]]);
228 char* p = (char*)file->data;
229 file->size = 0; // # bytes read so far
230
231 for (i = 0; i < pairs; ++i) {
232 // Read enough additional bytes to get us up to the next size
233 // (again, we're trying the possibilities in order of increasing
234 // size).
235 size_t next = size[index[i]] - file->size;
236 size_t read = 0;
237 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700238 switch (type) {
239 case MTD:
240 read = mtd_read_data(ctx, p, next);
241 break;
242
243 case EMMC:
244 read = fread(p, 1, next, dev);
245 break;
246 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800247 if (next != read) {
248 printf("short read (%d bytes of %d) for partition \"%s\"\n",
249 read, next, partition);
250 free(file->data);
251 file->data = NULL;
252 return -1;
253 }
254 SHA_update(&sha_ctx, p, read);
255 file->size += read;
256 }
257
258 // Duplicate the SHA context and finalize the duplicate so we can
259 // check it against this pair's expected hash.
260 SHA_CTX temp_ctx;
261 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
262 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
263
264 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
265 printf("failed to parse sha1 %s in %s\n",
266 sha1sum[index[i]], filename);
267 free(file->data);
268 file->data = NULL;
269 return -1;
270 }
271
272 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
273 // we have a match. stop reading the partition; we'll return
274 // the data we've read so far.
Doug Zongkerf291d852010-07-07 13:55:25 -0700275 printf("partition read matched size %d sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800276 size[index[i]], sha1sum[index[i]]);
277 break;
278 }
279
280 p += read;
281 }
282
Doug Zongkerf291d852010-07-07 13:55:25 -0700283 switch (type) {
284 case MTD:
285 mtd_read_close(ctx);
286 break;
287
288 case EMMC:
289 fclose(dev);
290 break;
291 }
292
Doug Zongkerc4351c72010-02-22 14:46:32 -0800293
294 if (i == pairs) {
295 // Ran off the end of the list of (size,sha1) pairs without
296 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700297 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800298 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800299 free(file->data);
300 file->data = NULL;
301 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800302 }
303
Doug Zongkerc4351c72010-02-22 14:46:32 -0800304 const uint8_t* sha_final = SHA_final(&sha_ctx);
305 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
306 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800307 }
308
Doug Zongkerc4351c72010-02-22 14:46:32 -0800309 // Fake some stat() info.
310 file->st.st_mode = 0644;
311 file->st.st_uid = 0;
312 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800313
Doug Zongkerc4351c72010-02-22 14:46:32 -0800314 free(copy);
315 free(index);
316 free(size);
317 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800318
Doug Zongkerc4351c72010-02-22 14:46:32 -0800319 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800320}
321
322
323// Save the contents of the given FileContents object under the given
324// filename. Return 0 on success.
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700325int SaveFileContents(const char* filename, FileContents file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800326 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
327 if (fd < 0) {
328 printf("failed to open \"%s\" for write: %s\n",
329 filename, strerror(errno));
330 return -1;
331 }
Doug Zongker512536a2010-02-17 16:11:44 -0800332
Doug Zongkerc4351c72010-02-22 14:46:32 -0800333 ssize_t bytes_written = FileSink(file.data, file.size, &fd);
334 if (bytes_written != file.size) {
335 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
336 filename, (long)bytes_written, (long)file.size,
337 strerror(errno));
338 close(fd);
339 return -1;
340 }
341 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800342 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800343
Doug Zongkerc4351c72010-02-22 14:46:32 -0800344 if (chmod(filename, file.st.st_mode) != 0) {
345 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
346 return -1;
347 }
348 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
349 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
350 return -1;
351 }
Doug Zongker512536a2010-02-17 16:11:44 -0800352
Doug Zongkerc4351c72010-02-22 14:46:32 -0800353 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800354}
355
Doug Zongkerf291d852010-07-07 13:55:25 -0700356// Write a memory buffer to 'target' partition, a string of the form
357// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
358// success.
359int WriteToPartition(unsigned char* data, size_t len,
360 const char* target) {
361 char* copy = strdup(target);
362 const char* magic = strtok(copy, ":");
363
364 enum PartitionType type;
365 if (strcmp(magic, "MTD") == 0) {
366 type = MTD;
367 } else if (strcmp(magic, "EMMC") == 0) {
368 type = EMMC;
369 } else {
370 printf("WriteToPartition called with bad target (%s)\n", target);
371 return -1;
372 }
373 const char* partition = strtok(NULL, ":");
374
Doug Zongkerc4351c72010-02-22 14:46:32 -0800375 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700376 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800377 return -1;
378 }
Doug Zongker512536a2010-02-17 16:11:44 -0800379
Doug Zongkerf291d852010-07-07 13:55:25 -0700380 switch (type) {
381 case MTD:
382 if (!mtd_partitions_scanned) {
383 mtd_scan_partitions();
384 mtd_partitions_scanned = 1;
385 }
386
387 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
388 if (mtd == NULL) {
389 printf("mtd partition \"%s\" not found for writing\n",
390 partition);
391 return -1;
392 }
393
394 MtdWriteContext* ctx = mtd_write_partition(mtd);
395 if (ctx == NULL) {
396 printf("failed to init mtd partition \"%s\" for writing\n",
397 partition);
398 return -1;
399 }
400
401 size_t written = mtd_write_data(ctx, (char*)data, len);
402 if (written != len) {
403 printf("only wrote %d of %d bytes to MTD %s\n",
404 written, len, partition);
405 mtd_write_close(ctx);
406 return -1;
407 }
408
409 if (mtd_erase_blocks(ctx, -1) < 0) {
410 printf("error finishing mtd write of %s\n", partition);
411 mtd_write_close(ctx);
412 return -1;
413 }
414
415 if (mtd_write_close(ctx)) {
416 printf("error closing mtd write of %s\n", partition);
417 return -1;
418 }
419 break;
420
421 case EMMC:
422 ;
423 FILE* f = fopen(partition, "wb");
424 if (fwrite(data, 1, len, f) != len) {
425 printf("short write writing to %s (%s)\n",
426 partition, strerror(errno));
427 return -1;
428 }
429 if (fclose(f) != 0) {
430 printf("error closing %s (%s)\n", partition, strerror(errno));
431 return -1;
432 }
433 break;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800434 }
Doug Zongker512536a2010-02-17 16:11:44 -0800435
Doug Zongkerf291d852010-07-07 13:55:25 -0700436 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800437 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800438}
439
440
441// Take a string 'str' of 40 hex digits and parse it into the 20
442// byte array 'digest'. 'str' may contain only the digest or be of
443// the form "<digest>:<anything>". Return 0 on success, -1 on any
444// error.
445int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800446 int i;
447 const char* ps = str;
448 uint8_t* pd = digest;
449 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
450 int digit;
451 if (*ps >= '0' && *ps <= '9') {
452 digit = *ps - '0';
453 } else if (*ps >= 'a' && *ps <= 'f') {
454 digit = *ps - 'a' + 10;
455 } else if (*ps >= 'A' && *ps <= 'F') {
456 digit = *ps - 'A' + 10;
457 } else {
458 return -1;
459 }
460 if (i % 2 == 0) {
461 *pd = digit << 4;
462 } else {
463 *pd |= digit;
464 ++pd;
465 }
Doug Zongker512536a2010-02-17 16:11:44 -0800466 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800467 if (*ps != '\0') return -1;
468 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800469}
470
Doug Zongkerc4351c72010-02-22 14:46:32 -0800471// Search an array of sha1 strings for one matching the given sha1.
472// Return the index of the match on success, or -1 if no match is
473// found.
474int FindMatchingPatch(uint8_t* sha1, char** const patch_sha1_str,
475 int num_patches) {
476 int i;
477 uint8_t patch_sha1[SHA_DIGEST_SIZE];
478 for (i = 0; i < num_patches; ++i) {
479 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
480 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
481 return i;
482 }
Doug Zongker512536a2010-02-17 16:11:44 -0800483 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800484 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800485}
486
487// Returns 0 if the contents of the file (argv[2]) or the cached file
488// match any of the sha1's on the command line (argv[3:]). Returns
489// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800490int applypatch_check(const char* filename,
491 int num_patches, char** const patch_sha1_str) {
492 FileContents file;
493 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800494
Doug Zongkerc4351c72010-02-22 14:46:32 -0800495 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700496 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800497 // partitions, where the filename encodes the sha1s; no need to
498 // check them twice.)
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700499 if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800500 (num_patches > 0 &&
501 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
502 printf("file \"%s\" doesn't have any of expected "
503 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800504
Doug Zongkerc4351c72010-02-22 14:46:32 -0800505 free(file.data);
Doug Zongker512536a2010-02-17 16:11:44 -0800506
Doug Zongkerc4351c72010-02-22 14:46:32 -0800507 // If the source file is missing or corrupted, it might be because
508 // we were killed in the middle of patching it. A copy of it
509 // should have been made in CACHE_TEMP_SOURCE. If that file
510 // exists and matches the sha1 we're looking for, the check still
511 // passes.
512
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700513 if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800514 printf("failed to load cache file\n");
515 return 1;
516 }
517
518 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
519 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
520 free(file.data);
521 return 1;
522 }
523 }
Doug Zongker512536a2010-02-17 16:11:44 -0800524
525 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800526 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800527}
528
529int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800530 ShowBSDiffLicense();
531 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800532}
533
534ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800535 int fd = *(int *)token;
536 ssize_t done = 0;
537 ssize_t wrote;
538 while (done < (ssize_t) len) {
539 wrote = write(fd, data+done, len-done);
540 if (wrote <= 0) {
541 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
542 return done;
543 }
544 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800545 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800546 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800547}
548
549typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800550 unsigned char* buffer;
551 ssize_t size;
552 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800553} MemorySinkInfo;
554
555ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800556 MemorySinkInfo* msi = (MemorySinkInfo*)token;
557 if (msi->size - msi->pos < len) {
558 return -1;
559 }
560 memcpy(msi->buffer + msi->pos, data, len);
561 msi->pos += len;
562 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800563}
564
565// Return the amount of free space (in bytes) on the filesystem
566// containing filename. filename must exist. Return -1 on error.
567size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800568 struct statfs sf;
569 if (statfs(filename, &sf) != 0) {
570 printf("failed to statfs %s: %s\n", filename, strerror(errno));
571 return -1;
572 }
573 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800574}
575
Doug Zongkerc4351c72010-02-22 14:46:32 -0800576int CacheSizeCheck(size_t bytes) {
577 if (MakeFreeSpaceOnCache(bytes) < 0) {
578 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
579 return 1;
580 } else {
581 return 0;
582 }
583}
584
585
586// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800587// (the original file is not touched until we have the desired
588// replacement for it) and idempotent (it's okay to run this program
589// multiple times).
590//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800591// - if the sha1 hash of <target_filename> is <target_sha1_string>,
592// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800593//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800594// - otherwise, if the sha1 hash of <source_filename> is one of the
595// entries in <patch_sha1_str>, the corresponding patch from
596// <patch_data> (which must be a VAL_BLOB) is applied to produce a
597// new file (the type of patch is automatically detected from the
598// blob daat). If that new file has sha1 hash <target_sha1_str>,
599// moves it to replace <target_filename>, and exits successfully.
600// Note that if <source_filename> and <target_filename> are not the
601// same, <source_filename> is NOT deleted on success.
602// <target_filename> may be the string "-" to mean "the same as
603// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800604//
605// - otherwise, or if any error is encountered, exits with non-zero
606// status.
607//
Doug Zongkerf291d852010-07-07 13:55:25 -0700608// <source_filename> may refer to a partition to read the source data.
609// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800610// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800611
Doug Zongkerc4351c72010-02-22 14:46:32 -0800612int applypatch(const char* source_filename,
613 const char* target_filename,
614 const char* target_sha1_str,
615 size_t target_size,
616 int num_patches,
617 char** const patch_sha1_str,
618 Value** patch_data) {
619 printf("\napplying patch to %s\n", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800620
Doug Zongkerc4351c72010-02-22 14:46:32 -0800621 if (target_filename[0] == '-' &&
622 target_filename[1] == '\0') {
623 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800624 }
625
Doug Zongkerc4351c72010-02-22 14:46:32 -0800626 uint8_t target_sha1[SHA_DIGEST_SIZE];
627 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
628 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800629 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800630 }
Doug Zongker512536a2010-02-17 16:11:44 -0800631
Doug Zongkerc4351c72010-02-22 14:46:32 -0800632 FileContents copy_file;
633 FileContents source_file;
634 const Value* source_patch_value = NULL;
635 const Value* copy_patch_value = NULL;
636 int made_copy = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800637
Doug Zongkerc4351c72010-02-22 14:46:32 -0800638 // We try to load the target file into the source_file object.
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700639 if (LoadFileContents(target_filename, &source_file,
640 RETOUCH_DO_MASK) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800641 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
642 // The early-exit case: the patch was already applied, this file
643 // has the desired hash, nothing for us to do.
644 printf("\"%s\" is already target; no patch needed\n",
645 target_filename);
646 return 0;
647 }
648 }
Doug Zongker512536a2010-02-17 16:11:44 -0800649
Doug Zongkerc4351c72010-02-22 14:46:32 -0800650 if (source_file.data == NULL ||
651 (target_filename != source_filename &&
652 strcmp(target_filename, source_filename) != 0)) {
653 // Need to load the source file: either we failed to load the
654 // target file, or we did but it's different from the source file.
655 free(source_file.data);
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700656 LoadFileContents(source_filename, &source_file,
657 RETOUCH_DO_MASK);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800658 }
659
660 if (source_file.data != NULL) {
661 int to_use = FindMatchingPatch(source_file.sha1,
662 patch_sha1_str, num_patches);
663 if (to_use >= 0) {
664 source_patch_value = patch_data[to_use];
665 }
666 }
667
668 if (source_patch_value == NULL) {
669 free(source_file.data);
670 printf("source file is bad; trying copy\n");
671
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700672 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
673 RETOUCH_DO_MASK) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800674 // fail.
675 printf("failed to read copy file\n");
676 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800677 }
678
Doug Zongkerc4351c72010-02-22 14:46:32 -0800679 int to_use = FindMatchingPatch(copy_file.sha1,
680 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700681 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800682 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800683 }
684
Doug Zongkerc4351c72010-02-22 14:46:32 -0800685 if (copy_patch_value == NULL) {
686 // fail.
687 printf("copy file doesn't match source SHA-1s either\n");
688 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800689 }
Doug Zongker512536a2010-02-17 16:11:44 -0800690 }
691
Doug Zongkerc4351c72010-02-22 14:46:32 -0800692 int retry = 1;
693 SHA_CTX ctx;
694 int output;
695 MemorySinkInfo msi;
696 FileContents* source_to_use;
697 char* outname;
698
699 // assume that target_filename (eg "/system/app/Foo.apk") is located
700 // on the same filesystem as its top-level directory ("/system").
701 // We need something that exists for calling statfs().
702 char target_fs[strlen(target_filename)+1];
703 char* slash = strchr(target_filename+1, '/');
704 if (slash != NULL) {
705 int count = slash - target_filename;
706 strncpy(target_fs, target_filename, count);
707 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800708 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800709 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800710 }
711
Doug Zongkerc4351c72010-02-22 14:46:32 -0800712 do {
713 // Is there enough room in the target filesystem to hold the patched
714 // file?
715
Doug Zongkerf291d852010-07-07 13:55:25 -0700716 if (strncmp(target_filename, "MTD:", 4) == 0 ||
717 strncmp(target_filename, "EMMC:", 5) == 0) {
718 // If the target is a partition, we're actually going to
719 // write the output to /tmp and then copy it to the
720 // partition. statfs() always returns 0 blocks free for
721 // /tmp, so instead we'll just assume that /tmp has enough
722 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800723
Doug Zongkerf291d852010-07-07 13:55:25 -0700724 // We still write the original source to cache, in case
725 // the partition write is interrupted.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
727 printf("not enough free space on /cache\n");
728 return 1;
729 }
730 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
731 printf("failed to back up source file\n");
732 return 1;
733 }
734 made_copy = 1;
735 retry = 0;
736 } else {
737 int enough_space = 0;
738 if (retry > 0) {
739 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700740 enough_space =
741 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800742 (free_space > (target_size * 3 / 2)); // 50% margin of error
743 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
744 (long)target_size, (long)free_space, retry, enough_space);
745 }
746
747 if (!enough_space) {
748 retry = 0;
749 }
750
751 if (!enough_space && source_patch_value != NULL) {
752 // Using the original source, but not enough free space. First
753 // copy the source file to cache, then delete it from the original
754 // location.
755
Doug Zongkerf291d852010-07-07 13:55:25 -0700756 if (strncmp(source_filename, "MTD:", 4) == 0 ||
757 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800758 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700759 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800760 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700761 printf("not enough free space for target but source "
762 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800763 return 1;
764 }
765
766 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
767 printf("not enough free space on /cache\n");
768 return 1;
769 }
770
771 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
772 printf("failed to back up source file\n");
773 return 1;
774 }
775 made_copy = 1;
776 unlink(source_filename);
777
778 size_t free_space = FreeSpaceForFile(target_fs);
779 printf("(now %ld bytes free for target)\n", (long)free_space);
780 }
781 }
782
783 const Value* patch;
784 if (source_patch_value != NULL) {
785 source_to_use = &source_file;
786 patch = source_patch_value;
787 } else {
788 source_to_use = &copy_file;
789 patch = copy_patch_value;
790 }
791
792 if (patch->type != VAL_BLOB) {
793 printf("patch is not a blob\n");
794 return 1;
795 }
796
797 SinkFn sink = NULL;
798 void* token = NULL;
799 output = -1;
800 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700801 if (strncmp(target_filename, "MTD:", 4) == 0 ||
802 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800803 // We store the decoded output in memory.
804 msi.buffer = malloc(target_size);
805 if (msi.buffer == NULL) {
806 printf("failed to alloc %ld bytes for output\n",
807 (long)target_size);
808 return 1;
809 }
810 msi.pos = 0;
811 msi.size = target_size;
812 sink = MemorySink;
813 token = &msi;
814 } else {
815 // We write the decoded output to "<tgt-file>.patch".
816 outname = (char*)malloc(strlen(target_filename) + 10);
817 strcpy(outname, target_filename);
818 strcat(outname, ".patch");
819
820 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
821 if (output < 0) {
822 printf("failed to open output file %s: %s\n",
823 outname, strerror(errno));
824 return 1;
825 }
826 sink = FileSink;
827 token = &output;
828 }
829
830 char* header = patch->data;
831 ssize_t header_bytes_read = patch->size;
832
833 SHA_init(&ctx);
834
835 int result;
836
837 if (header_bytes_read >= 8 &&
838 memcmp(header, "BSDIFF40", 8) == 0) {
839 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
840 patch, 0, sink, token, &ctx);
841 } else if (header_bytes_read >= 8 &&
842 memcmp(header, "IMGDIFF2", 8) == 0) {
843 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
844 patch, sink, token, &ctx);
845 } else {
846 printf("Unknown patch file format\n");
847 return 1;
848 }
849
850 if (output >= 0) {
851 fsync(output);
852 close(output);
853 }
854
855 if (result != 0) {
856 if (retry == 0) {
857 printf("applying patch failed\n");
858 return result != 0;
859 } else {
860 printf("applying patch failed; retrying\n");
861 }
862 if (outname != NULL) {
863 unlink(outname);
864 }
865 } else {
866 // succeeded; no need to retry
867 break;
868 }
869 } while (retry-- > 0);
870
871 const uint8_t* current_target_sha1 = SHA_final(&ctx);
872 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
873 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800874 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800875 }
876
877 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700878 // Copy the temp file to the partition.
879 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800880 printf("write of patched data to %s failed\n", target_filename);
881 return 1;
882 }
883 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -0800884 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800885 // Give the .patch file the same owner, group, and mode of the
886 // original source file.
887 if (chmod(outname, source_to_use->st.st_mode) != 0) {
888 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
889 return 1;
890 }
891 if (chown(outname, source_to_use->st.st_uid,
892 source_to_use->st.st_gid) != 0) {
893 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
894 return 1;
895 }
Doug Zongker512536a2010-02-17 16:11:44 -0800896
Doug Zongkerc4351c72010-02-22 14:46:32 -0800897 // Finally, rename the .patch file to replace the target file.
898 if (rename(outname, target_filename) != 0) {
899 printf("rename of .patch to \"%s\" failed: %s\n",
900 target_filename, strerror(errno));
901 return 1;
902 }
Doug Zongker512536a2010-02-17 16:11:44 -0800903 }
904
Doug Zongkerc4351c72010-02-22 14:46:32 -0800905 // If this run of applypatch created the copy, and we're here, we
906 // can delete it.
907 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -0800908
Doug Zongkerc4351c72010-02-22 14:46:32 -0800909 // Success!
910 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800911}