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 
17 #include "install/install.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 
29 #include <algorithm>
30 #include <atomic>
31 #include <chrono>
32 #include <condition_variable>
33 #include <filesystem>
34 #include <functional>
35 #include <limits>
36 #include <mutex>
37 #include <thread>
38 #include <vector>
39 
40 #include <android-base/file.h>
41 #include <android-base/logging.h>
42 #include <android-base/parsedouble.h>
43 #include <android-base/parseint.h>
44 #include <android-base/properties.h>
45 #include <android-base/stringprintf.h>
46 #include <android-base/strings.h>
47 #include <android-base/unique_fd.h>
48 
49 #include "install/package.h"
50 #include "install/spl_check.h"
51 #include "install/verifier.h"
52 #include "install/wipe_data.h"
53 #include "otautil/error_code.h"
54 #include "otautil/paths.h"
55 #include "otautil/sysutil.h"
56 #include "private/setup_commands.h"
57 #include "recovery_ui/ui.h"
58 #include "recovery_utils/roots.h"
59 #include "recovery_utils/thermalutil.h"
60 
61 using namespace std::chrono_literals;
62 
63 static constexpr int kRecoveryApiVersion = 3;
64 // We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
65 // into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
66 static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
67 
68 // Default allocation of progress bar segments to operations
69 static constexpr int VERIFICATION_PROGRESS_TIME = 60;
70 static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25;
71 // The charater used to separate dynamic fingerprints. e.x. sargo|aosp-sargo
72 static const char* FINGERPRING_SEPARATOR = "|";
73 static std::condition_variable finish_log_temperature;
74 static bool isInStringList(const std::string& target_token, const std::string& str_list,
75                            const std::string& deliminator);
76 
ReadMetadataFromPackage(ZipArchiveHandle zip,std::map<std::string,std::string> * metadata)77 bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map<std::string, std::string>* metadata) {
78   CHECK(metadata != nullptr);
79 
80   static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata";
81   ZipEntry64 entry;
82   if (FindEntry(zip, METADATA_PATH, &entry) != 0) {
83     LOG(ERROR) << "Failed to find " << METADATA_PATH;
84     return false;
85   }
86 
87   uint32_t length = entry.uncompressed_length;
88   std::string metadata_string(length, '\0');
89   int32_t err =
90       ExtractToMemory(zip, &entry, reinterpret_cast<uint8_t*>(&metadata_string[0]), length);
91   if (err != 0) {
92     LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err);
93     return false;
94   }
95 
96   for (const std::string& line : android::base::Split(metadata_string, "\n")) {
97     size_t eq = line.find('=');
98     if (eq != std::string::npos) {
99       metadata->emplace(android::base::Trim(line.substr(0, eq)),
100                         android::base::Trim(line.substr(eq + 1)));
101     }
102   }
103 
104   return true;
105 }
106 
107 // Gets the value for the given key in |metadata|. Returns an emtpy string if the key isn't
108 // present.
get_value(const std::map<std::string,std::string> & metadata,const std::string & key)109 static std::string get_value(const std::map<std::string, std::string>& metadata,
110                              const std::string& key) {
111   const auto& it = metadata.find(key);
112   return (it == metadata.end()) ? "" : it->second;
113 }
114 
OtaTypeToString(OtaType type)115 static std::string OtaTypeToString(OtaType type) {
116   switch (type) {
117     case OtaType::AB:
118       return "AB";
119     case OtaType::BLOCK:
120       return "BLOCK";
121     case OtaType::BRICK:
122       return "BRICK";
123   }
124 }
125 
126 // Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
ReadSourceTargetBuild(const std::map<std::string,std::string> & metadata,std::vector<std::string> * log_buffer)127 static void ReadSourceTargetBuild(const std::map<std::string, std::string>& metadata,
128                                   std::vector<std::string>* log_buffer) {
129   // Examples of the pre-build and post-build strings in metadata:
130   //   pre-build-incremental=2943039
131   //   post-build-incremental=2951741
132   auto source_build = get_value(metadata, "pre-build-incremental");
133   if (!source_build.empty()) {
134     log_buffer->push_back("source_build: " + source_build);
135   }
136 
137   auto target_build = get_value(metadata, "post-build-incremental");
138   if (!target_build.empty()) {
139     log_buffer->push_back("target_build: " + target_build);
140   }
141 }
142 
143 // Checks the build version, fingerprint and timestamp in the metadata of the A/B package.
144 // Downgrading is not allowed unless explicitly enabled in the package and only for
145 // incremental packages.
CheckAbSpecificMetadata(const std::map<std::string,std::string> & metadata)146 static bool CheckAbSpecificMetadata(const std::map<std::string, std::string>& metadata) {
147   // Incremental updates should match the current build.
148   auto device_pre_build = android::base::GetProperty("ro.build.version.incremental", "");
149   auto pkg_pre_build = get_value(metadata, "pre-build-incremental");
150   if (!pkg_pre_build.empty() && pkg_pre_build != device_pre_build) {
151     LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected "
152                << device_pre_build;
153     return false;
154   }
155 
156   auto device_fingerprint = android::base::GetProperty("ro.build.fingerprint", "");
157   auto pkg_pre_build_fingerprint = get_value(metadata, "pre-build");
158   if (!pkg_pre_build_fingerprint.empty() &&
159       !isInStringList(device_fingerprint, pkg_pre_build_fingerprint, FINGERPRING_SEPARATOR)) {
160     LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected "
161                << device_fingerprint;
162     return false;
163   }
164 
165   // Check for downgrade version.
166   int64_t build_timestamp =
167       android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits<int64_t>::max());
168   int64_t pkg_post_timestamp = 0;
169   // We allow to full update to the same version we are running, in case there
170   // is a problem with the current copy of that version.
171   auto pkg_post_timestamp_string = get_value(metadata, "post-timestamp");
172   if (pkg_post_timestamp_string.empty() ||
173       !android::base::ParseInt(pkg_post_timestamp_string, &pkg_post_timestamp) ||
174       pkg_post_timestamp < build_timestamp) {
175     if (get_value(metadata, "ota-downgrade") != "yes") {
176       LOG(ERROR) << "Update package is older than the current build, expected a build "
177                     "newer than timestamp "
178                  << build_timestamp << " but package has timestamp " << pkg_post_timestamp
179                  << " and downgrade not allowed.";
180       return false;
181     }
182     if (pkg_pre_build_fingerprint.empty()) {
183       LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed.";
184       return false;
185     }
186   }
187 
188   return true;
189 }
190 
CheckPackageMetadata(const std::map<std::string,std::string> & metadata,OtaType ota_type)191 bool CheckPackageMetadata(const std::map<std::string, std::string>& metadata, OtaType ota_type) {
192   auto package_ota_type = get_value(metadata, "ota-type");
193   auto expected_ota_type = OtaTypeToString(ota_type);
194   if (ota_type != OtaType::AB && ota_type != OtaType::BRICK) {
195     LOG(INFO) << "Skip package metadata check for ota type " << expected_ota_type;
196     return true;
197   }
198 
199   if (package_ota_type != expected_ota_type) {
200     LOG(ERROR) << "Unexpected ota package type, expects " << expected_ota_type << ", actual "
201                << package_ota_type;
202     return false;
203   }
204 
205   auto device = android::base::GetProperty("ro.product.device", "");
206   auto pkg_device = get_value(metadata, "pre-device");
207   // device name can be a | separated list, so need to check
208   if (pkg_device.empty() || !isInStringList(device, pkg_device, FINGERPRING_SEPARATOR)) {
209     LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << device;
210     return false;
211   }
212 
213   // We allow the package to not have any serialno; and we also allow it to carry multiple serial
214   // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the
215   // verification if the device's serialno doesn't match any of these carried numbers.
216   auto pkg_serial_no = get_value(metadata, "serialno");
217   if (!pkg_serial_no.empty()) {
218     auto device_serial_no = android::base::GetProperty("ro.serialno", "");
219     bool serial_number_match = false;
220     for (const auto& number : android::base::Split(pkg_serial_no, "|")) {
221       if (device_serial_no == android::base::Trim(number)) {
222         serial_number_match = true;
223       }
224     }
225     if (!serial_number_match) {
226       LOG(ERROR) << "Package is for serial " << pkg_serial_no;
227       return false;
228     }
229   }
230 
231   if (ota_type == OtaType::AB) {
232     return CheckAbSpecificMetadata(metadata);
233   }
234 
235   return true;
236 }
237 
SetUpAbUpdateCommands(const std::string & package,ZipArchiveHandle zip,int status_fd,std::vector<std::string> * cmd)238 bool SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd,
239                            std::vector<std::string>* cmd) {
240   CHECK(cmd != nullptr);
241 
242   // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset
243   // in the zip file.
244   static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt";
245   ZipEntry64 properties_entry;
246   if (FindEntry(zip, AB_OTA_PAYLOAD_PROPERTIES, &properties_entry) != 0) {
247     LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
248     return false;
249   }
250   auto properties_entry_length = properties_entry.uncompressed_length;
251   if (properties_entry_length > std::numeric_limits<size_t>::max()) {
252     LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES
253                << " because's uncompressed size exceeds size of address space. "
254                << properties_entry_length;
255     return false;
256   }
257   std::vector<uint8_t> payload_properties(properties_entry_length);
258   int32_t err =
259       ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
260   if (err != 0) {
261     LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
262     return false;
263   }
264 
265   static constexpr const char* AB_OTA_PAYLOAD = "payload.bin";
266   ZipEntry64 payload_entry;
267   if (FindEntry(zip, AB_OTA_PAYLOAD, &payload_entry) != 0) {
268     LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD;
269     return false;
270   }
271   long payload_offset = payload_entry.offset;
272   *cmd = {
273     "/system/bin/update_engine_sideload",
274     "--payload=file://" + package,
275     android::base::StringPrintf("--offset=%ld", payload_offset),
276     "--headers=" + std::string(payload_properties.begin(), payload_properties.end()),
277     android::base::StringPrintf("--status_fd=%d", status_fd),
278   };
279   return true;
280 }
281 
SetUpNonAbUpdateCommands(const std::string & package,ZipArchiveHandle zip,int retry_count,int status_fd,std::vector<std::string> * cmd)282 bool SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count,
283                               int status_fd, std::vector<std::string>* cmd) {
284   CHECK(cmd != nullptr);
285 
286   // In non-A/B updates we extract the update binary from the package.
287   static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary";
288   ZipEntry64 binary_entry;
289   if (FindEntry(zip, UPDATE_BINARY_NAME, &binary_entry) != 0) {
290     LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME;
291     return false;
292   }
293 
294   const std::string binary_path = Paths::Get().temporary_update_binary();
295   unlink(binary_path.c_str());
296   android::base::unique_fd fd(
297       open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755));
298   if (fd == -1) {
299     PLOG(ERROR) << "Failed to create " << binary_path;
300     return false;
301   }
302 
303   if (auto error = ExtractEntryToFile(zip, &binary_entry, fd); error != 0) {
304     LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error);
305     return false;
306   }
307 
308   // When executing the update binary contained in the package, the arguments passed are:
309   //   - the version number for this interface
310   //   - an FD to which the program can write in order to update the progress bar.
311   //   - the name of the package zip file.
312   //   - an optional argument "retry" if this update is a retry of a failed update attempt.
313   *cmd = {
314     binary_path,
315     std::to_string(kRecoveryApiVersion),
316     std::to_string(status_fd),
317     package,
318   };
319   if (retry_count > 0) {
320     cmd->push_back("retry");
321   }
322   return true;
323 }
324 
log_max_temperature(int * max_temperature,const std::atomic<bool> & logger_finished)325 static void log_max_temperature(int* max_temperature, const std::atomic<bool>& logger_finished) {
326   CHECK(max_temperature != nullptr);
327   std::mutex mtx;
328   std::unique_lock<std::mutex> lck(mtx);
329   while (!logger_finished.load() &&
330          finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) {
331     *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone());
332   }
333 }
334 
335 // If the package contains an update binary, extract it and run it.
TryUpdateBinary(Package * package,bool * wipe_cache,std::vector<std::string> * log_buffer,int retry_count,int * max_temperature,RecoveryUI * ui)336 static InstallResult TryUpdateBinary(Package* package, bool* wipe_cache,
337                                      std::vector<std::string>* log_buffer, int retry_count,
338                                      int* max_temperature, RecoveryUI* ui) {
339   std::map<std::string, std::string> metadata;
340   auto zip = package->GetZipArchiveHandle();
341   if (!ReadMetadataFromPackage(zip, &metadata)) {
342     LOG(ERROR) << "Failed to parse metadata in the zip file";
343     return INSTALL_CORRUPT;
344   }
345 
346   bool package_is_ab = get_value(metadata, "ota-type") == OtaTypeToString(OtaType::AB);
347   bool device_supports_ab = android::base::GetBoolProperty("ro.build.ab_update", false);
348   bool ab_device_supports_nonab =
349       android::base::GetBoolProperty("ro.virtual_ab.allow_non_ab", false);
350   bool device_only_supports_ab = device_supports_ab && !ab_device_supports_nonab;
351 
352   const auto current_spl = android::base::GetProperty("ro.build.version.security_patch", "");
353   if (ViolatesSPLDowngrade(zip, current_spl)) {
354     LOG(ERROR) << "Denying OTA because it's SPL downgrade";
355     return INSTALL_ERROR;
356   }
357 
358   if (package_is_ab) {
359     CHECK(package->GetType() == PackageType::kFile);
360   }
361 
362   // Verify against the metadata in the package first. Expects A/B metadata if:
363   // Package declares itself as an A/B package
364   // Package does not declare itself as an A/B package, but device only supports A/B;
365   //   still calls CheckPackageMetadata to get a meaningful error message.
366   if (package_is_ab || device_only_supports_ab) {
367     if (!CheckPackageMetadata(metadata, OtaType::AB)) {
368       log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
369       return INSTALL_ERROR;
370     }
371   }
372 
373   ReadSourceTargetBuild(metadata, log_buffer);
374 
375   // The updater in child process writes to the pipe to communicate with recovery.
376   android::base::unique_fd pipe_read, pipe_write;
377   // Explicitly disable O_CLOEXEC using 0 as the flags (last) parameter to Pipe
378   // so that the child updater process will recieve a non-closed fd.
379   if (!android::base::Pipe(&pipe_read, &pipe_write, 0)) {
380     PLOG(ERROR) << "Failed to create pipe for updater-recovery communication";
381     return INSTALL_CORRUPT;
382   }
383 
384   // The updater-recovery communication protocol.
385   //
386   //   progress <frac> <secs>
387   //       fill up the next <frac> part of of the progress bar over <secs> seconds. If <secs> is
388   //       zero, use `set_progress` commands to manually control the progress of this segment of the
389   //       bar.
390   //
391   //   set_progress <frac>
392   //       <frac> should be between 0.0 and 1.0; sets the progress bar within the segment defined by
393   //       the most recent progress command.
394   //
395   //   ui_print <string>
396   //       display <string> on the screen.
397   //
398   //   wipe_cache
399   //       a wipe of cache will be performed following a successful installation.
400   //
401   //   clear_display
402   //       turn off the text display.
403   //
404   //   enable_reboot
405   //       packages can explicitly request that they want the user to be able to reboot during
406   //       installation (useful for debugging packages that don't exit).
407   //
408   //   retry_update
409   //       updater encounters some issue during the update. It requests a reboot to retry the same
410   //       package automatically.
411   //
412   //   log <string>
413   //       updater requests logging the string (e.g. cause of the failure).
414   //
415 
416   std::string package_path = package->GetPath();
417 
418   std::vector<std::string> args;
419   if (auto setup_result =
420           package_is_ab
421               ? SetUpAbUpdateCommands(package_path, zip, pipe_write.get(), &args)
422               : SetUpNonAbUpdateCommands(package_path, zip, retry_count, pipe_write.get(), &args);
423       !setup_result) {
424     log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure));
425     return INSTALL_CORRUPT;
426   }
427 
428   pid_t pid = fork();
429   if (pid == -1) {
430     PLOG(ERROR) << "Failed to fork update binary";
431     log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure));
432     return INSTALL_ERROR;
433   }
434 
435   if (pid == 0) {
436     umask(022);
437     pipe_read.reset();
438 
439     // Convert the std::string vector to a NULL-terminated char* vector suitable for execv.
440     auto chr_args = StringVectorToNullTerminatedArray(args);
441     execv(chr_args[0], chr_args.data());
442     // We shouldn't use LOG/PLOG in the forked process, since they may cause the child process to
443     // hang. This deadlock results from an improperly copied mutex in the ui functions.
444     // (Bug: 34769056)
445     fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
446     _exit(EXIT_FAILURE);
447   }
448   pipe_write.reset();
449 
450   std::atomic<bool> logger_finished(false);
451   std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished));
452 
453   *wipe_cache = false;
454   bool retry_update = false;
455 
456   char buffer[1024];
457   FILE* from_child = android::base::Fdopen(std::move(pipe_read), "r");
458   while (fgets(buffer, sizeof(buffer), from_child) != nullptr) {
459     std::string line(buffer);
460     size_t space = line.find_first_of(" \n");
461     std::string command(line.substr(0, space));
462     if (command.empty()) continue;
463 
464     // Get rid of the leading and trailing space and/or newline.
465     std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space));
466 
467     if (command == "progress") {
468       std::vector<std::string> tokens = android::base::Split(args, " ");
469       double fraction;
470       int seconds;
471       if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) &&
472           android::base::ParseInt(tokens[1], &seconds)) {
473         ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds);
474       } else {
475         LOG(ERROR) << "invalid \"progress\" parameters: " << line;
476       }
477     } else if (command == "set_progress") {
478       std::vector<std::string> tokens = android::base::Split(args, " ");
479       double fraction;
480       if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) {
481         ui->SetProgress(fraction);
482       } else {
483         LOG(ERROR) << "invalid \"set_progress\" parameters: " << line;
484       }
485     } else if (command == "ui_print") {
486       ui->PrintOnScreenOnly("%s\n", args.c_str());
487       fflush(stdout);
488     } else if (command == "wipe_cache") {
489       *wipe_cache = true;
490     } else if (command == "clear_display") {
491       ui->SetBackground(RecoveryUI::NONE);
492     } else if (command == "enable_reboot") {
493       // packages can explicitly request that they want the user
494       // to be able to reboot during installation (useful for
495       // debugging packages that don't exit).
496       ui->SetEnableReboot(true);
497     } else if (command == "retry_update") {
498       retry_update = true;
499     } else if (command == "log") {
500       if (!args.empty()) {
501         // Save the logging request from updater and write to last_install later.
502         log_buffer->push_back(args);
503       } else {
504         LOG(ERROR) << "invalid \"log\" parameters: " << line;
505       }
506     } else {
507       LOG(ERROR) << "unknown command [" << command << "]";
508     }
509   }
510   fclose(from_child);
511 
512   int status;
513   waitpid(pid, &status, 0);
514 
515   logger_finished.store(true);
516   finish_log_temperature.notify_one();
517   temperature_logger.join();
518 
519   if (retry_update) {
520     return INSTALL_RETRY;
521   }
522   if (WIFEXITED(status)) {
523     if (WEXITSTATUS(status) != EXIT_SUCCESS) {
524       LOG(ERROR) << "Error in " << package_path << " (status " << WEXITSTATUS(status) << ")";
525       return INSTALL_ERROR;
526     }
527   } else if (WIFSIGNALED(status)) {
528     LOG(ERROR) << "Error in " << package_path << " (killed by signal " << WTERMSIG(status) << ")";
529     return INSTALL_ERROR;
530   } else {
531     LOG(FATAL) << "Invalid status code " << status;
532   }
533 
534   return INSTALL_SUCCESS;
535 }
536 
VerifyAndInstallPackage(Package * package,bool * wipe_cache,std::vector<std::string> * log_buffer,int retry_count,int * max_temperature,RecoveryUI * ui)537 static InstallResult VerifyAndInstallPackage(Package* package, bool* wipe_cache,
538                                              std::vector<std::string>* log_buffer, int retry_count,
539                                              int* max_temperature, RecoveryUI* ui) {
540   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
541   // Give verification half the progress bar...
542   ui->SetProgressType(RecoveryUI::DETERMINATE);
543   ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
544 
545   // Verify package.
546   if (!verify_package(package, ui)) {
547     log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
548     return INSTALL_CORRUPT;
549   }
550 
551   // Verify and install the contents of the package.
552   ui->Print("Installing update...\n");
553   if (retry_count > 0) {
554     ui->Print("Retry attempt: %d\n", retry_count);
555   }
556   ui->SetEnableReboot(false);
557   auto result = TryUpdateBinary(package, wipe_cache, log_buffer, retry_count, max_temperature, ui);
558   ui->SetEnableReboot(true);
559   ui->Print("\n");
560 
561   return result;
562 }
563 
InstallPackage(Package * package,const std::string_view package_id,bool should_wipe_cache,int retry_count,RecoveryUI * ui)564 InstallResult InstallPackage(Package* package, const std::string_view package_id,
565                              bool should_wipe_cache, int retry_count, RecoveryUI* ui) {
566   auto start = std::chrono::system_clock::now();
567 
568   int start_temperature = GetMaxValueFromThermalZone();
569   int max_temperature = start_temperature;
570 
571   InstallResult result;
572   std::vector<std::string> log_buffer;
573 
574   ui->Print("Supported API: %d\n", kRecoveryApiVersion);
575 
576   ui->Print("Finding update package...\n");
577   LOG(INFO) << "Update package id: " << package_id;
578   if (!package) {
579     log_buffer.push_back(android::base::StringPrintf("error: %d", kMapFileFailure));
580     result = INSTALL_CORRUPT;
581   } else if (setup_install_mounts() != 0) {
582     LOG(ERROR) << "failed to set up expected mounts for install; aborting";
583     result = INSTALL_ERROR;
584   } else {
585     bool updater_wipe_cache = false;
586     result = VerifyAndInstallPackage(package, &updater_wipe_cache, &log_buffer, retry_count,
587                                      &max_temperature, ui);
588     should_wipe_cache = should_wipe_cache || updater_wipe_cache;
589   }
590 
591   // Measure the time spent to apply OTA update in seconds.
592   std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
593   int time_total = static_cast<int>(duration.count());
594 
595   bool has_cache = volume_for_mount_point("/cache") != nullptr;
596   // Skip logging the uncrypt_status on devices without /cache.
597   if (has_cache) {
598     static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status";
599     if (ensure_path_mounted(UNCRYPT_STATUS) != 0) {
600       LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS;
601     } else {
602       std::string uncrypt_status;
603       if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) {
604         PLOG(WARNING) << "failed to read uncrypt status";
605       } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) {
606         LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status;
607       } else {
608         log_buffer.push_back(android::base::Trim(uncrypt_status));
609       }
610     }
611   }
612 
613   // The first two lines need to be the package name and install result.
614   std::vector<std::string> log_header = {
615     std::string(package_id),
616     result == INSTALL_SUCCESS ? "1" : "0",
617     "time_total: " + std::to_string(time_total),
618     "retry: " + std::to_string(retry_count),
619   };
620 
621   int end_temperature = GetMaxValueFromThermalZone();
622   max_temperature = std::max(end_temperature, max_temperature);
623   if (start_temperature > 0) {
624     log_buffer.push_back("temperature_start: " + std::to_string(start_temperature));
625   }
626   if (end_temperature > 0) {
627     log_buffer.push_back("temperature_end: " + std::to_string(end_temperature));
628   }
629   if (max_temperature > 0) {
630     log_buffer.push_back("temperature_max: " + std::to_string(max_temperature));
631   }
632 
633   std::string log_content =
634       android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n";
635   const std::string& install_file = Paths::Get().temporary_install_file();
636   if (!android::base::WriteStringToFile(log_content, install_file)) {
637     PLOG(ERROR) << "failed to write " << install_file;
638   }
639 
640   // Write a copy into last_log.
641   LOG(INFO) << log_content;
642 
643   if (result == INSTALL_SUCCESS && should_wipe_cache) {
644     if (!WipeCache(ui, nullptr)) {
645       result = INSTALL_ERROR;
646     }
647   }
648 
649   return result;
650 }
651 
verify_package(Package * package,RecoveryUI * ui)652 bool verify_package(Package* package, RecoveryUI* ui) {
653   static constexpr const char* CERTIFICATE_ZIP_FILE = "/system/etc/security/otacerts.zip";
654   std::vector<Certificate> loaded_keys = LoadKeysFromZipfile(CERTIFICATE_ZIP_FILE);
655   if (loaded_keys.empty()) {
656     LOG(ERROR) << "Failed to load keys";
657     return false;
658   }
659   LOG(INFO) << loaded_keys.size() << " key(s) loaded from " << CERTIFICATE_ZIP_FILE;
660 
661   // Verify package.
662   ui->Print("Verifying update package...\n");
663   auto t0 = std::chrono::system_clock::now();
664   int err = verify_file(package, loaded_keys);
665   std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
666   ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
667   if (err != VERIFY_SUCCESS) {
668     LOG(ERROR) << "Signature verification failed";
669     LOG(ERROR) << "error: " << kZipVerificationFailure;
670     return false;
671   }
672   return true;
673 }
674 
SetupPackageMount(const std::string & package_path,bool * should_use_fuse)675 bool SetupPackageMount(const std::string& package_path, bool* should_use_fuse) {
676   CHECK(should_use_fuse != nullptr);
677 
678   if (package_path.empty()) {
679     return false;
680   }
681 
682   *should_use_fuse = true;
683   if (package_path[0] == '@') {
684     auto block_map_path = package_path.substr(1);
685     if (ensure_path_mounted(block_map_path) != 0) {
686       LOG(ERROR) << "Failed to mount " << block_map_path;
687       return false;
688     }
689     // uncrypt only produces block map only if the package stays on /data.
690     *should_use_fuse = false;
691     return true;
692   }
693 
694   // Package is not a block map file.
695   if (ensure_path_mounted(package_path) != 0) {
696     LOG(ERROR) << "Failed to mount " << package_path;
697     return false;
698   }
699 
700   // Reject the package if the input path doesn't equal the canonicalized path.
701   // e.g. /cache/../sdcard/update_package.
702   std::error_code ec;
703   auto canonical_path = std::filesystem::canonical(package_path, ec);
704   if (ec) {
705     LOG(ERROR) << "Failed to get canonical of " << package_path << ", " << ec.message();
706     return false;
707   }
708   if (canonical_path.string() != package_path) {
709     LOG(ERROR) << "Installation aborts. The canonical path " << canonical_path.string()
710                << " doesn't equal the original path " << package_path;
711     return false;
712   }
713 
714   constexpr const char* CACHE_ROOT = "/cache";
715   if (android::base::StartsWith(package_path, CACHE_ROOT)) {
716     *should_use_fuse = false;
717   }
718   return true;
719 }
720 
721 // Check if `target_token` is in string `str_list`, where `str_list` is expected to be a
722 // list delimited by `deliminator`
723 // E.X. isInStringList("a", "a|b|c|d", "|") => true
724 // E.X. isInStringList("abc", "abc", "|") => true
isInStringList(const std::string & target_token,const std::string & str_list,const std::string & deliminator)725 static bool isInStringList(const std::string& target_token, const std::string& str_list,
726                            const std::string& deliminator) {
727   if (target_token.length() > str_list.length()) {
728     return false;
729   } else if (target_token.length() == str_list.length() || deliminator.length() == 0) {
730     return target_token == str_list;
731   }
732   auto&& list = android::base::Split(str_list, deliminator);
733   return std::find(list.begin(), list.end(), target_token) != list.end();
734 }
735