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