blob: 60d76a5ea1494f3b09269f47fcb09a181e7c9094 [file] [log] [blame]
Ethan Yonker8373cfe2017-09-08 06:50:54 -05001/*
2 Copyright 2012 to 2016 bigbiff/Dees_Troy TeamWin
3 This file is part of TWRP/TeamWin Recovery Project.
4
5 TWRP is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 TWRP is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with TWRP. If not, see <http://www.gnu.org/licenses/>.
17*/
18
19#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <limits.h>
23#include <sys/stat.h>
24#include <sys/wait.h>
25#include <unistd.h>
26
27#include <string.h>
28#include <stdio.h>
29
30#include "twcommon.h"
31#include "mtdutils/mounts.h"
32#include "mtdutils/mtdutils.h"
33#include "minzip/SysUtil.h"
34#include "minzip/Zip.h"
35#ifdef USE_OLD_VERIFIER
36#include "verifier24/verifier.h"
37#else
38#include "verifier.h"
39#endif
40#include "variables.h"
41#include "data.hpp"
42#include "partitions.hpp"
43#include "twrpDigestDriver.hpp"
44#include "twrpDigest/twrpDigest.hpp"
45#include "twrpDigest/twrpMD5.hpp"
46#include "twrp-functions.hpp"
47#include "gui/gui.hpp"
48#include "gui/pages.hpp"
49#include "legacy_property_service.h"
50#include "twinstall.h"
51#include "installcommand.h"
52extern "C" {
53 #include "gui/gui.h"
54}
55
56#define AB_OTA "payload_properties.txt"
57
58static const char* properties_path = "/dev/__properties__";
59static const char* properties_path_renamed = "/dev/__properties_kk__";
60static bool legacy_props_env_initd = false;
61static bool legacy_props_path_modified = false;
62
63enum zip_type {
64 UNKNOWN_ZIP_TYPE = 0,
65 UPDATE_BINARY_ZIP_TYPE,
66 AB_OTA_ZIP_TYPE,
67 TWRP_THEME_ZIP_TYPE
68};
69
70// to support pre-KitKat update-binaries that expect properties in the legacy format
71static int switch_to_legacy_properties()
72{
73 if (!legacy_props_env_initd) {
74 if (legacy_properties_init() != 0)
75 return -1;
76
77 char tmp[32];
78 int propfd, propsz;
79 legacy_get_property_workspace(&propfd, &propsz);
80 sprintf(tmp, "%d,%d", dup(propfd), propsz);
81 setenv("ANDROID_PROPERTY_WORKSPACE", tmp, 1);
82 legacy_props_env_initd = true;
83 }
84
85 if (TWFunc::Path_Exists(properties_path)) {
86 // hide real properties so that the updater uses the envvar to find the legacy format properties
87 if (rename(properties_path, properties_path_renamed) != 0) {
88 LOGERR("Renaming %s failed: %s\n", properties_path, strerror(errno));
89 return -1;
90 } else {
91 legacy_props_path_modified = true;
92 }
93 }
94
95 return 0;
96}
97
98static int switch_to_new_properties()
99{
100 if (TWFunc::Path_Exists(properties_path_renamed)) {
101 if (rename(properties_path_renamed, properties_path) != 0) {
102 LOGERR("Renaming %s failed: %s\n", properties_path_renamed, strerror(errno));
103 return -1;
104 } else {
105 legacy_props_path_modified = false;
106 }
107 }
108
109 return 0;
110}
111
112static int Install_Theme(const char* path, ZipArchive *Zip) {
113#ifdef TW_OEM_BUILD // We don't do custom themes in OEM builds
114 mzCloseZipArchive(Zip);
115 return INSTALL_CORRUPT;
116#else
117 const ZipEntry* xml_location = mzFindZipEntry(Zip, "ui.xml");
118
119 mzCloseZipArchive(Zip);
120 if (xml_location == NULL) {
121 return INSTALL_CORRUPT;
122 }
123 if (!PartitionManager.Mount_Settings_Storage(true))
124 return INSTALL_ERROR;
125 string theme_path = DataManager::GetSettingsStoragePath();
126 theme_path += "/TWRP/theme";
127 if (!TWFunc::Path_Exists(theme_path)) {
128 if (!TWFunc::Recursive_Mkdir(theme_path)) {
129 return INSTALL_ERROR;
130 }
131 }
132 theme_path += "/ui.zip";
133 if (TWFunc::copy_file(path, theme_path, 0644) != 0) {
134 return INSTALL_ERROR;
135 }
136 LOGINFO("Installing custom theme '%s' to '%s'\n", path, theme_path.c_str());
137 PageManager::RequestReload();
138 return INSTALL_SUCCESS;
139#endif
140}
141
142static int Prepare_Update_Binary(const char *path, ZipArchive *Zip, int* wipe_cache) {
143 const ZipEntry* binary_location = mzFindZipEntry(Zip, ASSUMED_UPDATE_BINARY_NAME);
144 int binary_fd, ret_val;
145
146 if (binary_location == NULL) {
147 return INSTALL_CORRUPT;
148 }
149
150 // Delete any existing updater
151 if (TWFunc::Path_Exists(TMP_UPDATER_BINARY_PATH) && unlink(TMP_UPDATER_BINARY_PATH) != 0) {
152 LOGINFO("Unable to unlink '%s': %s\n", TMP_UPDATER_BINARY_PATH, strerror(errno));
153 }
154
155 binary_fd = creat(TMP_UPDATER_BINARY_PATH, 0755);
156 if (binary_fd < 0) {
157 LOGERR("Could not create file for updater extract in '%s': %s\n", TMP_UPDATER_BINARY_PATH, strerror(errno));
158 mzCloseZipArchive(Zip);
159 return INSTALL_ERROR;
160 }
161
162 ret_val = mzExtractZipEntryToFile(Zip, binary_location, binary_fd);
163 close(binary_fd);
164
165 if (!ret_val) {
166 mzCloseZipArchive(Zip);
167 LOGERR("Could not extract '%s'\n", ASSUMED_UPDATE_BINARY_NAME);
168 return INSTALL_ERROR;
169 }
170
171 // If exists, extract file_contexts from the zip file
172 const ZipEntry* selinx_contexts = mzFindZipEntry(Zip, "file_contexts");
173 if (selinx_contexts == NULL) {
174 mzCloseZipArchive(Zip);
175 LOGINFO("Zip does not contain SELinux file_contexts file in its root.\n");
176 } else {
177 string output_filename = "/file_contexts";
178 LOGINFO("Zip contains SELinux file_contexts file in its root. Extracting to %s\n", output_filename.c_str());
179 // Delete any file_contexts
180 if (TWFunc::Path_Exists(output_filename) && unlink(output_filename.c_str()) != 0) {
181 LOGINFO("Unable to unlink '%s': %s\n", output_filename.c_str(), strerror(errno));
182 }
183
184 int file_contexts_fd = creat(output_filename.c_str(), 0644);
185 if (file_contexts_fd < 0) {
186 LOGERR("Could not extract to '%s': %s\n", output_filename.c_str(), strerror(errno));
187 mzCloseZipArchive(Zip);
188 return INSTALL_ERROR;
189 }
190
191 ret_val = mzExtractZipEntryToFile(Zip, selinx_contexts, file_contexts_fd);
192 close(file_contexts_fd);
193
194 if (!ret_val) {
195 mzCloseZipArchive(Zip);
196 LOGERR("Could not extract '%s'\n", output_filename.c_str());
197 return INSTALL_ERROR;
198 }
199 }
200 mzCloseZipArchive(Zip);
201 return INSTALL_SUCCESS;
202}
203
204static int Run_Update_Binary(const char *path, ZipArchive *Zip, int* wipe_cache, zip_type ztype) {
205 int ret_val, pipe_fd[2], status, zip_verify;
206 char buffer[1024];
207 FILE* child_data;
208
209#ifndef TW_NO_LEGACY_PROPS
210 /* Set legacy properties */
211 if (switch_to_legacy_properties() != 0) {
212 LOGERR("Legacy property environment did not initialize successfully. Properties may not be detected.\n");
213 } else {
214 LOGINFO("Legacy property environment initialized.\n");
215 }
216#endif
217
218 pipe(pipe_fd);
219
220 std::vector<std::string> args;
221 if (ztype == UPDATE_BINARY_ZIP_TYPE) {
222 ret_val = update_binary_command(path, Zip, 0, pipe_fd[1], &args);
223 } else if (ztype == AB_OTA_ZIP_TYPE) {
224 ret_val = abupdate_binary_command(path, Zip, 0, pipe_fd[1], &args);
225 } else {
226 LOGERR("Unknown zip type %i\n", ztype);
227 ret_val = INSTALL_CORRUPT;
228 }
229 if (ret_val) {
230 close(pipe_fd[0]);
231 close(pipe_fd[1]);
232 return ret_val;
233 }
234
235 // Convert the vector to a NULL-terminated char* array suitable for execv.
236 const char* chr_args[args.size() + 1];
237 chr_args[args.size()] = NULL;
238 for (size_t i = 0; i < args.size(); i++)
239 chr_args[i] = args[i].c_str();
240
241 pid_t pid = fork();
242 if (pid == 0) {
243 close(pipe_fd[0]);
244 execve(chr_args[0], const_cast<char**>(chr_args), environ);
245 printf("E:Can't execute '%s': %s\n", chr_args[0], strerror(errno));
246 _exit(-1);
247 }
248 close(pipe_fd[1]);
249
250 *wipe_cache = 0;
251
252 DataManager::GetValue(TW_SIGNED_ZIP_VERIFY_VAR, zip_verify);
253 child_data = fdopen(pipe_fd[0], "r");
254 while (fgets(buffer, sizeof(buffer), child_data) != NULL) {
255 char* command = strtok(buffer, " \n");
256 if (command == NULL) {
257 continue;
258 } else if (strcmp(command, "progress") == 0) {
259 char* fraction_char = strtok(NULL, " \n");
260 char* seconds_char = strtok(NULL, " \n");
261
262 float fraction_float = strtof(fraction_char, NULL);
263 int seconds_float = strtol(seconds_char, NULL, 10);
264
265 if (zip_verify)
266 DataManager::ShowProgress(fraction_float * (1 - VERIFICATION_PROGRESS_FRACTION), seconds_float);
267 else
268 DataManager::ShowProgress(fraction_float, seconds_float);
269 } else if (strcmp(command, "set_progress") == 0) {
270 char* fraction_char = strtok(NULL, " \n");
271 float fraction_float = strtof(fraction_char, NULL);
272 DataManager::SetProgress(fraction_float);
273 } else if (strcmp(command, "ui_print") == 0) {
274 char* display_value = strtok(NULL, "\n");
275 if (display_value) {
276 gui_print("%s", display_value);
277 } else {
278 gui_print("\n");
279 }
280 } else if (strcmp(command, "wipe_cache") == 0) {
281 *wipe_cache = 1;
282 } else if (strcmp(command, "clear_display") == 0) {
283 // Do nothing, not supported by TWRP
284 } else if (strcmp(command, "log") == 0) {
285 printf("%s\n", strtok(NULL, "\n"));
286 } else {
287 LOGERR("unknown command [%s]\n", command);
288 }
289 }
290 fclose(child_data);
291
292 int waitrc = TWFunc::Wait_For_Child(pid, &status, "Updater");
293
294#ifndef TW_NO_LEGACY_PROPS
295 /* Unset legacy properties */
296 if (legacy_props_path_modified) {
297 if (switch_to_new_properties() != 0) {
298 LOGERR("Legacy property environment did not disable successfully. Legacy properties may still be in use.\n");
299 } else {
300 LOGINFO("Legacy property environment disabled.\n");
301 }
302 }
303#endif
304
305 if (waitrc != 0)
306 return INSTALL_ERROR;
307
308 return INSTALL_SUCCESS;
309}
310
311extern "C" int TWinstall_zip(const char* path, int* wipe_cache) {
312 int ret_val, zip_verify = 1;
313 ZipArchive Zip;
314
315 if (strcmp(path, "error") == 0) {
316 LOGERR("Failed to get adb sideload file: '%s'\n", path);
317 return INSTALL_CORRUPT;
318 }
319
320 gui_msg(Msg("installing_zip=Installing zip file '{1}'")(path));
321 if (strlen(path) < 9 || strncmp(path, "/sideload", 9) != 0) {
322 string digest_str;
323 string Full_Filename = path;
324 string digest_file = path;
325 digest_file += ".md5";
326
327 gui_msg("check_for_digest=Checking for Digest file...");
328 if (!TWFunc::Path_Exists(digest_file)) {
329 gui_msg("no_digest=Skipping Digest check: no Digest file found");
330 }
331 else {
332 if (TWFunc::read_file(digest_file, digest_str) != 0) {
333 LOGERR("Skipping MD5 check: MD5 file unreadable\n");
334 }
335 else {
336 twrpDigest *digest = new twrpMD5();
337 if (!twrpDigestDriver::stream_file_to_digest(Full_Filename, digest)) {
338 delete digest;
339 return INSTALL_CORRUPT;
340 }
341 string digest_check = digest->return_digest_string();
342 if (digest_str == digest_check) {
343 gui_msg(Msg("digest_matched=Digest matched for '{1}'.")(path));
344 }
345 else {
346 LOGERR("Aborting zip install: Digest verification failed\n");
347 delete digest;
348 return INSTALL_CORRUPT;
349 }
350 delete digest;
351 }
352 }
353 }
354
355#ifndef TW_OEM_BUILD
356 DataManager::GetValue(TW_SIGNED_ZIP_VERIFY_VAR, zip_verify);
357#endif
358 DataManager::SetProgress(0);
359
360 MemMapping map;
361 if (sysMapFile(path, &map) != 0) {
362 gui_msg(Msg(msg::kError, "fail_sysmap=Failed to map file '{1}'")(path));
363 return -1;
364 }
365
366 if (zip_verify) {
367 gui_msg("verify_zip_sig=Verifying zip signature...");
368 std::vector<Certificate> loadedKeys;
369 if (!load_keys("/res/keys", loadedKeys)) {
370 LOGINFO("Failed to load keys");
371 gui_err("verify_zip_fail=Zip signature verification failed!");
372 return -1;
373 }
374 ret_val = verify_file(map.addr, map.length, loadedKeys, NULL);
375 if (ret_val != VERIFY_SUCCESS) {
376 LOGINFO("Zip signature verification failed: %i\n", ret_val);
377 gui_err("verify_zip_fail=Zip signature verification failed!");
378 sysReleaseMap(&map);
379 return -1;
380 } else {
381 gui_msg("verify_zip_done=Zip signature verified successfully.");
382 }
383 }
384 ret_val = mzOpenZipArchive(map.addr, map.length, &Zip);
385 if (ret_val != 0) {
386 gui_err("zip_corrupt=Zip file is corrupt!");
387 sysReleaseMap(&map);
388 return INSTALL_CORRUPT;
389 }
390
391 time_t start, stop;
392 time(&start);
393 const ZipEntry* file_location = mzFindZipEntry(&Zip, ASSUMED_UPDATE_BINARY_NAME);
394 if (file_location != NULL) {
395 LOGINFO("Update binary zip\n");
396 ret_val = Prepare_Update_Binary(path, &Zip, wipe_cache);
397 if (ret_val == INSTALL_SUCCESS)
398 ret_val = Run_Update_Binary(path, &Zip, wipe_cache, UPDATE_BINARY_ZIP_TYPE);
399 } else {
400 file_location = mzFindZipEntry(&Zip, AB_OTA);
401 if (file_location != NULL) {
402 LOGINFO("AB zip\n");
403 ret_val = Run_Update_Binary(path, &Zip, wipe_cache, AB_OTA_ZIP_TYPE);
404 } else {
405 file_location = mzFindZipEntry(&Zip, "ui.xml");
406 if (file_location != NULL) {
407 LOGINFO("TWRP theme zip\n");
408 ret_val = Install_Theme(path, &Zip);
409 } else {
410 mzCloseZipArchive(&Zip);
411 ret_val = INSTALL_CORRUPT;
412 }
413 }
414 }
415 time(&stop);
416 int total_time = (int) difftime(stop, start);
417 if (ret_val == INSTALL_CORRUPT) {
418 gui_err("invalid_zip_format=Invalid zip file format!");
419 } else {
420 LOGINFO("Install took %i second(s).\n", total_time);
421 }
422 sysReleaseMap(&map);
423 return ret_val;
424}