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