• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2011 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 "update_engine/payload_consumer/postinstall_runner_action.h"
18 
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <sys/mount.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include <cmath>
27 #include <fstream>
28 #include <string>
29 
30 #include <base/files/file_path.h>
31 #include <base/files/file_util.h>
32 #include <base/logging.h>
33 #include <base/strings/string_split.h>
34 
35 #include "update_engine/common/action_processor.h"
36 #include "update_engine/common/boot_control_interface.h"
37 #include "update_engine/common/error_code_utils.h"
38 #include "update_engine/common/platform_constants.h"
39 #include "update_engine/common/subprocess.h"
40 #include "update_engine/common/utils.h"
41 
42 namespace {
43 
44 // The file descriptor number from the postinstall program's perspective where
45 // it can report status updates. This can be any number greater than 2 (stderr),
46 // but must be kept in sync with the "bin/postinst_progress" defined in the
47 // sample_images.sh file.
48 const int kPostinstallStatusFd = 3;
49 
Contains(std::string_view haystack,std::string_view needle)50 static constexpr bool Contains(std::string_view haystack,
51                                std::string_view needle) {
52   return haystack.find(needle) != std::string::npos;
53 }
54 
LogBuildInfoForPartition(std::string_view mount_point)55 static void LogBuildInfoForPartition(std::string_view mount_point) {
56   static constexpr std::array<std::string_view, 3> kBuildPropFiles{
57       "build.prop", "etc/build.prop", "system/build.prop"};
58   for (const auto& file : kBuildPropFiles) {
59     auto path = std::string(mount_point);
60     if (path.back() != '/') {
61       path.push_back('/');
62     }
63     path += file;
64     LOG(INFO) << "Trying to read " << path;
65     std::ifstream infile(path);
66     std::string line;
67     while (std::getline(infile, line)) {
68       if (Contains(line, "ro.build")) {
69         LOG(INFO) << line;
70       }
71     }
72   }
73 }
74 
75 }  // namespace
76 
77 namespace chromeos_update_engine {
78 
79 using std::string;
80 using std::vector;
81 
PostinstallRunnerAction(BootControlInterface * boot_control,HardwareInterface * hardware)82 PostinstallRunnerAction::PostinstallRunnerAction(
83     BootControlInterface* boot_control, HardwareInterface* hardware)
84     : boot_control_(boot_control), hardware_(hardware) {
85 #ifdef __ANDROID__
86   fs_mount_dir_ = "/postinstall";
87 #else   // __ANDROID__
88   base::FilePath temp_dir;
89   TEST_AND_RETURN(base::CreateNewTempDirectory("au_postint_mount", &temp_dir));
90   fs_mount_dir_ = temp_dir.value();
91 #endif  // __ANDROID__
92   CHECK(!fs_mount_dir_.empty());
93   EnsureUnmounted();
94   LOG(INFO) << "postinstall mount point: " << fs_mount_dir_;
95 }
96 
EnsureUnmounted()97 void PostinstallRunnerAction::EnsureUnmounted() {
98   if (utils::IsMountpoint(fs_mount_dir_)) {
99     LOG(INFO) << "Found previously mounted filesystem at " << fs_mount_dir_;
100     utils::UnmountFilesystem(fs_mount_dir_);
101   }
102 }
103 
PerformAction()104 void PostinstallRunnerAction::PerformAction() {
105   CHECK(HasInputObject());
106   CHECK(boot_control_);
107   install_plan_ = GetInputObject();
108 
109   auto dynamic_control = boot_control_->GetDynamicPartitionControl();
110   CHECK(dynamic_control);
111 
112   // Mount snapshot partitions for Virtual AB updates.
113   // If we are switching slots, then we are required to MapAllPartitions,
114   // as FinishUpdate() requires all partitions to be mapped.
115   // And switching slots requires FinishUpdate() to be called first
116   if (dynamic_control->GetVirtualAbFeatureFlag().IsEnabled() &&
117       !constants::kIsRecovery) {
118     if (!install_plan_.partitions.empty() ||
119         install_plan_.switch_slot_on_reboot) {
120       if (!dynamic_control->MapAllPartitions()) {
121         LOG(ERROR) << "Failed to map all partitions, this would cause "
122                       "FinishUpdate to fail. Abort early.";
123         return CompletePostinstall(ErrorCode::kPostInstallMountError);
124       }
125     }
126   }
127 
128   // We always powerwash when rolling back, however policy can determine
129   // if this is a full/normal powerwash, or a special rollback powerwash
130   // that retains a small amount of system state such as enrollment and
131   // network configuration. In both cases all user accounts are deleted.
132   if (install_plan_.powerwash_required) {
133     if (hardware_->SchedulePowerwash()) {
134       powerwash_scheduled_ = true;
135     } else {
136       return CompletePostinstall(ErrorCode::kPostinstallPowerwashError);
137     }
138   }
139 
140   // Initialize all the partition weights.
141   partition_weight_.resize(install_plan_.partitions.size());
142   total_weight_ = 0;
143   for (size_t i = 0; i < install_plan_.partitions.size(); ++i) {
144     auto& partition = install_plan_.partitions[i];
145     if (!install_plan_.run_post_install && partition.postinstall_optional) {
146       partition.run_postinstall = false;
147       LOG(INFO) << "Skipping optional post-install for partition "
148                 << partition.name << " according to install plan.";
149     }
150 
151     // TODO(deymo): This code sets the weight to all the postinstall commands,
152     // but we could remember how long they took in the past and use those
153     // values.
154     partition_weight_[i] = partition.run_postinstall;
155     total_weight_ += partition_weight_[i];
156   }
157   accumulated_weight_ = 0;
158   ReportProgress(0);
159 
160   PerformPartitionPostinstall();
161 }
162 
MountPartition(const InstallPlan::Partition & partition)163 bool PostinstallRunnerAction::MountPartition(
164     const InstallPlan::Partition& partition) noexcept {
165   // Perform post-install for the current_partition_ partition. At this point we
166   // need to call CompletePartitionPostinstall to complete the operation and
167   // cleanup.
168   const auto mountable_device = partition.readonly_target_path;
169   if (!utils::FileExists(mountable_device.c_str())) {
170     LOG(ERROR) << "Mountable device " << mountable_device << " for partition "
171                << partition.name << " does not exist";
172     return false;
173   }
174 
175   if (!utils::FileExists(fs_mount_dir_.c_str())) {
176     LOG(ERROR) << "Mount point " << fs_mount_dir_
177                << " does not exist, mount call will fail";
178     return false;
179   }
180   // Double check that the fs_mount_dir is not busy with a previous mounted
181   // filesystem from a previous crashed postinstall step.
182   EnsureUnmounted();
183 
184 #ifdef __ANDROID__
185   // In Chromium OS, the postinstall step is allowed to write to the block
186   // device on the target image, so we don't mark it as read-only and should
187   // be read-write since we just wrote to it during the update.
188 
189   // Mark the block device as read-only before mounting for post-install.
190   if (!utils::SetBlockDeviceReadOnly(mountable_device, true)) {
191     return false;
192   }
193 #endif  // __ANDROID__
194 
195   if (!utils::MountFilesystem(
196           mountable_device,
197           fs_mount_dir_,
198           MS_RDONLY,
199           partition.filesystem_type,
200           hardware_->GetPartitionMountOptions(partition.name))) {
201     return false;
202   }
203   return true;
204 }
205 
PerformPartitionPostinstall()206 void PostinstallRunnerAction::PerformPartitionPostinstall() {
207   if (install_plan_.download_url.empty()) {
208     LOG(INFO) << "Skipping post-install";
209     return CompletePostinstall(ErrorCode::kSuccess);
210   }
211 
212   // Skip all the partitions that don't have a post-install step.
213   while (current_partition_ < install_plan_.partitions.size() &&
214          !install_plan_.partitions[current_partition_].run_postinstall) {
215     VLOG(1) << "Skipping post-install on partition "
216             << install_plan_.partitions[current_partition_].name;
217     // Attempt to mount a device if it has postinstall script configured, even
218     // if we want to skip running postinstall script.
219     // This is because we've seen bugs like b/198787355 which is only triggered
220     // when you attempt to mount a device. If device fails to mount, it will
221     // likely fail to mount during boot anyway, so it's better to catch any
222     // issues earlier.
223     // It's possible that some of the partitions aren't mountable, but these
224     // partitions shouldn't have postinstall configured. Therefore we guard this
225     // logic with |postinstall_path.empty()|.
226     const auto& partition = install_plan_.partitions[current_partition_];
227     if (!partition.postinstall_path.empty()) {
228       const auto mountable_device = partition.readonly_target_path;
229       if (!MountPartition(partition)) {
230         return CompletePostinstall(ErrorCode::kPostInstallMountError);
231       }
232       LogBuildInfoForPartition(fs_mount_dir_);
233       if (!utils::UnmountFilesystem(fs_mount_dir_)) {
234         return CompletePartitionPostinstall(
235             1, "Error unmounting the device " + mountable_device);
236       }
237     }
238     current_partition_++;
239   }
240   if (current_partition_ == install_plan_.partitions.size())
241     return CompletePostinstall(ErrorCode::kSuccess);
242 
243   const InstallPlan::Partition& partition =
244       install_plan_.partitions[current_partition_];
245 
246   const string mountable_device = partition.readonly_target_path;
247   // Perform post-install for the current_partition_ partition. At this point we
248   // need to call CompletePartitionPostinstall to complete the operation and
249   // cleanup.
250 
251   if (!MountPartition(partition)) {
252     CompletePostinstall(ErrorCode::kPostInstallMountError);
253     return;
254   }
255   LogBuildInfoForPartition(fs_mount_dir_);
256   base::FilePath postinstall_path(partition.postinstall_path);
257   if (postinstall_path.IsAbsolute()) {
258     LOG(ERROR) << "Invalid absolute path passed to postinstall, use a relative"
259                   "path instead: "
260                << partition.postinstall_path;
261     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
262   }
263 
264   string abs_path =
265       base::FilePath(fs_mount_dir_).Append(postinstall_path).value();
266   if (!base::StartsWith(
267           abs_path, fs_mount_dir_, base::CompareCase::SENSITIVE)) {
268     LOG(ERROR) << "Invalid relative postinstall path: "
269                << partition.postinstall_path;
270     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
271   }
272 
273   LOG(INFO) << "Performing postinst (" << partition.postinstall_path << " at "
274             << abs_path << ") installed on mountable device "
275             << mountable_device;
276 
277   // Logs the file format of the postinstall script we are about to run. This
278   // will help debug when the postinstall script doesn't match the architecture
279   // of our build.
280   LOG(INFO) << "Format file for new " << partition.postinstall_path
281             << " is: " << utils::GetFileFormat(abs_path);
282 
283   // Runs the postinstall script asynchronously to free up the main loop while
284   // it's running.
285   vector<string> command = {abs_path};
286   // In Brillo and Android, we pass the slot number and status fd.
287   command.push_back(std::to_string(install_plan_.target_slot));
288   command.push_back(std::to_string(kPostinstallStatusFd));
289   // If install plan only contains one partition, notify the script. Most likely
290   // we are scheduled by `triggerPostinstall` API. Certain scripts might want
291   // different behaviors when triggered by `triggerPostinstall` API. For
292   // example, call scheduler API to schedule a postinstall run during
293   // applyPayload(), and only run actual postinstall work if scheduled by
294   // external async scheduler.
295   if (install_plan_.partitions.size() == 1 &&
296       !install_plan_.switch_slot_on_reboot &&
297       install_plan_.download_url.starts_with(kPrefsManifestBytes)) {
298     command.push_back("1");
299   }
300 
301   current_command_ = Subprocess::Get().ExecFlags(
302       command,
303       Subprocess::kRedirectStderrToStdout,
304       {kPostinstallStatusFd},
305       base::Bind(&PostinstallRunnerAction::CompletePartitionPostinstall,
306                  base::Unretained(this)));
307   // Subprocess::Exec should never return a negative process id.
308   CHECK_GE(current_command_, 0);
309 
310   if (!current_command_) {
311     CompletePartitionPostinstall(1, "Postinstall didn't launch");
312     return;
313   }
314 
315   // Monitor the status file descriptor.
316   progress_fd_ =
317       Subprocess::Get().GetPipeFd(current_command_, kPostinstallStatusFd);
318   int fd_flags = fcntl(progress_fd_, F_GETFL, 0) | O_NONBLOCK;
319   if (HANDLE_EINTR(fcntl(progress_fd_, F_SETFL, fd_flags)) < 0) {
320     PLOG(ERROR) << "Unable to set non-blocking I/O mode on fd " << progress_fd_;
321   }
322 
323   progress_controller_ = base::FileDescriptorWatcher::WatchReadable(
324       progress_fd_,
325       base::BindRepeating(&PostinstallRunnerAction::OnProgressFdReady,
326                           base::Unretained(this)));
327 }
328 
OnProgressFdReady()329 void PostinstallRunnerAction::OnProgressFdReady() {
330   char buf[1024];
331   size_t bytes_read;
332   do {
333     bytes_read = 0;
334     bool eof;
335     bool ok =
336         utils::ReadAll(progress_fd_, buf, std::size(buf), &bytes_read, &eof);
337     progress_buffer_.append(buf, bytes_read);
338     // Process every line.
339     vector<string> lines = base::SplitString(
340         progress_buffer_, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
341     if (!lines.empty()) {
342       progress_buffer_ = lines.back();
343       lines.pop_back();
344       for (const auto& line : lines) {
345         ProcessProgressLine(line);
346       }
347     }
348     if (!ok || eof) {
349       // There was either an error or an EOF condition, so we are done watching
350       // the file descriptor.
351       progress_controller_.reset();
352       return;
353     }
354   } while (bytes_read);
355 }
356 
ProcessProgressLine(const string & line)357 bool PostinstallRunnerAction::ProcessProgressLine(const string& line) {
358   double frac = 0;
359   if (sscanf(line.c_str(), "global_progress %lf", &frac) == 1 &&
360       !std::isnan(frac)) {
361     ReportProgress(frac);
362     return true;
363   }
364 
365   return false;
366 }
367 
ReportProgress(double frac)368 void PostinstallRunnerAction::ReportProgress(double frac) {
369   if (!delegate_)
370     return;
371   if (current_partition_ >= partition_weight_.size() || total_weight_ == 0) {
372     delegate_->ProgressUpdate(1.);
373     return;
374   }
375   if (!std::isfinite(frac) || frac < 0)
376     frac = 0;
377   if (frac > 1)
378     frac = 1;
379   double postinst_action_progress =
380       (accumulated_weight_ + partition_weight_[current_partition_] * frac) /
381       total_weight_;
382   delegate_->ProgressUpdate(postinst_action_progress);
383 }
384 
Cleanup()385 void PostinstallRunnerAction::Cleanup() {
386   utils::UnmountFilesystem(fs_mount_dir_);
387 #ifndef __ANDROID__
388 #if BASE_VER < 800000
389   if (!base::DeleteFile(base::FilePath(fs_mount_dir_), true)) {
390 #else
391   if (!base::DeleteFile(base::FilePath(fs_mount_dir_))) {
392 #endif
393     PLOG(WARNING) << "Not removing temporary mountpoint " << fs_mount_dir_;
394   }
395 #endif
396 
397   progress_fd_ = -1;
398   progress_controller_.reset();
399 
400   progress_buffer_.clear();
401 }
402 
403 void PostinstallRunnerAction::CompletePartitionPostinstall(
404     int return_code, const string& output) {
405   current_command_ = 0;
406   Cleanup();
407 
408   if (return_code != 0) {
409     LOG(ERROR) << "Postinst command failed with code: " << return_code;
410     ErrorCode error_code = ErrorCode::kPostinstallRunnerError;
411 
412     if (return_code == 3) {
413       // This special return code means that we tried to update firmware,
414       // but couldn't because we booted from FW B, and we need to reboot
415       // to get back to FW A.
416       error_code = ErrorCode::kPostinstallBootedFromFirmwareB;
417     }
418 
419     if (return_code == 4) {
420       // This special return code means that we tried to update firmware,
421       // but couldn't because we booted from FW B, and we need to reboot
422       // to get back to FW A.
423       error_code = ErrorCode::kPostinstallFirmwareRONotUpdatable;
424     }
425 
426     // If postinstall script for this partition is optional we can ignore the
427     // result.
428     if (install_plan_.partitions[current_partition_].postinstall_optional) {
429       LOG(INFO) << "Ignoring postinstall failure since it is optional";
430     } else {
431       return CompletePostinstall(error_code);
432     }
433   }
434   accumulated_weight_ += partition_weight_[current_partition_];
435   current_partition_++;
436   ReportProgress(0);
437 
438   PerformPartitionPostinstall();
439 }
440 
441 PostinstallRunnerAction::~PostinstallRunnerAction() {
442   if (!install_plan_.partitions.empty()) {
443     auto dynamic_control = boot_control_->GetDynamicPartitionControl();
444     CHECK(dynamic_control);
445     dynamic_control->UnmapAllPartitions();
446     LOG(INFO) << "Unmapped all partitions.";
447   }
448 }
449 
450 void PostinstallRunnerAction::CompletePostinstall(ErrorCode error_code) {
451   // We only attempt to mark the new slot as active if all the postinstall
452   // steps succeeded.
453   DEFER {
454     if (error_code != ErrorCode::kSuccess &&
455         error_code != ErrorCode::kUpdatedButNotActive) {
456       LOG(ERROR) << "Postinstall action failed. "
457                  << utils::ErrorCodeToString(error_code);
458 
459       // Undo any changes done to trigger Powerwash.
460       if (powerwash_scheduled_)
461         hardware_->CancelPowerwash();
462     }
463     processor_->ActionComplete(this, error_code);
464   };
465   if (error_code == ErrorCode::kSuccess) {
466     if (install_plan_.switch_slot_on_reboot) {
467       if (!boot_control_->GetDynamicPartitionControl()->FinishUpdate(
468               install_plan_.powerwash_required) ||
469           !boot_control_->SetActiveBootSlot(install_plan_.target_slot)) {
470         error_code = ErrorCode::kPostinstallRunnerError;
471       } else {
472         // Schedules warm reset on next reboot, ignores the error.
473         hardware_->SetWarmReset(true);
474         // Sets the vbmeta digest for the other slot to boot into.
475         hardware_->SetVbmetaDigestForInactiveSlot(false);
476       }
477     } else {
478       error_code = ErrorCode::kUpdatedButNotActive;
479     }
480   }
481 
482   LOG(INFO) << "All post-install commands succeeded";
483   if (HasOutputPipe()) {
484     SetOutputObject(install_plan_);
485   }
486 }
487 
488 void PostinstallRunnerAction::SuspendAction() {
489   if (!current_command_)
490     return;
491   if (kill(current_command_, SIGSTOP) != 0) {
492     PLOG(ERROR) << "Couldn't pause child process " << current_command_;
493   } else {
494     is_current_command_suspended_ = true;
495   }
496 }
497 
498 void PostinstallRunnerAction::ResumeAction() {
499   if (!current_command_)
500     return;
501   if (kill(current_command_, SIGCONT) != 0) {
502     PLOG(ERROR) << "Couldn't resume child process " << current_command_;
503   } else {
504     is_current_command_suspended_ = false;
505   }
506 }
507 
508 void PostinstallRunnerAction::TerminateProcessing() {
509   if (!current_command_)
510     return;
511   // Calling KillExec() will discard the callback we registered and therefore
512   // the unretained reference to this object.
513   Subprocess::Get().KillExec(current_command_);
514 
515   // If the command has been suspended, resume it after KillExec() so that the
516   // process can process the SIGTERM sent by KillExec().
517   if (is_current_command_suspended_) {
518     ResumeAction();
519   }
520 
521   current_command_ = 0;
522   Cleanup();
523 }
524 
525 }  // namespace chromeos_update_engine
526