merge from eclair

This commit is contained in:
Jean-Baptiste Queru 2009-11-15 12:05:33 -08:00
commit b2ce982d43
18 changed files with 582 additions and 458 deletions

View File

@ -1,11 +1,11 @@
ifneq ($(TARGET_SIMULATOR),true)
ifeq ($(TARGET_ARCH),arm)
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
commands_recovery_local_path := $(LOCAL_PATH)
ifneq ($(TARGET_SIMULATOR),true)
ifeq ($(TARGET_ARCH),arm)
LOCAL_SRC_FILES := \
recovery.c \
bootloader.c \
@ -31,7 +31,13 @@ LOCAL_CFLAGS += -DRECOVERY_API_VERSION=$(RECOVERY_API_VERSION)
LOCAL_MODULE_TAGS := eng
LOCAL_STATIC_LIBRARIES := libminzip libunz libmtdutils libmincrypt
LOCAL_STATIC_LIBRARIES :=
ifeq ($(TARGET_RECOVERY_UI_LIB),)
LOCAL_SRC_FILES += default_recovery_ui.c
else
LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UI_LIB)
endif
LOCAL_STATIC_LIBRARIES += libminzip libunz libmtdutils libmincrypt
LOCAL_STATIC_LIBRARIES += libminui libpixelflinger_static libpng libcutils
LOCAL_STATIC_LIBRARIES += libstdc++ libc

View File

@ -68,7 +68,7 @@ void ui_set_progress(float fraction); // 0.0 - 1.0 within the defined scope
// Default allocation of progress bar segments to operations
static const int VERIFICATION_PROGRESS_TIME = 60;
static const float VERIFICATION_PROGRESS_FRACTION = 0.5;
static const float VERIFICATION_PROGRESS_FRACTION = 0.25;
static const float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
static const float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;

65
default_recovery_ui.c Normal file
View File

@ -0,0 +1,65 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <linux/input.h>
#include "recovery_ui.h"
#include "common.h"
char* MENU_HEADERS[] = { "Android system recovery utility",
"",
NULL };
char* MENU_ITEMS[] = { "reboot system now",
"apply sdcard:update.zip",
"wipe data/factory reset",
"wipe cache partition",
NULL };
int device_toggle_display(volatile char* key_pressed, int key_code) {
return key_code == KEY_HOME;
}
int device_reboot_now(volatile char* key_pressed, int key_code) {
return 0;
}
int device_handle_key(int key_code, int visible) {
if (visible) {
switch (key_code) {
case KEY_DOWN:
case KEY_VOLUMEDOWN:
return HIGHLIGHT_DOWN;
case KEY_UP:
case KEY_VOLUMEUP:
return HIGHLIGHT_UP;
case KEY_ENTER:
return SELECT_ITEM;
}
}
return NO_ACTION;
}
int device_perform_action(int which) {
return which;
}
int device_wipe_data() {
return 0;
}

View File

@ -234,20 +234,8 @@ try_update_binary(const char *path, ZipArchive *zip) {
}
static int
handle_update_package(const char *path, ZipArchive *zip,
const RSAPublicKey *keys, int numKeys)
handle_update_package(const char *path, ZipArchive *zip)
{
// Give verification half the progress bar...
ui_print("Verifying update package...\n");
ui_show_progress(
VERIFICATION_PROGRESS_FRACTION,
VERIFICATION_PROGRESS_TIME);
if (!verify_jar_signature(zip, keys, numKeys)) {
LOGE("Verification failed\n");
return INSTALL_CORRUPT;
}
// Update should take the rest of the progress bar.
ui_print("Installing update...\n");
@ -360,10 +348,25 @@ install_package(const char *root_path)
}
LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);
// Give verification half the progress bar...
ui_print("Verifying update package...\n");
ui_show_progress(
VERIFICATION_PROGRESS_FRACTION,
VERIFICATION_PROGRESS_TIME);
int err;
err = verify_file(path, loadedKeys, numKeys);
free(loadedKeys);
LOGI("verify_file returned %d\n", err);
if (err != VERIFY_SUCCESS) {
LOGE("signature verification failed\n");
return INSTALL_CORRUPT;
}
/* Try to open the package.
*/
ZipArchive zip;
int err = mzOpenZipArchive(path, &zip);
err = mzOpenZipArchive(path, &zip);
if (err != 0) {
LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
return INSTALL_CORRUPT;
@ -371,8 +374,7 @@ install_package(const char *root_path)
/* Verify and install the contents of the package.
*/
int status = handle_update_package(path, &zip, loadedKeys, numKeys);
int status = handle_update_package(path, &zip);
mzCloseZipArchive(&zip);
free(loadedKeys);
return status;
}

View File

@ -115,6 +115,7 @@ static void set_active_framebuffer(unsigned n)
if (n > 1) return;
vi.yres_virtual = vi.yres * 2;
vi.yoffset = n * vi.yres;
vi.bits_per_pixel = 16;
if (ioctl(gr_fb_fd, FBIOPUT_VSCREENINFO, &vi) < 0) {
perror("active fb swap failed");
}

View File

