Home | History | Annotate | Download | only in recovery
      1 /*
      2  * Copyright (C) 2007 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 <ctype.h>
     18 #include <errno.h>
     19 #include <fcntl.h>
     20 #include <limits.h>
     21 #include <sys/stat.h>
     22 #include <sys/wait.h>
     23 #include <unistd.h>
     24 
     25 #include "common.h"
     26 #include "install.h"
     27 #include "mincrypt/rsa.h"
     28 #include "minui/minui.h"
     29 #include "minzip/SysUtil.h"
     30 #include "minzip/Zip.h"
     31 #include "mtdutils/mounts.h"
     32 #include "mtdutils/mtdutils.h"
     33 #include "roots.h"
     34 #include "verifier.h"
     35 
     36 #define ASSUMED_UPDATE_BINARY_NAME  "META-INF/com/google/android/update-binary"
     37 #define PUBLIC_KEYS_FILE "/res/keys"
     38 
     39 static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
     40 
     41 // If the package contains an update binary, extract it and run it.
     42 static int
     43 try_update_binary(const char *path, ZipArchive *zip) {
     44     const ZipEntry* binary_entry =
     45             mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
     46     if (binary_entry == NULL) {
     47         mzCloseZipArchive(zip);
     48         return INSTALL_CORRUPT;
     49     }
     50 
     51     char* binary = "/tmp/update_binary";
     52     unlink(binary);
     53     int fd = creat(binary, 0755);
     54     if (fd < 0) {
     55         mzCloseZipArchive(zip);
     56         LOGE("Can't make %s\n", binary);
     57         return 1;
     58     }
     59     bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
     60     close(fd);
     61     mzCloseZipArchive(zip);
     62 
     63     if (!ok) {
     64         LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
     65         return 1;
     66     }
     67 
     68     int pipefd[2];
     69     pipe(pipefd);
     70 
     71     // When executing the update binary contained in the package, the
     72     // arguments passed are:
     73     //
     74     //   - the version number for this interface
     75     //
     76     //   - an fd to which the program can write in order to update the
     77     //     progress bar.  The program can write single-line commands:
     78     //
     79     //        progress <frac> <secs>
     80     //            fill up the next <frac> part of of the progress bar
     81     //            over <secs> seconds.  If <secs> is zero, use
     82     //            set_progress commands to manually control the
     83     //            progress of this segment of the bar
     84     //
     85     //        set_progress <frac>
     86     //            <frac> should be between 0.0 and 1.0; sets the
     87     //            progress bar within the segment defined by the most
     88     //            recent progress command.
     89     //
     90     //        firmware <"hboot"|"radio"> <filename>
     91     //            arrange to install the contents of <filename> in the
     92     //            given partition on reboot.
     93     //
     94     //            (API v2: <filename> may start with "PACKAGE:" to
     95     //            indicate taking a file from the OTA package.)
     96     //
     97     //            (API v3: this command no longer exists.)
     98     //
     99     //        ui_print <string>
    100     //            display <string> on the screen.
    101     //
    102     //   - the name of the package zip file.
    103     //
    104 
    105     char** args = malloc(sizeof(char*) * 5);
    106     args[0] = binary;
    107     args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk
    108     args[2] = malloc(10);
    109     sprintf(args[2], "%d", pipefd[1]);
    110     args[3] = (char*)path;
    111     args[4] = NULL;
    112 
    113     pid_t pid = fork();
    114     if (pid == 0) {
    115         close(pipefd[0]);
    116         execv(binary, args);
    117         fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
    118         _exit(-1);
    119     }
    120     close(pipefd[1]);
    121 
    122     char buffer[1024];
    123     FILE* from_child = fdopen(pipefd[0], "r");
    124     while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
    125         char* command = strtok(buffer, " \n");
    126         if (command == NULL) {
    127             continue;
    128         } else if (strcmp(command, "progress") == 0) {
    129             char* fraction_s = strtok(NULL, " \n");
    130             char* seconds_s = strtok(NULL, " \n");
    131 
    132             float fraction = strtof(fraction_s, NULL);
    133             int seconds = strtol(seconds_s, NULL, 10);
    134 
    135             ui_show_progress(fraction * (1-VERIFICATION_PROGRESS_FRACTION),
    136                              seconds);
    137         } else if (strcmp(command, "set_progress") == 0) {
    138             char* fraction_s = strtok(NULL, " \n");
    139             float fraction = strtof(fraction_s, NULL);
    140             ui_set_progress(fraction);
    141         } else if (strcmp(command, "ui_print") == 0) {
    142             char* str = strtok(NULL, "\n");
    143             if (str) {
    144                 ui_print("%s", str);
    145             } else {
    146                 ui_print("\n");
    147             }
    148         } else {
    149             LOGE("unknown command [%s]\n", command);
    150         }
    151     }
    152     fclose(from_child);
    153 
    154     int status;
    155     waitpid(pid, &status, 0);
    156     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
    157         LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
    158         return INSTALL_ERROR;
    159     }
    160 
    161     return INSTALL_SUCCESS;
    162 }
    163 
    164 // Reads a file containing one or more public keys as produced by
    165 // DumpPublicKey:  this is an RSAPublicKey struct as it would appear
    166 // as a C source literal, eg:
    167 //
    168 //  "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
    169 //
    170 // (Note that the braces and commas in this example are actual
    171 // characters the parser expects to find in the file; the ellipses
    172 // indicate more numbers omitted from this example.)
    173 //
    174 // The file may contain multiple keys in this format, separated by
    175 // commas.  The last key must not be followed by a comma.
    176 //
    177 // Returns NULL if the file failed to parse, or if it contain zero keys.
    178 static RSAPublicKey*
    179 load_keys(const char* filename, int* numKeys) {
    180     RSAPublicKey* out = NULL;
    181     *numKeys = 0;
    182 
    183     FILE* f = fopen(filename, "r");
    184     if (f == NULL) {
    185         LOGE("opening %s: %s\n", filename, strerror(errno));
    186         goto exit;
    187     }
    188 
    189     int i;
    190     bool done = false;
    191     while (!done) {
    192         ++*numKeys;
    193         out = realloc(out, *numKeys * sizeof(RSAPublicKey));
    194         RSAPublicKey* key = out + (*numKeys - 1);
    195         if (fscanf(f, " { %i , 0x%x , { %u",
    196                    &(key->len), &(key->n0inv), &(key->n[0])) != 3) {
    197             goto exit;
    198         }
    199         if (key->len != RSANUMWORDS) {
    200             LOGE("key length (%d) does not match expected size\n", key->len);
    201             goto exit;
    202         }
    203         for (i = 1; i < key->len; ++i) {
    204             if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit;
    205         }
    206         if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit;
    207         for (i = 1; i < key->len; ++i) {
    208             if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit;
    209         }
    210         fscanf(f, " } } ");
    211 
    212         // if the line ends in a comma, this file has more keys.
    213         switch (fgetc(f)) {
    214             case ',':
    215                 // more keys to come.
    216                 break;
    217 
    218             case EOF:
    219                 done = true;
    220                 break;
    221 
    222             default:
    223                 LOGE("unexpected character between keys\n");
    224                 goto exit;
    225         }
    226     }
    227 
    228     fclose(f);
    229     return out;
    230 
    231 exit:
    232     if (f) fclose(f);
    233     free(out);
    234     *numKeys = 0;
    235     return NULL;
    236 }
    237 
    238 static int
    239 really_install_package(const char *path)
    240 {
    241     ui_set_background(BACKGROUND_ICON_INSTALLING);
    242     ui_print("Finding update package...\n");
    243     ui_show_indeterminate_progress();
    244     LOGI("Update location: %s\n", path);
    245 
    246     if (ensure_path_mounted(path) != 0) {
    247         LOGE("Can't mount %s\n", path);
    248         return INSTALL_CORRUPT;
    249     }
    250 
    251     ui_print("Opening update package...\n");
    252 
    253     int numKeys;
    254     RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    255     if (loadedKeys == NULL) {
    256         LOGE("Failed to load keys\n");
    257         return INSTALL_CORRUPT;
    258     }
    259     LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);
    260 
    261     // Give verification half the progress bar...
    262     ui_print("Verifying update package...\n");
    263     ui_show_progress(
    264             VERIFICATION_PROGRESS_FRACTION,
    265             VERIFICATION_PROGRESS_TIME);
    266 
    267     int err;
    268     err = verify_file(path, loadedKeys, numKeys);
    269     free(loadedKeys);
    270     LOGI("verify_file returned %d\n", err);
    271     if (err != VERIFY_SUCCESS) {
    272         LOGE("signature verification failed\n");
    273         return INSTALL_CORRUPT;
    274     }
    275 
    276     /* Try to open the package.
    277      */
    278     ZipArchive zip;
    279     err = mzOpenZipArchive(path, &zip);
    280     if (err != 0) {
    281         LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
    282         return INSTALL_CORRUPT;
    283     }
    284 
    285     /* Verify and install the contents of the package.
    286      */
    287     ui_print("Installing update...\n");
    288     return try_update_binary(path, &zip);
    289 }
    290 
    291 int
    292 install_package(const char* path)
    293 {
    294     FILE* install_log = fopen_path(LAST_INSTALL_FILE, "w");
    295     if (install_log) {
    296         fputs(path, install_log);
    297         fputc('\n', install_log);
    298     } else {
    299         LOGE("failed to open last_install: %s\n", strerror(errno));
    300     }
    301     int result = really_install_package(path);
    302     if (install_log) {
    303         fputc(result == INSTALL_SUCCESS ? '1' : '0', install_log);
    304         fputc('\n', install_log);
    305         fclose(install_log);
    306         chmod(LAST_INSTALL_FILE, 0644);
    307     }
    308     return result;
    309 }
    310