-
Notifications
You must be signed in to change notification settings - Fork 0
/
recovery.cpp
1651 lines (1439 loc) · 56.1 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 <inttypes.h>
#include <limits.h>
#include <linux/fs.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 <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <algorithm>
#include <chrono>
#include <memory>
#include <string>
#include <vector>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <bootloader_message/bootloader_message.h>
#include <cutils/android_reboot.h>
#include <cutils/properties.h> /* for property_list */
#include <healthd/BatteryMonitor.h>
#include <private/android_logger.h> /* private pmsg functions */
#include <private/android_filesystem_config.h> /* for AID_SYSTEM */
#include <selinux/android.h>
#include <selinux/label.h>
#include <selinux/selinux.h>
#include <ziparchive/zip_archive.h>
#include "adb_install.h"
#include "common.h"
#include "device.h"
#include "error_code.h"
#include "fuse_sdcard_provider.h"
#include "fuse_sideload.h"
#include "install.h"
#include "minadbd/minadbd.h"
#include "minui/minui.h"
#include "otautil/DirUtil.h"
#include "roots.h"
#include "rotate_logs.h"
#include "screen_ui.h"
#include "stub_ui.h"
#include "ui.h"
static const struct option OPTIONS[] = {
{ "update_package", required_argument, NULL, 'u' },
{ "retry_count", required_argument, NULL, 'n' },
{ "wipe_data", no_argument, NULL, 'w' },
{ "wipe_cache", no_argument, NULL, 'c' },
{ "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' },
{ "shutdown_after", no_argument, NULL, 'p' },
{ "reason", required_argument, NULL, 'r' },
{ "security", no_argument, NULL, 'e'},
{ "wipe_ab", no_argument, NULL, 0 },
{ "wipe_package_size", required_argument, NULL, 0 },
{ "prompt_and_wipe_data", no_argument, NULL, 0 },
{ NULL, 0, NULL, 0 },
};
// More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
static const std::vector<std::string> bootreason_blacklist {
"kernel_panic",
"Panic",
};
static const char *CACHE_LOG_DIR = "/cache/recovery";
static const char *COMMAND_FILE = "/cache/recovery/command";
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 *CONVERT_FBE_DIR = "/tmp/convert_fbe";
static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
static const char *CACHE_ROOT = "/cache";
static const char *DATA_ROOT = "/data";
static const char *SDCARD_ROOT = "/sdcard";
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";
// We will try to apply the update package 5 times at most in case of an I/O error or
// bspatch | imgpatch error.
static const int RETRY_LIMIT = 4;
static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
// GmsCore enters recovery mode to install package when having enough battery
// percentage. Normally, the threshold is 40% without charger and 20% with charger.
// So we should check battery with a slightly lower limitation.
static const int BATTERY_OK_PERCENTAGE = 20;
static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
static constexpr const char* DEFAULT_LOCALE = "en-US";
static std::string locale;
static bool has_cache = false;
RecoveryUI* ui = nullptr;
bool modified_flash = false;
std::string stage;
const char* reason = nullptr;
struct selabel_handle* sehandle;
/*
* 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)
*
* The arguments which may be supplied in the recovery.command file:
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --prompt_and_wipe_data - prompt the user that data is corrupt,
* with their consent 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
*/
// open a given path, mounting partitions as necessary
FILE* fopen_path(const char *path, const char *mode) {
if (ensure_path_mounted(path) != 0) {
LOG(ERROR) << "Can't mount " << 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 (fsync(fileno(fp)) == -1) {
PLOG(ERROR) << "Failed to fsync " << name;
}
if (ferror(fp)) {
PLOG(ERROR) << "Error in " << name;
}
fclose(fp);
}
bool is_ro_debuggable() {
return android::base::GetBoolProperty("ro.debuggable", false);
}
bool reboot(const std::string& command) {
std::string cmd = command;
if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
cmd += ",quiescent";
}
return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
}
static void redirect_stdio(const char* filename) {
int pipefd[2];
if (pipe(pipefd) == -1) {
PLOG(ERROR) << "pipe failed";
// 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) {
PLOG(ERROR) << "fork failed";
// 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, "ae");
if (log_fp == nullptr) {
PLOG(ERROR) << "fopen \"" << filename << "\" failed";
close(pipefd[0]);
_exit(EXIT_FAILURE);
}
FILE* pipe_fp = fdopen(pipefd[0], "r");
if (pipe_fp == nullptr) {
PLOG(ERROR) << "fdopen failed";
check_and_fclose(log_fp, filename);
close(pipefd[0]);
_exit(EXIT_FAILURE);
}
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);
}
PLOG(ERROR) << "getline failed";
free(line);
check_and_fclose(log_fp, filename);
close(pipefd[0]);
_exit(EXIT_FAILURE);
} 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) {
PLOG(ERROR) << "dup2 stdout failed";
}
if (dup2(pipefd[1], STDERR_FILENO) == -1) {
PLOG(ERROR) << "dup2 stderr failed";
}
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 std::vector<std::string> get_args(const int argc, char** const argv) {
CHECK_GT(argc, 0);
bootloader_message boot = {};
std::string err;
if (!read_bootloader_message(&boot, &err)) {
LOG(ERROR) << err;
// If fails, leave a zeroed bootloader_message.
boot = {};
}
stage = std::string(boot.stage);
if (boot.command[0] != 0) {
std::string boot_command = std::string(boot.command, sizeof(boot.command));
LOG(INFO) << "Boot command: " << boot_command;
}
if (boot.status[0] != 0) {
std::string boot_status = std::string(boot.status, sizeof(boot.status));
LOG(INFO) << "Boot status: " << boot_status;
}
std::vector<std::string> args(argv, argv + argc);
// --- if arguments weren't supplied, look in the bootloader control block
if (args.size() == 1) {
boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
std::string boot_recovery(boot.recovery);
std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
if (!tokens.empty() && tokens[0] == "recovery") {
for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
// Skip empty and '\0'-filled tokens.
if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
}
LOG(INFO) << "Got " << args.size() << " arguments from boot message";
} else if (boot.recovery[0] != 0) {
LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
}
}
// --- if that doesn't work, try the command file (if we have /cache).
if (args.size() == 1 && has_cache) {
std::string content;
if (ensure_path_mounted(COMMAND_FILE) == 0 &&
android::base::ReadFileToString(COMMAND_FILE, &content)) {
std::vector<std::string> tokens = android::base::Split(content, "\n");
// All the arguments in COMMAND_FILE are needed (unlike the BCB message,
// COMMAND_FILE doesn't use filename as the first argument).
for (auto it = tokens.begin(); it != tokens.end(); it++) {
// Skip empty and '\0'-filled tokens.
if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
}
LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
}
}
// Write the arguments (excluding the filename in args[0]) back into the
// bootloader control block. So the device will always boot into recovery to
// finish the pending work, until finish_recovery() is called.
std::vector<std::string> options(args.cbegin() + 1, args.cend());
if (!update_bootloader_message(options, &err)) {
LOG(ERROR) << "Failed to set BCB message: " << err;
}
return args;
}
// Set the BCB to reboot back into recovery (it won't resume the install from
// sdcard though).
static void set_sdcard_update_bootloader_message() {
std::vector<std::string> options;
std::string err;
if (!update_bootloader_message(options, &err)) {
LOG(ERROR) << "Failed to set BCB message: " << err;
}
}
// 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) {
PLOG(ERROR) << "Error getting klog size";
return;
}
std::string buffer(klog_buf_len, 0);
int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
if (n == -1) {
PLOG(ERROR) << "Error in reading klog";
return;
}
buffer.resize(n);
android::base::WriteStringToFile(buffer, destination);
}
// write content to the current pmsg session.
static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
filename, buf, len);
}
static void copy_log_file_to_pmsg(const char* source, const char* destination) {
std::string content;
android::base::ReadFileToString(source, &content);
__pmsg_write(destination, content.c_str(), content.length());
}
// How much of the temp log we have copied to the copy in cache.
static off_t tmplog_offset = 0;
static void copy_log_file(const char* source, const char* destination, bool append) {
FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
if (dest_fp == nullptr) {
PLOG(ERROR) << "Can't open " << destination;
} else {
FILE* source_fp = fopen(source, "re");
if (source_fp != nullptr) {
if (append) {
fseeko(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 = ftello(source_fp);
}
check_and_fclose(source_fp, source);
}
check_and_fclose(dest_fp, destination);
}
}
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;
}
// Always write to pmsg, this allows the OTA logs to be caught in logcat -L
copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
// We can do nothing for now if there's no /cache partition.
if (!has_cache) {
return;
}
ensure_path_mounted(LAST_LOG_FILE);
ensure_path_mounted(LAST_KMSG_FILE);
rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
// 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, AID_SYSTEM, AID_SYSTEM);
chmod(LAST_KMSG_FILE, 0600);
chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
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). This function is
// idempotent: call it as many times as you like.
static void finish_recovery() {
// Save the locale to cache, so if recovery is next started up without a '--locale' argument
// (e.g., directly from the bootloader) it will use the last-known locale.
if (!locale.empty() && has_cache) {
LOG(INFO) << "Saving locale \"" << locale << "\"";
if (ensure_path_mounted(LOCALE_FILE) != 0) {
LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
} else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
}
}
copy_logs();
// Reset to normal system boot so recovery won't cycle indefinitely.
std::string err;
if (!clear_bootloader_message(&err)) {
LOG(ERROR) << "Failed to clear BCB message: " << err;
}
// Remove the command file, so recovery won't repeat indefinitely.
if (has_cache) {
if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
}
ensure_path_unmounted(CACHE_ROOT);
}
sync(); // For good measure.
}
struct saved_log_file {
std::string name;
struct stat sb;
std::string data;
};
static bool erase_volume(const char* volume) {
bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
bool is_data = (strcmp(volume, DATA_ROOT) == 0);
ui->SetBackground(RecoveryUI::ERASING);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
std::vector<saved_log_file> log_files;
if (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);
struct dirent* de;
std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
if (d) {
while ((de = readdir(d.get())) != nullptr) {
if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
struct stat sb;
if (stat(path.c_str(), &sb) == 0) {
// truncate files to 512kb
if (sb.st_size > (1 << 19)) {
sb.st_size = 1 << 19;
}
std::string data(sb.st_size, '\0');
FILE* f = fopen(path.c_str(), "rbe");
fread(&data[0], 1, data.size(), f);
fclose(f);
log_files.emplace_back(saved_log_file{ path, sb, data });
}
}
}
} else {
if (errno != ENOENT) {
PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
}
}
}
ui->Print("Formatting %s...\n", volume);
ensure_path_unmounted(volume);
int result;
if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
// Create convert_fbe breadcrumb file to signal to init
// to convert to file based encryption, not full disk encryption
if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
return true;
}
FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
if (!f) {
ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
return true;
}
fclose(f);
result = format_volume(volume, CONVERT_FBE_DIR);
remove(CONVERT_FBE_FILE);
rmdir(CONVERT_FBE_DIR);
} else {
result = format_volume(volume);
}
if (is_cache) {
// Re-create the log dir and write back the log entries.
if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
dirCreateHierarchy(CACHE_LOG_DIR, 0777, nullptr, false, sehandle) == 0) {
for (const auto& log : log_files) {
if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
log.sb.st_gid)) {
PLOG(ERROR) << "Failed to write to " << log.name;
}
}
} else {
PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
}
// 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();
}
return (result == 0);
}
// Display a menu with the specified 'headers' and 'items'. Device specific HandleMenuKey() may
// return a positive number beyond the given range. Caller sets 'menu_only' to true to ensure only
// a menu item gets selected. 'initial_selection' controls the initial cursor location. Returns the
// (non-negative) chosen item number, or -1 if timed out waiting for input.
static int get_menu_selection(const char* const* headers, const char* const* items, bool menu_only,
int initial_selection, Device* device) {
// Throw away keys pressed previously, so user doesn't accidentally trigger menu items.
ui->FlushKeys();
ui->StartMenu(headers, items, initial_selection);
int selected = initial_selection;
int chosen_item = -1;
while (chosen_item < 0) {
int key = ui->WaitKey();
if (key == -1) { // WaitKey() timed out.
if (ui->WasTextEverVisible()) {
continue;
} else {
LOG(INFO) << "Timed out waiting for key input; rebooting.";
ui->EndMenu();
return -1;
}
}
bool visible = ui->IsTextVisible();
int action = device->HandleMenuKey(key, visible);
if (action < 0) {
switch (action) {
case Device::kHighlightUp:
selected = ui->SelectMenu(--selected);
break;
case Device::kHighlightDown:
selected = ui->SelectMenu(++selected);
break;
case Device::kInvokeItem:
chosen_item = selected;
break;
case Device::kNoAction:
break;
}
} else if (!menu_only) {
chosen_item = action;
}
}
ui->EndMenu();
return chosen_item;
}
// Returns the selected filename, or an empty string.
static std::string browse_directory(const std::string& path, Device* device) {
ensure_path_mounted(path.c_str());
std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
if (!d) {
PLOG(ERROR) << "error opening " << path;
return "";
}
std::vector<std::string> dirs;
std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
dirent* de;
while ((de = readdir(d.get())) != nullptr) {
std::string name(de->d_name);
if (de->d_type == DT_DIR) {
// Skip "." and ".." entries.
if (name == "." || name == "..") continue;
dirs.push_back(name + "/");
} else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
zips.push_back(name);
}
}
std::sort(dirs.begin(), dirs.end());
std::sort(zips.begin(), zips.end());
// Append dirs to the zips list.
zips.insert(zips.end(), dirs.begin(), dirs.end());
const char* entries[zips.size() + 1];
entries[zips.size()] = nullptr;
for (size_t i = 0; i < zips.size(); i++) {
entries[i] = zips[i].c_str();
}
const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
int chosen_item = 0;
while (true) {
chosen_item = get_menu_selection(headers, entries, true, chosen_item, device);
const std::string& item = zips[chosen_item];
if (chosen_item == 0) {
// Go up but continue browsing (if the caller is browse_directory).
return "";
}
std::string new_path = path + "/" + item;
if (new_path.back() == '/') {
// Recurse down into a subdirectory.
new_path.pop_back();
std::string result = browse_directory(new_path, device);
if (!result.empty()) return result;
} else {
// Selected a zip file: return the path to the caller.
return new_path;
}
}
// Unreachable.
}
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, true, 0, device);
return (chosen_item == 1);
}
static bool ask_to_wipe_data(Device* device) {
return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
}
// Return true on success.
static bool wipe_data(Device* device) {
modified_flash = true;
ui->Print("\n-- Wiping data...\n");
bool success =
device->PreWipeData() &&
erase_volume("/data") &&
(has_cache ? erase_volume("/cache") : true) &&
device->PostWipeData();
ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
return success;
}
static bool prompt_and_wipe_data(Device* device) {
// Use a single string and let ScreenRecoveryUI handles the wrapping.
const char* const headers[] = {
"Can't load Android system. Your data may be corrupt. "
"If you continue to get this message, you may need to "
"perform a factory data reset and erase all user data "
"stored on this device.",
nullptr
};
const char* const items[] = {
"Try again",
"Factory data reset",
NULL
};
for (;;) {
int chosen_item = get_menu_selection(headers, items, true, 0, device);
if (chosen_item != 1) {
return true; // Just reboot, no wipe; not a failure, user asked for it
}
if (ask_to_wipe_data(device)) {
return wipe_data(device);
}
}
}
// Return true on success.
static bool wipe_cache(bool should_confirm, Device* device) {
if (!has_cache) {
ui->Print("No /cache partition found.\n");
return false;
}
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;
}
// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
static bool secure_wipe_partition(const std::string& partition) {
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
if (fd == -1) {
PLOG(ERROR) << "Failed to open \"" << partition << "\"";
return false;
}
uint64_t range[2] = { 0, 0 };
if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
PLOG(ERROR) << "Failed to get partition size";
return false;
}
LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
LOG(INFO) << " Trying BLKSECDISCARD...";
if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
PLOG(WARNING) << " Failed";
// Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
unsigned int zeroes;
if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
LOG(INFO) << " Trying BLKDISCARD...";
if (ioctl(fd, BLKDISCARD, &range) == -1) {
PLOG(ERROR) << " Failed";
return false;
}
} else {
LOG(INFO) << " Trying BLKZEROOUT...";
if (ioctl(fd, BLKZEROOUT, &range) == -1) {
PLOG(ERROR) << " Failed";
return false;
}
}
}
LOG(INFO) << " Done";
return true;
}
// Check if the wipe package matches expectation:
// 1. verify the package.
// 2. check metadata (ota-type, pre-device and serial number if having one).
static bool check_wipe_package(size_t wipe_package_size) {
if (wipe_package_size == 0) {
LOG(ERROR) << "wipe_package_size is zero";
return false;
}
std::string wipe_package;
std::string err_str;
if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
PLOG(ERROR) << "Failed to read wipe package";
return false;
}
if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
wipe_package.size())) {
LOG(ERROR) << "Failed to verify package";
return false;
}
// Extract metadata
ZipArchiveHandle zip;
int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
"wipe_package", &zip);
if (err != 0) {
LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
return false;
}
std::string metadata;
if (!read_metadata_from_package(zip, &metadata)) {
CloseArchive(zip);
return false;
}
CloseArchive(zip);
// Check metadata
std::vector<std::string> lines = android::base::Split(metadata, "\n");
bool ota_type_matched = false;
bool device_type_matched = false;
bool has_serial_number = false;
bool serial_number_matched = false;
for (const auto& line : lines) {
if (line == "ota-type=BRICK") {
ota_type_matched = true;
} else if (android::base::StartsWith(line, "pre-device=")) {
std::string device_type = line.substr(strlen("pre-device="));
std::string real_device_type = android::base::GetProperty("ro.build.product", "");
device_type_matched = (device_type == real_device_type);
} else if (android::base::StartsWith(line, "serialno=")) {
std::string serial_no = line.substr(strlen("serialno="));
std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
has_serial_number = true;
serial_number_matched = (serial_no == real_serial_no);
}
}
return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
}
// Wipe the current A/B device, with a secure wipe of all the partitions in
// RECOVERY_WIPE.
static bool wipe_ab_device(size_t wipe_package_size) {
ui->SetBackground(RecoveryUI::ERASING);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
if (!check_wipe_package(wipe_package_size)) {
LOG(ERROR) << "Failed to verify wipe package";
return false;
}
std::string partition_list;
if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
return false;
}
std::vector<std::string> lines = android::base::Split(partition_list, "\n");
for (const std::string& line : lines) {
std::string partition = android::base::Trim(line);
// Ignore '#' comment or empty lines.
if (android::base::StartsWith(partition, "#") || partition.empty()) {
continue;
}
// Proceed anyway even if it fails to wipe some partition.
secure_wipe_partition(partition);
}
return true;
}
static void choose_recovery_file(Device* device) {
std::vector<std::string> entries;
if (has_cache) {
for (int i = 0; i < KEEP_LOG_COUNT; i++) {
auto add_to_entries = [&](const char* filename) {
std::string log_file(filename);
if (i > 0) {
log_file += "." + std::to_string(i);
}
if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
entries.push_back(std::move(log_file));
}
};
// Add LAST_LOG_FILE + LAST_LOG_FILE.x
add_to_entries(LAST_LOG_FILE);
// Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
add_to_entries(LAST_KMSG_FILE);
}
} else {
// If cache partition is not found, view /tmp/recovery.log instead.
if (access(TEMPORARY_LOG_FILE, R_OK) == -1) {
return;
} else {
entries.push_back(TEMPORARY_LOG_FILE);
}
}
entries.push_back("Back");
std::vector<const char*> menu_entries(entries.size());
std::transform(entries.cbegin(), entries.cend(), menu_entries.begin(),
[](const std::string& entry) { return entry.c_str(); });
menu_entries.push_back(nullptr);
const char* headers[] = { "Select file to view", nullptr };
int chosen_item = 0;
while (true) {
chosen_item = get_menu_selection(headers, menu_entries.data(), true, chosen_item, device);
if (entries[chosen_item] == "Back") break;
ui->ShowFile(entries[chosen_item].c_str());
}
}
static void run_graphics_test() {
// Switch to graphics screen.
ui->ShowText(false);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
sleep(1);
ui->SetBackground(RecoveryUI::ERROR);
sleep(1);
ui->SetBackground(RecoveryUI::NO_COMMAND);
sleep(1);
ui->SetBackground(RecoveryUI::ERASING);
sleep(1);
// Calling SetBackground() after SetStage() to trigger a redraw.
ui->SetStage(1, 3);
ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);