• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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"
31 #include "edify/expr.h"
32 
33 static int LoadPartitionContents(const char* filename, FileContents* file);
34 static ssize_t FileSink(unsigned char* data, ssize_t len, void* token);
35 static int GenerateTarget(FileContents* source_file,
36                           const Value* source_patch_value,
37                           FileContents* copy_file,
38                           const Value* copy_patch_value,
39                           const char* source_filename,
40                           const char* target_filename,
41                           const uint8_t target_sha1[SHA_DIGEST_SIZE],
42                           size_t target_size);
43 
44 static int mtd_partitions_scanned = 0;
45 
46 // Read a file into memory; optionally (retouch_flag == RETOUCH_DO_MASK) mask
47 // the retouched entries back to their original value (such that SHA-1 checks
48 // don't fail due to randomization); store the file contents and associated
49 // metadata in *file.
50 //
51 // Return 0 on success.
LoadFileContents(const char * filename,FileContents * file,int retouch_flag)52 int LoadFileContents(const char* filename, FileContents* file,
53                      int retouch_flag) {
54     file->data = NULL;
55 
56     // A special 'filename' beginning with "MTD:" or "EMMC:" means to
57     // load the contents of a partition.
58     if (strncmp(filename, "MTD:", 4) == 0 ||
59         strncmp(filename, "EMMC:", 5) == 0) {
60         return LoadPartitionContents(filename, file);
61     }
62 
63     if (stat(filename, &file->st) != 0) {
64         printf("failed to stat \"%s\": %s\n", filename, strerror(errno));
65         return -1;
66     }
67 
68     file->size = file->st.st_size;
69     file->data = malloc(file->size);
70 
71     FILE* f = fopen(filename, "rb");
72     if (f == NULL) {
73         printf("failed to open \"%s\": %s\n", filename, strerror(errno));
74         free(file->data);
75         file->data = NULL;
76         return -1;
77     }
78 
79     ssize_t bytes_read = fread(file->data, 1, file->size, f);
80     if (bytes_read != file->size) {
81         printf("short read of \"%s\" (%ld bytes of %ld)\n",
82                filename, (long)bytes_read, (long)file->size);
83         free(file->data);
84         file->data = NULL;
85         return -1;
86     }
87     fclose(f);
88 
89     // apply_patch[_check] functions are blind to randomization. Randomization
90     // is taken care of in [Undo]RetouchBinariesFn. If there is a mismatch
91     // within a file, this means the file is assumed "corrupt" for simplicity.
92     if (retouch_flag) {
93         int32_t desired_offset = 0;
94         if (retouch_mask_data(file->data, file->size,
95                               &desired_offset, NULL) != RETOUCH_DATA_MATCHED) {
96             printf("error trying to mask retouch entries\n");
97             free(file->data);
98             file->data = NULL;
99             return -1;
100         }
101     }
102 
103     SHA(file->data, file->size, file->sha1);
104     return 0;
105 }
106 
107 static size_t* size_array;
108 // comparison function for qsort()ing an int array of indexes into
109 // size_array[].
compare_size_indices(const void * a,const void * b)110 static int compare_size_indices(const void* a, const void* b) {
111     int aa = *(int*)a;
112     int bb = *(int*)b;
113     if (size_array[aa] < size_array[bb]) {
114         return -1;
115     } else if (size_array[aa] > size_array[bb]) {
116         return 1;
117     } else {
118         return 0;
119     }
120 }
121 
122 // Load the contents of an MTD or EMMC partition into the provided
123 // FileContents.  filename should be a string of the form
124 // "MTD:<partition_name>:<size_1>:<sha1_1>:<size_2>:<sha1_2>:..."  (or
125 // "EMMC:<partition_device>:...").  The smallest size_n bytes for
126 // which that prefix of the partition contents has the corresponding
127 // sha1 hash will be loaded.  It is acceptable for a size value to be
128 // repeated with different sha1s.  Will return 0 on success.
129 //
130 // This complexity is needed because if an OTA installation is
131 // interrupted, the partition might contain either the source or the
132 // target data, which might be of different lengths.  We need to know
133 // the length in order to read from a partition (there is no
134 // "end-of-file" marker), so the caller must specify the possible
135 // lengths and the hash of the data, and we'll do the load expecting
136 // to find one of those hashes.
137 enum PartitionType { MTD, EMMC };
138 
LoadPartitionContents(const char * filename,FileContents * file)139 static int LoadPartitionContents(const char* filename, FileContents* file) {
140     char* copy = strdup(filename);
141     const char* magic = strtok(copy, ":");
142 
143     enum PartitionType type;
144 
145     if (strcmp(magic, "MTD") == 0) {
146         type = MTD;
147     } else if (strcmp(magic, "EMMC") == 0) {
148         type = EMMC;
149     } else {
150         printf("LoadPartitionContents called with bad filename (%s)\n",
151                filename);
152         return -1;
153     }
154     const char* partition = strtok(NULL, ":");
155 
156     int i;
157     int colons = 0;
158     for (i = 0; filename[i] != '\0'; ++i) {
159         if (filename[i] == ':') {
160             ++colons;
161         }
162     }
163     if (colons < 3 || colons%2 == 0) {
164         printf("LoadPartitionContents called with bad filename (%s)\n",
165                filename);
166     }
167 
168     int pairs = (colons-1)/2;     // # of (size,sha1) pairs in filename
169     int* index = malloc(pairs * sizeof(int));
170     size_t* size = malloc(pairs * sizeof(size_t));
171     char** sha1sum = malloc(pairs * sizeof(char*));
172 
173     for (i = 0; i < pairs; ++i) {
174         const char* size_str = strtok(NULL, ":");
175         size[i] = strtol(size_str, NULL, 10);
176         if (size[i] == 0) {
177             printf("LoadPartitionContents called with bad size (%s)\n", filename);
178             return -1;
179         }
180         sha1sum[i] = strtok(NULL, ":");
181         index[i] = i;
182     }
183 
184     // sort the index[] array so it indexes the pairs in order of
185     // increasing size.
186     size_array = size;
187     qsort(index, pairs, sizeof(int), compare_size_indices);
188 
189     MtdReadContext* ctx = NULL;
190     FILE* dev = NULL;
191 
192     switch (type) {
193         case MTD:
194             if (!mtd_partitions_scanned) {
195                 mtd_scan_partitions();
196                 mtd_partitions_scanned = 1;
197             }
198 
199             const MtdPartition* mtd = mtd_find_partition_by_name(partition);
200             if (mtd == NULL) {
201                 printf("mtd partition \"%s\" not found (loading %s)\n",
202                        partition, filename);
203                 return -1;
204             }
205 
206             ctx = mtd_read_partition(mtd);
207             if (ctx == NULL) {
208                 printf("failed to initialize read of mtd partition \"%s\"\n",
209                        partition);
210                 return -1;
211             }
212             break;
213 
214         case EMMC:
215             dev = fopen(partition, "rb");
216             if (dev == NULL) {
217                 printf("failed to open emmc partition \"%s\": %s\n",
218                        partition, strerror(errno));
219                 return -1;
220             }
221     }
222 
223     SHA_CTX sha_ctx;
224     SHA_init(&sha_ctx);
225     uint8_t parsed_sha[SHA_DIGEST_SIZE];
226 
227     // allocate enough memory to hold the largest size.
228     file->data = malloc(size[index[pairs-1]]);
229     char* p = (char*)file->data;
230     file->size = 0;                // # bytes read so far
231 
232     for (i = 0; i < pairs; ++i) {
233         // Read enough additional bytes to get us up to the next size
234         // (again, we're trying the possibilities in order of increasing
235         // size).
236         size_t next = size[index[i]] - file->size;
237         size_t read = 0;
238         if (next > 0) {
239             switch (type) {
240                 case MTD:
241                     read = mtd_read_data(ctx, p, next);
242                     break;
243 
244                 case EMMC:
245                     read = fread(p, 1, next, dev);
246                     break;
247             }
248             if (next != read) {
249                 printf("short read (%d bytes of %d) for partition \"%s\"\n",
250                        read, next, partition);
251                 free(file->data);
252                 file->data = NULL;
253                 return -1;
254             }
255             SHA_update(&sha_ctx, p, read);
256             file->size += read;
257         }
258 
259         // Duplicate the SHA context and finalize the duplicate so we can
260         // check it against this pair's expected hash.
261         SHA_CTX temp_ctx;
262         memcpy(&temp_ctx, &sha_ctx, sizeof(SHA_CTX));
263         const uint8_t* sha_so_far = SHA_final(&temp_ctx);
264 
265         if (ParseSha1(sha1sum[index[i]], parsed_sha) != 0) {
266             printf("failed to parse sha1 %s in %s\n",
267                    sha1sum[index[i]], filename);
268             free(file->data);
269             file->data = NULL;
270             return -1;
271         }
272 
273         if (memcmp(sha_so_far, parsed_sha, SHA_DIGEST_SIZE) == 0) {
274             // we have a match.  stop reading the partition; we'll return
275             // the data we've read so far.
276             printf("partition read matched size %d sha %s\n",
277                    size[index[i]], sha1sum[index[i]]);
278             break;
279         }
280 
281         p += read;
282     }
283 
284     switch (type) {
285         case MTD:
286             mtd_read_close(ctx);
287             break;
288 
289         case EMMC:
290             fclose(dev);
291             break;
292     }
293 
294 
295     if (i == pairs) {
296         // Ran off the end of the list of (size,sha1) pairs without
297         // finding a match.
298         printf("contents of partition \"%s\" didn't match %s\n",
299                partition, filename);
300         free(file->data);
301         file->data = NULL;
302         return -1;
303     }
304 
305     const uint8_t* sha_final = SHA_final(&sha_ctx);
306     for (i = 0; i < SHA_DIGEST_SIZE; ++i) {
307         file->sha1[i] = sha_final[i];
308     }
309 
310     // Fake some stat() info.
311     file->st.st_mode = 0644;
312     file->st.st_uid = 0;
313     file->st.st_gid = 0;
314 
315     free(copy);
316     free(index);
317     free(size);
318     free(sha1sum);
319 
320     return 0;
321 }
322 
323 
324 // Save the contents of the given FileContents object under the given
325 // filename.  Return 0 on success.
SaveFileContents(const char * filename,const FileContents * file)326 int SaveFileContents(const char* filename, const FileContents* file) {
327     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
328     if (fd < 0) {
329         printf("failed to open \"%s\" for write: %s\n",
330                filename, strerror(errno));
331         return -1;
332     }
333 
334     ssize_t bytes_written = FileSink(file->data, file->size, &fd);
335     if (bytes_written != file->size) {
336         printf("short write of \"%s\" (%ld bytes of %ld) (%s)\n",
337                filename, (long)bytes_written, (long)file->size,
338                strerror(errno));
339         close(fd);
340         return -1;
341     }
342     fsync(fd);
343     close(fd);
344 
345     if (chmod(filename, file->st.st_mode) != 0) {
346         printf("chmod of \"%s\" failed: %s\n", filename, strerror(errno));
347         return -1;
348     }
349     if (chown(filename, file->st.st_uid, file->st.st_gid) != 0) {
350         printf("chown of \"%s\" failed: %s\n", filename, strerror(errno));
351         return -1;
352     }
353 
354     return 0;
355 }
356 
357 // Write a memory buffer to 'target' partition, a string of the form
358 // "MTD:<partition>[:...]" or "EMMC:<partition_device>:".  Return 0 on
359 // success.
WriteToPartition(unsigned char * data,size_t len,const char * target)360 int WriteToPartition(unsigned char* data, size_t len,
361                         const char* target) {
362     char* copy = strdup(target);
363     const char* magic = strtok(copy, ":");
364 
365     enum PartitionType type;
366     if (strcmp(magic, "MTD") == 0) {
367         type = MTD;
368     } else if (strcmp(magic, "EMMC") == 0) {
369         type = EMMC;
370     } else {
371         printf("WriteToPartition called with bad target (%s)\n", target);
372         return -1;
373     }
374     const char* partition = strtok(NULL, ":");
375 
376     if (partition == NULL) {
377         printf("bad partition target name \"%s\"\n", target);
378         return -1;
379     }
380 
381     switch (type) {
382         case MTD:
383             if (!mtd_partitions_scanned) {
384                 mtd_scan_partitions();
385                 mtd_partitions_scanned = 1;
386             }
387 
388             const MtdPartition* mtd = mtd_find_partition_by_name(partition);
389             if (mtd == NULL) {
390                 printf("mtd partition \"%s\" not found for writing\n",
391                        partition);
392                 return -1;
393             }
394 
395             MtdWriteContext* ctx = mtd_write_partition(mtd);
396             if (ctx == NULL) {
397                 printf("failed to init mtd partition \"%s\" for writing\n",
398                        partition);
399                 return -1;
400             }
401 
402             size_t written = mtd_write_data(ctx, (char*)data, len);
403             if (written != len) {
404                 printf("only wrote %d of %d bytes to MTD %s\n",
405                        written, len, partition);
406                 mtd_write_close(ctx);
407                 return -1;
408             }
409 
410             if (mtd_erase_blocks(ctx, -1) < 0) {
411                 printf("error finishing mtd write of %s\n", partition);
412                 mtd_write_close(ctx);
413                 return -1;
414             }
415 
416             if (mtd_write_close(ctx)) {
417                 printf("error closing mtd write of %s\n", partition);
418                 return -1;
419             }
420             break;
421 
422         case EMMC:
423             ;
424             FILE* f = fopen(partition, "wb");
425             if (fwrite(data, 1, len, f) != len) {
426                 printf("short write writing to %s (%s)\n",
427                        partition, strerror(errno));
428                 return -1;
429             }
430             if (fclose(f) != 0) {
431                 printf("error closing %s (%s)\n", partition, strerror(errno));
432                 return -1;
433             }
434             break;
435     }
436 
437     free(copy);
438     return 0;
439 }
440 
441 
442 // Take a string 'str' of 40 hex digits and parse it into the 20
443 // byte array 'digest'.  'str' may contain only the digest or be of
444 // the form "<digest>:<anything>".  Return 0 on success, -1 on any
445 // error.
ParseSha1(const char * str,uint8_t * digest)446 int ParseSha1(const char* str, uint8_t* digest) {
447     int i;
448     const char* ps = str;
449     uint8_t* pd = digest;
450     for (i = 0; i < SHA_DIGEST_SIZE * 2; ++i, ++ps) {
451         int digit;
452         if (*ps >= '0' && *ps <= '9') {
453             digit = *ps - '0';
454         } else if (*ps >= 'a' && *ps <= 'f') {
455             digit = *ps - 'a' + 10;
456         } else if (*ps >= 'A' && *ps <= 'F') {
457             digit = *ps - 'A' + 10;
458         } else {
459             return -1;
460         }
461         if (i % 2 == 0) {
462             *pd = digit << 4;
463         } else {
464             *pd |= digit;
465             ++pd;
466         }
467     }
468     if (*ps != '\0') return -1;
469     return 0;
470 }
471 
472 // Search an array of sha1 strings for one matching the given sha1.
473 // Return the index of the match on success, or -1 if no match is
474 // found.
FindMatchingPatch(uint8_t * sha1,const char ** patch_sha1_str,int num_patches)475 int FindMatchingPatch(uint8_t* sha1, const char** patch_sha1_str,
476                       int num_patches) {
477     int i;
478     uint8_t patch_sha1[SHA_DIGEST_SIZE];
479     for (i = 0; i < num_patches; ++i) {
480         if (ParseSha1(patch_sha1_str[i], patch_sha1) == 0 &&
481             memcmp(patch_sha1, sha1, SHA_DIGEST_SIZE) == 0) {
482             return i;
483         }
484     }
485     return -1;
486 }
487 
488 // Returns 0 if the contents of the file (argv[2]) or the cached file
489 // match any of the sha1's on the command line (argv[3:]).  Returns
490 // nonzero otherwise.
applypatch_check(const char * filename,int num_patches,char ** const patch_sha1_str)491 int applypatch_check(const char* filename,
492                      int num_patches, char** const patch_sha1_str) {
493     FileContents file;
494     file.data = NULL;
495 
496     // It's okay to specify no sha1s; the check will pass if the
497     // LoadFileContents is successful.  (Useful for reading
498     // partitions, where the filename encodes the sha1s; no need to
499     // check them twice.)
500     if (LoadFileContents(filename, &file, RETOUCH_DO_MASK) != 0 ||
501         (num_patches > 0 &&
502          FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0)) {
503         printf("file \"%s\" doesn't have any of expected "
504                "sha1 sums; checking cache\n", filename);
505 
506         free(file.data);
507         file.data = NULL;
508 
509         // If the source file is missing or corrupted, it might be because
510         // we were killed in the middle of patching it.  A copy of it
511         // should have been made in CACHE_TEMP_SOURCE.  If that file
512         // exists and matches the sha1 we're looking for, the check still
513         // passes.
514 
515         if (LoadFileContents(CACHE_TEMP_SOURCE, &file, RETOUCH_DO_MASK) != 0) {
516             printf("failed to load cache file\n");
517             return 1;
518         }
519 
520         if (FindMatchingPatch(file.sha1, patch_sha1_str, num_patches) < 0) {
521             printf("cache bits don't match any sha1 for \"%s\"\n", filename);
522             free(file.data);
523             return 1;
524         }
525     }
526 
527     free(file.data);
528     return 0;
529 }
530 
ShowLicenses()531 int ShowLicenses() {
532     ShowBSDiffLicense();
533     return 0;
534 }
535 
FileSink(unsigned char * data,ssize_t len,void * token)536 ssize_t FileSink(unsigned char* data, ssize_t len, void* token) {
537     int fd = *(int *)token;
538     ssize_t done = 0;
539     ssize_t wrote;
540     while (done < (ssize_t) len) {
541         wrote = write(fd, data+done, len-done);
542         if (wrote <= 0) {
543             printf("error writing %d bytes: %s\n", (int)(len-done), strerror(errno));
544             return done;
545         }
546         done += wrote;
547     }
548     return done;
549 }
550 
551 typedef struct {
552     unsigned char* buffer;
553     ssize_t size;
554     ssize_t pos;
555 } MemorySinkInfo;
556 
MemorySink(unsigned char * data,ssize_t len,void * token)557 ssize_t MemorySink(unsigned char* data, ssize_t len, void* token) {
558     MemorySinkInfo* msi = (MemorySinkInfo*)token;
559     if (msi->size - msi->pos < len) {
560         return -1;
561     }
562     memcpy(msi->buffer + msi->pos, data, len);
563     msi->pos += len;
564     return len;
565 }
566 
567 // Return the amount of free space (in bytes) on the filesystem
568 // containing filename.  filename must exist.  Return -1 on error.
FreeSpaceForFile(const char * filename)569 size_t FreeSpaceForFile(const char* filename) {
570     struct statfs sf;
571     if (statfs(filename, &sf) != 0) {
572         printf("failed to statfs %s: %s\n", filename, strerror(errno));
573         return -1;
574     }
575     return sf.f_bsize * sf.f_bfree;
576 }
577 
CacheSizeCheck(size_t bytes)578 int CacheSizeCheck(size_t bytes) {
579     if (MakeFreeSpaceOnCache(bytes) < 0) {
580         printf("unable to make %ld bytes available on /cache\n", (long)bytes);
581         return 1;
582     } else {
583         return 0;
584     }
585 }
586 
587 
588 // This function applies binary patches to files in a way that is safe
589 // (the original file is not touched until we have the desired
590 // replacement for it) and idempotent (it's okay to run this program
591 // multiple times).
592 //
593 // - if the sha1 hash of <target_filename> is <target_sha1_string>,
594 //   does nothing and exits successfully.
595 //
596 // - otherwise, if the sha1 hash of <source_filename> is one of the
597 //   entries in <patch_sha1_str>, the corresponding patch from
598 //   <patch_data> (which must be a VAL_BLOB) is applied to produce a
599 //   new file (the type of patch is automatically detected from the
600 //   blob daat).  If that new file has sha1 hash <target_sha1_str>,
601 //   moves it to replace <target_filename>, and exits successfully.
602 //   Note that if <source_filename> and <target_filename> are not the
603 //   same, <source_filename> is NOT deleted on success.
604 //   <target_filename> may be the string "-" to mean "the same as
605 //   source_filename".
606 //
607 // - otherwise, or if any error is encountered, exits with non-zero
608 //   status.
609 //
610 // <source_filename> may refer to a partition to read the source data.
611 // See the comments for the LoadPartition Contents() function above
612 // for the format of such a filename.
613 
applypatch(const char * source_filename,const char * target_filename,const char * target_sha1_str,size_t target_size,int num_patches,char ** const patch_sha1_str,Value ** patch_data)614 int applypatch(const char* source_filename,
615                const char* target_filename,
616                const char* target_sha1_str,
617                size_t target_size,
618                int num_patches,
619                char** const patch_sha1_str,
620                Value** patch_data) {
621     printf("\napplying patch to %s\n", source_filename);
622 
623     if (target_filename[0] == '-' &&
624         target_filename[1] == '\0') {
625         target_filename = source_filename;
626     }
627 
628     uint8_t target_sha1[SHA_DIGEST_SIZE];
629     if (ParseSha1(target_sha1_str, target_sha1) != 0) {
630         printf("failed to parse tgt-sha1 \"%s\"\n", target_sha1_str);
631         return 1;
632     }
633 
634     FileContents copy_file;
635     FileContents source_file;
636     copy_file.data = NULL;
637     source_file.data = NULL;
638     const Value* source_patch_value = NULL;
639     const Value* copy_patch_value = NULL;
640 
641     // We try to load the target file into the source_file object.
642     if (LoadFileContents(target_filename, &source_file,
643                          RETOUCH_DO_MASK) == 0) {
644         if (memcmp(source_file.sha1, target_sha1, SHA_DIGEST_SIZE) == 0) {
645             // The early-exit case:  the patch was already applied, this file
646             // has the desired hash, nothing for us to do.
647             printf("\"%s\" is already target; no patch needed\n",
648                    target_filename);
649             free(source_file.data);
650             return 0;
651         }
652     }
653 
654     if (source_file.data == NULL ||
655         (target_filename != source_filename &&
656          strcmp(target_filename, source_filename) != 0)) {
657         // Need to load the source file:  either we failed to load the
658         // target file, or we did but it's different from the source file.
659         free(source_file.data);
660         source_file.data = NULL;
661         LoadFileContents(source_filename, &source_file,
662                          RETOUCH_DO_MASK);
663     }
664 
665     if (source_file.data != NULL) {
666         int to_use = FindMatchingPatch(source_file.sha1,
667                                        patch_sha1_str, num_patches);
668         if (to_use >= 0) {
669             source_patch_value = patch_data[to_use];
670         }
671     }
672 
673     if (source_patch_value == NULL) {
674         free(source_file.data);
675         source_file.data = NULL;
676         printf("source file is bad; trying copy\n");
677 
678         if (LoadFileContents(CACHE_TEMP_SOURCE, &copy_file,
679                              RETOUCH_DO_MASK) < 0) {
680             // fail.
681             printf("failed to read copy file\n");
682             return 1;
683         }
684 
685         int to_use = FindMatchingPatch(copy_file.sha1,
686                                        patch_sha1_str, num_patches);
687         if (to_use >= 0) {
688             copy_patch_value = patch_data[to_use];
689         }
690 
691         if (copy_patch_value == NULL) {
692             // fail.
693             printf("copy file doesn't match source SHA-1s either\n");
694             free(copy_file.data);
695             return 1;
696         }
697     }
698 
699     int result = GenerateTarget(&source_file, source_patch_value,
700                                 &copy_file, copy_patch_value,
701                                 source_filename, target_filename,
702                                 target_sha1, target_size);
703     free(source_file.data);
704     free(copy_file.data);
705 
706     return result;
707 }
708 
GenerateTarget(FileContents * source_file,const Value * source_patch_value,FileContents * copy_file,const Value * copy_patch_value,const char * source_filename,const char * target_filename,const uint8_t target_sha1[SHA_DIGEST_SIZE],size_t target_size)709 static int GenerateTarget(FileContents* source_file,
710                           const Value* source_patch_value,
711                           FileContents* copy_file,
712                           const Value* copy_patch_value,
713                           const char* source_filename,
714                           const char* target_filename,
715                           const uint8_t target_sha1[SHA_DIGEST_SIZE],
716                           size_t target_size) {
717     int retry = 1;
718     SHA_CTX ctx;
719     int output;
720     MemorySinkInfo msi;
721     FileContents* source_to_use;
722     char* outname;
723     int made_copy = 0;
724 
725     // assume that target_filename (eg "/system/app/Foo.apk") is located
726     // on the same filesystem as its top-level directory ("/system").
727     // We need something that exists for calling statfs().
728     char target_fs[strlen(target_filename)+1];
729     char* slash = strchr(target_filename+1, '/');
730     if (slash != NULL) {
731         int count = slash - target_filename;
732         strncpy(target_fs, target_filename, count);
733         target_fs[count] = '\0';
734     } else {
735         strcpy(target_fs, target_filename);
736     }
737 
738     do {
739         // Is there enough room in the target filesystem to hold the patched
740         // file?
741 
742         if (strncmp(target_filename, "MTD:", 4) == 0 ||
743             strncmp(target_filename, "EMMC:", 5) == 0) {
744             // If the target is a partition, we're actually going to
745             // write the output to /tmp and then copy it to the
746             // partition.  statfs() always returns 0 blocks free for
747             // /tmp, so instead we'll just assume that /tmp has enough
748             // space to hold the file.
749 
750             // We still write the original source to cache, in case
751             // the partition write is interrupted.
752             if (MakeFreeSpaceOnCache(source_file->size) < 0) {
753                 printf("not enough free space on /cache\n");
754                 return 1;
755             }
756             if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
757                 printf("failed to back up source file\n");
758                 return 1;
759             }
760             made_copy = 1;
761             retry = 0;
762         } else {
763             int enough_space = 0;
764             if (retry > 0) {
765                 size_t free_space = FreeSpaceForFile(target_fs);
766                 enough_space =
767                     (free_space > (256 << 10)) &&          // 256k (two-block) minimum
768                     (free_space > (target_size * 3 / 2));  // 50% margin of error
769                 printf("target %ld bytes; free space %ld bytes; retry %d; enough %d\n",
770                        (long)target_size, (long)free_space, retry, enough_space);
771             }
772 
773             if (!enough_space) {
774                 retry = 0;
775             }
776 
777             if (!enough_space && source_patch_value != NULL) {
778                 // Using the original source, but not enough free space.  First
779                 // copy the source file to cache, then delete it from the original
780                 // location.
781 
782                 if (strncmp(source_filename, "MTD:", 4) == 0 ||
783                     strncmp(source_filename, "EMMC:", 5) == 0) {
784                     // It's impossible to free space on the target filesystem by
785                     // deleting the source if the source is a partition.  If
786                     // we're ever in a state where we need to do this, fail.
787                     printf("not enough free space for target but source "
788                            "is partition\n");
789                     return 1;
790                 }
791 
792                 if (MakeFreeSpaceOnCache(source_file->size) < 0) {
793                     printf("not enough free space on /cache\n");
794                     return 1;
795                 }
796 
797                 if (SaveFileContents(CACHE_TEMP_SOURCE, source_file) < 0) {
798                     printf("failed to back up source file\n");
799                     return 1;
800                 }
801                 made_copy = 1;
802                 unlink(source_filename);
803 
804                 size_t free_space = FreeSpaceForFile(target_fs);
805                 printf("(now %ld bytes free for target)\n", (long)free_space);
806             }
807         }
808 
809         const Value* patch;
810         if (source_patch_value != NULL) {
811             source_to_use = source_file;
812             patch = source_patch_value;
813         } else {
814             source_to_use = copy_file;
815             patch = copy_patch_value;
816         }
817 
818         if (patch->type != VAL_BLOB) {
819             printf("patch is not a blob\n");
820             return 1;
821         }
822 
823         SinkFn sink = NULL;
824         void* token = NULL;
825         output = -1;
826         outname = NULL;
827         if (strncmp(target_filename, "MTD:", 4) == 0 ||
828             strncmp(target_filename, "EMMC:", 5) == 0) {
829             // We store the decoded output in memory.
830             msi.buffer = malloc(target_size);
831             if (msi.buffer == NULL) {
832                 printf("failed to alloc %ld bytes for output\n",
833                        (long)target_size);
834                 return 1;
835             }
836             msi.pos = 0;
837             msi.size = target_size;
838             sink = MemorySink;
839             token = &msi;
840         } else {
841             // We write the decoded output to "<tgt-file>.patch".
842             outname = (char*)malloc(strlen(target_filename) + 10);
843             strcpy(outname, target_filename);
844             strcat(outname, ".patch");
845 
846             output = open(outname, O_WRONLY | O_CREAT | O_TRUNC);
847             if (output < 0) {
848                 printf("failed to open output file %s: %s\n",
849                        outname, strerror(errno));
850                 return 1;
851             }
852             sink = FileSink;
853             token = &output;
854         }
855 
856         char* header = patch->data;
857         ssize_t header_bytes_read = patch->size;
858 
859         SHA_init(&ctx);
860 
861         int result;
862 
863         if (header_bytes_read >= 8 &&
864             memcmp(header, "BSDIFF40", 8) == 0) {
865             result = ApplyBSDiffPatch(source_to_use->data, source_to_use->size,
866                                       patch, 0, sink, token, &ctx);
867         } else if (header_bytes_read >= 8 &&
868                    memcmp(header, "IMGDIFF2", 8) == 0) {
869             result = ApplyImagePatch(source_to_use->data, source_to_use->size,
870                                      patch, sink, token, &ctx);
871         } else {
872             printf("Unknown patch file format\n");
873             return 1;
874         }
875 
876         if (output >= 0) {
877             fsync(output);
878             close(output);
879         }
880 
881         if (result != 0) {
882             if (retry == 0) {
883                 printf("applying patch failed\n");
884                 return result != 0;
885             } else {
886                 printf("applying patch failed; retrying\n");
887             }
888             if (outname != NULL) {
889                 unlink(outname);
890             }
891         } else {
892             // succeeded; no need to retry
893             break;
894         }
895     } while (retry-- > 0);
896 
897     const uint8_t* current_target_sha1 = SHA_final(&ctx);
898     if (memcmp(current_target_sha1, target_sha1, SHA_DIGEST_SIZE) != 0) {
899         printf("patch did not produce expected sha1\n");
900         return 1;
901     }
902 
903     if (output < 0) {
904         // Copy the temp file to the partition.
905         if (WriteToPartition(msi.buffer, msi.pos, target_filename) != 0) {
906             printf("write of patched data to %s failed\n", target_filename);
907             return 1;
908         }
909         free(msi.buffer);
910     } else {
911         // Give the .patch file the same owner, group, and mode of the
912         // original source file.
913         if (chmod(outname, source_to_use->st.st_mode) != 0) {
914             printf("chmod of \"%s\" failed: %s\n", outname, strerror(errno));
915             return 1;
916         }
917         if (chown(outname, source_to_use->st.st_uid,
918                   source_to_use->st.st_gid) != 0) {
919             printf("chown of \"%s\" failed: %s\n", outname, strerror(errno));
920             return 1;
921         }
922 
923         // Finally, rename the .patch file to replace the target file.
924         if (rename(outname, target_filename) != 0) {
925             printf("rename of .patch to \"%s\" failed: %s\n",
926                    target_filename, strerror(errno));
927             return 1;
928         }
929     }
930 
931     // If this run of applypatch created the copy, and we're here, we
932     // can delete it.
933     if (made_copy) unlink(CACHE_TEMP_SOURCE);
934 
935     // Success!
936     return 0;
937 }
938