blob: 3f67c32dfed0a8945e25196c19b85aae84377ec4 [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],
Doug Zongkera3ccba62012-08-20 15:28:02 -070042 size_t target_size,
43 const Value* bonus_data);
Doug Zongker512536a2010-02-17 16:11:44 -080044
45static int mtd_partitions_scanned = 0;
46
Hristo Bojinovdb314d62010-08-02 10:29:49 -070047// Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
48// the retouched entries back to their original value (such that SHA-1 checks
49// don't fail due to randomization); store the file contents and associated
50// metadata in *file.
51//
52// Return 0 on success.
53int LoadFileContents(const char* filename, FileContents* file,
54 int retouch_flag) {
Doug Zongker512536a2010-02-17 16:11:44 -080055 file->data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -080056
Doug Zongkerf291d852010-07-07 13:55:25 -070057 // A special 'filename' beginning with "MTD:" or "EMMC:" means to
58 // load the contents of a partition.
59 if (strncmp(filename, "MTD:", 4) == 0 ||
60 strncmp(filename, "EMMC:", 5) == 0) {
61 return LoadPartitionContents(filename, file);
Doug Zongkerc4351c72010-02-22 14:46:32 -080062 }
Doug Zongker512536a2010-02-17 16:11:44 -080063
Doug Zongkerc4351c72010-02-22 14:46:32 -080064 if (stat(filename, &file->st) != 0) {
65 printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
66 return -1;
67 }
68
69 file->size = file->st.st_size;
70 file->data = malloc(file->size);
71
72 FILE* f = fopen(filename, "rb");
73 if (f == NULL) {
74 printf("failed to open \"%s\": %s\n", filename, strerror(errno));
75 free(file->data);
76 file->data = NULL;
77 return -1;
78 }
79
80 ssize_t bytes_read = fread(file->data, 1, file->size, f);
81 if (bytes_read != file->size) {
82 printf("short read of \"%s\" (%ld bytes of %ld)\n",
83 filename, (long)bytes_read, (long)file->size);
84 free(file->data);
85 file->data = NULL;
86 return -1;
87 }
88 fclose(f);
89
Hristo Bojinovdb314d62010-08-02 10:29:49 -070090 // apply_patch[_check] functions are blind to randomization. Randomization
91 // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
92 // within a file, this means the file is assumed "corrupt" for simplicity.
93 if (retouch_flag) {
94 int32_t desired_offset = 0;
95 if (retouch_mask_data(file->data, file->size,
96 &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
97 printf("error trying to mask retouch entries\n");
98 free(file->data);
99 file->data = NULL;
100 return -1;
101 }
102 }
103
Doug Zongkerc4351c72010-02-22 14:46:32 -0800104 SHA(file->data, file->size, file->sha1);
105 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800106}
107
108static size_t* size_array;
109// comparison function for qsort()ing an int array of indexes into
110// size_array[].
111static int compare_size_indices(const void* a, const void* b) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800112 int aa = *(int*)a;
113 int bb = *(int*)b;
114 if (size_array[aa] < size_array[bb]) {
115 return -1;
116 } else if (size_array[aa] > size_array[bb]) {
117 return 1;
118 } else {
119 return 0;
120 }
Doug Zongker512536a2010-02-17 16:11:44 -0800121}
122
Doug Zongkerf291d852010-07-07 13:55:25 -0700123// Load the contents of an MTD or EMMC partition into the provided
Doug Zongker512536a2010-02-17 16:11:44 -0800124// FileContents. filename should be a string of the form
Doug Zongkerf291d852010-07-07 13:55:25 -0700125// "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..." (or
126// "EMMC:<partition_device>:..."). The smallest size_n bytes for
127// which that prefix of the partition contents has the corresponding
128// sha1 hash will be loaded. It is acceptable for a size value to be
129// repeated with different sha1s. Will return 0 on success.
Doug Zongker512536a2010-02-17 16:11:44 -0800130//
131// This complexity is needed because if an OTA installation is
132// interrupted, the partition might contain either the source or the
133// target data, which might be of different lengths. We need to know
Doug Zongkerf291d852010-07-07 13:55:25 -0700134// the length in order to read from a partition (there is no
135// "end-of-file" marker), so the caller must specify the possible
136// lengths and the hash of the data, and we'll do the load expecting
137// to find one of those hashes.
138enum PartitionType { MTD, EMMC };
139
140static int LoadPartitionContents(const char* filename, FileContents* file) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800141 char* copy = strdup(filename);
142 const char* magic = strtok(copy, ":");
Doug Zongkerf291d852010-07-07 13:55:25 -0700143
144 enum PartitionType type;
145
146 if (strcmp(magic, "MTD") == 0) {
147 type = MTD;
148 } else if (strcmp(magic, "EMMC") == 0) {
149 type = EMMC;
150 } else {
151 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800152 filename);
153 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800154 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800155 const char* partition = strtok(NULL, ":");
Doug Zongker512536a2010-02-17 16:11:44 -0800156
Doug Zongkerc4351c72010-02-22 14:46:32 -0800157 int i;
158 int colons = 0;
159 for (i = 0; filename[i] != '\0'; ++i) {
160 if (filename[i] == ':') {
161 ++colons;
162 }
Doug Zongker512536a2010-02-17 16:11:44 -0800163 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800164 if (colons < 3 || colons%2 == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700165 printf("LoadPartitionContents called with bad filename (%s)\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800166 filename);
167 }
Doug Zongker512536a2010-02-17 16:11:44 -0800168
Doug Zongkerc4351c72010-02-22 14:46:32 -0800169 int pairs = (colons-1)/2; // # of (size,sha1) pairs in filename
170 int* index = malloc(pairs * sizeof(int));
171 size_t* size = malloc(pairs * sizeof(size_t));
172 char** sha1sum = malloc(pairs * sizeof(char*));
Doug Zongker512536a2010-02-17 16:11:44 -0800173
Doug Zongkerc4351c72010-02-22 14:46:32 -0800174 for (i = 0; i < pairs; ++i) {
175 const char* size_str = strtok(NULL, ":");
176 size[i] = strtol(size_str, NULL, 10);
177 if (size[i] == 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700178 printf("LoadPartitionContents called with bad size (%s)\n", filename);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800179 return -1;
180 }
181 sha1sum[i] = strtok(NULL, ":");
182 index[i] = i;
183 }
Doug Zongker512536a2010-02-17 16:11:44 -0800184
Doug Zongkerc4351c72010-02-22 14:46:32 -0800185 // sort the index[] array so it indexes the pairs in order of
186 // increasing size.
187 size_array = size;
188 qsort(index, pairs, sizeof(int), compare_size_indices);
Doug Zongker512536a2010-02-17 16:11:44 -0800189
Doug Zongkerf291d852010-07-07 13:55:25 -0700190 MtdReadContext* ctx = NULL;
191 FILE* dev = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800192
Doug Zongkerf291d852010-07-07 13:55:25 -0700193 switch (type) {
194 case MTD:
195 if (!mtd_partitions_scanned) {
196 mtd_scan_partitions();
197 mtd_partitions_scanned = 1;
198 }
Doug Zongker512536a2010-02-17 16:11:44 -0800199
Doug Zongkerf291d852010-07-07 13:55:25 -0700200 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
201 if (mtd == NULL) {
202 printf("mtd partition \"%s\" not found (loading %s)\n",
203 partition, filename);
204 return -1;
205 }
206
207 ctx = mtd_read_partition(mtd);
208 if (ctx == NULL) {
209 printf("failed to initialize read of mtd partition \"%s\"\n",
210 partition);
211 return -1;
212 }
213 break;
214
215 case EMMC:
216 dev = fopen(partition, "rb");
217 if (dev == NULL) {
218 printf("failed to open emmc partition \"%s\": %s\n",
219 partition, strerror(errno));
220 return -1;
221 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800222 }
Doug Zongker512536a2010-02-17 16:11:44 -0800223
Doug Zongkerc4351c72010-02-22 14:46:32 -0800224 SHA_CTX sha_ctx;
225 SHA_init(&sha_ctx);
226 uint8_t parsed_sha[SHA_DIGEST_SIZE];
227
228 // allocate enough memory to hold the largest size.
229 file->data = malloc(size[index[pairs-1]]);
230 char* p = (char*)file->data;
231 file->size = 0; // # bytes read so far
232
233 for (i = 0; i < pairs; ++i) {
234 // Read enough additional bytes to get us up to the next size
235 // (again, we're trying the possibilities in order of increasing
236 // size).
237 size_t next = size[index[i]] - file->size;
238 size_t read = 0;
239 if (next > 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700240 switch (type) {
241 case MTD:
242 read = mtd_read_data(ctx, p, next);
243 break;
244
245 case EMMC:
246 read = fread(p, 1, next, dev);
247 break;
248 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800249 if (next != read) {
250 printf("short read (%d bytes of %d) for partition \"%s\"\n",
251 read, next, partition);
252 free(file->data);
253 file->data = NULL;
254 return -1;
255 }
256 SHA_update(&sha_ctx, p, read);
257 file->size += read;
258 }
259
260 // Duplicate the SHA context and finalize the duplicate so we can
261 // check it against this pair's expected hash.
262 SHA_CTX temp_ctx;
263 memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
264 const uint8_t* sha_so_far = SHA_final(&temp_ctx);
265
266 if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
267 printf("failed to parse sha1 %s in %s\n",
268 sha1sum[index[i]], filename);
269 free(file->data);
270 file->data = NULL;
271 return -1;
272 }
273
274 if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
275 // we have a match. stop reading the partition; we'll return
276 // the data we've read so far.
Doug Zongkerf291d852010-07-07 13:55:25 -0700277 printf("partition read matched size %d sha %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800278 size[index[i]], sha1sum[index[i]]);
279 break;
280 }
281
282 p += read;
283 }
284
Doug Zongkerf291d852010-07-07 13:55:25 -0700285 switch (type) {
286 case MTD:
287 mtd_read_close(ctx);
288 break;
289
290 case EMMC:
291 fclose(dev);
292 break;
293 }
294
Doug Zongkerc4351c72010-02-22 14:46:32 -0800295
296 if (i == pairs) {
297 // Ran off the end of the list of (size,sha1) pairs without
298 // finding a match.
Doug Zongkerf291d852010-07-07 13:55:25 -0700299 printf("contents of partition \"%s\" didn't match %s\n",
Doug Zongkerc4351c72010-02-22 14:46:32 -0800300 partition, filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800301 free(file->data);
302 file->data = NULL;
303 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800304 }
305
Doug Zongkerc4351c72010-02-22 14:46:32 -0800306 const uint8_t* sha_final = SHA_final(&sha_ctx);
307 for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
308 file->sha1[i] = sha_final[i];
Doug Zongker512536a2010-02-17 16:11:44 -0800309 }
310
Doug Zongkerc4351c72010-02-22 14:46:32 -0800311 // Fake some stat() info.
312 file->st.st_mode = 0644;
313 file->st.st_uid = 0;
314 file->st.st_gid = 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800315
Doug Zongkerc4351c72010-02-22 14:46:32 -0800316 free(copy);
317 free(index);
318 free(size);
319 free(sha1sum);
Doug Zongker512536a2010-02-17 16:11:44 -0800320
Doug Zongkerc4351c72010-02-22 14:46:32 -0800321 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800322}
323
324
325// Save the contents of the given FileContents object under the given
326// filename. Return 0 on success.
Doug Zongker1c43c972012-02-28 11:07:09 -0800327int SaveFileContents(const char* filename, const FileContents* file) {
Nick Kralevich956cde82012-06-26 15:01:03 -0700328 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800329 if (fd < 0) {
330 printf("failed to open \"%s\" for write: %s\n",
331 filename, strerror(errno));
332 return -1;
333 }
Doug Zongker512536a2010-02-17 16:11:44 -0800334
Doug Zongker1c43c972012-02-28 11:07:09 -0800335 ssize_t bytes_written = FileSink(file->data, file->size, &fd);
336 if (bytes_written != file->size) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800337 printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
Doug Zongker1c43c972012-02-28 11:07:09 -0800338 filename, (long)bytes_written, (long)file->size,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800339 strerror(errno));
340 close(fd);
341 return -1;
342 }
343 fsync(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800344 close(fd);
Doug Zongker512536a2010-02-17 16:11:44 -0800345
Doug Zongker1c43c972012-02-28 11:07:09 -0800346 if (chmod(filename, file->st.st_mode) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800347 printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
348 return -1;
349 }
Doug Zongker1c43c972012-02-28 11:07:09 -0800350 if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800351 printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
352 return -1;
353 }
Doug Zongker512536a2010-02-17 16:11:44 -0800354
Doug Zongkerc4351c72010-02-22 14:46:32 -0800355 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800356}
357
Doug Zongkerf291d852010-07-07 13:55:25 -0700358// Write a memory buffer to 'target' partition, a string of the form
359// "MTD:<partition>[:...]" or "EMMC:<partition_device>:". Return 0 on
360// success.
361int WriteToPartition(unsigned char* data, size_t len,
362 const char* target) {
363 char* copy = strdup(target);
364 const char* magic = strtok(copy, ":");
365
366 enum PartitionType type;
367 if (strcmp(magic, "MTD") == 0) {
368 type = MTD;
369 } else if (strcmp(magic, "EMMC") == 0) {
370 type = EMMC;
371 } else {
372 printf("WriteToPartition called with bad target (%s)\n", target);
373 return -1;
374 }
375 const char* partition = strtok(NULL, ":");
376
Doug Zongkerc4351c72010-02-22 14:46:32 -0800377 if (partition == NULL) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700378 printf("bad partition target name \"%s\"\n", target);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800379 return -1;
380 }
Doug Zongker512536a2010-02-17 16:11:44 -0800381
Doug Zongkerf291d852010-07-07 13:55:25 -0700382 switch (type) {
383 case MTD:
384 if (!mtd_partitions_scanned) {
385 mtd_scan_partitions();
386 mtd_partitions_scanned = 1;
387 }
388
389 const MtdPartition* mtd = mtd_find_partition_by_name(partition);
390 if (mtd == NULL) {
391 printf("mtd partition \"%s\" not found for writing\n",
392 partition);
393 return -1;
394 }
395
396 MtdWriteContext* ctx = mtd_write_partition(mtd);
397 if (ctx == NULL) {
398 printf("failed to init mtd partition \"%s\" for writing\n",
399 partition);
400 return -1;
401 }
402
403 size_t written = mtd_write_data(ctx, (char*)data, len);
404 if (written != len) {
405 printf("only wrote %d of %d bytes to MTD %s\n",
406 written, len, partition);
407 mtd_write_close(ctx);
408 return -1;
409 }
410
411 if (mtd_erase_blocks(ctx, -1) < 0) {
412 printf("error finishing mtd write of %s\n", partition);
413 mtd_write_close(ctx);
414 return -1;
415 }
416
417 if (mtd_write_close(ctx)) {
418 printf("error closing mtd write of %s\n", partition);
419 return -1;
420 }
421 break;
422
423 case EMMC:
Doug Zongker044a0b42013-07-08 09:42:54 -0700424 {
425 size_t start = 0;
426 int success = 0;
Doug Zongkerc870a992013-07-09 10:34:46 -0700427 int fd = open(partition, O_RDWR);
428 if (fd < 0) {
Doug Zongker044a0b42013-07-08 09:42:54 -0700429 printf("failed to open %s: %s\n", partition, strerror(errno));
Doug Zongkerf291d852010-07-07 13:55:25 -0700430 return -1;
431 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700432 int attempt;
433
Doug Zongkerc870a992013-07-09 10:34:46 -0700434 for (attempt = 0; attempt < 10; ++attempt) {
435 off_t next_sync = start + (1<<20);
436 printf("raw write %s attempt %d start at %d\n", partition, attempt+1, start);
437 lseek(fd, start, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700438 while (start < len) {
439 size_t to_write = len - start;
Doug Zongkerc870a992013-07-09 10:34:46 -0700440 if (to_write > 4096) to_write = 4096;
Doug Zongker044a0b42013-07-08 09:42:54 -0700441
Doug Zongkerc870a992013-07-09 10:34:46 -0700442 ssize_t written = write(fd, data+start, to_write);
443 if (written < 0) {
444 if (errno == EINTR) {
445 written = 0;
446 } else {
447 printf("failed write writing to %s (%s)\n",
448 partition, strerror(errno));
449 return -1;
450 }
Doug Zongker044a0b42013-07-08 09:42:54 -0700451 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700452 start += written;
453 if (start >= next_sync) {
454 fsync(fd);
455 next_sync = start + (1<<20);
Doug Zongker044a0b42013-07-08 09:42:54 -0700456 }
457 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700458 fsync(fd);
Doug Zongker044a0b42013-07-08 09:42:54 -0700459
460 // drop caches so our subsequent verification read
461 // won't just be reading the cache.
462 sync();
Doug Zongkerc870a992013-07-09 10:34:46 -0700463 int dc = open("/proc/sys/vm/drop_caches", O_WRONLY);
464 write(dc, "3\n", 2);
465 close(dc);
Doug Zongker044a0b42013-07-08 09:42:54 -0700466 sleep(1);
467 printf(" caches dropped\n");
468
469 // verify
Doug Zongkerc870a992013-07-09 10:34:46 -0700470 lseek(fd, 0, SEEK_SET);
Doug Zongker044a0b42013-07-08 09:42:54 -0700471 unsigned char buffer[4096];
472 start = len;
473 size_t p;
474 for (p = 0; p < len; p += sizeof(buffer)) {
475 size_t to_read = len - p;
476 if (to_read > sizeof(buffer)) to_read = sizeof(buffer);
477
Doug Zongkerc870a992013-07-09 10:34:46 -0700478 size_t so_far = 0;
479 while (so_far < to_read) {
480 ssize_t read_count = read(fd, buffer+so_far, to_read-so_far);
481 if (read_count < 0) {
482 if (errno == EINTR) {
483 read_count = 0;
484 } else {
485 printf("verify read error %s at %d: %s\n",
486 partition, p, strerror(errno));
487 return -1;
488 }
489 }
490 if (read_count < to_read) {
491 printf("short verify read %s at %d: %d %d %s\n",
492 partition, p, read_count, to_read, strerror(errno));
493 }
494 so_far += read_count;
Doug Zongker044a0b42013-07-08 09:42:54 -0700495 }
496
497 if (memcmp(buffer, data+p, to_read)) {
498 printf("verification failed starting at %d\n", p);
499 start = p;
500 break;
501 }
502 }
503
504 if (start == len) {
505 printf("verification read succeeded (attempt %d)\n", attempt+1);
506 success = true;
507 break;
508 }
Doug Zongkerc870a992013-07-09 10:34:46 -0700509
510 sleep(2);
Doug Zongker044a0b42013-07-08 09:42:54 -0700511 }
512
513 if (!success) {
514 printf("failed to verify after all attempts\n");
515 return -1;
516 }
517
Doug Zongkerc870a992013-07-09 10:34:46 -0700518 if (close(fd) != 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -0700519 printf("error closing %s (%s)\n", partition, strerror(errno));
520 return -1;
521 }
522 break;
Doug Zongker044a0b42013-07-08 09:42:54 -0700523 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800524 }
Doug Zongker512536a2010-02-17 16:11:44 -0800525
Doug Zongkerf291d852010-07-07 13:55:25 -0700526 free(copy);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800527 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800528}
529
530
531// Take a string 'str' of 40 hex digits and parse it into the 20
532// byte array 'digest'. 'str' may contain only the digest or be of
533// the form "<digest>:<anything>". Return 0 on success, -1 on any
534// error.
535int ParseSha1(const char* str, uint8_t* digest) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800536 int i;
537 const char* ps = str;
538 uint8_t* pd = digest;
539 for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
540 int digit;
541 if (*ps >= '0' && *ps <= '9') {
542 digit = *ps - '0';
543 } else if (*ps >= 'a' && *ps <= 'f') {
544 digit = *ps - 'a' + 10;
545 } else if (*ps >= 'A' && *ps <= 'F') {
546 digit = *ps - 'A' + 10;
547 } else {
548 return -1;
549 }
550 if (i % 2 == 0) {
551 *pd = digit << 4;
552 } else {
553 *pd |= digit;
554 ++pd;
555 }
Doug Zongker512536a2010-02-17 16:11:44 -0800556 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800557 if (*ps != '\0') return -1;
558 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800559}
560
Doug Zongkerc4351c72010-02-22 14:46:32 -0800561// Search an array of sha1 strings for one matching the given sha1.
562// Return the index of the match on success, or -1 if no match is
563// found.
Doug Zongker044a0b42013-07-08 09:42:54 -0700564int FindMatchingPatch(uint8_t* sha1, char* const * const patch_sha1_str,
Doug Zongkerc4351c72010-02-22 14:46:32 -0800565 int num_patches) {
566 int i;
567 uint8_t patch_sha1[SHA_DIGEST_SIZE];
568 for (i = 0; i < num_patches; ++i) {
569 if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
570 memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
571 return i;
572 }
Doug Zongker512536a2010-02-17 16:11:44 -0800573 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800574 return -1;
Doug Zongker512536a2010-02-17 16:11:44 -0800575}
576
577// Returns 0 if the contents of the file (argv[2]) or the cached file
578// match any of the sha1's on the command line (argv[3:]). Returns
579// nonzero otherwise.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800580int applypatch_check(const char* filename,
581 int num_patches, char** const patch_sha1_str) {
582 FileContents file;
583 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800584
Doug Zongkerc4351c72010-02-22 14:46:32 -0800585 // It's okay to specify no sha1s; the check will pass if the
Doug Zongkerf291d852010-07-07 13:55:25 -0700586 // LoadFileContents is successful. (Useful for reading
Doug Zongkerc4351c72010-02-22 14:46:32 -0800587 // partitions, where the filename encodes the sha1s; no need to
588 // check them twice.)
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700589 if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
Doug Zongkerc4351c72010-02-22 14:46:32 -0800590 (num_patches > 0 &&
591 FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
592 printf("file \"%s\" doesn't have any of expected "
593 "sha1 sums; checking cache\n", filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800594
Doug Zongkerc4351c72010-02-22 14:46:32 -0800595 free(file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800596 file.data = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800597
Doug Zongkerc4351c72010-02-22 14:46:32 -0800598 // If the source file is missing or corrupted, it might be because
599 // we were killed in the middle of patching it. A copy of it
600 // should have been made in CACHE_TEMP_SOURCE. If that file
601 // exists and matches the sha1 we're looking for, the check still
602 // passes.
603
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700604 if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800605 printf("failed to load cache file\n");
606 return 1;
607 }
608
609 if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
610 printf("cache bits don't match any sha1 for \"%s\"\n", filename);
611 free(file.data);
612 return 1;
613 }
614 }
Doug Zongker512536a2010-02-17 16:11:44 -0800615
616 free(file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800617 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800618}
619
620int ShowLicenses() {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800621 ShowBSDiffLicense();
622 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -0800623}
624
625ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800626 int fd = *(int *)token;
627 ssize_t done = 0;
628 ssize_t wrote;
629 while (done < (ssize_t) len) {
630 wrote = write(fd, data+done, len-done);
631 if (wrote <= 0) {
632 printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
633 return done;
634 }
635 done += wrote;
Doug Zongker512536a2010-02-17 16:11:44 -0800636 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800637 return done;
Doug Zongker512536a2010-02-17 16:11:44 -0800638}
639
640typedef struct {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800641 unsigned char* buffer;
642 ssize_t size;
643 ssize_t pos;
Doug Zongker512536a2010-02-17 16:11:44 -0800644} MemorySinkInfo;
645
646ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800647 MemorySinkInfo* msi = (MemorySinkInfo*)token;
648 if (msi->size - msi->pos < len) {
649 return -1;
650 }
651 memcpy(msi->buffer + msi->pos, data, len);
652 msi->pos += len;
653 return len;
Doug Zongker512536a2010-02-17 16:11:44 -0800654}
655
656// Return the amount of free space (in bytes) on the filesystem
657// containing filename. filename must exist. Return -1 on error.
658size_t FreeSpaceForFile(const char* filename) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800659 struct statfs sf;
660 if (statfs(filename, &sf) != 0) {
661 printf("failed to statfs %s: %s\n", filename, strerror(errno));
662 return -1;
663 }
664 return sf.f_bsize * sf.f_bfree;
Doug Zongker512536a2010-02-17 16:11:44 -0800665}
666
Doug Zongkerc4351c72010-02-22 14:46:32 -0800667int CacheSizeCheck(size_t bytes) {
668 if (MakeFreeSpaceOnCache(bytes) < 0) {
669 printf("unable to make %ld bytes available on /cache\n", (long)bytes);
670 return 1;
671 } else {
672 return 0;
673 }
674}
675
Doug Zongkerbf80f492012-10-19 12:24:26 -0700676static void print_short_sha1(const uint8_t sha1[SHA_DIGEST_SIZE]) {
677 int i;
678 const char* hex = "0123456789abcdef";
679 for (i = 0; i < 4; ++i) {
680 putchar(hex[(sha1[i]>>4) & 0xf]);
681 putchar(hex[sha1[i] & 0xf]);
682 }
683}
Doug Zongkerc4351c72010-02-22 14:46:32 -0800684
685// This function applies binary patches to files in a way that is safe
Doug Zongker512536a2010-02-17 16:11:44 -0800686// (the original file is not touched until we have the desired
687// replacement for it) and idempotent (it's okay to run this program
688// multiple times).
689//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800690// - if the sha1 hash of <target_filename> is <target_sha1_string>,
691// does nothing and exits successfully.
Doug Zongker512536a2010-02-17 16:11:44 -0800692//
Doug Zongkerc4351c72010-02-22 14:46:32 -0800693// - otherwise, if the sha1 hash of <source_filename> is one of the
694// entries in <patch_sha1_str>, the corresponding patch from
695// <patch_data> (which must be a VAL_BLOB) is applied to produce a
696// new file (the type of patch is automatically detected from the
697// blob daat). If that new file has sha1 hash <target_sha1_str>,
698// moves it to replace <target_filename>, and exits successfully.
699// Note that if <source_filename> and <target_filename> are not the
700// same, <source_filename> is NOT deleted on success.
701// <target_filename> may be the string "-" to mean "the same as
702// source_filename".
Doug Zongker512536a2010-02-17 16:11:44 -0800703//
704// - otherwise, or if any error is encountered, exits with non-zero
705// status.
706//
Doug Zongkerf291d852010-07-07 13:55:25 -0700707// <source_filename> may refer to a partition to read the source data.
708// See the comments for the LoadPartition Contents() function above
Doug Zongkerc4351c72010-02-22 14:46:32 -0800709// for the format of such a filename.
Doug Zongker512536a2010-02-17 16:11:44 -0800710
Doug Zongkerc4351c72010-02-22 14:46:32 -0800711int applypatch(const char* source_filename,
712 const char* target_filename,
713 const char* target_sha1_str,
714 size_t target_size,
715 int num_patches,
716 char** const patch_sha1_str,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700717 Value** patch_data,
718 Value* bonus_data) {
Doug Zongkerbf80f492012-10-19 12:24:26 -0700719 printf("patch %s: ", source_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800720
Doug Zongkerc4351c72010-02-22 14:46:32 -0800721 if (target_filename[0] == '-' &&
722 target_filename[1] == '\0') {
723 target_filename = source_filename;
Doug Zongker512536a2010-02-17 16:11:44 -0800724 }
725
Doug Zongkerc4351c72010-02-22 14:46:32 -0800726 uint8_t target_sha1[SHA_DIGEST_SIZE];
727 if (ParseSha1(target_sha1_str, target_sha1) != 0) {
728 printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
Doug Zongker512536a2010-02-17 16:11:44 -0800729 return 1;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800730 }
Doug Zongker512536a2010-02-17 16:11:44 -0800731
Doug Zongkerc4351c72010-02-22 14:46:32 -0800732 FileContents copy_file;
733 FileContents source_file;
Doug Zongker1c43c972012-02-28 11:07:09 -0800734 copy_file.data = NULL;
735 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800736 const Value* source_patch_value = NULL;
737 const Value* copy_patch_value = NULL;
Doug Zongker512536a2010-02-17 16:11:44 -0800738
Doug Zongkerc4351c72010-02-22 14:46:32 -0800739 // We try to load the target file into the source_file object.
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700740 if (LoadFileContents(target_filename, &source_file,
741 RETOUCH_DO_MASK) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800742 if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
743 // The early-exit case: the patch was already applied, this file
744 // has the desired hash, nothing for us to do.
Doug Zongkerbf80f492012-10-19 12:24:26 -0700745 printf("already ");
746 print_short_sha1(target_sha1);
747 putchar('\n');
Doug Zongker1c43c972012-02-28 11:07:09 -0800748 free(source_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800749 return 0;
750 }
751 }
Doug Zongker512536a2010-02-17 16:11:44 -0800752
Doug Zongkerc4351c72010-02-22 14:46:32 -0800753 if (source_file.data == NULL ||
754 (target_filename != source_filename &&
755 strcmp(target_filename, source_filename) != 0)) {
756 // Need to load the source file: either we failed to load the
757 // target file, or we did but it's different from the source file.
758 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800759 source_file.data = NULL;
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700760 LoadFileContents(source_filename, &source_file,
761 RETOUCH_DO_MASK);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800762 }
763
764 if (source_file.data != NULL) {
765 int to_use = FindMatchingPatch(source_file.sha1,
766 patch_sha1_str, num_patches);
767 if (to_use >= 0) {
768 source_patch_value = patch_data[to_use];
769 }
770 }
771
772 if (source_patch_value == NULL) {
773 free(source_file.data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800774 source_file.data = NULL;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800775 printf("source file is bad; trying copy\n");
776
Hristo Bojinovdb314d62010-08-02 10:29:49 -0700777 if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
778 RETOUCH_DO_MASK) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800779 // fail.
780 printf("failed to read copy file\n");
781 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800782 }
783
Doug Zongkerc4351c72010-02-22 14:46:32 -0800784 int to_use = FindMatchingPatch(copy_file.sha1,
785 patch_sha1_str, num_patches);
Doug Zongker8cd9e4f2010-08-12 17:38:09 -0700786 if (to_use >= 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800787 copy_patch_value = patch_data[to_use];
Doug Zongker512536a2010-02-17 16:11:44 -0800788 }
789
Doug Zongkerc4351c72010-02-22 14:46:32 -0800790 if (copy_patch_value == NULL) {
791 // fail.
792 printf("copy file doesn't match source SHA-1s either\n");
Doug Zongker1c43c972012-02-28 11:07:09 -0800793 free(copy_file.data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800794 return 1;
Doug Zongker512536a2010-02-17 16:11:44 -0800795 }
Doug Zongker512536a2010-02-17 16:11:44 -0800796 }
797
Doug Zongker1c43c972012-02-28 11:07:09 -0800798 int result = GenerateTarget(&source_file, source_patch_value,
799 &copy_file, copy_patch_value,
800 source_filename, target_filename,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700801 target_sha1, target_size, bonus_data);
Doug Zongker1c43c972012-02-28 11:07:09 -0800802 free(source_file.data);
803 free(copy_file.data);
804
805 return result;
806}
807
808static int GenerateTarget(FileContents* source_file,
809 const Value* source_patch_value,
810 FileContents* copy_file,
811 const Value* copy_patch_value,
812 const char* source_filename,
813 const char* target_filename,
814 const uint8_t target_sha1[SHA_DIGEST_SIZE],
Doug Zongkera3ccba62012-08-20 15:28:02 -0700815 size_t target_size,
816 const Value* bonus_data) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800817 int retry = 1;
818 SHA_CTX ctx;
819 int output;
820 MemorySinkInfo msi;
821 FileContents* source_to_use;
822 char* outname;
Doug Zongker1c43c972012-02-28 11:07:09 -0800823 int made_copy = 0;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800824
825 // assume that target_filename (eg "/system/app/Foo.apk") is located
826 // on the same filesystem as its top-level directory ("/system").
827 // We need something that exists for calling statfs().
828 char target_fs[strlen(target_filename)+1];
829 char* slash = strchr(target_filename+1, '/');
830 if (slash != NULL) {
831 int count = slash - target_filename;
832 strncpy(target_fs, target_filename, count);
833 target_fs[count] = '\0';
Doug Zongker512536a2010-02-17 16:11:44 -0800834 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800835 strcpy(target_fs, target_filename);
Doug Zongker512536a2010-02-17 16:11:44 -0800836 }
837
Doug Zongkerc4351c72010-02-22 14:46:32 -0800838 do {
839 // Is there enough room in the target filesystem to hold the patched
840 // file?
841
Doug Zongkerf291d852010-07-07 13:55:25 -0700842 if (strncmp(target_filename, "MTD:", 4) == 0 ||
843 strncmp(target_filename, "EMMC:", 5) == 0) {
844 // If the target is a partition, we're actually going to
845 // write the output to /tmp and then copy it to the
846 // partition. statfs() always returns 0 blocks free for
847 // /tmp, so instead we'll just assume that /tmp has enough
848 // space to hold the file.
Doug Zongkerc4351c72010-02-22 14:46:32 -0800849
Doug Zongkerf291d852010-07-07 13:55:25 -0700850 // We still write the original source to cache, in case
851 // the partition write is interrupted.
Doug Zongker1c43c972012-02-28 11:07:09 -0800852 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800853 printf("not enough free space on /cache\n");
854 return 1;
855 }
856 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
857 printf("failed to back up source file\n");
858 return 1;
859 }
860 made_copy = 1;
861 retry = 0;
862 } else {
863 int enough_space = 0;
864 if (retry > 0) {
865 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongker201cd462010-08-13 09:41:21 -0700866 enough_space =
867 (free_space > (256 << 10)) && // 256k (two-block) minimum
Doug Zongkerc4351c72010-02-22 14:46:32 -0800868 (free_space > (target_size * 3 / 2)); // 50% margin of error
Doug Zongkerbf80f492012-10-19 12:24:26 -0700869 if (!enough_space) {
870 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
871 (long)target_size, (long)free_space, retry, enough_space);
872 }
Doug Zongkerc4351c72010-02-22 14:46:32 -0800873 }
874
875 if (!enough_space) {
876 retry = 0;
877 }
878
879 if (!enough_space && source_patch_value != NULL) {
880 // Using the original source, but not enough free space. First
881 // copy the source file to cache, then delete it from the original
882 // location.
883
Doug Zongkerf291d852010-07-07 13:55:25 -0700884 if (strncmp(source_filename, "MTD:", 4) == 0 ||
885 strncmp(source_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800886 // It's impossible to free space on the target filesystem by
Doug Zongkerf291d852010-07-07 13:55:25 -0700887 // deleting the source if the source is a partition. If
Doug Zongkerc4351c72010-02-22 14:46:32 -0800888 // we're ever in a state where we need to do this, fail.
Doug Zongkerf291d852010-07-07 13:55:25 -0700889 printf("not enough free space for target but source "
890 "is partition\n");
Doug Zongkerc4351c72010-02-22 14:46:32 -0800891 return 1;
892 }
893
Doug Zongker1c43c972012-02-28 11:07:09 -0800894 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800895 printf("not enough free space on /cache\n");
896 return 1;
897 }
898
899 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
900 printf("failed to back up source file\n");
901 return 1;
902 }
903 made_copy = 1;
904 unlink(source_filename);
905
906 size_t free_space = FreeSpaceForFile(target_fs);
Doug Zongkerbf80f492012-10-19 12:24:26 -0700907 printf("(now %ld bytes free for target) ", (long)free_space);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800908 }
909 }
910
911 const Value* patch;
912 if (source_patch_value != NULL) {
Doug Zongker1c43c972012-02-28 11:07:09 -0800913 source_to_use = source_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800914 patch = source_patch_value;
915 } else {
Doug Zongker1c43c972012-02-28 11:07:09 -0800916 source_to_use = copy_file;
Doug Zongkerc4351c72010-02-22 14:46:32 -0800917 patch = copy_patch_value;
918 }
919
920 if (patch->type != VAL_BLOB) {
921 printf("patch is not a blob\n");
922 return 1;
923 }
924
925 SinkFn sink = NULL;
926 void* token = NULL;
927 output = -1;
928 outname = NULL;
Doug Zongkerf291d852010-07-07 13:55:25 -0700929 if (strncmp(target_filename, "MTD:", 4) == 0 ||
930 strncmp(target_filename, "EMMC:", 5) == 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -0800931 // We store the decoded output in memory.
932 msi.buffer = malloc(target_size);
933 if (msi.buffer == NULL) {
934 printf("failed to alloc %ld bytes for output\n",
935 (long)target_size);
936 return 1;
937 }
938 msi.pos = 0;
939 msi.size = target_size;
940 sink = MemorySink;
941 token = &msi;
942 } else {
943 // We write the decoded output to "<tgt-file>.patch".
944 outname = (char*)malloc(strlen(target_filename) + 10);
945 strcpy(outname, target_filename);
946 strcat(outname, ".patch");
947
Nick Kralevich956cde82012-06-26 15:01:03 -0700948 output = open(outname, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800949 if (output < 0) {
950 printf("failed to open output file %s: %s\n",
951 outname, strerror(errno));
952 return 1;
953 }
954 sink = FileSink;
955 token = &output;
956 }
957
958 char* header = patch->data;
959 ssize_t header_bytes_read = patch->size;
960
961 SHA_init(&ctx);
962
963 int result;
964
965 if (header_bytes_read >= 8 &&
966 memcmp(header, "BSDIFF40", 8) == 0) {
967 result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
968 patch, 0, sink, token, &ctx);
969 } else if (header_bytes_read >= 8 &&
970 memcmp(header, "IMGDIFF2", 8) == 0) {
971 result = ApplyImagePatch(source_to_use->data, source_to_use->size,
Doug Zongkera3ccba62012-08-20 15:28:02 -0700972 patch, sink, token, &ctx, bonus_data);
Doug Zongkerc4351c72010-02-22 14:46:32 -0800973 } else {
974 printf("Unknown patch file format\n");
975 return 1;
976 }
977
978 if (output >= 0) {
979 fsync(output);
980 close(output);
981 }
982
983 if (result != 0) {
984 if (retry == 0) {
985 printf("applying patch failed\n");
986 return result != 0;
987 } else {
988 printf("applying patch failed; retrying\n");
989 }
990 if (outname != NULL) {
991 unlink(outname);
992 }
993 } else {
994 // succeeded; no need to retry
995 break;
996 }
997 } while (retry-- > 0);
998
999 const uint8_t* current_target_sha1 = SHA_final(&ctx);
1000 if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
1001 printf("patch did not produce expected sha1\n");
Doug Zongker512536a2010-02-17 16:11:44 -08001002 return 1;
Doug Zongkerbf80f492012-10-19 12:24:26 -07001003 } else {
1004 printf("now ");
1005 print_short_sha1(target_sha1);
1006 putchar('\n');
Doug Zongkerc4351c72010-02-22 14:46:32 -08001007 }
1008
1009 if (output < 0) {
Doug Zongkerf291d852010-07-07 13:55:25 -07001010 // Copy the temp file to the partition.
1011 if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001012 printf("write of patched data to %s failed\n", target_filename);
1013 return 1;
1014 }
1015 free(msi.buffer);
Doug Zongker512536a2010-02-17 16:11:44 -08001016 } else {
Doug Zongkerc4351c72010-02-22 14:46:32 -08001017 // Give the .patch file the same owner, group, and mode of the
1018 // original source file.
1019 if (chmod(outname, source_to_use->st.st_mode) != 0) {
1020 printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
1021 return 1;
1022 }
1023 if (chown(outname, source_to_use->st.st_uid,
1024 source_to_use->st.st_gid) != 0) {
1025 printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
1026 return 1;
1027 }
Doug Zongker512536a2010-02-17 16:11:44 -08001028
Doug Zongkerc4351c72010-02-22 14:46:32 -08001029 // Finally, rename the .patch file to replace the target file.
1030 if (rename(outname, target_filename) != 0) {
1031 printf("rename of .patch to \"%s\" failed: %s\n",
1032 target_filename, strerror(errno));
1033 return 1;
1034 }
Doug Zongker512536a2010-02-17 16:11:44 -08001035 }
1036
Doug Zongkerc4351c72010-02-22 14:46:32 -08001037 // If this run of applypatch created the copy, and we're here, we
1038 // can delete it.
1039 if (made_copy) unlink(CACHE_TEMP_SOURCE);
Doug Zongker512536a2010-02-17 16:11:44 -08001040
Doug Zongkerc4351c72010-02-22 14:46:32 -08001041 // Success!
1042 return 0;
Doug Zongker512536a2010-02-17 16:11:44 -08001043}