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 <string.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 
26 #include <chrono>
27 #include <string>
28 #include <vector>
29 
30 #include <android-base/parseint.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
33 
34 #include "common.h"
35 #include "error_code.h"
36 #include "install.h"
37 #include "minui/minui.h"
38 #include "minzip/SysUtil.h"
39 #include "minzip/Zip.h"
40 #include "mtdutils/mounts.h"
41 #include "mtdutils/mtdutils.h"
42 #include "roots.h"
43 #include "ui.h"
44 #include "verifier.h"
45 
46 extern RecoveryUI* ui;
47 
48 #define ASSUMED_UPDATE_BINARY_NAME  "META-INF/com/google/android/update-binary"
49 #define PUBLIC_KEYS_FILE "/res/keys"
50 static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
51 
52 // Default allocation of progress bar segments to operations
53 static const int VERIFICATION_PROGRESS_TIME = 60;
54 static const float VERIFICATION_PROGRESS_FRACTION = 0.25;
55 static const float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
56 static const float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;
57 
58 // This function parses and returns the build.version.incremental
parse_build_number(std::string str)59 static int parse_build_number(std::string str) {
60     size_t pos = str.find("=");
61     if (pos != std::string::npos) {
62         std::string num_string = android::base::Trim(str.substr(pos+1));
63         int build_number;
64         if (android::base::ParseInt(num_string.c_str(), &build_number, 0)) {
65             return build_number;
66         }
67     }
68 
69     LOGE("Failed to parse build number in %s.\n", str.c_str());
70     return -1;
71 }
72 
73 // Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
read_source_target_build(ZipArchive * zip,std::vector<std::string> & log_buffer)74 static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
75     const ZipEntry* meta_entry = mzFindZipEntry(zip, METADATA_PATH);
76     if (meta_entry == nullptr) {
77         LOGE("Failed to find %s in update package.\n", METADATA_PATH);
78         return;
79     }
80 
81     std::string meta_data(meta_entry->uncompLen, '\0');
82     if (!mzReadZipEntry(zip, meta_entry, &meta_data[0], meta_entry->uncompLen)) {
83         LOGE("Failed to read metadata in update package.\n");
84         return;
85     }
86 
87     // Examples of the pre-build and post-build strings in metadata:
88     // pre-build-incremental=2943039
89     // post-build-incremental=2951741
90     std::vector<std::string> lines = android::base::Split(meta_data, "\n");
91     for (const std::string& line : lines) {
92         std::string str = android::base::Trim(line);
93         if (android::base::StartsWith(str, "pre-build-incremental")){
94             int source_build = parse_build_number(str);
95             if (source_build != -1) {
96                 log_buffer.push_back(android::base::StringPrintf("source_build: %d",
97                         source_build));
98             }
99         } else if (android::base::StartsWith(str, "post-build-incremental")) {
100             int target_build = parse_build_number(str);
101             if (target_build != -1) {
102                 log_buffer.push_back(android::base::StringPrintf("target_build: %d",
103                         target_build));
104             }
105         }
106     }
107 }
108 
109 // If the package contains an update binary, extract it and run it.
110 static int
try_update_binary(const char * path,ZipArchive * zip,bool * wipe_cache,std::vector<std::string> & log_buffer,int retry_count)111 try_update_binary(const char* path, ZipArchive* zip, bool* wipe_cache,
112                   std::vector<std::string>& log_buffer, int retry_count)
113 {
114     read_source_target_build(zip, log_buffer);
115 
116     const ZipEntry* binary_entry =
117             mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
118     if (binary_entry == NULL) {
119         mzCloseZipArchive(zip);
120         return INSTALL_CORRUPT;
121     }
122 
123     const char* binary = "/tmp/update_binary";
124     unlink(binary);
125     int fd = creat(binary, 0755);
126     if (fd < 0) {
127         mzCloseZipArchive(zip);
128         LOGE("Can't make %s\n", binary);
129         return INSTALL_ERROR;
130     }
131     bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
132     close(fd);
133     mzCloseZipArchive(zip);
134 
135     if (!ok) {
136         LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
137         return INSTALL_ERROR;
138     }
139 
140     int pipefd[2];
141     pipe(pipefd);
142 
143     // When executing the update binary contained in the package, the
144     // arguments passed are:
145     //
146     //   - the version number for this interface
147     //
148     //   - an fd to which the program can write in order to update the
149     //     progress bar.  The program can write single-line commands:
150     //
151     //        progress <frac> <secs>
152     //            fill up the next <frac> part of of the progress bar
153     //            over <secs> seconds.  If <secs> is zero, use
154     //            set_progress commands to manually control the
155     //            progress of this segment of the bar.
156     //
157     //        set_progress <frac>
158     //            <frac> should be between 0.0 and 1.0; sets the
159     //            progress bar within the segment defined by the most
160     //            recent progress command.
161     //
162     //        firmware <"hboot"|"radio"> <filename>
163     //            arrange to install the contents of <filename> in the
164     //            given partition on reboot.
165     //
166     //            (API v2: <filename> may start with "PACKAGE:" to
167     //            indicate taking a file from the OTA package.)
168     //
169     //            (API v3: this command no longer exists.)
170     //
171     //        ui_print <string>
172     //            display <string> on the screen.
173     //
174     //        wipe_cache
175     //            a wipe of cache will be performed following a successful
176     //            installation.
177     //
178     //        clear_display
179     //            turn off the text display.
180     //
181     //        enable_reboot
182     //            packages can explicitly request that they want the user
183     //            to be able to reboot during installation (useful for
184     //            debugging packages that don't exit).
185     //
186     //   - the name of the package zip file.
187     //
188     //   - an optional argument "retry" if this update is a retry of a failed
189     //   update attempt.
190     //
191 
192     const char** args = (const char**)malloc(sizeof(char*) * 6);
193     args[0] = binary;
194     args[1] = EXPAND(RECOVERY_API_VERSION);   // defined in Android.mk
195     char* temp = (char*)malloc(10);
196     sprintf(temp, "%d", pipefd[1]);
197     args[2] = temp;
198     args[3] = (char*)path;
199     args[4] = retry_count > 0 ? "retry" : NULL;
200     args[5] = NULL;
201 
202     pid_t pid = fork();
203     if (pid == 0) {
204         umask(022);
205         close(pipefd[0]);
206         execv(binary, (char* const*)args);
207         fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
208         _exit(-1);
209     }
210     close(pipefd[1]);
211 
212     *wipe_cache = false;
213     bool retry_update = false;
214 
215     char buffer[1024];
216     FILE* from_child = fdopen(pipefd[0], "r");
217     while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
218         char* command = strtok(buffer, " \n");
219         if (command == NULL) {
220             continue;
221         } else if (strcmp(command, "progress") == 0) {
222             char* fraction_s = strtok(NULL, " \n");
223             char* seconds_s = strtok(NULL, " \n");
224 
225             float fraction = strtof(fraction_s, NULL);
226             int seconds = strtol(seconds_s, NULL, 10);
227 
228             ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
229         } else if (strcmp(command, "set_progress") == 0) {
230             char* fraction_s = strtok(NULL, " \n");
231             float fraction = strtof(fraction_s, NULL);
232             ui->SetProgress(fraction);
233         } else if (strcmp(command, "ui_print") == 0) {
234             char* str = strtok(NULL, "\n");
235             if (str) {
236                 ui->PrintOnScreenOnly("%s", str);
237             } else {
238                 ui->PrintOnScreenOnly("\n");
239             }
240             fflush(stdout);
241         } else if (strcmp(command, "wipe_cache") == 0) {
242             *wipe_cache = true;
243         } else if (strcmp(command, "clear_display") == 0) {
244             ui->SetBackground(RecoveryUI::NONE);
245         } else if (strcmp(command, "enable_reboot") == 0) {
246             // packages can explicitly request that they want the user
247             // to be able to reboot during installation (useful for
248             // debugging packages that don't exit).
249             ui->SetEnableReboot(true);
250         } else if (strcmp(command, "retry_update") == 0) {
251             retry_update = true;
252         } else if (strcmp(command, "log") == 0) {
253             // Save the logging request from updater and write to
254             // last_install later.
255             log_buffer.push_back(std::string(strtok(NULL, "\n")));
256         } else {
257             LOGE("unknown command [%s]\n", command);
258         }
259     }
260     fclose(from_child);
261 
262     int status;
263     waitpid(pid, &status, 0);
264     if (retry_update) {
265         return INSTALL_RETRY;
266     }
267     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
268         LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
269         return INSTALL_ERROR;
270     }
271 
272     return INSTALL_SUCCESS;
273 }
274 
275 static int
really_install_package(const char * path,bool * wipe_cache,bool needs_mount,std::vector<std::string> & log_buffer,int retry_count)276 really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
277                        std::vector<std::string>& log_buffer, int retry_count)
278 {
279     ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
280     ui->Print("Finding update package...\n");
281     // Give verification half the progress bar...
282     ui->SetProgressType(RecoveryUI::DETERMINATE);
283     ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
284     LOGI("Update location: %s\n", path);
285 
286     // Map the update package into memory.
287     ui->Print("Opening update package...\n");
288 
289     if (path && needs_mount) {
290         if (path[0] == '@') {
291             ensure_path_mounted(path+1);
292         } else {
293             ensure_path_mounted(path);
294         }
295     }
296 
297     MemMapping map;
298     if (sysMapFile(path, &map) != 0) {
299         LOGE("failed to map file\n");
300         return INSTALL_CORRUPT;
301     }
302 
303     // Load keys.
304     std::vector<Certificate> loadedKeys;
305     if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
306         LOGE("Failed to load keys\n");
307         return INSTALL_CORRUPT;
308     }
309     LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
310 
311     // Verify package.
312     ui->Print("Verifying update package...\n");
313     auto t0 = std::chrono::system_clock::now();
314     int err = verify_file(map.addr, map.length, loadedKeys);
315     std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
316     ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
317     if (err != VERIFY_SUCCESS) {
318         LOGE("signature verification failed\n");
319         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
320 
321         sysReleaseMap(&map);
322         return INSTALL_CORRUPT;
323     }
324 
325     // Try to open the package.
326     ZipArchive zip;
327     err = mzOpenZipArchive(map.addr, map.length, &zip);
328     if (err != 0) {
329         LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
330         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
331 
332         sysReleaseMap(&map);
333         return INSTALL_CORRUPT;
334     }
335 
336     // Verify and install the contents of the package.
337     ui->Print("Installing update...\n");
338     if (retry_count > 0) {
339         ui->Print("Retry attempt: %d\n", retry_count);
340     }
341     ui->SetEnableReboot(false);
342     int result = try_update_binary(path, &zip, wipe_cache, log_buffer, retry_count);
343     ui->SetEnableReboot(true);
344     ui->Print("\n");
345 
346     sysReleaseMap(&map);
347 
348     return result;
349 }
350 
351 int
install_package(const char * path,bool * wipe_cache,const char * install_file,bool needs_mount,int retry_count)352 install_package(const char* path, bool* wipe_cache, const char* install_file,
353                 bool needs_mount, int retry_count)
354 {
355     modified_flash = true;
356     auto start = std::chrono::system_clock::now();
357 
358     FILE* install_log = fopen_path(install_file, "w");
359     if (install_log) {
360         fputs(path, install_log);
361         fputc('\n', install_log);
362     } else {
363         LOGE("failed to open last_install: %s\n", strerror(errno));
364     }
365     int result;
366     std::vector<std::string> log_buffer;
367     if (setup_install_mounts() != 0) {
368         LOGE("failed to set up expected mounts for install; aborting\n");
369         result = INSTALL_ERROR;
370     } else {
371         result = really_install_package(path, wipe_cache, needs_mount, log_buffer, retry_count);
372     }
373     if (install_log != nullptr) {
374         fputc(result == INSTALL_SUCCESS ? '1' : '0', install_log);
375         fputc('\n', install_log);
376         std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
377         int count = static_cast<int>(duration.count());
378         // Report the time spent to apply OTA update in seconds.
379         fprintf(install_log, "time_total: %d\n", count);
380         fprintf(install_log, "retry: %d\n", retry_count);
381 
382         for (const auto& s : log_buffer) {
383             fprintf(install_log, "%s\n", s.c_str());
384         }
385 
386         fclose(install_log);
387     }
388     return result;
389 }
390