blob: a0493e0261d0a8c50180635c26e15fc134b99680 [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
33int SaveFileContents(const char* filename, FileContents file);
34int LoadMTDContents(const char* filename, FileContents* file);
35int ParseSha1(const char* str, uint8_t* digest);
36ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
37
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 Zongkerc4351c72010-02-22 14:46:32 -080045 // A special 'filename' beginning with "MTD:" means to load the
46 // contents of an MTD partition.
47 if (strncmp(filename, "MTD:", 4) == 0) {
48 return LoadMTDContents(filename, file);
49 }
Doug Zongker512536a2010-02-17 16:11:44 -080050
Doug Zongkerc4351c72010-02-22 14:46:32 -080051 if (stat(filename, &file->st) != 0) {
52 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
53 return -1;
54 }
55
56 file->size = file->st.st_size;
57 file->data = malloc(file->size);
58
59 FILE* f = fopen(filename, "rb");
60 if (f == NULL) {
61 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
62 free(file->data);
63 file->data = NULL;
64 return -1;
65 }
66
67 ssize_t bytes_read = fread(file->data, 1, file->size, f);
68 if (bytes_read != file->size) {
69 printf("short read of \"%s\" (%ld bytes of %ld)\n",
70 filename, (long)bytes_read, (long)file->size);
71 free(file->data);
72 file->data = NULL;
73 return -1;
74 }
75 fclose(f);
76
77 SHA(file->data, file->size, file->sha1);
78 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -080079}
80
81static size_t* size_array;
82// comparison function for qsort()ing an int array of indexes into
83// size_array[].
84static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -080085 int aa = *(int*)a;
86 int bb = *(int*)b;
87 if (size_array[aa] < size_array[bb]) {
88 return -1;
89 } else if (size_array[aa] > size_array[bb]) {
90 return 1;
91 } else {
92 return 0;
93 }
Doug Zongker512536a2010-02-17 16:11:44 -080094}
95
96void FreeFileContents(FileContents* file) {
97 if (file) free(file->data);
98 free(file);
99}
100
101// Load the contents of an MTD partition into the provided
102// FileContents. filename should be a string of the form
103// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:...".
104// The smallest size_n bytes for which that prefix of the mtd contents
105// has the corresponding sha1 hash will be loaded. It is acceptable
106// for a size value to be repeated with different sha1s. Will return
107// 0 on success.
108//
109// This complexity is needed because if an OTA installation is
110// interrupted, the partition might contain either the source or the
111// target data, which might be of different lengths. We need to know
112// the length in order to read from MTD (there is no "end-of-file"
113// marker), so the caller must specify the possible lengths and the
114// hash of the data, and we'll do the load expecting to find one of
115// those hashes.
116int LoadMTDContents(const char* filename, FileContents* file) {
Koushik Duttad771acb2010-11-11 00:00:45 -0800117#ifdef BOARD_USES_MTDUTILS
Doug Zongkerc4351c72010-02-22 14:46:32 -0800118 char* copy = strdup(filename);
119 const char* magic = strtok(copy, ":");
120 if (strcmp(magic, "MTD") != 0) {
121 printf("LoadMTDContents called with bad filename (%s)\n",
122 filename);
123 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800124 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800125 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800126
Doug Zongkerc4351c72010-02-22 14:46:32 -0800127 int i;
128 int colons = 0;
129 for (i = 0; filename[i] != '\0'; ++i) {
130 if (filename[i] == ':') {
131 ++colons;
132 }
Doug Zongker512536a2010-02-17 16:11:44 -0800133 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800134 if (colons < 3 || colons%2 == 0) {
135 printf("LoadMTDContents called with bad filename (%s)\n",
136 filename);
137 }
Doug Zongker512536a2010-02-17 16:11:44 -0800138
Doug Zongkerc4351c72010-02-22 14:46:32 -0800139 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
140 int* index = malloc(pairs * sizeof(int));
141 size_t* size = malloc(pairs * sizeof(size_t));
142 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800143
Doug Zongkerc4351c72010-02-22 14:46:32 -0800144 for (i = 0; i < pairs; ++i) {
145 const char* size_str = strtok(NULL, ":");
146 size[i] = strtol(size_str, NULL, 10);
147 if (size[i] == 0) {
148 printf("LoadMTDContents called with bad size (%s)\n", filename);
149 return -1;
150 }
151 sha1sum[i] = strtok(NULL, ":");
152 index[i] = i;
153 }
Doug Zongker512536a2010-02-17 16:11:44 -0800154
Doug Zongkerc4351c72010-02-22 14:46:32 -0800155 // sort the index[] array so it indexes the pairs in order of
156 // increasing size.
157 size_array = size;
158 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800159
Doug Zongkerc4351c72010-02-22 14:46:32 -0800160 if (!mtd_partitions_scanned) {
161 mtd_scan_partitions();
162 mtd_partitions_scanned = 1;
163 }
Doug Zongker512536a2010-02-17 16:11:44 -0800164
Doug Zongkerc4351c72010-02-22 14:46:32 -0800165 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
166 if (mtd == NULL) {
167 printf("mtd partition \"%s\" not found (loading %s)\n",
168 partition, filename);
169 return -1;
170 }
Doug Zongker512536a2010-02-17 16:11:44 -0800171
Doug Zongkerc4351c72010-02-22 14:46:32 -0800172 MtdReadContext* ctx = mtd_read_partition(mtd);
173 if (ctx == NULL) {
174 printf("failed to initialize read of mtd partition \"%s\"\n",
175 partition);
176 return -1;
177 }
Doug Zongker512536a2010-02-17 16:11:44 -0800178
Doug Zongkerc4351c72010-02-22 14:46:32 -0800179 SHA_CTX sha_ctx;
180 SHA_init(&sha_ctx);
181 uint8_t parsed_sha[SHA_DIGEST_SIZE];
182
183 // allocate enough memory to hold the largest size.
184 file->data = malloc(size[index[pairs-1]]);
185 char* p = (char*)file->data;
186 file->size = 0; // # bytes read so far
187
188 for (i = 0; i < pairs; ++i) {
189 // Read enough additional bytes to get us up to the next size
190 // (again, we're trying the possibilities in order of increasing
191 // size).
192 size_t next = size[index[i]] - file->size;
193 size_t read = 0;
194 if (next > 0) {
195 read = mtd_read_data(ctx, p, next);
196 if (next != read) {
197 printf("short read (%d bytes of %d) for partition \"%s\"\n",
198 read, next, partition);
199 free(file->data);
200 file->data = NULL;
201 return -1;
202 }
203 SHA_update(&sha_ctx, p, read);
204 file->size += read;
205 }
206
207 // Duplicate the SHA context and finalize the duplicate so we can
208 // check it against this pair's expected hash.
209 SHA_CTX temp_ctx;
210 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
211 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
212
213 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
214 printf("failed to parse sha1 %s in %s\n",
215 sha1sum[index[i]], filename);
216 free(file->data);
217 file->data = NULL;
218 return -1;
219 }
220
221 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
222 // we have a match. stop reading the partition; we'll return
223 // the data we've read so far.
224 printf("mtd read matched size %d sha %s\n",
225 size[index[i]], sha1sum[index[i]]);
226 break;
227 }
228
229 p += read;
230 }
231
232 mtd_read_close(ctx);
233
234 if (i == pairs) {
235 // Ran off the end of the list of (size,sha1) pairs without
236 // finding a match.
237 printf("contents of MTD partition \"%s\" didn't match %s\n",
238 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800239 free(file->data);
240 file->data = NULL;
241 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800242 }
243
Doug Zongkerc4351c72010-02-22 14:46:32 -0800244 const uint8_t* sha_final = SHA_final(&sha_ctx);
245 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
246 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800247 }
248
Doug Zongkerc4351c72010-02-22 14:46:32 -0800249 // Fake some stat() info.
250 file->st.st_mode = 0644;
251 file->st.st_uid = 0;
252 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800253
Doug Zongkerc4351c72010-02-22 14:46:32 -0800254 free(copy);
255 free(index);
256 free(size);
257 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800258
Doug Zongkerc4351c72010-02-22 14:46:32 -0800259 return 0;
Koushik Duttad771acb2010-11-11 00:00:45 -0800260#else
261 printf("mtd utils not supported.\n");
262 return -1;
263#endif
Doug Zongker512536a2010-02-17 16:11:44 -0800264}
265
266
267// Save the contents of the given FileContents object under the given
268// filename. Return 0 on success.
269int SaveFileContents(const char* filename, FileContents file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800270 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
271 if (fd < 0) {
272 printf("failed to open \"%s\" for write: %s\n",
273 filename, strerror(errno));
274 return -1;
275 }
Doug Zongker512536a2010-02-17 16:11:44 -0800276
Doug Zongkerc4351c72010-02-22 14:46:32 -0800277 ssize_t bytes_written = FileSink(file.data, file.size, &fd);
278 if (bytes_written != file.size) {
279 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
280 filename, (long)bytes_written, (long)file.size,
281 strerror(errno));
282 close(fd);
283 return -1;
284 }
285 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800286 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800287
Doug Zongkerc4351c72010-02-22 14:46:32 -0800288 if (chmod(filename, file.st.st_mode) != 0) {
289 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
290 return -1;
291 }
292 if (chown(filename, file.st.st_uid, file.st.st_gid) != 0) {
293 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
294 return -1;
295 }
Doug Zongker512536a2010-02-17 16:11:44 -0800296
Doug Zongkerc4351c72010-02-22 14:46:32 -0800297 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800298}
299
300// Write a memory buffer to target_mtd partition, a string of the form
301// "MTD:<partition>[:...]". Return 0 on success.
302int WriteToMTDPartition(unsigned char* data, size_t len,
303 const char* target_mtd) {
Koushik Duttad771acb2010-11-11 00:00:45 -0800304#ifdef BOARD_USES_MTDUTILS
Doug Zongkerc4351c72010-02-22 14:46:32 -0800305 char* partition = strchr(target_mtd, ':');
306 if (partition == NULL) {
307 printf("bad MTD target name \"%s\"\n", target_mtd);
308 return -1;
309 }
310 ++partition;
311 // Trim off anything after a colon, eg "MTD:boot:blah:blah:blah...".
312 // We want just the partition name "boot".
313 partition = strdup(partition);
314 char* end = strchr(partition, ':');
315 if (end != NULL)
316 *end = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800317
Doug Zongkerc4351c72010-02-22 14:46:32 -0800318 if (!mtd_partitions_scanned) {
319 mtd_scan_partitions();
320 mtd_partitions_scanned = 1;
321 }
Doug Zongker512536a2010-02-17 16:11:44 -0800322
Doug Zongkerc4351c72010-02-22 14:46:32 -0800323 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
324 if (mtd == NULL) {
325 printf("mtd partition \"%s\" not found for writing\n", partition);
326 return -1;
327 }
Doug Zongker512536a2010-02-17 16:11:44 -0800328
Doug Zongkerc4351c72010-02-22 14:46:32 -0800329 MtdWriteContext* ctx = mtd_write_partition(mtd);
330 if (ctx == NULL) {
331 printf("failed to init mtd partition \"%s\" for writing\n",
332 partition);
333 return -1;
334 }
Doug Zongker512536a2010-02-17 16:11:44 -0800335
Doug Zongkerc4351c72010-02-22 14:46:32 -0800336 size_t written = mtd_write_data(ctx, (char*)data, len);
337 if (written != len) {
338 printf("only wrote %d of %d bytes to MTD %s\n",
339 written, len, partition);
340 mtd_write_close(ctx);
341 return -1;
342 }
Doug Zongker512536a2010-02-17 16:11:44 -0800343
Doug Zongkerc4351c72010-02-22 14:46:32 -0800344 if (mtd_erase_blocks(ctx, -1) < 0) {
345 printf("error finishing mtd write of %s\n", partition);
346 mtd_write_close(ctx);
347 return -1;
348 }
Doug Zongker512536a2010-02-17 16:11:44 -0800349
Doug Zongkerc4351c72010-02-22 14:46:32 -0800350 if (mtd_write_close(ctx)) {
351 printf("error closing mtd write of %s\n", partition);
352 return -1;
353 }
Doug Zongker512536a2010-02-17 16:11:44 -0800354
Doug Zongkerc4351c72010-02-22 14:46:32 -0800355 free(partition);
356 return 0;
Koushik Duttad771acb2010-11-11 00:00:45 -0800357#else
358 printf("mtd utils not supported.\n");
359 return -1;
360#endif
361
Doug Zongker512536a2010-02-17 16:11:44 -0800362}
363
364
365// Take a string 'str' of 40 hex digits and parse it into the 20
366// byte array 'digest'. 'str' may contain only the digest or be of
367// the form "<digest>:<anything>". Return 0 on success, -1 on any
368// error.
369int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800370 int i;
371 const char* ps = str;
372 uint8_t* pd = digest;
373 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
374 int digit;
375 if (*ps >= '0' && *ps <= '9') {
376 digit = *ps - '0';
377 } else if (*ps >= 'a' && *ps <= 'f') {
378 digit = *ps - 'a' + 10;
379 } else if (*ps >= 'A' && *ps <= 'F') {
380 digit = *ps - 'A' + 10;
381 } else {
382 return -1;
383 }
384 if (i % 2 == 0) {
385 *pd = digit << 4;
386 } else {
387 *pd |= digit;
388 ++pd;
389 }
Doug Zongker512536a2010-02-17 16:11:44 -0800390 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800391 if (*ps != '\0') return -1;
392 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800393}
394
Doug Zongkerc4351c72010-02-22 14:46:32 -0800395// Search an array of sha1 strings for one matching the given sha1.
396// Return the index of the match on success, or -1 if no match is
397// found.
398int FindMatchingPatch(uint8_t* sha1, char** const patch_sha1_str,
399 int num_patches) {
400 int i;
401 uint8_t patch_sha1[SHA_DIGEST_SIZE];
402 for (i = 0; i < num_patches; ++i) {
403 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
404 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
405 return i;
406 }
Doug Zongker512536a2010-02-17 16:11:44 -0800407 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800408 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800409}
410
411// Returns 0 if the contents of the file (argv[2]) or the cached file
412// match any of the sha1's on the command line (argv[3:]). Returns
413// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800414int applypatch_check(const char* filename,
415 int num_patches, char** const patch_sha1_str) {
416 FileContents file;
417 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800418
Doug Zongkerc4351c72010-02-22 14:46:32 -0800419 // It's okay to specify no sha1s; the check will pass if the
420 // LoadFileContents is successful. (Useful for reading MTD
421 // partitions, where the filename encodes the sha1s; no need to
422 // check them twice.)
423 if (LoadFileContents(filename, &file) != 0 ||
424 (num_patches > 0 &&
425 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
426 printf("file \"%s\" doesn't have any of expected "
427 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800428
Doug Zongkerc4351c72010-02-22 14:46:32 -0800429 free(file.data);
Doug Zongker512536a2010-02-17 16:11:44 -0800430
Doug Zongkerc4351c72010-02-22 14:46:32 -0800431 // If the source file is missing or corrupted, it might be because
432 // we were killed in the middle of patching it. A copy of it
433 // should have been made in CACHE_TEMP_SOURCE. If that file
434 // exists and matches the sha1 we're looking for, the check still
435 // passes.
436
437 if (LoadFileContents(CACHE_TEMP_SOURCE, &file) != 0) {
438 printf("failed to load cache file\n");
439 return 1;
440 }
441
442 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
443 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
444 free(file.data);
445 return 1;
446 }
447 }
Doug Zongker512536a2010-02-17 16:11:44 -0800448
449 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800450 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800451}
452
453int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800454 ShowBSDiffLicense();
455 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800456}
457
458ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800459 int fd = *(int *)token;
460 ssize_t done = 0;
461 ssize_t wrote;
462 while (done < (ssize_t) len) {
463 wrote = write(fd, data+done, len-done);
464 if (wrote <= 0) {
465 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
466 return done;
467 }
468 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800469 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800470 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800471}
472
473typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800474 unsigned char* buffer;
475 ssize_t size;
476 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800477} MemorySinkInfo;
478
479ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800480 MemorySinkInfo* msi = (MemorySinkInfo*)token;
481 if (msi->size - msi->pos < len) {
482 return -1;
483 }
484 memcpy(msi->buffer + msi->pos, data, len);
485 msi->pos += len;
486 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800487}
488
489// Return the amount of free space (in bytes) on the filesystem
490// containing filename. filename must exist. Return -1 on error.
491size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800492 struct statfs sf;
493 if (statfs(filename, &sf) != 0) {
494 printf("failed to statfs %s: %s\n", filename, strerror(errno));
495 return -1;
496 }
497 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800498}
499
Doug Zongkerc4351c72010-02-22 14:46:32 -0800500int CacheSizeCheck(size_t bytes) {
501 if (MakeFreeSpaceOnCache(bytes) < 0) {
502 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
503 return 1;
504 } else {
505 return 0;
506 }
507}
508
509
510// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800511// (the original file is not touched until we have the desired
512// replacement for it) and idempotent (it's okay to run this program
513// multiple times).
514//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800515// - if the sha1 hash of <target_filename> is <target_sha1_string>,
516// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800517//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800518// - otherwise, if the sha1 hash of <source_filename> is one of the
519// entries in <patch_sha1_str>, the corresponding patch from
520// <patch_data> (which must be a VAL_BLOB) is applied to produce a
521// new file (the type of patch is automatically detected from the
522// blob daat). If that new file has sha1 hash <target_sha1_str>,
523// moves it to replace <target_filename>, and exits successfully.
524// Note that if <source_filename> and <target_filename> are not the
525// same, <source_filename> is NOT deleted on success.
526// <target_filename> may be the string "-" to mean "the same as
527// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800528//
529// - otherwise, or if any error is encountered, exits with non-zero
530// status.
531//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800532// <source_filename> may refer to an MTD partition to read the source
533// data. See the comments for the LoadMTDContents() function above
534// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800535
Doug Zongkerc4351c72010-02-22 14:46:32 -0800536int applypatch(const char* source_filename,
537 const char* target_filename,
538 const char* target_sha1_str,
539 size_t target_size,
540 int num_patches,
541 char** const patch_sha1_str,
542 Value** patch_data) {
543 printf("\napplying patch to %s\n", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800544
Doug Zongkerc4351c72010-02-22 14:46:32 -0800545 if (target_filename[0] == '-' &&
546 target_filename[1] == '\0') {
547 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800548 }
549
Doug Zongkerc4351c72010-02-22 14:46:32 -0800550 uint8_t target_sha1[SHA_DIGEST_SIZE];
551 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
552 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800553 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800554 }
Doug Zongker512536a2010-02-17 16:11:44 -0800555
Doug Zongkerc4351c72010-02-22 14:46:32 -0800556 FileContents copy_file;
557 FileContents source_file;
558 const Value* source_patch_value = NULL;
559 const Value* copy_patch_value = NULL;
560 int made_copy = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800561
Doug Zongkerc4351c72010-02-22 14:46:32 -0800562 // We try to load the target file into the source_file object.
563 if (LoadFileContents(target_filename, &source_file) == 0) {
564 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
565 // The early-exit case: the patch was already applied, this file
566 // has the desired hash, nothing for us to do.
567 printf("\"%s\" is already target; no patch needed\n",
568 target_filename);
569 return 0;
570 }
571 }
Doug Zongker512536a2010-02-17 16:11:44 -0800572
Doug Zongkerc4351c72010-02-22 14:46:32 -0800573 if (source_file.data == NULL ||
574 (target_filename != source_filename &&
575 strcmp(target_filename, source_filename) != 0)) {
576 // Need to load the source file: either we failed to load the
577 // target file, or we did but it's different from the source file.
578 free(source_file.data);
579 LoadFileContents(source_filename, &source_file);
580 }
581
582 if (source_file.data != NULL) {
583 int to_use = FindMatchingPatch(source_file.sha1,
584 patch_sha1_str, num_patches);
585 if (to_use >= 0) {
586 source_patch_value = patch_data[to_use];
587 }
588 }
589
590 if (source_patch_value == NULL) {
591 free(source_file.data);
592 printf("source file is bad; trying copy\n");
593
594 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file) < 0) {
595 // fail.
596 printf("failed to read copy file\n");
597 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800598 }
599
Doug Zongkerc4351c72010-02-22 14:46:32 -0800600 int to_use = FindMatchingPatch(copy_file.sha1,
601 patch_sha1_str, num_patches);
602 if (to_use > 0) {
603 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800604 }
605
Doug Zongkerc4351c72010-02-22 14:46:32 -0800606 if (copy_patch_value == NULL) {
607 // fail.
608 printf("copy file doesn't match source SHA-1s either\n");
609 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800610 }
Doug Zongker512536a2010-02-17 16:11:44 -0800611 }
612
Doug Zongkerc4351c72010-02-22 14:46:32 -0800613 int retry = 1;
614 SHA_CTX ctx;
615 int output;
616 MemorySinkInfo msi;
617 FileContents* source_to_use;
618 char* outname;
619
620 // assume that target_filename (eg "/system/app/Foo.apk") is located
621 // on the same filesystem as its top-level directory ("/system").
622 // We need something that exists for calling statfs().
623 char target_fs[strlen(target_filename)+1];
624 char* slash = strchr(target_filename+1, '/');
625 if (slash != NULL) {
626 int count = slash - target_filename;
627 strncpy(target_fs, target_filename, count);
628 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800629 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800630 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800631 }
632
Doug Zongkerc4351c72010-02-22 14:46:32 -0800633 do {
634 // Is there enough room in the target filesystem to hold the patched
635 // file?
636
637 if (strncmp(target_filename, "MTD:", 4) == 0) {
638 // If the target is an MTD partition, we're actually going to
639 // write the output to /tmp and then copy it to the partition.
640 // statfs() always returns 0 blocks free for /tmp, so instead
641 // we'll just assume that /tmp has enough space to hold the file.
642
643 // We still write the original source to cache, in case the MTD
644 // write is interrupted.
645 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
646 printf("not enough free space on /cache\n");
647 return 1;
648 }
649 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
650 printf("failed to back up source file\n");
651 return 1;
652 }
653 made_copy = 1;
654 retry = 0;
655 } else {
656 int enough_space = 0;
657 if (retry > 0) {
658 size_t free_space = FreeSpaceForFile(target_fs);
659 int enough_space =
660 (free_space > (target_size * 3 / 2)); // 50% margin of error
661 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
662 (long)target_size, (long)free_space, retry, enough_space);
663 }
664
665 if (!enough_space) {
666 retry = 0;
667 }
668
669 if (!enough_space && source_patch_value != NULL) {
670 // Using the original source, but not enough free space. First
671 // copy the source file to cache, then delete it from the original
672 // location.
673
674 if (strncmp(source_filename, "MTD:", 4) == 0) {
675 // It's impossible to free space on the target filesystem by
676 // deleting the source if the source is an MTD partition. If
677 // we're ever in a state where we need to do this, fail.
678 printf("not enough free space for target but source is MTD\n");
679 return 1;
680 }
681
682 if (MakeFreeSpaceOnCache(source_file.size) < 0) {
683 printf("not enough free space on /cache\n");
684 return 1;
685 }
686
687 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
688 printf("failed to back up source file\n");
689 return 1;
690 }
691 made_copy = 1;
692 unlink(source_filename);
693
694 size_t free_space = FreeSpaceForFile(target_fs);
695 printf("(now %ld bytes free for target)\n", (long)free_space);
696 }
697 }
698
699 const Value* patch;
700 if (source_patch_value != NULL) {
701 source_to_use = &source_file;
702 patch = source_patch_value;
703 } else {
704 source_to_use = &copy_file;
705 patch = copy_patch_value;
706 }
707
708 if (patch->type != VAL_BLOB) {
709 printf("patch is not a blob\n");
710 return 1;
711 }
712
713 SinkFn sink = NULL;
714 void* token = NULL;
715 output = -1;
716 outname = NULL;
717 if (strncmp(target_filename, "MTD:", 4) == 0) {
718 // We store the decoded output in memory.
719 msi.buffer = malloc(target_size);
720 if (msi.buffer == NULL) {
721 printf("failed to alloc %ld bytes for output\n",
722 (long)target_size);
723 return 1;
724 }
725 msi.pos = 0;
726 msi.size = target_size;
727 sink = MemorySink;
728 token = &msi;
729 } else {
730 // We write the decoded output to "<tgt-file>.patch".
731 outname = (char*)malloc(strlen(target_filename) + 10);
732 strcpy(outname, target_filename);
733 strcat(outname, ".patch");
734
735 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
736 if (output < 0) {
737 printf("failed to open output file %s: %s\n",
738 outname, strerror(errno));
739 return 1;
740 }
741 sink = FileSink;
742 token = &output;
743 }
744
745 char* header = patch->data;
746 ssize_t header_bytes_read = patch->size;
747
748 SHA_init(&ctx);
749
750 int result;
751
752 if (header_bytes_read >= 8 &&
753 memcmp(header, "BSDIFF40", 8) == 0) {
754 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
755 patch, 0, sink, token, &ctx);
756 } else if (header_bytes_read >= 8 &&
757 memcmp(header, "IMGDIFF2", 8) == 0) {
758 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
759 patch, sink, token, &ctx);
760 } else {
761 printf("Unknown patch file format\n");
762 return 1;
763 }
764
765 if (output >= 0) {
766 fsync(output);
767 close(output);
768 }
769
770 if (result != 0) {
771 if (retry == 0) {
772 printf("applying patch failed\n");
773 return result != 0;
774 } else {
775 printf("applying patch failed; retrying\n");
776 }
777 if (outname != NULL) {
778 unlink(outname);
779 }
780 } else {
781 // succeeded; no need to retry
782 break;
783 }
784 } while (retry-- > 0);
785
786 const uint8_t* current_target_sha1 = SHA_final(&ctx);
787 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
788 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -0800789 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800790 }
791
792 if (output < 0) {
793 // Copy the temp file to the MTD partition.
794 if (WriteToMTDPartition(msi.buffer, msi.pos, target_filename) != 0) {
795 printf("write of patched data to %s failed\n", target_filename);
796 return 1;
797 }
798 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -0800799 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800800 // Give the .patch file the same owner, group, and mode of the
801 // original source file.
802 if (chmod(outname, source_to_use->st.st_mode) != 0) {
803 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
804 return 1;
805 }
806 if (chown(outname, source_to_use->st.st_uid,
807 source_to_use->st.st_gid) != 0) {
808 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
809 return 1;
810 }
Doug Zongker512536a2010-02-17 16:11:44 -0800811
Doug Zongkerc4351c72010-02-22 14:46:32 -0800812 // Finally, rename the .patch file to replace the target file.
813 if (rename(outname, target_filename) != 0) {
814 printf("rename of .patch to \"%s\" failed: %s\n",
815 target_filename, strerror(errno));
816 return 1;
817 }
Doug Zongker512536a2010-02-17 16:11:44 -0800818 }
819
Doug Zongkerc4351c72010-02-22 14:46:32 -0800820 // If this run of applypatch created the copy, and we're here, we
821 // can delete it.
822 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -0800823
Doug Zongkerc4351c72010-02-22 14:46:32 -0800824 // Success!
825 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800826}