@ -41,22 +41,6 @@ unsigned int gr_get_height(gr_surface surface);
// see http://www.mjmwired.net/kernel/Documentation/input/ for info.
struct input_event;
// Dream-specific key codes
#define KEY_DREAM_HOME 102 // = KEY_HOME
#define KEY_DREAM_RED 107 // = KEY_END
#define KEY_DREAM_VOLUMEDOWN 114 // = KEY_VOLUMEDOWN
#define KEY_DREAM_VOLUMEUP 115 // = KEY_VOLUMEUP
#define KEY_DREAM_SYM 127 // = KEY_COMPOSE
#define KEY_DREAM_MENU 139 // = KEY_MENU
#define KEY_DREAM_BACK 158 // = KEY_BACK
#define KEY_DREAM_FOCUS 211 // = KEY_HP (light touch on camera)
#define KEY_DREAM_CAMERA 212 // = KEY_CAMERA
#define KEY_DREAM_AT 215 // = KEY_EMAIL
#define KEY_DREAM_GREEN 231
#define KEY_DREAM_FATTOUCH 258 // = BTN_2 ???
#define KEY_DREAM_BALL 272 // = BTN_MOUSE
#define KEY_DREAM_TOUCH 330 // = BTN_TOUCH
int ev_init(void);
void ev_exit(void);
int ev_get(struct input_event *ev, unsigned dont_wait);

View File

