-
Notifications
You must be signed in to change notification settings - Fork 0
/
recovery.cpp
1579 lines (1362 loc) · 51.2 KB
/
recovery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2007 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 <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <linux/input.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/klog.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <chrono>
#include <base/file.h>
#include <base/stringprintf.h>
#include "bootloader.h"
#include "common.h"
#include "cutils/properties.h"
#include "cutils/android_reboot.h"
#include "install.h"
#include "minui/minui.h"
#include "minzip/DirUtil.h"
#include "roots.h"
#include "ui.h"
#include "screen_ui.h"
#include "device.h"
#include "voldclient.h"
#include "adb_install.h"
#include "adb.h"
#include "fuse_sideload.h"
#include "fuse_sdcard_provider.h"
extern "C" {
#include "recovery_cmds.h"
}
#include "libs/CarbonExtras/Settings.h"
#include "libs/CarbonExtras/RebootMenu.h"
struct selabel_handle *sehandle;
#ifdef HAVE_OEMLOCK
/*
* liboemlock must supply the following C symbols:
*
* - int oemlock_get()
*
* Returns the current state of the OEM lock, if available.
* -1: Not available and/or error
* 0: Unlocked
* 1: Locked
*
* - int oemlock_set(int lock)
*
* Sets the state of the OEM lock. The "lock" parameter will be set
* to 0 for unlock and 1 for lock.
*
* Returns 0 on success, -1 on error
*/
extern "C" {
int oemlock_get();
int oemlock_set(int lock);
}
enum OemLockOp {
OEM_LOCK_NONE,
OEM_LOCK_UNLOCK
};
static OemLockOp oem_lock = OEM_LOCK_NONE;
#endif
static const struct option OPTIONS[] = {
{ "send_intent", required_argument, NULL, 'i' },
{ "update_package", required_argument, NULL, 'u' },
{ "headless", no_argument, NULL, 'h' },
{ "wipe_data", no_argument, NULL, 'w' },
{ "wipe_cache", no_argument, NULL, 'c' },
{ "wipe_media", no_argument, NULL, 'm' },
{ "show_text", no_argument, NULL, 't' },
{ "sideload", no_argument, NULL, 's' },
{ "sideload_auto_reboot", no_argument, NULL, 'a' },
{ "just_exit", no_argument, NULL, 'x' },
{ "locale", required_argument, NULL, 'l' },
{ "stages", required_argument, NULL, 'g' },
{ "shutdown_after", no_argument, NULL, 'p' },
{ "reason", required_argument, NULL, 'r' },
{ NULL, 0, NULL, 0 },
};
static const char *CACHE_LOG_DIR = "/cache/recovery";
static const char *COMMAND_FILE = "/cache/recovery/command";
static const char *INTENT_FILE = "/cache/recovery/intent";
static const char *LOG_FILE = "/cache/recovery/log";
static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
static const char *LOCALE_FILE = "/cache/recovery/last_locale";
static const char *CACHE_ROOT = "/cache";
static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
static const int KEEP_LOG_COUNT = 10;
RecoveryUI* ui = NULL;
char* locale = NULL;
char* stage = NULL;
char* reason = NULL;
bool modified_flash = false;
#include "mtdutils/mounts.h"
/*
* The recovery tool communicates with the main system through /cache files.
* /cache/recovery/command - INPUT - command line for tool, one arg per line
* /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
* /cache/recovery/intent - OUTPUT - intent that was passed in
*
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
* --just_exit - do nothing; exit and reboot
*
* After completing, we remove /cache/recovery/command and reboot.
* Arguments may also be supplied in the bootloader control block (BCB).
* These important scenarios must be safely restartable at any point:
*
* FACTORY RESET
* 1. user selects "factory reset"
* 2. main system writes "--wipe_data" to /cache/recovery/command
* 3. main system reboots into recovery
* 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
* -- after this, rebooting will restart the erase --
* 5. erase_volume() reformats /data
* 6. erase_volume() reformats /cache
* 7. finish_recovery() erases BCB
* -- after this, rebooting will restart the main system --
* 8. main() calls reboot() to boot main system
*
* OTA INSTALL
* 1. main system downloads OTA package to /cache/some-filename.zip
* 2. main system writes "--update_package=/cache/some-filename.zip"
* 3. main system reboots into recovery
* 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
* -- after this, rebooting will attempt to reinstall the update --
* 5. install_package() attempts to install the update
* NOTE: the package install must itself be restartable from any point
* 6. finish_recovery() erases BCB
* -- after this, rebooting will (try to) restart the main system --
* 7. ** if install failed **
* 7a. prompt_and_wait() shows an error icon and waits for the user
* 7b; the user reboots (pulling the battery, etc) into the main system
* 8. main() calls maybe_install_firmware_update()
* ** if the update contained radio/hboot firmware **:
* 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
* -- after this, rebooting will reformat cache & restart main system --
* 8b. m_i_f_u() writes firmware image into raw cache partition
* 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
* -- after this, rebooting will attempt to reinstall firmware --
* 8d. bootloader tries to flash firmware
* 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
* -- after this, rebooting will reformat cache & restart main system --
* 8f. erase_volume() reformats /cache
* 8g. finish_recovery() erases BCB
* -- after this, rebooting will (try to) restart the main system --
* 9. main() calls reboot() to boot main system
*/
static const int MAX_ARG_LENGTH = 4096;
static const int MAX_ARGS = 100;
// open a given path, mounting partitions as necessary
FILE* fopen_path(const char *path, const char *mode) {
if (ensure_path_mounted(path) != 0) {
LOGE("Can't mount %s\n", path);
return NULL;
}
// When writing, try to create the containing directory, if necessary.
// Use generous permissions, the system (init.rc) will reset them.
if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1, sehandle);
FILE *fp = fopen(path, mode);
return fp;
}
// close a file, log an error if the error indicator is set
static void check_and_fclose(FILE *fp, const char *name) {
fflush(fp);
if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
fclose(fp);
}
bool is_ro_debuggable() {
char value[PROPERTY_VALUE_MAX+1];
return (property_get("ro.debuggable", value, NULL) == 1 && value[0] == '1');
}
static void redirect_stdio(const char* filename) {
int pipefd[2];
if (pipe(pipefd) == -1) {
LOGE("pipe failed: %s\n", strerror(errno));
// Fall back to traditional logging mode without timestamps.
// If these fail, there's not really anywhere to complain...
freopen(filename, "a", stdout); setbuf(stdout, NULL);
freopen(filename, "a", stderr); setbuf(stderr, NULL);
return;
}
pid_t pid = fork();
if (pid == -1) {
LOGE("fork failed: %s\n", strerror(errno));
// Fall back to traditional logging mode without timestamps.
// If these fail, there's not really anywhere to complain...
freopen(filename, "a", stdout); setbuf(stdout, NULL);
freopen(filename, "a", stderr); setbuf(stderr, NULL);
return;
}
if (pid == 0) {
/// Close the unused write end.
close(pipefd[1]);
auto start = std::chrono::steady_clock::now();
// Child logger to actually write to the log file.
FILE* log_fp = fopen(filename, "a");
if (log_fp == nullptr) {
LOGE("fopen \"%s\" failed: %s\n", filename, strerror(errno));
close(pipefd[0]);
_exit(1);
}
FILE* pipe_fp = fdopen(pipefd[0], "r");
if (pipe_fp == nullptr) {
LOGE("fdopen failed: %s\n", strerror(errno));
check_and_fclose(log_fp, filename);
close(pipefd[0]);
_exit(1);
}
char* line = nullptr;
size_t len = 0;
while (getline(&line, &len, pipe_fp) != -1) {
auto now = std::chrono::steady_clock::now();
double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
now - start).count();
if (line[0] == '\n') {
fprintf(log_fp, "[%12.6lf]\n", duration);
} else {
fprintf(log_fp, "[%12.6lf] %s", duration, line);
}
fflush(log_fp);
}
LOGE("getline failed: %s\n", strerror(errno));
free(line);
check_and_fclose(log_fp, filename);
close(pipefd[0]);
_exit(1);
} else {
// Redirect stdout/stderr to the logger process.
// Close the unused read end.
close(pipefd[0]);
setbuf(stdout, nullptr);
setbuf(stderr, nullptr);
if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
LOGE("dup2 stdout failed: %s\n", strerror(errno));
}
if (dup2(pipefd[1], STDERR_FILENO) == -1) {
LOGE("dup2 stderr failed: %s\n", strerror(errno));
}
close(pipefd[1]);
}
}
// command line args come from, in decreasing precedence:
// - the actual command line
// - the bootloader control block (one per line, after "recovery")
// - the contents of COMMAND_FILE (one per line)
static void
get_args(int *argc, char ***argv) {
struct bootloader_message boot;
memset(&boot, 0, sizeof(boot));
get_bootloader_message(&boot); // this may fail, leaving a zeroed structure
stage = strndup(boot.stage, sizeof(boot.stage));
if (boot.command[0] != 0 && boot.command[0] != 255) {
LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command);
}
if (boot.status[0] != 0 && boot.status[0] != 255) {
LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status);
}
// --- if arguments weren't supplied, look in the bootloader control block
if (*argc <= 1) {
boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
const char *arg = strtok(boot.recovery, "\n");
if (arg != NULL && !strcmp(arg, "recovery")) {
*argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
(*argv)[0] = strdup(arg);
for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
if ((arg = strtok(NULL, "\n")) == NULL) break;
// Arguments that may only be passed in BCB
#ifdef HAVE_OEMLOCK
if (strcmp(arg, "--oemunlock") == 0) {
oem_lock = OEM_LOCK_UNLOCK;
--*argc;
continue;
}
#endif
(*argv)[*argc] = strdup(arg);
}
LOGI("Got arguments from boot message\n");
} else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
}
}
// --- if that doesn't work, try the command file
if (*argc <= 1) {
FILE *fp = fopen_path(COMMAND_FILE, "r");
if (fp != NULL) {
char *token;
char *argv0 = (*argv)[0];
*argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
(*argv)[0] = argv0; // use the same program name
char buf[MAX_ARG_LENGTH];
for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
if (!fgets(buf, sizeof(buf), fp)) break;
token = strtok(buf, "\r\n");
if (token != NULL) {
(*argv)[*argc] = strdup(token); // Strip newline.
} else {
--*argc;
}
}
check_and_fclose(fp, COMMAND_FILE);
LOGI("Got arguments from %s\n", COMMAND_FILE);
}
}
// --> write the arguments we have back into the bootloader control block
// always boot into recovery after this (until finish_recovery() is called)
strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
int i;
for (i = 1; i < *argc; ++i) {
strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
strlcat(boot.recovery, "\n", sizeof(boot.recovery));
}
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);
}
// Read from kernel log into buffer and write out to file.
static void save_kernel_log(const char* destination) {
int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
if (klog_buf_len <= 0) {
LOGE("Error getting klog size: %s\n", strerror(errno));
return;
}
std::string buffer(klog_buf_len, 0);
int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
if (n == -1) {
LOGE("Error in reading klog: %s\n", strerror(errno));
return;
}
buffer.resize(n);
android::base::WriteStringToFile(buffer, destination);
}
// How much of the temp log we have copied to the copy in cache.
static long tmplog_offset = 0;
static void copy_log_file(const char* source, const char* destination, bool append) {
FILE* dest_fp = fopen_path(destination, append ? "a" : "w");
if (dest_fp == nullptr) {
LOGE("Can't open %s\n", destination);
} else {
FILE* source_fp = fopen(source, "r");
if (source_fp != nullptr) {
if (append) {
fseek(source_fp, tmplog_offset, SEEK_SET); // Since last write
}
char buf[4096];
size_t bytes;
while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
fwrite(buf, 1, bytes, dest_fp);
}
if (append) {
tmplog_offset = ftell(source_fp);
}
check_and_fclose(source_fp, source);
}
check_and_fclose(dest_fp, destination);
}
}
// Rename last_log -> last_log.1 -> last_log.2 -> ... -> last_log.$max.
// Similarly rename last_kmsg -> last_kmsg.1 -> ... -> last_kmsg.$max.
// Overwrite any existing last_log.$max and last_kmsg.$max.
static void rotate_logs(int max) {
// Logs should only be rotated once.
static bool rotated = false;
if (rotated) {
return;
}
rotated = true;
ensure_path_mounted(LAST_LOG_FILE);
ensure_path_mounted(LAST_KMSG_FILE);
for (int i = max-1; i >= 0; --i) {
std::string old_log = android::base::StringPrintf("%s", LAST_LOG_FILE);
if (i > 0) {
old_log += "." + std::to_string(i);
}
std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
// Ignore errors if old_log doesn't exist.
rename(old_log.c_str(), new_log.c_str());
std::string old_kmsg = android::base::StringPrintf("%s", LAST_KMSG_FILE);
if (i > 0) {
old_kmsg += "." + std::to_string(i);
}
std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
rename(old_kmsg.c_str(), new_kmsg.c_str());
}
}
static void copy_logs() {
// We only rotate and record the log of the current session if there are
// actual attempts to modify the flash, such as wipes, installs from BCB
// or menu selections. This is to avoid unnecessary rotation (and
// possible deletion) of log files, if it does not do anything loggable.
if (!modified_flash) {
return;
}
rotate_logs(KEEP_LOG_COUNT);
// Copy logs to cache so the system can find out what happened.
copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
save_kernel_log(LAST_KMSG_FILE);
chmod(LOG_FILE, 0600);
chown(LOG_FILE, 1000, 1000); // system user
chmod(LAST_KMSG_FILE, 0600);
chown(LAST_KMSG_FILE, 1000, 1000); // system user
chmod(LAST_LOG_FILE, 0640);
chmod(LAST_INSTALL_FILE, 0644);
sync();
}
// 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
// record any intent we were asked to communicate back to the system.
// this function is idempotent: call it as many times as you like.
static void
finish_recovery(const char *send_intent) {
// By this point, we're ready to return to the main system...
if (send_intent != NULL) {
FILE *fp = fopen_path(INTENT_FILE, "w");
if (fp == NULL) {
LOGE("Can't open %s\n", INTENT_FILE);
} else {
fputs(send_intent, fp);
check_and_fclose(fp, INTENT_FILE);
}
}
// Save the locale to cache, so if recovery is next started up
// without a --locale argument (eg, directly from the bootloader)
// it will use the last-known locale.
if (locale != NULL) {
LOGI("Saving locale \"%s\"\n", locale);
FILE* fp = fopen_path(LOCALE_FILE, "w");
fwrite(locale, 1, strlen(locale), fp);
fflush(fp);
fsync(fileno(fp));
check_and_fclose(fp, LOCALE_FILE);
}
copy_logs();
// Reset to normal system boot so recovery won't cycle indefinitely.
struct bootloader_message boot;
memset(&boot, 0, sizeof(boot));
set_bootloader_message(&boot);
// Remove the command file, so recovery won't repeat indefinitely.
if (ensure_path_mounted(COMMAND_FILE) != 0 ||
(unlink(COMMAND_FILE) && errno != ENOENT)) {
LOGW("Can't unlink %s\n", COMMAND_FILE);
}
ensure_path_unmounted(CACHE_ROOT);
sync(); // For good measure.
}
typedef struct _saved_log_file {
char* name;
struct stat st;
unsigned char* data;
struct _saved_log_file* next;
} saved_log_file;
static bool erase_volume(const char* volume, bool force = false) {
bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
saved_log_file* head = NULL;
ui->SetBackground(RecoveryUI::ERASING);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
if (!force && is_cache) {
// If we're reformatting /cache, we load any past logs
// (i.e. "/cache/recovery/last_*") and the current log
// ("/cache/recovery/log") into memory, so we can restore them after
// the reformat.
ensure_path_mounted(volume);
DIR* d;
struct dirent* de;
d = opendir(CACHE_LOG_DIR);
if (d) {
char path[PATH_MAX];
strcpy(path, CACHE_LOG_DIR);
strcat(path, "/");
int path_len = strlen(path);
while ((de = readdir(d)) != NULL) {
if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
saved_log_file* p = (saved_log_file*) malloc(sizeof(saved_log_file));
strcpy(path+path_len, de->d_name);
p->name = strdup(path);
if (stat(path, &(p->st)) == 0) {
// truncate files to 512kb
if (p->st.st_size > (1 << 19)) {
p->st.st_size = 1 << 19;
}
p->data = (unsigned char*) malloc(p->st.st_size);
FILE* f = fopen(path, "rb");
fread(p->data, 1, p->st.st_size, f);
fclose(f);
p->next = head;
head = p;
} else {
free(p);
}
}
}
closedir(d);
} else {
if (errno != ENOENT) {
printf("opendir failed: %s\n", strerror(errno));
}
}
}
ui->Print("Formatting %s...\n", volume);
if (volume[0] == '/') {
ensure_path_unmounted(volume);
}
int result = format_volume(volume, force);
if (!force && is_cache) {
while (head) {
FILE* f = fopen_path(head->name, "wb");
if (f) {
fwrite(head->data, 1, head->st.st_size, f);
fclose(f);
chmod(head->name, head->st.st_mode);
chown(head->name, head->st.st_uid, head->st.st_gid);
}
free(head->name);
free(head->data);
saved_log_file* temp = head->next;
free(head);
head = temp;
}
// Any part of the log we'd copied to cache is now gone.
// Reset the pointer so we copy from the beginning of the temp
// log.
tmplog_offset = 0;
copy_logs();
}
ui->SetBackground(RecoveryUI::NONE);
ui->SetProgressType(RecoveryUI::EMPTY);
return (result == 0);
}
int
get_menu_selection(const char* const * headers, const char* const * items,
int menu_only, int initial_selection, Device* device) {
// throw away keys pressed previously, so user doesn't
// accidentally trigger menu items.
ui->FlushKeys();
// Count items to detect valid values for absolute selection
int item_count = 0;
while (items[item_count] != NULL)
++item_count;
ui->StartMenu(headers, items, initial_selection);
int selected = initial_selection;
int chosen_item = -1;
while (chosen_item < 0 && chosen_item != Device::kGoBack && chosen_item != Device::kRefresh) {
int key = ui->WaitKey();
int visible = ui->IsTextVisible();
if (key == -1) { // ui_wait_key() timed out
if (ui->WasTextEverVisible()) {
continue;
} else {
LOGI("timed out waiting for key input; rebooting.\n");
ui->EndMenu();
return 0; // XXX fixme
}
} else if (key == -2) { // we are returning from ui_cancel_wait_key(): no action
return Device::kNoAction;
}
else if (key == -6) {
return Device::kRefresh;
}
int action = device->HandleMenuKey(key, visible);
if (action >= 0) {
if ((action & ~KEY_FLAG_ABS) >= item_count) {
action = Device::kNoAction;
}
else {
// Absolute selection. Update selected item and give some
// feedback in the UI by selecting the item for a short time.
selected = action & ~KEY_FLAG_ABS;
action = Device::kInvokeItem;
selected = ui->SelectMenu(selected, true);
usleep(50*1000);
}
}
if (action < 0) {
switch (action) {
case Device::kHighlightUp:
selected = ui->SelectMenu(--selected);
break;
case Device::kHighlightDown:
selected = ui->SelectMenu(++selected);
break;
case Device::kScrollUp:
selected = ui->ScrollMenu(selected, 0);
break;
case Device::kScrollDown:
selected = ui->ScrollMenu(selected, 1);
break;
case Device::kInvokeItem:
chosen_item = selected;
break;
case Device::kNoAction:
break;
case Device::kGoBack:
chosen_item = Device::kGoBack;
break;
case Device::kRefresh:
chosen_item = Device::kRefresh;
break;
}
} else if (!menu_only) {
chosen_item = action;
}
}
ui->EndMenu();
return chosen_item;
}
static int compare_string(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}
// Returns a malloc'd path, or NULL.
static char* browse_directory(const char* path, Device* device) {
DIR* d = opendir(path);
if (d == NULL) {
LOGE("error opening %s: %s\n", path, strerror(errno));
return NULL;
}
int d_size = 0;
int d_alloc = 10;
char** dirs = (char**)malloc(d_alloc * sizeof(char*));
int z_size = 1;
int z_alloc = 10;
char** zips = (char**)malloc(z_alloc * sizeof(char*));
zips[0] = strdup("../");
struct dirent* de;
while ((de = readdir(d)) != NULL) {
int name_len = strlen(de->d_name);
if (de->d_type == DT_DIR) {
// skip "." and ".." entries
if (name_len == 1 && de->d_name[0] == '.') continue;
if (name_len == 2 && de->d_name[0] == '.' &&
de->d_name[1] == '.') continue;
if (d_size >= d_alloc) {
d_alloc *= 2;
dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
}
dirs[d_size] = (char*)malloc(name_len + 2);
strcpy(dirs[d_size], de->d_name);
dirs[d_size][name_len] = '/';
dirs[d_size][name_len+1] = '\0';
++d_size;
} else if (de->d_type == DT_REG &&
name_len >= 4 &&
strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
if (z_size >= z_alloc) {
z_alloc *= 2;
zips = (char**)realloc(zips, z_alloc * sizeof(char*));
}
zips[z_size++] = strdup(de->d_name);
}
}
closedir(d);
qsort(dirs, d_size, sizeof(char*), compare_string);
qsort(zips, z_size, sizeof(char*), compare_string);
// append dirs to the zips list
if (d_size + z_size + 1 > z_alloc) {
z_alloc = d_size + z_size + 1;
zips = (char**)realloc(zips, z_alloc * sizeof(char*));
}
memcpy(zips + z_size, dirs, d_size * sizeof(char*));
free(dirs);
z_size += d_size;
zips[z_size] = NULL;
const char* headers[] = { "Choose a package to install:", path, NULL };
char* result;
int chosen_item = 0;
while (true) {
chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
if (chosen_item == 0 || chosen_item == Device::kGoBack) {
// go up but continue browsing (if the caller is update_directory)
result = NULL;
break;
}
char* item = zips[chosen_item];
int item_len = strlen(item);
char new_path[PATH_MAX];
strlcpy(new_path, path, PATH_MAX);
strlcat(new_path, "/", PATH_MAX);
strlcat(new_path, item, PATH_MAX);
if (item[item_len-1] == '/') {
// recurse down into a subdirectory
new_path[strlen(new_path)-1] = '\0'; // truncate the trailing '/'
result = browse_directory(new_path, device);
if (result) break;
} else {
// selected a zip file: return the malloc'd path to the caller.
result = strdup(new_path);
break;
}
}
for (int i = 0; i < z_size; ++i) free(zips[i]);
free(zips);
return result;
}
static bool yes_no(Device* device, const char* question1, const char* question2) {
const char* headers[] = { question1, question2, NULL };
const char* items[] = { " No", " Yes", NULL };
int chosen_item = get_menu_selection(headers, items, 1, 0, device);
return (chosen_item == 1);
}
// Return true on success.
static bool wipe_data(int should_confirm, Device* device, bool force = false) {
if (should_confirm && !yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!")) {
return false;
}
modified_flash = true;
ui->Print("\n-- Wiping data...\n");
bool success;
retry:
success =
device->PreWipeData() &&
erase_volume("/data", force) &&
erase_volume("/cache") &&
device->PostWipeData();
if (!success && !force) {
if (!should_confirm || yes_no(device, "Wipe failed, format instead?", " THIS CAN NOT BE UNDONE!")) {
force = true;
goto retry;
}
}
ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
return success;
}
static bool wipe_media(int should_confirm, Device* device) {
if (should_confirm && !yes_no(device, "Wipe all user media?", " THIS CAN NOT BE UNDONE!")) {
return false;
}
modified_flash = true;
ui->Print("\n-- Wiping media...\n");
bool success =
device->PreWipeMedia() &&
erase_volume("media") &&
device->PostWipeMedia();
ui->Print("Media wipe %s.\n", success ? "complete" : "failed");
return success;
}
// Return true on success.
static bool wipe_cache(bool should_confirm, Device* device) {
if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
return false;
}
modified_flash = true;
ui->Print("\n-- Wiping cache...\n");
bool success = erase_volume("/cache");
ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
return success;
}
static void choose_recovery_file(Device* device) {
// "Back" + KEEP_LOG_COUNT * 2 + terminating nullptr entry
char* entries[1 + KEEP_LOG_COUNT * 2 + 1];
memset(entries, 0, sizeof(entries));
unsigned int n = 0;
// Add LAST_LOG_FILE + LAST_LOG_FILE.x
// Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
for (int i = 0; i < KEEP_LOG_COUNT; i++) {
char* log_file;
int ret;
ret = (i == 0) ? asprintf(&log_file, "%s", LAST_LOG_FILE) :
asprintf(&log_file, "%s.%d", LAST_LOG_FILE, i);
if (ret == -1) {
// memory allocation failure - return early. Should never happen.
return;
}
if ((ensure_path_mounted(log_file) != 0) || (access(log_file, R_OK) == -1)) {
free(log_file);
} else {
entries[n++] = log_file;
}
char* kmsg_file;
ret = (i == 0) ? asprintf(&kmsg_file, "%s", LAST_KMSG_FILE) :
asprintf(&kmsg_file, "%s.%d", LAST_KMSG_FILE, i);
if (ret == -1) {
// memory allocation failure - return early. Should never happen.
return;
}
if ((ensure_path_mounted(kmsg_file) != 0) || (access(kmsg_file, R_OK) == -1)) {
free(kmsg_file);
} else {
entries[n++] = kmsg_file;
}
}
entries[n++] = strdup("Back");
const char* headers[] = { "Select file to view", nullptr };
while (true) {
int chosen_item = get_menu_selection(headers, entries, 1, 0, device);
if (strcmp(entries[chosen_item], "Back") == 0) break;
ui->ShowFile(entries[chosen_item]);
}
for (size_t i = 0; i < (sizeof(entries) / sizeof(*entries)); i++) {
free(entries[i]);
}
}
static int apply_from_storage(Device* device, const std::string& id, bool* wipe_cache) {
modified_flash = true;
int status;
if (!vdc->volumeMount(id)) {
return INSTALL_ERROR;
}
VolumeInfo vi = vdc->getVolume(id);
char* path = browse_directory(vi.mInternalPath.c_str(), device);
if (path == NULL) {
ui->Print("\n-- No package file selected.\n");
vdc->volumeUnmount(vi.mId);
return INSTALL_NONE;
}
ui->ClearText();
ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
ui->Print("\n-- Install %s ...\n", path);
set_sdcard_update_bootloader_message();
void* token = start_sdcard_fuse(path);
vdc->volumeUnmount(vi.mId, true);
status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
TEMPORARY_INSTALL_FILE, false);
finish_sdcard_fuse(token);
free(path);
return status;
}
static int
show_apply_update_menu(Device* device) {
static const char* headers[] = { "Apply update", "", NULL };
char* menu_items[MAX_NUM_MANAGED_VOLUMES + 1 + 1];
std::vector<VolumeInfo> volumes = vdc->getVolumes();
const int item_sideload = 0;
int n, i;
std::vector<VolumeInfo>::iterator vitr;
refresh:
menu_items[item_sideload] = strdup("Apply from ADB");