blob: 4bc69424e2918da49378154982766e41ee8b4994 [file] [log] [blame]
Dees_Troy32c8eb82012-09-11 15:28:06 -04001/*
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 <string.h>
26#include <stdio.h>
27
28#include "common.h"
Dees_Troyb9d88ac2012-09-14 14:34:19 -040029#include "mincrypt/rsa.h"
30#include "mincrypt/sha.h"
Dees_Troy32c8eb82012-09-11 15:28:06 -040031#include "minui/minui.h"
32#include "minzip/SysUtil.h"
33#include "minzip/Zip.h"
34#include "mtdutils/mounts.h"
35#include "mtdutils/mtdutils.h"
36#include "roots.h"
37#include "verifier.h"
38#include "ui.h"
39#include "variables.h"
40#include "data.hpp"
41#include "partitions.hpp"
Dees_Troy38bd7602012-09-14 13:33:53 -040042#include "twrp-functions.hpp"
Dees_Troy32c8eb82012-09-11 15:28:06 -040043
44extern "C" {
45#include "extra-functions.h"
46int __system(const char *command);
47};
48
49extern RecoveryUI* ui;
50
51#define ASSUMED_UPDATE_BINARY_NAME "META-INF/com/google/android/update-binary"
52#define PUBLIC_KEYS_FILE "/res/keys"
53
54// Default allocation of progress bar segments to operations
55static const int VERIFICATION_PROGRESS_TIME = 60;
56static const float VERIFICATION_PROGRESS_FRACTION = 0.25;
57static const float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
58static const float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;
59
60enum { INSTALL_SUCCESS, INSTALL_ERROR, INSTALL_CORRUPT };
61
Dees_Troy32c8eb82012-09-11 15:28:06 -040062// If the package contains an update binary, extract it and run it.
63static int
64try_update_binary(const char *path, ZipArchive *zip, int* wipe_cache) {
65 const ZipEntry* binary_entry =
66 mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
67 if (binary_entry == NULL) {
68 mzCloseZipArchive(zip);
69 return INSTALL_CORRUPT;
70 }
71
72 const char* binary = "/tmp/update_binary";
73 unlink(binary);
74 int fd = creat(binary, 0755);
75 if (fd < 0) {
76 mzCloseZipArchive(zip);
77 LOGE("Can't make %s\n", binary);
78 return INSTALL_ERROR;
79 }
80 bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
81 close(fd);
82 mzCloseZipArchive(zip);
83
84 if (!ok) {
85 LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
86 return INSTALL_ERROR;
87 }
88
89 int pipefd[2];
90 pipe(pipefd);
91
92 // When executing the update binary contained in the package, the
93 // arguments passed are:
94 //
95 // - the version number for this interface
96 //
97 // - an fd to which the program can write in order to update the
98 // progress bar. The program can write single-line commands:
99 //
100 // progress <frac> <secs>
101 // fill up the next <frac> part of of the progress bar
102 // over <secs> seconds. If <secs> is zero, use
103 // set_progress commands to manually control the
104 // progress of this segment of the bar
105 //
106 // set_progress <frac>
107 // <frac> should be between 0.0 and 1.0; sets the
108 // progress bar within the segment defined by the most
109 // recent progress command.
110 //
111 // firmware <"hboot"|"radio"> <filename>
112 // arrange to install the contents of <filename> in the
113 // given partition on reboot.
114 //
115 // (API v2: <filename> may start with "PACKAGE:" to
116 // indicate taking a file from the OTA package.)
117 //
118 // (API v3: this command no longer exists.)
119 //
120 // ui_print <string>
121 // display <string> on the screen.
122 //
123 // - the name of the package zip file.
124 //
125
126 const char** args = (const char**)malloc(sizeof(char*) * 5);
127 args[0] = binary;
128 args[1] = EXPAND(RECOVERY_API_VERSION); // defined in Android.mk
129 char* temp = (char*)malloc(10);
130 sprintf(temp, "%d", pipefd[1]);
131 args[2] = temp;
132 args[3] = (char*)path;
133 args[4] = NULL;
134
135 pid_t pid = fork();
136 if (pid == 0) {
137 close(pipefd[0]);
138 execv(binary, (char* const*)args);
139 fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
140 _exit(-1);
141 }
142 close(pipefd[1]);
143
144 *wipe_cache = 0;
145
146 char buffer[1024];
147 FILE* from_child = fdopen(pipefd[0], "r");
148 while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
149 char* command = strtok(buffer, " \n");
150 if (command == NULL) {
151 continue;
152 } else if (strcmp(command, "progress") == 0) {
153 char* fraction_s = strtok(NULL, " \n");
154 char* seconds_s = strtok(NULL, " \n");
155
156 float fraction = strtof(fraction_s, NULL);
157 int seconds = strtol(seconds_s, NULL, 10);
158
159 ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
160 } else if (strcmp(command, "set_progress") == 0) {
161 char* fraction_s = strtok(NULL, " \n");
162 float fraction = strtof(fraction_s, NULL);
163 ui->SetProgress(fraction);
164 } else if (strcmp(command, "ui_print") == 0) {
165 char* str = strtok(NULL, "\n");
166 if (str) {
167 ui->Print("%s", str);
168 } else {
169 ui->Print("\n");
170 }
171 } else if (strcmp(command, "wipe_cache") == 0) {
172 *wipe_cache = 1;
173 } else if (strcmp(command, "clear_display") == 0) {
174 //ui->SetBackground(RecoveryUI::NONE);
175 } else {
176 LOGE("unknown command [%s]\n", command);
177 }
178 }
179 fclose(from_child);
180
181 int status;
182 waitpid(pid, &status, 0);
183 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
184 LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
185 return INSTALL_ERROR;
186 }
187
188 return INSTALL_SUCCESS;
189}
190
191// Reads a file containing one or more public keys as produced by
192// DumpPublicKey: this is an RSAPublicKey struct as it would appear
193// as a C source literal, eg:
194//
195// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
196//
197// (Note that the braces and commas in this example are actual
198// characters the parser expects to find in the file; the ellipses
199// indicate more numbers omitted from this example.)
200//
201// The file may contain multiple keys in this format, separated by
202// commas. The last key must not be followed by a comma.
203//
204// Returns NULL if the file failed to parse, or if it contain zero keys.
205static RSAPublicKey*
206load_keys(const char* filename, int* numKeys) {
207 RSAPublicKey* out = NULL;
208 *numKeys = 0;
209
210 FILE* f = fopen(filename, "r");
211 if (f == NULL) {
212 LOGE("opening %s: %s\n", filename, strerror(errno));
213 goto exit;
214 }
215
216 {
217 int i;
218 bool done = false;
219 while (!done) {
220 ++*numKeys;
221 out = (RSAPublicKey*)realloc(out, *numKeys * sizeof(RSAPublicKey));
222 RSAPublicKey* key = out + (*numKeys - 1);
223 if (fscanf(f, " { %i , 0x%x , { %u",
224 &(key->len), &(key->n0inv), &(key->n[0])) != 3) {
225 goto exit;
226 }
227 if (key->len != RSANUMWORDS) {
228 LOGE("key length (%d) does not match expected size\n", key->len);
229 goto exit;
230 }
231 for (i = 1; i < key->len; ++i) {
232 if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit;
233 }
234 if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit;
235 for (i = 1; i < key->len; ++i) {
236 if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit;
237 }
238 fscanf(f, " } } ");
239
240 // if the line ends in a comma, this file has more keys.
241 switch (fgetc(f)) {
242 case ',':
243 // more keys to come.
244 break;
245
246 case EOF:
247 done = true;
248 break;
249
250 default:
251 LOGE("unexpected character between keys\n");
252 goto exit;
253 }
254 }
255 }
256
257 fclose(f);
258 return out;
259
260exit:
261 if (f) fclose(f);
262 free(out);
263 *numKeys = 0;
264 return NULL;
265}
266
Dees_Troy32c8eb82012-09-11 15:28:06 -0400267extern "C" int TWinstall_zip(const char* path, int* wipe_cache) {
268 int err, zip_verify, md5_return, md5_verify;
269
270 ui_print("Installing '%s'...\n", path);
271
272 if (!PartitionManager.Mount_By_Path(path, 0)) {
273 LOGE("Failed to mount '%s'\n", path);
274 return -1;
275 }
276
277 ui_print("Checking for MD5 file...\n");
Dees_Troy38bd7602012-09-14 13:33:53 -0400278 md5_return = TWFunc::Check_MD5(path);
Dees_Troy32c8eb82012-09-11 15:28:06 -0400279 if (md5_return == 0) {
280 // MD5 did not match.
281 LOGE("Zip MD5 does not match.\nUnable to install zip.\n");
282 return INSTALL_CORRUPT;
283 } else if (md5_return == -1) {
284 DataManager::GetValue(TW_FORCE_MD5_CHECK_VAR, md5_verify);
285 if (md5_verify == 1) {
286 // Forced MD5 checking is on and no MD5 file found.
287 LOGE("No MD5 file found for '%s'.\nDisable force MD5 check to avoid this error.\n", path);
288 return INSTALL_CORRUPT;
289 } else
Dees_Troyc51f1f92012-09-20 15:32:13 -0400290 ui_print("Skipping MD5 check: no MD5 file found.\n");
Dees_Troy32c8eb82012-09-11 15:28:06 -0400291 } else if (md5_return == 1)
292 ui_print("Zip MD5 matched.\n"); // MD5 found and matched.
293
294 DataManager::GetValue(TW_SIGNED_ZIP_VERIFY_VAR, zip_verify);
295 if (zip_verify) {
296 ui_print("Verifying zip signature...\n");
297 int numKeys;
298 RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
299 if (loadedKeys == NULL) {
300 LOGE("Failed to load keys\n");
301 return -1;
302 }
303 LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);
304
305 // Give verification half the progress bar...
306 ui->Print("Verifying update package...\n");
307 ui->SetProgressType(RecoveryUI::DETERMINATE);
308 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
309
Dees_Troyb9d88ac2012-09-14 14:34:19 -0400310 err = verify_file(path, loadedKeys, numKeys);
Dees_Troy32c8eb82012-09-11 15:28:06 -0400311 free(loadedKeys);
312 LOGI("verify_file returned %d\n", err);
313 if (err != VERIFY_SUCCESS) {
314 LOGE("signature verification failed\n");
315 return -1;
316 }
317 }
318 /* Try to open the package.
319 */
320 ZipArchive zip;
321 err = mzOpenZipArchive(path, &zip);
322 if (err != 0) {
323 LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
324 return INSTALL_CORRUPT;
325 }
326
327 /* Verify and install the contents of the package.
328 */
329 return try_update_binary(path, &zip, wipe_cache);
330}