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