No Description

recovery.cpp 65KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  1. /*
  2. * Copyright (C) 2007 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <ctype.h>
  17. #include <dirent.h>
  18. #include <errno.h>
  19. #include <fcntl.h>
  20. #include <getopt.h>
  21. #include <inttypes.h>
  22. #include <limits.h>
  23. #include <linux/fs.h>
  24. #include <linux/input.h>
  25. #include <stdarg.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <sys/klog.h>
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <time.h>
  33. #include <unistd.h>
  34. #include <algorithm>
  35. #include <chrono>
  36. #include <memory>
  37. #include <string>
  38. #include <vector>
  39. #include <android-base/file.h>
  40. #include <android-base/logging.h>
  41. #include <android-base/parseint.h>
  42. #include <android-base/properties.h>
  43. #include <android-base/stringprintf.h>
  44. #include <android-base/strings.h>
  45. #include <android-base/unique_fd.h>
  46. #include <bootloader_message/bootloader_message.h>
  47. #include <cutils/android_reboot.h>
  48. #include <cutils/properties.h> /* for property_list */
  49. #include <health2/Health.h>
  50. #include <private/android_filesystem_config.h> /* for AID_SYSTEM */
  51. #include <private/android_logger.h> /* private pmsg functions */
  52. #include <selinux/android.h>
  53. #include <selinux/label.h>
  54. #include <selinux/selinux.h>
  55. #include <ziparchive/zip_archive.h>
  56. #include <volume_manager/VolumeManager.h>
  57. #include "adb_install.h"
  58. #include "common.h"
  59. #include "device.h"
  60. #include "fuse_sdcard_provider.h"
  61. #include "fuse_sideload.h"
  62. #include "install.h"
  63. #include "minadbd/minadbd.h"
  64. #include "minui/minui.h"
  65. #include "otautil/DirUtil.h"
  66. #include "otautil/error_code.h"
  67. #include "roots.h"
  68. #include "rotate_logs.h"
  69. #include "screen_ui.h"
  70. #include "stub_ui.h"
  71. #include "ui.h"
  72. #include "volclient.h"
  73. // For e2fsprogs
  74. extern "C" {
  75. const char* program_name = "fstools";
  76. }
  77. #include "recovery_cmds.h"
  78. struct recovery_cmd {
  79. const char *name;
  80. int (*main_func)(int argc, char **argv);
  81. };
  82. static const struct recovery_cmd recovery_cmds[] = {
  83. { "reboot", reboot_main },
  84. { "poweroff", reboot_main },
  85. { "gunzip", pigz_main },
  86. { "gzip", pigz_main },
  87. { "unzip", miniunz_main },
  88. { "zip", minizip_main },
  89. { "sh", mksh_main },
  90. { "awk", awk_main },
  91. /* Filesystem tools */
  92. { "e2fsdroid", e2fsdroid_main },
  93. { "e2fsdroid_static", e2fsdroid_main },
  94. { "sload.f2fs", fsck_f2fs_main },
  95. { "mke2fs", mke2fs_main },
  96. { "mke2fs_static", mke2fs_main },
  97. { "e2fsck", e2fsck_main },
  98. { "fsck.ext4", e2fsck_main },
  99. { "mkfs.ext4", mke2fs_main },
  100. { "resize2fs", resize2fs_main },
  101. { "tune2fs", tune2fs_main },
  102. { "mkfs.f2fs", mkfs_f2fs_main },
  103. { "fsck.f2fs", fsck_f2fs_main },
  104. { "fsck_msdos", fsck_msdos_main },
  105. { "mkfs.exfat", mkfs_exfat_main },
  106. { "fsck.exfat", fsck_exfat_main },
  107. { "fsck.ntfs", fsck_ntfs_main },
  108. { "mkfs.ntfs", mkfs_ntfs_main },
  109. { "mount.ntfs", mount_ntfs_main },
  110. { "sgdisk", sgdisk_main },
  111. { nullptr, nullptr },
  112. };
  113. struct recovery_cmd get_command(char* command) {
  114. int i;
  115. for (i = 0; recovery_cmds[i].name; i++) {
  116. if (strcmp(command, recovery_cmds[i].name) == 0) {
  117. break;
  118. }
  119. }
  120. return recovery_cmds[i];
  121. }
  122. using android::volmgr::VolumeInfo;
  123. using android::volmgr::VolumeManager;
  124. static const struct option OPTIONS[] = {
  125. { "update_package", required_argument, NULL, 'u' },
  126. { "retry_count", required_argument, NULL, 'n' },
  127. { "wipe_data", no_argument, NULL, 'w' },
  128. { "wipe_cache", no_argument, NULL, 'c' },
  129. { "show_text", no_argument, NULL, 't' },
  130. { "sideload", no_argument, NULL, 's' },
  131. { "sideload_auto_reboot", no_argument, NULL, 'a' },
  132. { "just_exit", no_argument, NULL, 'x' },
  133. { "locale", required_argument, NULL, 'l' },
  134. { "shutdown_after", no_argument, NULL, 'p' },
  135. { "reason", required_argument, NULL, 'r' },
  136. { "security", no_argument, NULL, 'e'},
  137. { "wipe_ab", no_argument, NULL, 0 },
  138. { "wipe_package_size", required_argument, NULL, 0 },
  139. { "prompt_and_wipe_data", no_argument, NULL, 0 },
  140. { NULL, 0, NULL, 0 },
  141. };
  142. // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
  143. static const std::vector<std::string> bootreason_blacklist {
  144. "kernel_panic",
  145. "Panic",
  146. };
  147. static const char *CACHE_LOG_DIR = "/cache/recovery";
  148. static const char *COMMAND_FILE = "/cache/recovery/command";
  149. static const char *LOG_FILE = "/cache/recovery/log";
  150. static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
  151. static const char *LOCALE_FILE = "/cache/recovery/last_locale";
  152. static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
  153. static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
  154. static const char *CACHE_ROOT = "/cache";
  155. static const char *DATA_ROOT = "/data";
  156. static const char* METADATA_ROOT = "/metadata";
  157. static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
  158. static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
  159. static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
  160. static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
  161. // We will try to apply the update package 5 times at most in case of an I/O error or
  162. // bspatch | imgpatch error.
  163. static const int RETRY_LIMIT = 4;
  164. static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
  165. // GmsCore enters recovery mode to install package when having enough battery
  166. // percentage. Normally, the threshold is 40% without charger and 20% with charger.
  167. // So we should check battery with a slightly lower limitation.
  168. static const int BATTERY_OK_PERCENTAGE = 20;
  169. static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
  170. static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
  171. static constexpr const char* DEFAULT_LOCALE = "en-US";
  172. // We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
  173. // into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
  174. static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
  175. static std::string locale;
  176. static bool has_cache = false;
  177. static const char* fbe_key_version = "/data/unencrypted/key/version";
  178. static const char* adb_keys_data = "/data/misc/adb/adb_keys";
  179. static const char* adb_keys_root = "/adb_keys";
  180. static const char* time_off_1_data = "/data/time/ats_1";
  181. static const char* time_off_2_data = "/data/system/time/ats_1";
  182. static const char* time_off_root = "/ats";
  183. RecoveryUI* ui = nullptr;
  184. bool modified_flash = false;
  185. std::string stage;
  186. const char* reason = nullptr;
  187. struct selabel_handle* sehandle;
  188. bool userdata_mountable = false;
  189. bool userdata_encrypted = true;
  190. /*
  191. * The recovery tool communicates with the main system through /cache files.
  192. * /cache/recovery/command - INPUT - command line for tool, one arg per line
  193. * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
  194. *
  195. * The arguments which may be supplied in the recovery.command file:
  196. * --update_package=path - verify install an OTA package file
  197. * --wipe_data - erase user data (and cache), then reboot
  198. * --prompt_and_wipe_data - prompt the user that data is corrupt,
  199. * with their consent erase user data (and cache), then reboot
  200. * --wipe_cache - wipe cache (but not user data), then reboot
  201. * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
  202. * --just_exit - do nothing; exit and reboot
  203. *
  204. * After completing, we remove /cache/recovery/command and reboot.
  205. * Arguments may also be supplied in the bootloader control block (BCB).
  206. * These important scenarios must be safely restartable at any point:
  207. *
  208. * FACTORY RESET
  209. * 1. user selects "factory reset"
  210. * 2. main system writes "--wipe_data" to /cache/recovery/command
  211. * 3. main system reboots into recovery
  212. * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
  213. * -- after this, rebooting will restart the erase --
  214. * 5. erase_volume() reformats /data
  215. * 6. erase_volume() reformats /cache
  216. * 7. finish_recovery() erases BCB
  217. * -- after this, rebooting will restart the main system --
  218. * 8. main() calls reboot() to boot main system
  219. *
  220. * OTA INSTALL
  221. * 1. main system downloads OTA package to /cache/some-filename.zip
  222. * 2. main system writes "--update_package=/cache/some-filename.zip"
  223. * 3. main system reboots into recovery
  224. * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
  225. * -- after this, rebooting will attempt to reinstall the update --
  226. * 5. install_package() attempts to install the update
  227. * NOTE: the package install must itself be restartable from any point
  228. * 6. finish_recovery() erases BCB
  229. * -- after this, rebooting will (try to) restart the main system --
  230. * 7. ** if install failed **
  231. * 7a. prompt_and_wait() shows an error icon and waits for the user
  232. * 7b. the user reboots (pulling the battery, etc) into the main system
  233. */
  234. // Open a given path, mounting partitions as necessary.
  235. FILE* fopen_path(const char* path, const char* mode) {
  236. if (ensure_path_mounted(path) != 0) {
  237. LOG(ERROR) << "Can't mount " << path;
  238. return nullptr;
  239. }
  240. // When writing, try to create the containing directory, if necessary. Use generous permissions,
  241. // the system (init.rc) will reset them.
  242. if (strchr("wa", mode[0])) {
  243. mkdir_recursively(path, 0777, true, sehandle);
  244. }
  245. return fopen(path, mode);
  246. }
  247. // close a file, log an error if the error indicator is set
  248. static void check_and_fclose(FILE *fp, const char *name) {
  249. fflush(fp);
  250. if (fsync(fileno(fp)) == -1) {
  251. PLOG(ERROR) << "Failed to fsync " << name;
  252. }
  253. if (ferror(fp)) {
  254. PLOG(ERROR) << "Error in " << name;
  255. }
  256. fclose(fp);
  257. }
  258. static bool file_copy(const char* src, const char* dst) {
  259. bool ret = false;
  260. char tmpdst[PATH_MAX];
  261. FILE* sfp;
  262. FILE* dfp;
  263. snprintf(tmpdst, sizeof(tmpdst), "%s.tmp", dst);
  264. sfp = fopen(src, "r");
  265. dfp = fopen(tmpdst, "w");
  266. if (sfp && dfp) {
  267. char buf[4096];
  268. size_t nr, nw;
  269. while ((nr = fread(buf, 1, sizeof(buf), sfp)) != 0) {
  270. nw = fwrite(buf, 1, nr, dfp);
  271. if (nr != nw)
  272. break;
  273. }
  274. ret = (!ferror(sfp) && !ferror(dfp));
  275. }
  276. if (dfp) fclose(dfp);
  277. if (sfp) fclose(sfp);
  278. if (ret) {
  279. ret = (rename(tmpdst, dst) == 0);
  280. }
  281. else {
  282. unlink(tmpdst);
  283. }
  284. return ret;
  285. }
  286. bool is_ro_debuggable() {
  287. return android::base::GetBoolProperty("ro.debuggable", false);
  288. }
  289. bool reboot(const std::string& command) {
  290. std::string cmd = command;
  291. if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
  292. cmd += ",quiescent";
  293. }
  294. return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
  295. }
  296. static void redirect_stdio(const char* filename) {
  297. int pipefd[2];
  298. if (pipe(pipefd) == -1) {
  299. PLOG(ERROR) << "pipe failed";
  300. // Fall back to traditional logging mode without timestamps.
  301. // If these fail, there's not really anywhere to complain...
  302. freopen(filename, "a", stdout); setbuf(stdout, NULL);
  303. freopen(filename, "a", stderr); setbuf(stderr, NULL);
  304. return;
  305. }
  306. pid_t pid = fork();
  307. if (pid == -1) {
  308. PLOG(ERROR) << "fork failed";
  309. // Fall back to traditional logging mode without timestamps.
  310. // If these fail, there's not really anywhere to complain...
  311. freopen(filename, "a", stdout); setbuf(stdout, NULL);
  312. freopen(filename, "a", stderr); setbuf(stderr, NULL);
  313. return;
  314. }
  315. if (pid == 0) {
  316. /// Close the unused write end.
  317. close(pipefd[1]);
  318. auto start = std::chrono::steady_clock::now();
  319. // Child logger to actually write to the log file.
  320. FILE* log_fp = fopen(filename, "ae");
  321. if (log_fp == nullptr) {
  322. PLOG(ERROR) << "fopen \"" << filename << "\" failed";
  323. close(pipefd[0]);
  324. _exit(EXIT_FAILURE);
  325. }
  326. FILE* pipe_fp = fdopen(pipefd[0], "r");
  327. if (pipe_fp == nullptr) {
  328. PLOG(ERROR) << "fdopen failed";
  329. check_and_fclose(log_fp, filename);
  330. close(pipefd[0]);
  331. _exit(EXIT_FAILURE);
  332. }
  333. char* line = nullptr;
  334. size_t len = 0;
  335. while (getline(&line, &len, pipe_fp) != -1) {
  336. auto now = std::chrono::steady_clock::now();
  337. double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
  338. now - start).count();
  339. if (line[0] == '\n') {
  340. fprintf(log_fp, "[%12.6lf]\n", duration);
  341. } else {
  342. fprintf(log_fp, "[%12.6lf] %s", duration, line);
  343. }
  344. fflush(log_fp);
  345. }
  346. PLOG(ERROR) << "getline failed";
  347. free(line);
  348. check_and_fclose(log_fp, filename);
  349. close(pipefd[0]);
  350. _exit(EXIT_FAILURE);
  351. } else {
  352. // Redirect stdout/stderr to the logger process.
  353. // Close the unused read end.
  354. close(pipefd[0]);
  355. setbuf(stdout, nullptr);
  356. setbuf(stderr, nullptr);
  357. if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
  358. PLOG(ERROR) << "dup2 stdout failed";
  359. }
  360. if (dup2(pipefd[1], STDERR_FILENO) == -1) {
  361. PLOG(ERROR) << "dup2 stderr failed";
  362. }
  363. close(pipefd[1]);
  364. }
  365. }
  366. // command line args come from, in decreasing precedence:
  367. // - the actual command line
  368. // - the bootloader control block (one per line, after "recovery")
  369. // - the contents of COMMAND_FILE (one per line)
  370. static std::vector<std::string> get_args(const int argc, char** const argv) {
  371. CHECK_GT(argc, 0);
  372. bootloader_message boot = {};
  373. std::string err;
  374. if (!read_bootloader_message(&boot, &err)) {
  375. LOG(ERROR) << err;
  376. // If fails, leave a zeroed bootloader_message.
  377. boot = {};
  378. }
  379. stage = std::string(boot.stage);
  380. if (boot.command[0] != 0) {
  381. std::string boot_command = std::string(boot.command, sizeof(boot.command));
  382. LOG(INFO) << "Boot command: " << boot_command;
  383. }
  384. if (boot.status[0] != 0) {
  385. std::string boot_status = std::string(boot.status, sizeof(boot.status));
  386. LOG(INFO) << "Boot status: " << boot_status;
  387. }
  388. std::vector<std::string> args(argv, argv + argc);
  389. // --- if arguments weren't supplied, look in the bootloader control block
  390. if (args.size() == 1) {
  391. boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
  392. std::string boot_recovery(boot.recovery);
  393. std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
  394. if (!tokens.empty() && tokens[0] == "recovery") {
  395. for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
  396. // Skip empty and '\0'-filled tokens.
  397. if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
  398. }
  399. LOG(INFO) << "Got " << args.size() << " arguments from boot message";
  400. } else if (boot.recovery[0] != 0) {
  401. LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
  402. }
  403. }
  404. // --- if that doesn't work, try the command file (if we have /cache).
  405. if (args.size() == 1 && has_cache) {
  406. std::string content;
  407. if (ensure_path_mounted(COMMAND_FILE) == 0 &&
  408. android::base::ReadFileToString(COMMAND_FILE, &content)) {
  409. std::vector<std::string> tokens = android::base::Split(content, "\n");
  410. // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
  411. // COMMAND_FILE doesn't use filename as the first argument).
  412. for (auto it = tokens.begin(); it != tokens.end(); it++) {
  413. // Skip empty and '\0'-filled tokens.
  414. if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
  415. }
  416. LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
  417. }
  418. }
  419. // Write the arguments (excluding the filename in args[0]) back into the
  420. // bootloader control block. So the device will always boot into recovery to
  421. // finish the pending work, until finish_recovery() is called.
  422. std::vector<std::string> options(args.cbegin() + 1, args.cend());
  423. if (!update_bootloader_message(options, &err)) {
  424. LOG(ERROR) << "Failed to set BCB message: " << err;
  425. }
  426. return args;
  427. }
  428. // Set the BCB to reboot back into recovery (it won't resume the install from
  429. // sdcard though).
  430. static void set_sdcard_update_bootloader_message() {
  431. std::vector<std::string> options;
  432. std::string err;
  433. if (!update_bootloader_message(options, &err)) {
  434. LOG(ERROR) << "Failed to set BCB message: " << err;
  435. }
  436. }
  437. // Read from kernel log into buffer and write out to file.
  438. static void save_kernel_log(const char* destination) {
  439. int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
  440. if (klog_buf_len <= 0) {
  441. PLOG(ERROR) << "Error getting klog size";
  442. return;
  443. }
  444. std::string buffer(klog_buf_len, 0);
  445. int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
  446. if (n == -1) {
  447. PLOG(ERROR) << "Error in reading klog";
  448. return;
  449. }
  450. buffer.resize(n);
  451. android::base::WriteStringToFile(buffer, destination);
  452. }
  453. // write content to the current pmsg session.
  454. static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
  455. return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
  456. filename, buf, len);
  457. }
  458. static void copy_log_file_to_pmsg(const char* source, const char* destination) {
  459. std::string content;
  460. android::base::ReadFileToString(source, &content);
  461. __pmsg_write(destination, content.c_str(), content.length());
  462. }
  463. // How much of the temp log we have copied to the copy in cache.
  464. static off_t tmplog_offset = 0;
  465. static void copy_log_file(const char* source, const char* destination, bool append) {
  466. FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
  467. if (dest_fp == nullptr) {
  468. PLOG(ERROR) << "Can't open " << destination;
  469. } else {
  470. FILE* source_fp = fopen(source, "re");
  471. if (source_fp != nullptr) {
  472. if (append) {
  473. fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
  474. }
  475. char buf[4096];
  476. size_t bytes;
  477. while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
  478. fwrite(buf, 1, bytes, dest_fp);
  479. }
  480. if (append) {
  481. tmplog_offset = ftello(source_fp);
  482. }
  483. check_and_fclose(source_fp, source);
  484. }
  485. check_and_fclose(dest_fp, destination);
  486. }
  487. }
  488. static void copy_logs() {
  489. // We only rotate and record the log of the current session if there are
  490. // actual attempts to modify the flash, such as wipes, installs from BCB
  491. // or menu selections. This is to avoid unnecessary rotation (and
  492. // possible deletion) of log files, if it does not do anything loggable.
  493. if (!modified_flash) {
  494. return;
  495. }
  496. // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
  497. copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
  498. copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
  499. // We can do nothing for now if there's no /cache partition.
  500. if (!has_cache) {
  501. return;
  502. }
  503. ensure_path_mounted(LAST_LOG_FILE);
  504. ensure_path_mounted(LAST_KMSG_FILE);
  505. rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
  506. // Copy logs to cache so the system can find out what happened.
  507. copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
  508. copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
  509. copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
  510. save_kernel_log(LAST_KMSG_FILE);
  511. chmod(LOG_FILE, 0600);
  512. chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
  513. chmod(LAST_KMSG_FILE, 0600);
  514. chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
  515. chmod(LAST_LOG_FILE, 0640);
  516. chmod(LAST_INSTALL_FILE, 0644);
  517. sync();
  518. }
  519. // Clear the recovery command and prepare to boot a (hopefully working) system,
  520. // copy our log file to cache as well (for the system to read). This function is
  521. // idempotent: call it as many times as you like.
  522. static void finish_recovery() {
  523. // Save the locale to cache, so if recovery is next started up without a '--locale' argument
  524. // (e.g., directly from the bootloader) it will use the last-known locale.
  525. if (!locale.empty() && has_cache) {
  526. LOG(INFO) << "Saving locale \"" << locale << "\"";
  527. if (ensure_path_mounted(LOCALE_FILE) != 0) {
  528. LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
  529. } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
  530. PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
  531. }
  532. }
  533. copy_logs();
  534. // Reset to normal system boot so recovery won't cycle indefinitely.
  535. std::string err;
  536. if (!clear_bootloader_message(&err)) {
  537. LOG(ERROR) << "Failed to clear BCB message: " << err;
  538. }
  539. // Remove the command file, so recovery won't repeat indefinitely.
  540. if (has_cache) {
  541. if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
  542. LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
  543. }
  544. ensure_path_unmounted(CACHE_ROOT);
  545. }
  546. sync(); // For good measure.
  547. }
  548. struct saved_log_file {
  549. std::string name;
  550. struct stat sb;
  551. std::string data;
  552. };
  553. static bool erase_volume(const char* volume) {
  554. bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
  555. bool is_data = (strcmp(volume, DATA_ROOT) == 0);
  556. std::vector<saved_log_file> log_files;
  557. if (is_cache) {
  558. // If we're reformatting /cache, we load any past logs
  559. // (i.e. "/cache/recovery/last_*") and the current log
  560. // ("/cache/recovery/log") into memory, so we can restore them after
  561. // the reformat.
  562. ensure_path_mounted(volume);
  563. struct dirent* de;
  564. std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
  565. if (d) {
  566. while ((de = readdir(d.get())) != nullptr) {
  567. if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
  568. std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
  569. struct stat sb;
  570. if (stat(path.c_str(), &sb) == 0) {
  571. // truncate files to 512kb
  572. if (sb.st_size > (1 << 19)) {
  573. sb.st_size = 1 << 19;
  574. }
  575. std::string data(sb.st_size, '\0');
  576. FILE* f = fopen(path.c_str(), "rbe");
  577. fread(&data[0], 1, data.size(), f);
  578. fclose(f);
  579. log_files.emplace_back(saved_log_file{ path, sb, data });
  580. }
  581. }
  582. }
  583. } else {
  584. if (errno != ENOENT) {
  585. PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
  586. }
  587. }
  588. }
  589. ui->Print("Formatting %s...\n", volume);
  590. ui->SetBackground(RecoveryUI::ERASING);
  591. ui->SetProgressType(RecoveryUI::INDETERMINATE);
  592. ensure_path_unmounted(volume);
  593. int result;
  594. if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
  595. // Create convert_fbe breadcrumb file to signal to init
  596. // to convert to file based encryption, not full disk encryption
  597. if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
  598. ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
  599. return true;
  600. }
  601. FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
  602. if (!f) {
  603. ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
  604. return true;
  605. }
  606. fclose(f);
  607. result = format_volume(volume, CONVERT_FBE_DIR);
  608. remove(CONVERT_FBE_FILE);
  609. rmdir(CONVERT_FBE_DIR);
  610. } else {
  611. result = format_volume(volume);
  612. }
  613. if (is_cache) {
  614. // Re-create the log dir and write back the log entries.
  615. if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
  616. mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
  617. for (const auto& log : log_files) {
  618. if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
  619. log.sb.st_gid)) {
  620. PLOG(ERROR) << "Failed to write to " << log.name;
  621. }
  622. }
  623. } else {
  624. PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
  625. }
  626. // Any part of the log we'd copied to cache is now gone.
  627. // Reset the pointer so we copy from the beginning of the temp
  628. // log.
  629. tmplog_offset = 0;
  630. copy_logs();
  631. }
  632. return (result == 0);
  633. }
  634. // Display a menu with the specified 'headers' and 'items'. Device specific HandleMenuKey() may
  635. // return a positive number beyond the given range. Caller sets 'menu_only' to true to ensure only
  636. // a menu item gets selected. 'initial_selection' controls the initial cursor location. Returns the
  637. // (non-negative) chosen item number, or -1 if timed out waiting for input.
  638. int get_menu_selection(bool menu_is_main,
  639. menu_type_t menu_type,
  640. const char* const* headers,
  641. const MenuItemVector& menu_items,
  642. bool menu_only,
  643. int initial_selection, Device* device) {
  644. // Throw away keys pressed previously, so user doesn't accidentally trigger menu items.
  645. ui->FlushKeys();
  646. ui->StartMenu(menu_is_main, menu_type, headers, menu_items, initial_selection);
  647. int selected = initial_selection;
  648. int chosen_item = -1;
  649. while (chosen_item < 0) {
  650. RecoveryUI::InputEvent evt = ui->WaitInputEvent();
  651. if (evt.type() == RecoveryUI::EVENT_TYPE_NONE) { // WaitKey() timed out.
  652. if (ui->WasTextEverVisible()) {
  653. continue;
  654. } else {
  655. LOG(INFO) << "Timed out waiting for key input; rebooting.";
  656. ui->EndMenu();
  657. return -1;
  658. }
  659. }
  660. int action = Device::kNoAction;
  661. if (evt.type() == RecoveryUI::EVENT_TYPE_TOUCH) {
  662. int touch_sel = ui->SelectMenu(evt.pos());
  663. if (touch_sel < 0) {
  664. action = touch_sel;
  665. }
  666. else {
  667. action = Device::kInvokeItem;
  668. selected = touch_sel;
  669. }
  670. }
  671. else {
  672. bool visible = ui->IsTextVisible();
  673. action = device->HandleMenuKey(evt.key(), visible);
  674. }
  675. if (action < 0) {
  676. switch (action) {
  677. case Device::kHighlightUp:
  678. selected = ui->SelectMenu(--selected);
  679. break;
  680. case Device::kHighlightDown:
  681. selected = ui->SelectMenu(++selected);
  682. break;
  683. case Device::kInvokeItem:
  684. chosen_item = selected;
  685. if (chosen_item < 0) {
  686. chosen_item = Device::kGoBack;
  687. }
  688. break;
  689. case Device::kNoAction:
  690. break;
  691. case Device::kGoBack:
  692. chosen_item = Device::kGoBack;
  693. break;
  694. case Device::kGoHome:
  695. chosen_item = Device::kGoHome;
  696. break;
  697. case Device::kRefresh:
  698. chosen_item = Device::kRefresh;
  699. break;
  700. }
  701. } else if (!menu_only) {
  702. chosen_item = action;
  703. }
  704. if (chosen_item == Device::kGoBack ||
  705. chosen_item == Device::kGoHome ||
  706. chosen_item == Device::kRefresh) {
  707. break;
  708. }
  709. }
  710. ui->EndMenu();
  711. if (chosen_item == Device::kGoHome) {
  712. device->GoHome();
  713. }
  714. return chosen_item;
  715. }
  716. // Returns the selected filename, or an empty string.
  717. static std::string browse_directory(const std::string& path, Device* device) {
  718. std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
  719. if (!d) {
  720. PLOG(ERROR) << "error opening " << path;
  721. return "";
  722. }
  723. std::vector<std::string> dirs;
  724. std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
  725. dirent* de;
  726. while ((de = readdir(d.get())) != nullptr) {
  727. std::string name(de->d_name);
  728. if (de->d_type == DT_DIR) {
  729. // Skip "." and ".." entries.
  730. if (name == "." || name == "..") continue;
  731. dirs.push_back(name + "/");
  732. } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
  733. zips.push_back(name);
  734. }
  735. }
  736. std::sort(dirs.begin(), dirs.end());
  737. std::sort(zips.begin(), zips.end());
  738. // Append dirs to the zips list.
  739. zips.insert(zips.end(), dirs.begin(), dirs.end());
  740. MenuItemVector items;
  741. for (size_t i = 0; i < zips.size(); i++) {
  742. items.push_back(MenuItem(zips[i]));
  743. }
  744. const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
  745. int chosen_item = 0;
  746. while (true) {
  747. chosen_item = get_menu_selection(false, MT_LIST, headers, items,
  748. true, chosen_item, device);
  749. if (chosen_item == Device::kGoHome) {
  750. return "@";
  751. }
  752. if (chosen_item == Device::kGoBack || chosen_item == 0) {
  753. // Go up but continue browsing (if the caller is browse_directory).
  754. return "";
  755. }
  756. if (chosen_item == Device::kRefresh) {
  757. return "@refresh";
  758. }
  759. const std::string& item = zips[chosen_item];
  760. std::string new_path = path + "/" + item;
  761. if (new_path.back() == '/') {
  762. // Recurse down into a subdirectory.
  763. new_path.pop_back();
  764. std::string result = browse_directory(new_path, device);
  765. if (!result.empty()) return result;
  766. } else {
  767. // Selected a zip file: return the path to the caller.
  768. return new_path;
  769. }
  770. }
  771. // Unreachable.
  772. }
  773. static bool yes_no(Device* device, const char* question1, const char* question2) {
  774. const char* headers[] = { question1, question2, NULL };
  775. const MenuItemVector items = {
  776. MenuItem(" No"),
  777. MenuItem(" Yes"),
  778. };
  779. int chosen_item;
  780. do {
  781. chosen_item = get_menu_selection(false, MT_LIST, headers, items,
  782. true, 0, device);
  783. }
  784. while (chosen_item == Device::kRefresh);
  785. return (chosen_item == 1);
  786. }
  787. static bool ask_to_continue_unverified_install(Device* device) {
  788. #ifdef RELEASE_BUILD
  789. return false;
  790. #else
  791. ui->SetProgressType(RecoveryUI::EMPTY);
  792. return yes_no(device, "Signature verification failed", "Install anyway?");
  793. #endif
  794. }
  795. static bool ask_to_wipe_data(Device* device) {
  796. return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
  797. }
  798. // Return true on success.
  799. static bool wipe_data(Device* device) {
  800. modified_flash = true;
  801. ui->Print("\n-- Wiping data...\n");
  802. bool success = device->PreWipeData();
  803. if (success) {
  804. success &= erase_volume(DATA_ROOT);
  805. if (has_cache) {
  806. success &= erase_volume(CACHE_ROOT);
  807. }
  808. if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
  809. success &= erase_volume(METADATA_ROOT);
  810. }
  811. }
  812. if (success) {
  813. success &= device->PostWipeData();
  814. }
  815. ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
  816. return success;
  817. }
  818. static bool prompt_and_wipe_data(Device* device) {
  819. // Use a single string and let ScreenRecoveryUI handles the wrapping.
  820. const char* const headers[] = {
  821. "Can't load Android system. Your data may be corrupt. "
  822. "If you continue to get this message, you may need to "
  823. "perform a factory data reset and erase all user data "
  824. "stored on this device.",
  825. nullptr
  826. };
  827. const MenuItemVector items = {
  828. MenuItem("Try again"),
  829. MenuItem("Factory data reset"),
  830. };
  831. for (;;) {
  832. int chosen_item = get_menu_selection(false, MT_LIST, headers, items,
  833. true, 0, device);
  834. if (chosen_item != 1) {
  835. return true; // Just reboot, no wipe; not a failure, user asked for it
  836. }
  837. if (ask_to_wipe_data(device)) {
  838. return wipe_data(device);
  839. }
  840. }
  841. }
  842. // Return true on success.
  843. static bool wipe_cache(bool should_confirm, Device* device) {
  844. if (!has_cache) {
  845. ui->Print("No /cache partition found.\n");
  846. return false;
  847. }
  848. if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
  849. return false;
  850. }
  851. modified_flash = true;
  852. ui->Print("\n-- Wiping cache...\n");
  853. bool success = erase_volume("/cache");
  854. ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
  855. return success;
  856. }
  857. static bool ask_to_wipe_system(Device* device) {
  858. return yes_no(device, "Wipe system?", " THIS CAN NOT BE UNDONE!");
  859. }
  860. // Return true on success.
  861. static bool wipe_system() {
  862. modified_flash = true;
  863. ui->Print("\n-- Wiping system...\n");
  864. bool success = erase_volume("/system");
  865. ui->Print("System wipe %s.\n", success ? "complete" : "failed");
  866. return success;
  867. }
  868. // Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
  869. // BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
  870. static bool secure_wipe_partition(const std::string& partition) {
  871. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
  872. if (fd == -1) {
  873. PLOG(ERROR) << "Failed to open \"" << partition << "\"";
  874. return false;
  875. }
  876. uint64_t range[2] = { 0, 0 };
  877. if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
  878. PLOG(ERROR) << "Failed to get partition size";
  879. return false;
  880. }
  881. LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
  882. LOG(INFO) << " Trying BLKSECDISCARD...";
  883. if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
  884. PLOG(WARNING) << " Failed";
  885. // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
  886. unsigned int zeroes;
  887. if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
  888. LOG(INFO) << " Trying BLKDISCARD...";
  889. if (ioctl(fd, BLKDISCARD, &range) == -1) {
  890. PLOG(ERROR) << " Failed";
  891. return false;
  892. }
  893. } else {
  894. LOG(INFO) << " Trying BLKZEROOUT...";
  895. if (ioctl(fd, BLKZEROOUT, &range) == -1) {
  896. PLOG(ERROR) << " Failed";
  897. return false;
  898. }
  899. }
  900. }
  901. LOG(INFO) << " Done";
  902. return true;
  903. }
  904. // Check if the wipe package matches expectation:
  905. // 1. verify the package.
  906. // 2. check metadata (ota-type, pre-device and serial number if having one).
  907. static bool check_wipe_package(size_t wipe_package_size) {
  908. if (wipe_package_size == 0) {
  909. LOG(ERROR) << "wipe_package_size is zero";
  910. return false;
  911. }
  912. std::string wipe_package;
  913. std::string err_str;
  914. if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
  915. PLOG(ERROR) << "Failed to read wipe package";
  916. return false;
  917. }
  918. if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
  919. wipe_package.size())) {
  920. LOG(ERROR) << "Failed to verify package";
  921. return false;
  922. }
  923. // Extract metadata
  924. ZipArchiveHandle zip;
  925. int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
  926. "wipe_package", &zip);
  927. if (err != 0) {
  928. LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
  929. return false;
  930. }
  931. std::string metadata;
  932. if (!read_metadata_from_package(zip, &metadata)) {
  933. CloseArchive(zip);
  934. return false;
  935. }
  936. CloseArchive(zip);
  937. // Check metadata
  938. std::vector<std::string> lines = android::base::Split(metadata, "\n");
  939. bool ota_type_matched = false;
  940. bool device_type_matched = false;
  941. bool has_serial_number = false;
  942. bool serial_number_matched = false;
  943. for (const auto& line : lines) {
  944. if (line == "ota-type=BRICK") {
  945. ota_type_matched = true;
  946. } else if (android::base::StartsWith(line, "pre-device=")) {
  947. std::string device_type = line.substr(strlen("pre-device="));
  948. std::string real_device_type = android::base::GetProperty("ro.build.product", "");
  949. device_type_matched = (device_type == real_device_type);
  950. } else if (android::base::StartsWith(line, "serialno=")) {
  951. std::string serial_no = line.substr(strlen("serialno="));
  952. std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
  953. has_serial_number = true;
  954. serial_number_matched = (serial_no == real_serial_no);
  955. }
  956. }
  957. return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
  958. }
  959. // Wipe the current A/B device, with a secure wipe of all the partitions in
  960. // RECOVERY_WIPE.
  961. static bool wipe_ab_device(size_t wipe_package_size) {
  962. ui->SetBackground(RecoveryUI::ERASING);
  963. ui->SetProgressType(RecoveryUI::INDETERMINATE);
  964. if (!check_wipe_package(wipe_package_size)) {
  965. LOG(ERROR) << "Failed to verify wipe package";
  966. return false;
  967. }
  968. std::string partition_list;
  969. if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
  970. LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
  971. return false;
  972. }
  973. std::vector<std::string> lines = android::base::Split(partition_list, "\n");
  974. for (const std::string& line : lines) {
  975. std::string partition = android::base::Trim(line);
  976. // Ignore '#' comment or empty lines.
  977. if (android::base::StartsWith(partition, "#") || partition.empty()) {
  978. continue;
  979. }
  980. // Proceed anyway even if it fails to wipe some partition.
  981. secure_wipe_partition(partition);
  982. }
  983. return true;
  984. }
  985. static int choose_recovery_file(Device* device) {
  986. std::vector<std::string> entries;
  987. if (access(TEMPORARY_LOG_FILE, R_OK) != -1) {
  988. entries.push_back(TEMPORARY_LOG_FILE);
  989. }
  990. if (has_cache) {
  991. for (int i = 0; i < KEEP_LOG_COUNT; i++) {
  992. auto add_to_entries = [&](const char* filename) {
  993. std::string log_file(filename);
  994. if (i > 0) {
  995. log_file += "." + std::to_string(i);
  996. }
  997. if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
  998. entries.push_back(std::move(log_file));
  999. }
  1000. };
  1001. // Add LAST_LOG_FILE + LAST_LOG_FILE.x
  1002. add_to_entries(LAST_LOG_FILE);
  1003. // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
  1004. add_to_entries(LAST_KMSG_FILE);
  1005. }
  1006. }
  1007. if (entries.empty()) {
  1008. // Should never happen
  1009. return Device::kNoAction;
  1010. }
  1011. MenuItemVector items(entries.size());
  1012. std::transform(entries.cbegin(), entries.cend(), items.begin(),
  1013. [](const std::string& entry) { return MenuItem(entry.c_str()); });
  1014. const char* headers[] = { "Select file to view", nullptr };
  1015. int chosen_item = 0;
  1016. while (true) {
  1017. chosen_item = get_menu_selection(false, MT_LIST, headers, items,
  1018. true, chosen_item, device);
  1019. if (chosen_item == Device::kGoHome ||
  1020. chosen_item == Device::kGoBack) {
  1021. break;
  1022. }
  1023. int key = ui->ShowFile(entries[chosen_item].c_str());
  1024. if (key == KEY_HOME || key == KEY_HOMEPAGE) {
  1025. chosen_item = Device::kGoHome;
  1026. break;
  1027. }
  1028. }
  1029. return chosen_item;
  1030. }
  1031. static void run_graphics_test() {
  1032. ui->SetBackground(RecoveryUI::ERROR);
  1033. ui->Redraw();
  1034. sleep(1);
  1035. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  1036. ui->Redraw();
  1037. sleep(1);
  1038. ui->SetBackground(RecoveryUI::ERASING);
  1039. ui->Redraw();
  1040. sleep(1);
  1041. ui->SetStage(1, 3);
  1042. ui->Redraw();
  1043. sleep(1);
  1044. ui->SetStage(2, 3);
  1045. ui->Redraw();
  1046. sleep(1);
  1047. ui->SetStage(3, 3);
  1048. ui->Redraw();
  1049. sleep(1);
  1050. ui->SetStage(-1, -1);
  1051. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  1052. ui->SetProgressType(RecoveryUI::DETERMINATE);
  1053. ui->ShowProgress(1.0, 10.0);
  1054. float fraction = 0.0;
  1055. for (size_t i = 0; i < 100; ++i) {
  1056. fraction += .01;
  1057. ui->SetProgress(fraction);
  1058. usleep(100000);
  1059. }
  1060. }
  1061. static int apply_from_storage(Device* device, VolumeInfo& vi, bool* wipe_cache) {
  1062. modified_flash = true;
  1063. int status;
  1064. if (!VolumeManager::Instance()->volumeMount(vi.mId)) {
  1065. return INSTALL_ERROR;
  1066. }
  1067. std::string path;
  1068. do {
  1069. path = browse_directory(vi.mPath, device);
  1070. if (path == "@") {
  1071. return INSTALL_NONE;
  1072. }
  1073. }
  1074. while (path == "@refresh");
  1075. if (path.empty()) {
  1076. ui->Print("\n-- No package file selected.\n");
  1077. VolumeManager::Instance()->volumeUnmount(vi.mId);
  1078. return INSTALL_NONE;
  1079. }
  1080. ui->Print("\n-- Install %s ...\n", path.c_str());
  1081. set_sdcard_update_bootloader_message();
  1082. void* token = start_sdcard_fuse(path.c_str());
  1083. if (!token) {
  1084. LOG(ERROR) << "Failed to start FUSE for sdcard install";
  1085. return INSTALL_ERROR;
  1086. }
  1087. VolumeManager::Instance()->volumeUnmount(vi.mId, true);
  1088. status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
  1089. TEMPORARY_INSTALL_FILE, false, 0/*retry_count*/,
  1090. true/*verify*/);
  1091. if (status == INSTALL_UNVERIFIED &&
  1092. ask_to_continue_unverified_install(device)) {
  1093. status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
  1094. TEMPORARY_INSTALL_FILE, false, 0/*retry_count*/,
  1095. false/*verify*/);
  1096. }
  1097. finish_sdcard_fuse(token);
  1098. return status;
  1099. }
  1100. static int
  1101. show_apply_update_menu(Device* device, bool* wipe_cache) {
  1102. MenuItemVector items;
  1103. static const char* headers[] = { "Apply update", nullptr };
  1104. refresh:
  1105. items.clear();
  1106. items.push_back(MenuItem("Apply from ADB")); // Index 0
  1107. std::vector<VolumeInfo> volumes;
  1108. VolumeManager::Instance()->getVolumeInfo(volumes);
  1109. for (auto& vol : volumes) {
  1110. if (vol.mLabel == "emulated") {
  1111. if (!userdata_mountable || userdata_encrypted) {
  1112. continue;
  1113. }
  1114. }
  1115. items.push_back(MenuItem("Choose from " + vol.mLabel));
  1116. }
  1117. int status = INSTALL_ERROR;
  1118. int chosen = get_menu_selection(false, MT_LIST, headers, items,
  1119. false, 0, device);
  1120. if (chosen == Device::kRefresh) {
  1121. goto refresh;
  1122. }
  1123. if (chosen == Device::kGoBack ||
  1124. chosen == Device::kGoHome) {
  1125. return INSTALL_NONE;
  1126. }
  1127. if (chosen == 0) {
  1128. static const char* s_headers[] = { "ADB Sideload", nullptr };
  1129. static const MenuItemVector s_items = { MenuItem("Cancel sideload") };
  1130. sideload_start();
  1131. int item = get_menu_selection(false, MT_LIST, s_headers, s_items,
  1132. false, 0, device);
  1133. if (item == Device::kRefresh) {
  1134. sideload_wait(false);
  1135. status = sideload_install(wipe_cache, TEMPORARY_INSTALL_FILE, true);
  1136. if (status == INSTALL_UNVERIFIED &&
  1137. ask_to_continue_unverified_install(device)) {
  1138. status = sideload_install(wipe_cache, TEMPORARY_INSTALL_FILE, false);
  1139. }
  1140. }
  1141. else {
  1142. sideload_wait(true);
  1143. status = INSTALL_NONE;
  1144. }
  1145. sideload_stop();
  1146. }
  1147. else {
  1148. status = apply_from_storage(device, volumes[chosen - 1], wipe_cache);
  1149. }
  1150. return status;
  1151. }
  1152. // Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
  1153. // which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
  1154. static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
  1155. for (;;) {
  1156. finish_recovery();
  1157. switch (status) {
  1158. case INSTALL_SUCCESS:
  1159. case INSTALL_NONE:
  1160. ui->SetBackground(RecoveryUI::NO_COMMAND);
  1161. break;
  1162. case INSTALL_ERROR:
  1163. case INSTALL_CORRUPT:
  1164. ui->SetBackground(RecoveryUI::ERROR);
  1165. break;
  1166. }
  1167. ui->SetProgressType(RecoveryUI::EMPTY);
  1168. int chosen_item = get_menu_selection(device->IsMainMenu(),
  1169. device->GetMenuType(),
  1170. nullptr,
  1171. device->GetMenuItems(),
  1172. false, 0, device);
  1173. if (chosen_item == Device::kGoBack ||
  1174. chosen_item == Device::kGoHome) {
  1175. device->GoHome();
  1176. continue;
  1177. }
  1178. if (chosen_item == Device::kRefresh) {
  1179. continue;
  1180. }
  1181. // Device-specific code may take some action here. It may return one of the core actions
  1182. // handled in the switch statement below.
  1183. Device::BuiltinAction chosen_action =
  1184. (chosen_item == -1) ? Device::REBOOT : device->InvokeMenuItem(chosen_item);
  1185. bool should_wipe_cache = false;
  1186. switch (chosen_action) {
  1187. case Device::NO_ACTION:
  1188. case Device::WIPE_MENU:
  1189. case Device::ADVANCED_MENU:
  1190. break;
  1191. case Device::REBOOT:
  1192. case Device::SHUTDOWN:
  1193. case Device::REBOOT_BOOTLOADER:
  1194. return chosen_action;
  1195. case Device::WIPE_DATA:
  1196. if (ui->IsTextVisible()) {
  1197. if (ask_to_wipe_data(device)) {
  1198. wipe_data(device);
  1199. }
  1200. } else {
  1201. wipe_data(device);
  1202. return Device::NO_ACTION;
  1203. }
  1204. break;
  1205. case Device::WIPE_CACHE:
  1206. wipe_cache(ui->IsTextVisible(), device);
  1207. if (!ui->IsTextVisible()) return Device::NO_ACTION;
  1208. break;
  1209. case Device::WIPE_SYSTEM:
  1210. if (ui->IsTextVisible()) {
  1211. if (ask_to_wipe_system(device)) {
  1212. wipe_system();
  1213. }
  1214. } else {
  1215. wipe_system();
  1216. return Device::NO_ACTION;
  1217. }
  1218. break;
  1219. case Device::APPLY_UPDATE:
  1220. {
  1221. status = show_apply_update_menu(device, &should_wipe_cache);
  1222. if (status != INSTALL_NONE) {
  1223. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  1224. if (!wipe_cache(false, device)) {
  1225. status = INSTALL_ERROR;
  1226. }
  1227. }
  1228. if (status != INSTALL_SUCCESS) {
  1229. ui->SetProgressType(RecoveryUI::EMPTY);
  1230. ui->SetBackground(RecoveryUI::ERROR);
  1231. ui->Print("Installation aborted.\n");
  1232. ui->Redraw();
  1233. copy_logs();
  1234. ui->FlushKeys();
  1235. ui->WaitInputEvent();
  1236. } else if (!ui->IsTextVisible()) {
  1237. return Device::NO_ACTION; // reboot if logs aren't visible
  1238. } else {
  1239. ui->Print("\nInstall complete.\n");
  1240. }
  1241. }
  1242. }
  1243. break;
  1244. case Device::VIEW_RECOVERY_LOGS:
  1245. choose_recovery_file(device);
  1246. if (chosen_item == Device::kGoHome) {
  1247. device->GoHome();
  1248. }
  1249. break;
  1250. case Device::RUN_GRAPHICS_TEST:
  1251. run_graphics_test();
  1252. break;
  1253. case Device::RUN_LOCALE_TEST: {
  1254. ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
  1255. screen_ui->CheckBackgroundTextImages(locale);
  1256. break;
  1257. }
  1258. case Device::MOUNT_SYSTEM:
  1259. // For a system image built with the root directory (i.e. system_root_image == "true"), we
  1260. // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
  1261. // work (the symlink is created through the build system). (Bug: 22855115)
  1262. if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
  1263. if (ensure_path_mounted_at("/", "/system_root") != -1) {
  1264. ui->Print("Mounted /system.\n");
  1265. }
  1266. } else {
  1267. if (ensure_path_mounted("/system") != -1) {
  1268. ui->Print("Mounted /system.\n");
  1269. }
  1270. }
  1271. break;
  1272. }
  1273. }
  1274. }
  1275. static void print_property(const char* key, const char* name, void* /* cookie */) {
  1276. printf("%s=%s\n", key, name);
  1277. }
  1278. static std::string load_locale_from_cache() {
  1279. if (ensure_path_mounted(LOCALE_FILE) != 0) {
  1280. LOG(ERROR) << "Can't mount " << LOCALE_FILE;
  1281. return "";
  1282. }
  1283. std::string content;
  1284. if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
  1285. PLOG(ERROR) << "Can't read " << LOCALE_FILE;
  1286. return "";
  1287. }
  1288. return android::base::Trim(content);
  1289. }
  1290. void ui_print(const char* format, ...) {
  1291. std::string buffer;
  1292. va_list ap;
  1293. va_start(ap, format);
  1294. android::base::StringAppendV(&buffer, format, ap);
  1295. va_end(ap);
  1296. if (ui != nullptr) {
  1297. ui->Print("%s", buffer.c_str());
  1298. } else {
  1299. fputs(buffer.c_str(), stdout);
  1300. }
  1301. }
  1302. static constexpr char log_characters[] = "VDIWEF";
  1303. void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
  1304. const char* /* tag */, const char* /* file */, unsigned int /* line */,
  1305. const char* message) {
  1306. if (severity >= android::base::ERROR && ui != nullptr) {
  1307. ui->Print("E:%s\n", message);
  1308. } else {
  1309. fprintf(stdout, "%c:%s\n", log_characters[severity], message);
  1310. }
  1311. }
  1312. static bool is_battery_ok() {
  1313. using android::hardware::health::V1_0::BatteryStatus;
  1314. using android::hardware::health::V2_0::Result;
  1315. using android::hardware::health::V2_0::toString;
  1316. using android::hardware::health::V2_0::implementation::Health;
  1317. struct healthd_config healthd_config = {
  1318. .batteryStatusPath = android::String8(android::String8::kEmptyString),
  1319. .batteryHealthPath = android::String8(android::String8::kEmptyString),
  1320. .batteryPresentPath = android::String8(android::String8::kEmptyString),
  1321. .batteryCapacityPath = android::String8(android::String8::kEmptyString),
  1322. .batteryVoltagePath = android::String8(android::String8::kEmptyString),
  1323. .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
  1324. .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
  1325. .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
  1326. .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
  1327. .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
  1328. .batteryFullChargePath = android::String8(android::String8::kEmptyString),
  1329. .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
  1330. .energyCounter = NULL,
  1331. .boot_min_cap = 0,
  1332. .screen_on = NULL
  1333. };
  1334. auto health =
  1335. android::hardware::health::V2_0::implementation::Health::initInstance(&healthd_config);
  1336. int wait_second = 0;
  1337. while (true) {
  1338. auto charge_status = BatteryStatus::UNKNOWN;
  1339. health
  1340. ->getChargeStatus([&charge_status](auto res, auto out_status) {
  1341. if (res == Result::SUCCESS) {
  1342. charge_status = out_status;
  1343. }
  1344. })
  1345. .isOk(); // should not have transport error
  1346. // Treat unknown status as charged.
  1347. bool charged = (charge_status != BatteryStatus::DISCHARGING &&
  1348. charge_status != BatteryStatus::NOT_CHARGING);
  1349. Result res = Result::UNKNOWN;
  1350. int32_t capacity = INT32_MIN;
  1351. health
  1352. ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
  1353. res = out_res;
  1354. capacity = out_capacity;
  1355. })
  1356. .isOk(); // should not have transport error
  1357. ui_print("charge_status %d, charged %d, status %s, capacity %" PRId32 "\n", charge_status,
  1358. charged, toString(res).c_str(), capacity);
  1359. // At startup, the battery drivers in devices like N5X/N6P take some time to load
  1360. // the battery profile. Before the load finishes, it reports value 50 as a fake
  1361. // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
  1362. // to finish loading the battery profile earlier than 10 seconds after kernel startup.
  1363. if (res == Result::SUCCESS && capacity == 50) {
  1364. if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
  1365. sleep(1);
  1366. wait_second++;
  1367. continue;
  1368. }
  1369. }
  1370. // If we can't read battery percentage, it may be a device without battery. In this
  1371. // situation, use 100 as a fake battery percentage.
  1372. if (res != Result::SUCCESS) {
  1373. capacity = 100;
  1374. }
  1375. return (charged && capacity >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
  1376. (!charged && capacity >= BATTERY_OK_PERCENTAGE);
  1377. }
  1378. }
  1379. // Set the retry count to |retry_count| in BCB.
  1380. static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
  1381. std::vector<std::string> options;
  1382. for (const auto& arg : args) {
  1383. if (!android::base::StartsWith(arg, "--retry_count")) {
  1384. options.push_back(arg);
  1385. }
  1386. }
  1387. // Update the retry counter in BCB.
  1388. options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
  1389. std::string err;
  1390. if (!update_bootloader_message(options, &err)) {
  1391. LOG(ERROR) << err;
  1392. }
  1393. }
  1394. static bool bootreason_in_blacklist() {
  1395. std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
  1396. if (!bootreason.empty()) {
  1397. for (const auto& str : bootreason_blacklist) {
  1398. if (strcasecmp(str.c_str(), bootreason.c_str()) == 0) {
  1399. return true;
  1400. }
  1401. }
  1402. }
  1403. return false;
  1404. }
  1405. static void log_failure_code(ErrorCode code, const char *update_package) {
  1406. std::vector<std::string> log_buffer = {
  1407. update_package,
  1408. "0", // install result
  1409. "error: " + std::to_string(code),
  1410. };
  1411. std::string log_content = android::base::Join(log_buffer, "\n");
  1412. if (!android::base::WriteStringToFile(log_content, TEMPORARY_INSTALL_FILE)) {
  1413. PLOG(ERROR) << "failed to write " << TEMPORARY_INSTALL_FILE;
  1414. }
  1415. // Also write the info into last_log.
  1416. LOG(INFO) << log_content;
  1417. }
  1418. static void copy_userdata_files() {
  1419. if (ensure_path_mounted("/data") == 0) {
  1420. userdata_mountable = true;
  1421. if (access(fbe_key_version, F_OK) != 0) {
  1422. userdata_encrypted = false;
  1423. }
  1424. if (access(adb_keys_root, F_OK) != 0) {
  1425. if (access(adb_keys_data, R_OK) == 0) {
  1426. file_copy(adb_keys_data, adb_keys_root);
  1427. }
  1428. }
  1429. if (access(time_off_root, F_OK) != 0) {
  1430. if (access(time_off_1_data, R_OK) == 0) {
  1431. file_copy(time_off_1_data, time_off_root);
  1432. }
  1433. else if (access(time_off_2_data, R_OK) == 0) {
  1434. file_copy(time_off_2_data, time_off_root);
  1435. }
  1436. }
  1437. ensure_path_unmounted("/data");
  1438. }
  1439. }
  1440. static void set_time() {
  1441. struct timeval now;
  1442. FILE* fp;
  1443. gettimeofday(&now, nullptr);
  1444. if (now.tv_sec <= TV_MIN) {
  1445. fp = fopen(time_off_root, "r");
  1446. if (fp) {
  1447. uint64_t off;
  1448. if (fread(&off, 1, sizeof(off), fp) == sizeof(off)) {
  1449. now.tv_sec = off / 1000;
  1450. now.tv_usec = (off % 1000) * 1000;
  1451. if (now.tv_sec > TV_MIN) {
  1452. settimeofday(&now, nullptr);
  1453. }
  1454. }
  1455. fclose(fp);
  1456. }
  1457. }
  1458. }
  1459. static void setup_adbd() {
  1460. int tries;
  1461. for (tries = 0; tries < 5; ++tries) {
  1462. if (access(adb_keys_root, F_OK) == 0) {
  1463. break;
  1464. }
  1465. sleep(1);
  1466. }
  1467. // Trigger (re)start of adb daemon
  1468. property_set("lineage.service.adb.root", "1");
  1469. }
  1470. int main(int argc, char **argv) {
  1471. // We don't have logcat yet under recovery; so we'll print error on screen and
  1472. // log to stdout (which is redirected to recovery.log) as we used to do.
  1473. android::base::InitLogging(argv, &UiLogger);
  1474. // Take last pmsg contents and rewrite it to the current pmsg session.
  1475. static const char filter[] = "recovery/";
  1476. // Do we need to rotate?
  1477. bool doRotate = false;
  1478. __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &doRotate);
  1479. // Take action to refresh pmsg contents
  1480. __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &doRotate);
  1481. // If this binary is started with the single argument "--adbd",
  1482. // instead of being the normal recovery binary, it turns into kind
  1483. // of a stripped-down version of adbd that only supports the
  1484. // 'sideload' command. Note this must be a real argument, not
  1485. // anything in the command file or bootloader control block; the
  1486. // only way recovery should be run with this argument is when it
  1487. // starts a copy of itself from the apply_from_adb() function.
  1488. if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
  1489. minadbd_main();
  1490. return 0;
  1491. }
  1492. // Handle alternative invocations
  1493. char* command = argv[0];
  1494. char* stripped = strrchr(argv[0], '/');
  1495. if (stripped) {
  1496. command = stripped + 1;
  1497. }
  1498. if (strcmp(command, "recovery") != 0) {
  1499. struct recovery_cmd cmd = get_command(command);
  1500. if (cmd.name) {
  1501. return cmd.main_func(argc, argv);
  1502. }
  1503. if (!strcmp(command, "setup_adbd")) {
  1504. setup_adbd();
  1505. return 0;
  1506. }
  1507. LOG(ERROR) << "Unhandled command " << command;
  1508. return 1;
  1509. }
  1510. // Clear umask for packages that copy files out to /tmp and then over
  1511. // to /system without properly setting all permissions (eg. gapps).
  1512. umask(0);
  1513. // redirect_stdio should be called only in non-sideload mode. Otherwise
  1514. // we may have two logger instances with different timestamps.
  1515. redirect_stdio(TEMPORARY_LOG_FILE);
  1516. load_volume_table();
  1517. has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
  1518. copy_userdata_files();
  1519. set_time();
  1520. setup_adbd();
  1521. time_t start = time(nullptr);
  1522. printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
  1523. std::vector<std::string> args = get_args(argc, argv);
  1524. std::vector<char*> args_to_parse(args.size());
  1525. std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
  1526. [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
  1527. const char* update_package = nullptr;
  1528. bool should_wipe_data = false;
  1529. bool should_prompt_and_wipe_data = false;
  1530. bool should_wipe_cache = false;
  1531. bool should_wipe_ab = false;
  1532. size_t wipe_package_size = 0;
  1533. bool show_text = false;
  1534. bool sideload = false;
  1535. bool sideload_auto_reboot = false;
  1536. bool just_exit = false;
  1537. bool shutdown_after = false;
  1538. int retry_count = 0;
  1539. bool security_update = false;
  1540. int arg;
  1541. int option_index;
  1542. while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
  1543. &option_index)) != -1) {
  1544. switch (arg) {
  1545. case 'n':
  1546. android::base::ParseInt(optarg, &retry_count, 0);
  1547. break;
  1548. case 'u':
  1549. update_package = optarg;
  1550. break;
  1551. case 'w':
  1552. should_wipe_data = true;
  1553. break;
  1554. case 'c':
  1555. should_wipe_cache = true;
  1556. break;
  1557. case 't':
  1558. show_text = true;
  1559. break;
  1560. case 's':
  1561. sideload = true;
  1562. break;
  1563. case 'a':
  1564. sideload = true;
  1565. sideload_auto_reboot = true;
  1566. break;
  1567. case 'x':
  1568. just_exit = true;
  1569. break;
  1570. case 'l':
  1571. locale = optarg;
  1572. break;
  1573. case 'p':
  1574. shutdown_after = true;
  1575. break;
  1576. case 'r':
  1577. reason = optarg;
  1578. break;
  1579. case 'e':
  1580. security_update = true;
  1581. break;
  1582. case 0: {
  1583. std::string option = OPTIONS[option_index].name;
  1584. if (option == "wipe_ab") {
  1585. should_wipe_ab = true;
  1586. } else if (option == "wipe_package_size") {
  1587. android::base::ParseUint(optarg, &wipe_package_size);
  1588. } else if (option == "prompt_and_wipe_data") {
  1589. should_prompt_and_wipe_data = true;
  1590. }
  1591. break;
  1592. }
  1593. case '?':
  1594. LOG(ERROR) << "Invalid command argument";
  1595. continue;
  1596. }
  1597. }
  1598. if (locale.empty()) {
  1599. if (has_cache) {
  1600. locale = load_locale_from_cache();
  1601. }
  1602. if (locale.empty()) {
  1603. locale = DEFAULT_LOCALE;
  1604. }
  1605. }
  1606. printf("locale is [%s]\n", locale.c_str());
  1607. printf("stage is [%s]\n", stage.c_str());
  1608. printf("reason is [%s]\n", reason);
  1609. Device* device = make_device();
  1610. if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
  1611. printf("Quiescent recovery mode.\n");
  1612. ui = new StubRecoveryUI();
  1613. } else {
  1614. ui = device->GetUI();
  1615. if (!ui->Init(locale)) {
  1616. printf("Failed to initialize UI, use stub UI instead.\n");
  1617. ui = new StubRecoveryUI();
  1618. }
  1619. }
  1620. VolumeClient* volclient = new VolumeClient(device);
  1621. VolumeManager* volmgr = VolumeManager::Instance();
  1622. if (!volmgr->start(volclient)) {
  1623. printf("Failed to start volume manager\n");
  1624. }
  1625. // Set background string to "installing security update" for security update,
  1626. // otherwise set it to "installing system update".
  1627. ui->SetSystemUpdateText(security_update);
  1628. int st_cur, st_max;
  1629. if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
  1630. ui->SetStage(st_cur, st_max);
  1631. }
  1632. ui->SetBackground(RecoveryUI::NONE);
  1633. if (show_text) ui->ShowText(true);
  1634. sehandle = selinux_android_file_context_handle();
  1635. selinux_android_set_sehandle(sehandle);
  1636. if (!sehandle) {
  1637. ui->Print("Warning: No file_contexts\n");
  1638. }
  1639. device->StartRecovery();
  1640. printf("Command:");
  1641. for (const auto& arg : args) {
  1642. printf(" \"%s\"", arg.c_str());
  1643. }
  1644. printf("\n\n");
  1645. property_list(print_property, nullptr);
  1646. printf("\n");
  1647. int status = INSTALL_SUCCESS;
  1648. if (update_package != nullptr) {
  1649. // It's not entirely true that we will modify the flash. But we want
  1650. // to log the update attempt since update_package is non-NULL.
  1651. modified_flash = true;
  1652. if (!is_battery_ok()) {
  1653. ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
  1654. BATTERY_OK_PERCENTAGE);
  1655. // Log the error code to last_install when installation skips due to
  1656. // low battery.
  1657. log_failure_code(kLowBattery, update_package);
  1658. status = INSTALL_SKIPPED;
  1659. } else if (bootreason_in_blacklist()) {
  1660. // Skip update-on-reboot when bootreason is kernel_panic or similar
  1661. ui->Print("bootreason is in the blacklist; skip OTA installation\n");
  1662. log_failure_code(kBootreasonInBlacklist, update_package);
  1663. status = INSTALL_SKIPPED;
  1664. } else {
  1665. // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
  1666. // identify the interrupted update due to unexpected reboots.
  1667. if (retry_count == 0) {
  1668. set_retry_bootloader_message(retry_count + 1, args);
  1669. }
  1670. status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true,
  1671. retry_count, true);
  1672. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  1673. wipe_cache(false, device);
  1674. }
  1675. if (status != INSTALL_SUCCESS) {
  1676. ui->Print("Installation aborted.\n");
  1677. // When I/O error happens, reboot and retry installation RETRY_LIMIT
  1678. // times before we abandon this OTA update.
  1679. if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
  1680. copy_logs();
  1681. retry_count += 1;
  1682. set_retry_bootloader_message(retry_count, args);
  1683. // Print retry count on screen.
  1684. ui->Print("Retry attempt %d\n", retry_count);
  1685. // Reboot and retry the update
  1686. if (!reboot("reboot,recovery")) {
  1687. ui->Print("Reboot failed\n");
  1688. } else {
  1689. while (true) {
  1690. pause();
  1691. }
  1692. }
  1693. }
  1694. // If this is an eng or userdebug build, then automatically
  1695. // turn the text display on if the script fails so the error
  1696. // message is visible.
  1697. if (is_ro_debuggable()) {
  1698. ui->ShowText(true);
  1699. }
  1700. }
  1701. }
  1702. } else if (should_wipe_data) {
  1703. if (!wipe_data(device)) {
  1704. status = INSTALL_ERROR;
  1705. }
  1706. } else if (should_prompt_and_wipe_data) {
  1707. ui->ShowText(true);
  1708. ui->SetBackground(RecoveryUI::ERROR);
  1709. if (!prompt_and_wipe_data(device)) {
  1710. status = INSTALL_ERROR;
  1711. }
  1712. ui->ShowText(false);
  1713. } else if (should_wipe_cache) {
  1714. if (!wipe_cache(false, device)) {
  1715. status = INSTALL_ERROR;
  1716. }
  1717. } else if (should_wipe_ab) {
  1718. if (!wipe_ab_device(wipe_package_size)) {
  1719. status = INSTALL_ERROR;
  1720. }
  1721. } else if (sideload) {
  1722. // 'adb reboot sideload' acts the same as user presses key combinations
  1723. // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
  1724. // display will NOT be turned on by default. And it will reboot after
  1725. // sideload finishes even if there are errors. Unless one turns on the
  1726. // text display during the installation. This is to enable automated
  1727. // testing.
  1728. if (!sideload_auto_reboot) {
  1729. ui->ShowText(true);
  1730. }
  1731. sideload_start();
  1732. sideload_wait(false);
  1733. status = sideload_install(&should_wipe_cache, TEMPORARY_INSTALL_FILE, true);
  1734. sideload_stop();
  1735. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  1736. if (!wipe_cache(false, device)) {
  1737. status = INSTALL_ERROR;
  1738. }
  1739. }
  1740. ui->Print("\nInstall from ADB complete (status: %d).\n", status);
  1741. if (sideload_auto_reboot) {
  1742. ui->Print("Rebooting automatically.\n");
  1743. }
  1744. } else if (!just_exit) {
  1745. // Always show menu if no command is specified.
  1746. // Note that this should be called before setting the background to avoid
  1747. // flickering the background image.
  1748. ui->ShowText(true);
  1749. status = INSTALL_NONE; // No command specified
  1750. ui->SetBackground(RecoveryUI::NO_COMMAND);
  1751. }
  1752. if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
  1753. ui->SetBackground(RecoveryUI::ERROR);
  1754. if (!ui->IsTextVisible()) {
  1755. ui->Redraw();
  1756. sleep(5);
  1757. }
  1758. }
  1759. Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
  1760. // 1. If the recovery menu is visible, prompt and wait for commands.
  1761. // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
  1762. // recovery to sideload a package.)
  1763. // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
  1764. // without waiting.
  1765. // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
  1766. // reboot after it shows the "error" screen for 5s.
  1767. if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
  1768. Device::BuiltinAction temp = prompt_and_wait(device, status);
  1769. if (temp != Device::NO_ACTION) {
  1770. after = temp;
  1771. }
  1772. }
  1773. // Save logs and clean up before rebooting or shutting down.
  1774. finish_recovery();
  1775. volmgr->unmountAll();
  1776. volmgr->stop();
  1777. delete volclient;
  1778. sync();
  1779. ui->Stop();
  1780. switch (after) {
  1781. case Device::SHUTDOWN:
  1782. ui->Print("Shutting down...\n");
  1783. android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
  1784. break;
  1785. case Device::REBOOT_BOOTLOADER:
  1786. #ifdef DOWNLOAD_MODE
  1787. ui->Print("Rebooting to download mode...\n");
  1788. android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,download");
  1789. #else
  1790. ui->Print("Rebooting to bootloader...\n");
  1791. android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
  1792. #endif
  1793. break;
  1794. default:
  1795. ui->Print("Rebooting...\n");
  1796. reboot("reboot,");
  1797. break;
  1798. }
  1799. while (true) {
  1800. pause();
  1801. }
  1802. // Should be unreachable.
  1803. return EXIT_SUCCESS;
  1804. }