No Description

recovery.cpp 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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 "adb_install.h"
  57. #include "common.h"
  58. #include "device.h"
  59. #include "fuse_sdcard_provider.h"
  60. #include "fuse_sideload.h"
  61. #include "install.h"
  62. #include "minadbd/minadbd.h"
  63. #include "minui/minui.h"
  64. #include "otautil/DirUtil.h"
  65. #include "otautil/error_code.h"
  66. #include "roots.h"
  67. #include "rotate_logs.h"
  68. #include "screen_ui.h"
  69. #include "stub_ui.h"
  70. #include "ui.h"
  71. static const struct option OPTIONS[] = {
  72. { "update_package", required_argument, NULL, 'u' },
  73. { "retry_count", required_argument, NULL, 'n' },
  74. { "wipe_data", no_argument, NULL, 'w' },
  75. { "wipe_cache", no_argument, NULL, 'c' },
  76. { "show_text", no_argument, NULL, 't' },
  77. { "sideload", no_argument, NULL, 's' },
  78. { "sideload_auto_reboot", no_argument, NULL, 'a' },
  79. { "just_exit", no_argument, NULL, 'x' },
  80. { "locale", required_argument, NULL, 'l' },
  81. { "shutdown_after", no_argument, NULL, 'p' },
  82. { "reason", required_argument, NULL, 'r' },
  83. { "security", no_argument, NULL, 'e'},
  84. { "wipe_ab", no_argument, NULL, 0 },
  85. { "wipe_package_size", required_argument, NULL, 0 },
  86. { "prompt_and_wipe_data", no_argument, NULL, 0 },
  87. { NULL, 0, NULL, 0 },
  88. };
  89. // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
  90. static const std::vector<std::string> bootreason_blacklist {
  91. "kernel_panic",
  92. "Panic",
  93. };
  94. static const char *CACHE_LOG_DIR = "/cache/recovery";
  95. static const char *COMMAND_FILE = "/cache/recovery/command";
  96. static const char *LOG_FILE = "/cache/recovery/log";
  97. static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
  98. static const char *LOCALE_FILE = "/cache/recovery/last_locale";
  99. static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
  100. static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
  101. static const char *CACHE_ROOT = "/cache";
  102. static const char *DATA_ROOT = "/data";
  103. static const char* METADATA_ROOT = "/metadata";
  104. static const char *SDCARD_ROOT = "/sdcard";
  105. static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
  106. static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
  107. static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
  108. static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
  109. // We will try to apply the update package 5 times at most in case of an I/O error or
  110. // bspatch | imgpatch error.
  111. static const int RETRY_LIMIT = 4;
  112. static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
  113. // GmsCore enters recovery mode to install package when having enough battery
  114. // percentage. Normally, the threshold is 40% without charger and 20% with charger.
  115. // So we should check battery with a slightly lower limitation.
  116. static const int BATTERY_OK_PERCENTAGE = 20;
  117. static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
  118. static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
  119. static constexpr const char* DEFAULT_LOCALE = "en-US";
  120. // We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
  121. // into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
  122. static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
  123. static std::string locale;
  124. static bool has_cache = false;
  125. RecoveryUI* ui = nullptr;
  126. bool modified_flash = false;
  127. std::string stage;
  128. const char* reason = nullptr;
  129. struct selabel_handle* sehandle;
  130. /*
  131. * The recovery tool communicates with the main system through /cache files.
  132. * /cache/recovery/command - INPUT - command line for tool, one arg per line
  133. * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
  134. *
  135. * The arguments which may be supplied in the recovery.command file:
  136. * --update_package=path - verify install an OTA package file
  137. * --wipe_data - erase user data (and cache), then reboot
  138. * --prompt_and_wipe_data - prompt the user that data is corrupt,
  139. * with their consent erase user data (and cache), then reboot
  140. * --wipe_cache - wipe cache (but not user data), then reboot
  141. * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
  142. * --just_exit - do nothing; exit and reboot
  143. *
  144. * After completing, we remove /cache/recovery/command and reboot.
  145. * Arguments may also be supplied in the bootloader control block (BCB).
  146. * These important scenarios must be safely restartable at any point:
  147. *
  148. * FACTORY RESET
  149. * 1. user selects "factory reset"
  150. * 2. main system writes "--wipe_data" to /cache/recovery/command
  151. * 3. main system reboots into recovery
  152. * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
  153. * -- after this, rebooting will restart the erase --
  154. * 5. erase_volume() reformats /data
  155. * 6. erase_volume() reformats /cache
  156. * 7. finish_recovery() erases BCB
  157. * -- after this, rebooting will restart the main system --
  158. * 8. main() calls reboot() to boot main system
  159. *
  160. * OTA INSTALL
  161. * 1. main system downloads OTA package to /cache/some-filename.zip
  162. * 2. main system writes "--update_package=/cache/some-filename.zip"
  163. * 3. main system reboots into recovery
  164. * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
  165. * -- after this, rebooting will attempt to reinstall the update --
  166. * 5. install_package() attempts to install the update
  167. * NOTE: the package install must itself be restartable from any point
  168. * 6. finish_recovery() erases BCB
  169. * -- after this, rebooting will (try to) restart the main system --
  170. * 7. ** if install failed **
  171. * 7a. prompt_and_wait() shows an error icon and waits for the user
  172. * 7b. the user reboots (pulling the battery, etc) into the main system
  173. */
  174. // Open a given path, mounting partitions as necessary.
  175. FILE* fopen_path(const char* path, const char* mode) {
  176. if (ensure_path_mounted(path) != 0) {
  177. LOG(ERROR) << "Can't mount " << path;
  178. return nullptr;
  179. }
  180. // When writing, try to create the containing directory, if necessary. Use generous permissions,
  181. // the system (init.rc) will reset them.
  182. if (strchr("wa", mode[0])) {
  183. mkdir_recursively(path, 0777, true, sehandle);
  184. }
  185. return fopen(path, mode);
  186. }
  187. // close a file, log an error if the error indicator is set
  188. static void check_and_fclose(FILE *fp, const char *name) {
  189. fflush(fp);
  190. if (fsync(fileno(fp)) == -1) {
  191. PLOG(ERROR) << "Failed to fsync " << name;
  192. }
  193. if (ferror(fp)) {
  194. PLOG(ERROR) << "Error in " << name;
  195. }
  196. fclose(fp);
  197. }
  198. bool is_ro_debuggable() {
  199. return android::base::GetBoolProperty("ro.debuggable", false);
  200. }
  201. bool reboot(const std::string& command) {
  202. std::string cmd = command;
  203. if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
  204. cmd += ",quiescent";
  205. }
  206. return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
  207. }
  208. static void redirect_stdio(const char* filename) {
  209. int pipefd[2];
  210. if (pipe(pipefd) == -1) {
  211. PLOG(ERROR) << "pipe failed";
  212. // Fall back to traditional logging mode without timestamps.
  213. // If these fail, there's not really anywhere to complain...
  214. freopen(filename, "a", stdout); setbuf(stdout, NULL);
  215. freopen(filename, "a", stderr); setbuf(stderr, NULL);
  216. return;
  217. }
  218. pid_t pid = fork();
  219. if (pid == -1) {
  220. PLOG(ERROR) << "fork failed";
  221. // Fall back to traditional logging mode without timestamps.
  222. // If these fail, there's not really anywhere to complain...
  223. freopen(filename, "a", stdout); setbuf(stdout, NULL);
  224. freopen(filename, "a", stderr); setbuf(stderr, NULL);
  225. return;
  226. }
  227. if (pid == 0) {
  228. /// Close the unused write end.
  229. close(pipefd[1]);
  230. auto start = std::chrono::steady_clock::now();
  231. // Child logger to actually write to the log file.
  232. FILE* log_fp = fopen(filename, "ae");
  233. if (log_fp == nullptr) {
  234. PLOG(ERROR) << "fopen \"" << filename << "\" failed";
  235. close(pipefd[0]);
  236. _exit(EXIT_FAILURE);
  237. }
  238. FILE* pipe_fp = fdopen(pipefd[0], "r");
  239. if (pipe_fp == nullptr) {
  240. PLOG(ERROR) << "fdopen failed";
  241. check_and_fclose(log_fp, filename);
  242. close(pipefd[0]);
  243. _exit(EXIT_FAILURE);
  244. }
  245. char* line = nullptr;
  246. size_t len = 0;
  247. while (getline(&line, &len, pipe_fp) != -1) {
  248. auto now = std::chrono::steady_clock::now();
  249. double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
  250. now - start).count();
  251. if (line[0] == '\n') {
  252. fprintf(log_fp, "[%12.6lf]\n", duration);
  253. } else {
  254. fprintf(log_fp, "[%12.6lf] %s", duration, line);
  255. }
  256. fflush(log_fp);
  257. }
  258. PLOG(ERROR) << "getline failed";
  259. free(line);
  260. check_and_fclose(log_fp, filename);
  261. close(pipefd[0]);
  262. _exit(EXIT_FAILURE);
  263. } else {
  264. // Redirect stdout/stderr to the logger process.
  265. // Close the unused read end.
  266. close(pipefd[0]);
  267. setbuf(stdout, nullptr);
  268. setbuf(stderr, nullptr);
  269. if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
  270. PLOG(ERROR) << "dup2 stdout failed";
  271. }
  272. if (dup2(pipefd[1], STDERR_FILENO) == -1) {
  273. PLOG(ERROR) << "dup2 stderr failed";
  274. }
  275. close(pipefd[1]);
  276. }
  277. }
  278. // command line args come from, in decreasing precedence:
  279. // - the actual command line
  280. // - the bootloader control block (one per line, after "recovery")
  281. // - the contents of COMMAND_FILE (one per line)
  282. static std::vector<std::string> get_args(const int argc, char** const argv) {
  283. CHECK_GT(argc, 0);
  284. bootloader_message boot = {};
  285. std::string err;
  286. if (!read_bootloader_message(&boot, &err)) {
  287. LOG(ERROR) << err;
  288. // If fails, leave a zeroed bootloader_message.
  289. boot = {};
  290. }
  291. stage = std::string(boot.stage);
  292. if (boot.command[0] != 0) {
  293. std::string boot_command = std::string(boot.command, sizeof(boot.command));
  294. LOG(INFO) << "Boot command: " << boot_command;
  295. }
  296. if (boot.status[0] != 0) {
  297. std::string boot_status = std::string(boot.status, sizeof(boot.status));
  298. LOG(INFO) << "Boot status: " << boot_status;
  299. }
  300. std::vector<std::string> args(argv, argv + argc);
  301. // --- if arguments weren't supplied, look in the bootloader control block
  302. if (args.size() == 1) {
  303. boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
  304. std::string boot_recovery(boot.recovery);
  305. std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
  306. if (!tokens.empty() && tokens[0] == "recovery") {
  307. for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
  308. // Skip empty and '\0'-filled tokens.
  309. if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
  310. }
  311. LOG(INFO) << "Got " << args.size() << " arguments from boot message";
  312. } else if (boot.recovery[0] != 0) {
  313. LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
  314. }
  315. }
  316. // --- if that doesn't work, try the command file (if we have /cache).
  317. if (args.size() == 1 && has_cache) {
  318. std::string content;
  319. if (ensure_path_mounted(COMMAND_FILE) == 0 &&
  320. android::base::ReadFileToString(COMMAND_FILE, &content)) {
  321. std::vector<std::string> tokens = android::base::Split(content, "\n");
  322. // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
  323. // COMMAND_FILE doesn't use filename as the first argument).
  324. for (auto it = tokens.begin(); it != tokens.end(); it++) {
  325. // Skip empty and '\0'-filled tokens.
  326. if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
  327. }
  328. LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
  329. }
  330. }
  331. // Write the arguments (excluding the filename in args[0]) back into the
  332. // bootloader control block. So the device will always boot into recovery to
  333. // finish the pending work, until finish_recovery() is called.
  334. std::vector<std::string> options(args.cbegin() + 1, args.cend());
  335. if (!update_bootloader_message(options, &err)) {
  336. LOG(ERROR) << "Failed to set BCB message: " << err;
  337. }
  338. return args;
  339. }
  340. // Set the BCB to reboot back into recovery (it won't resume the install from
  341. // sdcard though).
  342. static void set_sdcard_update_bootloader_message() {
  343. std::vector<std::string> options;
  344. std::string err;
  345. if (!update_bootloader_message(options, &err)) {
  346. LOG(ERROR) << "Failed to set BCB message: " << err;
  347. }
  348. }
  349. // Read from kernel log into buffer and write out to file.
  350. static void save_kernel_log(const char* destination) {
  351. int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
  352. if (klog_buf_len <= 0) {
  353. PLOG(ERROR) << "Error getting klog size";
  354. return;
  355. }
  356. std::string buffer(klog_buf_len, 0);
  357. int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
  358. if (n == -1) {
  359. PLOG(ERROR) << "Error in reading klog";
  360. return;
  361. }
  362. buffer.resize(n);
  363. android::base::WriteStringToFile(buffer, destination);
  364. }
  365. // write content to the current pmsg session.
  366. static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
  367. return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
  368. filename, buf, len);
  369. }
  370. static void copy_log_file_to_pmsg(const char* source, const char* destination) {
  371. std::string content;
  372. android::base::ReadFileToString(source, &content);
  373. __pmsg_write(destination, content.c_str(), content.length());
  374. }
  375. // How much of the temp log we have copied to the copy in cache.
  376. static off_t tmplog_offset = 0;
  377. static void copy_log_file(const char* source, const char* destination, bool append) {
  378. FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
  379. if (dest_fp == nullptr) {
  380. PLOG(ERROR) << "Can't open " << destination;
  381. } else {
  382. FILE* source_fp = fopen(source, "re");
  383. if (source_fp != nullptr) {
  384. if (append) {
  385. fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
  386. }
  387. char buf[4096];
  388. size_t bytes;
  389. while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
  390. fwrite(buf, 1, bytes, dest_fp);
  391. }
  392. if (append) {
  393. tmplog_offset = ftello(source_fp);
  394. }
  395. check_and_fclose(source_fp, source);
  396. }
  397. check_and_fclose(dest_fp, destination);
  398. }
  399. }
  400. static void copy_logs() {
  401. // We only rotate and record the log of the current session if there are
  402. // actual attempts to modify the flash, such as wipes, installs from BCB
  403. // or menu selections. This is to avoid unnecessary rotation (and
  404. // possible deletion) of log files, if it does not do anything loggable.
  405. if (!modified_flash) {
  406. return;
  407. }
  408. // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
  409. copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
  410. copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
  411. // We can do nothing for now if there's no /cache partition.
  412. if (!has_cache) {
  413. return;
  414. }
  415. ensure_path_mounted(LAST_LOG_FILE);
  416. ensure_path_mounted(LAST_KMSG_FILE);
  417. rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
  418. // Copy logs to cache so the system can find out what happened.
  419. copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
  420. copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
  421. copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
  422. save_kernel_log(LAST_KMSG_FILE);
  423. chmod(LOG_FILE, 0600);
  424. chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
  425. chmod(LAST_KMSG_FILE, 0600);
  426. chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
  427. chmod(LAST_LOG_FILE, 0640);
  428. chmod(LAST_INSTALL_FILE, 0644);
  429. sync();
  430. }
  431. // Clear the recovery command and prepare to boot a (hopefully working) system,
  432. // copy our log file to cache as well (for the system to read). This function is
  433. // idempotent: call it as many times as you like.
  434. static void finish_recovery() {
  435. // Save the locale to cache, so if recovery is next started up without a '--locale' argument
  436. // (e.g., directly from the bootloader) it will use the last-known locale.
  437. if (!locale.empty() && has_cache) {
  438. LOG(INFO) << "Saving locale \"" << locale << "\"";
  439. if (ensure_path_mounted(LOCALE_FILE) != 0) {
  440. LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
  441. } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
  442. PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
  443. }
  444. }
  445. copy_logs();
  446. // Reset to normal system boot so recovery won't cycle indefinitely.
  447. std::string err;
  448. if (!clear_bootloader_message(&err)) {
  449. LOG(ERROR) << "Failed to clear BCB message: " << err;
  450. }
  451. // Remove the command file, so recovery won't repeat indefinitely.
  452. if (has_cache) {
  453. if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
  454. LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
  455. }
  456. ensure_path_unmounted(CACHE_ROOT);
  457. }
  458. sync(); // For good measure.
  459. }
  460. struct saved_log_file {
  461. std::string name;
  462. struct stat sb;
  463. std::string data;
  464. };
  465. static bool erase_volume(const char* volume) {
  466. bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
  467. bool is_data = (strcmp(volume, DATA_ROOT) == 0);
  468. ui->SetBackground(RecoveryUI::ERASING);
  469. ui->SetProgressType(RecoveryUI::INDETERMINATE);
  470. std::vector<saved_log_file> log_files;
  471. if (is_cache) {
  472. // If we're reformatting /cache, we load any past logs
  473. // (i.e. "/cache/recovery/last_*") and the current log
  474. // ("/cache/recovery/log") into memory, so we can restore them after
  475. // the reformat.
  476. ensure_path_mounted(volume);
  477. struct dirent* de;
  478. std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
  479. if (d) {
  480. while ((de = readdir(d.get())) != nullptr) {
  481. if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
  482. std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
  483. struct stat sb;
  484. if (stat(path.c_str(), &sb) == 0) {
  485. // truncate files to 512kb
  486. if (sb.st_size > (1 << 19)) {
  487. sb.st_size = 1 << 19;
  488. }
  489. std::string data(sb.st_size, '\0');
  490. FILE* f = fopen(path.c_str(), "rbe");
  491. fread(&data[0], 1, data.size(), f);
  492. fclose(f);
  493. log_files.emplace_back(saved_log_file{ path, sb, data });
  494. }
  495. }
  496. }
  497. } else {
  498. if (errno != ENOENT) {
  499. PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
  500. }
  501. }
  502. }
  503. ui->Print("Formatting %s...\n", volume);
  504. ensure_path_unmounted(volume);
  505. int result;
  506. if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
  507. // Create convert_fbe breadcrumb file to signal to init
  508. // to convert to file based encryption, not full disk encryption
  509. if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
  510. ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
  511. return true;
  512. }
  513. FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
  514. if (!f) {
  515. ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
  516. return true;
  517. }
  518. fclose(f);
  519. result = format_volume(volume, CONVERT_FBE_DIR);
  520. remove(CONVERT_FBE_FILE);
  521. rmdir(CONVERT_FBE_DIR);
  522. } else {
  523. result = format_volume(volume);
  524. }
  525. if (is_cache) {
  526. // Re-create the log dir and write back the log entries.
  527. if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
  528. mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
  529. for (const auto& log : log_files) {
  530. if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
  531. log.sb.st_gid)) {
  532. PLOG(ERROR) << "Failed to write to " << log.name;
  533. }
  534. }
  535. } else {
  536. PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
  537. }
  538. // Any part of the log we'd copied to cache is now gone.
  539. // Reset the pointer so we copy from the beginning of the temp
  540. // log.
  541. tmplog_offset = 0;
  542. copy_logs();
  543. }
  544. return (result == 0);
  545. }
  546. // Display a menu with the specified 'headers' and 'items'. Device specific HandleMenuKey() may
  547. // return a positive number beyond the given range. Caller sets 'menu_only' to true to ensure only
  548. // a menu item gets selected. 'initial_selection' controls the initial cursor location. Returns the
  549. // (non-negative) chosen item number, or -1 if timed out waiting for input.
  550. static int get_menu_selection(const char* const* headers, const char* const* items, bool menu_only,
  551. int initial_selection, Device* device) {
  552. // Throw away keys pressed previously, so user doesn't accidentally trigger menu items.
  553. ui->FlushKeys();
  554. ui->StartMenu(headers, items, initial_selection);
  555. int selected = initial_selection;
  556. int chosen_item = -1;
  557. while (chosen_item < 0) {
  558. int key = ui->WaitKey();
  559. if (key == -1) { // WaitKey() timed out.
  560. if (ui->WasTextEverVisible()) {
  561. continue;
  562. } else {
  563. LOG(INFO) << "Timed out waiting for key input; rebooting.";
  564. ui->EndMenu();
  565. return -1;
  566. }
  567. }
  568. bool visible = ui->IsTextVisible();
  569. int action = device->HandleMenuKey(key, visible);
  570. if (action < 0) {
  571. switch (action) {
  572. case Device::kHighlightUp:
  573. selected = ui->SelectMenu(--selected);
  574. break;
  575. case Device::kHighlightDown:
  576. selected = ui->SelectMenu(++selected);
  577. break;
  578. case Device::kInvokeItem:
  579. chosen_item = selected;
  580. break;
  581. case Device::kNoAction:
  582. break;
  583. }
  584. } else if (!menu_only) {
  585. chosen_item = action;
  586. }
  587. }
  588. ui->EndMenu();
  589. return chosen_item;
  590. }
  591. // Returns the selected filename, or an empty string.
  592. static std::string browse_directory(const std::string& path, Device* device) {
  593. ensure_path_mounted(path.c_str());
  594. std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
  595. if (!d) {
  596. PLOG(ERROR) << "error opening " << path;
  597. return "";
  598. }
  599. std::vector<std::string> dirs;
  600. std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
  601. dirent* de;
  602. while ((de = readdir(d.get())) != nullptr) {
  603. std::string name(de->d_name);
  604. if (de->d_type == DT_DIR) {
  605. // Skip "." and ".." entries.
  606. if (name == "." || name == "..") continue;
  607. dirs.push_back(name + "/");
  608. } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
  609. zips.push_back(name);
  610. }
  611. }
  612. std::sort(dirs.begin(), dirs.end());
  613. std::sort(zips.begin(), zips.end());
  614. // Append dirs to the zips list.
  615. zips.insert(zips.end(), dirs.begin(), dirs.end());
  616. const char* entries[zips.size() + 1];
  617. entries[zips.size()] = nullptr;
  618. for (size_t i = 0; i < zips.size(); i++) {
  619. entries[i] = zips[i].c_str();
  620. }
  621. const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
  622. int chosen_item = 0;
  623. while (true) {
  624. chosen_item = get_menu_selection(headers, entries, true, chosen_item, device);
  625. const std::string& item = zips[chosen_item];
  626. if (chosen_item == 0) {
  627. // Go up but continue browsing (if the caller is browse_directory).
  628. return "";
  629. }
  630. std::string new_path = path + "/" + item;
  631. if (new_path.back() == '/') {
  632. // Recurse down into a subdirectory.
  633. new_path.pop_back();
  634. std::string result = browse_directory(new_path, device);
  635. if (!result.empty()) return result;
  636. } else {
  637. // Selected a zip file: return the path to the caller.
  638. return new_path;
  639. }
  640. }
  641. // Unreachable.
  642. }
  643. static bool yes_no(Device* device, const char* question1, const char* question2) {
  644. const char* headers[] = { question1, question2, NULL };
  645. const char* items[] = { " No", " Yes", NULL };
  646. int chosen_item = get_menu_selection(headers, items, true, 0, device);
  647. return (chosen_item == 1);
  648. }
  649. static bool ask_to_wipe_data(Device* device) {
  650. return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
  651. }
  652. // Return true on success.
  653. static bool wipe_data(Device* device) {
  654. modified_flash = true;
  655. ui->Print("\n-- Wiping data...\n");
  656. bool success = device->PreWipeData();
  657. if (success) {
  658. success &= erase_volume(DATA_ROOT);
  659. if (has_cache) {
  660. success &= erase_volume(CACHE_ROOT);
  661. }
  662. if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
  663. success &= erase_volume(METADATA_ROOT);
  664. }
  665. }
  666. if (success) {
  667. success &= device->PostWipeData();
  668. }
  669. ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
  670. return success;
  671. }
  672. static bool prompt_and_wipe_data(Device* device) {
  673. // Use a single string and let ScreenRecoveryUI handles the wrapping.
  674. const char* const headers[] = {
  675. "Can't load Android system. Your data may be corrupt. "
  676. "If you continue to get this message, you may need to "
  677. "perform a factory data reset and erase all user data "
  678. "stored on this device.",
  679. nullptr
  680. };
  681. const char* const items[] = {
  682. "Try again",
  683. "Factory data reset",
  684. NULL
  685. };
  686. for (;;) {
  687. int chosen_item = get_menu_selection(headers, items, true, 0, device);
  688. if (chosen_item != 1) {
  689. return true; // Just reboot, no wipe; not a failure, user asked for it
  690. }
  691. if (ask_to_wipe_data(device)) {
  692. return wipe_data(device);
  693. }
  694. }
  695. }
  696. // Return true on success.
  697. static bool wipe_cache(bool should_confirm, Device* device) {
  698. if (!has_cache) {
  699. ui->Print("No /cache partition found.\n");
  700. return false;
  701. }
  702. if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
  703. return false;
  704. }
  705. modified_flash = true;
  706. ui->Print("\n-- Wiping cache...\n");
  707. bool success = erase_volume("/cache");
  708. ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
  709. return success;
  710. }
  711. // Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
  712. // BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
  713. static bool secure_wipe_partition(const std::string& partition) {
  714. android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
  715. if (fd == -1) {
  716. PLOG(ERROR) << "Failed to open \"" << partition << "\"";
  717. return false;
  718. }
  719. uint64_t range[2] = { 0, 0 };
  720. if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
  721. PLOG(ERROR) << "Failed to get partition size";
  722. return false;
  723. }
  724. LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
  725. LOG(INFO) << " Trying BLKSECDISCARD...";
  726. if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
  727. PLOG(WARNING) << " Failed";
  728. // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
  729. unsigned int zeroes;
  730. if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
  731. LOG(INFO) << " Trying BLKDISCARD...";
  732. if (ioctl(fd, BLKDISCARD, &range) == -1) {
  733. PLOG(ERROR) << " Failed";
  734. return false;
  735. }
  736. } else {
  737. LOG(INFO) << " Trying BLKZEROOUT...";
  738. if (ioctl(fd, BLKZEROOUT, &range) == -1) {
  739. PLOG(ERROR) << " Failed";
  740. return false;
  741. }
  742. }
  743. }
  744. LOG(INFO) << " Done";
  745. return true;
  746. }
  747. // Check if the wipe package matches expectation:
  748. // 1. verify the package.
  749. // 2. check metadata (ota-type, pre-device and serial number if having one).
  750. static bool check_wipe_package(size_t wipe_package_size) {
  751. if (wipe_package_size == 0) {
  752. LOG(ERROR) << "wipe_package_size is zero";
  753. return false;
  754. }
  755. std::string wipe_package;
  756. std::string err_str;
  757. if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
  758. PLOG(ERROR) << "Failed to read wipe package";
  759. return false;
  760. }
  761. if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
  762. wipe_package.size())) {
  763. LOG(ERROR) << "Failed to verify package";
  764. return false;
  765. }
  766. // Extract metadata
  767. ZipArchiveHandle zip;
  768. int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
  769. "wipe_package", &zip);
  770. if (err != 0) {
  771. LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
  772. return false;
  773. }
  774. std::string metadata;
  775. if (!read_metadata_from_package(zip, &metadata)) {
  776. CloseArchive(zip);
  777. return false;
  778. }
  779. CloseArchive(zip);
  780. // Check metadata
  781. std::vector<std::string> lines = android::base::Split(metadata, "\n");
  782. bool ota_type_matched = false;
  783. bool device_type_matched = false;
  784. bool has_serial_number = false;
  785. bool serial_number_matched = false;
  786. for (const auto& line : lines) {
  787. if (line == "ota-type=BRICK") {
  788. ota_type_matched = true;
  789. } else if (android::base::StartsWith(line, "pre-device=")) {
  790. std::string device_type = line.substr(strlen("pre-device="));
  791. std::string real_device_type = android::base::GetProperty("ro.build.product", "");
  792. device_type_matched = (device_type == real_device_type);
  793. } else if (android::base::StartsWith(line, "serialno=")) {
  794. std::string serial_no = line.substr(strlen("serialno="));
  795. std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
  796. has_serial_number = true;
  797. serial_number_matched = (serial_no == real_serial_no);
  798. }
  799. }
  800. return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
  801. }
  802. // Wipe the current A/B device, with a secure wipe of all the partitions in
  803. // RECOVERY_WIPE.
  804. static bool wipe_ab_device(size_t wipe_package_size) {
  805. ui->SetBackground(RecoveryUI::ERASING);
  806. ui->SetProgressType(RecoveryUI::INDETERMINATE);
  807. if (!check_wipe_package(wipe_package_size)) {
  808. LOG(ERROR) << "Failed to verify wipe package";
  809. return false;
  810. }
  811. std::string partition_list;
  812. if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
  813. LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
  814. return false;
  815. }
  816. std::vector<std::string> lines = android::base::Split(partition_list, "\n");
  817. for (const std::string& line : lines) {
  818. std::string partition = android::base::Trim(line);
  819. // Ignore '#' comment or empty lines.
  820. if (android::base::StartsWith(partition, "#") || partition.empty()) {
  821. continue;
  822. }
  823. // Proceed anyway even if it fails to wipe some partition.
  824. secure_wipe_partition(partition);
  825. }
  826. return true;
  827. }
  828. static void choose_recovery_file(Device* device) {
  829. std::vector<std::string> entries;
  830. if (has_cache) {
  831. for (int i = 0; i < KEEP_LOG_COUNT; i++) {
  832. auto add_to_entries = [&](const char* filename) {
  833. std::string log_file(filename);
  834. if (i > 0) {
  835. log_file += "." + std::to_string(i);
  836. }
  837. if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
  838. entries.push_back(std::move(log_file));
  839. }
  840. };
  841. // Add LAST_LOG_FILE + LAST_LOG_FILE.x
  842. add_to_entries(LAST_LOG_FILE);
  843. // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
  844. add_to_entries(LAST_KMSG_FILE);
  845. }
  846. } else {
  847. // If cache partition is not found, view /tmp/recovery.log instead.
  848. if (access(TEMPORARY_LOG_FILE, R_OK) == -1) {
  849. return;
  850. } else {
  851. entries.push_back(TEMPORARY_LOG_FILE);
  852. }
  853. }
  854. entries.push_back("Back");
  855. std::vector<const char*> menu_entries(entries.size());
  856. std::transform(entries.cbegin(), entries.cend(), menu_entries.begin(),
  857. [](const std::string& entry) { return entry.c_str(); });
  858. menu_entries.push_back(nullptr);
  859. const char* headers[] = { "Select file to view", nullptr };
  860. int chosen_item = 0;
  861. while (true) {
  862. chosen_item = get_menu_selection(headers, menu_entries.data(), true, chosen_item, device);
  863. if (entries[chosen_item] == "Back") break;
  864. ui->ShowFile(entries[chosen_item].c_str());
  865. }
  866. }
  867. static void run_graphics_test() {
  868. // Switch to graphics screen.
  869. ui->ShowText(false);
  870. ui->SetProgressType(RecoveryUI::INDETERMINATE);
  871. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  872. sleep(1);
  873. ui->SetBackground(RecoveryUI::ERROR);
  874. sleep(1);
  875. ui->SetBackground(RecoveryUI::NO_COMMAND);
  876. sleep(1);
  877. ui->SetBackground(RecoveryUI::ERASING);
  878. sleep(1);
  879. // Calling SetBackground() after SetStage() to trigger a redraw.
  880. ui->SetStage(1, 3);
  881. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  882. sleep(1);
  883. ui->SetStage(2, 3);
  884. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  885. sleep(1);
  886. ui->SetStage(3, 3);
  887. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  888. sleep(1);
  889. ui->SetStage(-1, -1);
  890. ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
  891. ui->SetProgressType(RecoveryUI::DETERMINATE);
  892. ui->ShowProgress(1.0, 10.0);
  893. float fraction = 0.0;
  894. for (size_t i = 0; i < 100; ++i) {
  895. fraction += .01;
  896. ui->SetProgress(fraction);
  897. usleep(100000);
  898. }
  899. ui->ShowText(true);
  900. }
  901. static int apply_from_sdcard(Device* device, bool* wipe_cache) {
  902. modified_flash = true;
  903. if (ensure_path_mounted(SDCARD_ROOT) != 0) {
  904. ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
  905. return INSTALL_ERROR;
  906. }
  907. std::string path = browse_directory(SDCARD_ROOT, device);
  908. if (path.empty()) {
  909. ui->Print("\n-- No package file selected.\n");
  910. ensure_path_unmounted(SDCARD_ROOT);
  911. return INSTALL_ERROR;
  912. }
  913. ui->Print("\n-- Install %s ...\n", path.c_str());
  914. set_sdcard_update_bootloader_message();
  915. void* token = start_sdcard_fuse(path.c_str());
  916. int status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
  917. TEMPORARY_INSTALL_FILE, false, 0/*retry_count*/);
  918. finish_sdcard_fuse(token);
  919. ensure_path_unmounted(SDCARD_ROOT);
  920. return status;
  921. }
  922. // Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
  923. // which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
  924. static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
  925. for (;;) {
  926. finish_recovery();
  927. switch (status) {
  928. case INSTALL_SUCCESS:
  929. case INSTALL_NONE:
  930. ui->SetBackground(RecoveryUI::NO_COMMAND);
  931. break;
  932. case INSTALL_ERROR:
  933. case INSTALL_CORRUPT:
  934. ui->SetBackground(RecoveryUI::ERROR);
  935. break;
  936. }
  937. ui->SetProgressType(RecoveryUI::EMPTY);
  938. int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), false, 0, device);
  939. // Device-specific code may take some action here. It may return one of the core actions
  940. // handled in the switch statement below.
  941. Device::BuiltinAction chosen_action =
  942. (chosen_item == -1) ? Device::REBOOT : device->InvokeMenuItem(chosen_item);
  943. bool should_wipe_cache = false;
  944. switch (chosen_action) {
  945. case Device::NO_ACTION:
  946. break;
  947. case Device::REBOOT:
  948. case Device::SHUTDOWN:
  949. case Device::REBOOT_BOOTLOADER:
  950. return chosen_action;
  951. case Device::WIPE_DATA:
  952. if (ui->IsTextVisible()) {
  953. if (ask_to_wipe_data(device)) {
  954. wipe_data(device);
  955. }
  956. } else {
  957. wipe_data(device);
  958. return Device::NO_ACTION;
  959. }
  960. break;
  961. case Device::WIPE_CACHE:
  962. wipe_cache(ui->IsTextVisible(), device);
  963. if (!ui->IsTextVisible()) return Device::NO_ACTION;
  964. break;
  965. case Device::APPLY_ADB_SIDELOAD:
  966. case Device::APPLY_SDCARD:
  967. {
  968. bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
  969. if (adb) {
  970. status = apply_from_adb(&should_wipe_cache, TEMPORARY_INSTALL_FILE);
  971. } else {
  972. status = apply_from_sdcard(device, &should_wipe_cache);
  973. }
  974. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  975. if (!wipe_cache(false, device)) {
  976. status = INSTALL_ERROR;
  977. }
  978. }
  979. if (status != INSTALL_SUCCESS) {
  980. ui->SetBackground(RecoveryUI::ERROR);
  981. ui->Print("Installation aborted.\n");
  982. copy_logs();
  983. } else if (!ui->IsTextVisible()) {
  984. return Device::NO_ACTION; // reboot if logs aren't visible
  985. } else {
  986. ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
  987. }
  988. }
  989. break;
  990. case Device::VIEW_RECOVERY_LOGS:
  991. choose_recovery_file(device);
  992. break;
  993. case Device::RUN_GRAPHICS_TEST:
  994. run_graphics_test();
  995. break;
  996. case Device::RUN_LOCALE_TEST: {
  997. ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
  998. screen_ui->CheckBackgroundTextImages(locale);
  999. break;
  1000. }
  1001. case Device::MOUNT_SYSTEM:
  1002. // For a system image built with the root directory (i.e. system_root_image == "true"), we
  1003. // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
  1004. // work (the symlink is created through the build system). (Bug: 22855115)
  1005. if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
  1006. if (ensure_path_mounted_at("/", "/system_root") != -1) {
  1007. ui->Print("Mounted /system.\n");
  1008. }
  1009. } else {
  1010. if (ensure_path_mounted("/system") != -1) {
  1011. ui->Print("Mounted /system.\n");
  1012. }
  1013. }
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. static void print_property(const char* key, const char* name, void* /* cookie */) {
  1019. printf("%s=%s\n", key, name);
  1020. }
  1021. static std::string load_locale_from_cache() {
  1022. if (ensure_path_mounted(LOCALE_FILE) != 0) {
  1023. LOG(ERROR) << "Can't mount " << LOCALE_FILE;
  1024. return "";
  1025. }
  1026. std::string content;
  1027. if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
  1028. PLOG(ERROR) << "Can't read " << LOCALE_FILE;
  1029. return "";
  1030. }
  1031. return android::base::Trim(content);
  1032. }
  1033. void ui_print(const char* format, ...) {
  1034. std::string buffer;
  1035. va_list ap;
  1036. va_start(ap, format);
  1037. android::base::StringAppendV(&buffer, format, ap);
  1038. va_end(ap);
  1039. if (ui != nullptr) {
  1040. ui->Print("%s", buffer.c_str());
  1041. } else {
  1042. fputs(buffer.c_str(), stdout);
  1043. }
  1044. }
  1045. static constexpr char log_characters[] = "VDIWEF";
  1046. void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
  1047. const char* /* tag */, const char* /* file */, unsigned int /* line */,
  1048. const char* message) {
  1049. if (severity >= android::base::ERROR && ui != nullptr) {
  1050. ui->Print("E:%s\n", message);
  1051. } else {
  1052. fprintf(stdout, "%c:%s\n", log_characters[severity], message);
  1053. }
  1054. }
  1055. static bool is_battery_ok() {
  1056. using android::hardware::health::V1_0::BatteryStatus;
  1057. using android::hardware::health::V2_0::Result;
  1058. using android::hardware::health::V2_0::toString;
  1059. using android::hardware::health::V2_0::implementation::Health;
  1060. struct healthd_config healthd_config = {
  1061. .batteryStatusPath = android::String8(android::String8::kEmptyString),
  1062. .batteryHealthPath = android::String8(android::String8::kEmptyString),
  1063. .batteryPresentPath = android::String8(android::String8::kEmptyString),
  1064. .batteryCapacityPath = android::String8(android::String8::kEmptyString),
  1065. .batteryVoltagePath = android::String8(android::String8::kEmptyString),
  1066. .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
  1067. .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
  1068. .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
  1069. .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
  1070. .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
  1071. .batteryFullChargePath = android::String8(android::String8::kEmptyString),
  1072. .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
  1073. .energyCounter = NULL,
  1074. .boot_min_cap = 0,
  1075. .screen_on = NULL
  1076. };
  1077. auto health =
  1078. android::hardware::health::V2_0::implementation::Health::initInstance(&healthd_config);
  1079. int wait_second = 0;
  1080. while (true) {
  1081. auto charge_status = BatteryStatus::UNKNOWN;
  1082. health
  1083. ->getChargeStatus([&charge_status](auto res, auto out_status) {
  1084. if (res == Result::SUCCESS) {
  1085. charge_status = out_status;
  1086. }
  1087. })
  1088. .isOk(); // should not have transport error
  1089. // Treat unknown status as charged.
  1090. bool charged = (charge_status != BatteryStatus::DISCHARGING &&
  1091. charge_status != BatteryStatus::NOT_CHARGING);
  1092. Result res = Result::UNKNOWN;
  1093. int32_t capacity = INT32_MIN;
  1094. health
  1095. ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
  1096. res = out_res;
  1097. capacity = out_capacity;
  1098. })
  1099. .isOk(); // should not have transport error
  1100. ui_print("charge_status %d, charged %d, status %s, capacity %" PRId32 "\n", charge_status,
  1101. charged, toString(res).c_str(), capacity);
  1102. // At startup, the battery drivers in devices like N5X/N6P take some time to load
  1103. // the battery profile. Before the load finishes, it reports value 50 as a fake
  1104. // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
  1105. // to finish loading the battery profile earlier than 10 seconds after kernel startup.
  1106. if (res == Result::SUCCESS && capacity == 50) {
  1107. if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
  1108. sleep(1);
  1109. wait_second++;
  1110. continue;
  1111. }
  1112. }
  1113. // If we can't read battery percentage, it may be a device without battery. In this
  1114. // situation, use 100 as a fake battery percentage.
  1115. if (res != Result::SUCCESS) {
  1116. capacity = 100;
  1117. }
  1118. return (charged && capacity >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
  1119. (!charged && capacity >= BATTERY_OK_PERCENTAGE);
  1120. }
  1121. }
  1122. // Set the retry count to |retry_count| in BCB.
  1123. static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
  1124. std::vector<std::string> options;
  1125. for (const auto& arg : args) {
  1126. if (!android::base::StartsWith(arg, "--retry_count")) {
  1127. options.push_back(arg);
  1128. }
  1129. }
  1130. // Update the retry counter in BCB.
  1131. options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
  1132. std::string err;
  1133. if (!update_bootloader_message(options, &err)) {
  1134. LOG(ERROR) << err;
  1135. }
  1136. }
  1137. static bool bootreason_in_blacklist() {
  1138. std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
  1139. if (!bootreason.empty()) {
  1140. for (const auto& str : bootreason_blacklist) {
  1141. if (strcasecmp(str.c_str(), bootreason.c_str()) == 0) {
  1142. return true;
  1143. }
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. static void log_failure_code(ErrorCode code, const char *update_package) {
  1149. std::vector<std::string> log_buffer = {
  1150. update_package,
  1151. "0", // install result
  1152. "error: " + std::to_string(code),
  1153. };
  1154. std::string log_content = android::base::Join(log_buffer, "\n");
  1155. if (!android::base::WriteStringToFile(log_content, TEMPORARY_INSTALL_FILE)) {
  1156. PLOG(ERROR) << "failed to write " << TEMPORARY_INSTALL_FILE;
  1157. }
  1158. // Also write the info into last_log.
  1159. LOG(INFO) << log_content;
  1160. }
  1161. int main(int argc, char **argv) {
  1162. // We don't have logcat yet under recovery; so we'll print error on screen and
  1163. // log to stdout (which is redirected to recovery.log) as we used to do.
  1164. android::base::InitLogging(argv, &UiLogger);
  1165. // Take last pmsg contents and rewrite it to the current pmsg session.
  1166. static const char filter[] = "recovery/";
  1167. // Do we need to rotate?
  1168. bool doRotate = false;
  1169. __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &doRotate);
  1170. // Take action to refresh pmsg contents
  1171. __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &doRotate);
  1172. // If this binary is started with the single argument "--adbd",
  1173. // instead of being the normal recovery binary, it turns into kind
  1174. // of a stripped-down version of adbd that only supports the
  1175. // 'sideload' command. Note this must be a real argument, not
  1176. // anything in the command file or bootloader control block; the
  1177. // only way recovery should be run with this argument is when it
  1178. // starts a copy of itself from the apply_from_adb() function.
  1179. if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
  1180. minadbd_main();
  1181. return 0;
  1182. }
  1183. time_t start = time(nullptr);
  1184. // redirect_stdio should be called only in non-sideload mode. Otherwise
  1185. // we may have two logger instances with different timestamps.
  1186. redirect_stdio(TEMPORARY_LOG_FILE);
  1187. printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
  1188. load_volume_table();
  1189. has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
  1190. std::vector<std::string> args = get_args(argc, argv);
  1191. std::vector<char*> args_to_parse(args.size());
  1192. std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
  1193. [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
  1194. const char* update_package = nullptr;
  1195. bool should_wipe_data = false;
  1196. bool should_prompt_and_wipe_data = false;
  1197. bool should_wipe_cache = false;
  1198. bool should_wipe_ab = false;
  1199. size_t wipe_package_size = 0;
  1200. bool show_text = false;
  1201. bool sideload = false;
  1202. bool sideload_auto_reboot = false;
  1203. bool just_exit = false;
  1204. bool shutdown_after = false;
  1205. int retry_count = 0;
  1206. bool security_update = false;
  1207. int arg;
  1208. int option_index;
  1209. while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
  1210. &option_index)) != -1) {
  1211. switch (arg) {
  1212. case 'n':
  1213. android::base::ParseInt(optarg, &retry_count, 0);
  1214. break;
  1215. case 'u':
  1216. update_package = optarg;
  1217. break;
  1218. case 'w':
  1219. should_wipe_data = true;
  1220. break;
  1221. case 'c':
  1222. should_wipe_cache = true;
  1223. break;
  1224. case 't':
  1225. show_text = true;
  1226. break;
  1227. case 's':
  1228. sideload = true;
  1229. break;
  1230. case 'a':
  1231. sideload = true;
  1232. sideload_auto_reboot = true;
  1233. break;
  1234. case 'x':
  1235. just_exit = true;
  1236. break;
  1237. case 'l':
  1238. locale = optarg;
  1239. break;
  1240. case 'p':
  1241. shutdown_after = true;
  1242. break;
  1243. case 'r':
  1244. reason = optarg;
  1245. break;
  1246. case 'e':
  1247. security_update = true;
  1248. break;
  1249. case 0: {
  1250. std::string option = OPTIONS[option_index].name;
  1251. if (option == "wipe_ab") {
  1252. should_wipe_ab = true;
  1253. } else if (option == "wipe_package_size") {
  1254. android::base::ParseUint(optarg, &wipe_package_size);
  1255. } else if (option == "prompt_and_wipe_data") {
  1256. should_prompt_and_wipe_data = true;
  1257. }
  1258. break;
  1259. }
  1260. case '?':
  1261. LOG(ERROR) << "Invalid command argument";
  1262. continue;
  1263. }
  1264. }
  1265. if (locale.empty()) {
  1266. if (has_cache) {
  1267. locale = load_locale_from_cache();
  1268. }
  1269. if (locale.empty()) {
  1270. locale = DEFAULT_LOCALE;
  1271. }
  1272. }
  1273. printf("locale is [%s]\n", locale.c_str());
  1274. printf("stage is [%s]\n", stage.c_str());
  1275. printf("reason is [%s]\n", reason);
  1276. Device* device = make_device();
  1277. if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
  1278. printf("Quiescent recovery mode.\n");
  1279. ui = new StubRecoveryUI();
  1280. } else {
  1281. ui = device->GetUI();
  1282. if (!ui->Init(locale)) {
  1283. printf("Failed to initialize UI, use stub UI instead.\n");
  1284. ui = new StubRecoveryUI();
  1285. }
  1286. }
  1287. // Set background string to "installing security update" for security update,
  1288. // otherwise set it to "installing system update".
  1289. ui->SetSystemUpdateText(security_update);
  1290. int st_cur, st_max;
  1291. if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
  1292. ui->SetStage(st_cur, st_max);
  1293. }
  1294. ui->SetBackground(RecoveryUI::NONE);
  1295. if (show_text) ui->ShowText(true);
  1296. sehandle = selinux_android_file_context_handle();
  1297. selinux_android_set_sehandle(sehandle);
  1298. if (!sehandle) {
  1299. ui->Print("Warning: No file_contexts\n");
  1300. }
  1301. device->StartRecovery();
  1302. printf("Command:");
  1303. for (const auto& arg : args) {
  1304. printf(" \"%s\"", arg.c_str());
  1305. }
  1306. printf("\n\n");
  1307. property_list(print_property, nullptr);
  1308. printf("\n");
  1309. ui->Print("Supported API: %d\n", kRecoveryApiVersion);
  1310. int status = INSTALL_SUCCESS;
  1311. if (update_package != nullptr) {
  1312. // It's not entirely true that we will modify the flash. But we want
  1313. // to log the update attempt since update_package is non-NULL.
  1314. modified_flash = true;
  1315. if (!is_battery_ok()) {
  1316. ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
  1317. BATTERY_OK_PERCENTAGE);
  1318. // Log the error code to last_install when installation skips due to
  1319. // low battery.
  1320. log_failure_code(kLowBattery, update_package);
  1321. status = INSTALL_SKIPPED;
  1322. } else if (bootreason_in_blacklist()) {
  1323. // Skip update-on-reboot when bootreason is kernel_panic or similar
  1324. ui->Print("bootreason is in the blacklist; skip OTA installation\n");
  1325. log_failure_code(kBootreasonInBlacklist, update_package);
  1326. status = INSTALL_SKIPPED;
  1327. } else {
  1328. // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
  1329. // identify the interrupted update due to unexpected reboots.
  1330. if (retry_count == 0) {
  1331. set_retry_bootloader_message(retry_count + 1, args);
  1332. }
  1333. status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true,
  1334. retry_count);
  1335. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  1336. wipe_cache(false, device);
  1337. }
  1338. if (status != INSTALL_SUCCESS) {
  1339. ui->Print("Installation aborted.\n");
  1340. // When I/O error happens, reboot and retry installation RETRY_LIMIT
  1341. // times before we abandon this OTA update.
  1342. if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
  1343. copy_logs();
  1344. retry_count += 1;
  1345. set_retry_bootloader_message(retry_count, args);
  1346. // Print retry count on screen.
  1347. ui->Print("Retry attempt %d\n", retry_count);
  1348. // Reboot and retry the update
  1349. if (!reboot("reboot,recovery")) {
  1350. ui->Print("Reboot failed\n");
  1351. } else {
  1352. while (true) {
  1353. pause();
  1354. }
  1355. }
  1356. }
  1357. // If this is an eng or userdebug build, then automatically
  1358. // turn the text display on if the script fails so the error
  1359. // message is visible.
  1360. if (is_ro_debuggable()) {
  1361. ui->ShowText(true);
  1362. }
  1363. }
  1364. }
  1365. } else if (should_wipe_data) {
  1366. if (!wipe_data(device)) {
  1367. status = INSTALL_ERROR;
  1368. }
  1369. } else if (should_prompt_and_wipe_data) {
  1370. ui->ShowText(true);
  1371. ui->SetBackground(RecoveryUI::ERROR);
  1372. if (!prompt_and_wipe_data(device)) {
  1373. status = INSTALL_ERROR;
  1374. }
  1375. ui->ShowText(false);
  1376. } else if (should_wipe_cache) {
  1377. if (!wipe_cache(false, device)) {
  1378. status = INSTALL_ERROR;
  1379. }
  1380. } else if (should_wipe_ab) {
  1381. if (!wipe_ab_device(wipe_package_size)) {
  1382. status = INSTALL_ERROR;
  1383. }
  1384. } else if (sideload) {
  1385. // 'adb reboot sideload' acts the same as user presses key combinations
  1386. // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
  1387. // display will NOT be turned on by default. And it will reboot after
  1388. // sideload finishes even if there are errors. Unless one turns on the
  1389. // text display during the installation. This is to enable automated
  1390. // testing.
  1391. if (!sideload_auto_reboot) {
  1392. ui->ShowText(true);
  1393. }
  1394. status = apply_from_adb(&should_wipe_cache, TEMPORARY_INSTALL_FILE);
  1395. if (status == INSTALL_SUCCESS && should_wipe_cache) {
  1396. if (!wipe_cache(false, device)) {
  1397. status = INSTALL_ERROR;
  1398. }
  1399. }
  1400. ui->Print("\nInstall from ADB complete (status: %d).\n", status);
  1401. if (sideload_auto_reboot) {
  1402. ui->Print("Rebooting automatically.\n");
  1403. }
  1404. } else if (!just_exit) {
  1405. // If this is an eng or userdebug build, automatically turn on the text display if no command
  1406. // is specified. Note that this should be called before setting the background to avoid
  1407. // flickering the background image.
  1408. if (is_ro_debuggable()) {
  1409. ui->ShowText(true);
  1410. }
  1411. status = INSTALL_NONE; // No command specified
  1412. ui->SetBackground(RecoveryUI::NO_COMMAND);
  1413. }
  1414. if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
  1415. ui->SetBackground(RecoveryUI::ERROR);
  1416. if (!ui->IsTextVisible()) {
  1417. sleep(5);
  1418. }
  1419. }
  1420. Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
  1421. // 1. If the recovery menu is visible, prompt and wait for commands.
  1422. // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
  1423. // recovery to sideload a package.)
  1424. // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
  1425. // without waiting.
  1426. // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
  1427. // reboot after it shows the "error" screen for 5s.
  1428. if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
  1429. Device::BuiltinAction temp = prompt_and_wait(device, status);
  1430. if (temp != Device::NO_ACTION) {
  1431. after = temp;
  1432. }
  1433. }
  1434. // Save logs and clean up before rebooting or shutting down.
  1435. finish_recovery();
  1436. switch (after) {
  1437. case Device::SHUTDOWN:
  1438. ui->Print("Shutting down...\n");
  1439. android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
  1440. break;
  1441. case Device::REBOOT_BOOTLOADER:
  1442. ui->Print("Rebooting to bootloader...\n");
  1443. android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
  1444. break;
  1445. default:
  1446. ui->Print("Rebooting...\n");
  1447. reboot("reboot,");
  1448. break;
  1449. }
  1450. while (true) {
  1451. pause();
  1452. }
  1453. // Should be unreachable.
  1454. return EXIT_SUCCESS;
  1455. }