@ -36,12 +36,14 @@
#include "minui/minui.h"
#include "minzip/DirUtil.h"
#include "roots.h"
#include "recovery_ui.h"
static const struct option OPTIONS[] = {
{ "send_intent", required_argument, NULL, 's' },
{ "update_package", required_argument, NULL, 'u' },
{ "wipe_data", no_argument, NULL, 'w' },
{ "wipe_cache", no_argument, NULL, 'c' },
{ NULL, 0, NULL, 0 },
};
static const char *COMMAND_FILE = "CACHE:recovery/command";
@ -206,6 +208,15 @@ get_args(int *argc, char ***argv) {
set_bootloader_message(&boot);
}
static void
set_sdcard_update_bootloader_message()
{
struct bootloader_message boot;
memset(&boot, 0, sizeof(boot));
strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
set_bootloader_message(&boot);
}
// clear the recovery command and prepare to boot a (hopefully working) system,
// copy our log file to cache as well (for the system to read), and
@ -269,116 +280,159 @@ erase_root(const char *root)
return format_root_device(root);
}
static void
prompt_and_wait()
{
char* headers[] = { "Android system recovery <"
static char**
prepend_title(char** headers) {
char* title[] = { "Android system recovery <"
EXPAND(RECOVERY_API_VERSION) "e>",
"",
"Use trackball to highlight;",
"click to select.",
"",
NULL };
// these constants correspond to elements of the items[] list.
#define ITEM_REBOOT 0
#define ITEM_APPLY_SDCARD 1
#define ITEM_WIPE_DATA 2
#define ITEM_WIPE_CACHE 3
char* items[] = { "reboot system now [Home+Back]",
"apply sdcard:update.zip [Alt+S]",
"wipe data/factory reset [Alt+W]",
"wipe cache partition",
"",
NULL };
// count the number of lines in our title, plus the
// caller-provided headers.
int count = 0;
char** p;
for (p = title; *p; ++p, ++count);
for (p = headers; *p; ++p, ++count);
char** new_headers = malloc((count+1) * sizeof(char*));
char** h = new_headers;
for (p = title; *p; ++p, ++h) *h = *p;
for (p = headers; *p; ++p, ++h) *h = *p;
*h = NULL;
return new_headers;
}
static int
get_menu_selection(char** headers, char** items, int menu_only) {
// throw away keys pressed previously, so user doesn't
// accidentally trigger menu items.
ui_clear_key_queue();
ui_start_menu(headers, items);
int selected = 0;
int chosen_item = -1;
finish_recovery(NULL);
ui_reset_progress();
for (;;) {
while (chosen_item < 0) {
int key = ui_wait_key();
int alt = ui_key_pressed(KEY_LEFTALT) || ui_key_pressed(KEY_RIGHTALT);
int visible = ui_text_visible();
if (key == KEY_DREAM_BACK && ui_key_pressed(KEY_DREAM_HOME)) {
// Wait for the keys to be released, to avoid triggering
// special boot modes (like coming back into recovery!).
while (ui_key_pressed(KEY_DREAM_BACK) ||
ui_key_pressed(KEY_DREAM_HOME)) {
usleep(1000);
int action = device_handle_key(key, visible);
if (action < 0) {
switch (action) {
case HIGHLIGHT_UP:
--selected;
selected = ui_menu_select(selected);
break;
case HIGHLIGHT_DOWN:
++selected;
selected = ui_menu_select(selected);
break;
case SELECT_ITEM:
chosen_item = selected;
break;
case NO_ACTION:
break;
}
chosen_item = ITEM_REBOOT;
} else if (alt && key == KEY_W) {
chosen_item = ITEM_WIPE_DATA;
} else if (alt && key == KEY_S) {
chosen_item = ITEM_APPLY_SDCARD;
} else if ((key == KEY_DOWN || key == KEY_VOLUMEDOWN) && visible) {
++selected;
selected = ui_menu_select(selected);
} else if ((key == KEY_UP || key == KEY_VOLUMEUP) && visible) {
--selected;
selected = ui_menu_select(selected);
} else if (key == BTN_MOUSE && visible) {
chosen_item = selected;
} else if (!menu_only) {
chosen_item = action;
}
}
ui_end_menu();
return chosen_item;
}
static void
wipe_data(int confirm) {
if (confirm) {
static char** title_headers = NULL;
if (title_headers == NULL) {
char* headers[] = { "Confirm wipe of all user data?",
" THIS CAN NOT BE UNDONE.",
"",
NULL };
title_headers = prepend_title(headers);
}
if (chosen_item >= 0) {
// turn off the menu, letting ui_print() to scroll output
// on the screen.
ui_end_menu();
char* items[] = { " No",
" No",
" No",
" No",
" No",
" No",
" No",
" Yes -- delete all user data", // [7]
" No",
" No",
" No",
NULL };
switch (chosen_item) {
case ITEM_REBOOT:
return;
int chosen_item = get_menu_selection(title_headers, items, 1);
if (chosen_item != 7) {
return;
}
}
case ITEM_WIPE_DATA:
ui_print("\n-- Wiping data...\n");
erase_root("DATA:");
erase_root("CACHE:");
ui_print("Data wipe complete.\n");
if (!ui_text_visible()) return;
break;
ui_print("\n-- Wiping data...\n");
device_wipe_data();
erase_root("DATA:");
erase_root("CACHE:");
ui_print("Data wipe complete.\n");
}
case ITEM_WIPE_CACHE:
ui_print("\n-- Wiping cache...\n");
erase_root("CACHE:");
ui_print("Cache wipe complete.\n");
if (!ui_text_visible()) return;
break;
static void
prompt_and_wait()
{
char** headers = prepend_title(MENU_HEADERS);
case ITEM_APPLY_SDCARD:
ui_print("\n-- Install from sdcard...\n");
int status = install_package(SDCARD_PACKAGE_FILE);
if (status != INSTALL_SUCCESS) {
ui_set_background(BACKGROUND_ICON_ERROR);
ui_print("Installation aborted.\n");
} else if (!ui_text_visible()) {
return; // reboot if logs aren't visible
for (;;) {
finish_recovery(NULL);
ui_reset_progress();
int chosen_item = get_menu_selection(headers, MENU_ITEMS, 0);
// device-specific code may take some action here. It may
// return one of the core actions handled in the switch
// statement below.
chosen_item = device_perform_action(chosen_item);
switch (chosen_item) {
case ITEM_REBOOT:
return;
case ITEM_WIPE_DATA:
wipe_data(ui_text_visible());
if (!ui_text_visible()) return;
break;
case ITEM_WIPE_CACHE:
ui_print("\n-- Wiping cache...\n");
erase_root("CACHE:");
ui_print("Cache wipe complete.\n");
if (!ui_text_visible()) return;
break;
case ITEM_APPLY_SDCARD:
ui_print("\n-- Install from sdcard...\n");
set_sdcard_update_bootloader_message();
int status = install_package(SDCARD_PACKAGE_FILE);
if (status != INSTALL_SUCCESS) {
ui_set_background(BACKGROUND_ICON_ERROR);
ui_print("Installation aborted.\n");
} else if (!ui_text_visible()) {
return; // reboot if logs aren't visible
} else {
if (firmware_update_pending()) {
ui_print("\nReboot via menu to complete\n"
"installation.\n");
} else {
if (firmware_update_pending()) {
ui_print("\nReboot via home+back or menu\n"
"to complete installation.\n");
} else {
ui_print("\nInstall from sdcard complete.\n");
}
}
break;
}
// if we didn't return from this function to reboot, show
// the menu again.
ui_start_menu(headers, items);
selected = 0;
chosen_item = -1;
finish_recovery(NULL);
ui_reset_progress();
// throw away keys pressed while the command was running,
// so user doesn't accidentally trigger menu items.
ui_clear_key_queue();
}
break;
}
}
}
@ -435,10 +489,14 @@ main(int argc, char **argv)
if (update_package != NULL) {
status = install_package(update_package);
if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
} else if (wipe_data || wipe_cache) {
if (wipe_data && erase_root("DATA:")) status = INSTALL_ERROR;
} else if (wipe_data) {
if (device_wipe_data()) status = INSTALL_ERROR;
if (erase_root("DATA:")) status = INSTALL_ERROR;
if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
} else if (wipe_cache) {
if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
} else {
status = INSTALL_ERROR; // No command specified
}

76
recovery_ui.h Normal file
View File

@ -0,0 +1,76 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _RECOVERY_UI_H
#define _RECOVERY_UI_H
// Called in the input thread when a new key (key_code) is pressed.
// *key_pressed is an array of KEY_MAX+1 bytes indicating which other
// keys are already pressed. Return true if the text display should
// be toggled.
extern int device_toggle_display(volatile char* key_pressed, int key_code);
// Called in the input thread when a new key (key_code) is pressed.
// *key_pressed is an array of KEY_MAX+1 bytes indicating which other
// keys are already pressed. Return true if the device should reboot
// immediately.
extern int device_reboot_now(volatile char* key_pressed, int key_code);
// Called from the main thread when recovery is waiting for input and
// a key is pressed. key is the code of the key pressed; visible is
// true if the recovery menu is being shown. Implementations can call
// ui_key_pressed() to discover if other keys are being held down.
// Return one of the defined constants below in order to:
//
// - move the menu highlight (HIGHLIGHT_*)
// - invoke the highlighted item (SELECT_ITEM)
// - do nothing (NO_ACTION)
// - invoke a specific action (a menu position: any non-negative number)
extern int device_handle_key(int key, int visible);
// Perform a recovery action selected from the menu. 'which' will be
// the item number of the selected menu item, or a non-negative number
// returned from device_handle_key(). The menu will be hidden when
// this is called; implementations can call ui_print() to print
// information to the screen.
extern int device_perform_action(int which);
// Called when we do a wipe data/factory reset operation (either via a
// reboot from the main system with the --wipe_data flag, or when the
// user boots into recovery manually and selects the option from the
// menu.) Can perform whatever device-specific wiping actions are
// needed. Return 0 on success. The userdata and cache partitions
// are erased after this returns (whether it returns success or not).
int device_wipe_data();
#define NO_ACTION -1
#define HIGHLIGHT_UP -2
#define HIGHLIGHT_DOWN -3
#define SELECT_ITEM -4
#define ITEM_REBOOT 0
#define ITEM_APPLY_SDCARD 1
#define ITEM_WIPE_DATA 2
#define ITEM_WIPE_CACHE 3
// Header text to display above the main menu.
extern char* MENU_HEADERS[];
// Text of menu items.
extern char* MENU_ITEMS[];
#endif

BIN
res/images/icon_error.png Normal file → Executable file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 10 KiB

BIN
res/images/icon_firmware_install.png Normal file → Executable file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

BIN
res/images/icon_installing.png Normal file → Executable file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -52,6 +52,7 @@ static RootInfo g_roots[] = {
{ "RECOVERY:", g_mtd_device, NULL, "recovery", "/", g_raw },
{ "SDCARD:", "/dev/block/mmcblk0p1", "/dev/block/mmcblk0", NULL, "/sdcard", "vfat" },
{ "SYSTEM:", g_mtd_device, NULL, "system", "/system", "yaffs2" },
{ "MBM:", g_mtd_device, NULL, "mbm", NULL, g_raw },
{ "TMP:", NULL, NULL, NULL, "/tmp", NULL },
};
#define NUM_ROOTS (sizeof(g_roots) / sizeof(g_roots[0]))

17
ui.c
View File

@ -27,6 +27,7 @@
#include "common.h"
#include "minui/minui.h"
#include "recovery_ui.h"
#define MAX_COLS 64
#define MAX_ROWS 32
@ -307,20 +308,14 @@ static void *input_thread(void *cookie)
}
pthread_mutex_unlock(&key_queue_mutex);
// Alt+L or Home+End: toggle log display
int alt = key_pressed[KEY_LEFTALT] || key_pressed[KEY_RIGHTALT];
if ((alt && ev.code == KEY_L && ev.value > 0) ||
(key_pressed[KEY_HOME] && ev.code == KEY_END && ev.value > 0)) {
if (ev.value > 0 && device_toggle_display(key_pressed, ev.code)) {
pthread_mutex_lock(&gUpdateMutex);
show_text = !show_text;
update_screen_locked();
pthread_mutex_unlock(&gUpdateMutex);
}
// Green+Menu+Red: reboot immediately
if (ev.code == KEY_DREAM_RED &&
key_pressed[KEY_DREAM_MENU] &&
key_pressed[KEY_DREAM_GREEN]) {
if (ev.value > 0 && device_reboot_now(key_pressed, ev.code)) {
reboot(RB_AUTOBOOT);
}
}
@ -344,7 +339,11 @@ void ui_init(void)
for (i = 0; BITMAPS[i].name != NULL; ++i) {
int result = res_create_surface(BITMAPS[i].name, BITMAPS[i].surface);
if (result < 0) {
LOGE("Missing bitmap %s\n(Code %d)\n", BITMAPS[i].name, result);
if (result == -2) {
LOGI("Bitmap %s missing header\n", BITMAPS[i].name);
} else {
LOGE("Missing bitmap %s\n(Code %d)\n", BITMAPS[i].name, result);
}
*BITMAPS[i].surface = NULL;
}
}

View File

@ -18,11 +18,47 @@ LOCAL_MODULE_TAGS := eng
LOCAL_SRC_FILES := $(updater_src_files)
LOCAL_STATIC_LIBRARIES := libapplypatch libedify libmtdutils libminzip libz
LOCAL_STATIC_LIBRARIES := $(TARGET_RECOVERY_UPDATER_LIBS) $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS)
LOCAL_STATIC_LIBRARIES += libapplypatch libedify libmtdutils libminzip libz
LOCAL_STATIC_LIBRARIES += libmincrypt libbz
LOCAL_STATIC_LIBRARIES += libcutils libstdc++ libc
LOCAL_C_INCLUDES += $(LOCAL_PATH)/..
# Each library in TARGET_RECOVERY_UPDATER_LIBS should have a function
# named "Register_<libname>()". Here we emit a little C function that
# gets #included by updater.c. It calls all those registration
# functions.
# Devices can also add libraries to TARGET_RECOVERY_UPDATER_EXTRA_LIBS.
# These libs are also linked in with updater, but we don't try to call
# any sort of registration function for these. Use this variable for
# any subsidiary static libraries required for your registered
# extension libs.
inc := $(call intermediates-dir-for,PACKAGING,updater_extensions)/register.inc
# During the first pass of reading the makefiles, we dump the list of
# extension libs to a temp file, then copy that to the ".list" file if
# it is different than the existing .list (if any). The register.inc
# file then uses the .list as a prerequisite, so it is only rebuilt
# (and updater.o recompiled) when the list of extension libs changes.
junk := $(shell mkdir -p $(dir $(inc));\
echo $(TARGET_RECOVERY_UPDATER_LIBS) > $(inc).temp;\
diff -q $(inc).temp $(inc).list || cp -f $(inc).temp $(inc).list)
$(inc) : libs := $(TARGET_RECOVERY_UPDATER_LIBS)
$(inc) : $(inc).list
$(hide) mkdir -p $(dir $@)
$(hide) echo "" > $@
$(hide) $(foreach lib,$(libs),echo "extern void Register_$(lib)(void);" >> $@)
$(hide) echo "void RegisterDeviceExtensions() {" >> $@
$(hide) $(foreach lib,$(libs),echo " Register_$(lib)();" >> $@)
$(hide) echo "}" >> $@
$(call intermediates-dir-for,EXECUTABLES,updater)/updater.o : $(inc)
LOCAL_C_INCLUDES += $(dir $(inc))
LOCAL_MODULE := updater
LOCAL_FORCE_STATIC_EXECUTABLE := true

View File

@ -23,6 +23,7 @@
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "cutils/misc.h"
@ -85,6 +86,8 @@ char* MountFn(const char* name, State* state, int argc, Expr* argv[]) {
} else {
if (mount(location, mount_point, type,
MS_NOATIME | MS_NODEV | MS_NODIRATIME, "") < 0) {
fprintf(stderr, "%s: failed to mount %s at %s: %s\n",
name, location, mount_point, strerror(errno));
result = strdup("");
} else {
result = mount_point;
@ -347,6 +350,7 @@ char* PackageExtractFileFn(const char* name, State* state,
// symlink target src1 src2 ...
// unlinks any previously existing src1, src2, etc before creating symlinks.
char* SymlinkFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc == 0) {
return ErrorAbort(state, "%s() expects 1+ args, got %d", name, argc);
@ -363,7 +367,16 @@ char* SymlinkFn(const char* name, State* state, int argc, Expr* argv[]) {
int i;
for (i = 0; i < argc-1; ++i) {
symlink(target, srcs[i]);
if (unlink(srcs[i]) < 0) {
if (errno != ENOENT) {
fprintf(stderr, "%s: failed to remove %s: %s\n",
name, srcs[i], strerror(errno));
}
}
if (symlink(target, srcs[i]) < 0) {
fprintf(stderr, "%s: failed to symlink %s to %s: %s\n",
name, srcs[i], target, strerror(errno));
}
free(srcs[i]);
}
free(srcs);
@ -423,8 +436,14 @@ char* SetPermFn(const char* name, State* state, int argc, Expr* argv[]) {
}
for (i = 3; i < argc; ++i) {
chown(args[i], uid, gid);
chmod(args[i], mode);
if (chown(args[i], uid, gid) < 0) {
fprintf(stderr, "%s: chown of %s to %d %d failed: %s\n",
name, args[i], uid, gid, strerror(errno));
}
if (chmod(args[i], mode) < 0) {
fprintf(stderr, "%s: chmod of %s to %o failed: %s\n",
name, args[i], mode, strerror(errno));
}
}
}
result = strdup("");
@ -759,6 +778,52 @@ char* UIPrintFn(const char* name, State* state, int argc, Expr* argv[]) {
return buffer;
}
char* RunProgramFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc < 1) {
return ErrorAbort(state, "%s() expects at least 1 arg", name);
}
char** args = ReadVarArgs(state, argc, argv);
if (args == NULL) {
return NULL;
}
char** args2 = malloc(sizeof(char*) * (argc+1));
memcpy(args2, args, sizeof(char*) * argc);
args2[argc] = NULL;
fprintf(stderr, "about to run program [%s] with %d args\n", args2[0], argc);
pid_t child = fork();
if (child == 0) {
execv(args2[0], args2);
fprintf(stderr, "run_program: execv failed: %s\n", strerror(errno));
_exit(1);
}
int status;
waitpid(child, &status, 0);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0) {
fprintf(stderr, "run_program: child exited with status %d\n",
WEXITSTATUS(status));
}
} else if (WIFSIGNALED(status)) {
fprintf(stderr, "run_program: child terminated by signal %d\n",
WTERMSIG(status));
}
int i;
for (i = 0; i < argc; ++i) {
free(args[i]);
}
free(args);
free(args2);
char buffer[20];
sprintf(buffer, "%d", status);
return strdup(buffer);
}
void RegisterInstallFunctions() {
RegisterFunction("mount", MountFn);
@ -785,4 +850,6 @@ void RegisterInstallFunctions() {
RegisterFunction("apply_patch_space", ApplyPatchFn);
RegisterFunction("ui_print", UIPrintFn);
RegisterFunction("run_program", RunProgramFn);
}

View File

@ -23,6 +23,11 @@
#include "install.h"
#include "minzip/Zip.h"
// Generated by the makefile, this function defines the
// RegisterDeviceExtensions() function, which calls all the
// registration functions for device-specific extensions.
#include "register.inc"
// Where in the package we expect to find the edify script to execute.
// (Note it's "updateR-script", not the older "update-script".)
#define SCRIPT_NAME "META-INF/com/google/android/updater-script"
@ -76,6 +81,7 @@ int main(int argc, char** argv) {
RegisterBuiltins();
RegisterInstallFunctions();
RegisterDeviceExtensions();
FinishRegistration();
// Parse the script.

View File

@ -17,345 +17,168 @@
#include "common.h"
#include "verifier.h"
#include "minzip/Zip.h"
#include "mincrypt/rsa.h"
#include "mincrypt/sha.h"
#include <netinet/in.h> /* required for resolv.h */
#include <resolv.h> /* for base64 codec */
#include <string.h>
#include <stdio.h>
#include <errno.h>
/* Return an allocated buffer with the contents of a zip file entry. */
static char *slurpEntry(const ZipArchive *pArchive, const ZipEntry *pEntry) {
if (!mzIsZipEntryIntact(pArchive, pEntry)) {
UnterminatedString fn = mzGetZipEntryFileName(pEntry);
LOGE("Invalid %.*s\n", fn.len, fn.str);
return NULL;
// Look for an RSA signature embedded in the .ZIP file comment given
// the path to the zip. Verify it matches one of the given public
// keys.
//
// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
// or no key matches the signature).
int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys) {
ui_set_progress(0.0);
FILE* f = fopen(path, "rb");
if (f == NULL) {
LOGE("failed to open %s (%s)\n", path, strerror(errno));
return VERIFY_FAILURE;
}
int len = mzGetZipEntryUncompLen(pEntry);
char *buf = malloc(len + 1);
if (buf == NULL) {
UnterminatedString fn = mzGetZipEntryFileName(pEntry);
LOGE("Can't allocate %d bytes for %.*s\n", len, fn.len, fn.str);
return NULL;
// An archive with a whole-file signature will end in six bytes:
//
// $ff $ff (2-byte comment size) (2-byte signature start)
//
// (As far as the ZIP format is concerned, these are part of the
// archive comment.) We start by reading this footer, this tells
// us how far back from the end we have to start reading to find
// the whole comment.
#define FOOTER_SIZE 6
if (fseek(f, -FOOTER_SIZE, SEEK_END) != 0) {
LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
fclose(f);
return VERIFY_FAILURE;
}
if (!mzReadZipEntry(pArchive, pEntry, buf, len)) {
UnterminatedString fn = mzGetZipEntryFileName(pEntry);
LOGE("Can't read %.*s\n", fn.len, fn.str);
free(buf);
return NULL;
unsigned char footer[FOOTER_SIZE];
if (fread(footer, 1, FOOTER_SIZE, f) != FOOTER_SIZE) {
LOGE("failed to read footer from %s (%s)\n", path, strerror(errno));
fclose(f);
return VERIFY_FAILURE;
}
buf[len] = '\0';
return buf;
}
struct DigestContext {
SHA_CTX digest;
unsigned *doneBytes;
unsigned totalBytes;
};
/* mzProcessZipEntryContents callback to update an SHA-1 hash context. */
static bool updateHash(const unsigned char *data, int dataLen, void *cookie) {
struct DigestContext *context = (struct DigestContext *) cookie;
SHA_update(&context->digest, data, dataLen);
if (context->doneBytes != NULL) {
*context->doneBytes += dataLen;
if (context->totalBytes > 0) {
ui_set_progress(*context->doneBytes * 1.0 / context->totalBytes);
}
}
return true;
}
/* Get the SHA-1 digest of a zip file entry. */
static bool digestEntry(const ZipArchive *pArchive, const ZipEntry *pEntry,
unsigned *doneBytes, unsigned totalBytes,
uint8_t digest[SHA_DIGEST_SIZE]) {
struct DigestContext context;
SHA_init(&context.digest);
context.doneBytes = doneBytes;
context.totalBytes = totalBytes;
if (!mzProcessZipEntryContents(pArchive, pEntry, updateHash, &context)) {
UnterminatedString fn = mzGetZipEntryFileName(pEntry);
LOGE("Can't digest %.*s\n", fn.len, fn.str);
return false;
if (footer[2] != 0xff || footer[3] != 0xff) {
fclose(f);
return VERIFY_FAILURE;
}
memcpy(digest, SHA_final(&context.digest), SHA_DIGEST_SIZE);
int comment_size = footer[4] + (footer[5] << 8);
int signature_start = footer[0] + (footer[1] << 8);
LOGI("comment is %d bytes; signature %d bytes from end\n",
comment_size, signature_start);
#ifdef LOG_VERBOSE
UnterminatedString fn = mzGetZipEntryFileName(pEntry);
char base64[SHA_DIGEST_SIZE * 3];
b64_ntop(digest, SHA_DIGEST_SIZE, base64, sizeof(base64));
LOGV("sha1(%.*s) = %s\n", fn.len, fn.str, base64);
#endif
if (signature_start - FOOTER_SIZE < RSANUMBYTES) {
// "signature" block isn't big enough to contain an RSA block.
LOGE("signature is too short\n");
fclose(f);
return VERIFY_FAILURE;
}
return true;
}
#define EOCD_HEADER_SIZE 22
// The end-of-central-directory record is 22 bytes plus any
// comment length.
size_t eocd_size = comment_size + EOCD_HEADER_SIZE;
/* Find a /META-INF/xxx.SF signature file signed by a matching xxx.RSA file. */
static const ZipEntry *verifySignature(const ZipArchive *pArchive,
const RSAPublicKey *pKeys, unsigned int numKeys) {
static const char prefix[] = "META-INF/";
static const char rsa[] = ".RSA", sf[] = ".SF";
if (fseek(f, -eocd_size, SEEK_END) != 0) {
LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
fclose(f);
return VERIFY_FAILURE;
}
unsigned int i, j;
for (i = 0; i < mzZipEntryCount(pArchive); ++i) {
const ZipEntry *rsaEntry = mzGetZipEntryAt(pArchive, i);
UnterminatedString rsaName = mzGetZipEntryFileName(rsaEntry);
int rsaLen = mzGetZipEntryUncompLen(rsaEntry);
if (rsaLen >= RSANUMBYTES && rsaName.len > sizeof(prefix) &&
!strncmp(rsaName.str, prefix, sizeof(prefix) - 1) &&
!strncmp(rsaName.str + rsaName.len - sizeof(rsa) + 1,
rsa, sizeof(rsa) - 1)) {
char *sfName = malloc(rsaName.len - sizeof(rsa) + sizeof(sf) + 1);
if (sfName == NULL) {
LOGE("Can't allocate %d bytes for filename\n", rsaName.len);
continue;
}
// Determine how much of the file is covered by the signature.
// This is everything except the signature data and length, which
// includes all of the EOCD except for the comment length field (2
// bytes) and the comment data.
size_t signed_len = ftell(f) + EOCD_HEADER_SIZE - 2;
/* Replace .RSA with .SF */
strncpy(sfName, rsaName.str, rsaName.len - sizeof(rsa) + 1);
strcpy(sfName + rsaName.len - sizeof(rsa) + 1, sf);
const ZipEntry *sfEntry = mzFindZipEntry(pArchive, sfName);
unsigned char* eocd = malloc(eocd_size);
if (eocd == NULL) {
LOGE("malloc for EOCD record failed\n");
fclose(f);
return VERIFY_FAILURE;
}
if (fread(eocd, 1, eocd_size, f) != eocd_size) {
LOGE("failed to read eocd from %s (%s)\n", path, strerror(errno));
fclose(f);
return VERIFY_FAILURE;
}
if (sfEntry == NULL) {
LOGW("Missing signature file %s\n", sfName);
free(sfName);
continue;
}
// If this is really is the EOCD record, it will begin with the
// magic number $50 $4b $05 $06.
if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
eocd[2] != 0x05 || eocd[3] != 0x06) {
LOGE("signature length doesn't match EOCD marker\n");
fclose(f);
return VERIFY_FAILURE;
}
free(sfName);
uint8_t sfDigest[SHA_DIGEST_SIZE];
if (!digestEntry(pArchive, sfEntry, NULL, 0, sfDigest)) continue;
char *rsaBuf = slurpEntry(pArchive, rsaEntry);
if (rsaBuf == NULL) continue;
/* Try to verify the signature with all the keys. */
uint8_t *sig = (uint8_t *) rsaBuf + rsaLen - RSANUMBYTES;
for (j = 0; j < numKeys; ++j) {
if (RSA_verify(&pKeys[j], sig, RSANUMBYTES, sfDigest)) {
free(rsaBuf);
LOGI("Verified %.*s\n", rsaName.len, rsaName.str);
return sfEntry;
}
}
free(rsaBuf);
LOGW("Can't verify %.*s\n", rsaName.len, rsaName.str);
int i;
for (i = 4; i < eocd_size-3; ++i) {
if (eocd[i ] == 0x50 && eocd[i+1] == 0x4b &&
eocd[i+2] == 0x05 && eocd[i+1] == 0x06) {
// if the sequence $50 $4b $05 $06 appears anywhere after
// the real one, minzip will find the later (wrong) one,
// which could be exploitable. Fail verification if
// this sequence occurs anywhere after the real one.
LOGE("EOCD marker occurs after start of EOCD\n");
fclose(f);
return VERIFY_FAILURE;
}
}
LOGE("No signature (%d files)\n", mzZipEntryCount(pArchive));
return NULL;
}
#define BUFFER_SIZE 4096
SHA_CTX ctx;
SHA_init(&ctx);
unsigned char* buffer = malloc(BUFFER_SIZE);
if (buffer == NULL) {
LOGE("failed to alloc memory for sha1 buffer\n");
fclose(f);
return VERIFY_FAILURE;
}
/* Verify /META-INF/MANIFEST.MF against the digest in a signature file. */
static const ZipEntry *verifyManifest(const ZipArchive *pArchive,
const ZipEntry *sfEntry) {
static const char prefix[] = "SHA1-Digest-Manifest: ", eol[] = "\r\n";
uint8_t expected[SHA_DIGEST_SIZE + 3], actual[SHA_DIGEST_SIZE];
char *sfBuf = slurpEntry(pArchive, sfEntry);
if (sfBuf == NULL) return NULL;
char *line, *save;
for (line = strtok_r(sfBuf, eol, &save); line != NULL;
line = strtok_r(NULL, eol, &save)) {
if (!strncasecmp(prefix, line, sizeof(prefix) - 1)) {
UnterminatedString fn = mzGetZipEntryFileName(sfEntry);
const char *digest = line + sizeof(prefix) - 1;
int n = b64_pton(digest, expected, sizeof(expected));
if (n != SHA_DIGEST_SIZE) {
LOGE("Invalid base64 in %.*s: %s (%d)\n",
fn.len, fn.str, digest, n);
line = NULL;
}
break;
double frac = -1.0;
size_t so_far = 0;
fseek(f, 0, SEEK_SET);
while (so_far < signed_len) {
int size = BUFFER_SIZE;
if (signed_len - so_far < size) size = signed_len - so_far;
if (fread(buffer, 1, size, f) != size) {
LOGE("failed to read data from %s (%s)\n", path, strerror(errno));
fclose(f);
return VERIFY_FAILURE;
}
SHA_update(&ctx, buffer, size);
so_far += size;
double f = so_far / (double)signed_len;
if (f > frac + 0.02 || size == so_far) {
ui_set_progress(f);
frac = f;
}
}
fclose(f);
free(buffer);
free(sfBuf);
if (line == NULL) {
LOGE("No digest manifest in signature file\n");
return false;
}
const char *mfName = "META-INF/MANIFEST.MF";
const ZipEntry *mfEntry = mzFindZipEntry(pArchive, mfName);
if (mfEntry == NULL) {
LOGE("No manifest file %s\n", mfName);
return NULL;
}
if (!digestEntry(pArchive, mfEntry, NULL, 0, actual)) return NULL;
if (memcmp(expected, actual, SHA_DIGEST_SIZE)) {
UnterminatedString fn = mzGetZipEntryFileName(sfEntry);
LOGE("Wrong digest for %s in %.*s\n", mfName, fn.len, fn.str);
return NULL;
}
LOGI("Verified %s\n", mfName);
return mfEntry;
}
/* Verify all the files in a Zip archive against the manifest. */
static bool verifyArchive(const ZipArchive *pArchive, const ZipEntry *mfEntry) {
static const char namePrefix[] = "Name: ";
static const char contPrefix[] = " "; // Continuation of the filename
static const char digestPrefix[] = "SHA1-Digest: ";
static const char eol[] = "\r\n";
char *mfBuf = slurpEntry(pArchive, mfEntry);
if (mfBuf == NULL) return false;
/* we're using calloc() here, so the initial state of the array is false */
bool *unverified = (bool *) calloc(mzZipEntryCount(pArchive), sizeof(bool));
if (unverified == NULL) {
LOGE("Can't allocate valid flags\n");
free(mfBuf);
return false;
}
/* Mark all the files in the archive that need to be verified.
* As we scan the manifest and check signatures, we'll unset these flags.
* At the end, we'll make sure that all the flags are unset.
*/
unsigned i, totalBytes = 0;
for (i = 0; i < mzZipEntryCount(pArchive); ++i) {
const ZipEntry *entry = mzGetZipEntryAt(pArchive, i);
UnterminatedString fn = mzGetZipEntryFileName(entry);
int len = mzGetZipEntryUncompLen(entry);
// Don't validate: directories, the manifest, *.RSA, and *.SF.
if (entry == mfEntry) {
LOGV("Skipping manifest %.*s\n", fn.len, fn.str);
} else if (fn.len > 0 && fn.str[fn.len-1] == '/' && len == 0) {
LOGV("Skipping directory %.*s\n", fn.len, fn.str);
} else if (!strncasecmp(fn.str, "META-INF/", 9) && (
!strncasecmp(fn.str + fn.len - 4, ".RSA", 4) ||
!strncasecmp(fn.str + fn.len - 3, ".SF", 3))) {
LOGV("Skipping signature %.*s\n", fn.len, fn.str);
} else {
unverified[i] = true;
totalBytes += len;
const uint8_t* sha1 = SHA_final(&ctx);
for (i = 0; i < numKeys; ++i) {
// The 6 bytes is the "$ff $ff (signature_start) (comment_size)" that
// the signing tool appends after the signature itself.
if (RSA_verify(pKeys+i, eocd + eocd_size - 6 - RSANUMBYTES,
RSANUMBYTES, sha1)) {
LOGI("whole-file signature verified\n");
free(eocd);
return VERIFY_SUCCESS;
}
}
unsigned doneBytes = 0;
char *line, *save, *name = NULL;
for (line = strtok_r(mfBuf, eol, &save); line != NULL;
line = strtok_r(NULL, eol, &save)) {
if (!strncasecmp(line, namePrefix, sizeof(namePrefix) - 1)) {
// "Name:" introducing a new stanza
if (name != NULL) {
LOGE("No digest:\n %s\n", name);
break;
}
name = strdup(line + sizeof(namePrefix) - 1);
if (name == NULL) {
LOGE("Can't copy filename in %s\n", line);
break;
}
} else if (!strncasecmp(line, contPrefix, sizeof(contPrefix) - 1)) {
// Continuing a long name (nothing else should be continued)
const char *tail = line + sizeof(contPrefix) - 1;
if (name == NULL) {
LOGE("Unexpected continuation:\n %s\n", tail);
}
char *concat;
if (asprintf(&concat, "%s%s", name, tail) < 0) {
LOGE("Can't append continuation %s\n", tail);
break;
}
free(name);
name = concat;
} else if (!strncasecmp(line, digestPrefix, sizeof(digestPrefix) - 1)) {
// "Digest:" supplying a hash code for the current stanza
const char *base64 = line + sizeof(digestPrefix) - 1;
if (name == NULL) {
LOGE("Unexpected digest:\n %s\n", base64);
break;
}
const ZipEntry *entry = mzFindZipEntry(pArchive, name);
if (entry == NULL) {
LOGE("Missing file:\n %s\n", name);
break;
}
if (!mzIsZipEntryIntact(pArchive, entry)) {
LOGE("Corrupt file:\n %s\n", name);
break;
}
if (!unverified[mzGetZipEntryIndex(pArchive, entry)]) {
LOGE("Unexpected file:\n %s\n", name);
break;
}
uint8_t expected[SHA_DIGEST_SIZE + 3], actual[SHA_DIGEST_SIZE];
int n = b64_pton(base64, expected, sizeof(expected));
if (n != SHA_DIGEST_SIZE) {
LOGE("Invalid base64:\n %s\n %s\n", name, base64);
break;
}
if (!digestEntry(pArchive, entry, &doneBytes, totalBytes, actual) ||
memcmp(expected, actual, SHA_DIGEST_SIZE) != 0) {
LOGE("Wrong digest:\n %s\n", name);
break;
}
LOGI("Verified %s\n", name);
unverified[mzGetZipEntryIndex(pArchive, entry)] = false;
free(name);
name = NULL;
}
}
if (name != NULL) free(name);
free(mfBuf);
for (i = 0; i < mzZipEntryCount(pArchive) && !unverified[i]; ++i) ;
free(unverified);
// This means we didn't get to the end of the manifest successfully.
if (line != NULL) return false;
if (i < mzZipEntryCount(pArchive)) {
const ZipEntry *entry = mzGetZipEntryAt(pArchive, i);
UnterminatedString fn = mzGetZipEntryFileName(entry);
LOGE("No digest for %.*s\n", fn.len, fn.str);
return false;
}
return true;
}
bool verify_jar_signature(const ZipArchive *pArchive,
const RSAPublicKey *pKeys, int numKeys) {
const ZipEntry *sfEntry = verifySignature(pArchive, pKeys, numKeys);
if (sfEntry == NULL) return false;
const ZipEntry *mfEntry = verifyManifest(pArchive, sfEntry);
if (mfEntry == NULL) return false;
return verifyArchive(pArchive, mfEntry);
free(eocd);
LOGE("failed to verify whole-file signature\n");
return VERIFY_FAILURE;
}

View File

@ -17,14 +17,14 @@
#ifndef _RECOVERY_VERIFIER_H
#define _RECOVERY_VERIFIER_H
#include "minzip/Zip.h"
#include "mincrypt/rsa.h"
/*
* Check the digital signature (as applied by jarsigner) on a Zip archive.
* Every file in the archive must be signed by one of the supplied RSA keys.
/* Look in the file for a signature footer, and verify that it
* matches one of the given keys. Return one of the constants below.
*/
bool verify_jar_signature(const ZipArchive *pArchive,
const RSAPublicKey *pKeys, int numKeys);
int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys);
#define VERIFY_SUCCESS 0
#define VERIFY_FAILURE 1
#endif /* _RECOVERY_VERIFIER_H */